-
-
Notifications
You must be signed in to change notification settings - Fork 271
Expand file tree
/
Copy pathhasp_dispatch.cpp
More file actions
1758 lines (1473 loc) · 54.8 KB
/
Copy pathhasp_dispatch.cpp
File metadata and controls
1758 lines (1473 loc) · 54.8 KB
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* MIT License - Copyright (c) 2019-2024 Francis Van Roie
For full license information read the LICENSE file in the project folder */
#include <time.h>
#include <sys/time.h>
// #include "ArduinoLog.h"
#include "hasplib.h"
#include "dev/device.h"
#include "drv/tft/tft_driver.h"
// #include "hasp_gui.h"
#if HASP_USE_DEBUG > 0
#include "../hasp_debug.h"
#include "hasp_gui.h" // for screenshot
#if HASP_TARGET_PC
#include <iostream>
#include <fstream>
#include <sstream>
#include "../mqtt/hasp_mqtt.h"
#else
#include "StringStream.h"
#include "StreamUtils.h" // for exec ReadBufferingStream
#include "CharStream.h"
#include "hasp_oobe.h"
#include "sys/gpio/hasp_gpio.h"
#include "hal/hasp_hal.h"
#include "sys/svc/hasp_ota.h"
#include "mqtt/hasp_mqtt.h"
#include "sys/net/hasp_network.h" // for network_get_status()
#include "sys/net/hasp_time.h"
#endif
#endif
dispatch_conf_t dispatch_setings = {.teleperiod = 300};
uint16_t dispatchSecondsToNextTeleperiod = 0;
uint16_t dispatchSecondsToNextSensordata = 0;
uint16_t dispatchSecondsToNextDiscovery = 0;
uint8_t nCommands = 0;
haspCommand_t commands[28];
moodlight_t moodlight = {.brightness = 255};
uint8_t saved_jsonl_page = 0;
/* Sends the payload out on the state/subtopic
*/
void dispatch_state_subtopic(const char* subtopic, const char* payload)
{
#if HASP_USE_MQTT == 0 && HASP_USE_TASMOTA_CLIENT == 0
LOG_TRACE(TAG_MSGR, F("%s => %s"), subtopic, payload);
#else
#if HASP_USE_MQTT > 0
switch(mqtt_send_state(subtopic, payload)) {
case MQTT_ERR_OK:
LOG_TRACE(TAG_MQTT_PUB, F("%s => %s"), subtopic, payload);
break;
case MQTT_ERR_PUB_FAIL:
LOG_ERROR(TAG_MQTT_PUB, F(D_MQTT_FAILED " %s => %s"), subtopic, payload);
break;
case MQTT_ERR_NO_CONN:
LOG_ERROR(TAG_MQTT, F(D_MQTT_NOT_CONNECTED " %s => %s"), subtopic, payload);
break;
case MQTT_ERR_DISABLED:
break;
default:
LOG_ERROR(TAG_MQTT, F(D_ERROR_UNKNOWN " %s => %s"), subtopic, payload);
}
#endif
#if HASP_USE_TASMOTA_CLIENT > 0
slave_send_state(subtopic, payload);
#endif
#endif
}
void dispatch_state_eventid(const char* topic, hasp_event_t eventid)
{
char payload[32];
char eventname[8];
LOG_INFO(TAG_MQTT, "dispatch_state_eventid topic[%s] eid[%d]", topic, (uint16_t)eventid);
Parser::get_event_name(eventid, eventname, sizeof(eventname));
if(eventid == HASP_EVENT_ON || eventid == HASP_EVENT_OFF) {
snprintf_P(payload, sizeof(payload), PSTR("{\"state\":\"%s\"}"), eventname);
} else {
snprintf_P(payload, sizeof(payload), PSTR("{\"event\":\"%s\"}"), eventname);
}
dispatch_state_subtopic(topic, payload);
}
void dispatch_state_brightness(const char* topic, hasp_event_t eventid, int32_t val)
{
char payload[64];
char eventname[8];
Parser::get_event_name(eventid, eventname, sizeof(eventname));
snprintf_P(payload, sizeof(payload), PSTR("{\"state\":\"%s\",\"brightness\":%d}"), eventname, val);
dispatch_state_subtopic(topic, payload);
}
void dispatch_state_antiburn(hasp_event_t eventid)
{
char topic[9];
char payload[64];
char eventname[8];
Parser::get_event_name(eventid, eventname, sizeof(eventname));
snprintf_P(topic, sizeof(topic), PSTR("antiburn"));
snprintf_P(payload, sizeof(payload), PSTR("{\"state\":\"%s\"}"), eventname);
dispatch_state_subtopic(topic, payload);
}
void dispatch_state_val(const char* topic, hasp_event_t eventid, int32_t val)
{
char payload[64];
char eventname[8];
Parser::get_event_name(eventid, eventname, sizeof(eventname));
snprintf_P(payload, sizeof(payload), PSTR("{\"state\":\"%s\",\"val\":%d}"), eventname, val);
dispatch_state_subtopic(topic, payload);
}
void dispatch_json_error(uint8_t tag, DeserializationError& jsonError)
{
LOG_ERROR(tag, F(D_JSON_FAILED " %d"), jsonError);
// const char * error = jsonError.c_str();
// LOG_ERROR(tag, F(D_JSON_FAILED " %s"), error);
}
// p[x].b[y].attr=value
static inline bool dispatch_parse_button_attribute(const char* topic_p, const char* payload, bool update)
{
long num;
char* pEnd;
uint8_t pageid, objid;
if(*topic_p != 'p' && *topic_p != 'P') return false; // obligated p
topic_p++;
if(*topic_p == '[') { // optional brackets, TODO: remove
topic_p++;
num = strtol(topic_p, &pEnd, DEC);
if(*pEnd != ']') return false; // obligated closing bracket
pEnd++;
} else {
num = strtol(topic_p, &pEnd, DEC);
}
if(num < 0 || num > HASP_NUM_PAGES) return false; // page number must be valid
pageid = (uint8_t)num;
topic_p = pEnd;
if(*topic_p == '.') topic_p++; // optional separator
if(*topic_p != 'b' && *topic_p != 'B') return false; // obligated b
topic_p++;
if(*topic_p == '[') { // optional brackets, TODO: remove
topic_p++;
num = strtol(topic_p, &pEnd, DEC);
if(*pEnd != ']') return false; // obligated closing bracket
pEnd++;
} else {
num = strtol(topic_p, &pEnd, DEC);
}
if(num < 0 || num > 255) return false; // id must be valid
objid = (uint8_t)num;
topic_p = pEnd;
if(*topic_p != '.') return false; // obligated separator
topic_p++;
hasp_process_attribute(pageid, objid, topic_p, payload, update);
return true;
}
#if USE_OBJ_ALIAS > 0
static inline bool dispatch_parse_alias_attribute(const char* topic_p, const char* payload, bool update)
{
bool result = false;
if(*topic_p != '@') return false; // obligated @
topic_p++;
const char *pSeperator = strchr(topic_p, '.');
uint16_t aliaslen = (uint16_t)(pSeperator-topic_p);
uint16_t aliashash = Parser::get_sdbm(topic_p, aliaslen, true);
topic_p = pSeperator;
if(*topic_p != '.') return false; // obligated separator
topic_p++;
LOG_DEBUG(TAG_MSGR, "parse alias attribute : obj alias hash[%d] command[%s] payload[%s]", aliashash, topic_p, payload);
lv_obj_t *top = lv_layer_top();
/* search object on page 0 */
hasp_cmd_process_data_t data = {.topic_p = topic_p, .payload = payload, .update = update};
LOG_DEBUG(TAG_MSGR, "parse alias attribute : search page 0 childs[%d]", lv_obj_count_children(top));
if (hasp_find_obj_from_alias(top, aliashash, false, &data)) {
result = true;
}
/* search object on currently visible page first include subpages (tabview) */
uint8_t current_page = haspPages.get();
LOG_DEBUG(TAG_MSGR, "parse alias attribute : search page %d childs[%d]", current_page, lv_obj_count_children(haspPages.get_obj(current_page)));
if (hasp_find_obj_from_alias(haspPages.get_obj(current_page), aliashash, false, &data)) {
result = true;
}
/* search object on all other pages include subpages (tabview) */
uint8_t page = HASP_START_PAGE;
while (page <= HASP_NUM_PAGES) {
if (page != current_page) {
LOG_DEBUG(TAG_MSGR, "parse alias attribute : search page %d childs[%d]", page, lv_obj_count_children(haspPages.get_obj(page)));
if (hasp_find_obj_from_alias(haspPages.get_obj(page), aliashash, false, &data)) {
result = true;
}
}
page++;
}
return result;
}
#endif // #if USE_OBJ_ALIAS > 0
static void dispatch_input(const char* topic, const char* payload)
{
#if HASP_USE_GPIO > 0
if(!Parser::is_only_digits(topic)) {
LOG_WARNING(TAG_MSGR, F("Invalid pin %s"), topic);
return;
}
// just output the pin state
uint8_t pin = atoi(topic);
if(gpio_input_pin_state(pin)) return;
LOG_WARNING(TAG_GPIO, F(D_BULLET "Pin %d is not configured"), pin);
#endif
}
static void dispatch_output(const char* topic, const char* payload)
{
#if HASP_USE_GPIO > 0
if(!Parser::is_only_digits(topic)) {
LOG_WARNING(TAG_MSGR, F("Invalid pin %s"), topic);
return;
}
uint8_t pin = atoi(topic);
if(strlen(payload) > 0) {
StaticJsonDocument<128> json;
// Note: Deserialization needs to be (const char *) so the objects WILL be copied
// this uses more memory but otherwise the mqtt receive buffer can get overwritten by the send buffer !!
DeserializationError jsonError = deserializeJson(json, payload);
if(jsonError) { // Couldn't parse incoming JSON command
dispatch_json_error(TAG_MSGR, jsonError);
} else {
// Save the current state
int32_t state_value;
bool power_state;
bool updated = false;
if(!gpio_get_pin_state(pin, power_state, state_value)) {
LOG_WARNING(TAG_GPIO, F(D_BULLET "Pin %d can not be set"), pin);
return;
}
JsonVariant state = json[F("state")];
JsonVariant value = json[F("val")];
JsonVariant brightness = json[F("brightness")];
// Check if the state needs to change
if(!state.isNull() && power_state != Parser::is_true(state)) {
power_state = Parser::is_true(state);
updated = true;
}
if(!value.isNull() && state_value != value.as<int32_t>()) {
state_value = value.as<int32_t>();
updated = true;
} else if(!brightness.isNull() && state_value != brightness.as<int32_t>()) {
state_value = brightness.as<int32_t>();
updated = true;
}
// Set new state
if(updated && gpio_set_pin_state(pin, power_state, state_value)) {
return; // value was set and state output already in gpio_set_pin_state
} else {
// output the new state to the log
}
}
}
// just output this pin
if(!gpio_output_pin_state(pin)) {
LOG_WARNING(TAG_GPIO, F(D_BULLET "Pin %d is not configured"), pin);
}
#endif
}
// static inline size_t dispatch_msg_length(size_t len)
// {
// return (len / 64) * 64 + 64;
// }
// void dispatch_enqueue_message(const char* topic, const char* payload, size_t payload_len, uint8_t source)
// {
// // Add new message to the queue
// dispatch_message_t data;
// size_t topic_len = strlen(topic);
// data.topic = (char*)hasp_calloc(sizeof(char), dispatch_msg_length(topic_len + 1));
// data.payload = (char*)hasp_calloc(sizeof(char), dispatch_msg_length(payload_len + 1));
// data.source = source;
// if(!data.topic || !data.payload) {
// LOG_ERROR(TAG_MQTT_RCV, D_ERROR_OUT_OF_MEMORY);
// hasp_free(data.topic);
// hasp_free(data.payload);
// return;
// }
// memcpy(data.topic, topic, topic_len);
// memcpy(data.payload, payload, payload_len);
// {
// size_t attempt = 0;
// while(xQueueSend(message_queue, &data, (TickType_t)0) == errQUEUE_FULL && attempt < 100) {
// delay(5);
// attempt++;
// };
// if(attempt >= 100) {
// LOG_ERROR(TAG_MSGR, D_ERROR_OUT_OF_MEMORY);
// }
// }
// }
// objectattribute=value
static void dispatch_command(const char* topic, const char* payload, bool update, uint8_t source)
{
/* ================================= Standard payload commands ======================================= */
if(dispatch_parse_button_attribute(topic, payload, update)) {
LOG_DEBUG(TAG_MSGR, "dispatch object matched pxby.attr");
return; // matched pxby.attr, first for speed
}
#if USE_OBJ_ALIAS > 0
if(dispatch_parse_alias_attribute(topic, payload, update)) {
LOG_DEBUG(TAG_MSGR, "dispatch object matched alias.attr");
return; // matched alias.attr
}
#endif // #if USE_OBJ_ALIAS > 0
// check and execute commands from commands array
for(int i = 0; i < nCommands; i++) {
if(!strcasecmp_P(topic, commands[i].p_cmdstr)) {
// LOG_DEBUG(TAG_MSGR, F("Command %d found in array !!!"), i);
commands[i].func(topic, payload, source); /* execute command */
return;
}
}
/* =============================== Not standard payload commands ===================================== */
if(topic == strstr_P(topic, PSTR("output"))) {
dispatch_output(topic + 6, payload);
} else if(topic == strstr_P(topic, PSTR("input"))) {
dispatch_input(topic + 5, payload);
// } else if(strcasecmp_P(topic, PSTR("screenshot")) == 0) {
// guiTakeScreenshot("/screenshot.bmp"); // Literal String
#if HASP_USE_CONFIG > 0
#if HASP_USE_WIFI > 0
} else if(!strcmp_P(topic, FP_CONFIG_SSID) || !strcmp_P(topic, FP_CONFIG_PASS)) {
StaticJsonDocument<64> settings;
settings[topic] = payload;
wifiSetConfig(settings.as<JsonObject>());
#endif // HASP_USE_WIFI
#if HASP_USE_MQTT > 0
} else if(!strcmp_P(topic, PSTR("mqtthost")) || !strcmp_P(topic, PSTR("mqttport")) ||
!strcmp_P(topic, PSTR("mqttuser")) || !strcmp_P(topic, PSTR("mqttpass")) ||
!strcmp_P(topic, PSTR("hostname"))) {
// char item[5];
// memset(item, 0, sizeof(item));
// strncpy(item, topic + 4, 4);
StaticJsonDocument<64> settings;
settings[topic + 4] = payload;
mqttSetConfig(settings.as<JsonObject>());
#endif // HASP_USE_MQTT
#endif // HASP_USE_CONFIG
} else {
if(strlen(payload) == 0) {
// dispatch_simple_text_command(topic); // Could cause an infinite loop!
}
LOG_WARNING(TAG_MSGR, F(D_DISPATCH_COMMAND_NOT_FOUND " => %s"), topic, payload);
}
}
// Parse one line of text and execute the command
static void dispatch_simple_text_command(const char* cmnd, uint8_t source)
{
while(cmnd[0] == ' ' || cmnd[0] == '\t') cmnd++; // skip leading spaces
if(cmnd[0] == '/' && cmnd[1] == '/') return; // comment
switch(cmnd[0]) {
case '#': // comment
case '\0': // empty line
break;
case '{':
dispatch_command("jsonl", cmnd, false, source);
break;
case '[':
dispatch_command("json", cmnd, false, source);
break; // comment
// case ' ':
// dispatch_simple_text_command(cmnd, source);
// break;
default: {
size_t pos1 = std::string(cmnd).find("=");
size_t pos2 = std::string(cmnd).find(" ");
size_t pos = 0;
bool update = false;
// Find what comes first, ' ' or '='
if(pos1 != std::string::npos) { // '=' found
if(pos2 != std::string::npos) { // ' ' found
pos = (pos1 < pos2 ? pos1 : pos2);
} else {
pos = pos1;
}
update = pos == pos1; // equal sign wins
} else {
pos = (pos2 != std::string::npos) ? pos2 : 0;
}
if(pos > 0) { // ' ' or '=' found
char topic[64];
memset(topic, 0, sizeof(topic));
if(pos < sizeof(topic))
memcpy(topic, cmnd, pos);
else
memcpy(topic, cmnd, sizeof(topic) - 1);
// topic is before '=', payload is after '=' position
update |= strlen(cmnd + pos + 1) > 0; // equal sign OR space with payload
LOG_TRACE(TAG_MSGR, update ? F("%s=%s") : F("%s%s"), topic, cmnd + pos + 1);
dispatch_topic_payload(topic, cmnd + pos + 1, update, source);
} else {
char empty_payload[1] = {0};
LOG_TRACE(TAG_MSGR, cmnd);
dispatch_topic_payload(cmnd, empty_payload, false, source);
}
}
}
}
// Strip command/config prefix from the topic and process the payload
void dispatch_topic_payload(const char* topic, const char* payload, bool update, uint8_t source)
{
if(!strcmp_P(topic, PSTR(MQTT_TOPIC_COMMAND)) || topic[0] == '\0') {
dispatch_simple_text_command((char*)payload, source);
return;
}
if(topic == strstr_P(topic, PSTR(MQTT_TOPIC_COMMAND "/"))) { // startsWith command/
topic += 8u;
dispatch_command(topic, (char*)payload, update, source);
return;
}
#if HASP_USE_CONFIG > 0
if(topic == strstr_P(topic, PSTR("config/"))) { // startsWith config/
topic += 7u;
dispatch_config(topic, (char*)payload, source);
return;
}
#endif
#if defined(HASP_USE_CUSTOM)
if(topic == strstr_P(topic, PSTR(MQTT_TOPIC_CUSTOM "/"))) { // startsWith custom
topic += 7u;
custom_topic_payload(topic, (char*)payload, source);
return;
}
#endif
dispatch_command(topic, (char*)payload, update, source); // dispatch as is
}
// void dispatch_output_group_state(uint8_t groupid, uint16_t state)
// {
// char payload[64];
// char number[16]; // Return the current state
// char topic[8];
// itoa(state, number, DEC);
// snprintf_P(payload, sizeof(payload), PSTR("{\"group\":%d,\"state\":\"%s\"}"), groupid, number);
// memcpy_P(topic, PSTR("output"), 7);
// dispatch_state_subtopic(topic, payload);
// }
#if HASP_USE_CONFIG > 0
// Get or Set a part of the config.json file
void dispatch_config(const char* topic, const char* payload, uint8_t source)
{
DynamicJsonDocument doc(512);
char buffer[512];
JsonObject settings;
bool update;
if(strlen(payload) == 0) {
// Make sure we have a valid JsonObject to start from
settings = doc.to<JsonObject>().createNestedObject(topic);
update = false;
} else {
DeserializationError jsonError = deserializeJson(doc, payload);
if(jsonError) { // Couldn't parse incoming JSON command
dispatch_json_error(TAG_MSGR, jsonError);
return;
}
settings = doc.as<JsonObject>();
update = true;
}
if(strcasecmp_P(topic, PSTR("debug")) == 0) {
#if HASP_TARGET_ARDUINO
if(update)
debugSetConfig(settings);
else
debugGetConfig(settings);
#endif
}
else if(strcasecmp_P(topic, PSTR("gui")) == 0) {
if(update)
guiSetConfig(settings);
else
guiGetConfig(settings);
}
else if(strcasecmp_P(topic, PSTR("hasp")) == 0) {
if(update)
haspSetConfig(settings);
else
haspGetConfig(settings);
}
#if HASP_USE_GPIO > 0
else if(strcasecmp_P(topic, PSTR("gpio")) == 0) {
if(update)
gpioSetConfig(settings);
else
gpioGetConfig(settings);
}
#endif
#if HASP_USE_WIFI > 0
else if(strcasecmp_P(topic, PSTR("wifi")) == 0) {
if(update)
wifiSetConfig(settings);
else
wifiGetConfig(settings);
}
else if(strcasecmp_P(topic, PSTR("time")) == 0) {
if(update)
timeSetConfig(settings);
else
timeGetConfig(settings);
}
#if HASP_USE_WIREGUARD > 0
else if(strcasecmp_P(topic, PSTR(FP_WG)) == 0) {
if(update)
wgSetConfig(settings);
else
wgGetConfig(settings);
}
#endif
#if HASP_USE_MQTT > 0
else if(strcasecmp_P(topic, PSTR(FP_MQTT)) == 0) {
if(update)
mqttSetConfig(settings);
else
mqttGetConfig(settings);
}
#endif
#if HASP_USE_TELNET > 0
// else if(strcasecmp_P(topic, PSTR("telnet")) == 0)
// telnetGetConfig(settings[F("telnet")]);
#endif
#if HASP_USE_MDNS > 0
else if(strcasecmp_P(topic, PSTR("mdns")) == 0) {
if(update)
mdnsSetConfig(settings);
else
mdnsGetConfig(settings);
}
#endif
#if HASP_USE_HTTP > 0 || HASP_USE_HTTP_ASYNC > 0
else if(strcasecmp_P(topic, PSTR(FP_HTTP)) == 0) {
if(update)
httpSetConfig(settings);
else
httpGetConfig(settings);
}
#endif
#if HASP_USE_FTP > 0
else if(strcasecmp_P(topic, PSTR(FP_FTP)) == 0) {
if(update)
ftpSetConfig(settings);
else
ftpGetConfig(settings);
}
#endif
#if HASP_USE_ARDUINOOTA > 0 || HASP_USE_HTTP_UPDATE > 0
else if(strcasecmp_P(topic, PSTR(FP_OTA)) == 0) {
if(update)
otaSetConfig(settings);
else
otaGetConfig(settings);
}
#endif
#endif
// Send output
if(!update) {
char subtopic[8];
settings.remove(FP_CONFIG_PASS); // hide password in output
/* size_t size = */ serializeJson(doc, buffer, sizeof(buffer));
memcpy_P(subtopic, PSTR("config"), 7);
dispatch_state_subtopic(subtopic, buffer);
}
}
#endif // HASP_USE_CONFIG
/********************************************** Output States ******************************************/
void dispatch_normalized_group_values(hasp_update_value_t& value)
{
// if(value.group == 0) return;
#if HASP_USE_GPIO > 0
if(value.group) {
gpio_set_normalized_group_values(value); // Update GPIO states first
}
#endif
#if USE_OBJ_ALIAS == 0
if(value.group)
#else
if(value.group || value.alias)
#endif
{
object_set_normalized_group_values(value); // Update onsreen objects except originating obj
}
LOG_VERBOSE(TAG_MSGR, F("GROUP %d value %d (%d-%d)"), value.group, value.val, value.min, value.max);
#if HASP_USE_GPIO > 0
if(value.group) {
gpio_output_group_values(value.group); // Output new gpio values
}
#endif
}
/********************************************** Native Commands ****************************************/
void dispatch_screenshot(const char*, const char* filename, uint8_t source)
{
#if HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0
if(strlen(filename) == 0) { // no filename given
char tempfile[32];
memcpy_P(tempfile, PSTR("/screenshot.bmp"), sizeof(tempfile));
guiTakeScreenshot(tempfile);
} else if(strlen(filename) > 31 || filename[0] != '/') { // Invalid filename
LOG_WARNING(TAG_MSGR, F("D_FILE_SAVE_FAILED"), filename);
} else { // Valid filename
guiTakeScreenshot(filename);
}
#else
LOG_WARNING(TAG_MSGR, D_FILE_SAVE_FAILED, filename);
#endif
}
bool dispatch_json_variant(JsonVariant& json, uint8_t& savedPage, uint8_t source)
{
if(json.is<JsonArray>()) { // handle json as an array of commands
LOG_DEBUG(TAG_MSGR, "Json ARRAY");
for(JsonVariant command : json.as<JsonArray>()) {
dispatch_json_variant(command, savedPage, source);
}
} else if(json.is<JsonObject>()) { // handle json as a jsonl
LOG_DEBUG(TAG_MSGR, "Json OBJECT");
hasp_new_object(json.as<JsonObject>(), savedPage);
} else if(json.is<std::string>()) { // handle json as a single command
LOG_DEBUG(TAG_MSGR, "Json text = %s", json.as<std::string>().c_str());
dispatch_simple_text_command(json.as<std::string>().c_str(), source);
} else if(json.is<const char*>()) { // handle json as a single command
LOG_DEBUG(TAG_MSGR, "Json text = %s", json.as<const char*>());
dispatch_simple_text_command(json.as<const char*>(), source);
} else if(json.isNull()) { // event handler not found
// nothing to do
} else {
LOG_WARNING(TAG_MSGR, "Json has unknown type");
return false;
}
return true;
}
void dispatch_text_line(const char* payload, uint8_t source)
{
{
// StaticJsonDocument<1024> doc;
size_t maxsize = (128u * ((strlen(payload) / 128) + 1)) + 512;
DynamicJsonDocument doc(maxsize);
// Note: Deserialization needs to be (const char *) so the objects WILL be copied
// this uses more memory but otherwise the mqtt receive buffer can get overwritten by the send buffer !!
DeserializationError jsonError = deserializeJson(doc, payload);
doc.shrinkToFit();
if(jsonError) {
// dispatch_json_error(TAG_MSGR, jsonError);
} else {
JsonVariant json = doc.as<JsonVariant>();
uint8_t savedPage = haspPages.get();
if(!dispatch_json_variant(json, savedPage, source)) {
LOG_WARNING(TAG_MSGR, F(D_DISPATCH_COMMAND_NOT_FOUND), payload);
// dispatch_simple_text_command(payload, source);
}
return;
}
}
// Could not parse as json
dispatch_simple_text_command(payload, source);
}
void dispatch_parse_json(const char*, const char* payload, uint8_t source)
{ // Parse an incoming JSON array into individual commands
// StaticJsonDocument<2048> doc;
size_t maxsize = (128u * ((strlen(payload) / 128) + 1)) + 512;
DynamicJsonDocument doc(maxsize);
DeserializationError jsonError = deserializeJson(doc, payload);
doc.shrinkToFit();
if(jsonError) {
dispatch_json_error(TAG_MSGR, jsonError);
return;
}
JsonVariant json = doc.as<JsonVariant>();
uint8_t savedPage = haspPages.get();
if(!dispatch_json_variant(json, savedPage, TAG_EVENT)) {
LOG_WARNING(TAG_MSGR, F(D_DISPATCH_COMMAND_NOT_FOUND), "");
}
}
#ifdef ARDUINO
void dispatch_parse_jsonl(Stream& stream, uint8_t& saved_page_id)
#else
void dispatch_parse_jsonl(std::istream& stream, uint8_t& saved_page_id)
#endif
{
#ifdef ARDUINO
stream.setTimeout(25);
#endif
// StaticJsonDocument<1024> jsonl;
DynamicJsonDocument jsonl(MQTT_MAX_PACKET_SIZE / 2 + 128);
DeserializationError jsonError; // = deserializeJson(jsonl, stream);
uint16_t line = 1;
// while(jsonError == DeserializationError::Ok) {
// hasp_new_object(jsonl.as<JsonObject>(), saved_page_id);
// jsonError = deserializeJson(jsonl, stream);
// line++;
// }
while(1) {
jsonError = deserializeJson(jsonl, stream);
if(jsonError == DeserializationError::Ok) {
hasp_new_object(jsonl.as<JsonObject>(), saved_page_id);
line++;
} else {
break;
}
};
/* For debugging purposes */
if(jsonError == DeserializationError::EmptyInput) {
LOG_DEBUG(TAG_MSGR, F(D_JSONL_SUCCEEDED));
} else {
LOG_ERROR(TAG_MSGR, F(D_JSONL_FAILED ": %s"), line, jsonError.c_str());
}
saved_jsonl_page = saved_page_id;
}
void dispatch_parse_jsonl(const char*, const char* payload, uint8_t source)
{
if(source != TAG_MQTT) saved_jsonl_page = haspPages.get();
#if HASP_USE_CONFIG > 0 && HASP_TARGET_ARDUINO
CharStream stream((char*)payload);
// stream.setTimeout(10);
dispatch_parse_jsonl(stream, saved_jsonl_page);
#else
std::istringstream stream((char*)payload);
dispatch_parse_jsonl(stream, saved_jsonl_page);
#endif
}
void dispatch_run_script(const char*, const char* payload, uint8_t source)
{
const char* filename = payload;
if(filename[0] == 'L' && filename[1] == ':') filename += 2; // strip littlefs drive letter
#if ARDUINO
#if HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0
if(!HASP_FS.exists(filename)) {
LOG_WARNING(TAG_MSGR, F(D_FILE_NOT_FOUND ": %s"), payload);
return;
}
LOG_TRACE(TAG_MSGR, F(D_FILE_LOADING), payload);
File cmdfile = HASP_FS.open(filename, "r");
if(!cmdfile) {
LOG_ERROR(TAG_MSGR, F(D_FILE_LOAD_FAILED), payload);
return;
}
// if(!gui_acquire(pdMS_TO_TICKS(500))) {
// LOG_ERROR(TAG_MSGR, F(D_FILE_LOAD_FAILED), payload);
// return;
// }
// char buffer[512]; // use stack
String buffer((char*)0); // use heap
buffer.reserve(512);
ReadBufferingStream bufferedFile{cmdfile, 512};
cmdfile.seek(0);
while(bufferedFile.available()) {
size_t index = 0;
buffer = "";
while(index < MQTT_MAX_PACKET_SIZE) {
int c = bufferedFile.read();
if(c < 0 || c == '\n' || c == '\r') { // CR or LF
break;
}
buffer += (char)c;
index++;
}
if(index > 0 && buffer.charAt(0) != '#') { // Check for comments
dispatch_simple_text_command(buffer.c_str(), TAG_FILE);
}
}
// gui_release();
cmdfile.close();
LOG_INFO(TAG_MSGR, F(D_FILE_LOADED), payload);
#else
LOG_ERROR(TAG_MSGR, F(D_FILE_LOAD_FAILED), payload);
#endif
#else
char path[strlen(filename) + 4];
path[0] = '.';
path[1] = '\0';
strcat(path, filename);
#if defined(WINDOWS)
path[1] = '\\';
#elif defined(POSIX)
path[1] = '/';
#endif
LOG_TRACE(TAG_HASP, F("Loading %s from disk..."), path);
std::ifstream f(path); // taking file as inputstream
if(f) {
std::string line;
while(std::getline(f, line)) {
LOG_VERBOSE(TAG_HASP, line.c_str());
if(!line.empty() && line[0] != '#') dispatch_simple_text_command(line.c_str(), TAG_FILE); // # for comments
}
} else {
LOG_ERROR(TAG_MSGR, F(D_FILE_LOAD_FAILED), payload);
}
f.close();
LOG_INFO(TAG_HASP, F("Loaded %s from disk"), path);
#endif
}
#if HASP_TARGET_PC
static void shell_command_thread(char* cmdline)
{
// run the command
FILE* pipe = popen(cmdline, "r");
// free the string duplicated previously
free(cmdline);
if(!pipe) {
LOG_ERROR(TAG_MSGR, F("Couldn't execute system command"));
return;
}
// read each line, up to 1023 chars long
char command[1024];
while(fgets(command, sizeof(command), pipe) != NULL) {
// strip newline character
char* temp = command;
while(*temp) {
if(*temp == '\r' || *temp == '\n') {
*temp = '\0';
break;
}
temp++;
}
// run the command
LOG_INFO(TAG_MSGR, F("Running '%s'"), command);
dispatch_text_line(command, TAG_MSGR);
}
// close the pipe, check return code
int status_code = pclose(pipe);
if(status_code) {
LOG_ERROR(TAG_MSGR, F("Process exited with non-zero return code %d"), status_code);
}
}
void dispatch_shell_execute(const char*, const char* payload, uint8_t source)
{
// must duplicate the string for thread's own usage
char* command = strdup(payload);
haspDevice.run_thread((void (*)(void*))shell_command_thread, (void*)command);
}
#endif
void dispatch_current_page()
{
char topic[8];
char payload[8];
memcpy_P(topic, PSTR("page"), 5);
snprintf_P(payload, sizeof(payload), PSTR("%d"), haspPages.get());
dispatch_state_subtopic(topic, payload);
}
// Dispatch Page Get or Set
void dispatch_page_next(lv_scr_load_anim_t animation)
{
haspPages.next(animation, 500, 0);
dispatch_current_page();