/
jswrap_esp8266_network.c
1764 lines (1515 loc) · 59.9 KB
/
jswrap_esp8266_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 ESP8266 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!
* ----------------------------------------------------------------------------
*/
// Set WIFI_DBG to 0 to disable debug printf's, to 1 for important printf's, to 2 for verbose
//#ifdef RELEASE
//#define WIFI_DBG 0
//#else
//#define WIFI_DBG 1
//#endif
#ifdef RELEASE
#define DBG(format, ...) do { } while(0)
#define DBGV(format, ...) do { } while(0)
#else
// Normal debug
#if WIFI_DBG > 0
#define DBG(format, ...) os_printf(format, ## __VA_ARGS__)
#else
#define DBG(format, ...) do { } while(0)
#endif
// Verbose debug
#if WIFI_DBG > 1
#define DBGV(format, ...) os_printf(format, ## __VA_ARGS__)
#else
#define DBGV(format, ...) do { } while(0)
#endif
#endif
// Because the ESP8266 JS wrapper is assured to be running on an ESP8266 we
// can assume that inclusion of ESP8266 headers will be acceptable.
#include <c_types.h>
#include <user_interface.h>
#include <mem.h>
#include "osapi_release.h"
#include <ping.h>
#include <espconn.h>
#include <sntp.h>
#include <espmissingincludes.h>
#include <uart.h>
#define ESP8266_ON_ACCESS_POINTS "#accessPoints"
#define _GCC_WRAP_STDINT_H
typedef long long int64_t;
#include "jswrap_esp8266_network.h"
#include "jswrap_esp8266.h"
#include "jswrap_modules.h"
#include "jswrap_interactive.h"
#include "jsinteractive.h"
#include "network.h"
#include "network_esp8266.h"
#include "jswrap_net.h"
#include "jswrap_storage.h"
//#define jsvUnLock(v) do { os_printf("Unlock %s @%d\n", __STRING(v), __LINE__); jsvUnLock(v); } while(0)
// Forward declaration of functions.
static void scanCB(void *arg, STATUS status);
static void wifiEventHandler(System_Event_t *event);
static void pingRecvCB();
static void startMDNS(char *hostname);
static void stopMDNS();
// Some common error handling
FLASH_STR(expect_cb, "Expecting callback function but got %v");
#define EXPECT_CB_EXCEPTION(jsCB) jsExceptionHere_flash(JSET_ERROR, expect_cb, jsCB)
FLASH_STR(expect_opt, "Expecting options object but got %t");
#define EXPECT_OPT_EXCEPTION(jsOPT) jsExceptionHere_flash(JSET_ERROR, expect_opt, jsOPT)
// #NOTE: For callback functions, be sure and unlock them in the `kill` handler.
// A callback function to be invoked when we find a new access point.
static JsVar *g_jsScanCallback;
// 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 on a disconnect response.
static JsVar *g_jsDisconnectCallback;
// Flag to tell the wifi event handler that it should turn STA off on disconnect
static bool g_disconnecting;
// Flag to tell the wifi event handler to ignore the next disconnect event because
// we're provoking it in order to connect to something different
static bool g_skipDisconnect;
// Global data structure for ping request
static struct ping_option pingOpt;
// Global data structure for setIP and setAPIP
static struct ip_info info;
// Configuration save to flash
typedef struct {
uint16_t length, version;
uint32_t crc;
uint8_t mode, phyMode;
uint8_t sleepType, ssidLen;
uint8_t authMode, hidden;
char staSsid[32], staPass[64];
char apSsid[32], apPass[64];
char dhcpHostname[64];
} Esp8266_config;
static Esp8266_config esp8266Config;
static uint8 savedMode = 0;
//===== Mapping from enums to strings
// Reasons for which a connection failed
// (The code here is a bit of a nightmare in order to get the strings into FLASH so they don't
// eat up valuable RAM space. Sadly the FLASH_STR's __attribute__ stuff can't be applied to the
// wifiReasons array as a whole.)
FLASH_STR(__wr0, "0 - <Not Used>"); // 0
FLASH_STR(__wr1, "unspecified"); // 1 - REASON_UNSPECIFIED
FLASH_STR(__wr2, "auth_expire"); // 2 - REASON_AUTH_EXPIRE
FLASH_STR(__wr3, "auth_leave"); // 3 - REASON_AUTH_LEAVE
FLASH_STR(__wr4, "assoc_expire"); // 4 - REASON_ASSOC_EXPIRE
FLASH_STR(__wr5, "assoc_toomany"); // 5 - REASON_ASSOC_TOOMANY
FLASH_STR(__wr6, "not_authed"); // 6 - REASON_NOT_AUTHED
FLASH_STR(__wr7, "not_assoced"); // 7 - REASON_NOT_ASSOCED
FLASH_STR(__wr8, "assoc_leave"); // 8 - REASON_ASSOC_LEAVE
FLASH_STR(__wr9, "assoc_not_authed"); // 9 - REASON_ASSOC_NOT_AUTHED
FLASH_STR(__wr10, "disassoc_pwrcap_bad"); // 10 - REASON_DISASSOC_PWRCAP_BAD
FLASH_STR(__wr11, "disassoc_supchan_bad"); // 11 - REASON_DISASSOC_SUPCHAN_BAD
FLASH_STR(__wr12, "12 - <Not Used>"); // 12
FLASH_STR(__wr13, "ie_invalid"); // 13 - REASON_IE_INVALID
FLASH_STR(__wr14, "mic_failure"); // 14 - REASON_MIC_FAILURE
FLASH_STR(__wr15, "4way_handshake_timeout"); // 15 - REASON_4WAY_HANDSHAKE_TIMEOUT
FLASH_STR(__wr16, "group_key_update_timeout"); // 16 - REASON_GROUP_KEY_UPDATE_TIMEOUT
FLASH_STR(__wr17, "ie_in_4way_differs"); // 17 - REASON_IE_IN_4WAY_DIFFERS
FLASH_STR(__wr18, "group_cipher_invalid"); // 18 - REASON_GROUP_CIPHER_INVALID
FLASH_STR(__wr19, "pairwise_cipher_invalid"); // 19 - REASON_PAIRWISE_CIPHER_INVALID
FLASH_STR(__wr20, "akmp_invalid"); // 20 - REASON_AKMP_INVALID
FLASH_STR(__wr21, "unsupp_rsn_ie_version"); // 21 - REASON_UNSUPP_RSN_IE_VERSION
FLASH_STR(__wr22, "invalid_rsn_ie_cap"); // 22 - REASON_UNSUPP_RSN_IE_VERSION
FLASH_STR(__wr23, "802_1x_auth_failed"); // 23 - REASON_802_1X_AUTH_FAILED
FLASH_STR(__wr24, "cipher_suite_rejected"); // 24 - REASON_CIPHER_SUITE_REJECTED
FLASH_STR(__wr200, "beacon_timeout"); // 200 - REASON_BEACON_TIMEOUT
FLASH_STR(__wr201, "no_ap_found"); // 201 - REASON_NO_AP_FOUND
FLASH_STR(__wr202, "auth_failed"); // 202 - REASON_AUTH_FAIL
FLASH_STR(__wr203, "assoc_failed"); // 203 - REASON_ASSOC_FAIL
FLASH_STR(__wr204, "handshake_timeout"); // 204 - REASON_HANDSHAKE_TIMEOUT
static const char *wifiReasons[] = {
__wr0, __wr1, __wr2, __wr3, __wr4, __wr5, __wr6, __wr7, __wr8, __wr9, __wr10,
__wr11, __wr12, __wr13, __wr14, __wr15, __wr16, __wr17, __wr18, __wr19, __wr20,
__wr21, __wr22, __wr23, __wr24, __wr200, __wr201, __wr202, __wr203, __wr204
};
static char wifiReasonBuff[sizeof("group_key_update_timeout")+1]; // length of longest string
static char *wifiGetReason(uint8 wifiReason) {
const char *reason;
if (wifiReason <= 24) reason = wifiReasons[wifiReason];
else if (wifiReason >= 200 && wifiReason <= 204) reason = wifiReasons[wifiReason-200+24];
else reason = wifiReasons[1];
flash_strncpy(wifiReasonBuff, reason, sizeof(wifiReasonBuff));
wifiReasonBuff[sizeof(wifiReasonBuff)-1] = 0; // force null termination
return wifiReasonBuff;
}
// Wifi events
FLASH_STR(__ev0, "#onassociated");
FLASH_STR(__ev1, "#ondisconnected");
FLASH_STR(__ev2, "#onauth_change");
FLASH_STR(__ev3, "#onconnected");
FLASH_STR(__ev4, "#ondhcp_timeout");
FLASH_STR(__ev5, "#onsta_joined");
FLASH_STR(__ev6, "#onsta_left");
FLASH_STR(__ev7, "#onprobe_recv");
static const char *wifi_events[] = { __ev0, __ev1, __ev2, __ev3, __ev4, __ev5, __ev6, __ev7 };
static char wifiEventBuff[sizeof("#ondisconnected")+1]; // length of longest string
static char *wifiGetEvent(uint32 event) {
flash_strncpy(wifiEventBuff, wifi_events[event], sizeof(wifiEventBuff));
wifiEventBuff[sizeof(wifiEventBuff)-1] = 0;
return wifiEventBuff;
}
static char *wifiAuth[] = { "open", "wep", "wpa", "wpa2", "wpa_wpa2" };
static char *wifiMode[] = { "off", "sta", "ap", "sta+ap" };
static char *wifiPhy[] = { "?", "11b", "11g", "11n" };
static char *wifiConn[] = {
"off", "connecting", "bad_password", "no_ap_found", "connect_failed", "connected"
};
static char macFmt[] = "%02x:%02x:%02x:%02x:%02x:%02x";
//===== This file contains definitions for two classes: ESP8266 and wifi
/*JSON{
"type": "library",
"class": "ESP8266"
}
The ESP8266 library is specific to the ESP8266 version of Espruino, i.e.,
running Espruino on an ESP8266 module (not to be confused with using the ESP8266
as Wifi add-on to an Espruino board). This library contains functions to handle
ESP8266-specific actions. For example: `var esp8266 = require('ESP8266');
esp8266.reboot();` performs a hardware reset of the module.
*/
/** 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;
}
void jswrap_wifi_disconnect(JsVar *jsCallback) {
DBGV("> Wifi.disconnect\n");
// Free any existing callback, then register new callback
if (g_jsDisconnectCallback != NULL) jsvUnLock(g_jsDisconnectCallback);
g_jsDisconnectCallback = NULL;
if (jsCallback != NULL && !jsvIsUndefined(jsCallback) && !jsvIsFunction(jsCallback)) {
EXPECT_CB_EXCEPTION(jsCallback);
return;
}
g_jsDisconnectCallback = jsvLockAgainSafe(jsCallback);
int8 conn = wifi_station_get_connect_status();
// Do the disconnect, we ignore errors 'cause we don't care if we're not currently connected
wifi_station_disconnect();
if (conn == STATION_GOT_IP) {
// If we're connected we let the event handler turn off wifi so we can cleanly disconnect
// The event handler will also make the callback
g_disconnecting = true;
} else {
// We're not really connected, so we might as well make the callback right here
DBGV(" Wifi.disconnect turning STA off\n");
wifi_set_opmode(wifi_get_opmode() & SOFTAP_MODE);
g_disconnecting = false;
if (jsvIsFunction(jsCallback)) {
jsiQueueEvents(NULL, jsCallback, NULL, 0);
}
}
DBG("Wifi.disconnect: opmode=%s\n", wifiMode[wifi_get_opmode()]);
DBGV("< Wifi.disconnect\n");
}
void jswrap_wifi_stopAP(JsVar *jsCallback) {
DBGV("> Wifi.stopAP\n");
// handle the callback parameter
if (jsCallback != NULL && !jsvIsUndefined(jsCallback) && !jsvIsFunction(jsCallback)) {
EXPECT_CB_EXCEPTION(jsCallback);
return;
}
// Change operating mode
bool ok = wifi_set_opmode(wifi_get_opmode() & STATION_MODE); // keep station mode intact
if (jsvIsFunction(jsCallback)) {
jsiQueueEvents(NULL, jsCallback, NULL, 0);
}
DBG("Wifi.stopAP: opmode=%s\n", wifiMode[wifi_get_opmode()]);
DBGV("< Wifi.stopAP\n");
}
void jswrap_wifi_connect(
JsVar *jsSsid,
JsVar *jsOptions,
JsVar *jsCallback
) {
DBGV("> Wifi.connect\n");
struct station_config stationConfig;
memset(&stationConfig, 0, sizeof(stationConfig));
// Handle parameter ssid
char ssid[33];
if (!jsvIsString(jsSsid)) {
jsExceptionHere(JSET_ERROR, "No SSID provided");
return;
} else {
int len = jsvGetString(jsSsid, ssid, sizeof(ssid)-1);
ssid[len]='\0';
os_strncpy((char *)stationConfig.ssid, ssid, 32);
}
// 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;
g_disconnecting = false; // we're gonna be connecting...
// Check for jsOptions
if (jsOptions != NULL) {
if (!jsvIsObject(jsOptions)) {
jsExceptionHere(JSET_ERROR, "Expecting Object, got %t", jsOptions);
return;
} else {
// Handle password
char password[65];
os_memset(password, 0, sizeof(password));
JsVar *jsPassword = jsvObjectGetChildIfExists(jsOptions, "password");
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) {
int len = jsvGetString(jsPassword, password, sizeof(password)-1);
password[len]='\0';
} else {
password[0] = '\0';
}
os_strncpy((char *)stationConfig.password, password, 64);
DBGV(" - ssid:%s passwordLen:%d\n", ssid, strlen(password));
jsvUnLock(jsPassword);
// Handle bssid
JsVar *jsBssid= jsvObjectGetChildIfExists(jsOptions, "bssid");
if (jsBssid != NULL && jsvIsString(jsBssid)) {
char macAddrString[6 * 3 + 1 ];
int len = jsvGetString(jsBssid, macAddrString, sizeof(macAddrString)-1);
macAddrString[len] ='\0';
DBGV("bssid %s, len: %d\n",macAddrString,len);
bool isMAC = networkParseMACAddress((unsigned char*) stationConfig.bssid, (char *) macAddrString);
if ( isMAC ) {
stationConfig.bssid_set = 1;
DBGV("stationConfig.bssid_set = 1, %d %d %d %d %d %d\n",
stationConfig.bssid[0], stationConfig.bssid[1], stationConfig.bssid[2],
stationConfig.bssid[3], stationConfig.bssid[4], stationConfig.bssid[5]
);
} else {
jsExceptionHere(JSET_ERROR, "Expecting bssid as \"aa:bb:cc:dd:cc:ff\"");
jsvUnLock(jsBssid);
return;
}
}
jsvUnLock(jsBssid);
//Handle channel
JsVar *jsChannel = jsvObjectGetChildIfExists(jsOptions, "channel");
if(jsChannel != NULL && jsvIsInt(jsChannel)){
uint8 channel = jsvGetInteger(jsChannel);
if ( channel >= 0 && channel <= 14) {
DBGV("channel %d\n", channel);
wifi_set_channel(channel);
} else {
jsExceptionHere(JSET_ERROR, "Expecting options.channel to be a integer between 0 and 14, but got %t", jsChannel);
jsvUnLock(jsChannel);
return;
}
}
jsvUnLock(jsChannel);
// Handle dnsServers
JsVar *jsDNSServers = jsvObjectGetChildIfExists(jsOptions, "dnsServers");
if (jsvIsArray(jsDNSServers) != false) {
int count = 0;
DBGV(" - We have DNS servers!!\n");
JsVarInt numDNSServers = jsvGetArrayLength(jsDNSServers);
ip_addr_t dnsAddresses[2];
if (numDNSServers == 0) {
DBGV("No servers!!");
count = 0;
}
if (numDNSServers > 0) {
// One server
count = 1;
JsVar *jsCurrentDNSServer = jsvGetArrayItem(jsDNSServers, 0);
char buffer[50];
size_t size = jsvGetString(jsCurrentDNSServer, buffer, sizeof(buffer)-1);
buffer[size] = '\0';
jsvUnLock(jsCurrentDNSServer);
dnsAddresses[0].addr = networkParseIPAddress(buffer);
}
if (numDNSServers > 1) {
// Two servers
count = 2;
JsVar *jsCurrentDNSServer = jsvGetArrayItem(jsDNSServers, 1);
char buffer[50];
size_t size = jsvGetString(jsCurrentDNSServer, buffer, sizeof(buffer)-1);
buffer[size] = '\0';
jsvUnLock(jsCurrentDNSServer);
dnsAddresses[1].addr = networkParseIPAddress(buffer);
}
if (numDNSServers > 2) {
DBG("Ignoring DNS servers after first 2.");
}
if (count > 0) {
espconn_dns_setserver((char)count, dnsAddresses);
}
}
jsvUnLock(jsDNSServers);
}
}
int8 wifiConnectStatus = wifi_station_get_connect_status();
if (wifiConnectStatus < 0) wifiConnectStatus = 0;
DBGV(" - Current connect status: %s\n", wifiConn[wifiConnectStatus]);
struct station_config existingConfig;
wifi_station_get_config(&existingConfig);
if (wifiConnectStatus == STATION_GOT_IP &&
os_strncmp((char *)existingConfig.ssid, (char *)stationConfig.ssid, 32) == 0 &&
os_strncmp((char *)existingConfig.password, (char *)stationConfig.password, 64) == 0) {
// we're already happily connected to the target AP, thus we don't need to do anything
if (jsvIsFunction(jsCallback)) {
JsVar *params[1];
params[0] = jsvNewNull();
jsiQueueEvents(NULL, jsCallback, params, 1); // TODO: fix callback params and unlock...
jsvUnLock(params[0]);
}
DBGV("< Wifi.connect - no action\n");
return;
} else {
// we're not happily connected to the right AP, so disconnect to start over
wifi_station_disconnect();
// we skip the disconnect event unless we're connected (then it's legit) and unless
// we're idle/off (then there is no disconnect event to start with)
g_skipDisconnect = wifiConnectStatus != STATION_GOT_IP && wifiConnectStatus != STATION_IDLE;
wifi_set_opmode(wifi_get_opmode() | STATION_MODE);
}
// set callback
if (jsvIsFunction(jsCallback)) g_jsGotIpCallback = jsvLockAgainSafe(jsCallback);
// Set the station configuration
int8 ok = wifi_station_set_config_current(&stationConfig);
// ensure we have a default DHCP hostname
char *old_hostname = wifi_station_get_hostname();
if (old_hostname == NULL || old_hostname[0] == 0)
wifi_station_set_hostname("espruino");
DBGV(" - old hostname=%s, new hostname=%s\n", old_hostname, wifi_station_get_hostname());
// Set the WiFi mode of the ESP8266
wifi_set_event_handler_cb(wifiEventHandler); // this seems to get lost sometimes...
// Perform the network level connection.
wifi_station_connect();
DBG("Wifi.connect: ssid=%s pass_len=%d opmode=%s num_dns_srv=%d\n",
ssid, strlen(password), wifiMode[wifi_get_opmode()], count);
DBGV("< Wifi.connect\n");
}
void jswrap_wifi_scan(JsVar *jsCallback) {
DBGV("> Wifi.scan\n");
// 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);
g_disconnecting = false; // we don't want that to interfere
// Ask the ESP8266 to perform a network scan after first entering
// station mode. The network scan will eventually result in a callback
// being executed (scanCB) which will contain the results.
wifi_set_opmode_current(wifi_get_opmode() | STATION_MODE);
// Request a scan of the network calling "scanCB" on completion
struct scan_config config = {0};
config.show_hidden = true;
wifi_station_scan(&config, scanCB);
DBG("Wifi.scan starting: mode=%s\n", wifiMode[wifi_get_opmode()]);
DBGV("< Wifi.scan\n");
}
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.
) {
DBGV("> Wifi.startAP\n");
// Check callback
if (jsCallback != NULL && !jsvIsUndefined(jsCallback) && !jsvIsFunction(jsCallback)) {
EXPECT_CB_EXCEPTION(jsCallback);
return;
}
// Validate that the SSID 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;
}
// Build our SoftAP configuration details
struct softap_config softApConfig;
memset(&softApConfig, 0, sizeof(softApConfig));
softApConfig.max_connection = 4;
softApConfig.beacon_interval = 100;
softApConfig.authmode = AUTH_OPEN;
// ssid is not null terminated
softApConfig.ssid_len = jsvGetString(jsSsid, (char *)softApConfig.ssid, sizeof(softApConfig.ssid));
// Handle any options that may have been supplied.
if (jsvIsObject(jsOptions)) {
// Handle hidden
JsVar *jsHidden = jsvObjectGetChildIfExists(jsOptions, "hidden");
if (jsvIsInt(jsHidden)) {
int hidden = jsvGetInteger(jsHidden);
if (hidden >= 0 && hidden <= 1) softApConfig.ssid_hidden = hidden;
}
jsvUnLock(jsHidden);
// Handle channel
JsVar *jsChan = jsvObjectGetChildIfExists(jsOptions, "channel");
if (jsvIsInt(jsChan)) {
int chan = jsvGetInteger(jsChan);
if (chan >= 1 && chan <= 13) softApConfig.channel = chan;
}
jsvUnLock(jsChan);
// Handle password
JsVar *jsPassword = jsvObjectGetChildIfExists(jsOptions, "password");
if (jsPassword != NULL) {
// handle password:null
if (jsvGetStringLength(jsPassword) != 0) {
if (!jsvIsString(jsPassword) || jsvGetStringLength(jsPassword) < 8) {
jsExceptionHere(JSET_ERROR, "Password must be string of at least 8 characters");
jsvUnLock(jsPassword);
return;
}
int len = jsvGetString(jsPassword, (char *)softApConfig.password, sizeof(softApConfig.password)-1);
softApConfig.password[len] = '\0';
}
}
jsvUnLock(jsPassword);
// Handle "authMode" processing. Here we check that "authMode", if supplied, is
// one of the allowed values and set the softApConfig object property appropriately.
JsVar *jsAuth = jsvObjectGetChildIfExists(jsOptions, "authMode");
if (jsvIsString(jsAuth)) {
if (jsvIsStringEqual(jsAuth, "open")) {
softApConfig.authmode = AUTH_OPEN;
} else if (jsvIsStringEqual(jsAuth, "wpa2")) {
softApConfig.authmode = AUTH_WPA2_PSK;
} else if (jsvIsStringEqual(jsAuth, "wpa")) {
softApConfig.authmode = AUTH_WPA_PSK;
} else if (jsvIsStringEqual(jsAuth, "wpa_wpa2")) {
softApConfig.authmode = AUTH_WPA_WPA2_PSK;
} else {
jsvUnLock(jsAuth);
jsExceptionHere(JSET_ERROR, "Unknown authMode value");
return;
}
} else {
// no explicit auth mode, set according to presence of password
softApConfig.authmode = softApConfig.password[0] == 0 ? AUTH_OPEN : AUTH_WPA2_PSK;
}
jsvUnLock(jsAuth);
// Make sure password and authmode match
if (softApConfig.authmode != AUTH_OPEN && softApConfig.password[0] == 0) {
jsExceptionHere(JSET_ERROR, "Password not set but authMode not open");
return;
}
if (softApConfig.authmode == AUTH_OPEN && softApConfig.password[0] != 0) {
jsExceptionHere(JSET_ERROR, "Auth mode set to open but password supplied");
return;
}
}
// Define that we are in Soft AP mode including station mode if required.
DBGV("Wifi: switching to soft-AP mode, authmode=%d\n", softApConfig.authmode);
wifi_set_opmode(wifi_get_opmode() | SOFTAP_MODE);
wifi_set_event_handler_cb(wifiEventHandler); // this seems to get lost sometimes...
// Set the WiFi configuration.
bool ok = wifi_softap_set_config_current(&softApConfig);
// Is this still true:
// We should really check that becoming an access point works, however as of SDK 1.4, we
// are finding that if we are currently connected to an access point and we switch to being
// an access point, it works ... but returns 1 indicating an error.
//if (!rc) DBG("Error %d returned from wifi_softap_set_config, probably ignore...\n", rc);
if (jsCallback != NULL) {
// Set the return error as a function of the return code returned from the call to
// the ESP8266 API to create the AP
JsVar *params[1];
FLASH_STR(_fstr, "Error from wifi_softap_set_config");
size_t len = flash_strlen(_fstr);
char buff[len+1];
flash_strncpy(buff, _fstr, len+1);
params[0] = ok ? jsvNewNull() : jsvNewFromString(buff);
jsiQueueEvents(NULL, jsCallback, params, 1);
jsvUnLock(params[0]);
}
DBG("Wifi.startAP ssid=%s pass_len=%d opmode=%d auth=%d\n",
softApConfig.ssid, os_strlen((char *)softApConfig.password), wifi_get_opmode(),
softApConfig.authmode);
DBGV("< Wifi.startAP\n");
}
JsVar *jswrap_wifi_getStatus(JsVar *jsCallback) {
DBGV("> Wifi.getStatus\n");
// Check callback
if (jsCallback != NULL && !jsvIsNull(jsCallback) && !jsvIsFunction(jsCallback)) {
EXPECT_CB_EXCEPTION(jsCallback);
return NULL;
}
uint8 opMode = wifi_get_opmode();
uint8 phy = wifi_get_phy_mode();
uint8 sleep = wifi_get_sleep_type();
int8 conn = wifi_station_get_connect_status();
if (conn < 0) conn = 0;
JsVar *jsWiFiStatus = jsvNewObject();
jsvObjectSetChildAndUnLock(jsWiFiStatus, "mode",
jsvNewFromString(wifiMode[opMode]));
jsvObjectSetChildAndUnLock(jsWiFiStatus, "station",
jsvNewFromString((opMode&STATION_MODE) ? wifiConn[conn] : "off"));
jsvObjectSetChildAndUnLock(jsWiFiStatus, "ap",
jsvNewFromString((opMode & SOFTAP_MODE) ? "enabled" : "disabled"));
jsvObjectSetChildAndUnLock(jsWiFiStatus, "phy",
jsvNewFromString(wifiPhy[phy]));
jsvObjectSetChildAndUnLock(jsWiFiStatus, "powersave",
jsvNewFromString(sleep == NONE_SLEEP_T ? "none" : "ps-poll"));
jsvObjectSetChildAndUnLock(jsWiFiStatus, "savedMode",
jsvNewFromString(wifiMode[savedMode]));
// Schedule callback if a function was provided
if (jsvIsFunction(jsCallback)) {
DBGV(" Wifi.getStatus queuing CB\n");
JsVar *params[1];
params[0] = jsWiFiStatus;
jsiQueueEvents(NULL, jsCallback, params, 1);
}
DBGV("< Wifi.getStatus\n");
return jsWiFiStatus;
}
void jswrap_wifi_setConfig(JsVar *jsSettings) {
DBGV("> Wifi.setConfig\n");
// Make sure jsSetings an object
if (!jsvIsObject(jsSettings)) {
EXPECT_OPT_EXCEPTION(jsSettings);
return;
}
// phy setting
JsVar *jsPhy = jsvObjectGetChildIfExists(jsSettings, "phy");
if (jsvIsString(jsPhy)) {
if (jsvIsStringEqual(jsPhy, "11b")) {
wifi_set_phy_mode(PHY_MODE_11B);
} else if (jsvIsStringEqual(jsPhy, "11g")) {
wifi_set_phy_mode(PHY_MODE_11G);
} else if (jsvIsStringEqual(jsPhy, "11n")) {
wifi_set_phy_mode(PHY_MODE_11N);
} else {
jsvUnLock(jsPhy);
jsExceptionHere(JSET_ERROR, "Unknown phy mode");
return;
}
}
if (jsPhy != NULL) jsvUnLock(jsPhy);
// powersave setting
JsVar *jsPowerSave = jsvObjectGetChildIfExists(jsSettings, "powersave");
if (jsvIsString(jsPowerSave)) {
if (jsvIsStringEqual(jsPowerSave, "none")) {
wifi_set_sleep_type(NONE_SLEEP_T);
} else if (jsvIsStringEqual(jsPowerSave, "ps-poll")) {
wifi_set_sleep_type(MODEM_SLEEP_T);
} else {
jsvUnLock(jsPowerSave);
jsExceptionHere(JSET_ERROR, "Unknown powersave mode");
return;
}
}
if (jsPowerSave != NULL) jsvUnLock(jsPowerSave);
DBGV("< Wifi.setConfig\n");
}
JsVar *jswrap_wifi_getDetails(JsVar *jsCallback) {
DBGV("> Wifi.getDetails\n");
// Check callback
if (jsCallback != NULL && !jsvIsNull(jsCallback) && !jsvIsFunction(jsCallback)) {
EXPECT_CB_EXCEPTION(jsCallback);
return NULL;
}
uint8 opMode = wifi_get_opmode();
JsVar *jsDetails = jsvNewObject();
int8 conn = wifi_station_get_connect_status();
if (conn < 0) conn = 0;
jsvObjectSetChildAndUnLock(jsDetails, "status", jsvNewFromString(wifiConn[conn]));
struct station_config config;
wifi_station_get_config(&config);
char buf[65];
// ssid
os_strncpy(buf, (char *)config.ssid, 32);
buf[32] = 0;
jsvObjectSetChildAndUnLock(jsDetails, "ssid", jsvNewFromString(buf));
// password
os_strncpy(buf, (char *)config.password, 64);
buf[64] = 0;
jsvObjectSetChildAndUnLock(jsDetails, "password", jsvNewFromString((char *)config.password));
if (opMode & STATION_MODE) {
int rssi = wifi_station_get_rssi();
if (rssi > 0) rssi = 0; // sanity...
jsvObjectSetChildAndUnLock(jsDetails, "rssi", jsvNewFromInteger(rssi));
//jsvObjectSetChildAndUnLock(jsDetails, "authMode", jsvNewFromString(wifiAuth[config.));
}
jsvObjectSetChildAndUnLock(jsDetails, "savedSsid", jsvNewNull());
// Schedule callback if a function was provided
if (jsvIsFunction(jsCallback)) {
JsVar *params[1];
params[0] = jsDetails;
jsiQueueEvents(NULL, jsCallback, params, 1);
}
DBGV("< Wifi.getDetails\n");
return jsDetails;
}
JsVar *jswrap_wifi_getAPDetails(JsVar *jsCallback) {
DBGV("> Wifi.getAPDetails\n");
// Check callback
if (jsCallback != NULL && !jsvIsNull(jsCallback) && !jsvIsFunction(jsCallback)) {
EXPECT_CB_EXCEPTION(jsCallback);
return NULL;
}
uint8 opMode = wifi_get_opmode();
JsVar *jsDetails = jsvNewObject();
jsvObjectSetChildAndUnLock(jsDetails, "status",
jsvNewFromString(opMode & SOFTAP_MODE ? "enabled" : "disabled"));
struct softap_config config;
wifi_softap_get_config(&config);
jsvObjectSetChildAndUnLock(jsDetails, "authMode", jsvNewFromString(wifiAuth[config.authmode]));
jsvObjectSetChildAndUnLock(jsDetails, "hidden", jsvNewFromBool(config.ssid_hidden));
jsvObjectSetChildAndUnLock(jsDetails, "maxConn", jsvNewFromInteger(config.max_connection));
char buf[65];
// ssid
os_strncpy(buf, (char *)config.ssid, 32);
buf[32] = 0;
jsvObjectSetChildAndUnLock(jsDetails, "ssid", jsvNewFromString(buf));
// password
os_strncpy(buf, (char *)config.password, 64);
buf[64] = 0;
jsvObjectSetChildAndUnLock(jsDetails, "password", jsvNewFromString((char *)config.password));
jsvObjectSetChildAndUnLock(jsDetails, "savedSsid", jsvNewNull());
if (opMode & SOFTAP_MODE) {
JsVar *jsArray = jsvNewArray(NULL, 0);
struct station_info *station = wifi_softap_get_station_info();
while(station) {
JsVar *jsSta = jsvNewObject();
jsvObjectSetChildAndUnLock(jsSta, "ip",
networkGetAddressAsString((uint8_t *)&station->ip.addr, 4, 10, '.'));
char macAddrString[6*3 + 1];
os_sprintf(macAddrString, macFmt,
station->bssid[0], station->bssid[1], station->bssid[2],
station->bssid[3], station->bssid[4], station->bssid[5]);
jsvObjectSetChildAndUnLock(jsSta, "mac", jsvNewFromString(macAddrString));
jsvArrayPush(jsArray, jsSta);
jsvUnLock(jsSta);
station = STAILQ_NEXT(station, next);
}
wifi_softap_free_station_info();
jsvObjectSetChildAndUnLock(jsDetails, "stations", jsArray);
}
// Schedule callback if a function was provided
if (jsvIsFunction(jsCallback)) {
JsVar *params[1];
params[0] = jsDetails;
jsiQueueEvents(NULL, jsCallback, params, 1);
}
DBGV("< Wifi.getAPDetails\n");
return jsDetails;
}
void jswrap_wifi_save(JsVar *what) {
DBGV("> Wifi.save\n");
JsVar *o = jsvNewObject();
if (!o) return;
if (jsvIsString(what) && jsvIsStringEqual(what, "clear")) {
JsVar *name = jsvNewFromString(WIFI_CONFIG_STORAGE_NAME);
jswrap_storage_erase(name);
jsvUnLock(name);
DBG("Wifi.save(clear)\n");
return;
}
// station stuff
struct station_config sta_config;
wifi_station_get_config(&sta_config);
jsvObjectSetChildAndUnLock(o, "ssid", jsvNewFromString((char *)sta_config.ssid));
jsvObjectSetChildAndUnLock(o, "password", jsvNewFromString((char *)sta_config.password));
jsvObjectSetChildAndUnLock(o, "mode", jsvNewFromInteger(wifi_get_opmode()));
jsvObjectSetChildAndUnLock(o, "phyMode", jsvNewFromInteger(wifi_get_phy_mode()));
jsvObjectSetChildAndUnLock(o, "sleepType", jsvNewFromInteger(wifi_get_sleep_type()));
char *hostname = wifi_station_get_hostname();
if (hostname) jsvObjectSetChildAndUnLock(o, "hostname", jsvNewFromString((char *) hostname));
// softap stuff
struct softap_config ap_config;
wifi_softap_get_config(&ap_config);
jsvObjectSetChildAndUnLock(o, "ssidAP", jsvNewFromString((char *)ap_config.ssid));
jsvObjectSetChildAndUnLock(o, "passwordAP", jsvNewFromString((char *) ap_config.password));
jsvObjectSetChildAndUnLock(o, "authmodeAP", jsvNewFromInteger(ap_config.authmode));
jsvObjectSetChildAndUnLock(o, "hiddenAP", jsvNewFromInteger(ap_config.ssid_hidden));
jsvObjectSetChildAndUnLock(o, "channelAP", jsvNewFromInteger(ap_config.channel));
savedMode = wifi_get_opmode();
// save object
JsVar *name = jsvNewFromString(WIFI_CONFIG_STORAGE_NAME);
//JsVar *arr = jsvNewArray(&o,1);
jswrap_storage_erase(name);
jswrap_storage_write(name,o,0,0);
jsvUnLock2(name,o);
DBGV("< Wifi.save: write completed\n");
}
void jswrap_wifi_restore(void) {
DBG("Wifi.restore\n");
JsVar *name = jsvNewFromString(WIFI_CONFIG_STORAGE_NAME);
JsVar *o = jswrap_storage_readJSON(name, true);
if (!o) { // no data
jsvUnLock2(name,o);
return;
}
JsVar *v;
v = jsvObjectGetChildIfExists(o,"mode");
savedMode = jsvGetInteger(v);
jsvUnLock(v);
wifi_set_opmode_current(savedMode);
v = jsvObjectGetChildIfExists(o,"phyMode");
wifi_set_phy_mode(jsvGetInteger(v));
jsvUnLock(v);
v = jsvObjectGetChildIfExists(o,"sleepType");
wifi_set_sleep_type(jsvGetInteger(v));
jsvUnLock(v);
if (savedMode & SOFTAP_MODE) {
struct softap_config ap_config;
os_memset(&ap_config, 0, sizeof(ap_config));
v = jsvObjectGetChildIfExists(o,"authmodeAP");
ap_config.authmode =jsvGetInteger(v);
jsvUnLock(v);
v = jsvObjectGetChildIfExists(o,"hiddenAP");
ap_config.ssid_hidden = jsvGetInteger(v);
jsvUnLock(v);
v = jsvObjectGetChildIfExists(o,"ssidAP");
jsvGetString(v, (char *)ap_config.ssid, sizeof(ap_config.ssid));
ap_config.ssid_len = jsvGetStringLength(v);
jsvUnLock(v);
v = jsvObjectGetChildIfExists(o,"passwordAP");
jsvGetString(v, (char *)ap_config.password, sizeof(ap_config.password));
jsvUnLock(v);
v = jsvObjectGetChildIfExists(o,"channelAP");
ap_config.channel = jsvGetInteger(v);
jsvUnLock(v);
ap_config.max_connection = 4;
ap_config.beacon_interval = 100;
wifi_softap_set_config_current(&ap_config);
DBG("Wifi.restore: AP=%s\n", ap_config.ssid);
}
if (savedMode & STATION_MODE) {
v = jsvObjectGetChildIfExists(o,"hostname");
if (v) {
char hostname[64];
jsvGetString(v, hostname, sizeof(hostname));
DBG("Wifi.restore: hostname=%s\n", hostname);
wifi_station_set_hostname(hostname);
}
jsvUnLock(v);
struct station_config sta_config;
os_memset(&sta_config, 0, sizeof(sta_config));
v = jsvObjectGetChildIfExists(o,"ssid");
jsvGetString(v, (char *)sta_config.ssid, sizeof(sta_config.ssid));
jsvUnLock(v);
v = jsvObjectGetChildIfExists(o,"password");
jsvGetString(v, (char *)sta_config.password, sizeof(sta_config.password));
jsvUnLock(v);
wifi_station_set_config_current(&sta_config);
DBG("Wifi.restore: STA=%s\n", sta_config.ssid);
//jsWarn("Station SSID '%s', password '%s'\n",sta_config.ssid,sta_config.password);
wifi_station_connect(); // we're not supposed to call this from user_init but it doesn't harm
// and we need it when invoked from JS
}
}
/**
* Get the ip info for the given interface. The interfaces are:
* * 0 - Station
* * 1 - Access Point
*/
static JsVar *getIPInfo(JsVar *jsCallback, int interface) {
// Check callback
if (jsCallback != NULL && !jsvIsNull(jsCallback) && !jsvIsFunction(jsCallback)) {