-
Notifications
You must be signed in to change notification settings - Fork 201
/
Copy pathESPDash.cpp
505 lines (451 loc) · 13.3 KB
/
ESPDash.cpp
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
#include "ESPDash.h"
// Integral type to string pairs events
// ID, type
struct CardNames cardTags[] = {
{GENERIC_CARD, "generic"},
{TEMPERATURE_CARD, "temperature"},
{HUMIDITY_CARD, "humidity"},
{STATUS_CARD, "status"},
{SLIDER_CARD, "slider"},
{BUTTON_CARD, "button"},
{PROGRESS_CARD, "progress"},
};
// Integral type to string pairs events
// ID, type
struct ChartNames chartTags[] = {
{BAR_CHART, "bar"},
};
/*
Constructors
*/
ESPDash::ESPDash(AsyncWebServer* server) : ESPDash(server, "/", true) {}
ESPDash::ESPDash(AsyncWebServer* server, bool enable_default_stats) : ESPDash(server, "/", enable_default_stats) {}
ESPDash::ESPDash(AsyncWebServer* server, const char* uri, bool enable_default_stats) {
_server = server;
default_stats_enabled = enable_default_stats;
// Initialize AsyncWebSocket
_ws = new AsyncWebSocket("/dashws");
// Attach AsyncWebServer Routes
_server->on(uri, HTTP_GET, [this](AsyncWebServerRequest *request){
if(basic_auth){
if(!request->authenticate(username, password))
return request->requestAuthentication();
}
// respond with the compressed frontend
AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", DASH_HTML, sizeof(DASH_HTML));
response->addHeader("Content-Encoding", "gzip");
response->addHeader("Cache-Control", "public, max-age=900");
request->send(response);
});
// Websocket Callback Handler
_ws->onEvent([&](AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len){
// Request Buffer
StaticJsonDocument<200> json;
if (type == WS_EVT_DATA) {
AwsFrameInfo * info = (AwsFrameInfo * ) arg;
if (info -> final && info -> index == 0 && info -> len == len) {
if (info -> opcode == WS_TEXT) {
data[len] = 0;
deserializeJson(json, reinterpret_cast<const char*>(data));
// client side commands parsing
if (json["command"] == "get:layout") {
generateLayoutJSON(client, false);
} else if (json["command"] == "ping") {
return _ws->text(client->id(), "{\"command\":\"pong\"}");
} else if (json["command"] == "get:stats") {
generateLayoutJSON(client, true);
} else if (json["command"] == "button:clicked") {
// execute and reference card data struct to funtion
uint32_t id = json["id"].as<uint32_t>();
for(int i=0; i < cards.Size(); i++){
Card *p = cards[i];
if(id == p->_id){
if(p->_callback != nullptr){
p->_callback(json["value"].as<int>());
}
}
}
} else if (json["command"] == "slider:changed") {
// execute and reference card data struct to funtion
uint32_t id = json["id"].as<uint32_t>();
for(int i=0; i < cards.Size(); i++){
Card *p = cards[i];
if(id == p->_id){
if(p->_callback != nullptr){
p->_callback(json["value"].as<int>());
}
}
}
}
}
}
}
});
// Attach Websocket Instance to AsyncWebServer
_server->addHandler(_ws);
}
void ESPDash::setAuthentication(const char *user, const char *pass) {
basic_auth = strlen(user) > 0 && strlen(pass) > 0;
if(basic_auth) {
strncpy(username, user, sizeof(username));
strncpy(password, pass, sizeof(password));
_ws->setAuthentication(user, pass);
}
}
void ESPDash::setAuthentication(const String &user, const String &pass) {
setAuthentication(user.c_str(), pass.c_str());
}
// Add Card
void ESPDash::add(Card *card) {
cards.PushBack(card);
refreshLayout();
}
// Remove Card
void ESPDash::remove(Card *card) {
for(int i=0; i < cards.Size(); i++){
Card *p = cards[i];
if(p->_id == card->_id){
cards.Erase(i);
refreshLayout();
return;
}
}
}
// Add Chart
void ESPDash::add(Chart *chart) {
charts.PushBack(chart);
refreshLayout();
}
// Remove Card
void ESPDash::remove(Chart *chart) {
for(int i=0; i < charts.Size(); i++){
Chart *p = charts[i];
if(p->_id == chart->_id){
charts.Erase(i);
refreshLayout();
return;
}
}
}
// Add Statistic
void ESPDash::add(Statistic *statistic) {
statistics.PushBack(statistic);
refreshStatistics();
}
// Remove Statistic
void ESPDash::remove(Statistic *statistic) {
for(int i=0; i < statistics.Size(); i++){
Statistic *p = statistics[i];
if(p->_id == statistic->_id){
statistics.Erase(i);
refreshStatistics();
return;
}
}
}
// generates the layout JSON string to the frontend
size_t ESPDash::generateLayoutJSON(AsyncWebSocketClient *client, bool changes_only, Card *onlyCard) {
// https://github.com/me-no-dev/ESPAsyncWebServer#limiting-the-number-of-web-socket-clients
// Browsers sometimes do not correctly close the websocket connection, even when the close() function is called in javascript.
// This will eventually exhaust the web server's resources and will cause the server to crash.
// Use DEFAULT_MAX_WS_CLIENTS or DASH_MAX_WS_CLIENTS (specific to ESP-DASH) to set the maximum number of clients
_ws->cleanupClients();
const size_t clients = _ws->count();
if (clients == 0) {
// do not consume cpu and memory if no client is connected
return 0;
}
String buf = "";
buf.reserve(changes_only ? DASH_PARTIAL_UPDATE_JSON_SIZE : DASH_LAYOUT_JSON_SIZE);
if (changes_only) {
buf += "{\"command\":\"update:components\",";
} else {
buf += "{\"command\":\"update:layout\",";
}
buf += "\"cards\":[";
StaticJsonDocument<DASH_CARD_JSON_SIZE> carddoc;
uint8_t card_count = 0;
// Generate JSON for all Cards
for (int i=0; i < cards.Size(); i++) {
Card *c = cards[i];
if (changes_only) {
if (c->_changed) {
c->_changed = false;
} else if (onlyCard == nullptr || onlyCard->_id != c->_id) {
continue;
}
}
if (card_count > 0) {
buf += ",";
}
// Generate JSON
JsonObject obj = carddoc.to<JsonObject>();
generateComponentJSON(obj, c, changes_only);
// Append to buf
serializeJson(carddoc, buf);
carddoc.clear();
card_count++;
}
buf += "],\"charts\":[";
DynamicJsonDocument chartdoc(DASH_CHART_JSON_SIZE);
uint8_t chart_count = 0;
// Generate JSON for all Charts
for (int i=0; i < charts.Size(); i++) {
Chart *c = charts[i];
if (changes_only) {
if (c->_changed) {
c->_changed = false;
} else {
continue;
}
}
if (chart_count > 0) {
buf += ",";
}
// Generate JSON
JsonObject obj = chartdoc.to<JsonObject>();
generateComponentJSON(obj, c, changes_only);
// Append to buf
serializeJson(chartdoc, buf);
chartdoc.clear();
chart_count++;
}
buf += "],\"stats\": [";
// Generate JSON for all Statistics
// Check if default statistics are needed
if (default_stats_enabled) {
StaticJsonDocument<64> obj;
if (!changes_only) {
// Hardware
obj["i"] = -1;
obj["k"] = "Hardware";
obj["v"] = DASH_HARDWARE;
serializeJson(obj, buf);
obj.clear();
buf += ",";
// SDK Version
obj["i"] = -2;
obj["k"] = "SDK Version";
#if defined(ESP8266)
obj["v"] = ESP.getCoreVersion();
#elif defined(ESP32)
obj["v"] = String(esp_get_idf_version());
#endif
serializeJson(obj, buf);
obj.clear();
buf += ",";
// MAC Address
obj["i"] = -3;
obj["k"] = "MAC Address";
obj["v"] = WiFi.macAddress();
serializeJson(obj, buf);
obj.clear();
buf += ",";
}
// Free Heap
obj["i"] = -4;
obj["k"] = "Free Heap (SRAM)";
obj["v"] = ESP.getFreeHeap();
serializeJson(obj, buf);
obj.clear();
buf += ",";
// WiFi Mode
obj["i"] = -5;
obj["k"] = "WiFi Mode";
obj["v"] = WiFi.getMode();
serializeJson(obj, buf);
obj.clear();
buf += ",";
// WiFi Signal
obj["i"] = -6;
obj["k"] = "WiFi Signal";
obj["v"] = WiFi.RSSI();
serializeJson(obj, buf);
obj.clear();
}
// Loop through user defined stats
StaticJsonDocument<128> obj;
bool prevStatWritten = default_stats_enabled;
for (int i=0; i < statistics.Size(); i++) {
Statistic *s = statistics[i];
if (changes_only) {
if (s->_changed) {
s->_changed = false;
} else {
continue;
}
}
if (prevStatWritten) {
buf += ",";
}
obj["i"] = s->_id;
obj["k"] = s->_key;
if(changes_only || strlen(s->_value) > 0)
obj["v"] = s->_value;
obj["v"] = s->_value;
serializeJson(obj, buf);
obj.clear();
prevStatWritten = true;
}
buf += "]";
// Close JSON
buf += "}";
// Store the length of the JSON string
size_t total = buf.length();
// Send resp
#ifdef DASH_DEBUG
Serial.printf("client=%d, count=%d, changes_only=%d, total=%d\n%s\n", (client == nullptr ? -1 : client->id()), clients, changes_only, total, buf.c_str());
#endif
if (client != nullptr) {
_ws->text(client->id(), buf.c_str(), total);
} else {
_ws->textAll(buf.c_str(), total);
}
// Serial.println("Free Heap (During Update): "+String( ESP.getFreeHeap() ));
// Return length
return total;
}
/*
Generate Card JSON
*/
void ESPDash::generateComponentJSON(JsonObject& doc, Card* card, bool change_only){
doc["id"] = card->_id;
if(!change_only){
doc["n"] = card->_name.c_str();
doc["t"] = cardTags[card->_type].type;
doc["min"] = card->_value_min;
doc["max"] = card->_value_max;
}
if(change_only || !card->_symbol.isEmpty())
doc["s"] = card->_symbol;
switch (card->_value_type) {
case Card::INTEGER:
doc["v"] = card->_value_i;
break;
case Card::FLOAT:
doc["v"] = String(card->_value_f, 2);
break;
case Card::STRING:
if(change_only || !card->_value_s.isEmpty()) {
doc["v"] = card->_value_s;
}
break;
default:
// blank value
break;
}
}
/*
Generate Chart JSON
*/
void ESPDash::generateComponentJSON(JsonObject& doc, Chart* chart, bool change_only){
doc["id"] = chart->_id;
if(!change_only){
doc["n"] = chart->_name.c_str();
doc["t"] = chartTags[chart->_type].type;
}
JsonArray xAxis = doc["x"].to<JsonArray>();
switch (chart->_x_axis_type) {
case GraphAxisType::INTEGER:
#if DASH_USE_LEGACY_CHART_STORAGE == 1
for(int i=0; i < chart->_x_axis_i.Size(); i++)
xAxis.add(chart->_x_axis_i[i]);
#else
if (chart->_x_axis_i_ptr != nullptr) {
for(unsigned int i=0; i < chart->_x_axis_ptr_size; i++)
xAxis.add(chart->_x_axis_i_ptr[i]);
}
#endif
break;
case GraphAxisType::FLOAT:
#if DASH_USE_LEGACY_CHART_STORAGE == 1
for(int i=0; i < chart->_x_axis_f.Size(); i++)
xAxis.add(chart->_x_axis_f[i]);
#else
if (chart->_x_axis_f_ptr != nullptr) {
for(unsigned int i=0; i < chart->_x_axis_ptr_size; i++)
xAxis.add(chart->_x_axis_f_ptr[i]);
}
#endif
break;
case GraphAxisType::CHAR:
#if DASH_USE_LEGACY_CHART_STORAGE == 1
for(int i=0; i < chart->_x_axis_s.Size(); i++)
xAxis.add(chart->_x_axis_s[i].c_str());
#else
if (chart->_x_axis_char_ptr != nullptr) {
for(unsigned int i=0; i < chart->_x_axis_ptr_size; i++)
xAxis.add(chart->_x_axis_char_ptr[i]);
}
#endif
break;
case GraphAxisType::STRING:
#if DASH_USE_LEGACY_CHART_STORAGE == 1
for(int i=0; i < chart->_x_axis_s.Size(); i++)
xAxis.add(chart->_x_axis_s[i].c_str());
#else
if (chart->_x_axis_s_ptr != nullptr) {
for(unsigned int i=0; i < chart->_x_axis_ptr_size; i++)
xAxis.add(chart->_x_axis_s_ptr[i]);
}
#endif
break;
default:
// blank value
break;
}
JsonArray yAxis = doc["y"].to<JsonArray>();
switch (chart->_y_axis_type) {
case GraphAxisType::INTEGER:
#if DASH_USE_LEGACY_CHART_STORAGE == 1
for(int i=0; i < chart->_y_axis_i.Size(); i++)
yAxis.add(chart->_y_axis_i[i]);
#else
if (chart->_y_axis_i_ptr != nullptr) {
for(unsigned int i=0; i < chart->_y_axis_ptr_size; i++)
yAxis.add(chart->_y_axis_i_ptr[i]);
}
#endif
break;
case GraphAxisType::FLOAT:
#if DASH_USE_LEGACY_CHART_STORAGE == 1
for(int i=0; i < chart->_y_axis_f.Size(); i++)
yAxis.add(chart->_y_axis_f[i]);
#else
if (chart->_y_axis_f_ptr != nullptr) {
for(unsigned int i=0; i < chart->_y_axis_ptr_size; i++)
yAxis.add(chart->_y_axis_f_ptr[i]);
}
#endif
break;
default:
// blank value
break;
}
}
/* Send Card Updates to all clients */
void ESPDash::sendUpdates(bool force) {
generateLayoutJSON(nullptr, !force);
}
void ESPDash::refreshLayout() {
_ws->textAll("{\"command\":\"refresh:layout\"}");
}
void ESPDash::refreshStatistics() {
generateLayoutJSON(nullptr, true);
}
void ESPDash::refreshCard(Card *card) {
generateLayoutJSON(nullptr, true, card);
}
uint32_t ESPDash::nextId() {
return _idCounter++;
}
bool ESPDash::hasClient() {
return _ws->count() > 0;
}
/*
Destructor
*/
ESPDash::~ESPDash(){
_server->removeHandler(_ws);
delete _ws;
}