Skip to content

feat(esp-wifi): add Country Code #3837

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jul 21, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions esp-wifi/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- Country Code is returned from the Wi-Fi scan results


### Changed

Expand Down
35 changes: 34 additions & 1 deletion esp-wifi/src/wifi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ pub mod event;
mod internal;
pub(crate) mod os_adapter;
pub(crate) mod state;
use alloc::{collections::vec_deque::VecDeque, string::String};
use alloc::{
collections::vec_deque::VecDeque,
string::{String, ToString},
};
use core::{
fmt::Debug,
marker::PhantomData,
Expand Down Expand Up @@ -241,6 +244,11 @@ pub struct AccessPointInfo {

/// The authentication method used by the access point.
pub auth_method: Option<AuthMethod>,

/// The country code of the access point (if available from beacon frames).
/// This is a 2-character ISO country code (e.g., "US", "DE", "JP").
#[cfg_attr(feature = "defmt", defmt(Debug2Format))]
pub country_code: Option<String>,
}

/// Configuration for a Wi-Fi access point.
Expand Down Expand Up @@ -1839,6 +1847,30 @@ fn convert_ap_info(record: &include::wifi_ap_record_t) -> AccessPointInfo {
let mut ssid = String::new();
ssid.push_str(ssid_ref);

// Extract country code from ESP-IDF structure
let country_code = {
let cc_bytes =
unsafe { core::slice::from_raw_parts(record.country.cc.as_ptr() as *const u8, 3) };
Copy link
Preview

Copilot AI Jul 19, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The magic number 3 for the country code array size should be defined as a constant to improve code maintainability and reduce the risk of inconsistencies if the underlying structure changes.

Suggested change
unsafe { core::slice::from_raw_parts(record.country.cc.as_ptr() as *const u8, 3) };
unsafe { core::slice::from_raw_parts(record.country.cc.as_ptr() as *const u8, COUNTRY_CODE_SIZE) };

Copilot uses AI. Check for mistakes.


// Find the null terminator or end of array
let cc_len = cc_bytes
.iter()
.position(|&b| b == 0)
.unwrap_or(cc_bytes.len());

if cc_len >= 2 {
// Validate that we have at least 2 valid ASCII characters
let cc_slice = &cc_bytes[..cc_len.min(2)];
Copy link
Preview

Copilot AI Jul 19, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The magic number 2 is used multiple times for country code length validation. Consider defining a constant like const COUNTRY_CODE_LENGTH: usize = 2; to improve maintainability and make the intent clearer.

Suggested change
if cc_len >= 2 {
// Validate that we have at least 2 valid ASCII characters
let cc_slice = &cc_bytes[..cc_len.min(2)];
if cc_len >= COUNTRY_CODE_LENGTH {
// Validate that we have at least COUNTRY_CODE_LENGTH valid ASCII characters
let cc_slice = &cc_bytes[..cc_len.min(COUNTRY_CODE_LENGTH)];

Copilot uses AI. Check for mistakes.

if cc_slice.iter().all(|&b| b.is_ascii_uppercase()) {
core::str::from_utf8(cc_slice).ok().map(|s| s.to_string())
} else {
None
}
} else {
None
}
};

AccessPointInfo {
ssid,
bssid: record.bssid,
Expand All @@ -1851,6 +1883,7 @@ fn convert_ap_info(record: &include::wifi_ap_record_t) -> AccessPointInfo {
},
signal_strength: record.rssi,
auth_method: Some(AuthMethod::from_raw(record.authmode)),
country_code,
}
}

Expand Down
79 changes: 79 additions & 0 deletions examples/src/bin/wifi_scan_with_country_codes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
//! WiFi scanning example with country code display
//!
//! This example demonstrates how to scan for WiFi access points and display
//! their country codes, which are now available directly from ESP-IDF.

//% FEATURES: esp-wifi esp-wifi/wifi esp-hal/unstable
//% CHIPS: esp32 esp32s2 esp32s3 esp32c2 esp32c3 esp32c6

#![no_std]
#![no_main]

extern crate alloc;

use alloc::{collections::BTreeSet, string::String, vec::Vec};
use esp_backtrace as _;
use esp_hal::{clock::CpuClock, main, rng::Rng, timer::timg::TimerGroup};
use esp_println::println;
use esp_wifi::{init, wifi::WifiMode};

esp_bootloader_esp_idf::esp_app_desc!();

#[main]
fn main() -> ! {
esp_println::logger::init_logger_from_env();
let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max());
let peripherals = esp_hal::init(config);

esp_alloc::heap_allocator!(size: 72 * 1024);

let timg0 = TimerGroup::new(peripherals.TIMG0);
let esp_wifi_ctrl = init(timg0.timer0, Rng::new(peripherals.RNG)).unwrap();

let (mut controller, _interfaces) =
esp_wifi::wifi::new(&esp_wifi_ctrl, peripherals.WIFI).unwrap();

controller.set_mode(WifiMode::Sta).unwrap();
controller.start().unwrap();

println!("Starting WiFi scan with country code display...");

// Perform WiFi scan
let scan_results = controller.scan_n(20).unwrap();

println!("Found {} access points:\n", scan_results.len());
println!("{:<25} | {:<8} | {:<5} | {:<8}", "SSID", "Channel", "RSSI", "Country");
println!("{:-<50}", "");

// Display scan results with country codes
for ap in &scan_results {
let country_display = ap.country_code.as_deref().unwrap_or("Unknown");
println!(
"{:<25} | {:<8} | {:<5} | {:<8}",
if ap.ssid.len() > 24 { &ap.ssid[..24] } else { &ap.ssid },
ap.channel,
ap.signal_strength,
country_display
);
}

// Show unique country codes found
let unique_countries: Vec<String> = {
let mut countries: BTreeSet<String> = BTreeSet::new();
for ap in &scan_results {
if let Some(ref country) = ap.country_code {
countries.insert(country.clone());
}
}
countries.into_iter().collect()
};

println!("\nUnique country codes detected: {:?}", unique_countries);
println!("Total APs with country info: {}",
scan_results.iter().filter(|ap| ap.country_code.is_some()).count());

loop {
let mut delay = esp_hal::delay::Delay::new();
delay.delay_millis(1000u32);
}
}
Loading