blob: ece88e705f9422f41d36bc7ff83533ff0b8c1d24 [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;
Daniël van de Giessend6176c12024-02-29 14:05:01 +0100116 #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 2, 0)
117 case WIFI_REASON_NO_AP_FOUND_IN_RSSI_THRESHOLD:
118 // No AP with RSSI within given threshold exists, or it may have momentarily dropped out; try to reconnect.
119 message = "no AP with RSSI within threshold found";
120 break;
121 case WIFI_REASON_NO_AP_FOUND_IN_AUTHMODE_THRESHOLD:
122 // No AP with authmode within given threshold exists, or it may have momentarily dropped out; try to reconnect.
123 message = "no AP with authmode within threshold found";
124 break;
125 case WIFI_REASON_NO_AP_FOUND_W_COMPATIBLE_SECURITY:
126 // No AP with compatible security exists, or it may have momentarily dropped out; try to reconnect.
127 message = "no AP with compatible security found";
128 break;
129 #endif
Damien Georgeea186de2021-09-22 00:35:46 +1000130 case WIFI_REASON_AUTH_FAIL:
131 // Password may be wrong, or it just failed to connect; try to reconnect.
Ihor Nehrutsad6154922023-11-09 16:18:39 +0200132 message = "authentication failed";
Damien Georgeea186de2021-09-22 00:35:46 +1000133 break;
134 default:
135 // Let other errors through and try to reconnect.
136 break;
137 }
Ihor Nehrutsad6154922023-11-09 16:18:39 +0200138 ESP_LOGI("wifi", "STA_DISCONNECTED, reason:%d:%s", disconn->reason, message);
Damien Georgeea186de2021-09-22 00:35:46 +1000139
140 wifi_sta_connected = false;
141 if (wifi_sta_connect_requested) {
142 wifi_mode_t mode;
143 if (esp_wifi_get_mode(&mode) != ESP_OK) {
144 break;
145 }
146 if (!(mode & WIFI_MODE_STA)) {
147 break;
148 }
149 if (conf_wifi_sta_reconnects) {
150 ESP_LOGI("wifi", "reconnect counter=%d, max=%d",
151 wifi_sta_reconnects, conf_wifi_sta_reconnects);
152 if (++wifi_sta_reconnects >= conf_wifi_sta_reconnects) {
153 break;
154 }
155 }
156 esp_err_t e = esp_wifi_connect();
157 if (e != ESP_OK) {
158 ESP_LOGI("wifi", "error attempting to reconnect: 0x%04x", e);
159 }
160 }
161 break;
162 }
Glenn Moloneydbced752023-07-01 13:54:44 +1000163
164 case WIFI_EVENT_AP_START:
165 wlan_ap_obj.active = true;
166 break;
167
168 case WIFI_EVENT_AP_STOP:
169 wlan_ap_obj.active = false;
170 break;
171
Damien Georgeea186de2021-09-22 00:35:46 +1000172 default:
173 break;
174 }
175}
176
Damien Georgee4650122023-05-09 09:52:54 +1000177static void network_wlan_ip_event_handler(void *event_handler_arg, esp_event_base_t event_base, int32_t event_id, void *event_data) {
178 switch (event_id) {
179 case IP_EVENT_STA_GOT_IP:
180 ESP_LOGI("network", "GOT_IP");
181 wifi_sta_connected = true;
182 wifi_sta_disconn_reason = 0; // Success so clear error. (in case of new error will be replaced anyway)
183 #if MICROPY_HW_ENABLE_MDNS_QUERIES || MICROPY_HW_ENABLE_MDNS_RESPONDER
184 if (!mdns_initialised) {
185 mdns_init();
186 #if MICROPY_HW_ENABLE_MDNS_RESPONDER
Jim Mussared65a3ce32023-10-03 13:32:48 +1100187 mdns_hostname_set(mod_network_hostname_data);
188 mdns_instance_name_set(mod_network_hostname_data);
Damien Georgee4650122023-05-09 09:52:54 +1000189 #endif
190 mdns_initialised = true;
191 }
192 #endif
193 break;
194
195 default:
196 break;
Damien Georgeea186de2021-09-22 00:35:46 +1000197 }
198}
199
Angus Grattondecf8e62024-02-27 15:32:29 +1100200static void require_if(mp_obj_t wlan_if, int if_no) {
Damien Georgee4650122023-05-09 09:52:54 +1000201 wlan_if_obj_t *self = MP_OBJ_TO_PTR(wlan_if);
202 if (self->if_id != if_no) {
203 mp_raise_msg(&mp_type_OSError, if_no == ESP_IF_WIFI_STA ? MP_ERROR_TEXT("STA required") : MP_ERROR_TEXT("AP required"));
204 }
205}
206
207void esp_initialise_wifi(void) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000208 static int wifi_initialized = 0;
209 if (!wifi_initialized) {
Damien Georgee4650122023-05-09 09:52:54 +1000210 esp_exceptions(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, network_wlan_wifi_event_handler, NULL, NULL));
211 esp_exceptions(esp_event_handler_instance_register(IP_EVENT, ESP_EVENT_ANY_ID, network_wlan_ip_event_handler, NULL, NULL));
212
213 wlan_sta_obj.base.type = &esp_network_wlan_type;
214 wlan_sta_obj.if_id = ESP_IF_WIFI_STA;
215 wlan_sta_obj.netif = esp_netif_create_default_wifi_sta();
Glenn Moloneydbced752023-07-01 13:54:44 +1000216 wlan_sta_obj.active = false;
Damien Georgee4650122023-05-09 09:52:54 +1000217
218 wlan_ap_obj.base.type = &esp_network_wlan_type;
219 wlan_ap_obj.if_id = ESP_IF_WIFI_AP;
220 wlan_ap_obj.netif = esp_netif_create_default_wifi_ap();
Glenn Moloneydbced752023-07-01 13:54:44 +1000221 wlan_ap_obj.active = false;
Damien Georgee4650122023-05-09 09:52:54 +1000222
Damien Georgeea186de2021-09-22 00:35:46 +1000223 wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
Angus Gratton960eef72023-11-14 16:46:55 +1100224 #if CONFIG_SPIRAM_IGNORE_NOTFOUND
225 if (!esp_psram_is_initialized()) {
226 // If PSRAM failed to initialize, disable "Wi-Fi Cache TX Buffers"
227 // (default SPIRAM config ESP32_WIFI_CACHE_TX_BUFFER_NUM==32, this is 54,400 bytes of heap)
228 cfg.cache_tx_buf_num = 0;
229 cfg.feature_caps &= ~CONFIG_FEATURE_CACHE_TX_BUF_BIT;
230
231 // Set some other options back to the non-SPIRAM default values
232 // to save more RAM.
233 //
234 // These can be determined from ESP-IDF components/esp_wifi/Kconfig and the
235 // WIFI_INIT_CONFIG_DEFAULT macro
236 cfg.tx_buf_type = 1; // Dynamic, this "magic number" is defined in IDF KConfig
237 cfg.static_tx_buf_num = 0; // Probably don't need, due to tx_buf_type
238 cfg.dynamic_tx_buf_num = 32; // ESP-IDF default value (maximum)
239 }
240 #endif
Damien Georgeea186de2021-09-22 00:35:46 +1000241 ESP_LOGD("modnetwork", "Initializing WiFi");
242 esp_exceptions(esp_wifi_init(&cfg));
243 esp_exceptions(esp_wifi_set_storage(WIFI_STORAGE_RAM));
Damien Georgee4650122023-05-09 09:52:54 +1000244
Damien Georgeea186de2021-09-22 00:35:46 +1000245 ESP_LOGD("modnetwork", "Initialized");
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000246 wifi_initialized = 1;
Damien Georgeea186de2021-09-22 00:35:46 +1000247 }
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000248}
249
Angus Grattondecf8e62024-02-27 15:32:29 +1100250static 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 +1000251 mp_arg_check_num(n_args, n_kw, 0, 1, false);
252
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000253 esp_initialise_wifi();
Damien Georgeea186de2021-09-22 00:35:46 +1000254
Damien Georgee4650122023-05-09 09:52:54 +1000255 int idx = (n_args > 0) ? mp_obj_get_int(args[0]) : ESP_IF_WIFI_STA;
256 if (idx == ESP_IF_WIFI_STA) {
Damien Georgeea186de2021-09-22 00:35:46 +1000257 return MP_OBJ_FROM_PTR(&wlan_sta_obj);
Damien Georgee4650122023-05-09 09:52:54 +1000258 } else if (idx == ESP_IF_WIFI_AP) {
Damien Georgeea186de2021-09-22 00:35:46 +1000259 return MP_OBJ_FROM_PTR(&wlan_ap_obj);
260 } else {
261 mp_raise_ValueError(MP_ERROR_TEXT("invalid WLAN interface identifier"));
262 }
263}
Damien Georgeea186de2021-09-22 00:35:46 +1000264
Angus Grattondecf8e62024-02-27 15:32:29 +1100265static mp_obj_t network_wlan_active(size_t n_args, const mp_obj_t *args) {
Damien Georgeea186de2021-09-22 00:35:46 +1000266 wlan_if_obj_t *self = MP_OBJ_TO_PTR(args[0]);
267
268 wifi_mode_t mode;
269 if (!wifi_started) {
270 mode = WIFI_MODE_NULL;
271 } else {
272 esp_exceptions(esp_wifi_get_mode(&mode));
273 }
274
Damien Georgee4650122023-05-09 09:52:54 +1000275 int bit = (self->if_id == ESP_IF_WIFI_STA) ? WIFI_MODE_STA : WIFI_MODE_AP;
Damien Georgeea186de2021-09-22 00:35:46 +1000276
277 if (n_args > 1) {
278 bool active = mp_obj_is_true(args[1]);
279 mode = active ? (mode | bit) : (mode & ~bit);
280 if (mode == WIFI_MODE_NULL) {
281 if (wifi_started) {
282 esp_exceptions(esp_wifi_stop());
283 wifi_started = false;
284 }
285 } else {
286 esp_exceptions(esp_wifi_set_mode(mode));
287 if (!wifi_started) {
288 esp_exceptions(esp_wifi_start());
289 wifi_started = true;
290 }
291 }
Glenn Moloneydbced752023-07-01 13:54:44 +1000292
293 // Wait for the interface to be in the correct state.
294 while (self->active != active) {
295 MICROPY_EVENT_POLL_HOOK;
296 }
Damien Georgeea186de2021-09-22 00:35:46 +1000297 }
298
299 return (mode & bit) ? mp_const_true : mp_const_false;
300}
Angus Grattondecf8e62024-02-27 15:32:29 +1100301static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(network_wlan_active_obj, 1, 2, network_wlan_active);
Damien Georgeea186de2021-09-22 00:35:46 +1000302
Angus Grattondecf8e62024-02-27 15:32:29 +1100303static 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 +0200304 enum { ARG_ssid, ARG_key, ARG_bssid };
Damien Georgeea186de2021-09-22 00:35:46 +1000305 static const mp_arg_t allowed_args[] = {
306 { MP_QSTR_, MP_ARG_OBJ, {.u_obj = mp_const_none} },
307 { MP_QSTR_, MP_ARG_OBJ, {.u_obj = mp_const_none} },
308 { MP_QSTR_bssid, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
309 };
310
311 // parse args
312 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
313 mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
314
315 wifi_config_t wifi_sta_config = {0};
316
317 // configure any parameters that are given
318 if (n_args > 1) {
319 size_t len;
320 const char *p;
321 if (args[ARG_ssid].u_obj != mp_const_none) {
322 p = mp_obj_str_get_data(args[ARG_ssid].u_obj, &len);
323 memcpy(wifi_sta_config.sta.ssid, p, MIN(len, sizeof(wifi_sta_config.sta.ssid)));
324 }
iabdalkadera7c7feb2022-06-04 12:22:55 +0200325 if (args[ARG_key].u_obj != mp_const_none) {
326 p = mp_obj_str_get_data(args[ARG_key].u_obj, &len);
Damien Georgeea186de2021-09-22 00:35:46 +1000327 memcpy(wifi_sta_config.sta.password, p, MIN(len, sizeof(wifi_sta_config.sta.password)));
328 }
329 if (args[ARG_bssid].u_obj != mp_const_none) {
330 p = mp_obj_str_get_data(args[ARG_bssid].u_obj, &len);
331 if (len != sizeof(wifi_sta_config.sta.bssid)) {
332 mp_raise_ValueError(NULL);
333 }
334 wifi_sta_config.sta.bssid_set = 1;
335 memcpy(wifi_sta_config.sta.bssid, p, sizeof(wifi_sta_config.sta.bssid));
336 }
337 esp_exceptions(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_sta_config));
338 }
339
Jim Mussared65a3ce32023-10-03 13:32:48 +1100340 esp_exceptions(esp_netif_set_hostname(wlan_sta_obj.netif, mod_network_hostname_data));
Jim Mussaredeb51ca42023-02-01 14:20:45 +1100341
Damien Georgeea186de2021-09-22 00:35:46 +1000342 wifi_sta_reconnects = 0;
343 // connect to the WiFi AP
344 MP_THREAD_GIL_EXIT();
345 esp_exceptions(esp_wifi_connect());
346 MP_THREAD_GIL_ENTER();
347 wifi_sta_connect_requested = true;
348
349 return mp_const_none;
350}
Angus Grattondecf8e62024-02-27 15:32:29 +1100351static MP_DEFINE_CONST_FUN_OBJ_KW(network_wlan_connect_obj, 1, network_wlan_connect);
Damien Georgeea186de2021-09-22 00:35:46 +1000352
Angus Grattondecf8e62024-02-27 15:32:29 +1100353static mp_obj_t network_wlan_disconnect(mp_obj_t self_in) {
Damien Georgeea186de2021-09-22 00:35:46 +1000354 wifi_sta_connect_requested = false;
355 esp_exceptions(esp_wifi_disconnect());
356 return mp_const_none;
357}
Angus Grattondecf8e62024-02-27 15:32:29 +1100358static MP_DEFINE_CONST_FUN_OBJ_1(network_wlan_disconnect_obj, network_wlan_disconnect);
Damien Georgeea186de2021-09-22 00:35:46 +1000359
Angus Grattondecf8e62024-02-27 15:32:29 +1100360static mp_obj_t network_wlan_status(size_t n_args, const mp_obj_t *args) {
Damien Georgeea186de2021-09-22 00:35:46 +1000361 wlan_if_obj_t *self = MP_OBJ_TO_PTR(args[0]);
362 if (n_args == 1) {
Damien Georgee4650122023-05-09 09:52:54 +1000363 if (self->if_id == ESP_IF_WIFI_STA) {
Damien Georgeea186de2021-09-22 00:35:46 +1000364 // Case of no arg is only for the STA interface
365 if (wifi_sta_connected) {
366 // Happy path, connected with IP
367 return MP_OBJ_NEW_SMALL_INT(STAT_GOT_IP);
Ihor Nehrutsad6154922023-11-09 16:18:39 +0200368 } else if (wifi_sta_disconn_reason == WIFI_REASON_NO_AP_FOUND) {
369 return MP_OBJ_NEW_SMALL_INT(WIFI_REASON_NO_AP_FOUND);
Daniël van de Giessend6176c12024-02-29 14:05:01 +0100370 #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 2, 0)
371 } else if (wifi_sta_disconn_reason == WIFI_REASON_NO_AP_FOUND_IN_RSSI_THRESHOLD) {
372 return MP_OBJ_NEW_SMALL_INT(WIFI_REASON_NO_AP_FOUND_IN_RSSI_THRESHOLD);
373 } else if (wifi_sta_disconn_reason == WIFI_REASON_NO_AP_FOUND_IN_AUTHMODE_THRESHOLD) {
374 return MP_OBJ_NEW_SMALL_INT(WIFI_REASON_NO_AP_FOUND_IN_AUTHMODE_THRESHOLD);
375 } else if (wifi_sta_disconn_reason == WIFI_REASON_NO_AP_FOUND_W_COMPATIBLE_SECURITY) {
376 return MP_OBJ_NEW_SMALL_INT(WIFI_REASON_NO_AP_FOUND_W_COMPATIBLE_SECURITY);
377 #endif
Ihor Nehrutsad6154922023-11-09 16:18:39 +0200378 } else if ((wifi_sta_disconn_reason == WIFI_REASON_AUTH_FAIL) || (wifi_sta_disconn_reason == WIFI_REASON_CONNECTION_FAIL)) {
379 // wrong password
380 return MP_OBJ_NEW_SMALL_INT(WIFI_REASON_AUTH_FAIL);
381 } else if (wifi_sta_disconn_reason == WIFI_REASON_ASSOC_LEAVE) {
382 // After wlan.disconnect()
383 return MP_OBJ_NEW_SMALL_INT(STAT_IDLE);
Damien Georgeea186de2021-09-22 00:35:46 +1000384 } else if (wifi_sta_connect_requested
385 && (conf_wifi_sta_reconnects == 0
386 || wifi_sta_reconnects < conf_wifi_sta_reconnects)) {
387 // No connection or error, but is requested = Still connecting
388 return MP_OBJ_NEW_SMALL_INT(STAT_CONNECTING);
389 } else if (wifi_sta_disconn_reason == 0) {
390 // No activity, No error = Idle
391 return MP_OBJ_NEW_SMALL_INT(STAT_IDLE);
392 } else {
393 // Simply pass the error through from ESP-identifier
394 return MP_OBJ_NEW_SMALL_INT(wifi_sta_disconn_reason);
395 }
396 }
397 return mp_const_none;
398 }
399
400 // one argument: return status based on query parameter
401 switch ((uintptr_t)args[1]) {
402 case (uintptr_t)MP_OBJ_NEW_QSTR(MP_QSTR_stations): {
403 // return list of connected stations, only if in soft-AP mode
Damien Georgee4650122023-05-09 09:52:54 +1000404 require_if(args[0], ESP_IF_WIFI_AP);
Damien Georgeea186de2021-09-22 00:35:46 +1000405 wifi_sta_list_t station_list;
406 esp_exceptions(esp_wifi_ap_get_sta_list(&station_list));
407 wifi_sta_info_t *stations = (wifi_sta_info_t *)station_list.sta;
408 mp_obj_t list = mp_obj_new_list(0, NULL);
409 for (int i = 0; i < station_list.num; ++i) {
410 mp_obj_tuple_t *t = mp_obj_new_tuple(1, NULL);
411 t->items[0] = mp_obj_new_bytes(stations[i].mac, sizeof(stations[i].mac));
412 mp_obj_list_append(list, t);
413 }
414 return list;
415 }
416 case (uintptr_t)MP_OBJ_NEW_QSTR(MP_QSTR_rssi): {
417 // return signal of AP, only in STA mode
Damien Georgee4650122023-05-09 09:52:54 +1000418 require_if(args[0], ESP_IF_WIFI_STA);
Damien Georgeea186de2021-09-22 00:35:46 +1000419
420 wifi_ap_record_t info;
421 esp_exceptions(esp_wifi_sta_get_ap_info(&info));
422 return MP_OBJ_NEW_SMALL_INT(info.rssi);
423 }
424 default:
425 mp_raise_ValueError(MP_ERROR_TEXT("unknown status param"));
426 }
427
428 return mp_const_none;
429}
Angus Grattondecf8e62024-02-27 15:32:29 +1100430static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(network_wlan_status_obj, 1, 2, network_wlan_status);
Damien Georgeea186de2021-09-22 00:35:46 +1000431
Angus Grattondecf8e62024-02-27 15:32:29 +1100432static mp_obj_t network_wlan_scan(mp_obj_t self_in) {
Damien Georgeea186de2021-09-22 00:35:46 +1000433 // check that STA mode is active
434 wifi_mode_t mode;
435 esp_exceptions(esp_wifi_get_mode(&mode));
436 if ((mode & WIFI_MODE_STA) == 0) {
437 mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("STA must be active"));
438 }
439
440 mp_obj_t list = mp_obj_new_list(0, NULL);
441 wifi_scan_config_t config = { 0 };
442 config.show_hidden = true;
443 MP_THREAD_GIL_EXIT();
444 esp_err_t status = esp_wifi_scan_start(&config, 1);
445 MP_THREAD_GIL_ENTER();
446 if (status == 0) {
447 uint16_t count = 0;
448 esp_exceptions(esp_wifi_scan_get_ap_num(&count));
Damien Georgeccaf1972022-06-28 13:15:10 +1000449 if (count == 0) {
450 // esp_wifi_scan_get_ap_records must be called to free internal buffers from the scan.
451 // But it returns an error if wifi_ap_records==NULL. So allocate at least 1 AP entry.
452 // esp_wifi_scan_get_ap_records will then return the actual number of APs in count.
453 count = 1;
454 }
Damien Georgeea186de2021-09-22 00:35:46 +1000455 wifi_ap_record_t *wifi_ap_records = calloc(count, sizeof(wifi_ap_record_t));
456 esp_exceptions(esp_wifi_scan_get_ap_records(&count, wifi_ap_records));
457 for (uint16_t i = 0; i < count; i++) {
458 mp_obj_tuple_t *t = mp_obj_new_tuple(6, NULL);
459 uint8_t *x = memchr(wifi_ap_records[i].ssid, 0, sizeof(wifi_ap_records[i].ssid));
460 int ssid_len = x ? x - wifi_ap_records[i].ssid : sizeof(wifi_ap_records[i].ssid);
461 t->items[0] = mp_obj_new_bytes(wifi_ap_records[i].ssid, ssid_len);
462 t->items[1] = mp_obj_new_bytes(wifi_ap_records[i].bssid, sizeof(wifi_ap_records[i].bssid));
463 t->items[2] = MP_OBJ_NEW_SMALL_INT(wifi_ap_records[i].primary);
464 t->items[3] = MP_OBJ_NEW_SMALL_INT(wifi_ap_records[i].rssi);
465 t->items[4] = MP_OBJ_NEW_SMALL_INT(wifi_ap_records[i].authmode);
466 t->items[5] = mp_const_false; // XXX hidden?
467 mp_obj_list_append(list, MP_OBJ_FROM_PTR(t));
468 }
469 free(wifi_ap_records);
470 }
471 return list;
472}
Angus Grattondecf8e62024-02-27 15:32:29 +1100473static MP_DEFINE_CONST_FUN_OBJ_1(network_wlan_scan_obj, network_wlan_scan);
Damien Georgeea186de2021-09-22 00:35:46 +1000474
Angus Grattondecf8e62024-02-27 15:32:29 +1100475static mp_obj_t network_wlan_isconnected(mp_obj_t self_in) {
Damien Georgeea186de2021-09-22 00:35:46 +1000476 wlan_if_obj_t *self = MP_OBJ_TO_PTR(self_in);
Damien Georgee4650122023-05-09 09:52:54 +1000477 if (self->if_id == ESP_IF_WIFI_STA) {
Damien Georgeea186de2021-09-22 00:35:46 +1000478 return mp_obj_new_bool(wifi_sta_connected);
479 } else {
480 wifi_sta_list_t sta;
481 esp_wifi_ap_get_sta_list(&sta);
482 return mp_obj_new_bool(sta.num != 0);
483 }
484}
Angus Grattondecf8e62024-02-27 15:32:29 +1100485static MP_DEFINE_CONST_FUN_OBJ_1(network_wlan_isconnected_obj, network_wlan_isconnected);
Damien Georgeea186de2021-09-22 00:35:46 +1000486
Angus Grattondecf8e62024-02-27 15:32:29 +1100487static 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 +1000488 if (n_args != 1 && kwargs->used != 0) {
489 mp_raise_TypeError(MP_ERROR_TEXT("either pos or kw args are allowed"));
490 }
491
492 wlan_if_obj_t *self = MP_OBJ_TO_PTR(args[0]);
493
Damien Georgee4650122023-05-09 09:52:54 +1000494 bool is_wifi = self->if_id == ESP_IF_WIFI_AP || self->if_id == ESP_IF_WIFI_STA;
Damien Georgeea186de2021-09-22 00:35:46 +1000495
496 wifi_config_t cfg;
497 if (is_wifi) {
498 esp_exceptions(esp_wifi_get_config(self->if_id, &cfg));
499 }
500
Damien Georgeea186de2021-09-22 00:35:46 +1000501 if (kwargs->used != 0) {
502 if (!is_wifi) {
503 goto unknown;
504 }
505
506 for (size_t i = 0; i < kwargs->alloc; i++) {
507 if (mp_map_slot_is_filled(kwargs, i)) {
508 int req_if = -1;
509
Damien George5adb1fa2021-12-10 23:28:46 +1100510 switch (mp_obj_str_get_qstr(kwargs->table[i].key)) {
511 case MP_QSTR_mac: {
Damien Georgeea186de2021-09-22 00:35:46 +1000512 mp_buffer_info_t bufinfo;
513 mp_get_buffer_raise(kwargs->table[i].value, &bufinfo, MP_BUFFER_READ);
514 if (bufinfo.len != 6) {
515 mp_raise_ValueError(MP_ERROR_TEXT("invalid buffer length"));
516 }
517 esp_exceptions(esp_wifi_set_mac(self->if_id, bufinfo.buf));
518 break;
519 }
iabdalkadera7c7feb2022-06-04 12:22:55 +0200520 case MP_QSTR_ssid:
Damien George5adb1fa2021-12-10 23:28:46 +1100521 case MP_QSTR_essid: {
Damien Georgee4650122023-05-09 09:52:54 +1000522 req_if = ESP_IF_WIFI_AP;
Damien Georgeea186de2021-09-22 00:35:46 +1000523 size_t len;
524 const char *s = mp_obj_str_get_data(kwargs->table[i].value, &len);
525 len = MIN(len, sizeof(cfg.ap.ssid));
526 memcpy(cfg.ap.ssid, s, len);
527 cfg.ap.ssid_len = len;
528 break;
529 }
Damien George5adb1fa2021-12-10 23:28:46 +1100530 case MP_QSTR_hidden: {
Damien Georgee4650122023-05-09 09:52:54 +1000531 req_if = ESP_IF_WIFI_AP;
Damien Georgeea186de2021-09-22 00:35:46 +1000532 cfg.ap.ssid_hidden = mp_obj_is_true(kwargs->table[i].value);
533 break;
534 }
iabdalkadera7c7feb2022-06-04 12:22:55 +0200535 case MP_QSTR_security:
Damien George5adb1fa2021-12-10 23:28:46 +1100536 case MP_QSTR_authmode: {
Damien Georgee4650122023-05-09 09:52:54 +1000537 req_if = ESP_IF_WIFI_AP;
Damien Georgeea186de2021-09-22 00:35:46 +1000538 cfg.ap.authmode = mp_obj_get_int(kwargs->table[i].value);
539 break;
540 }
iabdalkadera7c7feb2022-06-04 12:22:55 +0200541 case MP_QSTR_key:
Damien George5adb1fa2021-12-10 23:28:46 +1100542 case MP_QSTR_password: {
Damien Georgee4650122023-05-09 09:52:54 +1000543 req_if = ESP_IF_WIFI_AP;
Damien Georgeea186de2021-09-22 00:35:46 +1000544 size_t len;
545 const char *s = mp_obj_str_get_data(kwargs->table[i].value, &len);
546 len = MIN(len, sizeof(cfg.ap.password) - 1);
547 memcpy(cfg.ap.password, s, len);
548 cfg.ap.password[len] = 0;
549 break;
550 }
Damien George5adb1fa2021-12-10 23:28:46 +1100551 case MP_QSTR_channel: {
glenn2098d1c502022-07-31 16:36:10 +1000552 uint8_t primary;
553 wifi_second_chan_t secondary;
554 // Get the current value of secondary
555 esp_exceptions(esp_wifi_get_channel(&primary, &secondary));
556 primary = mp_obj_get_int(kwargs->table[i].value);
557 esp_err_t err = esp_wifi_set_channel(primary, secondary);
558 if (err == ESP_ERR_INVALID_ARG) {
559 // May need to swap secondary channel above to below or below to above
560 secondary = (
561 (secondary == WIFI_SECOND_CHAN_ABOVE)
562 ? WIFI_SECOND_CHAN_BELOW
563 : (secondary == WIFI_SECOND_CHAN_BELOW)
564 ? WIFI_SECOND_CHAN_ABOVE
565 : WIFI_SECOND_CHAN_NONE);
566 esp_exceptions(esp_wifi_set_channel(primary, secondary));
567 }
Damien Georgeea186de2021-09-22 00:35:46 +1000568 break;
569 }
IhorNehrutsa1ea82b62022-06-28 16:38:45 +0300570 case MP_QSTR_hostname:
Damien George5adb1fa2021-12-10 23:28:46 +1100571 case MP_QSTR_dhcp_hostname: {
Jim Mussaredeb51ca42023-02-01 14:20:45 +1100572 // TODO: Deprecated. Use network.hostname(name) instead.
Jim Mussared65a3ce32023-10-03 13:32:48 +1100573 mod_network_hostname(1, &kwargs->table[i].value);
Damien Georgeea186de2021-09-22 00:35:46 +1000574 break;
575 }
Damien George5adb1fa2021-12-10 23:28:46 +1100576 case MP_QSTR_max_clients: {
Damien Georgee4650122023-05-09 09:52:54 +1000577 req_if = ESP_IF_WIFI_AP;
Damien Georgeea186de2021-09-22 00:35:46 +1000578 cfg.ap.max_connection = mp_obj_get_int(kwargs->table[i].value);
579 break;
580 }
Damien George5adb1fa2021-12-10 23:28:46 +1100581 case MP_QSTR_reconnects: {
Damien Georgeea186de2021-09-22 00:35:46 +1000582 int reconnects = mp_obj_get_int(kwargs->table[i].value);
Damien Georgee4650122023-05-09 09:52:54 +1000583 req_if = ESP_IF_WIFI_STA;
Damien Georgeea186de2021-09-22 00:35:46 +1000584 // parameter reconnects == -1 means to retry forever.
585 // here means conf_wifi_sta_reconnects == 0 to retry forever.
586 conf_wifi_sta_reconnects = (reconnects == -1) ? 0 : reconnects + 1;
587 break;
588 }
wemosff28d2e2022-04-11 20:12:57 +0800589 case MP_QSTR_txpower: {
590 int8_t power = (mp_obj_get_float(kwargs->table[i].value) * 4);
591 esp_exceptions(esp_wifi_set_max_tx_power(power));
592 break;
593 }
glenn2076f2e3e2022-07-31 18:17:40 +1000594 case MP_QSTR_protocol: {
595 esp_exceptions(esp_wifi_set_protocol(self->if_id, mp_obj_get_int(kwargs->table[i].value)));
596 break;
597 }
glenn201093dea2022-08-25 16:55:57 +1000598 case MP_QSTR_pm: {
599 esp_exceptions(esp_wifi_set_ps(mp_obj_get_int(kwargs->table[i].value)));
600 break;
601 }
Damien Georgeea186de2021-09-22 00:35:46 +1000602 default:
603 goto unknown;
604 }
605
606 // We post-check interface requirements to save on code size
607 if (req_if >= 0) {
608 require_if(args[0], req_if);
609 }
610 }
611 }
612
613 esp_exceptions(esp_wifi_set_config(self->if_id, &cfg));
614
615 return mp_const_none;
616 }
617
618 // Get config
619
620 if (n_args != 2) {
621 mp_raise_TypeError(MP_ERROR_TEXT("can query only one param"));
622 }
623
624 int req_if = -1;
625 mp_obj_t val = mp_const_none;
626
Damien George5adb1fa2021-12-10 23:28:46 +1100627 switch (mp_obj_str_get_qstr(args[1])) {
628 case MP_QSTR_mac: {
Damien Georgeea186de2021-09-22 00:35:46 +1000629 uint8_t mac[6];
630 switch (self->if_id) {
Damien Georgee4650122023-05-09 09:52:54 +1000631 case ESP_IF_WIFI_AP: // fallthrough intentional
632 case ESP_IF_WIFI_STA:
Damien Georgeea186de2021-09-22 00:35:46 +1000633 esp_exceptions(esp_wifi_get_mac(self->if_id, mac));
634 return mp_obj_new_bytes(mac, sizeof(mac));
635 default:
636 goto unknown;
637 }
638 }
iabdalkadera7c7feb2022-06-04 12:22:55 +0200639 case MP_QSTR_ssid:
Damien George5adb1fa2021-12-10 23:28:46 +1100640 case MP_QSTR_essid:
Damien Georgeea186de2021-09-22 00:35:46 +1000641 switch (self->if_id) {
Damien Georgee4650122023-05-09 09:52:54 +1000642 case ESP_IF_WIFI_STA:
Damien Georgeea186de2021-09-22 00:35:46 +1000643 val = mp_obj_new_str((char *)cfg.sta.ssid, strlen((char *)cfg.sta.ssid));
644 break;
Damien Georgee4650122023-05-09 09:52:54 +1000645 case ESP_IF_WIFI_AP:
Damien Georgeea186de2021-09-22 00:35:46 +1000646 val = mp_obj_new_str((char *)cfg.ap.ssid, cfg.ap.ssid_len);
647 break;
648 default:
Damien Georgee4650122023-05-09 09:52:54 +1000649 req_if = ESP_IF_WIFI_AP;
Damien Georgeea186de2021-09-22 00:35:46 +1000650 }
651 break;
Damien George5adb1fa2021-12-10 23:28:46 +1100652 case MP_QSTR_hidden:
Damien Georgee4650122023-05-09 09:52:54 +1000653 req_if = ESP_IF_WIFI_AP;
Damien Georgeea186de2021-09-22 00:35:46 +1000654 val = mp_obj_new_bool(cfg.ap.ssid_hidden);
655 break;
iabdalkadera7c7feb2022-06-04 12:22:55 +0200656 case MP_QSTR_security:
Damien George5adb1fa2021-12-10 23:28:46 +1100657 case MP_QSTR_authmode:
Damien Georgee4650122023-05-09 09:52:54 +1000658 req_if = ESP_IF_WIFI_AP;
Damien Georgeea186de2021-09-22 00:35:46 +1000659 val = MP_OBJ_NEW_SMALL_INT(cfg.ap.authmode);
660 break;
glenn2098d1c502022-07-31 16:36:10 +1000661 case MP_QSTR_channel: {
662 uint8_t channel;
663 wifi_second_chan_t second;
664 esp_exceptions(esp_wifi_get_channel(&channel, &second));
665 val = MP_OBJ_NEW_SMALL_INT(channel);
Damien Georgeea186de2021-09-22 00:35:46 +1000666 break;
glenn2098d1c502022-07-31 16:36:10 +1000667 }
Daniël van de Giessenba8aad32023-07-04 15:36:37 +0200668 case MP_QSTR_ifname: {
669 val = esp_ifname(self->netif);
670 break;
671 }
IhorNehrutsa1ea82b62022-06-28 16:38:45 +0300672 case MP_QSTR_hostname:
Damien George5adb1fa2021-12-10 23:28:46 +1100673 case MP_QSTR_dhcp_hostname: {
Jim Mussaredeb51ca42023-02-01 14:20:45 +1100674 // TODO: Deprecated. Use network.hostname() instead.
Damien Georgee4650122023-05-09 09:52:54 +1000675 req_if = ESP_IF_WIFI_STA;
Jim Mussared65a3ce32023-10-03 13:32:48 +1100676 val = mod_network_hostname(0, NULL);
Damien Georgeea186de2021-09-22 00:35:46 +1000677 break;
678 }
Damien George5adb1fa2021-12-10 23:28:46 +1100679 case MP_QSTR_max_clients: {
Damien Georgeea186de2021-09-22 00:35:46 +1000680 val = MP_OBJ_NEW_SMALL_INT(cfg.ap.max_connection);
681 break;
682 }
Damien George5adb1fa2021-12-10 23:28:46 +1100683 case MP_QSTR_reconnects:
Damien Georgee4650122023-05-09 09:52:54 +1000684 req_if = ESP_IF_WIFI_STA;
Damien Georgeea186de2021-09-22 00:35:46 +1000685 int rec = conf_wifi_sta_reconnects - 1;
686 val = MP_OBJ_NEW_SMALL_INT(rec);
687 break;
wemosff28d2e2022-04-11 20:12:57 +0800688 case MP_QSTR_txpower: {
689 int8_t power;
690 esp_exceptions(esp_wifi_get_max_tx_power(&power));
691 val = mp_obj_new_float(power * 0.25);
692 break;
693 }
glenn2076f2e3e2022-07-31 18:17:40 +1000694 case MP_QSTR_protocol: {
695 uint8_t protocol_bitmap;
696 esp_exceptions(esp_wifi_get_protocol(self->if_id, &protocol_bitmap));
697 val = MP_OBJ_NEW_SMALL_INT(protocol_bitmap);
698 break;
699 }
glenn201093dea2022-08-25 16:55:57 +1000700 case MP_QSTR_pm: {
701 wifi_ps_type_t ps_type;
702 esp_exceptions(esp_wifi_get_ps(&ps_type));
703 val = MP_OBJ_NEW_SMALL_INT(ps_type);
704 break;
705 }
Damien Georgeea186de2021-09-22 00:35:46 +1000706 default:
707 goto unknown;
708 }
709
Damien Georgeea186de2021-09-22 00:35:46 +1000710 // We post-check interface requirements to save on code size
711 if (req_if >= 0) {
712 require_if(args[0], req_if);
713 }
714
715 return val;
716
717unknown:
718 mp_raise_ValueError(MP_ERROR_TEXT("unknown config param"));
719}
720MP_DEFINE_CONST_FUN_OBJ_KW(network_wlan_config_obj, 1, network_wlan_config);
721
Angus Grattondecf8e62024-02-27 15:32:29 +1100722static const mp_rom_map_elem_t wlan_if_locals_dict_table[] = {
Damien Georgeea186de2021-09-22 00:35:46 +1000723 { MP_ROM_QSTR(MP_QSTR_active), MP_ROM_PTR(&network_wlan_active_obj) },
724 { MP_ROM_QSTR(MP_QSTR_connect), MP_ROM_PTR(&network_wlan_connect_obj) },
725 { MP_ROM_QSTR(MP_QSTR_disconnect), MP_ROM_PTR(&network_wlan_disconnect_obj) },
726 { MP_ROM_QSTR(MP_QSTR_status), MP_ROM_PTR(&network_wlan_status_obj) },
727 { MP_ROM_QSTR(MP_QSTR_scan), MP_ROM_PTR(&network_wlan_scan_obj) },
728 { MP_ROM_QSTR(MP_QSTR_isconnected), MP_ROM_PTR(&network_wlan_isconnected_obj) },
729 { MP_ROM_QSTR(MP_QSTR_config), MP_ROM_PTR(&network_wlan_config_obj) },
Jim Mussaredeb51ca42023-02-01 14:20:45 +1100730 { MP_ROM_QSTR(MP_QSTR_ifconfig), MP_ROM_PTR(&esp_network_ifconfig_obj) },
glenn201093dea2022-08-25 16:55:57 +1000731
732 // Constants
733 { MP_ROM_QSTR(MP_QSTR_PM_NONE), MP_ROM_INT(WIFI_PS_NONE) },
734 { MP_ROM_QSTR(MP_QSTR_PM_PERFORMANCE), MP_ROM_INT(WIFI_PS_MIN_MODEM) },
735 { MP_ROM_QSTR(MP_QSTR_PM_POWERSAVE), MP_ROM_INT(WIFI_PS_MAX_MODEM) },
Damien Georgeea186de2021-09-22 00:35:46 +1000736};
Angus Grattondecf8e62024-02-27 15:32:29 +1100737static MP_DEFINE_CONST_DICT(wlan_if_locals_dict, wlan_if_locals_dict_table);
Damien Georgeea186de2021-09-22 00:35:46 +1000738
Jim Mussared662b9762021-07-14 14:38:38 +1000739MP_DEFINE_CONST_OBJ_TYPE(
Damien George53cb0732023-05-11 11:51:02 +1000740 esp_network_wlan_type,
Jim Mussared662b9762021-07-14 14:38:38 +1000741 MP_QSTR_WLAN,
742 MP_TYPE_FLAG_NONE,
Damien George53cb0732023-05-11 11:51:02 +1000743 make_new, network_wlan_make_new,
Jim Mussared9dce8272022-06-24 16:27:46 +1000744 locals_dict, &wlan_if_locals_dict
Jim Mussared662b9762021-07-14 14:38:38 +1000745 );
746
Damien Georgeea186de2021-09-22 00:35:46 +1000747#endif // MICROPY_PY_NETWORK_WLAN