-
Notifications
You must be signed in to change notification settings - Fork 7.3k
/
manager.c
1803 lines (1540 loc) · 60 KB
/
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
/*
* SPDX-FileCopyrightText: 2019-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <string.h>
#include <sys/param.h>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
#include <cJSON.h>
#include <esp_log.h>
#include <esp_err.h>
#include <esp_wifi.h>
#include <esp_timer.h>
#include <protocomm.h>
#include <protocomm_security0.h>
#include <protocomm_security1.h>
#include <protocomm_security2.h>
#include "wifi_provisioning_priv.h"
#define WIFI_PROV_MGR_VERSION "v1.1"
#define WIFI_PROV_STORAGE_BIT BIT0
#define WIFI_PROV_SETTING_BIT BIT1
#define MAX_SCAN_RESULTS CONFIG_WIFI_PROV_SCAN_MAX_ENTRIES
#define ACQUIRE_LOCK(mux) assert(xSemaphoreTake(mux, portMAX_DELAY) == pdTRUE)
#define RELEASE_LOCK(mux) assert(xSemaphoreGive(mux) == pdTRUE)
static const char *TAG = "wifi_prov_mgr";
ESP_EVENT_DEFINE_BASE(WIFI_PROV_EVENT);
ESP_EVENT_DEFINE_BASE(WIFI_PROV_MGR_PVT_EVENT);
typedef enum {
WIFI_PROV_STATE_IDLE,
WIFI_PROV_STATE_STARTING,
WIFI_PROV_STATE_STARTED,
WIFI_PROV_STATE_CRED_RECV,
WIFI_PROV_STATE_FAIL,
WIFI_PROV_STATE_SUCCESS,
WIFI_PROV_STATE_STOPPING
} wifi_prov_mgr_state_t;
typedef enum {
WIFI_PROV_MGR_STOP,
} wifi_prov_mgr_pvt_event_t;
/**
* @brief Structure for storing capabilities supported by
* the provisioning service
*/
struct wifi_prov_capabilities {
/* Security 0 is used */
bool no_sec;
/* Proof of Possession is not required for establishing session */
bool no_pop;
/* Provisioning doesn't stop on it's own after receiving Wi-Fi credentials
* instead application has to explicitly call wifi_prov_mgr_stop_provisioning() */
bool no_auto_stop;
};
/**
* @brief Structure for storing miscellaneous information about
* provisioning service that will be conveyed to clients
*/
struct wifi_prov_info {
const char *version;
struct wifi_prov_capabilities capabilities;
};
/**
* @brief Context data for provisioning manager
*/
struct wifi_prov_mgr_ctx {
/* Provisioning manager configuration */
wifi_prov_mgr_config_t mgr_config;
/* State of the provisioning service */
wifi_prov_mgr_state_t prov_state;
/* Provisioning scheme configuration */
void *prov_scheme_config;
/* Protocomm handle */
protocomm_t *pc;
/* Type of security to use with protocomm */
int security;
/* Pointer to security params */
const void* protocomm_sec_params;
/* Handle for Provisioning Auto Stop timer */
esp_timer_handle_t autostop_timer;
/* Handle for delayed Wi-Fi connection timer */
esp_timer_handle_t wifi_connect_timer;
/* Handle for delayed cleanup timer */
esp_timer_handle_t cleanup_delay_timer;
/* State of Wi-Fi Station */
wifi_prov_sta_state_t wifi_state;
/* Code for Wi-Fi station disconnection (if disconnected) */
wifi_prov_sta_fail_reason_t wifi_disconnect_reason;
/* Protocomm handlers for Wi-Fi configuration endpoint */
wifi_prov_config_handlers_t *wifi_prov_handlers;
/* Protocomm handlers for Wi-Fi scan endpoint */
wifi_prov_scan_handlers_t *wifi_scan_handlers;
/* Protocomm handlers for Wi-Fi ctrl endpoint */
wifi_ctrl_handlers_t *wifi_ctrl_handlers;
/* Count of used endpoint UUIDs */
unsigned int endpoint_uuid_used;
/* Provisioning service information */
struct wifi_prov_info mgr_info;
/* Application related information in JSON format */
cJSON *app_info_json;
/* Delay after which resources will be cleaned up asynchronously
* upon execution of wifi_prov_mgr_stop_provisioning() */
uint32_t cleanup_delay;
/* Wi-Fi scan parameters and state variables */
bool scanning;
uint8_t channels_per_group;
uint16_t curr_channel;
uint16_t ap_list_len[14]; // 14 entries corresponding to each channel
wifi_ap_record_t *ap_list[14];
wifi_ap_record_t *ap_list_sorted[MAX_SCAN_RESULTS];
wifi_scan_config_t scan_cfg;
};
/* Mutex to lock/unlock access to provisioning singleton
* context data. This is allocated only once on first init
* and never deleted as wifi_prov_mgr is a singleton */
static SemaphoreHandle_t prov_ctx_lock = NULL;
/* Pointer to provisioning context data */
static struct wifi_prov_mgr_ctx *prov_ctx;
/* This executes registered app_event_callback for a particular event
*
* NOTE : By the time this function returns, it is possible that
* the manager got de-initialized due to a call to wifi_prov_mgr_deinit()
* either inside the event callbacks or from another thread. Therefore
* post execution of execute_event_cb(), the validity of prov_ctx must
* always be checked. A cleaner way, to avoid this pitfall safely, would
* be to limit the usage of this function to only public APIs, and that
* too at the very end, just before returning.
*
* NOTE: This function should be called only after ensuring that the
* context is valid and the control mutex is locked. */
static void execute_event_cb(wifi_prov_cb_event_t event_id, void *event_data, size_t event_data_size)
{
ESP_LOGD(TAG, "execute_event_cb : %d", event_id);
if (prov_ctx) {
wifi_prov_cb_func_t app_cb = prov_ctx->mgr_config.app_event_handler.event_cb;
void *app_data = prov_ctx->mgr_config.app_event_handler.user_data;
wifi_prov_cb_func_t scheme_cb = prov_ctx->mgr_config.scheme_event_handler.event_cb;
void *scheme_data = prov_ctx->mgr_config.scheme_event_handler.user_data;
/* Release the mutex before executing the callbacks. This is done so that
* wifi_prov_mgr_event_handler() doesn't stay blocked for the duration */
RELEASE_LOCK(prov_ctx_lock);
if (scheme_cb) {
/* Call scheme specific event handler */
scheme_cb(scheme_data, event_id, event_data);
}
if (app_cb) {
/* Call application specific event handler */
app_cb(app_data, event_id, event_data);
}
if (esp_event_post(WIFI_PROV_EVENT, event_id,
event_data, event_data_size,
portMAX_DELAY) != ESP_OK) {
ESP_LOGE(TAG, "Failed to post event %d to default event loop", event_id);
}
ACQUIRE_LOCK(prov_ctx_lock);
}
}
esp_err_t wifi_prov_mgr_set_app_info(const char *label, const char *version,
const char**capabilities, size_t total_capabilities)
{
if (!label || !version || !capabilities) {
return ESP_ERR_INVALID_ARG;
}
if (!prov_ctx_lock) {
ESP_LOGE(TAG, "Provisioning manager not initialized");
return ESP_ERR_INVALID_STATE;
}
esp_err_t ret = ESP_FAIL;
ACQUIRE_LOCK(prov_ctx_lock);
if (prov_ctx && prov_ctx->prov_state == WIFI_PROV_STATE_IDLE) {
if (!prov_ctx->app_info_json) {
prov_ctx->app_info_json = cJSON_CreateObject();
}
cJSON *new_entry_json = cJSON_CreateObject();
cJSON *capabilities_json = cJSON_CreateArray();
cJSON_AddItemToObject(prov_ctx->app_info_json, label, new_entry_json);
/* Version ("ver") */
cJSON_AddStringToObject(new_entry_json, "ver", version);
/* List of capabilities ("cap") */
cJSON_AddItemToObject(new_entry_json, "cap", capabilities_json);
for (unsigned int i = 0; i < total_capabilities; i++) {
if (capabilities[i]) {
cJSON_AddItemToArray(capabilities_json, cJSON_CreateString(capabilities[i]));
}
}
ret = ESP_OK;
} else {
ret = ESP_ERR_INVALID_STATE;
}
RELEASE_LOCK(prov_ctx_lock);
return ret;
}
static cJSON* wifi_prov_get_info_json(void)
{
cJSON *full_info_json = prov_ctx->app_info_json ?
cJSON_Duplicate(prov_ctx->app_info_json, 1) : cJSON_CreateObject();
cJSON *prov_info_json = cJSON_CreateObject();
cJSON *prov_capabilities = cJSON_CreateArray();
/* Use label "prov" to indicate provisioning related information */
cJSON_AddItemToObject(full_info_json, "prov", prov_info_json);
/* Version field */
cJSON_AddStringToObject(prov_info_json, "ver", prov_ctx->mgr_info.version);
cJSON_AddNumberToObject(prov_info_json, "sec_ver", prov_ctx->security);
/* Capabilities field */
cJSON_AddItemToObject(prov_info_json, "cap", prov_capabilities);
/* If Security / Proof of Possession is not used, indicate in capabilities */
if (prov_ctx->mgr_info.capabilities.no_sec) {
cJSON_AddItemToArray(prov_capabilities, cJSON_CreateString("no_sec"));
} else if (prov_ctx->mgr_info.capabilities.no_pop) {
cJSON_AddItemToArray(prov_capabilities, cJSON_CreateString("no_pop"));
}
/* Indicate capability for performing Wi-Fi scan */
cJSON_AddItemToArray(prov_capabilities, cJSON_CreateString("wifi_scan"));
return full_info_json;
}
/* Declare the internal event handler */
static void wifi_prov_mgr_event_handler_internal(void* arg, esp_event_base_t event_base,
int32_t event_id, void* event_data);
static esp_err_t wifi_prov_mgr_start_service(const char *service_name, const char *service_key)
{
const wifi_prov_scheme_t *scheme = &prov_ctx->mgr_config.scheme;
esp_err_t ret;
/* Create new protocomm instance */
prov_ctx->pc = protocomm_new();
if (prov_ctx->pc == NULL) {
ESP_LOGE(TAG, "Failed to create new protocomm instance");
return ESP_FAIL;
}
ret = scheme->set_config_service(prov_ctx->prov_scheme_config, service_name, service_key);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to configure service");
protocomm_delete(prov_ctx->pc);
return ret;
}
/* Start provisioning */
ret = scheme->prov_start(prov_ctx->pc, prov_ctx->prov_scheme_config);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to start service");
protocomm_delete(prov_ctx->pc);
return ret;
}
/* Set version information / capabilities of provisioning service and application */
cJSON *version_json = wifi_prov_get_info_json();
char *version_str = cJSON_Print(version_json);
ret = protocomm_set_version(prov_ctx->pc, "proto-ver", version_str);
free(version_str);
cJSON_Delete(version_json);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to set version endpoint");
scheme->prov_stop(prov_ctx->pc);
protocomm_delete(prov_ctx->pc);
return ret;
}
/* Set protocomm security type for endpoint */
if (prov_ctx->security == 0) {
#ifdef CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_0
ret = protocomm_set_security(prov_ctx->pc, "prov-session",
&protocomm_security0, NULL);
#else
// Enable SECURITY_VERSION_0 in Protocomm configuration menu
return ESP_ERR_NOT_SUPPORTED;
#endif
} else if (prov_ctx->security == 1) {
#ifdef CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_1
ret = protocomm_set_security(prov_ctx->pc, "prov-session",
&protocomm_security1, prov_ctx->protocomm_sec_params);
#else
// Enable SECURITY_VERSION_1 in Protocomm configuration menu
return ESP_ERR_NOT_SUPPORTED;
#endif
} else if (prov_ctx->security == 2) {
#ifdef CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_2
ret = protocomm_set_security(prov_ctx->pc, "prov-session",
&protocomm_security2, prov_ctx->protocomm_sec_params);
#else
// Enable SECURITY_VERSION_2 in Protocomm configuration menu
return ESP_ERR_NOT_SUPPORTED;
#endif
} else {
ESP_LOGE(TAG, "Unsupported protocomm security version %d", prov_ctx->security);
ret = ESP_ERR_INVALID_ARG;
}
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to set security endpoint");
scheme->prov_stop(prov_ctx->pc);
protocomm_delete(prov_ctx->pc);
return ret;
}
prov_ctx->wifi_prov_handlers = malloc(sizeof(wifi_prov_config_handlers_t));
ret = get_wifi_prov_handlers(prov_ctx->wifi_prov_handlers);
if (ret != ESP_OK) {
ESP_LOGD(TAG, "Failed to allocate memory for provisioning handlers");
scheme->prov_stop(prov_ctx->pc);
protocomm_delete(prov_ctx->pc);
return ESP_ERR_NO_MEM;
}
/* Add protocomm endpoint for Wi-Fi station configuration */
ret = protocomm_add_endpoint(prov_ctx->pc, "prov-config",
wifi_prov_config_data_handler,
prov_ctx->wifi_prov_handlers);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to set provisioning endpoint");
free(prov_ctx->wifi_prov_handlers);
scheme->prov_stop(prov_ctx->pc);
protocomm_delete(prov_ctx->pc);
return ret;
}
prov_ctx->wifi_scan_handlers = malloc(sizeof(wifi_prov_scan_handlers_t));
ret = get_wifi_scan_handlers(prov_ctx->wifi_scan_handlers);
if (ret != ESP_OK) {
ESP_LOGD(TAG, "Failed to allocate memory for Wi-Fi scan handlers");
free(prov_ctx->wifi_prov_handlers);
scheme->prov_stop(prov_ctx->pc);
protocomm_delete(prov_ctx->pc);
return ESP_ERR_NO_MEM;
}
/* Add endpoint for scanning Wi-Fi APs and sending scan list */
ret = protocomm_add_endpoint(prov_ctx->pc, "prov-scan",
wifi_prov_scan_handler,
prov_ctx->wifi_scan_handlers);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to set Wi-Fi scan endpoint");
free(prov_ctx->wifi_scan_handlers);
free(prov_ctx->wifi_prov_handlers);
scheme->prov_stop(prov_ctx->pc);
protocomm_delete(prov_ctx->pc);
return ret;
}
prov_ctx->wifi_ctrl_handlers = malloc(sizeof(wifi_ctrl_handlers_t));
ret = get_wifi_ctrl_handlers(prov_ctx->wifi_ctrl_handlers);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to allocate memory for Wi-Fi ctrl handlers");
free(prov_ctx->wifi_prov_handlers);
scheme->prov_stop(prov_ctx->pc);
protocomm_delete(prov_ctx->pc);
return ESP_ERR_NO_MEM;
}
/* Add endpoint for controlling state of Wi-Fi station */
ret = protocomm_add_endpoint(prov_ctx->pc, "prov-ctrl",
wifi_ctrl_handler,
prov_ctx->wifi_ctrl_handlers);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to set Wi-Fi ctrl endpoint");
free(prov_ctx->wifi_ctrl_handlers);
free(prov_ctx->wifi_prov_handlers);
scheme->prov_stop(prov_ctx->pc);
protocomm_delete(prov_ctx->pc);
return ret;
}
/* Register global event handler */
ret = esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID,
wifi_prov_mgr_event_handler_internal, NULL);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to register WiFi event handler");
free(prov_ctx->wifi_scan_handlers);
free(prov_ctx->wifi_ctrl_handlers);
free(prov_ctx->wifi_prov_handlers);
scheme->prov_stop(prov_ctx->pc);
protocomm_delete(prov_ctx->pc);
return ret;
}
ret = esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP,
wifi_prov_mgr_event_handler_internal, NULL);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to register IP event handler");
esp_event_handler_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID,
wifi_prov_mgr_event_handler_internal);
free(prov_ctx->wifi_scan_handlers);
free(prov_ctx->wifi_ctrl_handlers);
free(prov_ctx->wifi_prov_handlers);
scheme->prov_stop(prov_ctx->pc);
protocomm_delete(prov_ctx->pc);
return ret;
}
ret = esp_event_handler_register(WIFI_PROV_MGR_PVT_EVENT, WIFI_PROV_MGR_STOP,
wifi_prov_mgr_event_handler_internal, NULL);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to register provisioning event handler");
esp_event_handler_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID,
wifi_prov_mgr_event_handler_internal);
esp_event_handler_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP,
wifi_prov_mgr_event_handler_internal);
free(prov_ctx->wifi_scan_handlers);
free(prov_ctx->wifi_ctrl_handlers);
free(prov_ctx->wifi_prov_handlers);
scheme->prov_stop(prov_ctx->pc);
protocomm_delete(prov_ctx->pc);
return ret;
}
ESP_LOGI(TAG, "Provisioning started with service name : %s ",
service_name ? service_name : "<NULL>");
return ESP_OK;
}
esp_err_t wifi_prov_mgr_endpoint_create(const char *ep_name)
{
if (!prov_ctx_lock) {
ESP_LOGE(TAG, "Provisioning manager not initialized");
return ESP_ERR_INVALID_STATE;
}
esp_err_t err = ESP_FAIL;
ACQUIRE_LOCK(prov_ctx_lock);
if (prov_ctx &&
prov_ctx->prov_state == WIFI_PROV_STATE_IDLE) {
err = prov_ctx->mgr_config.scheme.set_config_endpoint(
prov_ctx->prov_scheme_config, ep_name,
prov_ctx->endpoint_uuid_used + 1);
}
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to create additional endpoint");
} else {
prov_ctx->endpoint_uuid_used++;
}
RELEASE_LOCK(prov_ctx_lock);
return err;
}
esp_err_t wifi_prov_mgr_endpoint_register(const char *ep_name, protocomm_req_handler_t handler, void *user_ctx)
{
if (!prov_ctx_lock) {
ESP_LOGE(TAG, "Provisioning manager not initialized");
return ESP_ERR_INVALID_STATE;
}
esp_err_t err = ESP_FAIL;
ACQUIRE_LOCK(prov_ctx_lock);
if (prov_ctx &&
prov_ctx->prov_state > WIFI_PROV_STATE_STARTING &&
prov_ctx->prov_state < WIFI_PROV_STATE_STOPPING) {
err = protocomm_add_endpoint(prov_ctx->pc, ep_name, handler, user_ctx);
}
RELEASE_LOCK(prov_ctx_lock);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to register handler for endpoint");
}
return err;
}
void wifi_prov_mgr_endpoint_unregister(const char *ep_name)
{
if (!prov_ctx_lock) {
ESP_LOGE(TAG, "Provisioning manager not initialized");
return;
}
ACQUIRE_LOCK(prov_ctx_lock);
if (prov_ctx &&
prov_ctx->prov_state > WIFI_PROV_STATE_STARTING &&
prov_ctx->prov_state < WIFI_PROV_STATE_STOPPING) {
protocomm_remove_endpoint(prov_ctx->pc, ep_name);
}
RELEASE_LOCK(prov_ctx_lock);
}
static void prov_stop_and_notify(bool is_async)
{
esp_event_handler_unregister(WIFI_PROV_MGR_PVT_EVENT, WIFI_PROV_MGR_STOP,
wifi_prov_mgr_event_handler_internal);
if (prov_ctx->cleanup_delay_timer) {
esp_timer_stop(prov_ctx->cleanup_delay_timer);
esp_timer_delete(prov_ctx->cleanup_delay_timer);
prov_ctx->cleanup_delay_timer = NULL;
}
wifi_prov_cb_func_t app_cb = prov_ctx->mgr_config.app_event_handler.event_cb;
void *app_data = prov_ctx->mgr_config.app_event_handler.user_data;
wifi_prov_cb_func_t scheme_cb = prov_ctx->mgr_config.scheme_event_handler.event_cb;
void *scheme_data = prov_ctx->mgr_config.scheme_event_handler.user_data;
/* This delay is so that the client side app is notified first
* and then the provisioning is stopped. Generally 1000ms is enough. */
if (!is_async)
{
uint32_t cleanup_delay = prov_ctx->cleanup_delay > 100 ? prov_ctx->cleanup_delay : 100;
vTaskDelay(cleanup_delay / portTICK_PERIOD_MS);
}
protocomm_remove_endpoint(prov_ctx->pc, "prov-ctrl");
protocomm_remove_endpoint(prov_ctx->pc, "prov-scan");
protocomm_remove_endpoint(prov_ctx->pc, "prov-config");
protocomm_unset_security(prov_ctx->pc, "prov-session");
protocomm_unset_version(prov_ctx->pc, "proto-ver");
/* All the extra application added endpoints are also
* removed automatically when prov_stop is called */
prov_ctx->mgr_config.scheme.prov_stop(prov_ctx->pc);
/* Delete protocomm instance */
protocomm_delete(prov_ctx->pc);
prov_ctx->pc = NULL;
/* Free provisioning handlers */
free(prov_ctx->wifi_prov_handlers->ctx);
free(prov_ctx->wifi_prov_handlers);
prov_ctx->wifi_prov_handlers = NULL;
free(prov_ctx->wifi_scan_handlers->ctx);
free(prov_ctx->wifi_scan_handlers);
prov_ctx->wifi_scan_handlers = NULL;
free(prov_ctx->wifi_ctrl_handlers);
prov_ctx->wifi_ctrl_handlers = NULL;
/* Switch device to Wi-Fi STA mode irrespective of
* whether provisioning was completed or not */
esp_wifi_set_mode(WIFI_MODE_STA);
ESP_LOGI(TAG, "Provisioning stopped");
if (is_async) {
/* NOTE: While calling this API in an async fashion,
* the context lock prov_ctx_lock has already been taken
*/
prov_ctx->prov_state = WIFI_PROV_STATE_IDLE;
ESP_LOGD(TAG, "execute_event_cb : %d", WIFI_PROV_END);
if (scheme_cb) {
scheme_cb(scheme_data, WIFI_PROV_END, NULL);
}
if (app_cb) {
app_cb(app_data, WIFI_PROV_END, NULL);
}
if (esp_event_post(WIFI_PROV_EVENT, WIFI_PROV_END, NULL, 0, portMAX_DELAY) != ESP_OK) {
ESP_LOGE(TAG, "Failed to post event WIFI_PROV_END");
}
}
}
/* This will do one of these:
* 1) if blocking is false, start a cleanup timer for stopping the provisioning service (returns true)
* 2) if blocking is true, stop provisioning service immediately (returns true)
* 3) if service was already in the process of termination, in blocking mode this will
* wait till the service is stopped (returns false)
* 4) if service was not running, this will return immediately (returns false)
*
* NOTE: This function should be called only after ensuring that the context
* is valid and the control mutex is locked
*
* NOTE: When blocking mode is selected, the event callbacks are not executed.
* This help with de-initialization.
*/
static bool wifi_prov_mgr_stop_service(bool blocking)
{
if (blocking) {
/* Wait for any ongoing calls to wifi_prov_mgr_start_service() or
* wifi_prov_mgr_stop_service() from another thread to finish */
while (prov_ctx && (
prov_ctx->prov_state == WIFI_PROV_STATE_STARTING ||
prov_ctx->prov_state == WIFI_PROV_STATE_STOPPING)) {
RELEASE_LOCK(prov_ctx_lock);
vTaskDelay(100 / portTICK_PERIOD_MS);
ACQUIRE_LOCK(prov_ctx_lock);
}
} else {
/* Wait for any ongoing call to wifi_prov_mgr_start_service()
* from another thread to finish */
while (prov_ctx &&
prov_ctx->prov_state == WIFI_PROV_STATE_STARTING) {
RELEASE_LOCK(prov_ctx_lock);
vTaskDelay(100 / portTICK_PERIOD_MS);
ACQUIRE_LOCK(prov_ctx_lock);
}
if (prov_ctx && prov_ctx->prov_state == WIFI_PROV_STATE_STOPPING) {
ESP_LOGD(TAG, "Provisioning is already stopping");
return false;
}
}
if (!prov_ctx || prov_ctx->prov_state == WIFI_PROV_STATE_IDLE) {
ESP_LOGD(TAG, "Provisioning not running");
return false;
}
/* Timers not needed anymore */
if (prov_ctx->autostop_timer) {
esp_timer_stop(prov_ctx->autostop_timer);
esp_timer_delete(prov_ctx->autostop_timer);
prov_ctx->autostop_timer = NULL;
}
if (prov_ctx->wifi_connect_timer) {
esp_timer_stop(prov_ctx->wifi_connect_timer);
esp_timer_delete(prov_ctx->wifi_connect_timer);
prov_ctx->wifi_connect_timer = NULL;
}
ESP_LOGD(TAG, "Stopping provisioning");
prov_ctx->prov_state = WIFI_PROV_STATE_STOPPING;
/* Free proof of possession */
if (prov_ctx->protocomm_sec_params) {
if (prov_ctx->security == 1) {
// In case of security 1 we keep an internal copy of "pop".
// Hence free it at this point
uint8_t *pop = (uint8_t *)((protocomm_security1_params_t *) prov_ctx->protocomm_sec_params)->data;
free(pop);
}
prov_ctx->protocomm_sec_params = NULL;
}
/* Delete all scan results */
for (uint16_t channel = 0; channel < 14; channel++) {
free(prov_ctx->ap_list[channel]);
prov_ctx->ap_list[channel] = NULL;
}
prov_ctx->scanning = false;
for (uint8_t i = 0; i < MAX_SCAN_RESULTS; i++) {
prov_ctx->ap_list_sorted[i] = NULL;
}
/* Remove event handler */
esp_event_handler_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID,
wifi_prov_mgr_event_handler_internal);
esp_event_handler_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP,
wifi_prov_mgr_event_handler_internal);
if (blocking) {
/* Run the cleanup without launching a separate task. Also the
* WIFI_PROV_END event is not emitted in this case */
RELEASE_LOCK(prov_ctx_lock);
prov_stop_and_notify(false);
ACQUIRE_LOCK(prov_ctx_lock);
prov_ctx->prov_state = WIFI_PROV_STATE_IDLE;
} else {
/* Launch cleanup timer to perform the cleanup asynchronously.
* It is important to do this asynchronously because, there are
* situations in which the transport level resources have to be
* released - some duration after - returning from a call to
* wifi_prov_mgr_stop_provisioning(), like when it is called
* inside a protocomm handler */
uint64_t cleanup_delay_ms = prov_ctx->cleanup_delay > 100 ? prov_ctx->cleanup_delay : 100;
esp_timer_start_once(prov_ctx->cleanup_delay_timer, cleanup_delay_ms * 1000U);
ESP_LOGD(TAG, "Provisioning scheduled for stopping");
}
return true;
}
/* Task spawned by timer callback */
static void stop_prov_timer_cb(void *arg)
{
wifi_prov_mgr_stop_provisioning();
}
static void cleanup_delay_timer_cb(void *arg)
{
esp_err_t ret = esp_event_post(WIFI_PROV_MGR_PVT_EVENT, WIFI_PROV_MGR_STOP, NULL, 0, pdMS_TO_TICKS(100));
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to post WIFI_PROV_MGR_STOP event! %d %s", ret, esp_err_to_name(ret));
}
}
esp_err_t wifi_prov_mgr_disable_auto_stop(uint32_t cleanup_delay)
{
if (!prov_ctx_lock) {
ESP_LOGE(TAG, "Provisioning manager not initialized");
return ESP_ERR_INVALID_STATE;
}
esp_err_t ret = ESP_FAIL;
ACQUIRE_LOCK(prov_ctx_lock);
if (prov_ctx && prov_ctx->prov_state == WIFI_PROV_STATE_IDLE) {
prov_ctx->mgr_info.capabilities.no_auto_stop = true;
prov_ctx->cleanup_delay = cleanup_delay;
ret = ESP_OK;
} else {
ret = ESP_ERR_INVALID_STATE;
}
RELEASE_LOCK(prov_ctx_lock);
return ret;
}
/* Call this if provisioning is completed before the timeout occurs */
esp_err_t wifi_prov_mgr_done(void)
{
if (!prov_ctx_lock) {
ESP_LOGE(TAG, "Provisioning manager not initialized");
return ESP_ERR_INVALID_STATE;
}
bool auto_stop_enabled = false;
ACQUIRE_LOCK(prov_ctx_lock);
if (prov_ctx && !prov_ctx->mgr_info.capabilities.no_auto_stop) {
auto_stop_enabled = true;
}
RELEASE_LOCK(prov_ctx_lock);
/* Stop provisioning if auto stop is enabled */
if (auto_stop_enabled) {
wifi_prov_mgr_stop_provisioning();
}
return ESP_OK;
}
static esp_err_t update_wifi_scan_results(void)
{
if (!prov_ctx->scanning) {
return ESP_ERR_INVALID_STATE;
}
ESP_LOGD(TAG, "Scan finished");
esp_err_t ret = ESP_FAIL;
uint16_t count = 0;
uint16_t curr_channel = prov_ctx->curr_channel;
if (prov_ctx->ap_list[curr_channel]) {
free(prov_ctx->ap_list[curr_channel]);
prov_ctx->ap_list[curr_channel] = NULL;
prov_ctx->ap_list_len[curr_channel] = 0;
}
if (esp_wifi_scan_get_ap_num(&count) != ESP_OK) {
ESP_LOGE(TAG, "Failed to get count of scanned APs");
goto exit;
}
if (!count) {
ESP_LOGD(TAG, "Scan result empty");
ret = ESP_OK;
goto exit;
}
uint16_t get_count = MIN(count, MAX_SCAN_RESULTS);
prov_ctx->ap_list[curr_channel] = (wifi_ap_record_t *) calloc(get_count, sizeof(wifi_ap_record_t));
if (!prov_ctx->ap_list[curr_channel]) {
ESP_LOGE(TAG, "Failed to allocate memory for AP list");
esp_wifi_clear_ap_list();
goto exit;
}
if (esp_wifi_scan_get_ap_records(&get_count, prov_ctx->ap_list[curr_channel]) != ESP_OK) {
ESP_LOGE(TAG, "Failed to get scanned AP records");
goto exit;
}
prov_ctx->ap_list_len[curr_channel] = get_count;
if (prov_ctx->channels_per_group) {
ESP_LOGD(TAG, "Scan results for channel %d :", curr_channel);
} else {
ESP_LOGD(TAG, "Scan results :");
}
ESP_LOGD(TAG, "\tS.N. %-32s %-12s %s %s", "SSID", "BSSID", "RSSI", "AUTH");
for (uint8_t i = 0; i < prov_ctx->ap_list_len[curr_channel]; i++) {
ESP_LOGD(TAG, "\t[%2d] %-32s %02x%02x%02x%02x%02x%02x %4d %4d", i,
prov_ctx->ap_list[curr_channel][i].ssid,
prov_ctx->ap_list[curr_channel][i].bssid[0],
prov_ctx->ap_list[curr_channel][i].bssid[1],
prov_ctx->ap_list[curr_channel][i].bssid[2],
prov_ctx->ap_list[curr_channel][i].bssid[3],
prov_ctx->ap_list[curr_channel][i].bssid[4],
prov_ctx->ap_list[curr_channel][i].bssid[5],
prov_ctx->ap_list[curr_channel][i].rssi,
prov_ctx->ap_list[curr_channel][i].authmode);
}
/* Store results in sorted list */
{
int rc = get_count;
int is = MAX_SCAN_RESULTS - rc - 1;
while (rc > 0 && is >= 0) {
if (prov_ctx->ap_list_sorted[is]) {
if (prov_ctx->ap_list_sorted[is]->rssi > prov_ctx->ap_list[curr_channel][rc - 1].rssi) {
prov_ctx->ap_list_sorted[is + rc] = &prov_ctx->ap_list[curr_channel][rc - 1];
rc--;
continue;
}
prov_ctx->ap_list_sorted[is + rc] = prov_ctx->ap_list_sorted[is];
}
is--;
}
while (rc > 0) {
prov_ctx->ap_list_sorted[rc - 1] = &prov_ctx->ap_list[curr_channel][rc - 1];
rc--;
}
}
ret = ESP_OK;
exit:
if (!prov_ctx->channels_per_group) {
/* All channel scan was performed
* so nothing more to do */
prov_ctx->scanning = false;
goto final;
}
curr_channel = prov_ctx->curr_channel = (prov_ctx->curr_channel + 1) % 14;
if (ret != ESP_OK || curr_channel == 0) {
prov_ctx->scanning = false;
goto final;
}
if ((curr_channel % prov_ctx->channels_per_group) == 0) {
vTaskDelay(120 / portTICK_PERIOD_MS);
}
ESP_LOGD(TAG, "Scan starting on channel %u...", curr_channel);
prov_ctx->scan_cfg.channel = curr_channel;
ret = esp_wifi_scan_start(&prov_ctx->scan_cfg, false);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to start scan");
prov_ctx->scanning = false;
goto final;
}
ESP_LOGD(TAG, "Scan started");
final:
return ret;
}
static void wifi_prov_mgr_event_handler_internal(
void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data)
{
if (!prov_ctx_lock) {
ESP_LOGE(TAG, "Provisioning manager not initialized");
return;
}
ACQUIRE_LOCK(prov_ctx_lock);
/* If pointer to provisioning application data is NULL
* then provisioning manager is not running, therefore
* return with error to allow the global handler to act */
if (!prov_ctx) {
RELEASE_LOCK(prov_ctx_lock);
return;
}
/* If scan completed then update scan result */
if (prov_ctx->prov_state == WIFI_PROV_STATE_STARTED &&
event_base == WIFI_EVENT &&
event_id == WIFI_EVENT_SCAN_DONE) {
update_wifi_scan_results();
}
/* Only handle events when credential is received and
* Wi-Fi STA is yet to complete trying the connection */
if (prov_ctx->prov_state < WIFI_PROV_STATE_CRED_RECV) {
RELEASE_LOCK(prov_ctx_lock);
return;
}
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
ESP_LOGI(TAG, "STA Start");
/* Once configuration is received through protocomm,
* device is started as station. Once station starts,
* wait for connection to establish with configured
* host SSID and password */
prov_ctx->wifi_state = WIFI_PROV_STA_CONNECTING;
} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
ESP_LOGI(TAG, "STA Got IP");
/* Station got IP. That means configuration is successful. */
prov_ctx->wifi_state = WIFI_PROV_STA_CONNECTED;
prov_ctx->prov_state = WIFI_PROV_STATE_SUCCESS;
/* If auto stop is enabled (default), schedule timer to
* stop provisioning after configured timeout. */
if (!prov_ctx->mgr_info.capabilities.no_auto_stop) {
ESP_LOGD(TAG, "Starting %d sec timer for stop_prov_timer_cb()",
CONFIG_WIFI_PROV_AUTOSTOP_TIMEOUT);
esp_timer_start_once(prov_ctx->autostop_timer, CONFIG_WIFI_PROV_AUTOSTOP_TIMEOUT * 1000000U);
}
/* Execute user registered callback handler */
execute_event_cb(WIFI_PROV_CRED_SUCCESS, NULL, 0);
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
ESP_LOGE(TAG, "STA Disconnected");
/* Station couldn't connect to configured host SSID */
prov_ctx->wifi_state = WIFI_PROV_STA_DISCONNECTED;
wifi_event_sta_disconnected_t* disconnected = (wifi_event_sta_disconnected_t*) event_data;
ESP_LOGE(TAG, "Disconnect reason : %d", disconnected->reason);
/* Set code corresponding to the reason for disconnection */
switch (disconnected->reason) {
case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT:
case WIFI_REASON_AUTH_FAIL:
case WIFI_REASON_HANDSHAKE_TIMEOUT:
case WIFI_REASON_MIC_FAILURE:
ESP_LOGE(TAG, "STA Auth Error");
prov_ctx->wifi_disconnect_reason = WIFI_PROV_STA_AUTH_ERROR;
break;
case WIFI_REASON_NO_AP_FOUND:
ESP_LOGE(TAG, "STA AP Not found");
prov_ctx->wifi_disconnect_reason = WIFI_PROV_STA_AP_NOT_FOUND;
break;
default:
/* If none of the expected reasons,
* retry connecting to host SSID */
prov_ctx->wifi_state = WIFI_PROV_STA_CONNECTING;
esp_wifi_connect();
}
/* In case of disconnection, update state of service and
* run the event handler with disconnection reason as data */
if (prov_ctx->wifi_state == WIFI_PROV_STA_DISCONNECTED) {
prov_ctx->prov_state = WIFI_PROV_STATE_FAIL;
wifi_prov_sta_fail_reason_t reason = prov_ctx->wifi_disconnect_reason;
/* Execute user registered callback handler */
execute_event_cb(WIFI_PROV_CRED_FAIL, (void *)&reason, sizeof(reason));
}
} else if (event_base == WIFI_PROV_MGR_PVT_EVENT && event_id == WIFI_PROV_MGR_STOP) {
prov_stop_and_notify(true);
}
RELEASE_LOCK(prov_ctx_lock);
}
esp_err_t wifi_prov_mgr_wifi_scan_start(bool blocking, bool passive,
uint8_t group_channels, uint32_t period_ms)
{
if (!prov_ctx_lock) {