esp32: Fix setting WLAN channel in AP mode.

- Previously the call to esp_wifi_set_channel() would be immediately
  overridden by calling esp_wifi_config(...) with the previous channel set.

- AP interface doesn't seem to need more than esp_wifi_config(...) to work.
  It will automatically configure 40MHz bandwidth and place the secondary
  channel using similar logic to what was being explicitly calculated here.

- However, calling esp_wifi_set_channel() on the STA interface is necessary
  if using this interface with ESP-NOW (without connecting to an AP). So
  the esp_wifi_set_channel() call is kept in for this purpose. Without
  this, tests/multi_espnow/70_channel.py fails.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
This commit is contained in:
Angus Gratton 2024-11-13 10:16:25 +11:00 committed by Damien George
parent 49b83ed44a
commit 03bc561edb

View File

@ -549,12 +549,23 @@ static mp_obj_t network_wlan_config(size_t n_args, const mp_obj_t *args, mp_map_
break;
}
case MP_QSTR_channel: {
uint8_t primary;
uint8_t channel = mp_obj_get_int(kwargs->table[i].value);
if (self->if_id == ESP_IF_WIFI_AP) {
cfg.ap.channel = channel;
} else {
// This setting is only used to determine the
// starting channel for a scan, so it can result in
// slightly faster connection times.
cfg.sta.channel = channel;
// This additional code to directly set the channel
// on the STA interface is only relevant for ESP-NOW
// (when there is no STA connection attempt.)
uint8_t old_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);
esp_exceptions(esp_wifi_get_channel(&old_primary, &secondary));
esp_err_t err = esp_wifi_set_channel(channel, secondary);
if (err == ESP_ERR_INVALID_ARG) {
// May need to swap secondary channel above to below or below to above
secondary = (
@ -563,7 +574,13 @@ static mp_obj_t network_wlan_config(size_t n_args, const mp_obj_t *args, mp_map_
: (secondary == WIFI_SECOND_CHAN_BELOW)
? WIFI_SECOND_CHAN_ABOVE
: WIFI_SECOND_CHAN_NONE);
esp_exceptions(esp_wifi_set_channel(primary, secondary));
err = esp_wifi_set_channel(channel, secondary);
}
esp_exceptions(err);
if (channel != old_primary) {
// Workaround the ESP-IDF Wi-Fi stack sometimes taking a moment to change channels
mp_hal_delay_ms(1);
}
}
break;
}