/
WrapWebServerFilesCommand.java
211 lines (176 loc) · 9.8 KB
/
WrapWebServerFilesCommand.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package com.thecoderscorner.menu.editorui.cli;
import com.thecoderscorner.menu.editorui.util.StringHelper;
import picocli.CommandLine;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.nio.file.*;
import java.time.LocalDateTime;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;
import java.util.zip.GZIPOutputStream;
import static com.thecoderscorner.menu.editorui.generator.core.CoreCodeGenerator.LINE_BREAK;
@CommandLine.Command(name="wrap-ws")
public class WrapWebServerFilesCommand implements Callable<Integer> {
public enum CreationMode {ESP_ASYNC, AVR_WEBSERVER}
@CommandLine.Option(names = {"-m", "--mode"}, description = "the webserver to create for")
private CreationMode creationMode;
@CommandLine.Option(names = {"-d", "--directory"}, description = "the source directory")
private File srcDir;
@CommandLine.Option(names = {"-a", "--want-maps"}, defaultValue = "false", description = "Keep map files in output")
private boolean wantMaps;
@CommandLine.Option(names = {"-l", "--debug"}, defaultValue = "false", description = "Add log statements around each operation")
private boolean debugLog;
@CommandLine.Option(names = {"-o", "--output"}, defaultValue = "", description = "Optionally provide the output file name")
private String outputFile;
@Override
public Integer call() throws Exception {
System.out.println("Wrapping web files in " + srcDir + " for mode " + creationMode);
// skip hidden files, directories and map files (unless map file mode is turned on)
var allFiles = Files.walk(srcDir.toPath(), FileVisitOption.FOLLOW_LINKS)
.filter(path -> !path.toFile().isDirectory() && !path.getFileName().toString().startsWith("."))
.collect(Collectors.toList());
StringBuilder sbVariables = new StringBuilder(8192);
StringBuilder sbFunctions = new StringBuilder(8192);
sbVariables.append("#include <Arduino.h>").append(LINE_BREAK);
sbVariables.append("#include <ESPAsyncWebServer.h>").append(LINE_BREAK).append(LINE_BREAK);
if(debugLog && creationMode == CreationMode.ESP_ASYNC) {
sbVariables.append("const char LOG_TAG_WS[] = \"web\";").append(LINE_BREAK);
}
sbVariables.append("// Generated by tcMenu Designer wrap-ws command on ").append(LocalDateTime.now()).append(LINE_BREAK);
sbVariables.append("// use tcmenu wrap-ws cli command to regenerate ").append(LINE_BREAK).append(LINE_BREAK);
sbFunctions.append("void prepareWebServer(AsyncWebServer& server) {").append(LINE_BREAK);
int entireSize = 0;
for (var file : allFiles) {
if ((!wantMaps && file.toString().endsWith(".map"))) {
System.out.println("Skipping map file " + file);
continue;
}
boolean binFile = checkFileIsBinary(file);
var theLocalPath = file.toString().replace(srcDir.toPath().toString(), "");
theLocalPath = theLocalPath.replace('\\', '/');
var varName = "webs" + theLocalPath.replaceAll("[^a-zA-Z0-9]", "_");
long size = Files.size(file);
var shouldGzip = size > 2000 && !binFile;
sbVariables.append(toVariableForPlatform(varName, binFile, shouldGzip));
sbVariables.append(LINE_BREAK);
if (shouldGzip) {
binFile = true;
var byteStream = new ByteArrayOutputStream((int) size);
try (var gzipStream = new GZIPOutputStream(byteStream)) {
var allBytes = Files.readAllBytes(file);
gzipStream.write(allBytes);
}
byte[] allBytes = byteStream.toByteArray();
System.out.println("Zipped " + file + " before " + size + ", after " + allBytes.length);
processAsBinary(sbVariables, allBytes);
entireSize += allBytes.length;
varName += "_gz";
} else if (!binFile) {
System.out.println("Small text " + file + " size is " + size);
var lines = Files.readAllLines(file);
lines.forEach(l -> sbVariables.append(" \"").append(l.replace("\"", "\\\""))
.append("\" \\").append(LINE_BREAK));
entireSize += size;
} else {
System.out.println("Binary " + file + " size is " + size);
var allBytes = Files.readAllBytes(file);
processAsBinary(sbVariables, allBytes);
entireSize += size;
}
sbVariables.append("};").append(LINE_BREAK);
sbFunctions.append(writeServeLogicFor(theLocalPath, varName, binFile, shouldGzip));
}
sbVariables.append(LINE_BREAK);
sbFunctions.append("}").append(LINE_BREAK);
sbFunctions.append(LINE_BREAK);
sbFunctions.append("// Add the following forward-definition to your code if you're calling this yourself");
sbFunctions.append(LINE_BREAK);
sbFunctions.append("// void prepareWebServer(AsyncWebServer& server); ");
sbFunctions.append(LINE_BREAK);
Path outputPath;
if (!StringHelper.isStringEmptyOrNull(outputFile)) {
outputPath = Paths.get(outputFile);
} else {
outputPath = srcDir.toPath().resolve("esp_ws.cpp");
}
Files.writeString(outputPath, sbVariables + sbFunctions.toString(), StandardOpenOption.CREATE);
System.out.println("Written file " + outputPath + ". Approx memory requirement for data is " + entireSize);
System.out.println("If you need to use this directly in your project, forward declare as follows:");
System.out.println(" void prepareWebServer(AsyncWebServer& server);");
return 0;
}
private void processAsBinary(StringBuilder sbVariables, byte[] allBytes) {
for(int i = 0; i< allBytes.length; i++) {
sbVariables.append(String.format("0x%02x", allBytes[i]));
if(i != (allBytes.length -1)) {
sbVariables.append(",");
}
else {
sbVariables.append("\n");
}
if((i%20)==19) {
sbVariables.append("\n");
}
}
}
private String writeServeLogicFor(String theLocalPath, String varName, boolean binary, boolean gzipped) {
String mimeType = mimeTypeFor(theLocalPath);
return switch (creationMode) {
case ESP_ASYNC -> writeServeLogicEspAsync(theLocalPath, varName, mimeType, binary, gzipped);
case AVR_WEBSERVER -> "TODO";
};
}
private String writeServeLogicEspAsync(String theLocalPath, String varName, String mime, boolean binary, boolean gzipped) {
String requestProcessing;
if(gzipped) {
requestProcessing = possibleDebugStatement("start", varName) +
" auto* resp = request->beginResponse_P(200, \"" + mime + "\", " + varName + ", sizeof(" + varName +"));" + LINE_BREAK +
" resp->addHeader(\"Content-Encoding\", \"gzip\");" + LINE_BREAK +
" resp->addHeader(\"Cache-Control\", \"max-age=2592000\");" + LINE_BREAK +
" request->send(resp);" + LINE_BREAK +
possibleDebugStatement("end", varName);
} else if(binary) {
requestProcessing = possibleDebugStatement("start", varName) +
" auto* resp = request->beginResponse_P(200, \"" + mime + "\", " + varName + ", sizeof(" + varName +"));" + LINE_BREAK +
" resp->addHeader(\"Cache-Control\", \"max-age=2592000\");" + LINE_BREAK +
" request->send(resp);" + LINE_BREAK +
possibleDebugStatement("end", varName);
} else {
requestProcessing = possibleDebugStatement("start", varName)+
" request->send_P(200, \"" + mime + "\", " + varName + ");" + LINE_BREAK +
possibleDebugStatement("end", varName);
}
return " server.on(\"" + theLocalPath + "\", HTTP_GET, [](AsyncWebServerRequest *request) {" + LINE_BREAK +
requestProcessing +
" });" + LINE_BREAK;
}
private String possibleDebugStatement(String key, String text) {
if(!debugLog) return "";
return switch(creationMode) {
case ESP_ASYNC -> " ESP_LOGI(LOG_TAG_WS, \"" + key + " " + text + "\");";
case AVR_WEBSERVER -> " serdebugF(\""+ key + " " + text + "\");";
} + LINE_BREAK;
}
private String mimeTypeFor(String p) {
String strPath = p.toLowerCase();
if(strPath.endsWith(".png")) return "image/png";
else if(strPath.endsWith(".jpg")) return "image/jpeg";
else if(strPath.endsWith(".ico")) return "image/vnd.microsoft.icon";
else if(strPath.endsWith(".js")) return "text/javascript";
else if(strPath.endsWith(".json")) return "application/json";
else if(strPath.endsWith(".css")) return "text/css";
else if(strPath.endsWith(".html")) return "text/html";
else return "text/plain";
}
private boolean checkFileIsBinary(Path file) {
var strFile = file.toString().toLowerCase();
return strFile.endsWith(".jpg") || strFile.endsWith(".png") || strFile.endsWith(".ico");
}
private String toVariableForPlatform(String varName, boolean bin, boolean shouldGZip) {
var reqType = bin || shouldGZip ? "uint8_t" : "char";
var gzExt = shouldGZip ? "_gz" : "";
return switch(creationMode) {
case ESP_ASYNC, AVR_WEBSERVER -> String.format("const %s %s%s[] PROGMEM = {", reqType, varName, gzExt);
};
}
}