Skip to content

Commit 9c0d59f

Browse files
authored
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
1 parent 75f7b33 commit 9c0d59f

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

Diff for: libraries/WiFi/src/WiFiGeneric.cpp

+34
Original file line numberDiff line numberDiff line change
@@ -1269,6 +1269,40 @@ int32_t WiFiGenericClass::channel(void)
12691269
return primaryChan;
12701270
}
12711271

1272+
/**
1273+
* Set the WiFi channel configuration
1274+
* @param primary primary channel. Depending on the region, not all channels may be available.
1275+
* @param secondary secondary channel (WIFI_SECOND_CHAN_NONE, WIFI_SECOND_CHAN_ABOVE, WIFI_SECOND_CHAN_BELOW)
1276+
* @return 0 on success, otherwise error
1277+
*/
1278+
int WiFiGenericClass::setChannel(uint8_t primary, wifi_second_chan_t secondary)
1279+
{
1280+
wifi_country_t country;
1281+
esp_err_t ret;
1282+
1283+
ret = esp_wifi_get_country(&country);
1284+
if (ret != ESP_OK) {
1285+
log_e("Failed to get country info");
1286+
return ret;
1287+
}
1288+
1289+
uint8_t min_chan = country.schan;
1290+
uint8_t max_chan = min_chan + country.nchan - 1;
1291+
1292+
if(primary < min_chan || primary > max_chan){
1293+
log_e("Invalid primary channel: %d. Valid range is %d-%d for country %s", primary, min_chan, max_chan, country.cc);
1294+
return ESP_ERR_INVALID_ARG;
1295+
}
1296+
1297+
ret = esp_wifi_set_channel(primary, secondary);
1298+
if (ret != ESP_OK) {
1299+
log_e("Failed to set channel");
1300+
return ret;
1301+
}
1302+
1303+
return ESP_OK;
1304+
}
1305+
12721306
/**
12731307
* store WiFi config in SDK flash area
12741308
* @param persistent

Diff for: libraries/WiFi/src/WiFiGeneric.h

+1
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,7 @@ class WiFiGenericClass
183183
static int waitStatusBits(int bits, uint32_t timeout_ms);
184184

185185
int32_t channel(void);
186+
int setChannel(uint8_t primary, wifi_second_chan_t secondary=WIFI_SECOND_CHAN_NONE);
186187

187188
void persistent(bool persistent);
188189
void enableLongRange(bool enable);

0 commit comments

Comments
 (0)