blob: aefc4394c2ac3bbbb76ec70744196dee96cd0574 [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"
44#include "mdns.h"
45
46#if MICROPY_PY_NETWORK_WLAN
47
48#if (WIFI_MODE_STA & WIFI_MODE_AP != WIFI_MODE_NULL || WIFI_MODE_STA | WIFI_MODE_AP != WIFI_MODE_APSTA)
49#error WIFI_MODE_STA and WIFI_MODE_AP are supposed to be bitfields!
50#endif
51
Jim Mussared662b9762021-07-14 14:38:38 +100052STATIC const wlan_if_obj_t wlan_sta_obj;
53STATIC const wlan_if_obj_t wlan_ap_obj;
Damien Georgeea186de2021-09-22 00:35:46 +100054
55// Set to "true" if esp_wifi_start() was called
56static bool wifi_started = false;
57
58// Set to "true" if the STA interface is requested to be connected by the
59// user, used for automatic reassociation.
60static bool wifi_sta_connect_requested = false;
61
62// Set to "true" if the STA interface is connected to wifi and has IP address.
63static bool wifi_sta_connected = false;
64
65// Store the current status. 0 means None here, safe to do so as first enum value is WIFI_REASON_UNSPECIFIED=1.
66static uint8_t wifi_sta_disconn_reason = 0;
67
68#if MICROPY_HW_ENABLE_MDNS_QUERIES || MICROPY_HW_ENABLE_MDNS_RESPONDER
69// Whether mDNS has been initialised or not
70static bool mdns_initialised = false;
71#endif
72
73static uint8_t conf_wifi_sta_reconnects = 0;
74static uint8_t wifi_sta_reconnects;
75
76// This function is called by the system-event task and so runs in a different
77// thread to the main MicroPython task. It must not raise any Python exceptions.
78void network_wlan_event_handler(system_event_t *event) {
79 switch (event->event_id) {
80 case SYSTEM_EVENT_STA_START:
81 ESP_LOGI("wifi", "STA_START");
82 wifi_sta_reconnects = 0;
83 break;
84 case SYSTEM_EVENT_STA_CONNECTED:
85 ESP_LOGI("network", "CONNECTED");
86 break;
87 case SYSTEM_EVENT_STA_GOT_IP:
88 ESP_LOGI("network", "GOT_IP");
89 wifi_sta_connected = true;
90 wifi_sta_disconn_reason = 0; // Success so clear error. (in case of new error will be replaced anyway)
91 #if MICROPY_HW_ENABLE_MDNS_QUERIES || MICROPY_HW_ENABLE_MDNS_RESPONDER
92 if (!mdns_initialised) {
93 mdns_init();
94 #if MICROPY_HW_ENABLE_MDNS_RESPONDER
Jim Mussaredeb51ca42023-02-01 14:20:45 +110095 mdns_hostname_set(mod_network_hostname);
96 mdns_instance_name_set(mod_network_hostname);
Damien Georgeea186de2021-09-22 00:35:46 +100097 #endif
98 mdns_initialised = true;
99 }
100 #endif
101 break;
102 case SYSTEM_EVENT_STA_DISCONNECTED: {
103 // This is a workaround as ESP32 WiFi libs don't currently
104 // auto-reassociate.
105 system_event_sta_disconnected_t *disconn = &event->event_info.disconnected;
106 char *message = "";
107 wifi_sta_disconn_reason = disconn->reason;
108 switch (disconn->reason) {
109 case WIFI_REASON_BEACON_TIMEOUT:
110 // AP has dropped out; try to reconnect.
111 message = "\nbeacon timeout";
112 break;
113 case WIFI_REASON_NO_AP_FOUND:
114 // AP may not exist, or it may have momentarily dropped out; try to reconnect.
115 message = "\nno AP found";
116 break;
117 case WIFI_REASON_AUTH_FAIL:
118 // Password may be wrong, or it just failed to connect; try to reconnect.
119 message = "\nauthentication failed";
120 break;
121 default:
122 // Let other errors through and try to reconnect.
123 break;
124 }
125 ESP_LOGI("wifi", "STA_DISCONNECTED, reason:%d%s", disconn->reason, message);
126
127 wifi_sta_connected = false;
128 if (wifi_sta_connect_requested) {
129 wifi_mode_t mode;
130 if (esp_wifi_get_mode(&mode) != ESP_OK) {
131 break;
132 }
133 if (!(mode & WIFI_MODE_STA)) {
134 break;
135 }
136 if (conf_wifi_sta_reconnects) {
137 ESP_LOGI("wifi", "reconnect counter=%d, max=%d",
138 wifi_sta_reconnects, conf_wifi_sta_reconnects);
139 if (++wifi_sta_reconnects >= conf_wifi_sta_reconnects) {
140 break;
141 }
142 }
143 esp_err_t e = esp_wifi_connect();
144 if (e != ESP_OK) {
145 ESP_LOGI("wifi", "error attempting to reconnect: 0x%04x", e);
146 }
147 }
148 break;
149 }
150 default:
151 break;
152 }
153}
154
155STATIC void require_if(mp_obj_t wlan_if, int if_no) {
156 wlan_if_obj_t *self = MP_OBJ_TO_PTR(wlan_if);
157 if (self->if_id != if_no) {
158 mp_raise_msg(&mp_type_OSError, if_no == WIFI_IF_STA ? MP_ERROR_TEXT("STA required") : MP_ERROR_TEXT("AP required"));
159 }
160}
161
162STATIC mp_obj_t get_wlan(size_t n_args, const mp_obj_t *args) {
163 static int initialized = 0;
164 if (!initialized) {
165 wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
166 ESP_LOGD("modnetwork", "Initializing WiFi");
167 esp_exceptions(esp_wifi_init(&cfg));
168 esp_exceptions(esp_wifi_set_storage(WIFI_STORAGE_RAM));
169 ESP_LOGD("modnetwork", "Initialized");
170 initialized = 1;
171 }
172
173 int idx = (n_args > 0) ? mp_obj_get_int(args[0]) : WIFI_IF_STA;
174 if (idx == WIFI_IF_STA) {
175 return MP_OBJ_FROM_PTR(&wlan_sta_obj);
176 } else if (idx == WIFI_IF_AP) {
177 return MP_OBJ_FROM_PTR(&wlan_ap_obj);
178 } else {
179 mp_raise_ValueError(MP_ERROR_TEXT("invalid WLAN interface identifier"));
180 }
181}
Jim Mussaredeb51ca42023-02-01 14:20:45 +1100182MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(esp_network_get_wlan_obj, 0, 1, get_wlan);
Damien Georgeea186de2021-09-22 00:35:46 +1000183
184STATIC mp_obj_t network_wlan_active(size_t n_args, const mp_obj_t *args) {
185 wlan_if_obj_t *self = MP_OBJ_TO_PTR(args[0]);
186
187 wifi_mode_t mode;
188 if (!wifi_started) {
189 mode = WIFI_MODE_NULL;
190 } else {
191 esp_exceptions(esp_wifi_get_mode(&mode));
192 }
193
194 int bit = (self->if_id == WIFI_IF_STA) ? WIFI_MODE_STA : WIFI_MODE_AP;
195
196 if (n_args > 1) {
197 bool active = mp_obj_is_true(args[1]);
198 mode = active ? (mode | bit) : (mode & ~bit);
199 if (mode == WIFI_MODE_NULL) {
200 if (wifi_started) {
201 esp_exceptions(esp_wifi_stop());
202 wifi_started = false;
203 }
204 } else {
205 esp_exceptions(esp_wifi_set_mode(mode));
206 if (!wifi_started) {
207 esp_exceptions(esp_wifi_start());
208 wifi_started = true;
209 }
210 }
robert-hhd6bc34a2023-01-19 12:42:09 +0100211 // This delay is a band-aid patch for issues #8289, #8792 and #9236,
212 // allowing the esp data structures to settle. It looks like some
213 // kind of race condition, which is not yet found. But at least
214 // this small delay seems not hurt much, since wlan.active() is
215 // usually not called in a time critical part of the code.
216 mp_hal_delay_ms(1);
Damien Georgeea186de2021-09-22 00:35:46 +1000217 }
218
219 return (mode & bit) ? mp_const_true : mp_const_false;
220}
221STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(network_wlan_active_obj, 1, 2, network_wlan_active);
222
223STATIC 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 +0200224 enum { ARG_ssid, ARG_key, ARG_bssid };
Damien Georgeea186de2021-09-22 00:35:46 +1000225 static const mp_arg_t allowed_args[] = {
226 { MP_QSTR_, MP_ARG_OBJ, {.u_obj = mp_const_none} },
227 { MP_QSTR_, MP_ARG_OBJ, {.u_obj = mp_const_none} },
228 { MP_QSTR_bssid, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
229 };
230
231 // parse args
232 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
233 mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
234
235 wifi_config_t wifi_sta_config = {0};
236
237 // configure any parameters that are given
238 if (n_args > 1) {
239 size_t len;
240 const char *p;
241 if (args[ARG_ssid].u_obj != mp_const_none) {
242 p = mp_obj_str_get_data(args[ARG_ssid].u_obj, &len);
243 memcpy(wifi_sta_config.sta.ssid, p, MIN(len, sizeof(wifi_sta_config.sta.ssid)));
244 }
iabdalkadera7c7feb2022-06-04 12:22:55 +0200245 if (args[ARG_key].u_obj != mp_const_none) {
246 p = mp_obj_str_get_data(args[ARG_key].u_obj, &len);
Damien Georgeea186de2021-09-22 00:35:46 +1000247 memcpy(wifi_sta_config.sta.password, p, MIN(len, sizeof(wifi_sta_config.sta.password)));
248 }
249 if (args[ARG_bssid].u_obj != mp_const_none) {
250 p = mp_obj_str_get_data(args[ARG_bssid].u_obj, &len);
251 if (len != sizeof(wifi_sta_config.sta.bssid)) {
252 mp_raise_ValueError(NULL);
253 }
254 wifi_sta_config.sta.bssid_set = 1;
255 memcpy(wifi_sta_config.sta.bssid, p, sizeof(wifi_sta_config.sta.bssid));
256 }
257 esp_exceptions(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_sta_config));
258 }
259
Jim Mussaredeb51ca42023-02-01 14:20:45 +1100260 esp_exceptions(tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_STA, mod_network_hostname));
261
Damien Georgeea186de2021-09-22 00:35:46 +1000262 wifi_sta_reconnects = 0;
263 // connect to the WiFi AP
264 MP_THREAD_GIL_EXIT();
265 esp_exceptions(esp_wifi_connect());
266 MP_THREAD_GIL_ENTER();
267 wifi_sta_connect_requested = true;
268
269 return mp_const_none;
270}
271STATIC MP_DEFINE_CONST_FUN_OBJ_KW(network_wlan_connect_obj, 1, network_wlan_connect);
272
273STATIC mp_obj_t network_wlan_disconnect(mp_obj_t self_in) {
274 wifi_sta_connect_requested = false;
275 esp_exceptions(esp_wifi_disconnect());
276 return mp_const_none;
277}
278STATIC MP_DEFINE_CONST_FUN_OBJ_1(network_wlan_disconnect_obj, network_wlan_disconnect);
279
280STATIC mp_obj_t network_wlan_status(size_t n_args, const mp_obj_t *args) {
281 wlan_if_obj_t *self = MP_OBJ_TO_PTR(args[0]);
282 if (n_args == 1) {
283 if (self->if_id == WIFI_IF_STA) {
284 // Case of no arg is only for the STA interface
285 if (wifi_sta_connected) {
286 // Happy path, connected with IP
287 return MP_OBJ_NEW_SMALL_INT(STAT_GOT_IP);
288 } else if (wifi_sta_connect_requested
289 && (conf_wifi_sta_reconnects == 0
290 || wifi_sta_reconnects < conf_wifi_sta_reconnects)) {
291 // No connection or error, but is requested = Still connecting
292 return MP_OBJ_NEW_SMALL_INT(STAT_CONNECTING);
293 } else if (wifi_sta_disconn_reason == 0) {
294 // No activity, No error = Idle
295 return MP_OBJ_NEW_SMALL_INT(STAT_IDLE);
296 } else {
297 // Simply pass the error through from ESP-identifier
298 return MP_OBJ_NEW_SMALL_INT(wifi_sta_disconn_reason);
299 }
300 }
301 return mp_const_none;
302 }
303
304 // one argument: return status based on query parameter
305 switch ((uintptr_t)args[1]) {
306 case (uintptr_t)MP_OBJ_NEW_QSTR(MP_QSTR_stations): {
307 // return list of connected stations, only if in soft-AP mode
308 require_if(args[0], WIFI_IF_AP);
309 wifi_sta_list_t station_list;
310 esp_exceptions(esp_wifi_ap_get_sta_list(&station_list));
311 wifi_sta_info_t *stations = (wifi_sta_info_t *)station_list.sta;
312 mp_obj_t list = mp_obj_new_list(0, NULL);
313 for (int i = 0; i < station_list.num; ++i) {
314 mp_obj_tuple_t *t = mp_obj_new_tuple(1, NULL);
315 t->items[0] = mp_obj_new_bytes(stations[i].mac, sizeof(stations[i].mac));
316 mp_obj_list_append(list, t);
317 }
318 return list;
319 }
320 case (uintptr_t)MP_OBJ_NEW_QSTR(MP_QSTR_rssi): {
321 // return signal of AP, only in STA mode
322 require_if(args[0], WIFI_IF_STA);
323
324 wifi_ap_record_t info;
325 esp_exceptions(esp_wifi_sta_get_ap_info(&info));
326 return MP_OBJ_NEW_SMALL_INT(info.rssi);
327 }
328 default:
329 mp_raise_ValueError(MP_ERROR_TEXT("unknown status param"));
330 }
331
332 return mp_const_none;
333}
334STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(network_wlan_status_obj, 1, 2, network_wlan_status);
335
336STATIC mp_obj_t network_wlan_scan(mp_obj_t self_in) {
337 // check that STA mode is active
338 wifi_mode_t mode;
339 esp_exceptions(esp_wifi_get_mode(&mode));
340 if ((mode & WIFI_MODE_STA) == 0) {
341 mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("STA must be active"));
342 }
343
344 mp_obj_t list = mp_obj_new_list(0, NULL);
345 wifi_scan_config_t config = { 0 };
346 config.show_hidden = true;
347 MP_THREAD_GIL_EXIT();
348 esp_err_t status = esp_wifi_scan_start(&config, 1);
349 MP_THREAD_GIL_ENTER();
350 if (status == 0) {
351 uint16_t count = 0;
352 esp_exceptions(esp_wifi_scan_get_ap_num(&count));
Damien Georgeccaf1972022-06-28 13:15:10 +1000353 if (count == 0) {
354 // esp_wifi_scan_get_ap_records must be called to free internal buffers from the scan.
355 // But it returns an error if wifi_ap_records==NULL. So allocate at least 1 AP entry.
356 // esp_wifi_scan_get_ap_records will then return the actual number of APs in count.
357 count = 1;
358 }
Damien Georgeea186de2021-09-22 00:35:46 +1000359 wifi_ap_record_t *wifi_ap_records = calloc(count, sizeof(wifi_ap_record_t));
360 esp_exceptions(esp_wifi_scan_get_ap_records(&count, wifi_ap_records));
361 for (uint16_t i = 0; i < count; i++) {
362 mp_obj_tuple_t *t = mp_obj_new_tuple(6, NULL);
363 uint8_t *x = memchr(wifi_ap_records[i].ssid, 0, sizeof(wifi_ap_records[i].ssid));
364 int ssid_len = x ? x - wifi_ap_records[i].ssid : sizeof(wifi_ap_records[i].ssid);
365 t->items[0] = mp_obj_new_bytes(wifi_ap_records[i].ssid, ssid_len);
366 t->items[1] = mp_obj_new_bytes(wifi_ap_records[i].bssid, sizeof(wifi_ap_records[i].bssid));
367 t->items[2] = MP_OBJ_NEW_SMALL_INT(wifi_ap_records[i].primary);
368 t->items[3] = MP_OBJ_NEW_SMALL_INT(wifi_ap_records[i].rssi);
369 t->items[4] = MP_OBJ_NEW_SMALL_INT(wifi_ap_records[i].authmode);
370 t->items[5] = mp_const_false; // XXX hidden?
371 mp_obj_list_append(list, MP_OBJ_FROM_PTR(t));
372 }
373 free(wifi_ap_records);
374 }
375 return list;
376}
377STATIC MP_DEFINE_CONST_FUN_OBJ_1(network_wlan_scan_obj, network_wlan_scan);
378
379STATIC mp_obj_t network_wlan_isconnected(mp_obj_t self_in) {
380 wlan_if_obj_t *self = MP_OBJ_TO_PTR(self_in);
381 if (self->if_id == WIFI_IF_STA) {
382 return mp_obj_new_bool(wifi_sta_connected);
383 } else {
384 wifi_sta_list_t sta;
385 esp_wifi_ap_get_sta_list(&sta);
386 return mp_obj_new_bool(sta.num != 0);
387 }
388}
389STATIC MP_DEFINE_CONST_FUN_OBJ_1(network_wlan_isconnected_obj, network_wlan_isconnected);
390
391STATIC mp_obj_t network_wlan_config(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
392 if (n_args != 1 && kwargs->used != 0) {
393 mp_raise_TypeError(MP_ERROR_TEXT("either pos or kw args are allowed"));
394 }
395
396 wlan_if_obj_t *self = MP_OBJ_TO_PTR(args[0]);
397
398 bool is_wifi = self->if_id == WIFI_IF_AP || self->if_id == WIFI_IF_STA;
399
400 wifi_config_t cfg;
401 if (is_wifi) {
402 esp_exceptions(esp_wifi_get_config(self->if_id, &cfg));
403 }
404
Damien Georgeea186de2021-09-22 00:35:46 +1000405 if (kwargs->used != 0) {
406 if (!is_wifi) {
407 goto unknown;
408 }
409
410 for (size_t i = 0; i < kwargs->alloc; i++) {
411 if (mp_map_slot_is_filled(kwargs, i)) {
412 int req_if = -1;
413
Damien George5adb1fa2021-12-10 23:28:46 +1100414 switch (mp_obj_str_get_qstr(kwargs->table[i].key)) {
415 case MP_QSTR_mac: {
Damien Georgeea186de2021-09-22 00:35:46 +1000416 mp_buffer_info_t bufinfo;
417 mp_get_buffer_raise(kwargs->table[i].value, &bufinfo, MP_BUFFER_READ);
418 if (bufinfo.len != 6) {
419 mp_raise_ValueError(MP_ERROR_TEXT("invalid buffer length"));
420 }
421 esp_exceptions(esp_wifi_set_mac(self->if_id, bufinfo.buf));
422 break;
423 }
iabdalkadera7c7feb2022-06-04 12:22:55 +0200424 case MP_QSTR_ssid:
Damien George5adb1fa2021-12-10 23:28:46 +1100425 case MP_QSTR_essid: {
Damien Georgeea186de2021-09-22 00:35:46 +1000426 req_if = WIFI_IF_AP;
427 size_t len;
428 const char *s = mp_obj_str_get_data(kwargs->table[i].value, &len);
429 len = MIN(len, sizeof(cfg.ap.ssid));
430 memcpy(cfg.ap.ssid, s, len);
431 cfg.ap.ssid_len = len;
432 break;
433 }
Damien George5adb1fa2021-12-10 23:28:46 +1100434 case MP_QSTR_hidden: {
Damien Georgeea186de2021-09-22 00:35:46 +1000435 req_if = WIFI_IF_AP;
436 cfg.ap.ssid_hidden = mp_obj_is_true(kwargs->table[i].value);
437 break;
438 }
iabdalkadera7c7feb2022-06-04 12:22:55 +0200439 case MP_QSTR_security:
Damien George5adb1fa2021-12-10 23:28:46 +1100440 case MP_QSTR_authmode: {
Damien Georgeea186de2021-09-22 00:35:46 +1000441 req_if = WIFI_IF_AP;
442 cfg.ap.authmode = mp_obj_get_int(kwargs->table[i].value);
443 break;
444 }
iabdalkadera7c7feb2022-06-04 12:22:55 +0200445 case MP_QSTR_key:
Damien George5adb1fa2021-12-10 23:28:46 +1100446 case MP_QSTR_password: {
Damien Georgeea186de2021-09-22 00:35:46 +1000447 req_if = WIFI_IF_AP;
448 size_t len;
449 const char *s = mp_obj_str_get_data(kwargs->table[i].value, &len);
450 len = MIN(len, sizeof(cfg.ap.password) - 1);
451 memcpy(cfg.ap.password, s, len);
452 cfg.ap.password[len] = 0;
453 break;
454 }
Damien George5adb1fa2021-12-10 23:28:46 +1100455 case MP_QSTR_channel: {
glenn2098d1c502022-07-31 16:36:10 +1000456 uint8_t primary;
457 wifi_second_chan_t secondary;
458 // Get the current value of secondary
459 esp_exceptions(esp_wifi_get_channel(&primary, &secondary));
460 primary = mp_obj_get_int(kwargs->table[i].value);
461 esp_err_t err = esp_wifi_set_channel(primary, secondary);
462 if (err == ESP_ERR_INVALID_ARG) {
463 // May need to swap secondary channel above to below or below to above
464 secondary = (
465 (secondary == WIFI_SECOND_CHAN_ABOVE)
466 ? WIFI_SECOND_CHAN_BELOW
467 : (secondary == WIFI_SECOND_CHAN_BELOW)
468 ? WIFI_SECOND_CHAN_ABOVE
469 : WIFI_SECOND_CHAN_NONE);
470 esp_exceptions(esp_wifi_set_channel(primary, secondary));
471 }
Damien Georgeea186de2021-09-22 00:35:46 +1000472 break;
473 }
IhorNehrutsa1ea82b62022-06-28 16:38:45 +0300474 case MP_QSTR_hostname:
Damien George5adb1fa2021-12-10 23:28:46 +1100475 case MP_QSTR_dhcp_hostname: {
Jim Mussaredeb51ca42023-02-01 14:20:45 +1100476 // TODO: Deprecated. Use network.hostname(name) instead.
477 size_t len;
478 const char *str = mp_obj_str_get_data(kwargs->table[i].value, &len);
479 if (len >= MICROPY_PY_NETWORK_HOSTNAME_MAX_LEN) {
480 mp_raise_ValueError(NULL);
481 }
482 strcpy(mod_network_hostname, str);
Damien Georgeea186de2021-09-22 00:35:46 +1000483 break;
484 }
Damien George5adb1fa2021-12-10 23:28:46 +1100485 case MP_QSTR_max_clients: {
Damien Georgeea186de2021-09-22 00:35:46 +1000486 req_if = WIFI_IF_AP;
487 cfg.ap.max_connection = mp_obj_get_int(kwargs->table[i].value);
488 break;
489 }
Damien George5adb1fa2021-12-10 23:28:46 +1100490 case MP_QSTR_reconnects: {
Damien Georgeea186de2021-09-22 00:35:46 +1000491 int reconnects = mp_obj_get_int(kwargs->table[i].value);
492 req_if = WIFI_IF_STA;
493 // parameter reconnects == -1 means to retry forever.
494 // here means conf_wifi_sta_reconnects == 0 to retry forever.
495 conf_wifi_sta_reconnects = (reconnects == -1) ? 0 : reconnects + 1;
496 break;
497 }
wemosff28d2e2022-04-11 20:12:57 +0800498 case MP_QSTR_txpower: {
499 int8_t power = (mp_obj_get_float(kwargs->table[i].value) * 4);
500 esp_exceptions(esp_wifi_set_max_tx_power(power));
501 break;
502 }
glenn2076f2e3e2022-07-31 18:17:40 +1000503 case MP_QSTR_protocol: {
504 esp_exceptions(esp_wifi_set_protocol(self->if_id, mp_obj_get_int(kwargs->table[i].value)));
505 break;
506 }
Damien Georgeea186de2021-09-22 00:35:46 +1000507 default:
508 goto unknown;
509 }
510
511 // We post-check interface requirements to save on code size
512 if (req_if >= 0) {
513 require_if(args[0], req_if);
514 }
515 }
516 }
517
518 esp_exceptions(esp_wifi_set_config(self->if_id, &cfg));
519
520 return mp_const_none;
521 }
522
523 // Get config
524
525 if (n_args != 2) {
526 mp_raise_TypeError(MP_ERROR_TEXT("can query only one param"));
527 }
528
529 int req_if = -1;
530 mp_obj_t val = mp_const_none;
531
Damien George5adb1fa2021-12-10 23:28:46 +1100532 switch (mp_obj_str_get_qstr(args[1])) {
533 case MP_QSTR_mac: {
Damien Georgeea186de2021-09-22 00:35:46 +1000534 uint8_t mac[6];
535 switch (self->if_id) {
536 case WIFI_IF_AP: // fallthrough intentional
537 case WIFI_IF_STA:
538 esp_exceptions(esp_wifi_get_mac(self->if_id, mac));
539 return mp_obj_new_bytes(mac, sizeof(mac));
540 default:
541 goto unknown;
542 }
543 }
iabdalkadera7c7feb2022-06-04 12:22:55 +0200544 case MP_QSTR_ssid:
Damien George5adb1fa2021-12-10 23:28:46 +1100545 case MP_QSTR_essid:
Damien Georgeea186de2021-09-22 00:35:46 +1000546 switch (self->if_id) {
547 case WIFI_IF_STA:
548 val = mp_obj_new_str((char *)cfg.sta.ssid, strlen((char *)cfg.sta.ssid));
549 break;
550 case WIFI_IF_AP:
551 val = mp_obj_new_str((char *)cfg.ap.ssid, cfg.ap.ssid_len);
552 break;
553 default:
554 req_if = WIFI_IF_AP;
555 }
556 break;
Damien George5adb1fa2021-12-10 23:28:46 +1100557 case MP_QSTR_hidden:
Damien Georgeea186de2021-09-22 00:35:46 +1000558 req_if = WIFI_IF_AP;
559 val = mp_obj_new_bool(cfg.ap.ssid_hidden);
560 break;
iabdalkadera7c7feb2022-06-04 12:22:55 +0200561 case MP_QSTR_security:
Damien George5adb1fa2021-12-10 23:28:46 +1100562 case MP_QSTR_authmode:
Damien Georgeea186de2021-09-22 00:35:46 +1000563 req_if = WIFI_IF_AP;
564 val = MP_OBJ_NEW_SMALL_INT(cfg.ap.authmode);
565 break;
glenn2098d1c502022-07-31 16:36:10 +1000566 case MP_QSTR_channel: {
567 uint8_t channel;
568 wifi_second_chan_t second;
569 esp_exceptions(esp_wifi_get_channel(&channel, &second));
570 val = MP_OBJ_NEW_SMALL_INT(channel);
Damien Georgeea186de2021-09-22 00:35:46 +1000571 break;
glenn2098d1c502022-07-31 16:36:10 +1000572 }
IhorNehrutsa1ea82b62022-06-28 16:38:45 +0300573 case MP_QSTR_hostname:
Damien George5adb1fa2021-12-10 23:28:46 +1100574 case MP_QSTR_dhcp_hostname: {
Jim Mussaredeb51ca42023-02-01 14:20:45 +1100575 // TODO: Deprecated. Use network.hostname() instead.
576 req_if = WIFI_IF_STA;
577 val = mp_obj_new_str(mod_network_hostname, strlen(mod_network_hostname));
Damien Georgeea186de2021-09-22 00:35:46 +1000578 break;
579 }
Damien George5adb1fa2021-12-10 23:28:46 +1100580 case MP_QSTR_max_clients: {
Damien Georgeea186de2021-09-22 00:35:46 +1000581 val = MP_OBJ_NEW_SMALL_INT(cfg.ap.max_connection);
582 break;
583 }
Damien George5adb1fa2021-12-10 23:28:46 +1100584 case MP_QSTR_reconnects:
Damien Georgeea186de2021-09-22 00:35:46 +1000585 req_if = WIFI_IF_STA;
586 int rec = conf_wifi_sta_reconnects - 1;
587 val = MP_OBJ_NEW_SMALL_INT(rec);
588 break;
wemosff28d2e2022-04-11 20:12:57 +0800589 case MP_QSTR_txpower: {
590 int8_t power;
591 esp_exceptions(esp_wifi_get_max_tx_power(&power));
592 val = mp_obj_new_float(power * 0.25);
593 break;
594 }
glenn2076f2e3e2022-07-31 18:17:40 +1000595 case MP_QSTR_protocol: {
596 uint8_t protocol_bitmap;
597 esp_exceptions(esp_wifi_get_protocol(self->if_id, &protocol_bitmap));
598 val = MP_OBJ_NEW_SMALL_INT(protocol_bitmap);
599 break;
600 }
Damien Georgeea186de2021-09-22 00:35:46 +1000601 default:
602 goto unknown;
603 }
604
Damien Georgeea186de2021-09-22 00:35:46 +1000605 // We post-check interface requirements to save on code size
606 if (req_if >= 0) {
607 require_if(args[0], req_if);
608 }
609
610 return val;
611
612unknown:
613 mp_raise_ValueError(MP_ERROR_TEXT("unknown config param"));
614}
615MP_DEFINE_CONST_FUN_OBJ_KW(network_wlan_config_obj, 1, network_wlan_config);
616
617STATIC const mp_rom_map_elem_t wlan_if_locals_dict_table[] = {
618 { MP_ROM_QSTR(MP_QSTR_active), MP_ROM_PTR(&network_wlan_active_obj) },
619 { MP_ROM_QSTR(MP_QSTR_connect), MP_ROM_PTR(&network_wlan_connect_obj) },
620 { MP_ROM_QSTR(MP_QSTR_disconnect), MP_ROM_PTR(&network_wlan_disconnect_obj) },
621 { MP_ROM_QSTR(MP_QSTR_status), MP_ROM_PTR(&network_wlan_status_obj) },
622 { MP_ROM_QSTR(MP_QSTR_scan), MP_ROM_PTR(&network_wlan_scan_obj) },
623 { MP_ROM_QSTR(MP_QSTR_isconnected), MP_ROM_PTR(&network_wlan_isconnected_obj) },
624 { MP_ROM_QSTR(MP_QSTR_config), MP_ROM_PTR(&network_wlan_config_obj) },
Jim Mussaredeb51ca42023-02-01 14:20:45 +1100625 { MP_ROM_QSTR(MP_QSTR_ifconfig), MP_ROM_PTR(&esp_network_ifconfig_obj) },
Damien Georgeea186de2021-09-22 00:35:46 +1000626};
627STATIC MP_DEFINE_CONST_DICT(wlan_if_locals_dict, wlan_if_locals_dict_table);
628
Jim Mussared662b9762021-07-14 14:38:38 +1000629MP_DEFINE_CONST_OBJ_TYPE(
630 wlan_if_type,
631 MP_QSTR_WLAN,
632 MP_TYPE_FLAG_NONE,
Jim Mussared9dce8272022-06-24 16:27:46 +1000633 locals_dict, &wlan_if_locals_dict
Jim Mussared662b9762021-07-14 14:38:38 +1000634 );
635
636STATIC const wlan_if_obj_t wlan_sta_obj = {{&wlan_if_type}, WIFI_IF_STA};
637STATIC const wlan_if_obj_t wlan_ap_obj = {{&wlan_if_type}, WIFI_IF_AP};
Damien Georgeea186de2021-09-22 00:35:46 +1000638
639#endif // MICROPY_PY_NETWORK_WLAN