forked from philippe44/squeezelite-esp32
-
Notifications
You must be signed in to change notification settings - Fork 99
/
wifi_manager.c
1646 lines (1438 loc) · 58.7 KB
/
wifi_manager.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
/*
Copyright (c) 2017-2019 Tony Pottier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@file wifi_manager.c
@author Tony Pottier
@brief Defines all functions necessary for esp32 to connect to a wifi/scan wifis
Contains the freeRTOS task and all necessary support
@see https://idyl.io
@see https://github.com/tonyp7/esp32-wifi-manager
*/
#include "wifi_manager.h"
#include "platform_esp32.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "dns_server.h"
#include "esp_system.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include <esp_event.h>
#include "esp_event_loop.h"
#include "tcpip_adapter.h"
// IDF-V4++ #include "esp_netif.h"
#include "esp_event.h"
#include "esp_wifi.h"
#include "esp_wifi_types.h"
#include "esp_log.h"
#include "nvs.h"
#include "nvs_flash.h"
#include "mdns.h"
#include "lwip/api.h"
#include "lwip/err.h"
#include "lwip/netdb.h"
#include "lwip/ip4_addr.h"
#include "esp_ota_ops.h"
#include "esp_app_format.h"
#include "cJSON.h"
#include "platform_config.h"
#include "trace.h"
#include "cmd_system.h"
#include "messaging.h"
#include "bt_app_core.h"
#include "http_server_handlers.h"
#include "monitor.h"
#include "globdefs.h"
#ifndef CONFIG_SQUEEZELITE_ESP32_RELEASE_URL
#pragma message "Defaulting release url"
#define CONFIG_SQUEEZELITE_ESP32_RELEASE_URL "https://github.com/sle118/squeezelite-esp32/releases"
#endif
#define STR_OR_BLANK(p) p==NULL?"":p
BaseType_t wifi_manager_task;
/* objects used to manipulate the main queue of events */
QueueHandle_t wifi_manager_queue;
SemaphoreHandle_t wifi_manager_json_mutex = NULL;
SemaphoreHandle_t wifi_manager_sta_ip_mutex = NULL;
char *wifi_manager_sta_ip = NULL;
#define STA_IP_LEN sizeof(char) * IP4ADDR_STRLEN_MAX
bool bHasConnected=false;
uint16_t ap_num = MAX_AP_NUM;
wifi_ap_record_t *accessp_records=NULL;
cJSON * accessp_cjson=NULL;
char *ip_info_json = NULL;
char * release_url=NULL;
cJSON * ip_info_cjson=NULL;
wifi_config_t* wifi_manager_config_sta = NULL;
static void (*chained_notify)(in_addr_t, u16_t, u16_t);
static int32_t total_connected_time=0;
static int64_t last_connected=0;
static uint16_t num_disconnect=0;
static char lms_server_ip[IP4ADDR_STRLEN_MAX]={0};
static uint16_t lms_server_port=0;
static uint16_t lms_server_cport=0;
void (**cb_ptr_arr)(void*) = NULL;
/* @brief tag used for ESP serial console messages */
static const char TAG[] = "wifi_manager";
/* @brief task handle for the main wifi_manager task */
static TaskHandle_t task_wifi_manager = NULL;
/**
* The actual WiFi settings in use
*/
//struct wifi_settings_t wifi_settings = {
// .sta_only = DEFAULT_STA_ONLY,
// .sta_power_save = DEFAULT_STA_POWER_SAVE,
// .sta_static_ip = 0
//};
/* wifi scanner config */
wifi_scan_config_t scan_config = {
.ssid = 0,
.bssid = 0,
.channel = 0,
.show_hidden = true
};
const char wifi_manager_nvs_namespace[] = "config";
EventGroupHandle_t wifi_manager_event_group;
/* @brief indicate that the ESP32 is currently connected. */
const int WIFI_MANAGER_WIFI_CONNECTED_BIT = BIT0;
const int WIFI_MANAGER_AP_STA_CONNECTED_BIT = BIT1;
/* @brief Set automatically once the SoftAP is started */
const int WIFI_MANAGER_AP_STARTED_BIT = BIT2;
/* @brief When set, means a client requested to connect to an access point.*/
const int WIFI_MANAGER_REQUEST_STA_CONNECT_BIT = BIT3;
/* @brief This bit is set automatically as soon as a connection was lost */
const int WIFI_MANAGER_STA_DISCONNECT_BIT = BIT4;
/* @brief When set, means the wifi manager attempts to restore a previously saved connection at startup. */
const int WIFI_MANAGER_REQUEST_RESTORE_STA_BIT = BIT5;
/* @brief When set, means a client requested to disconnect from currently connected AP. */
const int WIFI_MANAGER_REQUEST_WIFI_DISCONNECT_BIT = BIT6;
/* @brief When set, means a scan is in progress */
const int WIFI_MANAGER_SCAN_BIT = BIT7;
/* @brief When set, means user requested for a disconnect */
const int WIFI_MANAGER_REQUEST_DISCONNECT_BIT = BIT8;
/* @brief When set, means user requested connecting to a new network and it failed */
const int WIFI_MANAGER_REQUEST_STA_CONNECT_FAILED_BIT = BIT9;
char * get_disconnect_code_desc(uint8_t reason){
switch (reason) {
case 1 : return "UNSPECIFIED"; break;
case 2 : return "AUTH_EXPIRE"; break;
case 3 : return "AUTH_LEAVE"; break;
case 4 : return "ASSOC_EXPIRE"; break;
case 5 : return "ASSOC_TOOMANY"; break;
case 6 : return "NOT_AUTHED"; break;
case 7 : return "NOT_ASSOCED"; break;
case 8 : return "ASSOC_LEAVE"; break;
case 9 : return "ASSOC_NOT_AUTHED"; break;
case 10 : return "DISASSOC_PWRCAP_BAD"; break;
case 11 : return "DISASSOC_SUPCHAN_BAD"; break;
case 12 : return "<n/a>"; break;
case 13 : return "IE_INVALID"; break;
case 14 : return "MIC_FAILURE"; break;
case 15 : return "4WAY_HANDSHAKE_TIMEOUT"; break;
case 16 : return "GROUP_KEY_UPDATE_TIMEOUT"; break;
case 17 : return "IE_IN_4WAY_DIFFERS"; break;
case 18 : return "GROUP_CIPHER_INVALID"; break;
case 19 : return "PAIRWISE_CIPHER_INVALID"; break;
case 20 : return "AKMP_INVALID"; break;
case 21 : return "UNSUPP_RSN_IE_VERSION"; break;
case 22 : return "INVALID_RSN_IE_CAP"; break;
case 23 : return "802_1X_AUTH_FAILED"; break;
case 24 : return "CIPHER_SUITE_REJECTED"; break;
case 200 : return "BEACON_TIMEOUT"; break;
case 201 : return "NO_AP_FOUND"; break;
case 202 : return "AUTH_FAIL"; break;
case 203 : return "ASSOC_FAIL"; break;
case 204 : return "HANDSHAKE_TIMEOUT"; break;
default: return "UNKNOWN"; break;
}
return "";
}
void wifi_manager_update_status(){
wifi_manager_send_message(ORDER_UPDATE_STATUS,NULL);
}
void set_host_name(){
esp_err_t err;
ESP_LOGD(TAG, "Retrieving host name from nvs");
char * host_name = (char * )config_alloc_get(NVS_TYPE_STR, "host_name");
if(host_name ==NULL){
ESP_LOGE(TAG, "Could not retrieve host name from nvs");
}
else {
ESP_LOGD(TAG, "Setting host name to : %s",host_name);
if((err=tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_STA, host_name)) !=ESP_OK){
ESP_LOGE(TAG, "Unable to set host name. Error: %s",esp_err_to_name(err));
}
// if((err=tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_AP, host_name)) !=ESP_OK){
// ESP_LOGE(TAG, "Unable to set host name. Error: %s",esp_err_to_name(err));
// }
free(host_name);
}
}
bool isGroupBitSet(uint8_t bit){
EventBits_t uxBits= xEventGroupGetBits(wifi_manager_event_group);
return (uxBits & bit);
}
void wifi_manager_scan_async(){
wifi_manager_send_message(ORDER_START_WIFI_SCAN, NULL);
}
void wifi_manager_disconnect_async(){
wifi_manager_send_message(ORDER_DISCONNECT_STA, NULL);
//xEventGroupSetBits(wifi_manager_event_group, WIFI_MANAGER_REQUEST_WIFI_DISCONNECT_BIT); TODO: delete
}
void wifi_manager_reboot_ota(char * url){
if(url == NULL){
wifi_manager_send_message(ORDER_RESTART_OTA, NULL);
}
else {
wifi_manager_send_message(ORDER_RESTART_OTA_URL,strdup(url) );
}
}
void wifi_manager_reboot(reboot_type_t rtype){
switch (rtype) {
case OTA:
wifi_manager_send_message(ORDER_RESTART_OTA, NULL);
break;
case RECOVERY:
wifi_manager_send_message(ORDER_RESTART_RECOVERY, NULL);
break;
case RESTART:
wifi_manager_send_message(ORDER_RESTART, NULL);
break;
default:
ESP_LOGE(TAG,"Unknown reboot type %d", rtype);
break;
}
wifi_manager_send_message(ORDER_DISCONNECT_STA, NULL);
//xEventGroupSetBits(wifi_manager_event_group, WIFI_MANAGER_REQUEST_WIFI_DISCONNECT_BIT); TODO: delete
}
void wifi_manager_init_wifi(){
/* event handler and event group for the wifi driver */
ESP_LOGD(TAG, "Initializing wifi. Creating event group");
wifi_manager_event_group = xEventGroupCreate();
bHasConnected=false;
// Now Initialize the Wifi Stack
ESP_LOGD(TAG, "Initializing wifi. Initializing tcp_ip adapter");
tcpip_adapter_init();
ESP_LOGD(TAG, "Initializing wifi. Creating the default event loop");
ESP_ERROR_CHECK(esp_event_loop_create_default());
ESP_LOGD(TAG, "Initializing wifi. Getting default wifi configuration");
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_LOGD(TAG, "Initializing wifi. Initializing wifi. ");
ESP_ERROR_CHECK( esp_wifi_init(&cfg) );
ESP_LOGD(TAG, "Initializing wifi. Calling register handlers");
wifi_manager_register_handlers();
ESP_LOGD(TAG, "Initializing wifi. Setting WiFi storage as RAM");
ESP_ERROR_CHECK( esp_wifi_set_storage(WIFI_STORAGE_RAM) );
ESP_LOGD(TAG, "Initializing wifi. Setting WiFi mode to WIFI_MODE_NULL");
ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_NULL) );
ESP_LOGD(TAG, "Initializing wifi. Starting wifi");
ESP_ERROR_CHECK( esp_wifi_start() );
taskYIELD();
ESP_LOGD(TAG, "Initializing wifi. done");
}
void set_lms_server_details(in_addr_t ip, u16_t hport, u16_t cport){
strncpy(lms_server_ip,inet_ntoa(ip),sizeof(lms_server_ip));
ESP_LOGI(TAG,"LMS IP: %s, hport: %d, cport: %d",lms_server_ip, hport, cport);
lms_server_port = hport;
lms_server_cport = cport;
}
static void connect_notify(in_addr_t ip, u16_t hport, u16_t cport) {
set_lms_server_details(ip,hport,cport);
if (chained_notify) (*chained_notify)(ip, hport, cport);
wifi_manager_update_status();
}
void wifi_manager_start(){
/* memory allocation */
ESP_LOGD(TAG, "wifi_manager_start. Creating message queue");
wifi_manager_queue = xQueueCreate( 3, sizeof( queue_message) );
ESP_LOGD(TAG, "wifi_manager_start. Creating mutexes");
wifi_manager_json_mutex = xSemaphoreCreateMutex();
wifi_manager_sta_ip_mutex = xSemaphoreCreateMutex();
ESP_LOGD(TAG, "wifi_manager_start. Creating access point json structure");
accessp_cjson = NULL;
accessp_cjson = wifi_manager_clear_ap_list_json(&accessp_cjson);
ip_info_json = NULL;
ESP_LOGD(TAG, "wifi_manager_start. Creating status jcon structure");
ip_info_cjson = wifi_manager_clear_ip_info_json(&ip_info_cjson);
ESP_LOGD(TAG, "wifi_manager_start. Allocating memory for wifi configuration structure");
wifi_manager_config_sta = (wifi_config_t*)malloc(sizeof(wifi_config_t));
memset(wifi_manager_config_sta, 0x00, sizeof(wifi_config_t));
// memset(&wifi_settings, 0x00, sizeof(wifi_settings));
ESP_LOGD(TAG, "wifi_manager_start. Allocating memory for callback functions registration");
cb_ptr_arr = malloc( sizeof( sizeof( void (*)( void* ) )) * MESSAGE_CODE_COUNT);
for(int i=0; i<MESSAGE_CODE_COUNT; i++){
cb_ptr_arr[i] = NULL;
}
ESP_LOGD(TAG, "About to set the STA IP String to 0.0.0.0");
wifi_manager_sta_ip = (char*)malloc(STA_IP_LEN);
wifi_manager_safe_update_sta_ip_string(NULL);
ESP_LOGD(TAG, "Getting release url ");
char * release_url = (char * )config_alloc_get_default(NVS_TYPE_STR, "release_url", QUOTE(CONFIG_SQUEEZELITE_ESP32_RELEASE_URL), 0);
if(release_url == NULL){
ESP_LOGE(TAG, "Unable to retrieve the release url from nvs");
}
else {
ESP_LOGD(TAG, "Found release url %s", release_url);
}
chained_notify = server_notify;
server_notify = connect_notify;
ESP_LOGD(TAG, "About to call init wifi");
wifi_manager_init_wifi();
/* start wifi manager task */
ESP_LOGD(TAG, "Creating wifi manager task");
wifi_manager_task= xTaskCreate(&wifi_manager, "wifi_manager", 4096, NULL, WIFI_MANAGER_TASK_PRIORITY, &task_wifi_manager);
}
esp_err_t wifi_manager_save_sta_config(){
nvs_handle handle;
esp_err_t esp_err;
ESP_LOGD(TAG, "About to save config to flash");
if(wifi_manager_config_sta){
esp_err = nvs_open(wifi_manager_nvs_namespace, NVS_READWRITE, &handle);
if (esp_err != ESP_OK) {
ESP_LOGE(TAG, "Unable to open name namespace %s. Error %s", wifi_manager_nvs_namespace, esp_err_to_name(esp_err));
return esp_err;
}
esp_err = nvs_set_blob(handle, "ssid", wifi_manager_config_sta->sta.ssid, sizeof(wifi_manager_config_sta->sta.ssid));
if (esp_err != ESP_OK) {
ESP_LOGE(TAG, "Unable to save ssid in name namespace %s. Error %s", wifi_manager_nvs_namespace, esp_err_to_name(esp_err));
return esp_err;
}
esp_err = nvs_set_blob(handle, "password", wifi_manager_config_sta->sta.password, sizeof(wifi_manager_config_sta->sta.password));
if (esp_err != ESP_OK) {
ESP_LOGE(TAG, "Unable to save password in name namespace %s. Error %s", wifi_manager_nvs_namespace, esp_err_to_name(esp_err));
return esp_err;
}
// esp_err = nvs_set_blob(handle, "settings", &wifi_settings, sizeof(wifi_settings));
// if (esp_err != ESP_OK) {
// ESP_LOGE(TAG, "Unable to save wifi_settings in name namespace %s. Error %s", wifi_manager_nvs_namespace, esp_err_to_name(esp_err));
// return esp_err;
// }
esp_err = nvs_commit(handle);
if (esp_err != ESP_OK) {
ESP_LOGE(TAG, "Unable to commit changes. Error %s", esp_err_to_name(esp_err));
messaging_post_message(MESSAGING_ERROR,MESSAGING_CLASS_SYSTEM,"Unable to save wifi credentials. %s",esp_err_to_name(esp_err));
return esp_err;
}
nvs_close(handle);
ESP_LOGD(TAG, "wifi_manager_wrote wifi_sta_config: ssid:%s password:%s",wifi_manager_config_sta->sta.ssid,wifi_manager_config_sta->sta.password);
}
return ESP_OK;
}
bool wifi_manager_fetch_wifi_sta_config(){
nvs_handle handle;
esp_err_t esp_err;
ESP_LOGD(TAG, "Fetching wifi sta config.");
esp_err=nvs_open(wifi_manager_nvs_namespace, NVS_READONLY, &handle);
if(esp_err == ESP_OK){
if(wifi_manager_config_sta == NULL){
ESP_LOGD(TAG, "Allocating memory for structure.");
wifi_manager_config_sta = (wifi_config_t*)malloc(sizeof(wifi_config_t));
}
memset(wifi_manager_config_sta, 0x00, sizeof(wifi_config_t));
/* ssid */
ESP_LOGD(TAG, "Fetching value for ssid.");
size_t sz = sizeof(wifi_manager_config_sta->sta.ssid);
uint8_t *buff = (uint8_t*)malloc(sizeof(uint8_t) * sz);
memset(buff,0x00,sizeof(uint8_t) * sz);
esp_err = nvs_get_blob(handle, "ssid", buff, &sz);
if(esp_err != ESP_OK){
ESP_LOGD(TAG, "No ssid found in nvs.");
FREE_AND_NULL(buff);
nvs_close(handle);
return false;
}
memcpy(wifi_manager_config_sta->sta.ssid, buff, sizeof(wifi_manager_config_sta->sta.ssid));
FREE_AND_NULL(buff);
ESP_LOGD(TAG, "wifi_manager_fetch_wifi_sta_config: ssid:%s ",wifi_manager_config_sta->sta.ssid);
/* password */
sz = sizeof(wifi_manager_config_sta->sta.password);
buff = (uint8_t*)malloc(sizeof(uint8_t) * sz);
memset(buff,0x00,sizeof(uint8_t) * sz);
esp_err = nvs_get_blob(handle, "password", buff, &sz);
if(esp_err != ESP_OK){
// Don't take this as an error. This could be an opened access point?
ESP_LOGW(TAG, "No wifi password found in nvs");
}
else {
memcpy(wifi_manager_config_sta->sta.password, buff, sizeof(wifi_manager_config_sta->sta.password));
ESP_LOGD(TAG, "wifi_manager_fetch_wifi_sta_config: password:%s",wifi_manager_config_sta->sta.password);
}
FREE_AND_NULL(buff);
nvs_close(handle);
return wifi_manager_config_sta->sta.ssid[0] != '\0';
}
else{
ESP_LOGW(TAG, "wifi manager has no previous configuration. %s",esp_err_to_name(esp_err));
return false;
}
}
cJSON * wifi_manager_get_new_json(cJSON **old){
ESP_LOGV(TAG, "wifi_manager_get_new_json called");
cJSON * root=*old;
if(root!=NULL){
cJSON_Delete(root);
*old=NULL;
}
ESP_LOGV(TAG, "wifi_manager_get_new_json done");
return cJSON_CreateObject();
}
cJSON * wifi_manager_get_new_array_json(cJSON **old){
ESP_LOGV(TAG, "wifi_manager_get_new_array_json called");
cJSON * root=*old;
if(root!=NULL){
cJSON_Delete(root);
*old=NULL;
}
ESP_LOGV(TAG, "wifi_manager_get_new_array_json done");
return cJSON_CreateArray();
}
void wifi_manager_update_basic_info(){
if(wifi_manager_lock_json_buffer( portMAX_DELAY )){
monitor_gpio_t *mgpio= get_jack_insertion_gpio();
cJSON * voltage = cJSON_GetObjectItemCaseSensitive(ip_info_cjson, "Voltage");
if(voltage){
cJSON_SetNumberValue(voltage, battery_value_svc());
}
cJSON * bt_status = cJSON_GetObjectItemCaseSensitive(ip_info_cjson, "bt_status");
if(bt_status){
cJSON_SetNumberValue(bt_status, bt_app_source_get_a2d_state());
}
cJSON * bt_sub_status = cJSON_GetObjectItemCaseSensitive(ip_info_cjson, "bt_sub_status");
if(bt_sub_status){
cJSON_SetNumberValue(bt_sub_status, bt_app_source_get_media_state());
}
cJSON * jack = cJSON_GetObjectItemCaseSensitive(ip_info_cjson, "Jack");
if(jack){
jack->type=mgpio->gpio>=0 && jack_inserted_svc()?cJSON_True:cJSON_False;
}
cJSON * disconnect_count = cJSON_GetObjectItemCaseSensitive(ip_info_cjson, "disconnect_count");
if(disconnect_count){
cJSON_SetNumberValue(disconnect_count, num_disconnect);
}
cJSON * avg_conn_time = cJSON_GetObjectItemCaseSensitive(ip_info_cjson, "avg_conn_time");
if(avg_conn_time){
cJSON_SetNumberValue(avg_conn_time, num_disconnect>0?(total_connected_time/num_disconnect):0);
}
if(lms_server_cport>0){
cJSON * value = cJSON_GetObjectItemCaseSensitive(ip_info_cjson, "lms_cport");
if(value){
cJSON_SetNumberValue(value,lms_server_cport);
}
else {
cJSON_AddNumberToObject(ip_info_cjson,"lms_cport",lms_server_cport);
}
}
if(lms_server_port>0){
cJSON * value = cJSON_GetObjectItemCaseSensitive(ip_info_cjson, "lms_port");
if(value){
cJSON_SetNumberValue(value,lms_server_port);
}
else {
cJSON_AddNumberToObject(ip_info_cjson,"lms_port",lms_server_port);
}
}
if(strlen(lms_server_ip) >0){
cJSON * value = cJSON_GetObjectItemCaseSensitive(ip_info_cjson, "lms_ip");
if(!value){
// only create if it does not exist. Since we're creating a reference
// to a char buffer, updates to cJSON aren't needed
cJSON_AddItemToObject(ip_info_cjson, "lms_ip", cJSON_CreateStringReference(lms_server_ip));
}
}
wifi_manager_unlock_json_buffer();
}
}
cJSON * wifi_manager_get_basic_info(cJSON **old){
monitor_gpio_t *mgpio= get_jack_insertion_gpio();
const esp_app_desc_t* desc = esp_ota_get_app_description();
ESP_LOGV(TAG, "wifi_manager_get_basic_info called");
cJSON *root = wifi_manager_get_new_json(old);
cJSON_AddItemToObject(root, "project_name", cJSON_CreateString(desc->project_name));
#ifdef CONFIG_FW_PLATFORM_NAME
cJSON_AddItemToObject(root, "platform_name", cJSON_CreateString(CONFIG_FW_PLATFORM_NAME));
#endif
cJSON_AddItemToObject(root, "version", cJSON_CreateString(desc->version));
if(release_url !=NULL) cJSON_AddItemToObject(root, "release_url", cJSON_CreateString(release_url));
cJSON_AddNumberToObject(root,"recovery", is_recovery_running?1:0);
cJSON_AddBoolToObject(root, "Jack", mgpio->gpio>=0 && jack_inserted_svc() );
cJSON_AddNumberToObject(root,"Voltage", battery_value_svc());
cJSON_AddNumberToObject(root,"disconnect_count", num_disconnect );
cJSON_AddNumberToObject(root,"avg_conn_time", num_disconnect>0?(total_connected_time/num_disconnect):0 );
cJSON_AddNumberToObject(root,"bt_status", bt_app_source_get_a2d_state());
cJSON_AddNumberToObject(root,"bt_sub_status", bt_app_source_get_media_state());
#if CONFIG_I2C_LOCKED
cJSON_AddTrueToObject(root, "is_i2c_locked");
#else
cJSON_AddFalseToObject(root, "is_i2c_locked");
#endif
ESP_LOGV(TAG, "wifi_manager_get_basic_info done");
return root;
}
cJSON * wifi_manager_clear_ip_info_json(cJSON **old){
ESP_LOGV(TAG, "wifi_manager_clear_ip_info_json called");
cJSON *root = wifi_manager_get_basic_info(old);
ESP_LOGV(TAG, "wifi_manager_clear_ip_info_json done");
return root;
}
cJSON * wifi_manager_clear_ap_list_json(cJSON **old){
ESP_LOGV(TAG, "wifi_manager_clear_ap_list_json called");
cJSON *root = wifi_manager_get_new_array_json(old);
ESP_LOGV(TAG, "wifi_manager_clear_ap_list_json done");
return root;
}
void wifi_manager_generate_ip_info_json(update_reason_code_t update_reason_code){
ESP_LOGD(TAG, "wifi_manager_generate_ip_info_json called");
wifi_config_t *config = wifi_manager_get_wifi_sta_config();
ip_info_cjson = wifi_manager_get_basic_info(&ip_info_cjson);
cJSON_AddNumberToObject(ip_info_cjson, "urc", update_reason_code);
if(config){
if(update_reason_code == UPDATE_CONNECTION_OK || update_reason_code == UPDATE_LOST_CONNECTION || update_reason_code == UPDATE_FAILED_ATTEMPT){
cJSON_AddItemToObject(ip_info_cjson, "ssid", cJSON_CreateString((char *)config->sta.ssid));
}
if(update_reason_code == UPDATE_CONNECTION_OK){
/* rest of the information is copied after the ssid */
tcpip_adapter_ip_info_t ip_info;
ESP_ERROR_CHECK(tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_STA, &ip_info));
cJSON_AddItemToObject(ip_info_cjson, "ip", cJSON_CreateString(ip4addr_ntoa((ip4_addr_t *)&ip_info.ip)));
cJSON_AddItemToObject(ip_info_cjson, "netmask", cJSON_CreateString(ip4addr_ntoa((ip4_addr_t *)&ip_info.netmask)));
cJSON_AddItemToObject(ip_info_cjson, "gw", cJSON_CreateString(ip4addr_ntoa((ip4_addr_t *)&ip_info.gw)));
wifi_ap_record_t ap;
esp_wifi_sta_get_ap_info(&ap);
cJSON_AddItemToObject(ip_info_cjson, "rssi", cJSON_CreateNumber(ap.rssi));
}
}
ESP_LOGV(TAG, "wifi_manager_generate_ip_info_json done");
}
#define LOCAL_MAC_SIZE 20
char * get_mac_string(uint8_t mac[6]){
char * macStr=malloc(LOCAL_MAC_SIZE);
memset(macStr, 0x00, LOCAL_MAC_SIZE);
snprintf(macStr, LOCAL_MAC_SIZE,MACSTR, MAC2STR(mac));
return macStr;
}
void wifi_manager_generate_access_points_json(cJSON ** ap_list){
*ap_list = wifi_manager_get_new_array_json(ap_list);
if(*ap_list==NULL) return;
for(int i=0; i<ap_num;i++){
cJSON * ap = cJSON_CreateObject();
if(ap == NULL) {
ESP_LOGE(TAG, "Unable to allocate memory for access point entry #%d",i);
return;
}
cJSON * radio = cJSON_CreateObject();
if(radio == NULL) {
ESP_LOGE(TAG, "Unable to allocate memory for access point entry #%d",i);
cJSON_Delete(ap);
return;
}
wifi_ap_record_t ap_rec = accessp_records[i];
cJSON_AddNumberToObject(ap, "chan", ap_rec.primary);
cJSON_AddNumberToObject(ap, "rssi", ap_rec.rssi);
cJSON_AddNumberToObject(ap, "auth", ap_rec.authmode);
cJSON_AddItemToObject(ap, "ssid", cJSON_CreateString((char *)ap_rec.ssid));
char * bssid = get_mac_string(ap_rec.bssid);
cJSON_AddItemToObject(ap, "bssid", cJSON_CreateString(STR_OR_BLANK(bssid)));
FREE_AND_NULL(bssid);
cJSON_AddNumberToObject(radio, "b", ap_rec.phy_11b?1:0);
cJSON_AddNumberToObject(radio, "g", ap_rec.phy_11g?1:0);
cJSON_AddNumberToObject(radio, "n", ap_rec.phy_11n?1:0);
cJSON_AddNumberToObject(radio, "low_rate", ap_rec.phy_lr?1:0);
cJSON_AddItemToObject(ap,"radio", radio);
cJSON_AddItemToArray(*ap_list, ap);
char * ap_json = cJSON_PrintUnformatted(ap);
if(ap_json!=NULL){
ESP_LOGD(TAG, "New access point found: %s", ap_json);
free(ap_json);
}
}
char * ap_list_json = cJSON_PrintUnformatted(*ap_list);
if(ap_list_json!=NULL){
ESP_LOGV(TAG, "Full access point list: %s", ap_list_json);
free(ap_list_json);
}
}
bool wifi_manager_lock_sta_ip_string(TickType_t xTicksToWait){
if(wifi_manager_sta_ip_mutex){
if( xSemaphoreTake( wifi_manager_sta_ip_mutex, xTicksToWait ) == pdTRUE ) {
return true;
}
else{
return false;
}
}
else{
return false;
}
}
void wifi_manager_unlock_sta_ip_string(){
xSemaphoreGive( wifi_manager_sta_ip_mutex );
}
void wifi_manager_safe_update_sta_ip_string(struct ip4_addr * ip4){
if(wifi_manager_lock_sta_ip_string(portMAX_DELAY)){
strcpy(wifi_manager_sta_ip, ip4!=NULL?ip4addr_ntoa(ip4):"0.0.0.0");
ESP_LOGD(TAG, "Set STA IP String to: %s", wifi_manager_sta_ip);
wifi_manager_unlock_sta_ip_string();
}
}
char* wifi_manager_get_sta_ip_string(){
return wifi_manager_sta_ip;
}
bool wifi_manager_lock_json_buffer(TickType_t xTicksToWait){
ESP_LOGV(TAG, "Locking json buffer");
if(wifi_manager_json_mutex){
if( xSemaphoreTake( wifi_manager_json_mutex, xTicksToWait ) == pdTRUE ) {
ESP_LOGV(TAG, "Json buffer locked!");
return true;
}
else{
ESP_LOGE(TAG, "Semaphore take failed. Unable to lock json buffer mutex");
return false;
}
}
else{
ESP_LOGV(TAG, "Unable to lock json buffer mutex");
return false;
}
}
void wifi_manager_unlock_json_buffer(){
ESP_LOGV(TAG, "Unlocking json buffer!");
xSemaphoreGive( wifi_manager_json_mutex );
}
char* wifi_manager_alloc_get_ap_list_json(){
return cJSON_PrintUnformatted(accessp_cjson);
}
static void event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data){
if(event_base== WIFI_EVENT){
switch(event_id) {
case WIFI_EVENT_WIFI_READY:
ESP_LOGD(TAG, "WIFI_EVENT_WIFI_READY");
break;
case WIFI_EVENT_SCAN_DONE:
ESP_LOGD(TAG, "WIFI_EVENT_SCAN_DONE");
xEventGroupClearBits(wifi_manager_event_group, WIFI_MANAGER_SCAN_BIT);
wifi_manager_send_message(EVENT_SCAN_DONE, NULL);
break;
case WIFI_EVENT_STA_AUTHMODE_CHANGE:
ESP_LOGD(TAG, "WIFI_EVENT_STA_AUTHMODE_CHANGE");
// structwifi_event_sta_authmode_change_t
// Argument structure for WIFI_EVENT_STA_AUTHMODE_CHANGE event
//
// Public Members
//
// wifi_auth_mode_told_mode
// the old auth mode of AP
//
// wifi_auth_mode_tnew_mode
// the new auth mode of AP
break;
case WIFI_EVENT_AP_START:
ESP_LOGD(TAG, "WIFI_EVENT_AP_START");
xEventGroupSetBits(wifi_manager_event_group, WIFI_MANAGER_AP_STARTED_BIT);
break;
case WIFI_EVENT_AP_STOP:
ESP_LOGD(TAG, "WIFI_EVENT_AP_STOP");
break;
case WIFI_EVENT_AP_PROBEREQRECVED:{
// wifi_event_ap_probe_req_rx_t
// Argument structure for WIFI_EVENT_AP_PROBEREQRECVED event
//
// Public Members
//
// int rssi
// Received probe request signal strength
//
// uint8_t mac[6]
// MAC address of the station which send probe request
wifi_event_ap_probe_req_rx_t * s =(wifi_event_ap_probe_req_rx_t*)event_data;
char * mac = get_mac_string(s->mac);
ESP_LOGD(TAG, "WIFI_EVENT_AP_PROBEREQRECVED. RSSI: %d, MAC: %s",s->rssi, STR_OR_BLANK(mac));
FREE_AND_NULL(mac);
}
break;
case WIFI_EVENT_STA_WPS_ER_SUCCESS:
ESP_LOGD(TAG, "WIFI_EVENT_STA_WPS_ER_SUCCESS");
break;
case WIFI_EVENT_STA_WPS_ER_FAILED:
ESP_LOGD(TAG, "WIFI_EVENT_STA_WPS_ER_FAILED");
break;
case WIFI_EVENT_STA_WPS_ER_TIMEOUT:
ESP_LOGD(TAG, "WIFI_EVENT_STA_WPS_ER_TIMEOUT");
break;
case WIFI_EVENT_STA_WPS_ER_PIN:
ESP_LOGD(TAG, "WIFI_EVENT_STA_WPS_ER_PIN");
break;
case WIFI_EVENT_AP_STACONNECTED:{ /* a user disconnected from the SoftAP */
wifi_event_ap_staconnected_t * stac = (wifi_event_ap_staconnected_t *)event_data;
char * mac = get_mac_string(stac->mac);
ESP_LOGD(TAG, "WIFI_EVENT_AP_STACONNECTED. aid: %d, mac: %s",stac->aid,STR_OR_BLANK(mac));
FREE_AND_NULL(mac);
xEventGroupSetBits(wifi_manager_event_group, WIFI_MANAGER_AP_STA_CONNECTED_BIT);
}
break;
case WIFI_EVENT_AP_STADISCONNECTED:
ESP_LOGD(TAG, "WIFI_EVENT_AP_STADISCONNECTED");
xEventGroupClearBits(wifi_manager_event_group, WIFI_MANAGER_AP_STA_CONNECTED_BIT);
break;
case WIFI_EVENT_STA_START:
ESP_LOGD(TAG, "WIFI_EVENT_STA_START");
break;
case WIFI_EVENT_STA_STOP:
ESP_LOGD(TAG, "WIFI_EVENT_STA_STOP");
break;
case WIFI_EVENT_STA_CONNECTED:{
// structwifi_event_sta_connected_t
// Argument structure for WIFI_EVENT_STA_CONNECTED event
//
// Public Members
//
// uint8_t ssid[32]
// SSID of connected AP
//
// uint8_t ssid_len
// SSID length of connected AP
//
// uint8_t bssid[6]
// BSSID of connected AP
//
// uint8_t channel
// channel of connected AP
//
// wifi_auth_mode_tauthmode
// authentication mode used by AP
//, get_mac_string(EVENT_HANDLER_ARG_FIELD(wifi_event_ap_probe_req_rx_t, mac)));
ESP_LOGD(TAG, "WIFI_EVENT_STA_CONNECTED. ");
wifi_event_sta_connected_t * s =(wifi_event_sta_connected_t*)event_data;
char * bssid = get_mac_string(s->bssid);
char * ssid = strdup((char*)s->ssid);
ESP_LOGD(TAG, "WIFI_EVENT_STA_CONNECTED. Channel: %d, Access point: %s, BSSID: %s ", s->channel, STR_OR_BLANK(ssid), (bssid));
FREE_AND_NULL(bssid);
FREE_AND_NULL(ssid);
}
break;
case WIFI_EVENT_STA_DISCONNECTED:{
// structwifi_event_sta_disconnected_t
// Argument structure for WIFI_EVENT_STA_DISCONNECTED event
//
// Public Members
//
// uint8_t ssid[32]
// SSID of disconnected AP
//
// uint8_t ssid_len
// SSID length of disconnected AP
//
// uint8_t bssid[6]
// BSSID of disconnected AP
//
// uint8_t reason
// reason of disconnection
wifi_event_sta_disconnected_t * s =(wifi_event_sta_disconnected_t*)event_data;
char * bssid = get_mac_string(s->bssid);
ESP_LOGD(TAG, "WIFI_EVENT_STA_DISCONNECTED. From BSSID: %s, reason code: %d (%s)", STR_OR_BLANK(bssid),s->reason, get_disconnect_code_desc(s->reason));
FREE_AND_NULL(bssid);
if(last_connected>0) total_connected_time+=((esp_timer_get_time()-last_connected)/(1000*1000));
last_connected = 0;
num_disconnect++;
ESP_LOGW(TAG, "Wifi disconnected. Number of disconnects: %d, Average time connected: %d", num_disconnect, num_disconnect>0?(total_connected_time/num_disconnect):0);
/* if a DISCONNECT message is posted while a scan is in progress this scan will NEVER end, causing scan to never work again. For this reason SCAN_BIT is cleared too */
xEventGroupClearBits(wifi_manager_event_group, WIFI_MANAGER_WIFI_CONNECTED_BIT | WIFI_MANAGER_SCAN_BIT);
// We want to process this message asynchronously, so make sure we copy the event buffer
ESP_LOGD(TAG, "Preparing to trigger event EVENT_STA_DISCONNECTED ");
void * parm=malloc(sizeof(wifi_event_sta_disconnected_t));
memcpy(parm,event_data,sizeof(wifi_event_sta_disconnected_t));
ESP_LOGD(TAG, "Triggering EVENT_STA_DISCONNECTED ");
/* post disconnect event with reason code */
wifi_manager_send_message(EVENT_STA_DISCONNECTED, parm );
}
break;
default:
break;
}
}
else if(event_base== IP_EVENT){
switch (event_id) {
case IP_EVENT_STA_GOT_IP:{
// structip_event_got_ip_t
// tcpip_adapter_if_t if_index; /*!< Interface for which the event is received */
// tcpip_adapter_ip6_info_t ip6_info; /*!< IPv6 address of the interface */
// // Event structure for IP_EVENT_STA_GOT_IP, IP_EVENT_ETH_GOT_IP events
//
// Public Members
//
// tcpip_adapter_if_tif_index
// Interface for which the event is received
//
// tcpip_adapter_ip_info_t ip_info
// IP address, netmask, gatway IP address
//
// bool ip_changed
// Whether the assigned IP has changed or not
ip_event_got_ip_t * s =(ip_event_got_ip_t*)event_data;
//tcpip_adapter_if_t index = s->if_index;
const tcpip_adapter_ip_info_t *ip_info = &s->ip_info;
ESP_LOGI(TAG, "SYSTEM_EVENT_STA_GOT_IP. IP="IPSTR", Gateway="IPSTR", NetMask="IPSTR", %s",
IP2STR(&ip_info->ip),
IP2STR(&ip_info->gw),
IP2STR(&ip_info->netmask),
s->ip_changed?"Address was changed":"Address unchanged");
// todo: if ip address was changed, we probably need to restart, as all sockets
// will become abnormal
xEventGroupSetBits(wifi_manager_event_group, WIFI_MANAGER_WIFI_CONNECTED_BIT);
last_connected = esp_timer_get_time();
void * parm=malloc(sizeof(ip_event_got_ip_t));
memcpy(parm,event_data,sizeof(ip_event_got_ip_t));
wifi_manager_send_message(EVENT_STA_GOT_IP, parm );
}
break;
case IP_EVENT_STA_LOST_IP:
ESP_LOGD(TAG, "IP_EVENT_STA_LOST_IP");
break;
case IP_EVENT_AP_STAIPASSIGNED:
ESP_LOGD(TAG, "IP_EVENT_AP_STAIPASSIGNED");
break;
case IP_EVENT_GOT_IP6:
ESP_LOGD(TAG, "IP_EVENT_GOT_IP6");
break;
case IP_EVENT_ETH_GOT_IP:
ESP_LOGD(TAG, "IP_EVENT_ETH_GOT_IP");
break;
default:
break;
}
}
}
wifi_config_t* wifi_manager_get_wifi_sta_config(){
return wifi_manager_config_sta;
}
void wifi_manager_connect_async(){
/* in order to avoid a false positive on the front end app we need to quickly flush the ip json
* There'se a risk the front end sees an IP or a password error when in fact
* it's a remnant from a previous connection
*/
if(wifi_manager_lock_json_buffer( portMAX_DELAY )){
ip_info_cjson= wifi_manager_clear_ip_info_json(&ip_info_cjson);
wifi_manager_unlock_json_buffer();
}
wifi_manager_send_message(ORDER_CONNECT_STA, (void*)CONNECTION_REQUEST_USER);
}
char* wifi_manager_alloc_get_ip_info_json(){
return cJSON_PrintUnformatted(ip_info_cjson);
}
void wifi_manager_destroy(){
vTaskDelete(task_wifi_manager);
task_wifi_manager = NULL;
/* heap buffers */
free(ip_info_json);
free(release_url);
cJSON_Delete(ip_info_cjson);
cJSON_Delete(accessp_cjson);
ip_info_cjson=NULL;
accessp_cjson=NULL;
free(wifi_manager_sta_ip);
wifi_manager_sta_ip = NULL;
if(wifi_manager_config_sta){
free(wifi_manager_config_sta);
wifi_manager_config_sta = NULL;
}
/* RTOS objects */
vSemaphoreDelete(wifi_manager_json_mutex);
wifi_manager_json_mutex = NULL;
vSemaphoreDelete(wifi_manager_sta_ip_mutex);
wifi_manager_sta_ip_mutex = NULL;
vEventGroupDelete(wifi_manager_event_group);
wifi_manager_event_group = NULL;
vQueueDelete(wifi_manager_queue);
wifi_manager_queue = NULL;
}
void wifi_manager_filter_unique( wifi_ap_record_t * aplist, uint16_t * aps) {
int total_unique;
wifi_ap_record_t * first_free;
total_unique=*aps;
first_free=NULL;
for(int i=0; i<*aps-1;i++) {