1 // Copyright 2019 Espressif Systems (Shanghai) PTE LTD
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //         http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include <stdint.h>
16 #include <string.h>
17 #include "esp_log.h"
18 #include "esp_event_base.h"
19 #include "esp_private/wifi.h"
20 #include "esp_smartconfig.h"
21 #include "smartconfig_ack.h"
22 
23 /* Smartconfig events definitions */
24 ESP_EVENT_DEFINE_BASE(SC_EVENT);
25 
26 static const char *TAG = "smartconfig";
27 
handler_got_ssid_passwd(void * arg,esp_event_base_t base,int32_t event_id,void * data)28 static void handler_got_ssid_passwd(void *arg, esp_event_base_t base, int32_t event_id, void *data)
29 {
30     smartconfig_event_got_ssid_pswd_t *evt = (smartconfig_event_got_ssid_pswd_t *)data;
31     uint8_t ssid[33] = { 0 };
32     uint8_t password[65] = { 0 };
33     uint8_t cellphone_ip[4];
34     esp_err_t err = ESP_OK;
35 
36     memcpy(ssid, evt->ssid, sizeof(evt->ssid));
37     memcpy(password, evt->password, sizeof(evt->password));
38     memcpy(cellphone_ip, evt->cellphone_ip, sizeof(evt->cellphone_ip));
39 
40     ESP_LOGD(TAG, "SSID:%s", ssid);
41     ESP_LOGD(TAG, "PASSWORD:%s", password);
42     ESP_LOGD(TAG, "Phone ip: %d.%d.%d.%d\n", cellphone_ip[0], cellphone_ip[1], cellphone_ip[2], cellphone_ip[3]);
43 
44     err = sc_send_ack_start(evt->type, evt->token, evt->cellphone_ip);
45     if (err != ESP_OK) {
46         ESP_LOGE(TAG, "Send smartconfig ACK error: %d", err);
47     }
48 }
49 
esp_smartconfig_start(const smartconfig_start_config_t * config)50 esp_err_t esp_smartconfig_start(const smartconfig_start_config_t *config)
51 {
52     esp_err_t err = ESP_OK;
53 
54     err = esp_event_handler_register(SC_EVENT, SC_EVENT_GOT_SSID_PSWD, handler_got_ssid_passwd, NULL);
55     if (err != ESP_OK) {
56         ESP_LOGE(TAG, "Register smartconfig default event handler fail!");
57         return err;
58     }
59 
60     err = esp_smartconfig_internal_start(config);
61     if (err != ESP_OK) {
62         esp_event_handler_unregister(SC_EVENT, SC_EVENT_GOT_SSID_PSWD, handler_got_ssid_passwd);
63     }
64     return err;
65 }
66 
esp_smartconfig_stop(void)67 esp_err_t esp_smartconfig_stop(void)
68 {
69     esp_err_t err = ESP_OK;
70 
71     err = esp_smartconfig_internal_stop();
72     if (err == ESP_OK) {
73         sc_send_ack_stop();
74         esp_event_handler_unregister(SC_EVENT, SC_EVENT_GOT_SSID_PSWD, handler_got_ssid_passwd);
75     }
76     return err;
77 }
78