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