From 9c0d59f9c4831dd03673f3a6294d21e6b13adb9b Mon Sep 17 00:00:00 2001 From: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com> Date: Tue, 26 Mar 2024 07:21:00 -0300 Subject: [PATCH] Add method to set the WiFi radio channel (#9405) * Add method to set the WiFi radio channel * Fix Tab * Add check * Change name * Fix description * Add check * Add error return * Improve error message --- libraries/WiFi/src/WiFiGeneric.cpp | 34 ++++++++++++++++++++++++++++++ libraries/WiFi/src/WiFiGeneric.h | 1 + 2 files changed, 35 insertions(+) diff --git a/libraries/WiFi/src/WiFiGeneric.cpp b/libraries/WiFi/src/WiFiGeneric.cpp index 2fade00e4..c827b3c48 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 3de439054..d48ee0a9d 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);