forked from espruino/Espruino
/
jswrap_esp8266_network.c
2015 lines (1733 loc) · 74.1 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 board specific functions.
*
* 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
#define WIFI_DBG 1
// 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
// 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.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 "jsinteractive.h"
#include "network.h"
#include "network_esp8266.h"
#include "jswrap_net.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;
// 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;
//===== 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
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
};
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 <= 201) 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.
*/
/*JSON{
"type": "library",
"class": "Wifi"
}
The wifi library is a generic cross-platform library to control the Wifi interface. It supports functionality such as connecting to wifi networks, getting network information, starting and access point, etc.
**Currently this library is ESP8266 specific** and needs to be ported to other Espruino platforms.
To get started and connect to your local access point all you need is
```
var wifi = require("Wifi");
wifi.connect("my-ssid", {password:"my-pwd"}, function(ap){ console.log("connected:", ap); });
```
If you want the connection to happen automatically at boot, add `wifi.save();`.
*/
/** 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;
}
//===== wifi library events
/*JSON{
"type" : "event",
"class" : "Wifi",
"name" : "associated",
"params" : [
["details","JsVar","An object with event details"]
]
}
The 'connected' event is called when an association with an access point has succeeded, i.e., a connection to the AP's network has been established.
The details include:
* ssid - The SSID of the access point to which the association was established
* mac - The BSSID/mac address of the access point
* channel - The wifi channel used (an integer, typ 1..14)
*/
/*JSON{
"type" : "event",
"class" : "Wifi",
"name" : "disconnected",
"params" : [
["details","JsVar","An object with event details"]
]
}
The 'disconnected' event is called when an association with an access point has been lost.
The details include:
* ssid - The SSID of the access point from which the association was lost
* mac - The BSSID/mac address of the access point
* reason - The reason for the disconnection (string)
*/
/*JSON{
"type" : "event",
"class" : "Wifi",
"name" : "auth_change",
"params" : [
["details","JsVar","An object with event details"]
]
}
The 'auth_change' event is called when the authentication mode with the associated access point changes.
The details include:
* oldMode - The old auth mode (string: open, wep, wpa, wpa2, wpa_wpa2)
* newMode - The new auth mode (string: open, wep, wpa, wpa2, wpa_wpa2)
*/
/*JSON{
"type" : "event",
"class" : "Wifi",
"name" : "dhcp_timeout"
}
The 'dhcp_timeout' event is called when a DHCP request to the connected access point fails and thus no IP address could be acquired (or renewed).
*/
/*JSON{
"type" : "event",
"class" : "Wifi",
"name" : "connected",
"params" : [
["details","JsVar","An object with event details"]
]
}
The 'connected' event is called when the connection with an access point is ready for traffic. In the case of a dynamic IP address configuration this is when an IP address is obtained, in the case of static IP address allocation this happens when an association is formed (in that case the 'associated' and 'connected' events are fired in rapid succession).
The details include:
* ip - The IP address obtained as string
* netmask - The network's IP range mask as string
* gw - The network's default gateway as string
*/
/*JSON{
"type" : "event",
"class" : "Wifi",
"name" : "sta_joined",
"params" : [
["details","JsVar","An object with event details"]
]
}
The 'sta_joined' event is called when a station establishes an association (i.e. connects) with the esp8266's access point.
The details include:
* mac - The MAC address of the station in string format (00:00:00:00:00:00)
*/
/*JSON{
"type" : "event",
"class" : "Wifi",
"name" : "sta_left",
"params" : [
["details","JsVar","An object with event details"]
]
}
The 'sta_left' event is called when a station disconnects from the esp8266's access point (or its association times out?).
The details include:
* mac - The MAC address of the station in string format (00:00:00:00:00:00)
*/
/*JSON{
"type" : "event",
"class" : "Wifi",
"name" : "probe_recv",
"params" : [
["details","JsVar","An object with event details"]
]
}
The 'probe_recv' event is called when a probe request is received from some station by the esp8266's access point.
The details include:
* mac - The MAC address of the station in string format (00:00:00:00:00:00)
* rssi - The signal strength in dB of the probe request
*/
//===== Functions
//===== Wifi.disconnect
/*JSON{
"type" : "staticmethod",
"class" : "Wifi",
"name" : "disconnect",
"generate" : "jswrap_ESP8266_wifi_disconnect",
"params" : [
["callback", "JsVar", "An optional function to be called back on disconnection. The callback function receives no argument."]
]
}
Disconnect the wifi station from an access point and disable the station mode. It is OK to call `disconnect` to turn off station mode even if no connection exists (for example, connection attempts may be failing). Station mode can be re-enabled by calling `connect` or `scan`.
*/
void jswrap_ESP8266_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");
}
//===== Wifi.stopAP
/*JSON{
"type" : "staticmethod",
"class" : "Wifi",
"name" : "stopAP",
"generate" : "jswrap_ESP8266_wifi_stopAP",
"params" : [
["callback", "JsVar", "An optional function to be called back on successful stop. The callback function receives no argument."]
]
}
Stop being an access point and disable the AP operation mode. Ap mode can be re-enabled by calling `startAP`.
*/
void jswrap_ESP8266_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");
}
//===== Wifi.connect
/*JSON{
"type" : "staticmethod",
"class" : "Wifi",
"name" : "connect",
"generate" : "jswrap_ESP8266_wifi_connect",
"params" : [
["ssid", "JsVar", "The access point network id."],
["options", "JsVar", "Connection options (optional)."],
["callback", "JsVar", "A function to be called back on completion (optional)."]
]
}
Connect to an access point as a station. If there is an existing connection to an AP it is first disconnected if the SSID or password are different from those passed as parameters. Put differently, if the passed SSID and password are identical to the currently connected AP then nothing is changed.
When the connection attempt completes the callback function is invoked with one `err` parameter, which is NULL if there is no error and a string message if there is an error. If DHCP is enabled the callback occurs once an IP addres has been obtained, if a static IP is set the callback occurs once the AP's network has been joined. The callback is also invoked if a connection already exists and does not need to be changed.
The options properties may contain:
* `password` - Password string to be used to access the network.
* `dnsServers` (array of String) - An array of up to two DNS servers in dotted decimal format string.
Notes:
* the options should include the ability to set a static IP and associated netmask and gateway, this is a future enhancement.
* the only error reported in the callback is "Bad password", all other errors (such as access point not found or DHCP timeout) just cause connection retries. If the reporting of such temporary errors is desired, the caller must use its own timeout and the `getDetails().status` field.
* the `connect` call automatically enabled station mode, it can be disabled again by calling `disconnect`.
*/
void jswrap_ESP8266_wifi_connect(
JsVar *jsSsid,
JsVar *jsOptions,
JsVar *jsCallback
) {
// Notes:
// The callback function is saved in the file local variable called g_jsGotIpCallback. The
// callback will be made when the WiFi callback found in the function called wifiEventHandler.
DBGV("> Wifi.connect\n");
// 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];
int 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;
g_disconnecting = false; // we're gonna be connecting...
// Get the optional password
char password[65];
os_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) {
len = jsvGetString(jsPassword, password, sizeof(password)-1);
password[len]='\0';
} else {
password[0] = '\0';
}
jsvUnLock(jsPassword);
}
// structure for SDK call, it's a shame we need to copy ssid and password but if we placed
// them straight into the stationConfig struct we wouldn't be able to printf them for debug
struct station_config stationConfig;
memset(&stationConfig, 0, sizeof(stationConfig));
os_strncpy((char *)stationConfig.ssid, ssid, 32);
os_strncpy((char *)stationConfig.password, password, 64);
DBGV(" - ssid:%s passwordLen:%d\n", ssid, strlen(password));
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);
// Do we have a child property called dnsServers?
JsVar *jsDNSServers = jsvObjectGetChild(jsOptions, "dnsServers", 0);
int count = 0;
if (jsvIsArray(jsDNSServers) != false) {
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);
// 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");
}
//===== Wifi.scan
/*JSON{
"type" : "staticmethod",
"class" : "Wifi",
"name" : "scan",
"generate" : "jswrap_ESP8266_wifi_scan",
"params" : [
["callback", "JsVar", "A function to be called back on completion."]
]
}
Perform a scan for access points. This will enable the station mode if it is not currently enabled. Once the scan is complete the callback function is called with an array of APs found, each AP is an object with:
* `ssid`: SSID string.
* `mac`: access point MAC address in 00:00:00:00:00:00 format.
* `authMode`: `open`, `wep`, `wpa`, `wpa2`, or `wpa_wpa2`.
* `channel`: wifi channel 1..13.
* `hidden`: true if the SSID is hidden.
* `rssi`: signal strength in dB in the range -110..0.
Notes:
* in order to perform the scan the station mode is turned on and remains on, use Wifi.disconnect() to turn it off again, if desired.
* only one scan can be in progress at a time.
*/
void jswrap_ESP8266_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
wifi_station_scan(NULL, scanCB);
DBG("Wifi.scan starting: mode=%s\n", wifiMode[wifi_get_opmode()]);
DBGV("< Wifi.scan\n");
}
//===== Wifi.startAP
/*JSON{
"type" : "staticmethod",
"class" : "Wifi",
"name" : "startAP",
"generate" : "jswrap_ESP8266_wifi_startAP",
"params" : [
["ssid", "JsVar", "The network id."],
["options", "JsVar", "Configuration options (optional)."],
["callback", "JsVar", "Optional function to be called when the AP is successfully started."]
]
}
Create a WiFi access point allowing stations to connect. If the password is NULL or an empty string the access point is open, otherwise it is encrypted.
The callback function is invoked once the access point is set-up and receives one `err` argument, which is NULL on success and contains an error message string otherwise.
The `options` object can contain the following properties.
* `authMode` - The authentication mode to use. Can be one of "open", "wpa2", "wpa", "wpa_wpa2". The default is open (but open access points are not recommended).
* `password` - The password for connecting stations if authMode is not open.
* `channel` - The channel to be used for the access point in the range 1..13. If the device is also connected to an access point as a station then that access point determines the channel.
Notes:
* the options should include the ability to set the AP IP and associated netmask, this is a future enhancement.
* the `startAP` call automatically enables AP mode. It can be disabled again by calling `stopAP`.
*/
void jswrap_ESP8266_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 channel
JsVar *jsChan = jsvObjectGetChild(jsOptions, "channel", 0);
if (jsvIsInt(jsChan)) {
int chan = jsvGetInteger(jsChan);
if (chan >= 1 && chan <= 13) softApConfig.channel = chan;
}
jsvUnLock(jsChan);
// Handle password
JsVar *jsPassword = jsvObjectGetChild(jsOptions, "password", 0);
if (jsPassword != NULL) {
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';
}
// 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 = jsvObjectGetChild(jsOptions, "authMode", 0);
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");
}
//===== Wifi.getStatus
/*JSON{
"type" : "staticmethod",
"class" : "Wifi",
"name" : "getStatus",
"generate" : "jswrap_ESP8266_wifi_getStatus",
"return" : ["JsVar", "An object representing the current WiFi status, if available immediately."],
"params" : [
["callback", "JsVar", "An optional function to be called back with the current Wifi status, i.e. the same object as returned directly. The callback function is more portable than the direct return value."]
]
}
Retrieve the current overall WiFi configuration. This call provides general information that pertains to both station and access point modes. The getDetails and getAPDetails calls provide more in-depth information about the station and access point configurations, respectively. The status object has the following properties:
* `station` - Status of the wifi station: `off`, `connecting`, ...
* `ap` - Status of the wifi access point: `disabled`, `enabled`.
* `mode` - The current operation mode: `off`, `sta`, `ap`, `sta+ap`.
* `phy` - Modulation standard configured: `11b`, `11g`, `11n` (the esp8266 docs are not very clear, but it is assumed that 11n means b/g/n). This setting limits the modulations that the radio will use, it does not indicate the current modulation used with a specific access point.
* `powersave` - Power saving mode: `none` (radio is on all the time), `ps-poll` (radio is off between beacons as determined by the access point's DTIM setting). Note that in 'ap' and 'sta+ap' modes the radio is always on, i.e., no power saving is possible.
* `savedMode` - The saved operation mode which will be applied at boot time: `off`, `sta`, `ap`, `sta+ap`.
*/
JsVar *jswrap_ESP8266_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("off"));
// 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;
}
//===== Wifi.setConfig
/*JSON{
"type" : "staticmethod",
"class" : "Wifi",
"name" : "setConfig",
"generate" : "jswrap_ESP8266_wifi_setConfig",
"params" : [
["settings", "JsVar", "An object with the configuration settings to change."]
]
}
Sets a number of global wifi configuration settings. All parameters are optional and which are passed determines which settings are updated.
The settings available are:
* `phy` - Modulation standard to allow: `11b`, `11g`, `11n` (the esp8266 docs are not very clear, but it is assumed that 11n means b/g/n).
* `powersave` - Power saving mode: `none` (radio is on all the time), `ps-poll` (radio is off between beacons as determined by the access point's DTIM setting). Note that in 'ap' and 'sta+ap' modes the radio is always on, i.e., no power saving is possible.
Note: esp8266 SDK programmers may be missing an "opmode" option to set the sta/ap/sta+ap operation mode. Please use connect/scan/disconnect/startAP/stopAP, which all set the esp8266 opmode indirectly.
*/
void jswrap_ESP8266_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 = jsvObjectGetChild(jsSettings, "phy", 0);
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 = jsvObjectGetChild(jsSettings, "powersave", 0);
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");
}
//===== Wifi.getDetails
/*JSON{
"type" : "staticmethod",
"class" : "Wifi",
"name" : "getDetails",
"generate" : "jswrap_ESP8266_wifi_getDetails",
"return" : ["JsVar", "An object representing the wifi station details, if available immediately."],
"params" : [
["callback", "JsVar", "An optional function to be called back with the wifi details, i.e. the same object as returned directly. The callback function is more portable than the direct return value."]
]
}
Retrieve the wifi station configuration and status details. The details object has the following properties:
* `status` - Details about the wifi station connection, one of `off`, `connecting`, `wrong_password`, `no_ap_found`, `connect_fail`, or `connected`. The off, bad_password and connected states are stable, the other states are transient. The connecting state will either result in connected or one of the error states (bad_password, no_ap_found, connect_fail) and the no_ap_found and connect_fail states will result in a reconnection attempt after some interval.
* `rssi` - signal strength of the connected access point in dB, typically in the range -110 to 0, with anything greater than -30 being an excessively strong signal.
* `ssid` - SSID of the access point.
* `password` - the password used to connect to the access point.
* `authMode` - the authentication used: `open`, `wpa`, `wpa2`, `wpa_wpa2` (not currently supported).
* `savedSsid` - the SSID to connect to automatically at boot time, null if none.
*/
JsVar *jswrap_ESP8266_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);