/
jswrap_esp32_network.c
1705 lines (1490 loc) · 54.6 KB
/
jswrap_esp32_network.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
/*
/*
* This file is part of Espruino, a JavaScript interpreter for Microcontrollers
*
* Copyright (C) 2015 Gordon Williams <gw@pur3.co.uk>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* ----------------------------------------------------------------------------
* This file is designed to be parsed during the build process
*
* Contains ESP32 and Wifi library specific functions.
*
* FOR DESCRIPTIONS OF THE WIFI FUNCTIONS IN THIS FILE, SEE
* libs/network/jswrap_wifi.c (or http://www.espruino.com/Reference#Wifi)
*
* IMPORTANT: the functions in this file have tests in ./tests/wifi-test-mode.js
* please maintain these tests if you make functional changes!
* ----------------------------------------------------------------------------
*/
// Includes from ESP-IDF
#include "esp_wifi.h"
#include "esp_event_loop.h"
#include "tcpip_adapter.h"
#include "mdns/include/mdns.h"
#include "lwip/apps/ping/ping.h"
#include "lwip/apps/ping/esp_ping.h"
#include "apps/sntp/sntp.h"
#include "lwip/dns.h"
#include "jsinteractive.h"
#include "network.h"
#include "jswrap_modules.h"
#include "jswrap_esp32_network.h"
#include "jswrap_storage.h"
#include "jsutils.h"
#define UNUSED(x) (void)(x)
static void sendWifiCompletionCB(
JsVar **g_jsCallback, //!< Pointer to the global callback variable
char *reason //!< NULL if successful, error string otherwise
);
// A callback function to be invoked on a disconnect response.
static JsVar *g_jsDisconnectCallback;
// A callback function to be invoked when we have an IP address.
static JsVar *g_jsGotIpCallback;
// A callback function to be invoked on ping responses.
static JsVar *g_jsPingCallback;
// A callback function to be invoked on gethostbyname responses.
static JsVar *g_jsHostByNameCallback;
// A callback function to be invoked when we complete an access point scan.
static JsVar *g_jsScanCallback;
// A callback function to be invoked when we are being an access point.
static JsVar *g_jsAPStartedCallback;
// The last time we were connected as a station.
static system_event_sta_connected_t g_lastEventStaConnected;
// The last time we were disconnected as a station.
static system_event_sta_disconnected_t g_lastEventStaDisconnected;
// Are we connected as a station?
static bool g_isStaConnected = false;
#define EXPECT_CB_EXCEPTION(jsCB) jsExceptionHere(JSET_ERROR, "Expecting callback function but got %v", jsCB)
#define EXPECT_OPT_EXCEPTION(jsOPT) jsExceptionHere(JSET_ERROR, "Expecting options object but got %t", jsOPT)
//===== mDNS
static bool mdns_started = 0;
void stopMDNS() {
jsWarn( "Wifi:stopMDNS");
mdns_free();
mdns_started = false;
}
void startMDNS(char *hostname) {
jsWarn( "Wifi:startMDNS - %s", hostname);
if (mdns_started) stopMDNS();
// start mDNS
ESP_ERROR_CHECK( mdns_init() );
//set mDNS hostname (required if you want to advertise services)
ESP_ERROR_CHECK( mdns_hostname_set(hostname) );
mdns_service_add(NULL, "_telnet", "_tcp", 23, NULL, 0);
mdns_started = true;
}
/**
* Convert an wifi_auth_mode_t data type to a string value.
*/
static char *authModeToString(wifi_auth_mode_t authMode) {
switch(authMode) {
case WIFI_AUTH_OPEN:
return "open";
case WIFI_AUTH_WEP:
return "wep";
case WIFI_AUTH_WPA_PSK:
return "wpa";
case WIFI_AUTH_WPA2_PSK:
return "wpa2";
case WIFI_AUTH_WPA_WPA2_PSK:
return "wpa_wpa2";
}
return "unknown";
} // End of authModeToString
/**
* Convert an wifi_cipher_type_t data type to a string value.
*
static char *cipherTypeToString(wifi_cipher_type_t cipherType) {
switch(cipherType) {
case WIFI_CIPHER_TYPE_NONE:
return "NONE";
case WIFI_CIPHER_TYPE_WEP40:
return "WEP40";
case WIFI_CIPHER_TYPE_WEP104:
return "WEP104";
case WIFI_CIPHER_TYPE_TKIP:
return "TKIP";
case WIFI_CIPHER_TYPE_CCMP:
return "CCMP";
case WIFI_CIPHER_TYPE_TKIP_CCMP:
return "TKIP+CCMP";
}
return "unknown";
} // End of authModeToString
*/
/**
* check esp function
*/
/**
* Convert an wifi_second_chan_t data type to a string value.
*/
static char *htModeToString(wifi_second_chan_t htMode) {
switch(htMode) {
case WIFI_SECOND_CHAN_NONE:
return "HT20";
case WIFI_SECOND_CHAN_ABOVE:
return "HT40+";
case WIFI_SECOND_CHAN_BELOW:
return "HT40-";
}
return "unknown";
} // End of htModeToString
/**
* Convert a Wifi reason code to a string representation.
*/
static char *wifiReasonToString(uint8_t reason) {
switch(reason) {
case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT:
return "4WAY_HANDSHAKE_TIMEOUT";
case WIFI_REASON_802_1X_AUTH_FAILED:
return "802_1X_AUTH_FAILED";
case WIFI_REASON_AKMP_INVALID:
return "AKMP_INVALID";
case WIFI_REASON_ASSOC_EXPIRE:
return "ASSOC_EXPIRE";
case WIFI_REASON_ASSOC_FAIL:
return "ASSOC_FAIL";
case WIFI_REASON_ASSOC_LEAVE:
return "ASSOC_LEAVE";
case WIFI_REASON_ASSOC_NOT_AUTHED:
return "ASSOC_NOT_AUTHED";
case WIFI_REASON_ASSOC_TOOMANY:
return "ASSOC_TOOMANY";
case WIFI_REASON_AUTH_EXPIRE:
return "AUTH_EXPIRE";
case WIFI_REASON_AUTH_FAIL:
return "AUTH_FAIL";
case WIFI_REASON_AUTH_LEAVE:
return "AUTH_LEAVE";
case WIFI_REASON_BEACON_TIMEOUT:
return "BEACON_TIMEOUT";
case WIFI_REASON_CIPHER_SUITE_REJECTED:
return "CIPHER_SUITE_REJECTED";
case WIFI_REASON_DISASSOC_PWRCAP_BAD:
return "DISASSOC_PWRCAP_BAD";
case WIFI_REASON_DISASSOC_SUPCHAN_BAD:
return "DISASSOC_SUPCHAN_BAD";
case WIFI_REASON_GROUP_CIPHER_INVALID:
return "GROUP_CIPHER_INVALID";
case WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT:
return "GROUP_KEY_UPDATE_TIMEOUT";
case WIFI_REASON_HANDSHAKE_TIMEOUT:
return "HANDSHAKE_TIMEOUT";
case WIFI_REASON_IE_INVALID:
return "IE_INVALID";
case WIFI_REASON_IE_IN_4WAY_DIFFERS:
return "IE_IN_4WAY_DIFFERS";
case WIFI_REASON_INVALID_RSN_IE_CAP:
return "INVALID_RSN_IE_CAP";
case WIFI_REASON_MIC_FAILURE:
return "MIC_FAILURE";
case WIFI_REASON_NOT_ASSOCED:
return "NOT_ASSOCED";
case WIFI_REASON_NOT_AUTHED:
return "NOT_AUTHED";
case WIFI_REASON_NO_AP_FOUND:
return "NO_AP_FOUND";
case WIFI_REASON_PAIRWISE_CIPHER_INVALID:
return "PAIRWISE_CIPHER_INVALID";
case WIFI_REASON_UNSPECIFIED:
return "UNSPECIFIED";
case WIFI_REASON_UNSUPP_RSN_IE_VERSION:
return "REASON_UNSUPP_RSN_IE_VERSION";
}
jsDebug(DBG_INFO, "wifiReasonToString: Unknown reason %d", reason);
return "Unknown reason";
} // End of wifiReasonToString
/**
* Convery a wifi_mode_t data type to a string value.
*/
static char *wifiModeToString(wifi_mode_t mode) {
switch(mode) {
case WIFI_MODE_NULL:
return "NULL";
case WIFI_MODE_STA:
return "STA";
case WIFI_MODE_AP:
return "AP";
case WIFI_MODE_APSTA:
return "APSTA";
}
return "UNKNOWN";
} // End of wifiModeToString
/**
* Convert an wifi event to a string value.
*/
static char *wifiEventToString(uint32_t event){
switch(event){
case SYSTEM_EVENT_STA_CONNECTED:return "STA_CONNECTED";
case SYSTEM_EVENT_STA_DISCONNECTED:return "STA_DISCONNECTED";
case SYSTEM_EVENT_STA_AUTHMODE_CHANGE:return "STA_AUTHMODE_CHANGE";
case SYSTEM_EVENT_STA_GOT_IP:return "STA_GOT_IP";
case SYSTEM_EVENT_AP_STACONNECTED:return "AP_STACONNECTED";
case SYSTEM_EVENT_AP_STADISCONNECTED: return "AP_STADISCONNECTED";
case SYSTEM_EVENT_AP_PROBEREQRECVED:return "AP_PROBEREQRECVED";
case SYSTEM_EVENT_WIFI_READY: return "WIFI_READY";
case SYSTEM_EVENT_SCAN_DONE: return "SCAN_DONE";
case SYSTEM_EVENT_STA_START: return "STA_START";
case SYSTEM_EVENT_STA_STOP: return "STA_STOP";
case SYSTEM_EVENT_STA_LOST_IP: return "LOST_IP";
case SYSTEM_EVENT_STA_WPS_ER_SUCCESS: return "STA_WPS_ER_SUCCESS";
case SYSTEM_EVENT_STA_WPS_ER_FAILED: return "STA_WPS_ER_FAILED";
case SYSTEM_EVENT_STA_WPS_ER_TIMEOUT: return "STA_WPS_ER_TIMEOUT";
case SYSTEM_EVENT_STA_WPS_ER_PIN: return "STA_WPS_ER_PIN";
case SYSTEM_EVENT_AP_START: return "AP_START";
case SYSTEM_EVENT_AP_STOP: return "AP_STOP";
case SYSTEM_EVENT_GOT_IP6: return "GOT_IP6";
case SYSTEM_EVENT_ETH_START: return "ETH_START";
case SYSTEM_EVENT_ETH_STOP: return "ETH_STOP";
case SYSTEM_EVENT_ETH_CONNECTED: return "ETH_CONNECTED";
case SYSTEM_EVENT_ETH_DISCONNECTED: return "ETH_DISCONNECTED";
case SYSTEM_EVENT_ETH_GOT_IP: return "ETH_GOT_IP";
case SYSTEM_EVENT_MAX: return "MAX";
default: return "unknown event";
}
}
/**
* convert WiFi error to a string value.
*/
static char *wifiErrorToString(esp_err_t err){
switch(err){
case 0x3001: return"WiFi driver was not installed by esp_wifi_init";
case 0x3002: return"WiFi driver was not started by esp_wifi_start";
case 0x3003: return"WiFi driver was not stopped by esp_wifi_stop";
case 0x3004: return"WiFi interface error";
case 0x3005: return"WiFi mode error";
case 0x3006: return"WiFi internal state error";
case 0x3007: return"WiFi internal control block of station or soft-AP error";
case 0x3008: return"WiFi internal NVS module error";
case 0x3009: return"MAC address is invalid";
case 0x300A: return"SSID is invalid";
case 0x300B: return"Password is invalid";
case 0x300C: return"Timeout error";
case 0x300D: return"WiFi is in sleep state(RF closed) and wakeup fail";
case 0x300E: return"The caller would block";
case 0x300F: return"Station still in disconnect status";
default: return "no WiFi error, see esp_err_to_name.c";
}
}
/**
* Callback function that is invoked at the culmination of a scan.
*/
static void scanCB() {
/**
* Create a JsVar that is an array of JS objects where each JS object represents a
* retrieved access point set of information. The structure of a record will be:
* o authMode
* o isHidden
* o rssi
* o channel
* o ssid
* When the array has been built, invoke the callback function passing in the array
* of records.
*/
if (g_jsScanCallback == NULL) {
return;
}
uint16_t apCount;
ESP_ERROR_CHECK(esp_wifi_scan_get_ap_num(&apCount));
JsVar *jsAccessPointArray = jsvNewArray(NULL, 0);
if (apCount > 0) {
wifi_ap_record_t *list = (wifi_ap_record_t *)malloc(sizeof(wifi_ap_record_t) * apCount);
ESP_ERROR_CHECK(esp_wifi_scan_get_ap_records(&apCount, list));
int i;
for (i=0; i<apCount; i++) {
JsVar *jsCurrentAccessPoint = jsvNewObject();
jsvObjectSetChildAndUnLock(jsCurrentAccessPoint, "rssi", jsvNewFromInteger(list[i].rssi));
jsvObjectSetChildAndUnLock(jsCurrentAccessPoint, "authMode", jsvNewFromString(authModeToString(list[i].authmode)));
// The SSID may **NOT** be NULL terminated ... so handle that.
char temp[32 + 1];
strncpy((char *)temp, list[i].ssid, 32);
temp[32] = '\0';
jsvObjectSetChildAndUnLock(jsCurrentAccessPoint, "ssid", jsvNewFromString(temp));
sprintf(temp, MACSTR, MAC2STR(list[i].bssid));
jsvObjectSetChildAndUnLock(jsCurrentAccessPoint, "mac", jsvNewFromString(temp));
sprintf(temp, "%d", list[i].primary);
jsvObjectSetChildAndUnLock(jsCurrentAccessPoint, "channel", jsvNewFromString(temp));
// Can't find a flag for this? http://esp-idf.readthedocs.io/en/latest/api-reference/wifi/esp_wifi.html?highlight=wifi_ap_record_t
//jsvObjectSetChildAndUnLock(jsCurrentAccessPoint, "isHidden", jsvNewFromBool(list[i].ssid_hidden));
// Add the new record to the array
jsvArrayPush(jsAccessPointArray, jsCurrentAccessPoint);
jsvUnLock(jsCurrentAccessPoint);
} // End of loop over each access point
free(list);
} // Number of access points > 0
// We have now completed the scan callback, so now we can invoke the JS callback.
JsVar *params[1];
params[0] = jsAccessPointArray;
jsiQueueEvents(NULL, g_jsScanCallback, params, 1);
jsvUnLock(jsAccessPointArray);
jsvUnLock(g_jsScanCallback);
g_jsScanCallback = NULL;
} // End of scanCB
/** Get the global object for the Wifi library/module, this is used in order to send the
* "on event" callbacks to the handlers.
*/
static JsVar *getWifiModule() {
JsVar *moduleName = jsvNewFromString("Wifi");
JsVar *m = jswrap_require(moduleName);
jsvUnLock(moduleName);
return m;
} // End of getWifiModule
/**
* Given an ESP32 WiFi event type, determine the corresponding
* event handler name we should publish upon. For example, if we
* have an event of type "SYSTEM_EVENT_STA_CONNECTED" then we wish
* to publish an event upon "#onassociated". The implementation
* here is a simple switch as at this time we don't want to assume
* anything about the values of event types (i.e. whether they are small
* and sequential). If we could make assumptions about the event
* types we may have been able to use a lookup array.
*
* The mappings are:
* SYSTEM_EVENT_AP_PROBEREQRECVED - #onprobe_recv
* SYSTEM_EVENT_AP_STACONNECTED - #onsta_joined
* SYSTEM_EVENT_AP_STADISCONNECTED - #onsta_left
* SYSTEM_EVENT_STA_AUTHMODE_CHANGE - #onauth_change
* SYSTEM_EVENT_STA_CONNECTED - #onassociated
* SYSTEM_EVENT_STA_DISCONNECTED - #ondisconnected
* SYSTEM_EVENT_STA_GOT_IP - #onconnected
*
* See also:
* * event_handler()
*
*/
static int s_retry_num = 0;
static char *wifiGetEvent(uint32_t event) {
jsDebug(DBG_INFO,"wifiGetEvent: Got event: %d", event);
switch(event) {
case SYSTEM_EVENT_AP_PROBEREQRECVED:
return "#onprobe_recv";
case SYSTEM_EVENT_AP_STACONNECTED:
return "#onsta_joined";
case SYSTEM_EVENT_AP_STADISCONNECTED:
return "#onsta_left";
case SYSTEM_EVENT_AP_START:
break;
case SYSTEM_EVENT_AP_STOP:
break;
case SYSTEM_EVENT_SCAN_DONE:
break;
case SYSTEM_EVENT_STA_AUTHMODE_CHANGE:
return "#onauth_change";
case SYSTEM_EVENT_STA_CONNECTED:
return "#onassociated";
case SYSTEM_EVENT_STA_DISCONNECTED:
return "#ondisconnected";
case SYSTEM_EVENT_STA_GOT_IP:
return "#onconnected";
case SYSTEM_EVENT_STA_START:
break;
case SYSTEM_EVENT_STA_STOP:
break;
case SYSTEM_EVENT_WIFI_READY:
break;
}
jsDebug(DBG_INFO, "Unhandled wifi event type: %d", event);
return NULL;
} // End of wifiGetEvent
/**
* Invoke the JavaScript callback to notify the program that an ESP8266
* WiFi event has occurred.
*/
static void sendWifiEvent(
uint32_t eventType, //!< The ESP32 WiFi event type.
JsVar *jsDetails //!< The JS object to be passed as a parameter to the callback.
) {
JsVar *module = getWifiModule();
if (!module) {
return; // out of memory?
}
// get event name as string and compose param list
JsVar *params[1];
params[0] = jsDetails;
char *eventName = wifiGetEvent(eventType);
if (eventName == NULL) {
return;
}
jsiQueueObjectCallbacks(module, eventName, params, 1);
jsvUnLock(module);
return;
}
/**
* Wifi event handler
* Here we get invoked whenever a WiFi event is received from the ESP32 WiFi
* subsystem. The events include:
* * SYSTEM_EVENT_STA_DISCONNECTED - As a station, we were disconnected.
*/
static esp_err_t event_handler(void *ctx, system_event_t *event)
{
UNUSED(ctx);
/*
* SYSTEM_EVENT_STA_DISCONNECT
* Structure contains:
* * ssid
* * ssid_len
* * bssid
* * reason
*/
jsDebug(DBG_INFO,"Wifi: Event(%d):SYSTEM_EVENT_%s\n",event->event_id,wifiEventToString(event->event_id));
if (event->event_id == SYSTEM_EVENT_STA_DISCONNECTED) {
if (--s_retry_num > 0 ) {
esp_wifi_connect();
jsDebug(DBG_INFO,"retry to AP connect");
return;
}
g_isStaConnected = false; // Flag as disconnected
g_lastEventStaDisconnected = event->event_info.disconnected; // Save the last disconnected info
if (jsvIsFunction(g_jsDisconnectCallback)) {
jsiQueueEvents(NULL, g_jsDisconnectCallback, NULL, 0);
jsvUnLock(g_jsDisconnectCallback);
g_jsDisconnectCallback = NULL;
}
JsVar *jsDetails = jsvNewObject();
char temp[33];
memcpy(temp, event->event_info.disconnected.ssid, 32);
temp[32] = '\0';
jsvObjectSetChildAndUnLock(jsDetails, "ssid", jsvNewFromString(temp));
sprintf(temp, MACSTR, MAC2STR(event->event_info.disconnected.bssid));
jsvObjectSetChildAndUnLock(jsDetails, "mac", jsvNewFromString(temp));
sprintf(temp, "%d", event->event_info.disconnected.reason);
jsvObjectSetChildAndUnLock(jsDetails, "reason", jsvNewFromString(temp));
sendWifiEvent(event->event_id, jsDetails);
return ESP_OK;
} // End of handle SYSTEM_EVENT_STA_DISCONNECTED
/**
* SYSTEM_EVENT_STA_CONNECTED
* Structure contains:
* * ssid
* * ssid_len
* * bssid
* * channel
* * authmode
*/
if (event->event_id == SYSTEM_EVENT_STA_CONNECTED) {
g_isStaConnected = true; // Flag us as connected.
g_lastEventStaConnected = event->event_info.connected; // Save the last connected info
// Publish the on("associated") event to any one who has registered
// an interest.
JsVar *jsDetails = jsvNewObject();
char temp[33];
memcpy(temp, event->event_info.connected.ssid, 32);
temp[32] = '\0';
jsvObjectSetChildAndUnLock(jsDetails, "ssid", jsvNewFromString(temp));
sprintf(temp, MACSTR, MAC2STR(event->event_info.connected.bssid));
jsvObjectSetChildAndUnLock(jsDetails, "mac", jsvNewFromString(temp));
sprintf(temp, "%d", event->event_info.connected.channel);
jsvObjectSetChildAndUnLock(jsDetails, "channel", jsvNewFromString(temp));
sendWifiEvent(event->event_id, jsDetails);
return ESP_OK;
} // End of handle SYSTEM_EVENT_STA_CONNECTED
if (event->event_id == SYSTEM_EVENT_STA_START) {
s_retry_num = 5; // Try to connect 5 times
// Perform an esp_wifi_connect
esp_err_t err = esp_wifi_connect();
if (err != ESP_OK) {
jsError( "Wifi: event_handler STA_START: esp_wifi_connect: %d(%s)", err,wifiErrorToString(err));
return NULL;
}
return ESP_OK;
}
/**
* SYSTEM_EVENT_STA_GOT_IP
* Structure contains:
* * ipinfo.ip
* * ipinfo.netmask
* * ip_info.gw
*/
if (event->event_id == SYSTEM_EVENT_STA_GOT_IP) {
sendWifiCompletionCB(&g_jsGotIpCallback, NULL);
JsVar *jsDetails = jsvNewObject();
// 123456789012345_6
// xxx.xxx.xxx.xxx\0
char temp[16];
sprintf(temp, IPSTR, IP2STR(&event->event_info.got_ip.ip_info.ip));
jsvObjectSetChildAndUnLock(jsDetails, "ip", jsvNewFromString(temp));
sprintf(temp, IPSTR, IP2STR(&event->event_info.got_ip.ip_info.netmask));
jsvObjectSetChildAndUnLock(jsDetails, "netmask", jsvNewFromString(temp));
sprintf(temp, IPSTR, IP2STR(&event->event_info.got_ip.ip_info.gw));
jsvObjectSetChildAndUnLock(jsDetails, "gw", jsvNewFromString(temp));
jsDebug(DBG_INFO, "Wifi: About to emit connect!");
sendWifiEvent(event->event_id, jsDetails);
// start mDNS
const char * hostname;
esp_err_t err = tcpip_adapter_get_hostname(TCPIP_ADAPTER_IF_STA, &hostname);
if (hostname && hostname[0] != 0) {
startMDNS(hostname);
}
return ESP_OK;
} // End of handle SYSTEM_EVENT_STA_GOT_IP
/**
* SYSTEM_EVENT_AP_STACONNECTED
* Structure contains:
* * mac
* * aid
*/
if (event->event_id == SYSTEM_EVENT_AP_STACONNECTED) {
JsVar *jsDetails = jsvNewObject();
// 12345678901234567_8
// xx:xx:xx:xx:xx:xx\0
char temp[18];
sprintf(temp, MACSTR, MAC2STR(&event->event_info.sta_connected.mac));
jsvObjectSetChildAndUnLock(jsDetails, "mac", jsvNewFromString(temp));
sendWifiEvent(event->event_id, jsDetails);
return ESP_OK;
}
/**
* SYSTEM_EVENT_AP_STADISCONNECTED
* Structure contains:
* * mac
* * aid
*/
if (event->event_id == SYSTEM_EVENT_AP_STADISCONNECTED) {
JsVar *jsDetails = jsvNewObject();
// 12345678901234567_8
// xx:xx:xx:xx:xx:xx\0
char temp[18];
sprintf(temp, MACSTR, MAC2STR(&event->event_info.sta_disconnected.mac));
jsvObjectSetChildAndUnLock(jsDetails, "mac", jsvNewFromString(temp));
sendWifiEvent(event->event_id, jsDetails);
return ESP_OK;
}
/**
* SYSTEM_EVENT_SCAN_DONE
* Called when a previous network scan has completed. Here we check to see if we have
* a registered callback that is interested in being called when a scan has completed
* and, if we do, we build the parameters for that callback and then invoke it.
*/
if (event->event_id == SYSTEM_EVENT_SCAN_DONE) {
scanCB();
return ESP_OK;
}
/**
* SYSTEM_EVENT_AP_START
* Called when we have started being an access point.
*/
if (event->event_id == SYSTEM_EVENT_AP_START) {
sendWifiCompletionCB(&g_jsAPStartedCallback, NULL);
return ESP_OK;
}
jsDebug(DBG_INFO, "Wifi: event_handler -> NOT HANDLED EVENT: %d", event->event_id );
return ESP_OK;
} // End of event_handler
/**
* Initialize the one time ESP32 wifi components including the event
* handler.
*/
void esp32_wifi_init() {
tcpip_adapter_init();
ESP_ERROR_CHECK( esp_event_loop_init(event_handler, NULL));
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
jsDebug(DBG_INFO, "esp32_wifi_init complete");
} // End of esp32_wifi_init
/**
* Some of the WiFi functions have a completion callback which is of the form:
* function(err) { ... }
* These callbacks are called with an error string (if an error is encountered) or null if there is
* no error. Since this occurrence happens a number of times, this helper function takes as input
* a pointer to a callback function and a parameter.
*/
static void sendWifiCompletionCB(
JsVar **g_jsCallback, //!< Pointer to the global callback variable
char *reason //!< NULL if successful, error string otherwise
) {
jsDebug(DBG_INFO, "sendWifiCompletionCB");
// Check that we have a callback function.
if (!jsvIsFunction(*g_jsCallback)){
return; // we have not got a function pointer: nothing to do
}
JsVar *params[1];
params[0] = reason ? jsvNewFromString(reason) : jsvNewNull();
jsiQueueEvents(NULL, *g_jsCallback, params, 1);
jsvUnLock(params[0]);
// unlock and delete the global callback
jsvUnLock(*g_jsCallback);
*g_jsCallback = NULL;
} // End of sendWifiCompletionCB
/*JSON{
"type":"init",
"generate":"jswrap_esp32_wifi_soft_init"
}
*/
/**
* Perform a soft initialization of ESP32 networking.
*/
void jswrap_esp32_wifi_soft_init() {
jsDebug(DBG_INFO, "jswrap_esp32_wifi_soft_init()");
JsNetwork net;
networkCreate(&net, JSNETWORKTYPE_ESP32); // Set the network type to be ESP32
networkState = NETWORKSTATE_ONLINE; // Set the global state of the networking to be online
}
void jswrap_wifi_disconnect(JsVar *jsCallback) {
// We save the callback function so that it can subsequently invoked. Then we execute the
// ESP-IDF function to disconnect us from the access point. The thinking is that will result
// in a subsequent event which we will detect and use to call the callback.
//
// Free any existing callback, then register new callback
if (g_jsDisconnectCallback != NULL) jsvUnLock(g_jsDisconnectCallback);
g_jsDisconnectCallback = NULL;
// Check that the callback is a good callback if supplied.
if (jsCallback != NULL && !jsvIsUndefined(jsCallback) && !jsvIsFunction(jsCallback)) {
EXPECT_CB_EXCEPTION(jsCallback);
return;
}
// Save the callback for later execution.
g_jsDisconnectCallback = jsvLockAgainSafe(jsCallback);
// Call the ESP-IDF to disconnect us from the access point.
jsDebug(DBG_INFO, "Disconnecting.....");
// turn off auto-connect
esp_wifi_set_auto_connect(false);
s_retry_num = 0; // flag so we don't attempt to reconnect
esp_wifi_disconnect();
} // End of jswrap_wifi_disconnect
void jswrap_wifi_stopAP(JsVar *jsCallback) {
// handle the callback parameter
if (jsCallback != NULL && !jsvIsUndefined(jsCallback) && !jsvIsFunction(jsCallback)) {
EXPECT_CB_EXCEPTION(jsCallback);
return;
}
// Change operating mode intelligently. We want to remove us from being
// an access point but if we are also a station, we want to preserve that.
esp_err_t err;
wifi_mode_t mode;
err = esp_wifi_get_mode(&mode);
switch(mode) {
case WIFI_MODE_NULL:
case WIFI_MODE_STA:
break;
case WIFI_MODE_AP:
mode = WIFI_MODE_NULL;
break;
case WIFI_MODE_APSTA:
mode = WIFI_MODE_STA;
break;
default:
break;
}
err = esp_wifi_set_mode(mode);
if (err != ESP_OK) {
jsDebug(DBG_INFO, "jswrap_wifi_stopAP: esp_wifi_set_mode rc=%d(%s)", err,wifiErrorToString(err));
}
if (jsvIsFunction(jsCallback)) {
jsiQueueEvents(NULL, jsCallback, NULL, 0);
}
} // End of jswrap_wifi_stopAP
void jswrap_wifi_connect(
JsVar *jsSsid,
JsVar *jsOptions,
JsVar *jsCallback
) {
jsDebug(DBG_INFO, "jswrap_wifi_connect: entry");
// Check that the ssid value isn't obviously in error.
if (!jsvIsString(jsSsid)) {
jsExceptionHere(JSET_ERROR, "No SSID provided");
return;
}
// Create SSID string
char ssid[33];
size_t len = jsvGetString(jsSsid, ssid, sizeof(ssid)-1);
ssid[len]='\0';
// Make sure jsOptions is NULL or an object
if (jsOptions != NULL && !jsvIsObject(jsOptions)) {
EXPECT_OPT_EXCEPTION(jsOptions);
return;
}
// Check callback
if (g_jsGotIpCallback != NULL) jsvUnLock(g_jsGotIpCallback);
g_jsGotIpCallback = NULL;
if (jsCallback != NULL && !jsvIsUndefined(jsCallback) && !jsvIsFunction(jsCallback)) {
EXPECT_CB_EXCEPTION(jsCallback);
return;
}
// Clear disconnect callback to prevent disconnection from disabling station mode
if (g_jsDisconnectCallback != NULL) jsvUnLock(g_jsDisconnectCallback);
g_jsDisconnectCallback = NULL;
// Get the optional password
char password[65];
memset(password, 0, sizeof(password));
if (jsOptions != NULL) {
JsVar *jsPassword = jsvObjectGetChild(jsOptions, "password", 0);
if (jsPassword != NULL && !jsvIsString(jsPassword)) {
jsExceptionHere(JSET_ERROR, "Expecting options.password to be a string but got %t", jsPassword);
jsvUnLock(jsPassword);
return;
}
if (jsPassword != NULL) {
size_t len = jsvGetString(jsPassword, password, sizeof(password)-1);
password[len]='\0';
} else {
password[0] = '\0';
}
jsvUnLock(jsPassword);
} // End of we had options
jsDebug(DBG_INFO, "jswrap_wifi_connect: SSID, password, Callback done");
// At this point, we have the ssid in "ssid" and the password in "password".
// Perform an esp_wifi_set_mode
wifi_mode_t mode;
esp_err_t err;
err = esp_wifi_get_mode(&mode);
if (err != ESP_OK) {
jsError( "jswrap_wifi_connect: esp_wifi_get_mode: %d(%s)", err,wifiErrorToString(err));
return;
}
switch(mode) {
case WIFI_MODE_NULL:
case WIFI_MODE_STA:
mode = WIFI_MODE_STA;
break;
case WIFI_MODE_APSTA:
case WIFI_MODE_AP:
mode = WIFI_MODE_APSTA;
break;
default:
jsError( "jswrap_wifi_connect: Unexpected mode type: %d", mode);
break;
}
err = esp_wifi_set_mode(mode);
if (err != ESP_OK) {
jsError( "jswrap_wifi_connect: esp_wifi_set_mode: %d(%s), mode=%d", err,wifiErrorToString(err), mode);
return;
}
jsDebug(DBG_INFO, "jswrap_wifi_connect: esi_wifi_set_mode done");
// Perform a an esp_wifi_set_config
wifi_config_t staConfig;
memset(&staConfig, 0, sizeof(staConfig));
memcpy(staConfig.sta.ssid, ssid, sizeof(staConfig.sta.ssid));
memcpy(staConfig.sta.password, password, sizeof(staConfig.sta.password));
staConfig.sta.bssid_set = false;
esp_wifi_set_auto_connect(true);
jsDebug(DBG_INFO, "jswrap_wifi_connect: esp_wifi_set_autoconnect done");
err = esp_wifi_set_config(ESP_IF_WIFI_STA, &staConfig);
if (err != ESP_OK) {
jsError( "jswrap_wifi_connect: esp_wifi_set_config: %d(%s)", err,wifiErrorToString(err));
return;
}
jsDebug(DBG_INFO, "jswrap_wifi_connect: esp_wifi_set_config done");
// Perform an esp_wifi_start
jsDebug(DBG_INFO, "jswrap_wifi_connect: esp_wifi_start %s",ssid);
err = esp_wifi_start();
if (err != ESP_OK) {
jsError( "jswrap_wifi_connect: esp_wifi_start: %d(%s)", err,wifiErrorToString(err));
return;
}
// Save the callback for later execution.
g_jsGotIpCallback = jsvLockAgainSafe(jsCallback);
err = esp_wifi_connect();
}
void jswrap_wifi_scan(JsVar *jsCallback) {
// If we have a saved scan callback function we must be scanning already
if (g_jsScanCallback != NULL) {
jsExceptionHere(JSET_ERROR, "A scan is already in progress.");
return;
}
// Check and save callback
if (!jsvIsFunction(jsCallback)) {
EXPECT_CB_EXCEPTION(jsCallback);
return;
}
g_jsScanCallback = jsvLockAgainSafe(jsCallback);
// We need to be in some kind of a station mode in order to perform a scan
// Now we determine the mode we are currently in and set our new mode appropriately.
// NULL -> STA
// STA -> STA
// AP -> APSTA
// APSTA -> APSTA
wifi_mode_t mode;
esp_err_t err = esp_wifi_get_mode(&mode);
if (err != ESP_OK) {
jsError( "jswrap_wifi_scan: esp_wifi_get_mode: %d(%s)", err,wifiErrorToString(err));
return;
}
switch(mode) {
case WIFI_MODE_NULL:
mode = WIFI_MODE_STA;
break;
case WIFI_MODE_STA:
break;
case WIFI_MODE_AP:
mode = WIFI_MODE_APSTA;
break;
case WIFI_MODE_APSTA:
break;
default:
jsError( "Unknown mode %d", mode);
break;
}
err = esp_wifi_set_mode(mode);
if (err != ESP_OK) {
jsError( "jswrap_wifi_scan: esp_wifi_set_mode: %d(%s)", err,wifiErrorToString(err));
return;
}
// Perform an esp_wifi_start
err = esp_wifi_start();
if (err != ESP_OK) {
jsError( "jswrap_wifi_connect: esp_wifi_start: %d(%s)", err,wifiErrorToString(err));
return;
}
wifi_scan_config_t scanConf = {
.ssid = NULL,
.bssid = NULL,
.channel = 0,
.show_hidden = true
};
esp_wifi_scan_start(&scanConf, false); // Don't block for scan.
// When the scan completes, we will be notified by an arriving event that is handled
// in the event handler. The event handler will see that we have a callback function
// registered and will invoke that callback at that time.
} // End of jswrap_wifi_scan
void jswrap_wifi_startAP(
JsVar *jsSsid, //!< The network SSID that we will use to listen as.
JsVar *jsOptions, //!< Configuration options.
JsVar *jsCallback //!< A callback to be invoked when completed.
) {
// Check callback. It is invalid if it is defined and not a function.
if (jsCallback != NULL && !jsvIsUndefined(jsCallback) && !jsvIsFunction(jsCallback)) {
EXPECT_CB_EXCEPTION(jsCallback);
return;
}
// Validate that the SSID value is provided and is a string.
if (!jsvIsString(jsSsid)) {
jsExceptionHere(JSET_ERROR, "No SSID.");
return;
}
// Make sure jsOptions is NULL or an object
if (jsOptions != NULL && !jsvIsNull(jsOptions) && !jsvIsObject(jsOptions)) {
EXPECT_OPT_EXCEPTION(jsOptions);
return;
}
// Check callback
if (g_jsAPStartedCallback != NULL) jsvUnLock(g_jsAPStartedCallback);
g_jsAPStartedCallback = NULL;
if (jsCallback != NULL && !jsvIsUndefined(jsCallback) && !jsvIsFunction(jsCallback)) {
EXPECT_CB_EXCEPTION(jsCallback);
return;
}
wifi_ap_config_t apConfig;
bzero(&apConfig, sizeof(apConfig));
apConfig.ssid_hidden = 0;
apConfig.beacon_interval = 100;
apConfig.channel = 0;
apConfig.authmode = WIFI_AUTH_OPEN;
apConfig.max_connection = 4;
apConfig.ssid_len = (uint8_t)jsvGetString(jsSsid, (char *)apConfig.ssid, sizeof(apConfig.ssid));
apConfig.authmode = WIFI_AUTH_OPEN;
strcpy(apConfig.password, "");
if (jsvIsObject(jsOptions)) {
// Handle channel
JsVar *jsChan = jsvObjectGetChild(jsOptions, "channel", 0);
if (jsvIsInt(jsChan)) {
int chan = jsvGetInteger(jsChan);
if (chan >= 1 && chan <= 13) {
apConfig.channel = (uint8_t)chan;
}