-
Notifications
You must be signed in to change notification settings - Fork 14
/
sonoff.ino
2562 lines (2360 loc) · 106 KB
/
sonoff.ino
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
/*
sonoff.ino - Sonoff-Tasmota firmware for iTead Sonoff, Wemos and NodeMCU hardware
Copyright (C) 2018 Theo Arends
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*====================================================
Prerequisites:
- Change libraries/PubSubClient/src/PubSubClient.h
#define MQTT_MAX_PACKET_SIZE 1000
- Select IDE Tools - Flash Mode: "DOUT"
- Select IDE Tools - Flash Size: "1M (no SPIFFS)"
====================================================*/
#define VERSION 0x06010103 // 6.1.1c
// Location specific includes
#include <core_version.h> // Arduino_Esp8266 version information (ARDUINO_ESP8266_RELEASE and ARDUINO_ESP8266_RELEASE_2_3_0)
#include "sonoff.h" // Enumeration used in user_config.h
#include "user_config.h" // Fixed user configurable options
#ifdef USE_CONFIG_OVERRIDE
#include "user_config_override.h" // Configuration overrides for user_config.h
#endif
#include "sonoff_post.h" // Configuration overrides for all previous includes
#include "i18n.h" // Language support configured by user_config.h
#include "sonoff_template.h" // Hardware configuration
#ifdef ARDUINO_ESP8266_RELEASE_2_4_0
#include "lwip/init.h"
#if LWIP_VERSION_MAJOR != 1
#error Please use stable lwIP v1.4
#endif
#endif
// Libraries
#include <Ticker.h> // RTC, Energy, OSWatch
#include <ESP8266WiFi.h> // MQTT, Ota, WifiManager
#include <ESP8266HTTPClient.h> // MQTT, Ota
#include <ESP8266httpUpdate.h> // Ota
#include <StreamString.h> // Webserver, Updater
#include <ArduinoJson.h> // WemoHue, IRremote, Domoticz
#ifdef USE_WEBSERVER
#include <ESP8266WebServer.h> // WifiManager, Webserver
#include <DNSServer.h> // WifiManager
#endif // USE_WEBSERVER
#ifdef USE_ARDUINO_OTA
#include <ArduinoOTA.h> // Arduino OTA
#ifndef USE_DISCOVERY
#define USE_DISCOVERY
#endif
#endif // USE_ARDUINO_OTA
#ifdef USE_DISCOVERY
#include <ESP8266mDNS.h> // MQTT, Webserver, Arduino OTA
#endif // USE_DISCOVERY
#ifdef USE_I2C
#include <Wire.h> // I2C support library
#endif // USE_I2C
#ifdef USE_SPI
#include <SPI.h> // SPI support, TFT
#endif // USE_SPI
// Structs
#include "settings.h"
enum TasmotaCommands {
CMND_BACKLOG, CMND_DELAY, CMND_POWER, CMND_FANSPEED, CMND_STATUS, CMND_STATE, CMND_POWERONSTATE, CMND_PULSETIME,
CMND_BLINKTIME, CMND_BLINKCOUNT, CMND_SENSOR, CMND_SAVEDATA, CMND_SETOPTION, CMND_TEMPERATURE_RESOLUTION, CMND_HUMIDITY_RESOLUTION,
CMND_PRESSURE_RESOLUTION, CMND_POWER_RESOLUTION, CMND_VOLTAGE_RESOLUTION, CMND_CURRENT_RESOLUTION, CMND_ENERGY_RESOLUTION, CMND_MODULE, CMND_MODULES,
CMND_GPIO, CMND_GPIOS, CMND_PWM, CMND_PWMFREQUENCY, CMND_PWMRANGE, CMND_COUNTER, CMND_COUNTERTYPE,
CMND_COUNTERDEBOUNCE, CMND_SLEEP, CMND_UPGRADE, CMND_UPLOAD, CMND_OTAURL, CMND_SERIALLOG, CMND_SYSLOG,
CMND_LOGHOST, CMND_LOGPORT, CMND_IPADDRESS, CMND_NTPSERVER, CMND_AP, CMND_SSID, CMND_PASSWORD, CMND_HOSTNAME,
CMND_WIFICONFIG, CMND_FRIENDLYNAME, CMND_SWITCHMODE,
CMND_TELEPERIOD, CMND_RESTART, CMND_RESET, CMND_TIMEZONE, CMND_TIMESTD, CMND_TIMEDST, CMND_ALTITUDE, CMND_LEDPOWER, CMND_LEDSTATE,
CMND_I2CSCAN, CMND_SERIALSEND, CMND_BAUDRATE, CMND_SERIALDELIMITER };
const char kTasmotaCommands[] PROGMEM =
D_CMND_BACKLOG "|" D_CMND_DELAY "|" D_CMND_POWER "|" D_CMND_FANSPEED "|" D_CMND_STATUS "|" D_CMND_STATE "|" D_CMND_POWERONSTATE "|" D_CMND_PULSETIME "|"
D_CMND_BLINKTIME "|" D_CMND_BLINKCOUNT "|" D_CMND_SENSOR "|" D_CMND_SAVEDATA "|" D_CMND_SETOPTION "|" D_CMND_TEMPERATURE_RESOLUTION "|" D_CMND_HUMIDITY_RESOLUTION "|"
D_CMND_PRESSURE_RESOLUTION "|" D_CMND_POWER_RESOLUTION "|" D_CMND_VOLTAGE_RESOLUTION "|" D_CMND_CURRENT_RESOLUTION "|" D_CMND_ENERGY_RESOLUTION "|" D_CMND_MODULE "|" D_CMND_MODULES "|"
D_CMND_GPIO "|" D_CMND_GPIOS "|" D_CMND_PWM "|" D_CMND_PWMFREQUENCY "|" D_CMND_PWMRANGE "|" D_CMND_COUNTER "|" D_CMND_COUNTERTYPE "|"
D_CMND_COUNTERDEBOUNCE "|" D_CMND_SLEEP "|" D_CMND_UPGRADE "|" D_CMND_UPLOAD "|" D_CMND_OTAURL "|" D_CMND_SERIALLOG "|" D_CMND_SYSLOG "|"
D_CMND_LOGHOST "|" D_CMND_LOGPORT "|" D_CMND_IPADDRESS "|" D_CMND_NTPSERVER "|" D_CMND_AP "|" D_CMND_SSID "|" D_CMND_PASSWORD "|" D_CMND_HOSTNAME "|"
D_CMND_WIFICONFIG "|" D_CMND_FRIENDLYNAME "|" D_CMND_SWITCHMODE "|"
D_CMND_TELEPERIOD "|" D_CMND_RESTART "|" D_CMND_RESET "|" D_CMND_TIMEZONE "|" D_CMND_TIMESTD "|" D_CMND_TIMEDST "|" D_CMND_ALTITUDE "|" D_CMND_LEDPOWER "|" D_CMND_LEDSTATE "|"
D_CMND_I2CSCAN "|" D_CMND_SERIALSEND "|" D_CMND_BAUDRATE "|" D_CMND_SERIALDELIMITER;
const uint8_t kIFan02Speed[4][3] = {{6,6,6}, {7,6,6}, {7,7,6}, {7,6,7}};
// Global variables
unsigned long feature_drv1; // Compiled driver feature map
unsigned long feature_drv2; // Compiled driver feature map
unsigned long feature_sns1; // Compiled sensor feature map
unsigned long feature_sns2; // Compiled sensor feature map
int baudrate = APP_BAUDRATE; // Serial interface baud rate
SerialConfig serial_config = SERIAL_8N1; // Serial interface configuration 8 data bits, No parity, 1 stop bit
byte serial_in_byte; // Received byte
uint8_t serial_local = 0; // Handle serial locally;
unsigned long serial_polling_window = 0; // Serial polling window
int serial_in_byte_counter = 0; // Index in receive buffer
byte dual_hex_code = 0; // Sonoff dual input flag
uint16_t dual_button_code = 0; // Sonoff dual received code
int16_t save_data_counter; // Counter and flag for config save to Flash
uint8_t fallback_topic_flag = 0; // Use Topic or FallbackTopic
unsigned long state_loop_timer = 0; // State loop timer
int state = 0; // State per second flag
int ota_state_flag = 0; // OTA state flag
int ota_result = 0; // OTA result
byte ota_retry_counter = OTA_ATTEMPTS; // OTA retry counter
char *ota_url; // OTA url string
int restart_flag = 0; // Sonoff restart flag
int wifi_state_flag = WIFI_RESTART; // Wifi state flag
uint32_t uptime = 0; // Counting every second until 4294967295 = 130 year
boolean latest_uptime_flag = true; // Signal latest uptime
int tele_period = 0; // Tele period timer
byte web_log_index = 1; // Index in Web log buffer (should never be 0)
byte reset_web_log_flag = 0; // Reset web console log
byte devices_present = 0; // Max number of devices supported
int status_update_timer = 0; // Refresh initial status
uint16_t pulse_timer[MAX_PULSETIMERS] = { 0 }; // Power off timer
uint16_t blink_timer = 0; // Power cycle timer
uint16_t blink_counter = 0; // Number of blink cycles
power_t blink_power; // Blink power state
power_t blink_mask = 0; // Blink relay active mask
power_t blink_powersave; // Blink start power save state
uint16_t mqtt_cmnd_publish = 0; // ignore flag for publish command
power_t latching_power = 0; // Power state at latching start
uint8_t latching_relay_pulse = 0; // Latching relay pulse timer
uint8_t backlog_index = 0; // Command backlog index
uint8_t backlog_pointer = 0; // Command backlog pointer
uint8_t backlog_mutex = 0; // Command backlog pending
uint16_t backlog_delay = 0; // Command backlog delay
uint8_t interlock_mutex = 0; // Interlock power command pending
#ifdef USE_MQTT_TLS
WiFiClientSecure EspClient; // Wifi Secure Client
#else
WiFiClient EspClient; // Wifi Client
#endif
WiFiUDP PortUdp; // UDP Syslog and Alexa
power_t power = 0; // Current copy of Settings.power
byte syslog_level; // Current copy of Settings.syslog_level
uint16_t syslog_timer = 0; // Timer to re-enable syslog_level
byte seriallog_level; // Current copy of Settings.seriallog_level
uint16_t seriallog_timer = 0; // Timer to disable Seriallog
uint8_t sleep; // Current copy of Settings.sleep
uint8_t stop_flash_rotate = 0; // Allow flash configuration rotation
int blinks = 201; // Number of LED blinks
uint8_t blinkstate = 0; // LED state
uint8_t blinkspeed = 1; // LED blink rate
uint8_t blockgpio0 = 4; // Block GPIO0 for 4 seconds after poweron to workaround Wemos D1 RTS circuit
uint8_t lastbutton[MAX_KEYS] = { NOT_PRESSED, NOT_PRESSED, NOT_PRESSED, NOT_PRESSED }; // Last button states
uint16_t holdbutton[MAX_KEYS] = { 0 }; // Timer for button hold
uint8_t multiwindow[MAX_KEYS] = { 0 }; // Max time between button presses to record press count
uint8_t multipress[MAX_KEYS] = { 0 }; // Number of button presses within multiwindow
uint8_t lastwallswitch[MAX_SWITCHES]; // Last wall switch states
uint8_t holdwallswitch[MAX_SWITCHES] = { 0 }; // Timer for wallswitch push button hold
uint8_t virtualswitch[MAX_SWITCHES]; // Virtual switch states
mytmplt my_module; // Active copy of Module name and GPIOs
uint8_t pin[GPIO_MAX]; // Possible pin configurations
power_t rel_inverted = 0; // Relay inverted flag (1 = (0 = On, 1 = Off))
uint8_t led_inverted = 0; // LED inverted flag (1 = (0 = On, 1 = Off))
uint8_t pwm_inverted = 0; // PWM inverted flag (1 = inverted)
uint8_t dht_flg = 0; // DHT configured
uint8_t energy_flg = 1; // Energy monitor configured
uint8_t i2c_flg = 0; // I2C configured
uint8_t spi_flg = 0; // SPI configured
uint8_t light_type = 0; // Light types
bool pwm_present = false; // Any PWM channel configured with SetOption15 0
boolean mdns_begun = false;
uint8_t ntp_force_sync = 0; // Force NTP sync
StateBitfield global_state;
RulesBitfield rules_flag;
char my_version[33]; // Composed version string
char my_hostname[33]; // Composed Wifi hostname
char mqtt_client[33]; // Composed MQTT Clientname
char mqtt_topic[33]; // Composed MQTT topic
char serial_in_buffer[INPUT_BUFFER_SIZE]; // Receive buffer
char mqtt_data[MESSZ]; // MQTT publish buffer and web page ajax buffer
char log_data[LOGSZ]; // Logging
char web_log[WEB_LOG_SIZE] = {'\0'}; // Web log buffer
String backlog[MAX_BACKLOG]; // Command backlog
/********************************************************************************************/
char* Format(char* output, const char* input, int size)
{
char *token;
uint8_t digits = 0;
if (strstr(input, "%")) {
strlcpy(output, input, size);
token = strtok(output, "%");
if (strstr(input, "%") == input) {
output[0] = '\0';
} else {
token = strtok(NULL, "");
}
if (token != NULL) {
digits = atoi(token);
if (digits) {
if (strchr(token, 'd')) {
snprintf_P(output, size, PSTR("%s%c0%dd"), output, '%', digits);
snprintf_P(output, size, output, ESP.getChipId() & 0x1fff); // %04d - short chip ID in dec, like in hostname
} else {
snprintf_P(output, size, PSTR("%s%c0%dX"), output, '%', digits);
snprintf_P(output, size, output, ESP.getChipId()); // %06X - full chip ID in hex
}
} else {
if (strchr(token, 'd')) {
snprintf_P(output, size, PSTR("%s%d"), output, ESP.getChipId()); // %d - full chip ID in dec
digits = 8;
}
}
}
}
if (!digits) strlcpy(output, input, size);
return output;
}
char* GetOtaUrl(char *otaurl, size_t otaurl_size)
{
if (strstr(Settings.ota_url, "%04d") != NULL) { // OTA url contains placeholder for chip ID
snprintf(otaurl, otaurl_size, Settings.ota_url, ESP.getChipId() & 0x1fff);
}
else if (strstr(Settings.ota_url, "%d") != NULL) { // OTA url contains placeholder for chip ID
snprintf_P(otaurl, otaurl_size, Settings.ota_url, ESP.getChipId());
}
else {
snprintf(otaurl, otaurl_size, Settings.ota_url);
}
return otaurl;
}
void GetTopic_P(char *stopic, byte prefix, char *topic, const char* subtopic)
{
/* prefix 0 = Cmnd
prefix 1 = Stat
prefix 2 = Tele
*/
char romram[CMDSZ];
String fulltopic;
snprintf_P(romram, sizeof(romram), subtopic);
if (fallback_topic_flag) {
fulltopic = FPSTR(kPrefixes[prefix]);
fulltopic += F("/");
fulltopic += mqtt_client;
} else {
fulltopic = Settings.mqtt_fulltopic;
if ((0 == prefix) && (-1 == fulltopic.indexOf(F(MQTT_TOKEN_PREFIX)))) {
fulltopic += F("/" MQTT_TOKEN_PREFIX); // Need prefix for commands to handle mqtt topic loops
}
for (byte i = 0; i < 3; i++) {
if ('\0' == Settings.mqtt_prefix[i][0]) {
snprintf_P(Settings.mqtt_prefix[i], sizeof(Settings.mqtt_prefix[i]), kPrefixes[i]);
}
}
fulltopic.replace(F(MQTT_TOKEN_PREFIX), Settings.mqtt_prefix[prefix]);
fulltopic.replace(F(MQTT_TOKEN_TOPIC), topic);
String token_id = WiFi.macAddress();
token_id.replace(":", "");
fulltopic.replace(F(MQTT_TOKEN_ID), token_id);
}
fulltopic.replace(F("#"), "");
fulltopic.replace(F("//"), "/");
if (!fulltopic.endsWith("/")) fulltopic += "/";
snprintf_P(stopic, TOPSZ, PSTR("%s%s"), fulltopic.c_str(), romram);
}
char* GetStateText(byte state)
{
if (state > 3) state = 1;
return Settings.state_text[state];
}
/********************************************************************************************/
void SetLatchingRelay(power_t power, uint8_t state)
{
power &= 1;
if (2 == state) { // Reset relay
state = 0;
latching_power = power;
latching_relay_pulse = 0;
}
else if (state && !latching_relay_pulse) { // Set port power to On
latching_power = power;
latching_relay_pulse = 2; // max 200mS (initiated by stateloop())
}
if (pin[GPIO_REL1 +latching_power] < 99) {
digitalWrite(pin[GPIO_REL1 +latching_power], bitRead(rel_inverted, latching_power) ? !state : state);
}
}
void SetDevicePower(power_t rpower, int source)
{
uint8_t state;
ShowSource(source);
if (POWER_ALL_ALWAYS_ON == Settings.poweronstate) { // All on and stay on
power = (1 << devices_present) -1;
rpower = power;
}
if (Settings.flag.interlock) { // Allow only one or no relay set
power_t mask = 1;
uint8_t count = 0;
for (byte i = 0; i < devices_present; i++) {
if (rpower & mask) count++;
mask <<= 1;
}
if (count > 1) {
power = 0;
rpower = 0;
}
}
XdrvSetPower(rpower);
if ((SONOFF_DUAL == Settings.module) || (CH4 == Settings.module)) {
Serial.write(0xA0);
Serial.write(0x04);
Serial.write(rpower &0xFF);
Serial.write(0xA1);
Serial.write('\n');
Serial.flush();
}
else if (EXS_RELAY == Settings.module) {
SetLatchingRelay(rpower, 1);
}
else {
for (byte i = 0; i < devices_present; i++) {
state = rpower &1;
if ((i < MAX_RELAYS) && (pin[GPIO_REL1 +i] < 99)) {
digitalWrite(pin[GPIO_REL1 +i], bitRead(rel_inverted, i) ? !state : state);
}
rpower >>= 1;
}
}
}
void SetLedPower(uint8_t state)
{
if (state) state = 1;
digitalWrite(pin[GPIO_LED1], (bitRead(led_inverted, 0)) ? !state : state);
}
uint8_t GetFanspeed()
{
uint8_t fanspeed = 0;
// if (SONOFF_IFAN02 == Settings.module) {
/* Fanspeed is controlled by relay 2, 3 and 4 as in Sonoff 4CH.
000x = 0
001x = 1
011x = 2
101x = 3
*/
fanspeed = (uint8_t)(power &0xF) >> 1;
if (fanspeed) { fanspeed = (fanspeed >> 1) +1; }
// }
return fanspeed;
}
/********************************************************************************************/
void MqttDataHandler(char* topic, byte* data, unsigned int data_len)
{
char *str;
if (!strcmp(Settings.mqtt_prefix[0],Settings.mqtt_prefix[1])) {
str = strstr(topic,Settings.mqtt_prefix[0]);
if ((str == topic) && mqtt_cmnd_publish) {
if (mqtt_cmnd_publish > 8) {
mqtt_cmnd_publish -= 8;
} else {
mqtt_cmnd_publish = 0;
}
return;
}
}
char topicBuf[TOPSZ];
char dataBuf[data_len+1];
char command [CMDSZ];
char stemp1[TOPSZ];
char *p;
char *type = NULL;
byte jsflg = 0;
byte lines = 1;
uint8_t grpflg = 0;
// uint8_t user_append_index = 0;
uint16_t i = 0;
uint16_t index;
uint32_t address;
ShowFreeMem(PSTR("MqttDataHandler"));
strncpy(topicBuf, topic, sizeof(topicBuf));
for (i = 0; i < data_len; i++) {
if (!isspace(data[i])) break;
}
data_len -= i;
memcpy(dataBuf, data +i, sizeof(dataBuf));
dataBuf[sizeof(dataBuf)-1] = 0;
if (topicBuf[0] != '/') { ShowSource(SRC_MQTT); }
snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_RESULT D_RECEIVED_TOPIC " %s, " D_DATA_SIZE " %d, " D_DATA " %s"),
topicBuf, data_len, dataBuf);
AddLog(LOG_LEVEL_DEBUG_MORE);
// if (LOG_LEVEL_DEBUG_MORE <= seriallog_level) Serial.println(dataBuf);
if (XdrvMqttData(topicBuf, sizeof(topicBuf), dataBuf, sizeof(dataBuf))) return;
grpflg = (strstr(topicBuf, Settings.mqtt_grptopic) != NULL);
fallback_topic_flag = (strstr(topicBuf, mqtt_client) != NULL);
type = strrchr(topicBuf, '/') +1; // Last part of received topic is always the command (type)
index = 1;
if (type != NULL) {
for (i = 0; i < strlen(type); i++) {
type[i] = toupper(type[i]);
}
while (isdigit(type[i-1])) {
i--;
}
if (i < strlen(type)) {
index = atoi(type +i);
// user_append_index = 1;
}
type[i] = '\0';
}
snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_RESULT D_GROUP " %d, " D_INDEX " %d, " D_COMMAND " %s, " D_DATA " %s"),
grpflg, index, type, dataBuf);
AddLog(LOG_LEVEL_DEBUG);
if (type != NULL) {
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_JSON_COMMAND "\":\"" D_JSON_ERROR "\"}"));
if (Settings.ledstate &0x02) blinks++;
if (!strcmp(dataBuf,"?")) data_len = 0;
int16_t payload = -99; // No payload
uint16_t payload16 = 0;
long payload32 = strtol(dataBuf, &p, 10);
if (p != dataBuf) {
payload = (int16_t) payload32; // -32766 - 32767
payload16 = (uint16_t) payload32; // 0 - 65535
} else {
payload32 = 0;
}
backlog_delay = MIN_BACKLOG_DELAY; // Reset backlog delay
int temp_payload = GetStateNumber(dataBuf);
if (temp_payload > -1) { payload = temp_payload; }
// snprintf_P(log_data, sizeof(log_data), PSTR("RSLT: Payload %d, Payload16 %d"), payload, payload16);
// AddLog(LOG_LEVEL_DEBUG);
int command_code = GetCommandCode(command, sizeof(command), type, kTasmotaCommands);
if (-1 == command_code) {
if (!XdrvCommand(grpflg, type, index, dataBuf, data_len, payload, payload16)) {
type = NULL; // Unknown command
}
}
else if (CMND_BACKLOG == command_code) {
if (data_len) {
uint8_t bl_pointer = (!backlog_pointer) ? MAX_BACKLOG -1 : backlog_pointer;
bl_pointer--;
char *blcommand = strtok(dataBuf, ";");
while ((blcommand != NULL) && (backlog_index != bl_pointer)) {
while(true) {
blcommand = LTrim(blcommand);
if (!strncasecmp_P(blcommand, PSTR(D_CMND_BACKLOG), strlen(D_CMND_BACKLOG))) {
blcommand += strlen(D_CMND_BACKLOG); // Skip unnecessary command Backlog
} else {
break;
}
}
if (*blcommand != '\0') {
backlog[backlog_index] = String(blcommand);
backlog_index++;
if (backlog_index >= MAX_BACKLOG) backlog_index = 0;
}
blcommand = strtok(NULL, ";");
}
// snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, D_JSON_APPENDED);
mqtt_data[0] = '\0';
} else {
uint8_t blflag = (backlog_pointer == backlog_index);
backlog_pointer = backlog_index;
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, blflag ? D_JSON_EMPTY : D_JSON_ABORTED);
}
}
else if (CMND_DELAY == command_code) {
if ((payload >= MIN_BACKLOG_DELAY) && (payload <= 3600)) backlog_delay = payload;
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, backlog_delay);
}
else if ((CMND_POWER == command_code) && (index > 0) && (index <= devices_present)) {
if ((payload < 0) || (payload > 4)) payload = 9;
// Settings.flag.device_index_enable = user_append_index;
ExecuteCommandPower(index, payload, SRC_IGNORE);
fallback_topic_flag = 0;
return;
}
else if ((CMND_FANSPEED == command_code) && (SONOFF_IFAN02 == Settings.module)) {
if ((payload >= 0) && (payload <= 3) && (payload != GetFanspeed())) {
for (byte i = 0; i < 3; i++) {
uint8_t state = kIFan02Speed[payload][i];
// uint8_t state = pgm_read_byte(kIFan02Speed +(payload *3) +i);
ExecuteCommandPower(i +2, state, SRC_IGNORE); // Use relay 2, 3 and 4
}
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, GetFanspeed());
}
else if (CMND_STATUS == command_code) {
if ((payload < 0) || (payload > MAX_STATUS)) payload = 99;
PublishStatus(payload);
fallback_topic_flag = 0;
return;
}
else if (CMND_STATE == command_code) {
mqtt_data[0] = '\0';
MqttShowState();
}
else if (CMND_SLEEP == command_code) {
if ((payload >= 0) && (payload < 251)) {
if ((!Settings.sleep && payload) || (Settings.sleep && !payload)) restart_flag = 2;
Settings.sleep = payload;
sleep = payload;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE_UNIT_NVALUE_UNIT, command, sleep, (Settings.flag.value_units) ? " " D_UNIT_MILLISECOND : "", Settings.sleep, (Settings.flag.value_units) ? " " D_UNIT_MILLISECOND : "");
}
else if ((CMND_UPGRADE == command_code) || (CMND_UPLOAD == command_code)) {
// Check if the payload is numerically 1, and had no trailing chars.
// e.g. "1foo" or "1.2.3" could fool us.
// Check if the version we have been asked to upgrade to is higher than our current version.
// We also need at least 3 chars to make a valid version number string.
if (((1 == data_len) && (1 == payload)) || ((data_len >= 3) && NewerVersion(dataBuf))) {
ota_state_flag = 3;
// snprintf_P(mqtt_data, sizeof(mqtt_data), "{\"%s\":\"" D_JSON_VERSION " %s " D_JSON_FROM " %s\"}", command, my_version, Settings.ota_url);
snprintf_P(mqtt_data, sizeof(mqtt_data), "{\"%s\":\"" D_JSON_VERSION " %s " D_JSON_FROM " %s\"}", command, my_version, GetOtaUrl(stemp1, sizeof(stemp1)));
} else {
snprintf_P(mqtt_data, sizeof(mqtt_data), "{\"%s\":\"" D_JSON_ONE_OR_GT "\"}", command, my_version);
}
}
else if (CMND_OTAURL == command_code) {
if ((data_len > 0) && (data_len < sizeof(Settings.ota_url)))
strlcpy(Settings.ota_url, (1 == payload) ? OTA_URL : dataBuf, sizeof(Settings.ota_url));
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.ota_url);
}
else if (CMND_SERIALLOG == command_code) {
if ((payload >= LOG_LEVEL_NONE) && (payload <= LOG_LEVEL_ALL)) {
Settings.flag.mqtt_serial = 0;
SetSeriallog(payload);
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE_ACTIVE_NVALUE, command, Settings.seriallog_level, seriallog_level);
}
else if (CMND_RESTART == command_code) {
switch (payload) {
case 1:
restart_flag = 2;
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, D_JSON_RESTARTING);
break;
case 99:
AddLog_P(LOG_LEVEL_INFO, PSTR(D_LOG_APPLICATION D_RESTARTING));
EspRestart();
break;
default:
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, D_JSON_ONE_TO_RESTART);
}
}
else if ((CMND_POWERONSTATE == command_code) && (Settings.module != MOTOR)) {
/* 0 = Keep relays off after power on
* 1 = Turn relays on after power on, if PulseTime set wait for PulseTime seconds, and turn relays off
* 2 = Toggle relays after power on
* 3 = Set relays to last saved state after power on
* 4 = Turn relays on and disable any relay control (used for Sonoff Pow to always measure power)
* 5 = Keep relays off after power on, if PulseTime set wait for PulseTime seconds, and turn relays on
*/
if ((payload >= POWER_ALL_OFF) && (payload <= POWER_ALL_OFF_PULSETIME_ON)) {
Settings.poweronstate = payload;
if (POWER_ALL_ALWAYS_ON == Settings.poweronstate) {
for (byte i = 1; i <= devices_present; i++) {
ExecuteCommandPower(i, POWER_ON, SRC_IGNORE);
}
}
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.poweronstate);
}
else if ((CMND_PULSETIME == command_code) && (index > 0) && (index <= MAX_PULSETIMERS)) {
if (data_len > 0) {
Settings.pulse_timer[index -1] = payload16; // 0 - 65535
pulse_timer[index -1] = 0;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_NVALUE_ACTIVE_NVALUE, command, index, Settings.pulse_timer[index -1], pulse_timer[index -1]);
}
else if (CMND_BLINKTIME == command_code) {
if ((payload > 2) && (payload <= 3600)) {
Settings.blinktime = payload;
if (blink_timer) blink_timer = Settings.blinktime;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.blinktime);
}
else if (CMND_BLINKCOUNT == command_code) {
if (data_len > 0) {
Settings.blinkcount = payload16; // 0 - 65535
if (blink_counter) blink_counter = Settings.blinkcount *2;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.blinkcount);
}
else if (CMND_SAVEDATA == command_code) {
if ((payload >= 0) && (payload <= 3600)) {
Settings.save_data = payload;
save_data_counter = Settings.save_data;
}
SettingsSaveAll();
if (Settings.save_data > 1) {
snprintf_P(stemp1, sizeof(stemp1), PSTR(D_JSON_EVERY " %d " D_UNIT_SECOND), Settings.save_data);
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, (Settings.save_data > 1) ? stemp1 : GetStateText(Settings.save_data));
}
else if (CMND_SENSOR == command_code) {
XdrvMailbox.index = index;
XdrvMailbox.data_len = data_len;
XdrvMailbox.payload16 = payload16;
XdrvMailbox.payload = payload;
XdrvMailbox.grpflg = grpflg;
XdrvMailbox.topic = command;
XdrvMailbox.data = dataBuf;
XsnsCall(FUNC_COMMAND);
// if (!XsnsCall(FUNC_COMMAND)) type = NULL;
}
else if ((CMND_SETOPTION == command_code) && (index < 82)) {
byte ptype;
byte pindex;
if (index <= 31) { // SetOption0 .. 31 = Settings.flag
ptype = 0;
pindex = index; // 0 .. 31
}
else if (index <= 49) { // SetOption32 .. 49 = Settings.param
ptype = 2;
pindex = index -32; // 0 .. 17 (= PARAM8_SIZE -1)
}
else { // SetOption50 .. 81 = Settings.flag3
ptype = 1;
pindex = index -50; // 0 .. 31
}
if (payload >= 0) {
if (0 == ptype) { // SetOption0 .. 31
if (payload <= 1) {
switch (pindex) {
case 5: // mqtt_power_retain (CMND_POWERRETAIN)
case 6: // mqtt_button_retain (CMND_BUTTONRETAIN)
case 7: // mqtt_switch_retain (CMND_SWITCHRETAIN)
case 9: // mqtt_sensor_retain (CMND_SENSORRETAIN)
case 22: // mqtt_serial (SerialSend and SerialLog)
case 25: // knx_enabled (Web config)
case 27: // knx_enable_enhancement (Web config)
ptype = 99; // Command Error
break; // Ignore command SetOption
case 3: // mqtt
case 15: // pwm_control
restart_flag = 2;
default:
bitWrite(Settings.flag.data, pindex, payload);
}
if (12 == pindex) { // stop_flash_rotate
stop_flash_rotate = payload;
SettingsSave(2);
}
#ifdef USE_HOME_ASSISTANT
if ((19 == pindex) || (30 == pindex)) {
HAssDiscovery(1); // hass_discovery or hass_light
}
#endif // USE_HOME_ASSISTANT
}
}
else if (1 == ptype) { // SetOption50 .. 81
if (payload <= 1) {
bitWrite(Settings.flag3.data, pindex, payload);
}
}
else { // SetOption32 .. 49
/*
switch (pindex) {
case P_HOLD_TIME:
case P_MAX_POWER_RETRY:
if ((payload >= 1) && (payload <= 250)) {
Settings.param[pindex] = payload;
}
break;
default:
ptype = 99; // Command Error
}
*/
if ((payload >= 1) && (payload <= 250)) {
Settings.param[pindex] = payload;
}
}
}
if (ptype < 99) {
if (2 == ptype) snprintf_P(stemp1, sizeof(stemp1), PSTR("%d"), Settings.param[pindex]);
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, index, (2 == ptype) ? stemp1 : (1 == ptype) ? GetStateText(bitRead(Settings.flag3.data, pindex)) : GetStateText(bitRead(Settings.flag.data, pindex)));
}
}
else if (CMND_TEMPERATURE_RESOLUTION == command_code) {
if ((payload >= 0) && (payload <= 3)) {
Settings.flag2.temperature_resolution = payload;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.flag2.temperature_resolution);
}
else if (CMND_HUMIDITY_RESOLUTION == command_code) {
if ((payload >= 0) && (payload <= 3)) {
Settings.flag2.humidity_resolution = payload;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.flag2.humidity_resolution);
}
else if (CMND_PRESSURE_RESOLUTION == command_code) {
if ((payload >= 0) && (payload <= 3)) {
Settings.flag2.pressure_resolution = payload;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.flag2.pressure_resolution);
}
else if (CMND_POWER_RESOLUTION == command_code) {
if ((payload >= 0) && (payload <= 3)) {
Settings.flag2.wattage_resolution = payload;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.flag2.wattage_resolution);
}
else if (CMND_VOLTAGE_RESOLUTION == command_code) {
if ((payload >= 0) && (payload <= 3)) {
Settings.flag2.voltage_resolution = payload;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.flag2.voltage_resolution);
}
else if (CMND_CURRENT_RESOLUTION == command_code) {
if ((payload >= 0) && (payload <= 3)) {
Settings.flag2.current_resolution = payload;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.flag2.current_resolution);
}
else if (CMND_ENERGY_RESOLUTION == command_code) {
if ((payload >= 0) && (payload <= 5)) {
Settings.flag2.energy_resolution = payload;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.flag2.energy_resolution);
}
else if (CMND_MODULE == command_code) {
if ((payload > 0) && (payload <= MAXMODULE)) {
payload--;
Settings.last_module = Settings.module;
Settings.module = payload;
if (Settings.last_module != payload) {
for (byte i = 0; i < MAX_GPIO_PIN; i++) {
Settings.my_gp.io[i] = 0;
}
}
restart_flag = 2;
}
snprintf_P(stemp1, sizeof(stemp1), kModules[Settings.module].name);
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE_SVALUE, command, Settings.module +1, stemp1);
}
else if (CMND_MODULES == command_code) {
for (byte i = 0; i < MAXMODULE; i++) {
if (!jsflg) {
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_MODULES "%d\":["), lines);
} else {
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,"), mqtt_data);
}
jsflg = 1;
snprintf_P(stemp1, sizeof(stemp1), kModules[i].name);
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s\"%d (%s)\""), mqtt_data, i +1, stemp1);
if ((strlen(mqtt_data) > (LOGSZ - TOPSZ)) || (i == MAXMODULE -1)) {
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s]}"), mqtt_data);
MqttPublishPrefixTopic_P(RESULT_OR_STAT, type);
jsflg = 0;
lines++;
}
}
mqtt_data[0] = '\0';
}
else if ((CMND_GPIO == command_code) && (index < MAX_GPIO_PIN)) {
mytmplt cmodule;
memcpy_P(&cmodule, &kModules[Settings.module], sizeof(cmodule));
if ((GPIO_USER == cmodule.gp.io[index]) && (payload >= 0) && (payload < GPIO_SENSOR_END)) {
for (byte i = 0; i < MAX_GPIO_PIN; i++) {
if ((GPIO_USER == cmodule.gp.io[i]) && (Settings.my_gp.io[i] == payload)) {
Settings.my_gp.io[i] = 0;
}
}
Settings.my_gp.io[index] = payload;
restart_flag = 2;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{"));
byte jsflg = 0;
for (byte i = 0; i < MAX_GPIO_PIN; i++) {
if (GPIO_USER == cmodule.gp.io[i]) {
if (jsflg) snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,"), mqtt_data);
jsflg = 1;
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s\"" D_CMND_GPIO "%d\":\"%d (%s)\""),
mqtt_data, i, Settings.my_gp.io[i], GetTextIndexed(stemp1, sizeof(stemp1), Settings.my_gp.io[i], kSensorNames));
}
}
if (jsflg) {
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s}"), mqtt_data);
} else {
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, D_JSON_NOT_SUPPORTED);
}
}
else if (CMND_GPIOS == command_code) {
mytmplt cmodule;
memcpy_P(&cmodule, &kModules[Settings.module], sizeof(cmodule));
for (byte i = 0; i < GPIO_SENSOR_END; i++) {
if (!jsflg) {
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_GPIOS "%d\":["), lines);
} else {
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,"), mqtt_data);
}
jsflg = 1;
if (!GetUsedInModule(i, cmodule.gp.io)) {
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s\"%d (%s)\""), mqtt_data, i, GetTextIndexed(stemp1, sizeof(stemp1), i, kSensorNames));
if ((strlen(mqtt_data) > (LOGSZ - TOPSZ)) || (i == GPIO_SENSOR_END -1)) {
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s]}"), mqtt_data);
MqttPublishPrefixTopic_P(RESULT_OR_STAT, type);
jsflg = 0;
lines++;
}
}
}
mqtt_data[0] = '\0';
}
else if ((CMND_PWM == command_code) && pwm_present && (index > 0) && (index <= MAX_PWMS)) {
if ((payload >= 0) && (payload <= Settings.pwm_range) && (pin[GPIO_PWM1 + index -1] < 99)) {
Settings.pwm_value[index -1] = payload;
analogWrite(pin[GPIO_PWM1 + index -1], bitRead(pwm_inverted, index -1) ? Settings.pwm_range - payload : payload);
}
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{"));
MqttShowPWMState(); // Render the PWM status to MQTT
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s}"), mqtt_data);
}
else if (CMND_PWMFREQUENCY == command_code) {
if ((1 == payload) || ((payload >= 100) && (payload <= 4000))) {
Settings.pwm_frequency = (1 == payload) ? PWM_FREQ : payload;
analogWriteFreq(Settings.pwm_frequency); // Default is 1000 (core_esp8266_wiring_pwm.c)
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.pwm_frequency);
}
else if (CMND_PWMRANGE == command_code) {
if ((1 == payload) || ((payload > 254) && (payload < 1024))) {
Settings.pwm_range = (1 == payload) ? PWM_RANGE : payload;
for (byte i = 0; i < MAX_PWMS; i++) {
if (Settings.pwm_value[i] > Settings.pwm_range) {
Settings.pwm_value[i] = Settings.pwm_range;
}
}
analogWriteRange(Settings.pwm_range); // Default is 1023 (Arduino.h)
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.pwm_range);
}
else if ((CMND_COUNTER == command_code) && (index > 0) && (index <= MAX_COUNTERS)) {
if ((data_len > 0) && (pin[GPIO_CNTR1 + index -1] < 99)) {
if ((dataBuf[0] == '-') || (dataBuf[0] == '+')) {
RtcSettings.pulse_counter[index -1] += payload32;
Settings.pulse_counter[index -1] += payload32;
} else {
RtcSettings.pulse_counter[index -1] = payload32;
Settings.pulse_counter[index -1] = payload32;
}
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_LVALUE, command, index, RtcSettings.pulse_counter[index -1]);
}
else if ((CMND_COUNTERTYPE == command_code) && (index > 0) && (index <= MAX_COUNTERS)) {
if ((payload >= 0) && (payload <= 1) && (pin[GPIO_CNTR1 + index -1] < 99)) {
bitWrite(Settings.pulse_counter_type, index -1, payload &1);
RtcSettings.pulse_counter[index -1] = 0;
Settings.pulse_counter[index -1] = 0;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_NVALUE, command, index, bitRead(Settings.pulse_counter_type, index -1));
}
else if (CMND_COUNTERDEBOUNCE == command_code) {
if ((data_len > 0) && (payload16 < 32001)) {
Settings.pulse_counter_debounce = payload16;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.pulse_counter_debounce);
}
else if (CMND_BAUDRATE == command_code) {
if (payload32 > 0) {
payload32 /= 1200; // Make it a valid baudrate
baudrate = (1 == payload) ? APP_BAUDRATE : payload32 * 1200;
SetSerialBaudrate(baudrate);
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.baudrate * 1200);
}
else if ((CMND_SERIALSEND == command_code) && (index > 0) && (index <= 3)) {
SetSeriallog(LOG_LEVEL_NONE);
Settings.flag.mqtt_serial = 1;
if (data_len > 0) {
if (1 == index) {
Serial.printf("%s\n", dataBuf);
}
else if (2 == index) {
Serial.printf("%s", dataBuf);
}
else if (3 == index) {
uint16_t dat_len = data_len;
Serial.printf("%s", Unescape(dataBuf, &dat_len));
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, D_JSON_DONE);
}
}
else if (CMND_SERIALDELIMITER == command_code) {
if ((data_len > 0) && (payload < 256)) {
if (payload > 0) {
Settings.serial_delimiter = payload;
} else {
uint16_t dat_len = data_len;
Unescape(dataBuf, &dat_len);
Settings.serial_delimiter = dataBuf[0];
}
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.serial_delimiter);
}
else if (CMND_SYSLOG == command_code) {
if ((payload >= LOG_LEVEL_NONE) && (payload <= LOG_LEVEL_ALL)) {
Settings.syslog_level = payload;
syslog_level = (Settings.flag2.emulation) ? 0 : payload;
syslog_timer = 0;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE_ACTIVE_NVALUE, command, Settings.syslog_level, syslog_level);
}
else if (CMND_LOGHOST == command_code) {
if ((data_len > 0) && (data_len < sizeof(Settings.syslog_host))) {
strlcpy(Settings.syslog_host, (1 == payload) ? SYS_LOG_HOST : dataBuf, sizeof(Settings.syslog_host));
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.syslog_host);
}
else if (CMND_LOGPORT == command_code) {
if (payload16 > 0) Settings.syslog_port = (1 == payload16) ? SYS_LOG_PORT : payload16;
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.syslog_port);
}
else if ((CMND_IPADDRESS == command_code) && (index > 0) && (index <= 4)) {
if (ParseIp(&address, dataBuf)) {
Settings.ip_address[index -1] = address;
// restart_flag = 2;
}
snprintf_P(stemp1, sizeof(stemp1), PSTR(" (%s)"), WiFi.localIP().toString().c_str());
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE_SVALUE, command, index, IPAddress(Settings.ip_address[index -1]).toString().c_str(), (1 == index) ? stemp1:"");
}
else if ((CMND_NTPSERVER == command_code) && (index > 0) && (index <= 3)) {
if ((data_len > 0) && (data_len < sizeof(Settings.ntp_server[0]))) {
strlcpy(Settings.ntp_server[index -1], (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? (1==index)?NTP_SERVER1:(2==index)?NTP_SERVER2:NTP_SERVER3 : dataBuf, sizeof(Settings.ntp_server[0]));
for (i = 0; i < strlen(Settings.ntp_server[index -1]); i++) {
if (Settings.ntp_server[index -1][i] == ',') Settings.ntp_server[index -1][i] = '.';
}
restart_flag = 2;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, index, Settings.ntp_server[index -1]);
}
else if (CMND_AP == command_code) {
if ((payload >= 0) && (payload <= 2)) {
switch (payload) {
case 0: // Toggle
Settings.sta_active ^= 1;
break;
case 1: // AP1
case 2: // AP2
Settings.sta_active = payload -1;
}
restart_flag = 2;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE_SVALUE, command, Settings.sta_active +1, Settings.sta_ssid[Settings.sta_active]);
}
else if ((CMND_SSID == command_code) && (index > 0) && (index <= 2)) {
if ((data_len > 0) && (data_len < sizeof(Settings.sta_ssid[0]))) {
strlcpy(Settings.sta_ssid[index -1], (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? (1 == index) ? STA_SSID1 : STA_SSID2 : dataBuf, sizeof(Settings.sta_ssid[0]));
Settings.sta_active = index -1;
restart_flag = 2;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, index, Settings.sta_ssid[index -1]);
}