blob: dfa3347c67953c59268fe7f9223e302b6e781b86 [file] [log] [blame]
Damien Georgeea186de2021-09-22 00:35:46 +10001/*
2 * This file is part of the MicroPython project, http://micropython.org/
3 *
4 * Development of the code in this file was sponsored by Microbric Pty Ltd
5 * and Mnemote Pty Ltd
6 *
7 * The MIT License (MIT)
8 *
9 * Copyright (c) 2016, 2017 Nick Moore @mnemote
10 * Copyright (c) 2017 "Eric Poulsen" <eric@zyxod.com>
11 *
12 * Based on esp8266/modnetwork.c which is Copyright (c) 2015 Paul Sokolovsky
13 * And the ESP IDF example code which is Public Domain / CC0
14 *
15 * Permission is hereby granted, free of charge, to any person obtaining a copy
16 * of this software and associated documentation files (the "Software"), to deal
17 * in the Software without restriction, including without limitation the rights
18 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
19 * copies of the Software, and to permit persons to whom the Software is
20 * furnished to do so, subject to the following conditions:
21 *
22 * The above copyright notice and this permission notice shall be included in
23 * all copies or substantial portions of the Software.
24 *
25 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
31 * THE SOFTWARE.
32 */
33
34#include <string.h>
35
36#include "py/objlist.h"
37#include "py/runtime.h"
robert-hhd6bc34a2023-01-19 12:42:09 +010038#include "py/mphal.h"
Jim Mussaredeb51ca42023-02-01 14:20:45 +110039#include "extmod/modnetwork.h"
Damien Georgeea186de2021-09-22 00:35:46 +100040#include "modnetwork.h"
41
42#include "esp_wifi.h"
43#include "esp_log.h"
Angus Gratton960eef72023-11-14 16:46:55 +110044#include "esp_psram.h"
Damien Georgeea186de2021-09-22 00:35:46 +100045
Carlosgg1f355762023-06-25 22:48:39 +010046#ifndef NO_QSTR
47#include "mdns.h"
48#endif
49
Damien Georgeea186de2021-09-22 00:35:46 +100050#if MICROPY_PY_NETWORK_WLAN
51
52#if (WIFI_MODE_STA & WIFI_MODE_AP != WIFI_MODE_NULL || WIFI_MODE_STA | WIFI_MODE_AP != WIFI_MODE_APSTA)
53#error WIFI_MODE_STA and WIFI_MODE_AP are supposed to be bitfields!
54#endif
55
Damien Georgee4650122023-05-09 09:52:54 +100056typedef base_if_obj_t wlan_if_obj_t;
57
Angus Grattondecf8e62024-02-27 15:32:29 +110058static wlan_if_obj_t wlan_sta_obj;
59static wlan_if_obj_t wlan_ap_obj;
Damien Georgeea186de2021-09-22 00:35:46 +100060
61// Set to "true" if esp_wifi_start() was called
62static bool wifi_started = false;
63
64// Set to "true" if the STA interface is requested to be connected by the
65// user, used for automatic reassociation.
66static bool wifi_sta_connect_requested = false;
67
68// Set to "true" if the STA interface is connected to wifi and has IP address.
69static bool wifi_sta_connected = false;
70
71// Store the current status. 0 means None here, safe to do so as first enum value is WIFI_REASON_UNSPECIFIED=1.
72static uint8_t wifi_sta_disconn_reason = 0;
73
74#if MICROPY_HW_ENABLE_MDNS_QUERIES || MICROPY_HW_ENABLE_MDNS_RESPONDER
75// Whether mDNS has been initialised or not
76static bool mdns_initialised = false;
77#endif
78
79static uint8_t conf_wifi_sta_reconnects = 0;
Glenn Moloneydbced752023-07-01 13:54:44 +100080static uint8_t wifi_sta_reconnects;
Damien Georgeea186de2021-09-22 00:35:46 +100081
82// This function is called by the system-event task and so runs in a different
83// thread to the main MicroPython task. It must not raise any Python exceptions.
Damien Georgee4650122023-05-09 09:52:54 +100084static void network_wlan_wifi_event_handler(void *event_handler_arg, esp_event_base_t event_base, int32_t event_id, void *event_data) {
85 switch (event_id) {
86 case WIFI_EVENT_STA_START:
Damien Georgeea186de2021-09-22 00:35:46 +100087 ESP_LOGI("wifi", "STA_START");
Glenn Moloneydbced752023-07-01 13:54:44 +100088 wlan_sta_obj.active = true;
Damien Georgeea186de2021-09-22 00:35:46 +100089 wifi_sta_reconnects = 0;
90 break;
Damien Georgee4650122023-05-09 09:52:54 +100091
Glenn Moloneydbced752023-07-01 13:54:44 +100092 case WIFI_EVENT_STA_STOP:
93 wlan_sta_obj.active = false;
94 break;
95
Damien Georgee4650122023-05-09 09:52:54 +100096 case WIFI_EVENT_STA_CONNECTED:
Damien Georgeea186de2021-09-22 00:35:46 +100097 ESP_LOGI("network", "CONNECTED");
98 break;
Damien Georgee4650122023-05-09 09:52:54 +100099
100 case WIFI_EVENT_STA_DISCONNECTED: {
Damien Georgeea186de2021-09-22 00:35:46 +1000101 // This is a workaround as ESP32 WiFi libs don't currently
102 // auto-reassociate.
Damien Georgee4650122023-05-09 09:52:54 +1000103
104 wifi_event_sta_disconnected_t *disconn = event_data;
Damien Georgeea186de2021-09-22 00:35:46 +1000105 char *message = "";
106 wifi_sta_disconn_reason = disconn->reason;
107 switch (disconn->reason) {
108 case WIFI_REASON_BEACON_TIMEOUT:
109 // AP has dropped out; try to reconnect.
Ihor Nehrutsad6154922023-11-09 16:18:39 +0200110 message = "beacon timeout";
Damien Georgeea186de2021-09-22 00:35:46 +1000111 break;
112 case WIFI_REASON_NO_AP_FOUND:
113 // AP may not exist, or it may have momentarily dropped out; try to reconnect.
Ihor Nehrutsad6154922023-11-09 16:18:39 +0200114 message = "no AP found";
Damien Georgeea186de2021-09-22 00:35:46 +1000115 break;
116 case WIFI_REASON_AUTH_FAIL:
117 // Password may be wrong, or it just failed to connect; try to reconnect.
Ihor Nehrutsad6154922023-11-09 16:18:39 +0200118 message = "authentication failed";
Damien Georgeea186de2021-09-22 00:35:46 +1000119 break;
120 default:
121 // Let other errors through and try to reconnect.
122 break;
123 }
Ihor Nehrutsad6154922023-11-09 16:18:39 +0200124 ESP_LOGI("wifi", "STA_DISCONNECTED, reason:%d:%s", disconn->reason, message);
Damien Georgeea186de2021-09-22 00:35:46 +1000125
126 wifi_sta_connected = false;
127 if (wifi_sta_connect_requested) {
128 wifi_mode_t mode;
129 if (esp_wifi_get_mode(&mode) != ESP_OK) {
130 break;
131 }
132 if (!(mode & WIFI_MODE_STA)) {
133 break;
134 }
135 if (conf_wifi_sta_reconnects) {
136 ESP_LOGI("wifi", "reconnect counter=%d, max=%d",
137 wifi_sta_reconnects, conf_wifi_sta_reconnects);
138 if (++wifi_sta_reconnects >= conf_wifi_sta_reconnects) {
139 break;
140 }
141 }
142 esp_err_t e = esp_wifi_connect();
143 if (e != ESP_OK) {
144 ESP_LOGI("wifi", "error attempting to reconnect: 0x%04x", e);
145 }
146 }
147 break;
148 }
Glenn Moloneydbced752023-07-01 13:54:44 +1000149
150 case WIFI_EVENT_AP_START:
151 wlan_ap_obj.active = true;
152 break;
153
154 case WIFI_EVENT_AP_STOP:
155 wlan_ap_obj.active = false;
156 break;
157
Damien Georgeea186de2021-09-22 00:35:46 +1000158 default:
159 break;
160 }
161}
162
Damien Georgee4650122023-05-09 09:52:54 +1000163static void network_wlan_ip_event_handler(void *event_handler_arg, esp_event_base_t event_base, int32_t event_id, void *event_data) {
164 switch (event_id) {
165 case IP_EVENT_STA_GOT_IP:
166 ESP_LOGI("network", "GOT_IP");
167 wifi_sta_connected = true;
168 wifi_sta_disconn_reason = 0; // Success so clear error. (in case of new error will be replaced anyway)
169 #if MICROPY_HW_ENABLE_MDNS_QUERIES || MICROPY_HW_ENABLE_MDNS_RESPONDER
170 if (!mdns_initialised) {
171 mdns_init();
172 #if MICROPY_HW_ENABLE_MDNS_RESPONDER
Jim Mussared65a3ce32023-10-03 13:32:48 +1100173 mdns_hostname_set(mod_network_hostname_data);
174 mdns_instance_name_set(mod_network_hostname_data);
Damien Georgee4650122023-05-09 09:52:54 +1000175 #endif
176 mdns_initialised = true;
177 }
178 #endif
179 break;
180
181 default:
182 break;
Damien Georgeea186de2021-09-22 00:35:46 +1000183 }
184}
185
Angus Grattondecf8e62024-02-27 15:32:29 +1100186static void require_if(mp_obj_t wlan_if, int if_no) {
Damien Georgee4650122023-05-09 09:52:54 +1000187 wlan_if_obj_t *self = MP_OBJ_TO_PTR(wlan_if);
188 if (self->if_id != if_no) {
189 mp_raise_msg(&mp_type_OSError, if_no == ESP_IF_WIFI_STA ? MP_ERROR_TEXT("STA required") : MP_ERROR_TEXT("AP required"));
190 }
191}
192
193void esp_initialise_wifi(void) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000194 static int wifi_initialized = 0;
195 if (!wifi_initialized) {
Damien Georgee4650122023-05-09 09:52:54 +1000196 esp_exceptions(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, network_wlan_wifi_event_handler, NULL, NULL));
197 esp_exceptions(esp_event_handler_instance_register(IP_EVENT, ESP_EVENT_ANY_ID, network_wlan_ip_event_handler, NULL, NULL));
198
199 wlan_sta_obj.base.type = &esp_network_wlan_type;
200 wlan_sta_obj.if_id = ESP_IF_WIFI_STA;
201 wlan_sta_obj.netif = esp_netif_create_default_wifi_sta();
Glenn Moloneydbced752023-07-01 13:54:44 +1000202 wlan_sta_obj.active = false;
Damien Georgee4650122023-05-09 09:52:54 +1000203
204 wlan_ap_obj.base.type = &esp_network_wlan_type;
205 wlan_ap_obj.if_id = ESP_IF_WIFI_AP;
206 wlan_ap_obj.netif = esp_netif_create_default_wifi_ap();
Glenn Moloneydbced752023-07-01 13:54:44 +1000207 wlan_ap_obj.active = false;
Damien Georgee4650122023-05-09 09:52:54 +1000208
Damien Georgeea186de2021-09-22 00:35:46 +1000209 wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
Angus Gratton960eef72023-11-14 16:46:55 +1100210 #if CONFIG_SPIRAM_IGNORE_NOTFOUND
211 if (!esp_psram_is_initialized()) {
212 // If PSRAM failed to initialize, disable "Wi-Fi Cache TX Buffers"
213 // (default SPIRAM config ESP32_WIFI_CACHE_TX_BUFFER_NUM==32, this is 54,400 bytes of heap)
214 cfg.cache_tx_buf_num = 0;
215 cfg.feature_caps &= ~CONFIG_FEATURE_CACHE_TX_BUF_BIT;
216
217 // Set some other options back to the non-SPIRAM default values
218 // to save more RAM.
219 //
220 // These can be determined from ESP-IDF components/esp_wifi/Kconfig and the
221 // WIFI_INIT_CONFIG_DEFAULT macro
222 cfg.tx_buf_type = 1; // Dynamic, this "magic number" is defined in IDF KConfig
223 cfg.static_tx_buf_num = 0; // Probably don't need, due to tx_buf_type
224 cfg.dynamic_tx_buf_num = 32; // ESP-IDF default value (maximum)
225 }
226 #endif
Damien Georgeea186de2021-09-22 00:35:46 +1000227 ESP_LOGD("modnetwork", "Initializing WiFi");
228 esp_exceptions(esp_wifi_init(&cfg));
229 esp_exceptions(esp_wifi_set_storage(WIFI_STORAGE_RAM));
Damien Georgee4650122023-05-09 09:52:54 +1000230
Damien Georgeea186de2021-09-22 00:35:46 +1000231 ESP_LOGD("modnetwork", "Initialized");
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000232 wifi_initialized = 1;
Damien Georgeea186de2021-09-22 00:35:46 +1000233 }
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000234}
235
Angus Grattondecf8e62024-02-27 15:32:29 +1100236static mp_obj_t network_wlan_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
Damien George53cb0732023-05-11 11:51:02 +1000237 mp_arg_check_num(n_args, n_kw, 0, 1, false);
238
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000239 esp_initialise_wifi();
Damien Georgeea186de2021-09-22 00:35:46 +1000240
Damien Georgee4650122023-05-09 09:52:54 +1000241 int idx = (n_args > 0) ? mp_obj_get_int(args[0]) : ESP_IF_WIFI_STA;
242 if (idx == ESP_IF_WIFI_STA) {
Damien Georgeea186de2021-09-22 00:35:46 +1000243 return MP_OBJ_FROM_PTR(&wlan_sta_obj);
Damien Georgee4650122023-05-09 09:52:54 +1000244 } else if (idx == ESP_IF_WIFI_AP) {
Damien Georgeea186de2021-09-22 00:35:46 +1000245 return MP_OBJ_FROM_PTR(&wlan_ap_obj);
246 } else {
247 mp_raise_ValueError(MP_ERROR_TEXT("invalid WLAN interface identifier"));
248 }
249}
Damien Georgeea186de2021-09-22 00:35:46 +1000250
Angus Grattondecf8e62024-02-27 15:32:29 +1100251static mp_obj_t network_wlan_active(size_t n_args, const mp_obj_t *args) {
Damien Georgeea186de2021-09-22 00:35:46 +1000252 wlan_if_obj_t *self = MP_OBJ_TO_PTR(args[0]);
253
254 wifi_mode_t mode;
255 if (!wifi_started) {
256 mode = WIFI_MODE_NULL;
257 } else {
258 esp_exceptions(esp_wifi_get_mode(&mode));
259 }
260
Damien Georgee4650122023-05-09 09:52:54 +1000261 int bit = (self->if_id == ESP_IF_WIFI_STA) ? WIFI_MODE_STA : WIFI_MODE_AP;
Damien Georgeea186de2021-09-22 00:35:46 +1000262
263 if (n_args > 1) {
264 bool active = mp_obj_is_true(args[1]);
265 mode = active ? (mode | bit) : (mode & ~bit);
266 if (mode == WIFI_MODE_NULL) {
267 if (wifi_started) {
268 esp_exceptions(esp_wifi_stop());
269 wifi_started = false;
270 }
271 } else {
272 esp_exceptions(esp_wifi_set_mode(mode));
273 if (!wifi_started) {
274 esp_exceptions(esp_wifi_start());
275 wifi_started = true;
276 }
277 }
Glenn Moloneydbced752023-07-01 13:54:44 +1000278
279 // Wait for the interface to be in the correct state.
280 while (self->active != active) {
281 MICROPY_EVENT_POLL_HOOK;
282 }
Damien Georgeea186de2021-09-22 00:35:46 +1000283 }
284
285 return (mode & bit) ? mp_const_true : mp_const_false;
286}
Angus Grattondecf8e62024-02-27 15:32:29 +1100287static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(network_wlan_active_obj, 1, 2, network_wlan_active);
Damien Georgeea186de2021-09-22 00:35:46 +1000288
Angus Grattondecf8e62024-02-27 15:32:29 +1100289static mp_obj_t network_wlan_connect(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
iabdalkadera7c7feb2022-06-04 12:22:55 +0200290 enum { ARG_ssid, ARG_key, ARG_bssid };
Damien Georgeea186de2021-09-22 00:35:46 +1000291 static const mp_arg_t allowed_args[] = {
292 { MP_QSTR_, MP_ARG_OBJ, {.u_obj = mp_const_none} },
293 { MP_QSTR_, MP_ARG_OBJ, {.u_obj = mp_const_none} },
294 { MP_QSTR_bssid, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
295 };
296
297 // parse args
298 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
299 mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
300
301 wifi_config_t wifi_sta_config = {0};
302
303 // configure any parameters that are given
304 if (n_args > 1) {
305 size_t len;
306 const char *p;
307 if (args[ARG_ssid].u_obj != mp_const_none) {
308 p = mp_obj_str_get_data(args[ARG_ssid].u_obj, &len);
309 memcpy(wifi_sta_config.sta.ssid, p, MIN(len, sizeof(wifi_sta_config.sta.ssid)));
310 }
iabdalkadera7c7feb2022-06-04 12:22:55 +0200311 if (args[ARG_key].u_obj != mp_const_none) {
312 p = mp_obj_str_get_data(args[ARG_key].u_obj, &len);
Damien Georgeea186de2021-09-22 00:35:46 +1000313 memcpy(wifi_sta_config.sta.password, p, MIN(len, sizeof(wifi_sta_config.sta.password)));
314 }
315 if (args[ARG_bssid].u_obj != mp_const_none) {
316 p = mp_obj_str_get_data(args[ARG_bssid].u_obj, &len);
317 if (len != sizeof(wifi_sta_config.sta.bssid)) {
318 mp_raise_ValueError(NULL);
319 }
320 wifi_sta_config.sta.bssid_set = 1;
321 memcpy(wifi_sta_config.sta.bssid, p, sizeof(wifi_sta_config.sta.bssid));
322 }
323 esp_exceptions(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_sta_config));
324 }
325
Jim Mussared65a3ce32023-10-03 13:32:48 +1100326 esp_exceptions(esp_netif_set_hostname(wlan_sta_obj.netif, mod_network_hostname_data));
Jim Mussaredeb51ca42023-02-01 14:20:45 +1100327
Damien Georgeea186de2021-09-22 00:35:46 +1000328 wifi_sta_reconnects = 0;
329 // connect to the WiFi AP
330 MP_THREAD_GIL_EXIT();
331 esp_exceptions(esp_wifi_connect());
332 MP_THREAD_GIL_ENTER();
333 wifi_sta_connect_requested = true;
334
335 return mp_const_none;
336}
Angus Grattondecf8e62024-02-27 15:32:29 +1100337static MP_DEFINE_CONST_FUN_OBJ_KW(network_wlan_connect_obj, 1, network_wlan_connect);
Damien Georgeea186de2021-09-22 00:35:46 +1000338
Angus Grattondecf8e62024-02-27 15:32:29 +1100339static mp_obj_t network_wlan_disconnect(mp_obj_t self_in) {
Damien Georgeea186de2021-09-22 00:35:46 +1000340 wifi_sta_connect_requested = false;
341 esp_exceptions(esp_wifi_disconnect());
342 return mp_const_none;
343}
Angus Grattondecf8e62024-02-27 15:32:29 +1100344static MP_DEFINE_CONST_FUN_OBJ_1(network_wlan_disconnect_obj, network_wlan_disconnect);
Damien Georgeea186de2021-09-22 00:35:46 +1000345
Angus Grattondecf8e62024-02-27 15:32:29 +1100346static mp_obj_t network_wlan_status(size_t n_args, const mp_obj_t *args) {
Damien Georgeea186de2021-09-22 00:35:46 +1000347 wlan_if_obj_t *self = MP_OBJ_TO_PTR(args[0]);
348 if (n_args == 1) {
Damien Georgee4650122023-05-09 09:52:54 +1000349 if (self->if_id == ESP_IF_WIFI_STA) {
Damien Georgeea186de2021-09-22 00:35:46 +1000350 // Case of no arg is only for the STA interface
351 if (wifi_sta_connected) {
352 // Happy path, connected with IP
353 return MP_OBJ_NEW_SMALL_INT(STAT_GOT_IP);
Ihor Nehrutsad6154922023-11-09 16:18:39 +0200354 } else if (wifi_sta_disconn_reason == WIFI_REASON_NO_AP_FOUND) {
355 return MP_OBJ_NEW_SMALL_INT(WIFI_REASON_NO_AP_FOUND);
356 } else if ((wifi_sta_disconn_reason == WIFI_REASON_AUTH_FAIL) || (wifi_sta_disconn_reason == WIFI_REASON_CONNECTION_FAIL)) {
357 // wrong password
358 return MP_OBJ_NEW_SMALL_INT(WIFI_REASON_AUTH_FAIL);
359 } else if (wifi_sta_disconn_reason == WIFI_REASON_ASSOC_LEAVE) {
360 // After wlan.disconnect()
361 return MP_OBJ_NEW_SMALL_INT(STAT_IDLE);
Damien Georgeea186de2021-09-22 00:35:46 +1000362 } else if (wifi_sta_connect_requested
363 && (conf_wifi_sta_reconnects == 0
364 || wifi_sta_reconnects < conf_wifi_sta_reconnects)) {
365 // No connection or error, but is requested = Still connecting
366 return MP_OBJ_NEW_SMALL_INT(STAT_CONNECTING);
367 } else if (wifi_sta_disconn_reason == 0) {
368 // No activity, No error = Idle
369 return MP_OBJ_NEW_SMALL_INT(STAT_IDLE);
370 } else {
371 // Simply pass the error through from ESP-identifier
372 return MP_OBJ_NEW_SMALL_INT(wifi_sta_disconn_reason);
373 }
374 }
375 return mp_const_none;
376 }
377
378 // one argument: return status based on query parameter
379 switch ((uintptr_t)args[1]) {
380 case (uintptr_t)MP_OBJ_NEW_QSTR(MP_QSTR_stations): {
381 // return list of connected stations, only if in soft-AP mode
Damien Georgee4650122023-05-09 09:52:54 +1000382 require_if(args[0], ESP_IF_WIFI_AP);
Damien Georgeea186de2021-09-22 00:35:46 +1000383 wifi_sta_list_t station_list;
384 esp_exceptions(esp_wifi_ap_get_sta_list(&station_list));
385 wifi_sta_info_t *stations = (wifi_sta_info_t *)station_list.sta;
386 mp_obj_t list = mp_obj_new_list(0, NULL);
387 for (int i = 0; i < station_list.num; ++i) {
388 mp_obj_tuple_t *t = mp_obj_new_tuple(1, NULL);
389 t->items[0] = mp_obj_new_bytes(stations[i].mac, sizeof(stations[i].mac));
390 mp_obj_list_append(list, t);
391 }
392 return list;
393 }
394 case (uintptr_t)MP_OBJ_NEW_QSTR(MP_QSTR_rssi): {
395 // return signal of AP, only in STA mode
Damien Georgee4650122023-05-09 09:52:54 +1000396 require_if(args[0], ESP_IF_WIFI_STA);
Damien Georgeea186de2021-09-22 00:35:46 +1000397
398 wifi_ap_record_t info;
399 esp_exceptions(esp_wifi_sta_get_ap_info(&info));
400 return MP_OBJ_NEW_SMALL_INT(info.rssi);
401 }
402 default:
403 mp_raise_ValueError(MP_ERROR_TEXT("unknown status param"));
404 }
405
406 return mp_const_none;
407}
Angus Grattondecf8e62024-02-27 15:32:29 +1100408static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(network_wlan_status_obj, 1, 2, network_wlan_status);
Damien Georgeea186de2021-09-22 00:35:46 +1000409
Angus Grattondecf8e62024-02-27 15:32:29 +1100410static mp_obj_t network_wlan_scan(mp_obj_t self_in) {
Damien Georgeea186de2021-09-22 00:35:46 +1000411 // check that STA mode is active
412 wifi_mode_t mode;
413 esp_exceptions(esp_wifi_get_mode(&mode));
414 if ((mode & WIFI_MODE_STA) == 0) {
415 mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("STA must be active"));
416 }
417
418 mp_obj_t list = mp_obj_new_list(0, NULL);
419 wifi_scan_config_t config = { 0 };
420 config.show_hidden = true;
421 MP_THREAD_GIL_EXIT();
422 esp_err_t status = esp_wifi_scan_start(&config, 1);
423 MP_THREAD_GIL_ENTER();
424 if (status == 0) {
425 uint16_t count = 0;
426 esp_exceptions(esp_wifi_scan_get_ap_num(&count));
Damien Georgeccaf1972022-06-28 13:15:10 +1000427 if (count == 0) {
428 // esp_wifi_scan_get_ap_records must be called to free internal buffers from the scan.
429 // But it returns an error if wifi_ap_records==NULL. So allocate at least 1 AP entry.
430 // esp_wifi_scan_get_ap_records will then return the actual number of APs in count.
431 count = 1;
432 }
Damien Georgeea186de2021-09-22 00:35:46 +1000433 wifi_ap_record_t *wifi_ap_records = calloc(count, sizeof(wifi_ap_record_t));
434 esp_exceptions(esp_wifi_scan_get_ap_records(&count, wifi_ap_records));
435 for (uint16_t i = 0; i < count; i++) {
436 mp_obj_tuple_t *t = mp_obj_new_tuple(6, NULL);
437 uint8_t *x = memchr(wifi_ap_records[i].ssid, 0, sizeof(wifi_ap_records[i].ssid));
438 int ssid_len = x ? x - wifi_ap_records[i].ssid : sizeof(wifi_ap_records[i].ssid);
439 t->items[0] = mp_obj_new_bytes(wifi_ap_records[i].ssid, ssid_len);
440 t->items[1] = mp_obj_new_bytes(wifi_ap_records[i].bssid, sizeof(wifi_ap_records[i].bssid));
441 t->items[2] = MP_OBJ_NEW_SMALL_INT(wifi_ap_records[i].primary);
442 t->items[3] = MP_OBJ_NEW_SMALL_INT(wifi_ap_records[i].rssi);
443 t->items[4] = MP_OBJ_NEW_SMALL_INT(wifi_ap_records[i].authmode);
444 t->items[5] = mp_const_false; // XXX hidden?
445 mp_obj_list_append(list, MP_OBJ_FROM_PTR(t));
446 }
447 free(wifi_ap_records);
448 }
449 return list;
450}
Angus Grattondecf8e62024-02-27 15:32:29 +1100451static MP_DEFINE_CONST_FUN_OBJ_1(network_wlan_scan_obj, network_wlan_scan);
Damien Georgeea186de2021-09-22 00:35:46 +1000452
Angus Grattondecf8e62024-02-27 15:32:29 +1100453static mp_obj_t network_wlan_isconnected(mp_obj_t self_in) {
Damien Georgeea186de2021-09-22 00:35:46 +1000454 wlan_if_obj_t *self = MP_OBJ_TO_PTR(self_in);
Damien Georgee4650122023-05-09 09:52:54 +1000455 if (self->if_id == ESP_IF_WIFI_STA) {
Damien Georgeea186de2021-09-22 00:35:46 +1000456 return mp_obj_new_bool(wifi_sta_connected);
457 } else {
458 wifi_sta_list_t sta;
459 esp_wifi_ap_get_sta_list(&sta);
460 return mp_obj_new_bool(sta.num != 0);
461 }
462}
Angus Grattondecf8e62024-02-27 15:32:29 +1100463static MP_DEFINE_CONST_FUN_OBJ_1(network_wlan_isconnected_obj, network_wlan_isconnected);
Damien Georgeea186de2021-09-22 00:35:46 +1000464
Angus Grattondecf8e62024-02-27 15:32:29 +1100465static mp_obj_t network_wlan_config(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
Damien Georgeea186de2021-09-22 00:35:46 +1000466 if (n_args != 1 && kwargs->used != 0) {
467 mp_raise_TypeError(MP_ERROR_TEXT("either pos or kw args are allowed"));
468 }
469
470 wlan_if_obj_t *self = MP_OBJ_TO_PTR(args[0]);
471
Damien Georgee4650122023-05-09 09:52:54 +1000472 bool is_wifi = self->if_id == ESP_IF_WIFI_AP || self->if_id == ESP_IF_WIFI_STA;
Damien Georgeea186de2021-09-22 00:35:46 +1000473
474 wifi_config_t cfg;
475 if (is_wifi) {
476 esp_exceptions(esp_wifi_get_config(self->if_id, &cfg));
477 }
478
Damien Georgeea186de2021-09-22 00:35:46 +1000479 if (kwargs->used != 0) {
480 if (!is_wifi) {
481 goto unknown;
482 }
483
484 for (size_t i = 0; i < kwargs->alloc; i++) {
485 if (mp_map_slot_is_filled(kwargs, i)) {
486 int req_if = -1;
487
Damien George5adb1fa2021-12-10 23:28:46 +1100488 switch (mp_obj_str_get_qstr(kwargs->table[i].key)) {
489 case MP_QSTR_mac: {
Damien Georgeea186de2021-09-22 00:35:46 +1000490 mp_buffer_info_t bufinfo;
491 mp_get_buffer_raise(kwargs->table[i].value, &bufinfo, MP_BUFFER_READ);
492 if (bufinfo.len != 6) {
493 mp_raise_ValueError(MP_ERROR_TEXT("invalid buffer length"));
494 }
495 esp_exceptions(esp_wifi_set_mac(self->if_id, bufinfo.buf));
496 break;
497 }
iabdalkadera7c7feb2022-06-04 12:22:55 +0200498 case MP_QSTR_ssid:
Damien George5adb1fa2021-12-10 23:28:46 +1100499 case MP_QSTR_essid: {
Damien Georgee4650122023-05-09 09:52:54 +1000500 req_if = ESP_IF_WIFI_AP;
Damien Georgeea186de2021-09-22 00:35:46 +1000501 size_t len;
502 const char *s = mp_obj_str_get_data(kwargs->table[i].value, &len);
503 len = MIN(len, sizeof(cfg.ap.ssid));
504 memcpy(cfg.ap.ssid, s, len);
505 cfg.ap.ssid_len = len;
506 break;
507 }
Damien George5adb1fa2021-12-10 23:28:46 +1100508 case MP_QSTR_hidden: {
Damien Georgee4650122023-05-09 09:52:54 +1000509 req_if = ESP_IF_WIFI_AP;
Damien Georgeea186de2021-09-22 00:35:46 +1000510 cfg.ap.ssid_hidden = mp_obj_is_true(kwargs->table[i].value);
511 break;
512 }
iabdalkadera7c7feb2022-06-04 12:22:55 +0200513 case MP_QSTR_security:
Damien George5adb1fa2021-12-10 23:28:46 +1100514 case MP_QSTR_authmode: {
Damien Georgee4650122023-05-09 09:52:54 +1000515 req_if = ESP_IF_WIFI_AP;
Damien Georgeea186de2021-09-22 00:35:46 +1000516 cfg.ap.authmode = mp_obj_get_int(kwargs->table[i].value);
517 break;
518 }
iabdalkadera7c7feb2022-06-04 12:22:55 +0200519 case MP_QSTR_key:
Damien George5adb1fa2021-12-10 23:28:46 +1100520 case MP_QSTR_password: {
Damien Georgee4650122023-05-09 09:52:54 +1000521 req_if = ESP_IF_WIFI_AP;
Damien Georgeea186de2021-09-22 00:35:46 +1000522 size_t len;
523 const char *s = mp_obj_str_get_data(kwargs->table[i].value, &len);
524 len = MIN(len, sizeof(cfg.ap.password) - 1);
525 memcpy(cfg.ap.password, s, len);
526 cfg.ap.password[len] = 0;
527 break;
528 }
Damien George5adb1fa2021-12-10 23:28:46 +1100529 case MP_QSTR_channel: {
glenn2098d1c502022-07-31 16:36:10 +1000530 uint8_t primary;
531 wifi_second_chan_t secondary;
532 // Get the current value of secondary
533 esp_exceptions(esp_wifi_get_channel(&primary, &secondary));
534 primary = mp_obj_get_int(kwargs->table[i].value);
535 esp_err_t err = esp_wifi_set_channel(primary, secondary);
536 if (err == ESP_ERR_INVALID_ARG) {
537 // May need to swap secondary channel above to below or below to above
538 secondary = (
539 (secondary == WIFI_SECOND_CHAN_ABOVE)
540 ? WIFI_SECOND_CHAN_BELOW
541 : (secondary == WIFI_SECOND_CHAN_BELOW)
542 ? WIFI_SECOND_CHAN_ABOVE
543 : WIFI_SECOND_CHAN_NONE);
544 esp_exceptions(esp_wifi_set_channel(primary, secondary));
545 }
Damien Georgeea186de2021-09-22 00:35:46 +1000546 break;
547 }
IhorNehrutsa1ea82b62022-06-28 16:38:45 +0300548 case MP_QSTR_hostname:
Damien George5adb1fa2021-12-10 23:28:46 +1100549 case MP_QSTR_dhcp_hostname: {
Jim Mussaredeb51ca42023-02-01 14:20:45 +1100550 // TODO: Deprecated. Use network.hostname(name) instead.
Jim Mussared65a3ce32023-10-03 13:32:48 +1100551 mod_network_hostname(1, &kwargs->table[i].value);
Damien Georgeea186de2021-09-22 00:35:46 +1000552 break;
553 }
Damien George5adb1fa2021-12-10 23:28:46 +1100554 case MP_QSTR_max_clients: {
Damien Georgee4650122023-05-09 09:52:54 +1000555 req_if = ESP_IF_WIFI_AP;
Damien Georgeea186de2021-09-22 00:35:46 +1000556 cfg.ap.max_connection = mp_obj_get_int(kwargs->table[i].value);
557 break;
558 }
Damien George5adb1fa2021-12-10 23:28:46 +1100559 case MP_QSTR_reconnects: {
Damien Georgeea186de2021-09-22 00:35:46 +1000560 int reconnects = mp_obj_get_int(kwargs->table[i].value);
Damien Georgee4650122023-05-09 09:52:54 +1000561 req_if = ESP_IF_WIFI_STA;
Damien Georgeea186de2021-09-22 00:35:46 +1000562 // parameter reconnects == -1 means to retry forever.
563 // here means conf_wifi_sta_reconnects == 0 to retry forever.
564 conf_wifi_sta_reconnects = (reconnects == -1) ? 0 : reconnects + 1;
565 break;
566 }
wemosff28d2e2022-04-11 20:12:57 +0800567 case MP_QSTR_txpower: {
568 int8_t power = (mp_obj_get_float(kwargs->table[i].value) * 4);
569 esp_exceptions(esp_wifi_set_max_tx_power(power));
570 break;
571 }
glenn2076f2e3e2022-07-31 18:17:40 +1000572 case MP_QSTR_protocol: {
573 esp_exceptions(esp_wifi_set_protocol(self->if_id, mp_obj_get_int(kwargs->table[i].value)));
574 break;
575 }
glenn201093dea2022-08-25 16:55:57 +1000576 case MP_QSTR_pm: {
577 esp_exceptions(esp_wifi_set_ps(mp_obj_get_int(kwargs->table[i].value)));
578 break;
579 }
Damien Georgeea186de2021-09-22 00:35:46 +1000580 default:
581 goto unknown;
582 }
583
584 // We post-check interface requirements to save on code size
585 if (req_if >= 0) {
586 require_if(args[0], req_if);
587 }
588 }
589 }
590
591 esp_exceptions(esp_wifi_set_config(self->if_id, &cfg));
592
593 return mp_const_none;
594 }
595
596 // Get config
597
598 if (n_args != 2) {
599 mp_raise_TypeError(MP_ERROR_TEXT("can query only one param"));
600 }
601
602 int req_if = -1;
603 mp_obj_t val = mp_const_none;
604
Damien George5adb1fa2021-12-10 23:28:46 +1100605 switch (mp_obj_str_get_qstr(args[1])) {
606 case MP_QSTR_mac: {
Damien Georgeea186de2021-09-22 00:35:46 +1000607 uint8_t mac[6];
608 switch (self->if_id) {
Damien Georgee4650122023-05-09 09:52:54 +1000609 case ESP_IF_WIFI_AP: // fallthrough intentional
610 case ESP_IF_WIFI_STA:
Damien Georgeea186de2021-09-22 00:35:46 +1000611 esp_exceptions(esp_wifi_get_mac(self->if_id, mac));
612 return mp_obj_new_bytes(mac, sizeof(mac));
613 default:
614 goto unknown;
615 }
616 }
iabdalkadera7c7feb2022-06-04 12:22:55 +0200617 case MP_QSTR_ssid:
Damien George5adb1fa2021-12-10 23:28:46 +1100618 case MP_QSTR_essid:
Damien Georgeea186de2021-09-22 00:35:46 +1000619 switch (self->if_id) {
Damien Georgee4650122023-05-09 09:52:54 +1000620 case ESP_IF_WIFI_STA:
Damien Georgeea186de2021-09-22 00:35:46 +1000621 val = mp_obj_new_str((char *)cfg.sta.ssid, strlen((char *)cfg.sta.ssid));
622 break;
Damien Georgee4650122023-05-09 09:52:54 +1000623 case ESP_IF_WIFI_AP:
Damien Georgeea186de2021-09-22 00:35:46 +1000624 val = mp_obj_new_str((char *)cfg.ap.ssid, cfg.ap.ssid_len);
625 break;
626 default:
Damien Georgee4650122023-05-09 09:52:54 +1000627 req_if = ESP_IF_WIFI_AP;
Damien Georgeea186de2021-09-22 00:35:46 +1000628 }
629 break;
Damien George5adb1fa2021-12-10 23:28:46 +1100630 case MP_QSTR_hidden:
Damien Georgee4650122023-05-09 09:52:54 +1000631 req_if = ESP_IF_WIFI_AP;
Damien Georgeea186de2021-09-22 00:35:46 +1000632 val = mp_obj_new_bool(cfg.ap.ssid_hidden);
633 break;
iabdalkadera7c7feb2022-06-04 12:22:55 +0200634 case MP_QSTR_security:
Damien George5adb1fa2021-12-10 23:28:46 +1100635 case MP_QSTR_authmode:
Damien Georgee4650122023-05-09 09:52:54 +1000636 req_if = ESP_IF_WIFI_AP;
Damien Georgeea186de2021-09-22 00:35:46 +1000637 val = MP_OBJ_NEW_SMALL_INT(cfg.ap.authmode);
638 break;
glenn2098d1c502022-07-31 16:36:10 +1000639 case MP_QSTR_channel: {
640 uint8_t channel;
641 wifi_second_chan_t second;
642 esp_exceptions(esp_wifi_get_channel(&channel, &second));
643 val = MP_OBJ_NEW_SMALL_INT(channel);
Damien Georgeea186de2021-09-22 00:35:46 +1000644 break;
glenn2098d1c502022-07-31 16:36:10 +1000645 }
Daniƫl van de Giessenba8aad32023-07-04 15:36:37 +0200646 case MP_QSTR_ifname: {
647 val = esp_ifname(self->netif);
648 break;
649 }
IhorNehrutsa1ea82b62022-06-28 16:38:45 +0300650 case MP_QSTR_hostname:
Damien George5adb1fa2021-12-10 23:28:46 +1100651 case MP_QSTR_dhcp_hostname: {
Jim Mussaredeb51ca42023-02-01 14:20:45 +1100652 // TODO: Deprecated. Use network.hostname() instead.
Damien Georgee4650122023-05-09 09:52:54 +1000653 req_if = ESP_IF_WIFI_STA;
Jim Mussared65a3ce32023-10-03 13:32:48 +1100654 val = mod_network_hostname(0, NULL);
Damien Georgeea186de2021-09-22 00:35:46 +1000655 break;
656 }
Damien George5adb1fa2021-12-10 23:28:46 +1100657 case MP_QSTR_max_clients: {
Damien Georgeea186de2021-09-22 00:35:46 +1000658 val = MP_OBJ_NEW_SMALL_INT(cfg.ap.max_connection);
659 break;
660 }
Damien George5adb1fa2021-12-10 23:28:46 +1100661 case MP_QSTR_reconnects:
Damien Georgee4650122023-05-09 09:52:54 +1000662 req_if = ESP_IF_WIFI_STA;
Damien Georgeea186de2021-09-22 00:35:46 +1000663 int rec = conf_wifi_sta_reconnects - 1;
664 val = MP_OBJ_NEW_SMALL_INT(rec);
665 break;
wemosff28d2e2022-04-11 20:12:57 +0800666 case MP_QSTR_txpower: {
667 int8_t power;
668 esp_exceptions(esp_wifi_get_max_tx_power(&power));
669 val = mp_obj_new_float(power * 0.25);
670 break;
671 }
glenn2076f2e3e2022-07-31 18:17:40 +1000672 case MP_QSTR_protocol: {
673 uint8_t protocol_bitmap;
674 esp_exceptions(esp_wifi_get_protocol(self->if_id, &protocol_bitmap));
675 val = MP_OBJ_NEW_SMALL_INT(protocol_bitmap);
676 break;
677 }
glenn201093dea2022-08-25 16:55:57 +1000678 case MP_QSTR_pm: {
679 wifi_ps_type_t ps_type;
680 esp_exceptions(esp_wifi_get_ps(&ps_type));
681 val = MP_OBJ_NEW_SMALL_INT(ps_type);
682 break;
683 }
Damien Georgeea186de2021-09-22 00:35:46 +1000684 default:
685 goto unknown;
686 }
687
Damien Georgeea186de2021-09-22 00:35:46 +1000688 // We post-check interface requirements to save on code size
689 if (req_if >= 0) {
690 require_if(args[0], req_if);
691 }
692
693 return val;
694
695unknown:
696 mp_raise_ValueError(MP_ERROR_TEXT("unknown config param"));
697}
698MP_DEFINE_CONST_FUN_OBJ_KW(network_wlan_config_obj, 1, network_wlan_config);
699
Angus Grattondecf8e62024-02-27 15:32:29 +1100700static const mp_rom_map_elem_t wlan_if_locals_dict_table[] = {
Damien Georgeea186de2021-09-22 00:35:46 +1000701 { MP_ROM_QSTR(MP_QSTR_active), MP_ROM_PTR(&network_wlan_active_obj) },
702 { MP_ROM_QSTR(MP_QSTR_connect), MP_ROM_PTR(&network_wlan_connect_obj) },
703 { MP_ROM_QSTR(MP_QSTR_disconnect), MP_ROM_PTR(&network_wlan_disconnect_obj) },
704 { MP_ROM_QSTR(MP_QSTR_status), MP_ROM_PTR(&network_wlan_status_obj) },
705 { MP_ROM_QSTR(MP_QSTR_scan), MP_ROM_PTR(&network_wlan_scan_obj) },
706 { MP_ROM_QSTR(MP_QSTR_isconnected), MP_ROM_PTR(&network_wlan_isconnected_obj) },
707 { MP_ROM_QSTR(MP_QSTR_config), MP_ROM_PTR(&network_wlan_config_obj) },
Jim Mussaredeb51ca42023-02-01 14:20:45 +1100708 { MP_ROM_QSTR(MP_QSTR_ifconfig), MP_ROM_PTR(&esp_network_ifconfig_obj) },
glenn201093dea2022-08-25 16:55:57 +1000709
710 // Constants
711 { MP_ROM_QSTR(MP_QSTR_PM_NONE), MP_ROM_INT(WIFI_PS_NONE) },
712 { MP_ROM_QSTR(MP_QSTR_PM_PERFORMANCE), MP_ROM_INT(WIFI_PS_MIN_MODEM) },
713 { MP_ROM_QSTR(MP_QSTR_PM_POWERSAVE), MP_ROM_INT(WIFI_PS_MAX_MODEM) },
Damien Georgeea186de2021-09-22 00:35:46 +1000714};
Angus Grattondecf8e62024-02-27 15:32:29 +1100715static MP_DEFINE_CONST_DICT(wlan_if_locals_dict, wlan_if_locals_dict_table);
Damien Georgeea186de2021-09-22 00:35:46 +1000716
Jim Mussared662b9762021-07-14 14:38:38 +1000717MP_DEFINE_CONST_OBJ_TYPE(
Damien George53cb0732023-05-11 11:51:02 +1000718 esp_network_wlan_type,
Jim Mussared662b9762021-07-14 14:38:38 +1000719 MP_QSTR_WLAN,
720 MP_TYPE_FLAG_NONE,
Damien George53cb0732023-05-11 11:51:02 +1000721 make_new, network_wlan_make_new,
Jim Mussared9dce8272022-06-24 16:27:46 +1000722 locals_dict, &wlan_if_locals_dict
Jim Mussared662b9762021-07-14 14:38:38 +1000723 );
724
Damien Georgeea186de2021-09-22 00:35:46 +1000725#endif // MICROPY_PY_NETWORK_WLAN