-
Notifications
You must be signed in to change notification settings - Fork 13
/
ESPTemplateProcessor.h
120 lines (103 loc) · 3.02 KB
/
ESPTemplateProcessor.h
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
#ifndef ESP_TEMPLATE_PROCESSOR_H
#define ESP_TEMPLATE_PROCESSOR_H
#ifdef ESP8266
#define WebServer ESP8266WebServer
#include <ESP8266WebServer.h>
#else
#include <WebServer.h>
#endif
#include <FS.h>
#ifdef ESP32
#include <SPIFFS.h>
#endif
typedef String ProcessorCallback(const String& key);
class ESPTemplateProcessor {
public:
ESPTemplateProcessor(WebServer& _server) :
server(_server)
{
}
bool send(const String& filePath, ProcessorCallback& processor, char bookend = '%', bool silentSerial = false)
{
// Open file.
if(!SPIFFS.exists(filePath)) {
if(!silentSerial) {
Serial.print("Cannot process "); Serial.print(filePath); Serial.println(": Does not exist.");
}
return false;
}
File file = SPIFFS.open(filePath, "r");
if (!file) {
if(!silentSerial) {
Serial.print("Cannot process "); Serial.print(filePath); Serial.println(": Failed to open.");
}
return false;
}
server.setContentLength(CONTENT_LENGTH_UNKNOWN);
server.sendHeader("Content-Type","text/html",true);
server.sendHeader("Cache-Control","no-cache");
server.send(200);
//server.sendContent(<chunk>)
// Process!
static const uint16_t MAX = 100;
String buffer;
int bufferLen = 0;
String keyBuffer;
int val;
char ch;
while ((val = file.read()) != -1) {
ch = char(val);
// Lookup expansion.
if (ch == bookend) {
// Clear out buffer.
server.sendContent(buffer);
buffer = "";
bufferLen = 0;
// Process substitution.
keyBuffer = "";
bool found = false;
while (!found && (val = file.read()) != -1) {
ch = char(val);
if (ch == bookend) {
found = true;
} else {
keyBuffer += ch;
}
}
// Check for bad exit.
if (val == -1 && !found) {
if(!silentSerial) {
Serial.print("Cannot process "); Serial.print(filePath); Serial.println(": Unable to parse.");
}
return false;
}
// Get substitution
String processed = processor(keyBuffer);
if(!silentSerial) {
Serial.print("Lookup '"); Serial.print(keyBuffer); Serial.print("' received: "); Serial.println(processed);
}
server.sendContent(processed);
} else {
bufferLen++;
buffer += ch;
if (bufferLen >= MAX) {
server.sendContent(buffer);
bufferLen = 0;
buffer = "";
}
}
}
if (val == -1) {
server.sendContent(buffer);
server.sendContent("");
return true;
} else {
if(!silentSerial) {
Serial.print("Failed to process '"); Serial.print(filePath); Serial.println("': Didn't reach the end of the file.");
}
}
}
private:
WebServer &server;
};
#endif