-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathrevk.c
5083 lines (4913 loc) · 175 KB
/
revk.c
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
// Main control code, working with WiFi, MQTT, and managing settings and OTA Copyright ©2019 Adrian Kennard Andrews & Arnold Ltd
static const char __attribute__((unused)) * TAG = "RevK";
//#define SETTING_DEBUG
//#define SETTING_CHANGED
#define ESP_IDF_431 // Older
// Note, low wifi buffers breaks mesh
#include "revk.h"
#include "settings_lib.h"
#ifdef CONFIG_ENABLE_WIFI_STATION
#undef CONFIG_REVK_APMODE // Bodge - clashes
#endif
#ifndef CONFIG_REVK_APMODE
#undef CONFIG_REVK_APDNS // Bodge
#endif
#ifdef CONFIG_REVK_MATTER
#undef CONFIG_MDNS_MAX_INTERFACES // Bodge - clashes
#endif
#ifndef CONFIG_IDF_TARGET_ESP8266
#include "esp_mac.h"
#include "aes/esp_aes.h"
#endif
#include "esp_http_client.h"
#include "esp_ota_ops.h"
#include "esp_tls.h"
#ifdef CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
#include "esp_crt_bundle.h"
#else
#include "lecert.h"
#endif
#include "esp_task_wdt.h"
#include "esp_sntp.h"
#include "esp_phy_init.h"
#include "esp_sleep.h"
#include <driver/gpio.h>
#ifdef CONFIG_REVK_MESH
#include <esp_mesh.h>
#include "freertos/semphr.h"
#endif
#ifdef CONFIG_MDNS_MAX_INTERFACES
#include "mdns.h"
#endif
#ifdef CONFIG_NIMBLE_ENABLED
#include "esp_bt.h"
#endif
#if defined(CONFIG_REVK_LUNAR) || defined(CONFIG_REVK_SOLAR)
#include <math.h>
#endif
#include "esp8266_rtc_io_compat.h"
#include "esp8266_ota_compat.h"
#include "esp8266_flash_compat.h"
#include "esp8266_gpio_compat.h"
#include "esp8266_wdt_compat.h"
const char revk_build_suffix[] = CONFIG_REVK_BUILD_SUFFIX;
// https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/protocols/esp_tls.html
//#ifndef CONFIG_ESP_TLS_USING_WOLFSSL
//#warning You may want to use WolfSSL: git submodule add --recursive https://github.com/espressif/esp-wolfssl.git components/esp-wolfssl
//#endif
//#ifndef CONFIG_HEAP_ABORT_WHEN_ALLOCATION_FAILS
//#warning CONFIG_HEAP_ABORT_WHEN_ALLOCATION_FAILS recommended
//#endif
//#ifndef CONFIG_MBEDTLS_DYNAMIC_BUFFER
//#warning CONFIG_MBEDTLS_DYNAMIC_BUFFER recommended
//#endif
#ifdef CONFIG_LWIP_IPV6
#ifndef CONFIG_LWIP_IPV6_AUTOCONFIG
#warning No CONFIG_LWIP_IPV6_AUTOCONFIG
#endif
#endif
#ifndef CONFIG_IDF_TARGET_ESP8266
#ifndef CONFIG_LWIP_TCPIP_CORE_LOCKING
#warning Suggest CONFIG_LWIP_TCPIP_CORE_LOCKING
#endif
#endif
#ifdef CONFIG_MBEDTLS_DYNAMIC_BUFFER
#warning CONFIG_MBEDTLS_DYNAMIC_BUFFER is buggy, sadly
#endif
#if CONFIG_FREERTOS_HZ != 1000
#warning CONFIG_FREERTOS_HZ recommend set to 1000
#endif
#ifndef CONFIG_ESP_TASK_WDT_PANIC
#warning CONFIG_ESP_TASK_WDT_PANIC recommended
#endif
#ifdef CONFIG_REVK_OLD_SETTINGS
#define settings \
s(otahost,CONFIG_REVK_OTAHOST); \
u8(otadays,CONFIG_REVK_OTADAYS); \
b(otaauto,true); \
u16(otastart,600); \
b(otabeta,false); \
bd(otacert,CONFIG_REVK_OTACERT); \
s(ntphost,CONFIG_REVK_NTPHOST); \
s(tz,CONFIG_REVK_TZ); \
u32(watchdogtime,CONFIG_REVK_WATCHDOG); \
s(appname,CONFIG_REVK_APPNAME); \
s(nodename,NULL); \
s(hostname,NULL); \
p(command); \
p(setting); \
p(state); \
p(event); \
p(info); \
p(error); \
b(prefixapp,CONFIG_REVK_PREFIXAPP); \
b(prefixhost,CONFIG_REVK_PREFIXHOST); \
led(blink,3,CONFIG_REVK_BLINK); \
bdp(clientkey,NULL); \
bd(clientcert,NULL); \
#define apconfigsettings \
u32(apport,CONFIG_REVK_APPORT); \
u32(aptime,CONFIG_REVK_APTIME); \
u32(apwait,CONFIG_REVK_APWAIT); \
io(apgpio,CONFIG_REVK_APGPIO); \
#define mqttsettings \
sa(mqtthost,CONFIG_REVK_MQTT_CLIENTS,CONFIG_REVK_MQTTHOST); \
sa(mqttuser,CONFIG_REVK_MQTT_CLIENTS,CONFIG_REVK_MQTTUSER); \
sap(mqttpass,CONFIG_REVK_MQTT_CLIENTS,CONFIG_REVK_MQTTPASS); \
u16a(mqttport,CONFIG_REVK_MQTT_CLIENTS,CONFIG_REVK_MQTTPORT); \
bad(mqttcert,CONFIG_REVK_MQTT_CLIENTS,CONFIG_REVK_MQTTCERT); \
#define wifisettings \
u16(wifireset,CONFIG_REVK_WIFIRESET); \
u16(wifiuptime,0); \
s(wifissid,CONFIG_REVK_WIFISSID); \
s(wifiip,CONFIG_REVK_WIFIIP); \
s(wifigw,CONFIG_REVK_WIFIGW); \
sa(wifidns,3,CONFIG_REVK_WIFIDNS); \
h(wifibssid,6,CONFIG_REVK_WIFIBSSID); \
u8(wifichan,CONFIG_REVK_WIFICHAN); \
sp(wifipass,CONFIG_REVK_WIFIPASS); \
b(wifips,CONFIG_REVK_WIFIPS); \
b(wifimaxps,CONFIG_REVK_WIFIMAXPS); \
#define apsettings \
s(apssid,CONFIG_REVK_APSSID); \
sp(appass,CONFIG_REVK_APPASS); \
u8(apmax,CONFIG_REVK_APMAX); \
s(apip,CONFIG_REVK_APIP); \
b(aplr,CONFIG_REVK_APLR); \
b(aphide,CONFIG_REVK_APHIDE); \
#define meshsettings \
u16(meshreset,CONFIG_REVK_MESHRESET); \
h(meshid,6,CONFIG_REVK_MESHID); \
hs(meshkey,16,NULL); \
u16(meshwidth,CONFIG_REVK_MESHWIDTH); \
u16(meshdepth,CONFIG_REVK_MESHDEPTH); \
u16(meshmax,CONFIG_REVK_MESHMAX); \
sp(meshpass,CONFIG_REVK_MESHPASS); \
b(meshlr,CONFIG_REVK_MESHLR); \
b(meshroot,false); \
#define s(n,d) char *n;
#define sp(n,d) char *n;
#define sa(n,a,d) char *n[a];
#define sap(n,a,d) char *n[a];
#define fh(n,a,s,d) char n[a][s];
#define u32(n,d) uint32_t n;
#define u16(n,d) uint16_t n;
#define u16a(n,a,d) uint16_t n[a];
#define i16(n) int16_t n;
#define u8a(n,a,d) uint8_t n[a];
#define u8(n,d) uint8_t n;
#define b(n,d) uint8_t n;
#define s8(n,d) int8_t n;
#define io(n,d) revk_gpio_t n;
#define ioa(n,a,d) revk_gpio_t n[a];
#ifndef CONFIG_REVK_BLINK
#define led(n,a,d) extern revk_gpio_t n[a];
#else
#define led(n,a,d) revk_gpio_t n[a];
#endif
#define p(n) char *topic##n;
#define h(n,l,d) char n[l];
#define hs(n,l,d) uint8_t n[l];
#define bd(n,d) revk_bindata_t *n;
#define bad(n,a,d) revk_bindata_t *n[a];
#define bdp(n,d) revk_bindata_t *n;
settings
#if defined(CONFIG_REVK_WIFI) || defined(CONFIG_REVK_MESH)
wifisettings
#ifdef CONFIG_REVK_MESH
meshsettings
#else
apsettings
#endif
#endif
#ifdef CONFIG_REVK_MQTT
mqttsettings
#endif
#ifdef CONFIG_REVK_APMODE
apconfigsettings
#endif
#undef s
#undef sp
#undef sa
#undef sap
#undef fh
#undef u32
#undef u16
#undef u16a
#undef i16
#undef u8
#undef b
#undef u8a
#undef s8
#undef io
#undef ioa
#undef led
#undef p
#undef h
#undef hs
#undef bd
#undef bad
#undef bdp
#endif
/* Public */
const char *revk_version = ""; /* Git version */
const char *revk_app = ""; /* App name */
char revk_id[13] = ""; /* Chip ID as hex (from MAC) */
uint64_t revk_binid = 0; /* Binary chip ID */
mac_t revk_mac; // MAC
static int8_t ota_percent = -1;
static int
ota_in_progress (void)
{
return ota_percent > 0 && ota_percent <= 100;
}
#ifdef CONFIG_REVK_LED_STRIP
led_strip_handle_t revk_strip = NULL;
#endif
/* Local */
static struct
{ // Flags
uint8_t setting_dump_requested:2;
uint8_t wdt_test:1;
uint8_t disablewifi:1;
uint8_t disableap:1;
uint8_t disablesettings:1;
#ifdef CONFIG_REVK_MESH
uint8_t mesh_root_known:1;
#endif
} volatile b = { 0 };
static uint32_t up_next; // next up report (uptime)
static EventGroupHandle_t revk_group;
const static int GROUP_OFFLINE = BIT0; // We are off line (IP not set)
#if defined(CONFIG_REVK_WIFI) || defined(CONFIG_REVK_MESH)
const static int GROUP_WIFI = BIT1; // We are WiFi connected
const static int GROUP_IP = BIT2; // We have IP address
#endif
#ifdef CONFIG_REVK_MQTT
const static int GROUP_MQTT = BIT6 /*7... */ ; // We are MQTT connected - and MORE BITS (CONFIG_REVK_MQTT_CLIENTS)
const static int GROUP_MQTT_DOWN = (GROUP_MQTT << CONFIG_REVK_MQTT_CLIENTS); /*... */
#endif
static TaskHandle_t ota_task_id = NULL;
static app_callback_t *app_callback = NULL;
lwmqtt_t mqtt_client[CONFIG_REVK_MQTT_CLIENTS] = { };
static uint32_t restart_time = 0;
uint32_t revk_nvs_time = 0;
static char *restart_reason = NULL;
#ifdef CONFIG_REVK_OLD_SETTINGS
nvs_handle revk_nvs = -1;
#endif
#if defined(CONFIG_REVK_WIFI) || defined(CONFIG_REVK_MESH)
static uint32_t link_down = 1; // When link last down
esp_netif_t *sta_netif = NULL;
esp_netif_t *ap_netif = NULL;
#endif
static uint8_t blink_on = 0,
blink_off = 0;
static const char *blink_colours = NULL;
#ifdef CONFIG_REVK_MESH
// OTA to mesh devices
static volatile uint8_t mesh_ota_ack = 0;
static SemaphoreHandle_t mesh_ota_sem = NULL;
static mesh_addr_t mesh_ota_addr = { };
#endif
/* Local functions */
static char *revk_upgrade_url (const char *val, const char *ext);
static int revk_upgrade_check (const char *url);
#if defined(CONFIG_REVK_APCONFIG) || defined(CONFIG_REVK_WEB_DEFAULT)
static httpd_handle_t webserver = NULL;
void revk_web_dummy (httpd_handle_t * webp, uint16_t port);
#endif
#ifdef CONFIG_REVK_APMODE
static volatile uint8_t dummy_dns_task_end = 0;
static uint32_t apstoptime = 0; // When to stop AP mode (uptime)
static void ap_start (void); // Start AP mode, allowed if already running
static void ap_stop (void); // Stop AP mode, allowed if if not running
#endif
static void ip_event_handler (void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data);
static void mqtt_rx (void *arg, char *topic, unsigned short plen, unsigned char *payload);
static const char *revk_upgrade (const char *target, jo_t j);
#ifdef CONFIG_REVK_MESH
static void mesh_init (void);
void mesh_make_mqtt (mesh_data_t * data, uint8_t tag, int tlen, const char *topic, int plen, const unsigned char *payload);
static SemaphoreHandle_t mesh_mutex = NULL;
#endif
void *
mallocspi (size_t size)
{
void *mem = NULL;
#if defined(CONFIG_ESP32_SPIRAM_SUPPORT) || defined(CONFIG_ESP32S3_SPIRAM_SUPPORT)
mem = heap_caps_malloc (size, MALLOC_CAP_SPIRAM);
if (!mem)
#endif
mem = malloc (size);
return mem;
}
uint32_t
uptime (void)
{
return esp_timer_get_time () / 1000000LL ? : 1;
}
#if defined(CONFIG_REVK_WIFI) || defined(CONFIG_REVK_MESH)
static void
makeip (esp_netif_ip_info_t * info, const char *ip, const char *gw)
{
char *i = strdup (ip);
int cidr = 24;
char *n = strrchr (i, '/');
if (n)
{
*n++ = 0;
cidr = atoi (n);
}
esp_netif_set_ip4_addr (&info->netmask, (0xFFFFFFFF << (32 - cidr)) >> 24, (0xFFFFFFFF << (32 - cidr)) >> 16,
(0xFFFFFFFF << (32 - cidr)) >> 8, (0xFFFFFFFF << (32 - cidr)));
REVK_ERR_CHECK (esp_netif_str_to_ip4 (i, &info->ip));
if (!gw || !*gw)
info->gw = info->ip;
else
REVK_ERR_CHECK (esp_netif_str_to_ip4 (gw, &info->gw));
freez (i);
}
#endif
#ifdef CONFIG_REVK_MESH
esp_err_t
mesh_safe_send (const mesh_addr_t * to, const mesh_data_t * data, int flag, const mesh_opt_t opt[], int opt_count)
{ // Mutex to protect non-re-entrant call
if (!esp_mesh_is_device_active ())
return ESP_ERR_MESH_DISCONNECTED;
if (!to && !esp_mesh_is_root () && !b.mesh_root_known)
return ESP_ERR_MESH_DISCONNECTED; // We are not root and root address not known
xSemaphoreTake (mesh_mutex, portMAX_DELAY);
esp_err_t e = esp_mesh_send (to, data, flag, opt, opt_count);
xSemaphoreGive (mesh_mutex);
static uint8_t fails = 0;
if (e)
{
if (e != ESP_ERR_MESH_DISCONNECTED)
ESP_LOGI (TAG, "Mesh send failed:%s (%d)", esp_err_to_name (e), data->size);
if (e == ESP_ERR_MESH_NO_MEMORY)
{
if (++fails > 100)
revk_restart (1, "ESP_ERR_MESH_NO_MEMORY"); // Messy, catch memory leak
}
} else
fails = 0;
return e;
}
#endif
#ifdef CONFIG_REVK_MESH
// TODO esp_mesh_set_ie_crypto_funcs may be better way to do this in future - but need to de-dup if mesh system not fixed!
esp_err_t
mesh_encode_send (mesh_addr_t * addr, mesh_data_t * data, int flags)
{ // Security - encode mesh message and send - **** THIS EXPECTS MESH_PAD AVAILABLE EXTRA BYTES ON SIZE ****
// Note, at this point this does not protect against replay - critical messages should check timestamps to mitigate against replay
// Add padding
uint8_t pad = 15 - (data->size & 15); // Padding
data->size += pad;
// Add padding len
data->data[data->size++] = pad; // Last byte in 16 byte block is how much padding
// Encrypt
uint8_t iv[16]; // Changes by the encrypt
esp_fill_random (iv, 16); // IV
memcpy (data->data + data->size, iv, 16);
esp_aes_context ctx;
esp_aes_init (&ctx);
esp_aes_setkey (&ctx, meshkey, 128);
esp_aes_crypt_cbc (&ctx, ESP_AES_ENCRYPT, data->size, iv, data->data, data->data);
esp_aes_free (&ctx);
// Add IV
data->size += 16;
return mesh_safe_send (addr, data, flags, NULL, 0);
}
#endif
#ifdef CONFIG_REVK_MESH
esp_err_t
mesh_decode (mesh_addr_t * addr, mesh_data_t * data)
{ // Security - decode mesh message
addr = addr; // Not used
if (data->size < 32 || (data->size & 15))
{
ESP_LOGE (TAG, "Bad mesh rx len %d", data->size);
return -1;
}
// Remove IV
data->size -= 16;
uint8_t *iv = data->data + data->size;
static uint8_t lastiv[16] = { };
if (!memcmp (lastiv, iv, 16))
{ // Check for duplicate
ESP_LOGI (TAG, "Duplicate mesh rx %d: %02X %02X %02X %02X...", data->size, iv[0], iv[1], iv[2], iv[3]);
return -2; // De-dup
}
memcpy (lastiv, iv, 16);
// Decrypt
esp_aes_context ctx;
esp_aes_init (&ctx);
esp_aes_setkey (&ctx, meshkey, 128);
esp_aes_crypt_cbc (&ctx, ESP_AES_DECRYPT, data->size, iv, data->data, data->data);
esp_aes_free (&ctx);
// Remove padding len
data->size--;
if (data->data[data->size] > 15)
{
ESP_LOGE (TAG, "Bad mesh rx pad %d", data->data[data->size]);
return -3;
}
// Remove padding
data->size -= data->data[data->size];
data->data[data->size] = 0; // Original expected a null
return 0;
}
#endif
#ifdef CONFIG_REVK_MESH
static void
mesh_task (void *pvParameters)
{ // Mesh root
pvParameters = pvParameters;
mesh_data_t data = { };
data.data = mallocspi (MESH_MPS + 1); // One extra for a null
while (1)
{ // Mesh receive loop
mesh_addr_t from = { };
data.size = MESH_MPS;
int flag = 0;
esp_err_t e = esp_mesh_recv (&from, &data, 1000, &flag, NULL, 0);
if (e)
{
if (e == ESP_ERR_MESH_NOT_START)
sleep (1);
else if (e != ESP_ERR_MESH_TIMEOUT)
{
ESP_LOGI (TAG, "Rx %s", esp_err_to_name (e));
usleep (100000);
}
continue;
}
b.mesh_root_known = 1; // We are root or we got from root, so let's mark known
data.data[data.size] = 0; // Add a null so we can parse JSON with NULL and log and so on
char mac[13];
sprintf (mac, "%02X%02X%02X%02X%02X%02X", from.addr[0], from.addr[1], from.addr[2], from.addr[3], from.addr[4], from.addr[5]);
// We use MESH_PROTO_BIN for flash (unencrypted)
// We use MESH_PROTO_MQTT to relay
// We use MESH_PROTO_JSON for messages internally
if (data.proto == MESH_PROTO_BIN)
{ // Includes loopback to self
static uint8_t ota_ack = 0; // The ACK we send
static int ota_size = 0; // Total size
static int ota_data = 0; // Data received
static esp_ota_handle_t ota_handle;
static const esp_partition_t *ota_partition = NULL;
static int ota_progress = 0;
static uint32_t next = 0;
uint32_t now = uptime ();
uint8_t type = *data.data;
void send_ack (void)
{ // ACK (to root)
if (ota_ack)
{
mesh_data_t data = {.data = &ota_ack,.size = 1,.proto = MESH_PROTO_BIN };
REVK_ERR_CHECK (mesh_safe_send (&from, &data, MESH_DATA_P2P, NULL, 0));
}
}
switch (type >> 4)
{
case 0x5: // Start - not checking sequence, expecting to be 0
if (data.size == 4)
{
ota_ack = 0xA0 + (*data.data & 0xF);
send_ack ();
if (!ota_size)
{
ota_size = (data.data[1] << 16) + (data.data[2] << 8) + data.data[3];
ota_partition = esp_ota_get_next_update_partition (esp_ota_get_running_partition ());
ESP_LOGI (TAG, "Start flash %d", ota_size);
jo_t j = jo_make (NULL);
jo_int (j, "size", ota_size);
revk_info_clients ("upgrade", &j, -1);
if (REVK_ERR_CHECK (esp_ota_begin (ota_partition, ota_size, &ota_handle)))
{
ota_size = 0; // Failed
ESP_LOGI (TAG, "Failed to start flash");
}
}
ota_progress = 0;
ota_data = 0;
next = now + 5;
}
break;
case 0xD: // Data
if (ota_size && (*data.data & 0xF) == ((ota_ack + 1) & 0xF))
{ // Expected data
ota_ack = 0xA0 + (*data.data & 0xF);
if (REVK_ERR_CHECK (esp_ota_write_with_offset (ota_handle, data.data + 1, data.size - 1, ota_data)))
{
ota_size = 0;
ESP_LOGE (TAG, "Flash failed at %d", ota_data);
}
ota_data += data.size - 1;
ota_percent = ota_data * 100 / ota_size;
if (ota_percent != ota_progress && (ota_percent == 100 || next < now || ota_percent / 10 != ota_progress / 10))
{
ESP_LOGI (TAG, "Flash %d%%", ota_percent);
jo_t j = jo_make (NULL);
jo_int (j, "size", ota_size);
jo_int (j, "loaded", ota_data);
jo_int (j, "progress", ota_progress = ota_percent);
revk_info_clients ("upgrade", &j, -1);
next = now + 5;
}
} // else ESP_LOGI(TAG, "Unexpected %02X not %02X+1", *data.data, ota_ack);
send_ack ();
break;
case 0xE: // End - not checking sequence
if (ota_size)
{
if (ota_data != ota_size)
ESP_LOGE (TAG, "Flash missing data %d/%d", ota_data, ota_size);
else if (ota_partition && !REVK_ERR_CHECK (esp_ota_end (ota_handle)))
{
jo_t j = jo_make (NULL);
jo_int (j, "size", ota_size);
jo_string (j, "complete", ota_partition->label);
revk_info_clients ("upgrade", &j, -1); // Send from target device so cloud knows target is upgraded
esp_ota_set_boot_partition (ota_partition);
revk_restart (3, "OTA");
}
ota_partition = NULL;
ota_size = 0;
ota_ack = 0xA0 + (*data.data & 0xF);
}
send_ack ();
break;
case 0xA: // Ack
if (esp_mesh_is_root () && !memcmp (&mesh_ota_addr, &from, sizeof (mesh_ota_addr)) && mesh_ota_ack
&& mesh_ota_ack == *data.data)
{
mesh_ota_ack = 0;
xSemaphoreGive (mesh_ota_sem);
} // else ESP_LOGI(TAG, "Extra ack %02X", *data.data);
break;
}
} else if (data.proto == MESH_PROTO_MQTT)
{
if (mesh_decode (&from, &data))
continue;
char *e = (char *) data.data + data.size;
char *topic = (char *) data.data;
uint8_t tag = *topic++;
char *payload = topic;
while (payload < e && *payload)
payload++;
if (payload == e)
continue; // We expect topic ending in NULL
payload++; // Clear the null
if (esp_mesh_is_root ())
{ // To root: tag is client bit map of which external MQTT server to send to
if (memcmp (from.addr, revk_mac, 6))
{ // From us is exception, we would have sent direct
for (int client = 0; client < CONFIG_REVK_MQTT_CLIENTS; client++)
if (tag & (1 << client))
lwmqtt_send_full (mqtt_client[client], -1, topic, e - payload, (void *) payload, tag >> 7); // Out
}
} else
{ // To leaf: tag is client ID
ESP_LOGD (TAG, "Mesh Rx MQTT%02X %s: %s %.*s", tag, mac, topic, (int) (e - payload), payload);
mqtt_rx ((void *) (int) tag, topic, e - payload, (void *) payload); // In
}
} else if (data.proto == MESH_PROTO_JSON)
{ // Internal message
if (mesh_decode (&from, &data))
continue;
ESP_LOGD (TAG, "Mesh Rx JSON %s: %.*s", mac, data.size, (char *) data.data);
jo_t j = jo_parse_mem (data.data, data.size + 1); // Include the null
if (app_callback)
app_callback (0, "mesh", mac, NULL, j);
jo_free (&j);
}
}
vTaskDelete (NULL);
}
#endif
#if defined(CONFIG_REVK_WIFI) || defined(CONFIG_REVK_MESH)
static void
dhcpc_stop (void)
{
if (!sta_netif)
return;
esp_netif_ip_info_t ip_info;
if (!esp_netif_get_old_ip_info (sta_netif, &ip_info))
esp_netif_dhcpc_stop (sta_netif); // Crashes is no old IP, work around
}
#endif
#if defined(CONFIG_REVK_WIFI) || defined(CONFIG_REVK_MESH)
static void
setup_ip (void)
{ // Set up DHCPC / fixed IP
if (!sta_netif)
return;
void dns (const char *ip, esp_netif_dns_type_t type)
{
if (!ip || !*ip)
return;
char *i = strdup (ip);
char *c = strrchr (i, '/');
if (c)
*c = 0;
esp_netif_dns_info_t dns = { 0 };
if (!esp_netif_str_to_ip4 (i, &dns.ip.u_addr.ip4))
dns.ip.type = ESP_IPADDR_TYPE_V4;
#ifdef CONFIG_LWIP_IPV6
else if (!esp_netif_str_to_ip6 (i, &dns.ip.u_addr.ip6))
dns.ip.type = ESP_IPADDR_TYPE_V6;
#endif
else
{
ESP_LOGE (TAG, "Bad DNS IP %s", i);
return;
}
if (esp_netif_set_dns_info (sta_netif, type, &dns))
ESP_LOGE (TAG, "Bad DNS %s", i);
else
ESP_LOGI (TAG, "Set DNS IP %s", i);
freez (i);
}
if (*wifiip)
{
dhcpc_stop ();
esp_netif_ip_info_t info = { 0, };
makeip (&info, wifiip, wifigw);
REVK_ERR_CHECK (esp_netif_set_ip_info (sta_netif, &info));
ESP_LOGI (TAG, "Fixed IP %s GW %s", wifiip, wifigw);
if (!*wifidns[0])
dns (wifiip, ESP_NETIF_DNS_MAIN); /* Fallback to using gateway for DNS */
link_down = 0; // Static so not GOT_IP
} else
{
if (!link_down)
link_down = uptime (); // Just in case we think we have a link, we don't yet - need GOT_IP
ESP_LOGI (TAG, "Dynamic IP start");
esp_netif_dhcpc_start (sta_netif); /* Dynamic IP */
}
dns (wifidns[0], ESP_NETIF_DNS_MAIN);
dns (wifidns[1], ESP_NETIF_DNS_BACKUP);
dns (wifidns[2], ESP_NETIF_DNS_FALLBACK);
#ifdef CONFIG_REVK_MQTT
if (*wifiip)
revk_mqtt_init (); // Won't start on GOT_IP so start here
#endif
}
#endif
#ifdef CONFIG_REVK_MESH
static void
stop_ip (const char *why)
{
revk_mqtt_close (why);
dhcpc_stop ();
}
#endif
#if defined(CONFIG_REVK_WIFI) || defined(CONFIG_REVK_MESH)
static void
sta_init (void)
{
#ifndef CONFIG_ENABLE_WIFI_STATION // Matter is handling
REVK_ERR_CHECK (esp_event_loop_create_default ());
sta_netif = esp_netif_create_default_wifi_sta ();
#ifndef CONFIG_ENABLE_WIFI_AP // Matter is handling
ap_netif = esp_netif_create_default_wifi_ap ();
#endif
#endif
if (sta_netif)
{
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT ();
REVK_ERR_CHECK (esp_wifi_init (&cfg));
REVK_ERR_CHECK (esp_wifi_set_storage (WIFI_STORAGE_FLASH));
#ifdef CONFIG_NIMBLE_ENABLED
REVK_ERR_CHECK (esp_wifi_set_ps (wifips ? wifimaxps ? WIFI_PS_MAX_MODEM : WIFI_PS_MIN_MODEM : WIFI_PS_MIN_MODEM));
#else
REVK_ERR_CHECK (esp_wifi_set_ps (wifips ? wifimaxps ? WIFI_PS_MAX_MODEM : WIFI_PS_MIN_MODEM : WIFI_PS_NONE));
#endif
}
REVK_ERR_CHECK (esp_event_handler_register (IP_EVENT, ESP_EVENT_ANY_ID, &ip_event_handler, NULL));
REVK_ERR_CHECK (esp_event_handler_register (WIFI_EVENT, ESP_EVENT_ANY_ID, &ip_event_handler, NULL));
}
#endif
#ifdef CONFIG_REVK_WIFI
static void
wifi_sta_config (void)
{
const char *ssid = wifissid;
ESP_LOGI (TAG, "WiFi STA [%s]", ssid);
wifi_config_t cfg = { 0, };
if (wifibssid[0] || wifibssid[1] || wifibssid[2])
{
memcpy (cfg.sta.bssid, wifibssid, sizeof (cfg.sta.bssid));
cfg.sta.bssid_set = 1;
}
cfg.sta.channel = wifichan;
cfg.sta.scan_method = WIFI_ALL_CHANNEL_SCAN;
strncpy ((char *) cfg.sta.ssid, ssid, sizeof (cfg.sta.ssid));
strncpy ((char *) cfg.sta.password, wifipass, sizeof (cfg.sta.password));
#ifndef CONFIG_IDF_TARGET_ESP8266
REVK_ERR_CHECK (esp_wifi_set_protocol
(ESP_IF_WIFI_STA, WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G | WIFI_PROTOCOL_11N | WIFI_PROTOCOL_LR));
#endif
REVK_ERR_CHECK (esp_wifi_set_config (ESP_IF_WIFI_STA, &cfg));
}
#endif
#ifdef CONFIG_REVK_WIFI
static void
wifi_init (void)
{
if (!sta_netif)
sta_init ();
else
REVK_ERR_CHECK (esp_wifi_stop ());
if (!sta_netif)
return;
// Mode
esp_wifi_set_mode (!b.disableap && *apssid ? WIFI_MODE_APSTA : WIFI_MODE_STA);
// Client
wifi_sta_config ();
// Doing AP mode after STA mode - seems to fail is not
if (!b.disableap && *apssid && ap_netif)
{ // AP config
wifi_config_t cfg = { 0, };
cfg.ap.channel = wifichan;
int l;
if ((l = strlen (apssid)) > sizeof (cfg.ap.ssid))
l = sizeof (cfg.ap.ssid);
cfg.ap.ssid_len = l;
memcpy (cfg.ap.ssid, apssid, cfg.ap.ssid_len = l);
if (*appass)
{
if ((l = strlen (appass)) > sizeof (cfg.ap.password))
l = sizeof (cfg.ap.password);
memcpy (&cfg.ap.password, appass, l);
cfg.ap.authmode = WIFI_AUTH_WPA_WPA2_PSK;
}
cfg.ap.ssid_hidden = aphide;
cfg.ap.max_connection = apmax;
esp_netif_ip_info_t info = { 0, };
makeip (&info, *apip ? apip : "10.0.0.1/24", NULL);
REVK_ERR_CHECK (esp_wifi_set_protocol
(ESP_IF_WIFI_AP, aplr ? WIFI_PROTOCOL_LR : (WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G | WIFI_PROTOCOL_11N)));
REVK_ERR_CHECK (esp_netif_dhcps_stop (ap_netif));
REVK_ERR_CHECK (esp_netif_set_ip_info (ap_netif, &info));
REVK_ERR_CHECK (esp_netif_dhcps_start (ap_netif));
REVK_ERR_CHECK (esp_wifi_set_config (ESP_IF_WIFI_AP, &cfg));
ESP_LOGI (TAG, "WIFiAP [%s]%s%s", apssid, aphide ? " (hidden)" : "", aplr ? " (LR)" : "");
}
setup_ip ();
REVK_ERR_CHECK (esp_wifi_start ());
}
#endif
#ifdef CONFIG_REVK_MESH
static void
mesh_init (void)
{
// https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_mesh.html
if (!sta_netif)
{
dhcpc_stop ();
esp_wifi_disconnect (); // Just in case
esp_wifi_stop ();
sta_init ();
REVK_ERR_CHECK (esp_netif_dhcps_stop (ap_netif));
REVK_ERR_CHECK (esp_wifi_set_mode (WIFI_MODE_APSTA));
REVK_ERR_CHECK (esp_wifi_set_protocol
(ESP_IF_WIFI_AP, meshlr ? WIFI_PROTOCOL_LR : (WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G | WIFI_PROTOCOL_11N)));
REVK_ERR_CHECK (esp_wifi_set_protocol
(ESP_IF_WIFI_STA,
WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G | WIFI_PROTOCOL_11N | (meshlr ? WIFI_PROTOCOL_LR : 0)));
REVK_ERR_CHECK (esp_mesh_set_max_layer (meshdepth));
REVK_ERR_CHECK (esp_mesh_set_xon_qsize (16));
esp_wifi_set_mode (WIFI_MODE_NULL); // Set by mesh
REVK_ERR_CHECK (esp_wifi_start ());
REVK_ERR_CHECK (esp_mesh_init ());
REVK_ERR_CHECK (esp_mesh_disable_ps ());
REVK_ERR_CHECK (esp_mesh_allow_root_conflicts (0));
REVK_ERR_CHECK (esp_mesh_send_block_time (1000)); // Note sure if needed or what but a second it a long time - send calls should check return code
REVK_ERR_CHECK (esp_event_handler_register (MESH_EVENT, ESP_EVENT_ANY_ID, &ip_event_handler, NULL));
mesh_cfg_t cfg = MESH_INIT_CONFIG_DEFAULT ();
memcpy ((uint8_t *) & cfg.mesh_id, meshid, 6);
if (wifibssid[0] || wifibssid[1] || wifibssid[2])
{
memcpy (cfg.router.bssid, wifibssid, sizeof (cfg.router.bssid));
cfg.router.allow_router_switch = 1; // Fallback if not found
}
cfg.channel = wifichan;
cfg.allow_channel_switch = 1; // Fallback
int l;
if ((l = strlen (wifissid)) > sizeof (cfg.router.ssid))
l = sizeof (cfg.router.ssid);
cfg.router.ssid_len = l;
memcpy (cfg.router.ssid, wifissid, cfg.router.ssid_len = l);
if (*wifipass)
{
if ((l = strlen (wifipass)) > sizeof (cfg.router.password))
l = sizeof (cfg.router.password);
memcpy (&cfg.router.password, wifipass, l);
}
cfg.mesh_ap.max_connection = meshwidth;
if (meshmax && meshmax < meshwidth)
cfg.mesh_ap.max_connection = meshmax;
if (*meshpass)
{
if ((l = strlen (meshpass)) > sizeof (cfg.mesh_ap.password))
l = sizeof (cfg.mesh_ap.password);
memcpy (&cfg.mesh_ap.password, meshpass, l);
}
REVK_ERR_CHECK (esp_mesh_set_config (&cfg));
if (meshmax)
REVK_ERR_CHECK (esp_mesh_set_capacity_num (meshmax + 10)); // Adding a few is to try and make mesh set up more stable when switching modes, etc, experimental
REVK_ERR_CHECK (esp_mesh_disable_ps ());
if (meshmax == 1 || meshroot)
esp_mesh_set_type (MESH_ROOT); // We are forcing root
revk_task ("mesh", mesh_task, NULL, 5);
}
REVK_ERR_CHECK (esp_mesh_start ());
}
#endif
#ifdef CONFIG_REVK_MQTT
char *
revk_topic (const char *name, const char *id, const char *suffix)
{ // Construct a topic, malloc'd and return pointer to it
if (!id)
id = hostname;
if (!*id)
id = NULL;
const char *t[4] = { 0 };
uint8_t tn = 0; // count
if (prefixhost)
{
if (prefixapp)
t[tn++] = appname;
if (id)
t[tn++] = id;
if (name && (!prefixapp || name != appname))
t[tn++] = name;
} else
{
if (name)
t[tn++] = name;
if (prefixapp && name != appname)
t[tn++] = appname;
if (id)
t[tn++] = id;
}
if (suffix)
t[tn++] = suffix;
char *topic = NULL;
if (t[3])
asprintf (&topic, "%s/%s/%s/%s", t[0], t[1], t[2], t[3]);
else if (t[2])
asprintf (&topic, "%s/%s/%s", t[0], t[1], t[2]);
else if (t[1])
asprintf (&topic, "%s/%s", t[0], t[1]);
else
asprintf (&topic, "%s", t[0]);
return topic;
}
#endif
#ifdef CONFIG_REVK_MQTT
void
revk_send_subunsub (int client, const mac_t mac, uint8_t sub)
{
char id[13];
sprintf (id, "%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
if (client >= CONFIG_REVK_MQTT_CLIENTS || !lwmqtt_connected (mqtt_client[client]))
return;
ESP_LOGI (TAG, "MQTT%d %s %s", client, sub ? "Subscribe" : "Unsubscribe", id);
void subunsub (const char *prefix)
{
void send (const char *id)
{
char *topic = revk_topic (prefix, id, "#");
if (!topic)
return;
if (sub)
lwmqtt_subscribe (mqtt_client[client], topic);
else
lwmqtt_unsubscribe (mqtt_client[client], topic);
freez (topic);
}
send (id);
send (prefixapp ? "*" : appname); // All apps
if (*hostname && strcmp (hostname, id))
send (hostname); // Hostname as well as MAC
#ifndef CONFIG_REVK_OLD_SETTINGS
if (prefix == topiccommand)
for (int i = 0; i < sizeof (topicgroup) / sizeof (*topicgroup); i++)
if (*topicgroup[i])
send (topicgroup[i]);
#endif
}
subunsub (topiccommand);
if (!client)
subunsub (topicsetting);
}
#endif
#ifdef CONFIG_REVK_MQTT
static void
mqtt_rx (void *arg, char *topic, unsigned short plen, unsigned char *payload)
{ // Expects to be able to write over topic
int client = (int) arg;
if (client < 0 || client >= CONFIG_REVK_MQTT_CLIENTS)
return;
if (topic)
{
const char *err = NULL;
// Break up topic
char *prefix = NULL; // What type of message, e.g. command, etc, at start or after id if prefixhost set
char *target = NULL; // The ID (hostname or MAC or *)
char *suffix = NULL; // The suffix, e.g. what command, etc, optional
char *apppart = NULL; // The app part (before prefix) if prefixapp set
char *p = topic;
void getprefix (void)
{ // Handle prefix (allow for / in command/setting)
if (!*p)
return;
prefix = p;
int l = 0;
if (*topiccommand && !strncmp (p, topiccommand, l = strlen (topiccommand)) && (!p[l] || p[l] == '/'))
p += l;
else if (*topicsetting && !strncmp (p, topicsetting, l = strlen (topicsetting)) && (!p[l] || p[l] == '/'))
p += l;
else
while (*p && *p != '/')
p++;
if (*p)
p++;
}
void getapp (void)
{ // Get app, only if app expected and correct
int l = strlen (appname);
if (!prefixapp || strncmp (p, appname, l) || (p[l] && p[l] != '/'))
return; // Not a expected, or correct, app prefix
apppart = p;
while (*p && *p != '/')
p++;