-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathwifi.rs
3033 lines (2559 loc) · 98 KB
/
wifi.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! WiFi support
use core::marker::PhantomData;
use core::str::Utf8Error;
use core::time::Duration;
use core::{cmp, ffi, fmt, ops};
extern crate alloc;
use alloc::boxed::Box;
use alloc::sync::Arc;
use enumset::*;
use embedded_svc::wifi::Wifi;
use crate::hal::modem::WifiModemPeripheral;
use crate::hal::peripheral::Peripheral;
use crate::sys::*;
use crate::eventloop::EspEventLoop;
use crate::eventloop::{
EspEventDeserializer, EspEventSource, EspSubscription, EspSystemEventLoop, System, Wait,
};
use crate::handle::RawHandle;
#[cfg(esp_idf_comp_esp_netif_enabled)]
use crate::netif::*;
use crate::nvs::EspDefaultNvsPartition;
use crate::private::common::*;
use crate::private::cstr::*;
use crate::private::mutex;
#[cfg(all(feature = "alloc", esp_idf_comp_esp_timer_enabled))]
use crate::timer::EspTaskTimerService;
pub use embedded_svc::wifi::{
AccessPointConfiguration, AccessPointInfo, AuthMethod, Capability, ClientConfiguration,
Configuration, PmfConfiguration, Protocol, ScanMethod, ScanSortMethod, SecondaryChannel,
};
pub mod config {
use core::time::Duration;
use crate::sys::*;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ScanType {
Active { min: Duration, max: Duration },
Passive(Duration),
}
impl ScanType {
pub const fn new() -> Self {
Self::Active {
min: Duration::from_secs(0),
max: Duration::from_secs(0),
}
}
}
impl Default for ScanType {
fn default() -> Self {
Self::new()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ScanConfig {
pub bssid: Option<[u8; 6]>,
pub ssid: Option<heapless::String<32>>,
pub channel: Option<u8>,
pub scan_type: ScanType,
pub show_hidden: bool,
}
impl ScanConfig {
pub const fn new() -> Self {
Self {
bssid: None,
ssid: None,
channel: None,
scan_type: ScanType::new(),
show_hidden: false,
}
}
}
impl Default for ScanConfig {
fn default() -> Self {
Self::new()
}
}
impl From<&ScanConfig> for wifi_scan_config_t {
fn from(s: &ScanConfig) -> Self {
#[allow(clippy::needless_update)]
Self {
bssid: s.bssid.map_or(core::ptr::null(), |v| v.as_ptr()) as *mut u8,
ssid: s.ssid.as_ref().map_or(core::ptr::null(), |v| v.as_ptr()) as *mut u8,
scan_time: wifi_scan_time_t {
active: wifi_active_scan_time_t {
min: match s.scan_type {
ScanType::Active { min, .. } => min.as_millis() as _,
_ => 0,
},
max: match s.scan_type {
ScanType::Active { max, .. } => max.as_millis() as _,
_ => 0,
},
},
passive: match s.scan_type {
ScanType::Passive(time) => time.as_millis() as _,
_ => 0,
},
},
channel: s.channel.unwrap_or_default(),
scan_type: matches!(s.scan_type, ScanType::Active { .. }).into(),
show_hidden: s.show_hidden,
..Default::default()
}
}
}
}
impl From<AuthMethod> for Newtype<wifi_auth_mode_t> {
fn from(method: AuthMethod) -> Self {
Newtype(match method {
AuthMethod::None => wifi_auth_mode_t_WIFI_AUTH_OPEN,
AuthMethod::WEP => wifi_auth_mode_t_WIFI_AUTH_WEP,
AuthMethod::WPA => wifi_auth_mode_t_WIFI_AUTH_WPA_PSK,
AuthMethod::WPA2Personal => wifi_auth_mode_t_WIFI_AUTH_WPA2_PSK,
AuthMethod::WPAWPA2Personal => wifi_auth_mode_t_WIFI_AUTH_WPA_WPA2_PSK,
AuthMethod::WPA2Enterprise => wifi_auth_mode_t_WIFI_AUTH_WPA2_ENTERPRISE,
AuthMethod::WPA3Personal => wifi_auth_mode_t_WIFI_AUTH_WPA3_PSK,
AuthMethod::WPA2WPA3Personal => wifi_auth_mode_t_WIFI_AUTH_WPA2_WPA3_PSK,
AuthMethod::WAPIPersonal => wifi_auth_mode_t_WIFI_AUTH_WAPI_PSK,
})
}
}
impl From<Newtype<wifi_auth_mode_t>> for Option<AuthMethod> {
#[allow(non_upper_case_globals)]
#[allow(non_snake_case)]
fn from(mode: Newtype<wifi_auth_mode_t>) -> Self {
match mode.0 {
wifi_auth_mode_t_WIFI_AUTH_OPEN => Some(AuthMethod::None),
wifi_auth_mode_t_WIFI_AUTH_WEP => Some(AuthMethod::WEP),
wifi_auth_mode_t_WIFI_AUTH_WPA_PSK => Some(AuthMethod::WPA),
wifi_auth_mode_t_WIFI_AUTH_WPA2_PSK => Some(AuthMethod::WPA2Personal),
wifi_auth_mode_t_WIFI_AUTH_WPA_WPA2_PSK => Some(AuthMethod::WPAWPA2Personal),
wifi_auth_mode_t_WIFI_AUTH_WPA2_ENTERPRISE => Some(AuthMethod::WPA2Enterprise),
wifi_auth_mode_t_WIFI_AUTH_WPA3_PSK => Some(AuthMethod::WPA3Personal),
wifi_auth_mode_t_WIFI_AUTH_WPA2_WPA3_PSK => Some(AuthMethod::WPA2WPA3Personal),
wifi_auth_mode_t_WIFI_AUTH_WAPI_PSK => Some(AuthMethod::WAPIPersonal),
_ => None,
}
}
}
impl TryFrom<&ClientConfiguration> for Newtype<wifi_sta_config_t> {
type Error = EspError;
fn try_from(conf: &ClientConfiguration) -> Result<Self, Self::Error> {
let bssid: [u8; 6] = match &conf.bssid {
Some(bssid_ref) => *bssid_ref,
None => [0; 6],
};
#[allow(clippy::needless_update)]
let mut result = wifi_sta_config_t {
ssid: [0; 32],
password: [0; 64],
scan_method: match conf.scan_method {
ScanMethod::CompleteScan(_) => wifi_scan_method_t_WIFI_ALL_CHANNEL_SCAN,
ScanMethod::FastScan => wifi_scan_method_t_WIFI_FAST_SCAN,
_ => wifi_scan_method_t_WIFI_ALL_CHANNEL_SCAN,
},
bssid_set: conf.bssid.is_some(),
bssid,
channel: conf.channel.unwrap_or(0u8),
listen_interval: 0,
sort_method: match conf.scan_method {
ScanMethod::CompleteScan(ScanSortMethod::Signal) => {
wifi_sort_method_t_WIFI_CONNECT_AP_BY_SIGNAL
}
ScanMethod::CompleteScan(ScanSortMethod::Security) => {
wifi_sort_method_t_WIFI_CONNECT_AP_BY_SECURITY
}
_ => wifi_sort_method_t_WIFI_CONNECT_AP_BY_SIGNAL,
},
threshold: wifi_scan_threshold_t {
rssi: -127,
authmode: Newtype::<wifi_auth_mode_t>::from(conf.auth_method).0,
..Default::default()
},
pmf_cfg: wifi_pmf_config_t {
capable: false,
required: false,
},
..Default::default()
};
set_str_no_termination_requirement(&mut result.ssid, conf.ssid.as_ref())?;
set_str_no_termination_requirement(&mut result.password, conf.password.as_ref())?;
Ok(Newtype(result))
}
}
impl From<Newtype<wifi_sta_config_t>> for ClientConfiguration {
fn from(conf: Newtype<wifi_sta_config_t>) -> Self {
Self {
ssid: array_to_heapless_string(conf.0.ssid),
bssid: if conf.0.bssid_set {
Some(conf.0.bssid)
} else {
None
},
auth_method: Option::<AuthMethod>::from(Newtype(conf.0.threshold.authmode)).unwrap(),
password: array_to_heapless_string(conf.0.password),
channel: if conf.0.channel != 0 {
Some(conf.0.channel)
} else {
None
},
#[allow(non_upper_case_globals)]
#[allow(non_snake_case)]
scan_method: match conf.0.scan_method {
wifi_scan_method_t_WIFI_FAST_SCAN => ScanMethod::FastScan,
wifi_scan_method_t_WIFI_ALL_CHANNEL_SCAN => match conf.0.sort_method {
wifi_sort_method_t_WIFI_CONNECT_AP_BY_SIGNAL => {
ScanMethod::CompleteScan(ScanSortMethod::Signal)
}
wifi_sort_method_t_WIFI_CONNECT_AP_BY_SECURITY => {
ScanMethod::CompleteScan(ScanSortMethod::Security)
}
_ => ScanMethod::default(),
},
_ => ScanMethod::default(),
},
pmf_cfg: match conf.0.pmf_cfg {
wifi_pmf_config_t {
capable: false,
required: _,
} => PmfConfiguration::NotCapable,
wifi_pmf_config_t {
capable: true,
required,
} => PmfConfiguration::Capable { required },
},
}
}
}
impl TryFrom<&AccessPointConfiguration> for Newtype<wifi_ap_config_t> {
type Error = EspError;
fn try_from(conf: &AccessPointConfiguration) -> Result<Self, Self::Error> {
let mut result = wifi_ap_config_t {
ssid: [0; 32],
password: [0; 64],
ssid_len: conf.ssid.len() as u8,
channel: conf.channel,
authmode: Newtype::<wifi_auth_mode_t>::from(conf.auth_method).0,
ssid_hidden: u8::from(conf.ssid_hidden),
max_connection: cmp::min(conf.max_connections, 16) as u8,
beacon_interval: 100,
..Default::default()
};
set_str(&mut result.ssid, conf.ssid.as_ref())?;
set_str(&mut result.password, conf.password.as_ref())?;
Ok(Newtype(result))
}
}
impl From<Newtype<wifi_ap_config_t>> for AccessPointConfiguration {
fn from(conf: Newtype<wifi_ap_config_t>) -> Self {
Self {
ssid: if conf.0.ssid_len == 0 {
Default::default()
} else {
unsafe {
core::str::from_utf8_unchecked(&conf.0.ssid[0..conf.0.ssid_len as usize])
.try_into()
.unwrap()
}
},
ssid_hidden: conf.0.ssid_hidden != 0,
channel: conf.0.channel,
secondary_channel: None,
auth_method: Option::<AuthMethod>::from(Newtype(conf.0.authmode)).unwrap(),
protocols: EnumSet::<Protocol>::empty(), // TODO
password: array_to_heapless_string(conf.0.password),
max_connections: conf.0.max_connection as u16,
}
}
}
impl TryFrom<Newtype<&wifi_ap_record_t>> for AccessPointInfo {
type Error = Utf8Error;
#[allow(non_upper_case_globals)]
#[allow(non_snake_case)]
fn try_from(ap_info: Newtype<&wifi_ap_record_t>) -> Result<Self, Self::Error> {
let a = ap_info.0;
Ok(Self {
ssid: from_cstr_fallible(&a.ssid)?.try_into().unwrap(),
bssid: a.bssid,
channel: a.primary,
secondary_channel: match a.second {
wifi_second_chan_t_WIFI_SECOND_CHAN_NONE => SecondaryChannel::None,
wifi_second_chan_t_WIFI_SECOND_CHAN_ABOVE => SecondaryChannel::Above,
wifi_second_chan_t_WIFI_SECOND_CHAN_BELOW => SecondaryChannel::Below,
_ => panic!(),
},
signal_strength: a.rssi,
protocols: EnumSet::<Protocol>::empty(), // TODO
auth_method: Option::<AuthMethod>::from(Newtype::<wifi_auth_mode_t>(a.authmode)),
})
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum WifiDeviceId {
Ap,
Sta,
}
impl From<WifiDeviceId> for wifi_interface_t {
fn from(id: WifiDeviceId) -> Self {
match id {
WifiDeviceId::Ap => wifi_interface_t_WIFI_IF_AP,
WifiDeviceId::Sta => wifi_interface_t_WIFI_IF_STA,
}
}
}
#[allow(non_upper_case_globals)]
impl From<wifi_interface_t> for WifiDeviceId {
fn from(id: wifi_interface_t) -> Self {
match id {
wifi_interface_t_WIFI_IF_AP => WifiDeviceId::Ap,
wifi_interface_t_WIFI_IF_STA => WifiDeviceId::Sta,
_ => unreachable!(),
}
}
}
extern "C" {
fn esp_wifi_internal_reg_rxcb(
ifx: wifi_interface_t,
rxcb: Option<
unsafe extern "C" fn(
buffer: *mut ffi::c_void,
len: u16,
eb: *mut ffi::c_void,
) -> esp_err_t,
>,
) -> esp_err_t;
fn esp_wifi_internal_free_rx_buffer(buffer: *mut ffi::c_void);
fn esp_wifi_internal_tx(
wifi_if: wifi_interface_t,
buffer: *mut ffi::c_void,
len: u16,
) -> esp_err_t;
}
#[allow(clippy::type_complexity)]
static mut RX_CALLBACK: Option<
Box<dyn FnMut(WifiDeviceId, WifiFrame) -> Result<(), EspError> + 'static>,
> = None;
#[allow(clippy::type_complexity)]
static mut TX_CALLBACK: Option<Box<dyn FnMut(WifiDeviceId, &[u8], bool) + 'static>> = None;
pub trait NonBlocking {
fn is_scan_done(&self) -> Result<bool, EspError>;
fn start_scan(
&mut self,
scan_config: &config::ScanConfig,
blocking: bool,
) -> Result<(), EspError>;
fn stop_scan(&mut self) -> Result<(), EspError>;
fn get_scan_result_n<const N: usize>(
&mut self,
) -> Result<(heapless::Vec<AccessPointInfo, N>, usize), EspError>;
#[cfg(feature = "alloc")]
fn get_scan_result(&mut self) -> Result<alloc::vec::Vec<AccessPointInfo>, EspError>;
fn start_wps(&mut self, config: &WpsConfig) -> Result<(), EspError>;
fn stop_wps(&mut self) -> Result<WpsStatus, EspError>;
fn is_wps_finished(&self) -> Result<bool, EspError>;
}
impl<T> NonBlocking for &mut T
where
T: NonBlocking,
{
fn is_scan_done(&self) -> Result<bool, EspError> {
(**self).is_scan_done()
}
fn start_scan(
&mut self,
scan_config: &config::ScanConfig,
blocking: bool,
) -> Result<(), EspError> {
(**self).start_scan(scan_config, blocking)
}
fn stop_scan(&mut self) -> Result<(), EspError> {
(**self).stop_scan()
}
fn get_scan_result_n<const N: usize>(
&mut self,
) -> Result<(heapless::Vec<AccessPointInfo, N>, usize), EspError> {
(**self).get_scan_result_n()
}
#[cfg(feature = "alloc")]
fn get_scan_result(&mut self) -> Result<alloc::vec::Vec<AccessPointInfo>, EspError> {
(**self).get_scan_result()
}
fn start_wps(&mut self, config: &WpsConfig) -> Result<(), EspError> {
(**self).start_wps(config)
}
fn stop_wps(&mut self) -> Result<WpsStatus, EspError> {
(**self).stop_wps()
}
fn is_wps_finished(&self) -> Result<bool, EspError> {
(**self).is_wps_finished()
}
}
/// This struct provides a safe wrapper over the ESP IDF Wifi C driver.
///
/// The driver works on Layer 2 (Data Link) in the OSI model, in that it provides
/// facilities for sending and receiving ethernet packets over the WiFi radio.
///
/// For most use cases, utilizing `EspWifi` - which provides a networking (IP)
/// layer as well - should be preferred. Using `WifiDriver` directly is beneficial
/// only when one would like to utilize a custom, non-STD network stack like `smoltcp`.
pub struct WifiDriver<'d> {
status: Arc<mutex::Mutex<WifiDriverStatus>>,
_subscription: EspSubscription<'static, System>,
#[cfg(all(feature = "alloc", esp_idf_comp_nvs_flash_enabled))]
_nvs: Option<EspDefaultNvsPartition>,
_p: PhantomData<&'d mut ()>,
}
#[derive(Clone, Debug)]
struct WifiDriverStatus {
pub sta: WifiStaStatus,
pub scan: WifiScanStatus,
pub ap: WifiApStatus,
pub wps: Option<WpsStatus>,
}
impl<'d> WifiDriver<'d> {
#[cfg(all(feature = "alloc", esp_idf_comp_nvs_flash_enabled))]
pub fn new<M: WifiModemPeripheral>(
_modem: impl Peripheral<P = M> + 'd,
sysloop: EspSystemEventLoop,
nvs: Option<EspDefaultNvsPartition>,
) -> Result<Self, EspError> {
Self::init(nvs.is_some())?;
let (status, subscription) = Self::subscribe(&sysloop)?;
Ok(Self {
status,
_subscription: subscription,
_nvs: nvs,
_p: PhantomData,
})
}
#[cfg(not(all(feature = "alloc", esp_idf_comp_nvs_flash_enabled)))]
pub fn new<M: WifiModemPeripheral>(
_modem: impl Peripheral<P = M> + 'd,
sysloop: EspSystemEventLoop,
) -> Result<Self, EspError> {
Self::init(false)?;
let (status, subscription) = Self::subscribe(&sysloop)?;
Ok(Self {
status,
_subscription: subscription,
_p: PhantomData,
})
}
#[allow(clippy::type_complexity)]
fn subscribe(
sysloop: &EspEventLoop<System>,
) -> Result<
(
Arc<mutex::Mutex<WifiDriverStatus>>,
EspSubscription<'static, System>,
),
EspError,
> {
let status = Arc::new(mutex::Mutex::new(WifiDriverStatus {
sta: WifiStaStatus::Stopped,
ap: WifiApStatus::Stopped,
scan: WifiScanStatus::Idle,
wps: None,
}));
let s_status = status.clone();
let subscription = sysloop.subscribe::<WifiEvent, _>(move |event: WifiEvent| {
let mut guard = s_status.lock();
match event {
WifiEvent::ApStarted => guard.ap = WifiApStatus::Started,
WifiEvent::ApStopped => guard.ap = WifiApStatus::Stopped,
WifiEvent::StaStarted => guard.sta = WifiStaStatus::Started,
WifiEvent::StaStopped => guard.sta = WifiStaStatus::Stopped,
WifiEvent::StaConnected(_) => guard.sta = WifiStaStatus::Connected,
WifiEvent::StaDisconnected(_) => guard.sta = WifiStaStatus::Started,
WifiEvent::ScanDone(_) => guard.scan = WifiScanStatus::Done,
WifiEvent::StaWpsSuccess(_)
| WifiEvent::StaWpsFailed
| WifiEvent::StaWpsTimeout
| WifiEvent::StaWpsPin(_)
| WifiEvent::StaWpsPbcOverlap => guard.wps = Some((&event).try_into().unwrap()),
_ => (),
};
})?;
Ok((status, subscription))
}
fn init(nvs_enabled: bool) -> Result<(), EspError> {
#[allow(clippy::needless_update)]
#[allow(unused_unsafe)]
let cfg = wifi_init_config_t {
#[cfg(esp_idf_version_major = "4")]
event_handler: Some(esp_event_send_internal),
osi_funcs: unsafe { core::ptr::addr_of_mut!(g_wifi_osi_funcs) },
wpa_crypto_funcs: unsafe { g_wifi_default_wpa_crypto_funcs },
static_rx_buf_num: CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM as _,
dynamic_rx_buf_num: CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM as _,
tx_buf_type: CONFIG_ESP32_WIFI_TX_BUFFER_TYPE as _,
static_tx_buf_num: WIFI_STATIC_TX_BUFFER_NUM as _,
dynamic_tx_buf_num: WIFI_DYNAMIC_TX_BUFFER_NUM as _,
rx_mgmt_buf_type: CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUF as _,
rx_mgmt_buf_num: WIFI_RX_MGMT_BUF_NUM_DEF as _,
cache_tx_buf_num: WIFI_CACHE_TX_BUFFER_NUM as _,
csi_enable: WIFI_CSI_ENABLED as _,
ampdu_rx_enable: WIFI_AMPDU_RX_ENABLED as _,
ampdu_tx_enable: WIFI_AMPDU_TX_ENABLED as _,
amsdu_tx_enable: WIFI_AMSDU_TX_ENABLED as _,
nvs_enable: i32::from(nvs_enabled),
nano_enable: WIFI_NANO_FORMAT_ENABLED as _,
rx_ba_win: WIFI_DEFAULT_RX_BA_WIN as _,
wifi_task_core_id: WIFI_TASK_CORE_ID as _,
beacon_max_len: WIFI_SOFTAP_BEACON_MAX_LEN as _,
mgmt_sbuf_num: WIFI_MGMT_SBUF_NUM as _,
#[cfg(any(
esp_idf_version_major = "4",
all(esp_idf_version_major = "5", esp_idf_version_minor = "0"),
esp_idf_version_full = "5.1.0",
esp_idf_version_full = "5.1.1",
esp_idf_version_full = "5.1.2"
))]
feature_caps: unsafe { g_wifi_feature_caps },
#[cfg(not(any(
esp_idf_version_major = "4",
all(esp_idf_version_major = "5", esp_idf_version_minor = "0"),
esp_idf_version_full = "5.1.0",
esp_idf_version_full = "5.1.1",
esp_idf_version_full = "5.1.2"
)))]
feature_caps: WIFI_FEATURE_CAPS as _,
sta_disconnected_pm: WIFI_STA_DISCONNECTED_PM_ENABLED != 0,
// Available since ESP IDF V4.4.4+
#[cfg(any(
not(esp_idf_version_major = "4"),
all(
esp_idf_version_major = "4",
any(
not(esp_idf_version_minor = "4"),
all(
not(esp_idf_version_patch = "0"),
not(esp_idf_version_patch = "1"),
not(esp_idf_version_patch = "2"),
not(esp_idf_version_patch = "3")
)
)
)
))]
espnow_max_encrypt_num: CONFIG_ESP_WIFI_ESPNOW_MAX_ENCRYPT_NUM as i32,
magic: WIFI_INIT_CONFIG_MAGIC as _,
// Available since ESP IDF V5.3.0
#[cfg(any(
all(not(esp_idf_version_major = "4"), not(esp_idf_version_major = "5")),
all(
esp_idf_version_major = "5",
not(esp_idf_version = "5.0"),
not(esp_idf_version = "5.1"),
not(esp_idf_version = "5.2"),
),
))]
tx_hetb_queue_num: WIFI_TX_HETB_QUEUE_NUM as _,
// Available since ESP IDF V5.3.0
#[cfg(any(
all(not(esp_idf_version_major = "4"), not(esp_idf_version_major = "5")),
all(
esp_idf_version_major = "5",
not(esp_idf_version = "5.0"),
not(esp_idf_version = "5.1"),
not(esp_idf_version = "5.2"),
),
))]
dump_hesigb_enable: WIFI_DUMP_HESIGB_ENABLED != 0,
..Default::default()
};
esp!(unsafe { esp_wifi_init(&cfg) })?;
::log::debug!("Driver initialized");
Ok(())
}
/// Returns the set of [`Capabilities`] for this driver. In `esp-idf`, all
/// drivers always have Client, AP and Mixed capabilities.
pub fn get_capabilities(&self) -> Result<EnumSet<Capability>, EspError> {
let caps = Capability::Client | Capability::AccessPoint | Capability::Mixed;
::log::debug!("Providing capabilities: {:?}", caps);
Ok(caps)
}
/// As per [`crate::sys::esp_wifi_start`](crate::sys::esp_wifi_start)
pub fn start(&mut self) -> Result<(), EspError> {
::log::debug!("Start requested");
esp!(unsafe { esp_wifi_start() })?;
::log::debug!("Starting");
Ok(())
}
/// As per [`crate::sys::esp_wifi_stop`](crate::sys::esp_wifi_stop)
pub fn stop(&mut self) -> Result<(), EspError> {
::log::debug!("Stop requested");
esp!(unsafe { esp_wifi_stop() })?;
::log::debug!("Stopping");
Ok(())
}
/// As per [`crate::sys::esp_wifi_connect`](crate::sys::esp_wifi_connect)
pub fn connect(&mut self) -> Result<(), EspError> {
::log::debug!("Connect requested");
esp!(unsafe { esp_wifi_connect() })?;
::log::debug!("Connecting");
Ok(())
}
/// As per [`crate::sys::esp_wifi_disconnect`](crate::sys::esp_wifi_disconnect)
pub fn disconnect(&mut self) -> Result<(), EspError> {
::log::debug!("Disconnect requested");
esp!(unsafe { esp_wifi_disconnect() })?;
::log::debug!("Disconnecting");
Ok(())
}
/// Returns `true` if the driver is in Access Point (AP) mode, as reported by
/// [`crate::sys::esp_wifi_get_mode`](crate::sys::esp_wifi_get_mode)
pub fn is_ap_enabled(&self) -> Result<bool, EspError> {
let mut mode: wifi_mode_t = 0;
esp!(unsafe { esp_wifi_get_mode(&mut mode) })?;
Ok(mode == wifi_mode_t_WIFI_MODE_AP || mode == wifi_mode_t_WIFI_MODE_APSTA)
}
/// Returns `true` if the driver is in Client (station or STA) mode, as
/// reported by [`crate::sys::esp_wifi_get_mode`](crate::sys::esp_wifi_get_mode)
pub fn is_sta_enabled(&self) -> Result<bool, EspError> {
let mut mode: wifi_mode_t = 0;
esp!(unsafe { esp_wifi_get_mode(&mut mode) })?;
Ok(mode == wifi_mode_t_WIFI_MODE_STA || mode == wifi_mode_t_WIFI_MODE_APSTA)
}
pub fn is_ap_started(&self) -> Result<bool, EspError> {
Ok(matches!(self.status.lock().ap, WifiApStatus::Started))
}
pub fn is_sta_started(&self) -> Result<bool, EspError> {
let guard = self.status.lock();
Ok(matches!(
guard.sta,
WifiStaStatus::Started | WifiStaStatus::Connected
))
}
pub fn is_sta_connected(&self) -> Result<bool, EspError> {
Ok(matches!(self.status.lock().sta, WifiStaStatus::Connected))
}
pub fn is_started(&self) -> Result<bool, EspError> {
let ap_enabled = self.is_ap_enabled()?;
let sta_enabled = self.is_sta_enabled()?;
if !ap_enabled && !sta_enabled {
Ok(false)
} else {
Ok(
(!ap_enabled || self.is_ap_started()?)
&& (!sta_enabled || self.is_sta_started()?),
)
}
}
pub fn is_connected(&self) -> Result<bool, EspError> {
let ap_enabled = self.is_ap_enabled()?;
let sta_enabled = self.is_sta_enabled()?;
if !ap_enabled && !sta_enabled {
Ok(false)
} else {
let guard = self.status.lock();
Ok((!ap_enabled || matches!(guard.ap, WifiApStatus::Started))
&& (!sta_enabled || matches!(guard.sta, WifiStaStatus::Connected)))
}
}
pub fn is_scan_done(&self) -> Result<bool, EspError> {
let guard = self.status.lock();
Ok(matches!(guard.scan, WifiScanStatus::Done))
}
#[allow(non_upper_case_globals)]
#[allow(non_snake_case)]
/// Returns the <`Configuration`> currently in use
pub fn get_configuration(&self) -> Result<Configuration, EspError> {
::log::debug!("Getting configuration");
let mut mode: wifi_mode_t = 0;
esp!(unsafe { esp_wifi_get_mode(&mut mode) })?;
let conf = match mode {
wifi_mode_t_WIFI_MODE_NULL => Configuration::None,
wifi_mode_t_WIFI_MODE_AP => Configuration::AccessPoint(self.get_ap_conf()?),
wifi_mode_t_WIFI_MODE_STA => Configuration::Client(self.get_sta_conf()?),
wifi_mode_t_WIFI_MODE_APSTA => {
Configuration::Mixed(self.get_sta_conf()?, self.get_ap_conf()?)
}
_ => panic!(),
};
::log::debug!("Configuration gotten: {:?}", &conf);
Ok(conf)
}
/// Sets the <`Configuration`> (SSID, channel, etc). This also defines whether
/// the driver will work in AP mode, client mode, client+AP mode, or none.
///
/// Calls [`crate::sys::esp_wifi_set_mode`](crate::sys::esp_wifi_set_mode)
/// and [`crate::sys::esp_wifi_set_config`](crate::sys::esp_wifi_set_config)
pub fn set_configuration(&mut self, conf: &Configuration) -> Result<(), EspError> {
::log::debug!("Setting configuration: {:?}", conf);
match conf {
Configuration::None => {
unsafe {
esp!(esp_wifi_set_mode(wifi_mode_t_WIFI_MODE_NULL))?;
}
::log::debug!("Wifi mode NULL set");
}
Configuration::AccessPoint(ap_conf) => {
unsafe {
esp!(esp_wifi_set_mode(wifi_mode_t_WIFI_MODE_AP))?;
}
::log::debug!("Wifi mode AP set");
self.set_ap_conf(ap_conf)?;
}
Configuration::Client(client_conf) => {
unsafe {
esp!(esp_wifi_set_mode(wifi_mode_t_WIFI_MODE_STA))?;
}
::log::debug!("Wifi mode STA set");
self.set_sta_conf(client_conf)?;
}
Configuration::Mixed(client_conf, ap_conf) => {
unsafe {
esp!(esp_wifi_set_mode(wifi_mode_t_WIFI_MODE_APSTA))?;
}
::log::debug!("Wifi mode APSTA set");
self.set_sta_conf(client_conf)?;
self.set_ap_conf(ap_conf)?;
}
}
::log::debug!("Configuration set");
Ok(())
}
/// Scan for nearby, visible access points.
///
/// It scans for all available access points nearby, but returns only the first `N` access points found.
/// In addition, it returns the actual amount it found. The function blocks until the scan is done.
///
/// Before calling this function the Wifi driver must be configured and started in either Client or Mixed mode.
///
/// # Example
/// ```ignore
/// let mut wifi_driver = WifiDriver::new(peripherals.modem, sysloop.clone());
/// wifi_driver.set_configuration(
/// &Configuration::Client(ClientConfiguration::default())
/// )
/// .unwrap();
/// wifi_driver.start().unwrap();
///
/// let (scan_result, found_aps) = wifi_driver.scan_n::<10>().unwrap();
/// ```
// For backwards compatibility
pub fn scan_n<const N: usize>(
&mut self,
) -> Result<(heapless::Vec<AccessPointInfo, N>, usize), EspError> {
self.start_scan(&Default::default(), true)?;
self.get_scan_result_n()
}
/// Scan for nearby, visible access points.
///
/// Unlike [`WifiDriver::scan_n()`], it returns all found access points by allocating memory
/// dynamically.
///
/// For more details see [`WifiDriver::scan_n()`].
// For backwards compatibility
#[cfg(feature = "alloc")]
pub fn scan(&mut self) -> Result<alloc::vec::Vec<AccessPointInfo>, EspError> {
self.start_scan(&Default::default(), true)?;
self.get_scan_result()
}
/// Start scanning for nearby, visible access points.
///
/// Unlike [`WifiDriver::scan_n()`] or [`WifiDriver::scan()`] it can be called as either blocking or not blocking.
/// A [`ScanConfig`] can be provided as well. To get the scan result call either [`WifiDriver::get_scan_result_n()`] or
/// [`WifiDriver::get_scan_result()`].
///
/// This function can be used in `async` context, when the current thread shouldn't be blocked.
///
/// # Example
///
/// This example shows how to use it in a `async` context.
///
/// ```ignore
/// let mut wifi_driver = WifiDriver::new(peripherals.modem, sysloop.clone());
/// wifi_driver.set_configuration(
/// &Configuration::Client(ClientConfiguration::default())
/// )
/// .unwrap();
/// wifi_driver.start().unwrap();
///
/// let scan_finish_signal = Arc::new(channel_bridge::notification::Notification::new());
/// let _sub = {
/// let scan_finish_signal = scan_finish_signal.clone();
/// sysloop.subscribe::<WifiEvent>(move |event| {
/// if *event == WifiEvent::ScanDone {
/// scan_finish_signal.notify();
/// }
/// }).unwrap()
/// };
///
/// wifi_driver.start_scan(&ScanConfig::default(), false).unwrap();
///
/// scan_finish_signal.wait().await;
///
/// let res = wifi_driver.get_scan_result().unwrap();
/// ```
pub fn start_scan(
&mut self,
scan_config: &config::ScanConfig,
blocking: bool,
) -> Result<(), EspError> {
::log::debug!("About to scan for access points");
let scan_config: wifi_scan_config_t = scan_config.into();
esp!(unsafe { esp_wifi_scan_start(&scan_config as *const wifi_scan_config_t, blocking) })?;
self.status.lock().scan = WifiScanStatus::Started;
Ok(())
}
/// Stops a previous started access point scan.
pub fn stop_scan(&mut self) -> Result<(), EspError> {
::log::debug!("About to stop scan for access points");
esp!(unsafe { esp_wifi_scan_stop() })?;
self.status.lock().scan = WifiScanStatus::Idle;
Ok(())
}
/// Get the results of an access point scan.
///
/// This call returns a list of the first `N` found access points. A scan can be started with [`WifiDriver::start_scan()`].
/// As [`WifiDriver::scan_n()`] it returns the actual amount of found access points as well.
pub fn get_scan_result_n<const N: usize>(
&mut self,
) -> Result<(heapless::Vec<AccessPointInfo, N>, usize), EspError> {
let scanned_count = self.get_scan_count()?;
let mut ap_infos_raw: heapless::Vec<wifi_ap_record_t, N> = heapless::Vec::new();
unsafe {
ap_infos_raw.set_len(scanned_count.min(N));
}
let fetched_count = self.fetch_scan_result(&mut ap_infos_raw)?;
let result = ap_infos_raw[..fetched_count]
.iter()
.map::<Result<AccessPointInfo, Utf8Error>, _>(|ap_info_raw| {
Newtype(ap_info_raw).try_into()
})
.filter_map(|r| r.ok())
.inspect(|ap_info| ::log::debug!("Found access point {:?}", ap_info))
.collect();
Ok((result, scanned_count))
}
/// Get the results of an access point scan.
///
/// Unlike [`WifiDriver::get_scan_result_n()`], it returns all found access points by allocating memory
/// dynamically.
///
/// For more details see [`WifiDriver::get_scan_result_n()`].
#[cfg(feature = "alloc")]
pub fn get_scan_result(&mut self) -> Result<alloc::vec::Vec<AccessPointInfo>, EspError> {
let scanned_count = self.get_scan_count()?;
let mut ap_infos_raw: alloc::vec::Vec<wifi_ap_record_t> =
alloc::vec::Vec::with_capacity(scanned_count);
#[allow(clippy::uninit_vec)]
// ... because we are filling it in on the next line and only reading the initialized members
unsafe {
ap_infos_raw.set_len(scanned_count)
};
let fetched_count = self.fetch_scan_result(&mut ap_infos_raw)?;
let result = ap_infos_raw[..fetched_count]
.iter()
.map::<Result<AccessPointInfo, Utf8Error>, _>(|ap_info_raw| {
Newtype(ap_info_raw).try_into()
})
.filter_map(|r| r.ok())
.inspect(|ap_info| ::log::debug!("Found access point {:?}", ap_info))
.collect();
Ok(result)
}
/// Sets callback functions for receiving and sending data, as per
/// [`crate::sys::esp_wifi_internal_reg_rxcb`](crate::sys::esp_wifi_internal_reg_rxcb) and
/// [`crate::sys::esp_wifi_set_tx_done_cb`](crate::sys::esp_wifi_set_tx_done_cb)
pub fn set_callbacks<R, T>(&mut self, rx_callback: R, tx_callback: T) -> Result<(), EspError>
where
R: FnMut(WifiDeviceId, WifiFrame) -> Result<(), EspError> + Send + 'static,
T: FnMut(WifiDeviceId, &[u8], bool) + Send + 'static,