-
Notifications
You must be signed in to change notification settings - Fork 7.4k
/
WiFiGeneric.cpp
785 lines (703 loc) · 24.4 KB
/
WiFiGeneric.cpp
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
/*
ESP8266WiFiGeneric.cpp - WiFi library for esp8266
Copyright (c) 2014 Ivan Grokhotkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Reworked on 28 Dec 2015 by Markus Sattler
*/
#include "WiFi.h"
#include "WiFiGeneric.h"
extern "C" {
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <string.h>
#include <esp_err.h>
#include <esp_wifi.h>
#include <esp_event_loop.h>
#include "lwip/ip_addr.h"
#include "lwip/opt.h"
#include "lwip/err.h"
#include "lwip/dns.h"
#include "esp_ipc.h"
} //extern "C"
#include "esp32-hal-log.h"
#include <vector>
#include "sdkconfig.h"
static xQueueHandle _network_event_queue;
static TaskHandle_t _network_event_task_handle = NULL;
static EventGroupHandle_t _network_event_group = NULL;
esp_err_t postToSysQueue(system_prov_event_t *data)
{
if (xQueueSend(_network_event_queue, &data, portMAX_DELAY) != pdPASS) {
log_w("Network Event Queue Send Failed!");
return ESP_FAIL;
}
return ESP_OK;
}
static void _network_event_task(void * arg){
system_prov_event_t *data;
for (;;) {
if(xQueueReceive(_network_event_queue, &data, portMAX_DELAY) == pdTRUE){
if(data->prov_event != NULL){
WiFiGenericClass::_eventCallback(arg, data->sys_event, data->prov_event);
free(data->sys_event);
free(data->prov_event);
} else {
WiFiGenericClass::_eventCallback(arg, data->sys_event, NULL);
}
free(data);
}
}
vTaskDelete(NULL);
_network_event_task_handle = NULL;
}
static esp_err_t _network_event_cb(void *arg, system_event_t *event){
system_prov_event_t *sys_prov_data = (system_prov_event_t *)malloc(sizeof(system_prov_event_t));
if(sys_prov_data == NULL) {
return ESP_FAIL;
}
sys_prov_data->sys_event = event;
sys_prov_data->prov_event = NULL;
if (postToSysQueue(sys_prov_data) != ESP_OK){
free(sys_prov_data);
return ESP_FAIL;
}
return ESP_OK;
}
static bool _start_network_event_task(){
if(!_network_event_group){
_network_event_group = xEventGroupCreate();
if(!_network_event_group){
log_e("Network Event Group Create Failed!");
return false;
}
xEventGroupSetBits(_network_event_group, WIFI_DNS_IDLE_BIT);
}
if(!_network_event_queue){
_network_event_queue = xQueueCreate(32, sizeof(system_prov_event_t));
if(!_network_event_queue){
log_e("Network Event Queue Create Failed!");
return false;
}
}
if(!_network_event_task_handle){
xTaskCreateUniversal(_network_event_task, "network_event", 4096, NULL, ESP_TASKD_EVENT_PRIO - 1, &_network_event_task_handle, CONFIG_ARDUINO_EVENT_RUNNING_CORE);
if(!_network_event_task_handle){
log_e("Network Event Task Start Failed!");
return false;
}
}
return esp_event_loop_init(&_network_event_cb, NULL) == ESP_OK;
}
void tcpipInit(){
static bool initialized = false;
if(!initialized && _start_network_event_task()){
initialized = true;
tcpip_adapter_init();
}
}
static bool lowLevelInitDone = false;
static bool wifiLowLevelInit(bool persistent){
if(!lowLevelInitDone){
tcpipInit();
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
esp_err_t err = esp_wifi_init(&cfg);
if(err){
log_e("esp_wifi_init %d", err);
return false;
}
if(!persistent){
esp_wifi_set_storage(WIFI_STORAGE_RAM);
}
lowLevelInitDone = true;
}
return true;
}
static bool wifiLowLevelDeinit(){
//deinit not working yet!
//esp_wifi_deinit();
return true;
}
static bool _esp_wifi_started = false;
static bool espWiFiStart(){
if(_esp_wifi_started){
return true;
}
esp_err_t err = esp_wifi_start();
if (err != ESP_OK) {
log_e("esp_wifi_start %d", err);
return false;
}
_esp_wifi_started = true;
system_event_t event;
event.event_id = SYSTEM_EVENT_WIFI_READY;
WiFiGenericClass::_eventCallback(nullptr, &event, NULL);
return true;
}
static bool espWiFiStop(){
esp_err_t err;
if(!_esp_wifi_started){
return true;
}
_esp_wifi_started = false;
err = esp_wifi_stop();
if(err){
log_e("Could not stop WiFi! %d", err);
_esp_wifi_started = true;
return false;
}
return wifiLowLevelDeinit();
}
// -----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------- Generic WiFi function -----------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
typedef struct WiFiEventCbList {
static wifi_event_id_t current_id;
wifi_event_id_t id;
WiFiEventCb cb;
WiFiEventFuncCb fcb;
WiFiEventSysCb scb;
WiFiProvEventCb provcb;
system_event_id_t event;
WiFiEventCbList() : id(current_id++), cb(NULL), fcb(NULL), scb(NULL), provcb(NULL), event(SYSTEM_EVENT_WIFI_READY) {}
} WiFiEventCbList_t;
wifi_event_id_t WiFiEventCbList::current_id = 1;
// arduino dont like std::vectors move static here
static std::vector<WiFiEventCbList_t> cbEventList;
bool WiFiGenericClass::_persistent = true;
bool WiFiGenericClass::_long_range = false;
wifi_mode_t WiFiGenericClass::_forceSleepLastMode = WIFI_MODE_NULL;
WiFiGenericClass::WiFiGenericClass()
{
}
int WiFiGenericClass::setStatusBits(int bits){
if(!_network_event_group){
return 0;
}
return xEventGroupSetBits(_network_event_group, bits);
}
int WiFiGenericClass::clearStatusBits(int bits){
if(!_network_event_group){
return 0;
}
return xEventGroupClearBits(_network_event_group, bits);
}
int WiFiGenericClass::getStatusBits(){
if(!_network_event_group){
return 0;
}
return xEventGroupGetBits(_network_event_group);
}
int WiFiGenericClass::waitStatusBits(int bits, uint32_t timeout_ms){
if(!_network_event_group){
return 0;
}
return xEventGroupWaitBits(
_network_event_group, // The event group being tested.
bits, // The bits within the event group to wait for.
pdFALSE, // BIT_0 and BIT_4 should be cleared before returning.
pdTRUE, // Don't wait for both bits, either bit will do.
timeout_ms / portTICK_PERIOD_MS ) & bits; // Wait a maximum of 100ms for either bit to be set.
}
/**
* set callback function
* @param cbEvent WiFiEventCb
* @param event optional filter (WIFI_EVENT_MAX is all events)
*/
wifi_event_id_t WiFiGenericClass::onEvent(WiFiProvEventCb cbEvent, system_event_id_t event)
{
if(!cbEvent){
return 0;
}
WiFiEventCbList_t newEventHandler;
newEventHandler.cb = NULL;
newEventHandler.fcb = NULL;
newEventHandler.scb = NULL;
newEventHandler.provcb = cbEvent;
newEventHandler.event = event;
cbEventList.push_back(newEventHandler);
return newEventHandler.id;
}
wifi_event_id_t WiFiGenericClass::onEvent(WiFiEventCb cbEvent, system_event_id_t event)
{
if(!cbEvent) {
return 0;
}
WiFiEventCbList_t newEventHandler;
newEventHandler.cb = cbEvent;
newEventHandler.fcb = NULL;
newEventHandler.scb = NULL;
newEventHandler.provcb = NULL;
newEventHandler.event = event;
cbEventList.push_back(newEventHandler);
return newEventHandler.id;
}
wifi_event_id_t WiFiGenericClass::onEvent(WiFiEventFuncCb cbEvent, system_event_id_t event)
{
if(!cbEvent) {
return 0;
}
WiFiEventCbList_t newEventHandler;
newEventHandler.cb = NULL;
newEventHandler.fcb = cbEvent;
newEventHandler.scb = NULL;
newEventHandler.provcb = NULL;
newEventHandler.event = event;
cbEventList.push_back(newEventHandler);
return newEventHandler.id;
}
wifi_event_id_t WiFiGenericClass::onEvent(WiFiEventSysCb cbEvent, system_event_id_t event)
{
if(!cbEvent) {
return 0;
}
WiFiEventCbList_t newEventHandler;
newEventHandler.cb = NULL;
newEventHandler.fcb = NULL;
newEventHandler.scb = cbEvent;
newEventHandler.provcb = NULL;
newEventHandler.event = event;
cbEventList.push_back(newEventHandler);
return newEventHandler.id;
}
/**
* removes a callback form event handler
* @param cbEvent WiFiEventCb
* @param event optional filter (WIFI_EVENT_MAX is all events)
*/
void WiFiGenericClass::removeEvent(WiFiEventCb cbEvent, system_event_id_t event)
{
if(!cbEvent) {
return;
}
for(uint32_t i = 0; i < cbEventList.size(); i++) {
WiFiEventCbList_t entry = cbEventList[i];
if(entry.cb == cbEvent && entry.event == event) {
cbEventList.erase(cbEventList.begin() + i);
}
}
}
void WiFiGenericClass::removeEvent(WiFiEventSysCb cbEvent, system_event_id_t event)
{
if(!cbEvent) {
return;
}
for(uint32_t i = 0; i < cbEventList.size(); i++) {
WiFiEventCbList_t entry = cbEventList[i];
if(entry.scb == cbEvent && entry.event == event) {
cbEventList.erase(cbEventList.begin() + i);
}
}
}
void WiFiGenericClass::removeEvent(wifi_event_id_t id)
{
for(uint32_t i = 0; i < cbEventList.size(); i++) {
WiFiEventCbList_t entry = cbEventList[i];
if(entry.id == id) {
cbEventList.erase(cbEventList.begin() + i);
}
}
}
/**
* callback for WiFi events
* @param arg
*/
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
const char * system_event_names[] = { "WIFI_READY", "SCAN_DONE", "STA_START", "STA_STOP", "STA_CONNECTED", "STA_DISCONNECTED", "STA_AUTHMODE_CHANGE", "STA_GOT_IP", "STA_LOST_IP", "STA_WPS_ER_SUCCESS", "STA_WPS_ER_FAILED", "STA_WPS_ER_TIMEOUT", "STA_WPS_ER_PIN", "STA_WPS_ER_PBC_OVERLAP", "AP_START", "AP_STOP", "AP_STACONNECTED", "AP_STADISCONNECTED", "AP_STAIPASSIGNED", "AP_PROBEREQRECVED", "GOT_IP6", "ETH_START", "ETH_STOP", "ETH_CONNECTED", "ETH_DISCONNECTED", "ETH_GOT_IP", "MAX"};
#endif
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_WARN
const char * system_event_reasons[] = { "UNSPECIFIED", "AUTH_EXPIRE", "AUTH_LEAVE", "ASSOC_EXPIRE", "ASSOC_TOOMANY", "NOT_AUTHED", "NOT_ASSOCED", "ASSOC_LEAVE", "ASSOC_NOT_AUTHED", "DISASSOC_PWRCAP_BAD", "DISASSOC_SUPCHAN_BAD", "UNSPECIFIED", "IE_INVALID", "MIC_FAILURE", "4WAY_HANDSHAKE_TIMEOUT", "GROUP_KEY_UPDATE_TIMEOUT", "IE_IN_4WAY_DIFFERS", "GROUP_CIPHER_INVALID", "PAIRWISE_CIPHER_INVALID", "AKMP_INVALID", "UNSUPP_RSN_IE_VERSION", "INVALID_RSN_IE_CAP", "802_1X_AUTH_FAILED", "CIPHER_SUITE_REJECTED", "BEACON_TIMEOUT", "NO_AP_FOUND", "AUTH_FAIL", "ASSOC_FAIL", "HANDSHAKE_TIMEOUT", "CONNECTION_FAIL" };
#define reason2str(r) ((r>176)?system_event_reasons[r-176]:system_event_reasons[r-1])
#endif
esp_err_t WiFiGenericClass::_eventCallback(void *arg, system_event_t *event, wifi_prov_event_t *prov_event)
{
if(WiFi.isProvEnabled()) {
wifi_prov_mgr_event_handler(arg,event);
}
if(event->event_id < 26) {
log_d("Event: %d - %s", event->event_id, system_event_names[event->event_id]);
}
if(event->event_id == SYSTEM_EVENT_SCAN_DONE) {
WiFiScanClass::_scanDone();
} else if(event->event_id == SYSTEM_EVENT_STA_START) {
WiFiSTAClass::_setStatus(WL_DISCONNECTED);
setStatusBits(STA_STARTED_BIT);
tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_STA, WiFiSTAClass::_hostname.c_str());
} else if(event->event_id == SYSTEM_EVENT_STA_STOP) {
WiFiSTAClass::_setStatus(WL_NO_SHIELD);
clearStatusBits(STA_STARTED_BIT | STA_CONNECTED_BIT | STA_HAS_IP_BIT | STA_HAS_IP6_BIT);
} else if(event->event_id == SYSTEM_EVENT_STA_CONNECTED) {
WiFiSTAClass::_setStatus(WL_IDLE_STATUS);
setStatusBits(STA_CONNECTED_BIT);
} else if(event->event_id == SYSTEM_EVENT_STA_DISCONNECTED) {
uint8_t reason = event->event_info.disconnected.reason;
log_w("Reason: %u - %s", reason, reason2str(reason));
if(reason == WIFI_REASON_NO_AP_FOUND) {
WiFiSTAClass::_setStatus(WL_NO_SSID_AVAIL);
} else if(reason == WIFI_REASON_AUTH_FAIL || reason == WIFI_REASON_ASSOC_FAIL) {
WiFiSTAClass::_setStatus(WL_CONNECT_FAILED);
} else if(reason == WIFI_REASON_BEACON_TIMEOUT || reason == WIFI_REASON_HANDSHAKE_TIMEOUT) {
WiFiSTAClass::_setStatus(WL_CONNECTION_LOST);
} else if(reason == WIFI_REASON_AUTH_EXPIRE) {
} else {
WiFiSTAClass::_setStatus(WL_DISCONNECTED);
}
clearStatusBits(STA_CONNECTED_BIT | STA_HAS_IP_BIT | STA_HAS_IP6_BIT);
if(((reason == WIFI_REASON_AUTH_EXPIRE) ||
(reason >= WIFI_REASON_BEACON_TIMEOUT && reason != WIFI_REASON_AUTH_FAIL)) &&
WiFi.getAutoReconnect())
{
WiFi.disconnect();
WiFi.begin();
}
} else if(event->event_id == SYSTEM_EVENT_STA_GOT_IP) {
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
uint8_t * ip = (uint8_t *)&(event->event_info.got_ip.ip_info.ip.addr);
uint8_t * mask = (uint8_t *)&(event->event_info.got_ip.ip_info.netmask.addr);
uint8_t * gw = (uint8_t *)&(event->event_info.got_ip.ip_info.gw.addr);
log_d("STA IP: %u.%u.%u.%u, MASK: %u.%u.%u.%u, GW: %u.%u.%u.%u",
ip[0], ip[1], ip[2], ip[3],
mask[0], mask[1], mask[2], mask[3],
gw[0], gw[1], gw[2], gw[3]);
#endif
WiFiSTAClass::_setStatus(WL_CONNECTED);
setStatusBits(STA_HAS_IP_BIT | STA_CONNECTED_BIT);
} else if(event->event_id == SYSTEM_EVENT_STA_LOST_IP) {
WiFiSTAClass::_setStatus(WL_IDLE_STATUS);
clearStatusBits(STA_HAS_IP_BIT);
} else if(event->event_id == SYSTEM_EVENT_AP_START) {
setStatusBits(AP_STARTED_BIT);
} else if(event->event_id == SYSTEM_EVENT_AP_STOP) {
clearStatusBits(AP_STARTED_BIT | AP_HAS_CLIENT_BIT);
} else if(event->event_id == SYSTEM_EVENT_AP_STACONNECTED) {
setStatusBits(AP_HAS_CLIENT_BIT);
} else if(event->event_id == SYSTEM_EVENT_AP_STADISCONNECTED) {
wifi_sta_list_t clients;
if(esp_wifi_ap_get_sta_list(&clients) != ESP_OK || !clients.num){
clearStatusBits(AP_HAS_CLIENT_BIT);
}
} else if(event->event_id == SYSTEM_EVENT_ETH_START) {
setStatusBits(ETH_STARTED_BIT);
} else if(event->event_id == SYSTEM_EVENT_ETH_STOP) {
clearStatusBits(ETH_STARTED_BIT | ETH_CONNECTED_BIT | ETH_HAS_IP_BIT | ETH_HAS_IP6_BIT);
} else if(event->event_id == SYSTEM_EVENT_ETH_CONNECTED) {
setStatusBits(ETH_CONNECTED_BIT);
} else if(event->event_id == SYSTEM_EVENT_ETH_DISCONNECTED) {
clearStatusBits(ETH_CONNECTED_BIT | ETH_HAS_IP_BIT | ETH_HAS_IP6_BIT);
} else if(event->event_id == SYSTEM_EVENT_ETH_GOT_IP) {
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
uint8_t * ip = (uint8_t *)&(event->event_info.got_ip.ip_info.ip.addr);
uint8_t * mask = (uint8_t *)&(event->event_info.got_ip.ip_info.netmask.addr);
uint8_t * gw = (uint8_t *)&(event->event_info.got_ip.ip_info.gw.addr);
log_d("ETH IP: %u.%u.%u.%u, MASK: %u.%u.%u.%u, GW: %u.%u.%u.%u",
ip[0], ip[1], ip[2], ip[3],
mask[0], mask[1], mask[2], mask[3],
gw[0], gw[1], gw[2], gw[3]);
#endif
setStatusBits(ETH_CONNECTED_BIT | ETH_HAS_IP_BIT);
} else if(event->event_id == SYSTEM_EVENT_GOT_IP6) {
if(event->event_info.got_ip6.if_index == TCPIP_ADAPTER_IF_AP){
setStatusBits(AP_HAS_IP6_BIT);
} else if(event->event_info.got_ip6.if_index == TCPIP_ADAPTER_IF_STA){
setStatusBits(STA_CONNECTED_BIT | STA_HAS_IP6_BIT);
} else if(event->event_info.got_ip6.if_index == TCPIP_ADAPTER_IF_ETH){
setStatusBits(ETH_CONNECTED_BIT | ETH_HAS_IP6_BIT);
}
}
for(uint32_t i = 0; i < cbEventList.size(); i++) {
WiFiEventCbList_t entry = cbEventList[i];
if(entry.cb || entry.fcb || entry.scb) {
if(entry.event == (system_event_id_t) event->event_id || entry.event == SYSTEM_EVENT_MAX) {
if(entry.cb) {
entry.cb((system_event_id_t) event->event_id);
} else if(entry.fcb) {
entry.fcb((system_event_id_t) event->event_id, (system_event_info_t) event->event_info);
} else {
entry.scb(event);
}
}
}
if(entry.provcb) {
entry.provcb(event,prov_event);
}
}
return ESP_OK;
}
/**
* Return the current channel associated with the network
* @return channel (1-13)
*/
int32_t WiFiGenericClass::channel(void)
{
uint8_t primaryChan = 0;
wifi_second_chan_t secondChan = WIFI_SECOND_CHAN_NONE;
if(!lowLevelInitDone){
return primaryChan;
}
esp_wifi_get_channel(&primaryChan, &secondChan);
return primaryChan;
}
/**
* store WiFi config in SDK flash area
* @param persistent
*/
void WiFiGenericClass::persistent(bool persistent)
{
_persistent = persistent;
}
/**
* enable WiFi long range mode
* @param enable
*/
void WiFiGenericClass::enableLongRange(bool enable)
{
_long_range = enable;
}
/**
* set new mode
* @param m WiFiMode_t
*/
bool WiFiGenericClass::mode(wifi_mode_t m)
{
wifi_mode_t cm = getMode();
if(cm == m) {
return true;
}
if(!cm && m){
if(!wifiLowLevelInit(_persistent)){
return false;
}
} else if(cm && !m){
return espWiFiStop();
}
esp_err_t err;
err = esp_wifi_set_mode(m);
if(err){
log_e("Could not set mode! %d", err);
return false;
}
if(_long_range){
if(m & WIFI_MODE_STA){
err = esp_wifi_set_protocol(WIFI_IF_STA, WIFI_PROTOCOL_LR);
if(err != ESP_OK){
log_e("Could not enable long range on STA! %d", err);
return false;
}
}
if(m & WIFI_MODE_AP){
err = esp_wifi_set_protocol(WIFI_IF_AP, WIFI_PROTOCOL_LR);
if(err != ESP_OK){
log_e("Could not enable long range on AP! %d", err);
return false;
}
}
}
if(!espWiFiStart()){
return false;
}
return true;
}
/**
* get WiFi mode
* @return WiFiMode
*/
wifi_mode_t WiFiGenericClass::getMode()
{
if(!lowLevelInitDone || !_esp_wifi_started){
return WIFI_MODE_NULL;
}
wifi_mode_t mode;
if(esp_wifi_get_mode(&mode) == ESP_ERR_WIFI_NOT_INIT){
log_w("WiFi not started");
return WIFI_MODE_NULL;
}
return mode;
}
/**
* control STA mode
* @param enable bool
* @return ok
*/
bool WiFiGenericClass::enableSTA(bool enable)
{
wifi_mode_t currentMode = getMode();
bool isEnabled = ((currentMode & WIFI_MODE_STA) != 0);
if(isEnabled != enable) {
if(enable) {
return mode((wifi_mode_t)(currentMode | WIFI_MODE_STA));
}
return mode((wifi_mode_t)(currentMode & (~WIFI_MODE_STA)));
}
return true;
}
/**
* control AP mode
* @param enable bool
* @return ok
*/
bool WiFiGenericClass::enableAP(bool enable)
{
wifi_mode_t currentMode = getMode();
bool isEnabled = ((currentMode & WIFI_MODE_AP) != 0);
if(isEnabled != enable) {
if(enable) {
return mode((wifi_mode_t)(currentMode | WIFI_MODE_AP));
}
return mode((wifi_mode_t)(currentMode & (~WIFI_MODE_AP)));
}
return true;
}
/**
* control modem sleep when only in STA mode
* @param enable bool
* @return ok
*/
bool WiFiGenericClass::setSleep(bool enable)
{
if((getMode() & WIFI_MODE_STA) == 0){
log_w("STA has not been started");
return false;
}
return esp_wifi_set_ps(enable?WIFI_PS_MIN_MODEM:WIFI_PS_NONE) == ESP_OK;
}
/**
* control modem sleep when only in STA mode
* @param mode wifi_ps_type_t
* @return ok
*/
bool WiFiGenericClass::setSleep(wifi_ps_type_t mode)
{
if((getMode() & WIFI_MODE_STA) == 0){
log_w("STA has not been started");
return false;
}
return esp_wifi_set_ps(mode) == ESP_OK;
}
/**
* get modem sleep enabled
* @return true if modem sleep is enabled
*/
bool WiFiGenericClass::getSleep()
{
wifi_ps_type_t ps;
if((getMode() & WIFI_MODE_STA) == 0){
log_w("STA has not been started");
return false;
}
if(esp_wifi_get_ps(&ps) == ESP_OK){
return ps == WIFI_PS_MIN_MODEM;
}
return false;
}
/**
* control wifi tx power
* @param power enum maximum wifi tx power
* @return ok
*/
bool WiFiGenericClass::setTxPower(wifi_power_t power){
if((getStatusBits() & (STA_STARTED_BIT | AP_STARTED_BIT)) == 0){
log_w("Neither AP or STA has been started");
return false;
}
return esp_wifi_set_max_tx_power(power) == ESP_OK;
}
wifi_power_t WiFiGenericClass::getTxPower(){
int8_t power;
if((getStatusBits() & (STA_STARTED_BIT | AP_STARTED_BIT)) == 0){
log_w("Neither AP or STA has been started");
return WIFI_POWER_19_5dBm;
}
if(esp_wifi_get_max_tx_power(&power)){
return WIFI_POWER_19_5dBm;
}
return (wifi_power_t)power;
}
// -----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------ Generic Network function ---------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
/**
* DNS callback
* @param name
* @param ipaddr
* @param callback_arg
*/
static void wifi_dns_found_callback(const char *name, const ip_addr_t *ipaddr, void *callback_arg)
{
if(ipaddr) {
(*reinterpret_cast<IPAddress*>(callback_arg)) = ipaddr->u_addr.ip4.addr;
}
xEventGroupSetBits(_network_event_group, WIFI_DNS_DONE_BIT);
}
/**
* Resolve the given hostname to an IP address.
* @param aHostname Name to be resolved
* @param aResult IPAddress structure to store the returned IP address
* @return 1 if aIPAddrString was successfully converted to an IP address,
* else error code
*/
int WiFiGenericClass::hostByName(const char* aHostname, IPAddress& aResult)
{
ip_addr_t addr;
aResult = static_cast<uint32_t>(0);
waitStatusBits(WIFI_DNS_IDLE_BIT, 16000);
clearStatusBits(WIFI_DNS_IDLE_BIT | WIFI_DNS_DONE_BIT);
err_t err = dns_gethostbyname(aHostname, &addr, &wifi_dns_found_callback, &aResult);
if(err == ERR_OK && addr.u_addr.ip4.addr) {
aResult = addr.u_addr.ip4.addr;
} else if(err == ERR_INPROGRESS) {
waitStatusBits(WIFI_DNS_DONE_BIT, 15000); //real internal timeout in lwip library is 14[s]
clearStatusBits(WIFI_DNS_DONE_BIT);
}
setStatusBits(WIFI_DNS_IDLE_BIT);
if((uint32_t)aResult == 0){
log_e("DNS Failed for %s", aHostname);
}
return (uint32_t)aResult != 0;
}
IPAddress WiFiGenericClass::calculateNetworkID(IPAddress ip, IPAddress subnet) {
IPAddress networkID;
for (size_t i = 0; i < 4; i++)
networkID[i] = subnet[i] & ip[i];
return networkID;
}
IPAddress WiFiGenericClass::calculateBroadcast(IPAddress ip, IPAddress subnet) {
IPAddress broadcastIp;
for (int i = 0; i < 4; i++)
broadcastIp[i] = ~subnet[i] | ip[i];
return broadcastIp;
}
uint8_t WiFiGenericClass::calculateSubnetCIDR(IPAddress subnetMask) {
uint8_t CIDR = 0;
for (uint8_t i = 0; i < 4; i++) {
if (subnetMask[i] == 0x80) // 128
CIDR += 1;
else if (subnetMask[i] == 0xC0) // 192
CIDR += 2;
else if (subnetMask[i] == 0xE0) // 224
CIDR += 3;
else if (subnetMask[i] == 0xF0) // 242
CIDR += 4;
else if (subnetMask[i] == 0xF8) // 248
CIDR += 5;
else if (subnetMask[i] == 0xFC) // 252
CIDR += 6;
else if (subnetMask[i] == 0xFE) // 254
CIDR += 7;
else if (subnetMask[i] == 0xFF) // 255
CIDR += 8;
}
return CIDR;
}