diff --git a/libraries/WiFi/src/WiFiGeneric.cpp b/libraries/WiFi/src/WiFiGeneric.cpp index 2fade00e450..c827b3c4868 100644 --- a/libraries/WiFi/src/WiFiGeneric.cpp +++ b/libraries/WiFi/src/WiFiGeneric.cpp @@ -1269,6 +1269,40 @@ int32_t WiFiGenericClass::channel(void) return primaryChan; } +/** + * Set the WiFi channel configuration + * @param primary primary channel. Depending on the region, not all channels may be available. + * @param secondary secondary channel (WIFI_SECOND_CHAN_NONE, WIFI_SECOND_CHAN_ABOVE, WIFI_SECOND_CHAN_BELOW) + * @return 0 on success, otherwise error + */ +int WiFiGenericClass::setChannel(uint8_t primary, wifi_second_chan_t secondary) +{ + wifi_country_t country; + esp_err_t ret; + + ret = esp_wifi_get_country(&country); + if (ret != ESP_OK) { + log_e("Failed to get country info"); + return ret; + } + + uint8_t min_chan = country.schan; + uint8_t max_chan = min_chan + country.nchan - 1; + + if(primary < min_chan || primary > max_chan){ + log_e("Invalid primary channel: %d. Valid range is %d-%d for country %s", primary, min_chan, max_chan, country.cc); + return ESP_ERR_INVALID_ARG; + } + + ret = esp_wifi_set_channel(primary, secondary); + if (ret != ESP_OK) { + log_e("Failed to set channel"); + return ret; + } + + return ESP_OK; +} + /** * store WiFi config in SDK flash area * @param persistent diff --git a/libraries/WiFi/src/WiFiGeneric.h b/libraries/WiFi/src/WiFiGeneric.h index 3de43905416..d48ee0a9de8 100644 --- a/libraries/WiFi/src/WiFiGeneric.h +++ b/libraries/WiFi/src/WiFiGeneric.h @@ -183,6 +183,7 @@ class WiFiGenericClass static int waitStatusBits(int bits, uint32_t timeout_ms); int32_t channel(void); + int setChannel(uint8_t primary, wifi_second_chan_t secondary=WIFI_SECOND_CHAN_NONE); void persistent(bool persistent); void enableLongRange(bool enable);