From 98d1c50159fe9427d72ec358ba0219eaebb1d991 Mon Sep 17 00:00:00 2001 From: glenn20 Date: Sun, 31 Jul 2022 16:36:10 +1000 Subject: [PATCH] esp32/network_wlan: Use esp_wifi_set/get_channel to config wifi channel. Set the channel with esp_wifi_set_channel(), which adds support for setting the channel of the STA interface Get the channel with esp_wifi_get_channel() which returns the actual wifi channel of the radio, rather than the configured channel. --- ports/esp32/network_wlan.c | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/ports/esp32/network_wlan.c b/ports/esp32/network_wlan.c index 9b2200e4ff..501dc40f27 100644 --- a/ports/esp32/network_wlan.c +++ b/ports/esp32/network_wlan.c @@ -448,8 +448,22 @@ STATIC mp_obj_t network_wlan_config(size_t n_args, const mp_obj_t *args, mp_map_ break; } case MP_QSTR_channel: { - req_if = WIFI_IF_AP; - cfg.ap.channel = mp_obj_get_int(kwargs->table[i].value); + uint8_t primary; + wifi_second_chan_t secondary; + // Get the current value of secondary + esp_exceptions(esp_wifi_get_channel(&primary, &secondary)); + primary = mp_obj_get_int(kwargs->table[i].value); + esp_err_t err = esp_wifi_set_channel(primary, secondary); + if (err == ESP_ERR_INVALID_ARG) { + // May need to swap secondary channel above to below or below to above + secondary = ( + (secondary == WIFI_SECOND_CHAN_ABOVE) + ? WIFI_SECOND_CHAN_BELOW + : (secondary == WIFI_SECOND_CHAN_BELOW) + ? WIFI_SECOND_CHAN_ABOVE + : WIFI_SECOND_CHAN_NONE); + esp_exceptions(esp_wifi_set_channel(primary, secondary)); + } break; } case MP_QSTR_hostname: @@ -535,10 +549,13 @@ STATIC mp_obj_t network_wlan_config(size_t n_args, const mp_obj_t *args, mp_map_ req_if = WIFI_IF_AP; val = MP_OBJ_NEW_SMALL_INT(cfg.ap.authmode); break; - case MP_QSTR_channel: - req_if = WIFI_IF_AP; - val = MP_OBJ_NEW_SMALL_INT(cfg.ap.channel); + case MP_QSTR_channel: { + uint8_t channel; + wifi_second_chan_t second; + esp_exceptions(esp_wifi_get_channel(&channel, &second)); + val = MP_OBJ_NEW_SMALL_INT(channel); break; + } case MP_QSTR_hostname: case MP_QSTR_dhcp_hostname: { const char *s;