-
Notifications
You must be signed in to change notification settings - Fork 264
/
Copy pathmod.rs
3442 lines (3010 loc) · 110 KB
/
mod.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
pub mod event;
pub(crate) mod os_adapter;
pub(crate) mod state;
use alloc::collections::vec_deque::VecDeque;
use core::{
fmt::Debug,
mem::{self, MaybeUninit},
ptr::addr_of,
time::Duration,
};
use enumset::{EnumSet, EnumSetType};
use esp_hal::sync::Locked;
use esp_wifi_sys::include::{
esp_eap_client_clear_ca_cert,
esp_eap_client_clear_certificate_and_key,
esp_eap_client_clear_identity,
esp_eap_client_clear_new_password,
esp_eap_client_clear_password,
esp_eap_client_clear_username,
esp_eap_client_set_ca_cert,
esp_eap_client_set_certificate_and_key,
esp_eap_client_set_disable_time_check,
esp_eap_client_set_fast_params,
esp_eap_client_set_identity,
esp_eap_client_set_new_password,
esp_eap_client_set_pac_file,
esp_eap_client_set_password,
esp_eap_client_set_ttls_phase2_method,
esp_eap_client_set_username,
esp_eap_fast_config,
esp_wifi_sta_enterprise_enable,
wifi_pkt_rx_ctrl_t,
wifi_scan_channel_bitmap_t,
WIFI_PROTOCOL_11AX,
WIFI_PROTOCOL_11B,
WIFI_PROTOCOL_11G,
WIFI_PROTOCOL_11N,
WIFI_PROTOCOL_LR,
};
#[cfg(feature = "sniffer")]
use esp_wifi_sys::include::{
esp_wifi_80211_tx,
esp_wifi_set_promiscuous,
esp_wifi_set_promiscuous_rx_cb,
wifi_promiscuous_pkt_t,
wifi_promiscuous_pkt_type_t,
};
use num_derive::FromPrimitive;
#[doc(hidden)]
pub(crate) use os_adapter::*;
#[cfg(feature = "sniffer")]
use portable_atomic::AtomicBool;
use portable_atomic::{AtomicUsize, Ordering};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "smoltcp")]
use smoltcp::phy::{Device, DeviceCapabilities, RxToken, TxToken};
pub use state::*;
#[cfg(not(coex))]
use crate::config::PowerSaveMode;
use crate::{
common_adapter::*,
esp_wifi_result,
hal::{
peripheral::{Peripheral, PeripheralRef},
ram,
},
EspWifiController,
};
const ETHERNET_FRAME_HEADER_SIZE: usize = 18;
const MTU: usize = crate::CONFIG.mtu;
#[cfg(feature = "utils")]
pub mod utils;
#[cfg(coex)]
use include::{coex_adapter_funcs_t, coex_pre_init, esp_coex_adapter_register};
#[cfg(all(feature = "csi", esp32c6))]
use crate::binary::include::wifi_csi_acquire_config_t;
#[cfg(feature = "csi")]
pub use crate::binary::include::wifi_csi_info_t;
#[cfg(feature = "csi")]
use crate::binary::include::{
esp_wifi_set_csi,
esp_wifi_set_csi_config,
esp_wifi_set_csi_rx_cb,
wifi_csi_config_t,
};
use crate::binary::{
c_types,
include::{
self,
__BindgenBitfieldUnit,
esp_err_t,
esp_interface_t_ESP_IF_WIFI_AP,
esp_interface_t_ESP_IF_WIFI_STA,
esp_supplicant_deinit,
esp_supplicant_init,
esp_wifi_connect,
esp_wifi_deinit_internal,
esp_wifi_disconnect,
esp_wifi_get_mode,
esp_wifi_init_internal,
esp_wifi_internal_free_rx_buffer,
esp_wifi_internal_reg_rxcb,
esp_wifi_internal_tx,
esp_wifi_scan_start,
esp_wifi_set_config,
esp_wifi_set_country,
esp_wifi_set_mode,
esp_wifi_set_protocol,
esp_wifi_set_tx_done_cb,
esp_wifi_start,
esp_wifi_stop,
g_wifi_default_wpa_crypto_funcs,
wifi_active_scan_time_t,
wifi_ap_config_t,
wifi_auth_mode_t,
wifi_cipher_type_t_WIFI_CIPHER_TYPE_CCMP,
wifi_config_t,
wifi_country_policy_t_WIFI_COUNTRY_POLICY_MANUAL,
wifi_country_t,
wifi_init_config_t,
wifi_interface_t,
wifi_interface_t_WIFI_IF_AP,
wifi_interface_t_WIFI_IF_STA,
wifi_mode_t,
wifi_mode_t_WIFI_MODE_AP,
wifi_mode_t_WIFI_MODE_APSTA,
wifi_mode_t_WIFI_MODE_NULL,
wifi_mode_t_WIFI_MODE_STA,
wifi_osi_funcs_t,
wifi_pmf_config_t,
wifi_scan_config_t,
wifi_scan_threshold_t,
wifi_scan_time_t,
wifi_scan_type_t_WIFI_SCAN_TYPE_ACTIVE,
wifi_scan_type_t_WIFI_SCAN_TYPE_PASSIVE,
wifi_sort_method_t_WIFI_CONNECT_AP_BY_SIGNAL,
wifi_sta_config_t,
wpa_crypto_funcs_t,
ESP_WIFI_OS_ADAPTER_MAGIC,
ESP_WIFI_OS_ADAPTER_VERSION,
WIFI_INIT_CONFIG_MAGIC,
},
};
/// Supported Wi-Fi authentication methods.
#[derive(EnumSetType, Debug, PartialOrd)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[derive(Default)]
#[allow(clippy::upper_case_acronyms)] // FIXME
pub enum AuthMethod {
/// No authentication (open network).
None,
/// Wired Equivalent Privacy (WEP) authentication.
WEP,
/// Wi-Fi Protected Access (WPA) authentication.
WPA,
/// Wi-Fi Protected Access 2 (WPA2) Personal authentication (default).
#[default]
WPA2Personal,
/// WPA/WPA2 Personal authentication (supports both).
WPAWPA2Personal,
/// WPA2 Enterprise authentication.
WPA2Enterprise,
/// WPA3 Personal authentication.
WPA3Personal,
/// WPA2/WPA3 Personal authentication (supports both).
WPA2WPA3Personal,
/// WLAN Authentication and Privacy Infrastructure (WAPI).
WAPIPersonal,
}
/// Supported Wi-Fi protocols.
#[derive(EnumSetType, Debug, PartialOrd)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[derive(Default)]
pub enum Protocol {
/// 802.11b protocol.
P802D11B,
/// 802.11b/g protocol.
P802D11BG,
/// 802.11b/g/n protocol (default).
#[default]
P802D11BGN,
/// 802.11b/g/n long-range (LR) protocol.
P802D11BGNLR,
/// 802.11 long-range (LR) protocol.
P802D11LR,
/// 802.11b/g/n/ax protocol.
P802D11BGNAX,
}
/// Secondary Wi-Fi channels.
#[derive(EnumSetType, Debug, PartialOrd)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[derive(Default)]
pub enum SecondaryChannel {
// TODO: Need to extend that for 5GHz
/// No secondary channel (default).
#[default]
None,
/// Secondary channel is above the primary channel.
Above,
/// Secondary channel is below the primary channel.
Below,
}
/// Information about a detected Wi-Fi access point.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct AccessPointInfo {
/// The SSID of the access point.
pub ssid: heapless::String<32>,
/// The BSSID (MAC address) of the access point.
pub bssid: [u8; 6],
/// The channel the access point is operating on.
pub channel: u8,
/// The secondary channel configuration of the access point.
pub secondary_channel: SecondaryChannel,
/// The signal strength of the access point (RSSI).
pub signal_strength: i8,
/// The set of protocols supported by the access point.
#[cfg_attr(feature = "defmt", defmt(Debug2Format))]
pub protocols: EnumSet<Protocol>,
/// The authentication method used by the access point.
pub auth_method: Option<AuthMethod>,
}
/// Configuration for a Wi-Fi access point.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct AccessPointConfiguration {
/// The SSID of the access point.
pub ssid: heapless::String<32>,
/// Whether the SSID is hidden or visible.
pub ssid_hidden: bool,
/// The channel the access point will operate on.
pub channel: u8,
/// The secondary channel configuration.
pub secondary_channel: Option<u8>,
/// The set of protocols supported by the access point.
#[cfg_attr(feature = "defmt", defmt(Debug2Format))]
pub protocols: EnumSet<Protocol>,
/// The authentication method to be used by the access point.
pub auth_method: AuthMethod,
/// The password for securing the access point (if applicable).
pub password: heapless::String<64>,
/// The maximum number of connections allowed on the access point.
pub max_connections: u16,
}
impl Default for AccessPointConfiguration {
fn default() -> Self {
Self {
ssid: unwrap!("iot-device".try_into()),
ssid_hidden: false,
channel: 1,
secondary_channel: None,
protocols: Protocol::P802D11B | Protocol::P802D11BG | Protocol::P802D11BGN,
auth_method: AuthMethod::None,
password: heapless::String::new(),
max_connections: 255,
}
}
}
/// Client configuration for a Wi-Fi connection.
#[derive(Clone, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct ClientConfiguration {
/// The SSID of the Wi-Fi network.
pub ssid: heapless::String<32>,
/// The BSSID (MAC address) of the client.
pub bssid: Option<[u8; 6]>,
// pub protocol: Protocol,
/// The authentication method for the Wi-Fi connection.
pub auth_method: AuthMethod,
/// The password for the Wi-Fi connection.
pub password: heapless::String<64>,
/// The Wi-Fi channel to connect to.
pub channel: Option<u8>,
}
impl Debug for ClientConfiguration {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("ClientConfiguration")
.field("ssid", &self.ssid)
.field("bssid", &self.bssid)
.field("auth_method", &self.auth_method)
.field("channel", &self.channel)
.finish()
}
}
impl Default for ClientConfiguration {
fn default() -> Self {
ClientConfiguration {
ssid: heapless::String::new(),
bssid: None,
auth_method: Default::default(),
password: heapless::String::new(),
channel: None,
}
}
}
#[cfg(feature = "csi")]
pub(crate) trait CsiCallback: FnMut(crate::binary::include::wifi_csi_info_t) {}
#[cfg(feature = "csi")]
impl<T> CsiCallback for T where T: FnMut(crate::binary::include::wifi_csi_info_t) {}
#[cfg(feature = "csi")]
unsafe extern "C" fn csi_rx_cb<C: CsiCallback>(
ctx: *mut crate::wifi::c_types::c_void,
data: *mut crate::binary::include::wifi_csi_info_t,
) {
let csi_callback = unsafe { &mut *(ctx as *mut C) };
csi_callback(*data);
}
#[derive(Clone, PartialEq, Eq)]
// https://github.com/esp-rs/esp-wifi-sys/blob/main/esp-wifi-sys/headers/local/esp_wifi_types_native.h#L94
/// Channel state information(CSI) configuration
#[cfg(all(not(esp32c6), feature = "csi"))]
pub struct CsiConfig {
/// Enable to receive legacy long training field(lltf) data.
pub lltf_en: bool,
/// Enable to receive HT long training field(htltf) data.
pub htltf_en: bool,
/// Enable to receive space time block code HT long training
/// field(stbc-htltf2) data.
pub stbc_htltf2_en: bool,
/// Enable to generate htlft data by averaging lltf and ht_ltf data when
/// receiving HT packet. Otherwise, use ht_ltf data directly.
pub ltf_merge_en: bool,
/// Enable to turn on channel filter to smooth adjacent sub-carrier. Disable
/// it to keep independence of adjacent sub-carrier.
pub channel_filter_en: bool,
/// Manually scale the CSI data by left shifting or automatically scale the
/// CSI data. If set true, please set the shift bits. false: automatically.
/// true: manually.
pub manu_scale: bool,
/// Manually left shift bits of the scale of the CSI data. The range of the
/// left shift bits is 0~15.
pub shift: u8,
/// Enable to dump 802.11 ACK frame.
pub dump_ack_en: bool,
}
#[derive(Clone, PartialEq, Eq)]
#[cfg(all(esp32c6, feature = "csi"))]
// See https://github.com/esp-rs/esp-wifi-sys/blob/2a466d96fe8119d49852fc794aea0216b106ba7b/esp-wifi-sys/src/include/esp32c6.rs#L5702-L5705
pub struct CsiConfig {
/// Enable to acquire CSI.
pub enable: u32,
/// Enable to acquire L-LTF when receiving a 11g PPDU.
pub acquire_csi_legacy: u32,
/// Enable to acquire HT-LTF when receiving an HT20 PPDU.
pub acquire_csi_ht20: u32,
/// Enable to acquire HT-LTF when receiving an HT40 PPDU.
pub acquire_csi_ht40: u32,
/// Enable to acquire HE-LTF when receiving an HE20 SU PPDU.
pub acquire_csi_su: u32,
/// Enable to acquire HE-LTF when receiving an HE20 MU PPDU.
pub acquire_csi_mu: u32,
/// Enable to acquire HE-LTF when receiving an HE20 DCM applied PPDU.
pub acquire_csi_dcm: u32,
/// Enable to acquire HE-LTF when receiving an HE20 Beamformed applied PPDU.
pub acquire_csi_beamformed: u32,
/// Wwhen receiving an STBC applied HE PPDU, 0- acquire the complete
/// HE-LTF1, 1- acquire the complete HE-LTF2, 2- sample evenly among the
/// HE-LTF1 and HE-LTF2.
pub acquire_csi_he_stbc: u32,
/// Vvalue 0-3.
pub val_scale_cfg: u32,
/// Enable to dump 802.11 ACK frame, default disabled.
pub dump_ack_en: u32,
/// Reserved.
pub reserved: u32,
}
#[cfg(feature = "csi")]
impl Default for CsiConfig {
#[cfg(not(esp32c6))]
fn default() -> Self {
Self {
lltf_en: true,
htltf_en: true,
stbc_htltf2_en: true,
ltf_merge_en: true,
channel_filter_en: true,
manu_scale: false,
shift: 0,
dump_ack_en: false,
}
}
#[cfg(esp32c6)]
fn default() -> Self {
// https://github.com/esp-rs/esp-wifi-sys/blob/2a466d96fe8119d49852fc794aea0216b106ba7b/esp-wifi-sys/headers/esp_wifi_he_types.h#L67-L82
Self {
enable: 1,
acquire_csi_legacy: 1,
acquire_csi_ht20: 1,
acquire_csi_ht40: 1,
acquire_csi_su: 1,
acquire_csi_mu: 1,
acquire_csi_dcm: 1,
acquire_csi_beamformed: 1,
acquire_csi_he_stbc: 2,
val_scale_cfg: 2,
dump_ack_en: 1,
reserved: 19,
}
}
}
#[cfg(feature = "csi")]
impl From<CsiConfig> for wifi_csi_config_t {
fn from(config: CsiConfig) -> Self {
#[cfg(not(esp32c6))]
{
wifi_csi_config_t {
lltf_en: config.lltf_en,
htltf_en: config.htltf_en,
stbc_htltf2_en: config.stbc_htltf2_en,
ltf_merge_en: config.ltf_merge_en,
channel_filter_en: config.channel_filter_en,
manu_scale: config.manu_scale,
shift: config.shift,
dump_ack_en: config.dump_ack_en,
}
}
#[cfg(esp32c6)]
{
wifi_csi_acquire_config_t {
_bitfield_align_1: [0; 0],
_bitfield_1: wifi_csi_acquire_config_t::new_bitfield_1(
config.enable,
config.acquire_csi_legacy,
config.acquire_csi_ht20,
config.acquire_csi_ht40,
config.acquire_csi_su,
config.acquire_csi_mu,
config.acquire_csi_dcm,
config.acquire_csi_beamformed,
config.acquire_csi_he_stbc,
config.val_scale_cfg,
config.dump_ack_en,
config.reserved,
),
}
}
}
}
#[cfg(feature = "csi")]
impl CsiConfig {
/// Set CSI data configuration
pub(crate) fn apply_config(&self) -> Result<(), WifiError> {
let conf: wifi_csi_config_t = self.clone().into();
unsafe {
esp_wifi_result!(esp_wifi_set_csi_config(&conf))?;
}
Ok(())
}
/// Register the RX callback function of CSI data. Each time a CSI data is
/// received, the callback function will be called.
pub(crate) fn set_receive_cb<C: CsiCallback>(&mut self, cb: C) -> Result<(), WifiError> {
let cb = alloc::boxed::Box::new(cb);
let cb_ptr = alloc::boxed::Box::into_raw(cb) as *mut crate::wifi::c_types::c_void;
unsafe {
esp_wifi_result!(esp_wifi_set_csi_rx_cb(Some(csi_rx_cb::<C>), cb_ptr))?;
}
Ok(())
}
/// Enable or disable CSI
pub(crate) fn set_csi(&self, enable: bool) -> Result<(), WifiError> {
// https://github.com/esp-rs/esp-wifi-sys/blob/2a466d96fe8119d49852fc794aea0216b106ba7b/esp-wifi-sys/headers/esp_wifi.h#L1241
unsafe {
esp_wifi_result!(esp_wifi_set_csi(enable))?;
}
Ok(())
}
}
/// Configuration for EAP-FAST authentication protocol.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct EapFastConfig {
/// Specifies the provisioning mode for EAP-FAST.
pub fast_provisioning: u8,
/// The maximum length of the PAC (Protected Access Credentials) list.
pub fast_max_pac_list_len: u8,
/// Indicates whether the PAC file is in binary format.
pub fast_pac_format_binary: bool,
}
/// Phase 2 authentication methods
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum TtlsPhase2Method {
/// EAP (Extensible Authentication Protocol).
Eap,
/// MSCHAPv2 (Microsoft Challenge Handshake Authentication Protocol 2).
Mschapv2,
/// MSCHAP (Microsoft Challenge Handshake Authentication Protocol).
Mschap,
/// PAP (Password Authentication Protocol).
Pap,
/// CHAP (Challenge Handshake Authentication Protocol).
Chap,
}
impl TtlsPhase2Method {
/// Maps the phase 2 method to a raw `u32` representation.
fn to_raw(&self) -> u32 {
match self {
TtlsPhase2Method::Eap => {
esp_wifi_sys::include::esp_eap_ttls_phase2_types_ESP_EAP_TTLS_PHASE2_EAP
}
TtlsPhase2Method::Mschapv2 => {
esp_wifi_sys::include::esp_eap_ttls_phase2_types_ESP_EAP_TTLS_PHASE2_MSCHAPV2
}
TtlsPhase2Method::Mschap => {
esp_wifi_sys::include::esp_eap_ttls_phase2_types_ESP_EAP_TTLS_PHASE2_MSCHAP
}
TtlsPhase2Method::Pap => {
esp_wifi_sys::include::esp_eap_ttls_phase2_types_ESP_EAP_TTLS_PHASE2_PAP
}
TtlsPhase2Method::Chap => {
esp_wifi_sys::include::esp_eap_ttls_phase2_types_ESP_EAP_TTLS_PHASE2_CHAP
}
}
}
}
/// Configuration for an EAP (Extensible Authentication Protocol) client.
#[derive(Clone, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct EapClientConfiguration {
/// The SSID of the network the client is connecting to.
pub ssid: heapless::String<32>,
/// The BSSID (MAC Address) of the specific access point.
pub bssid: Option<[u8; 6]>,
// pub protocol: Protocol,
/// The authentication method used for EAP.
pub auth_method: AuthMethod,
/// The identity used during authentication.
pub identity: Option<heapless::String<128>>,
/// The username used for inner authentication.
/// Some EAP methods require a username for authentication.
pub username: Option<heapless::String<128>>,
/// The password used for inner authentication.
pub password: Option<heapless::String<64>>,
/// A new password to be set during the authentication process.
/// Some methods support password changes during authentication.
pub new_password: Option<heapless::String<64>>,
/// Configuration for EAP-FAST.
pub eap_fast_config: Option<EapFastConfig>,
/// A PAC (Protected Access Credential) file for EAP-FAST.
pub pac_file: Option<&'static [u8]>,
/// A boolean flag indicating whether time checking is enforced during
/// authentication.
pub time_check: bool,
/// A CA (Certificate Authority) certificate for validating the
/// authentication server's certificate.
pub ca_cert: Option<&'static [u8]>,
/// A tuple containing the client's certificate, private key, and an
/// intermediate certificate.
#[allow(clippy::type_complexity)]
pub certificate_and_key: Option<(&'static [u8], &'static [u8], Option<&'static [u8]>)>,
/// The Phase 2 authentication method used for EAP-TTLS.
pub ttls_phase2_method: Option<TtlsPhase2Method>,
/// The specific Wi-Fi channel to use for the connection.
pub channel: Option<u8>,
}
impl Debug for EapClientConfiguration {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("EapClientConfiguration")
.field("ssid", &self.ssid)
.field("bssid", &self.bssid)
.field("auth_method", &self.auth_method)
.field("channel", &self.channel)
.field("identity", &self.identity)
.field("username", &self.username)
.field("eap_fast_config", &self.eap_fast_config)
.field("time_check", &self.time_check)
.field("pac_file set", &self.pac_file.is_some())
.field("ca_cert set", &self.ca_cert.is_some())
.field(
"certificate_and_key set",
&self.certificate_and_key.is_some(),
)
.field("ttls_phase2_method", &self.ttls_phase2_method)
.finish()
}
}
impl Default for EapClientConfiguration {
fn default() -> Self {
EapClientConfiguration {
ssid: heapless::String::new(),
bssid: None,
auth_method: AuthMethod::WPA2Enterprise,
identity: None,
username: None,
password: None,
channel: None,
eap_fast_config: None,
time_check: false,
new_password: None,
pac_file: None,
ca_cert: None,
certificate_and_key: None,
ttls_phase2_method: None,
}
}
}
/// Introduces Wi-Fi configuration options.
#[derive(EnumSetType, Debug, PartialOrd)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum Capability {
/// The device operates as a client, connecting to an existing network.
Client,
/// The device operates as an access point, allowing other devices to
/// connect to it.
AccessPoint,
/// The device can operate in both client and access point modes
/// simultaneously.
Mixed,
}
/// Configuration of Wi-Fi operation mode.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[derive(Default)]
#[allow(clippy::large_enum_variant)]
pub enum Configuration {
/// No configuration (default).
#[default]
None,
/// Client-only configuration.
Client(ClientConfiguration),
/// Access point-only configuration.
AccessPoint(AccessPointConfiguration),
/// Simultaneous client and access point configuration.
Mixed(ClientConfiguration, AccessPointConfiguration),
/// EAP client configuration for enterprise Wi-Fi.
#[cfg_attr(feature = "serde", serde(skip))]
EapClient(EapClientConfiguration),
}
impl Configuration {
/// Returns a reference to the client configuration if available.
pub fn as_client_conf_ref(&self) -> Option<&ClientConfiguration> {
match self {
Self::Client(client_conf) | Self::Mixed(client_conf, _) => Some(client_conf),
_ => None,
}
}
/// Returns a reference to the access point configuration if available.
pub fn as_ap_conf_ref(&self) -> Option<&AccessPointConfiguration> {
match self {
Self::AccessPoint(ap_conf) | Self::Mixed(_, ap_conf) => Some(ap_conf),
_ => None,
}
}
/// Returns a mutable reference to the client configuration, creating it if
/// necessary.
pub fn as_client_conf_mut(&mut self) -> &mut ClientConfiguration {
match self {
Self::Client(client_conf) => client_conf,
Self::Mixed(_, _) => {
let prev = mem::replace(self, Self::None);
match prev {
Self::Mixed(client_conf, _) => {
*self = Self::Client(client_conf);
self.as_client_conf_mut()
}
_ => unreachable!(),
}
}
_ => {
*self = Self::Client(Default::default());
self.as_client_conf_mut()
}
}
}
/// Returns a mutable reference to the access point configuration, creating
/// it if necessary.
pub fn as_ap_conf_mut(&mut self) -> &mut AccessPointConfiguration {
match self {
Self::AccessPoint(ap_conf) => ap_conf,
Self::Mixed(_, _) => {
let prev = mem::replace(self, Self::None);
match prev {
Self::Mixed(_, ap_conf) => {
*self = Self::AccessPoint(ap_conf);
self.as_ap_conf_mut()
}
_ => unreachable!(),
}
}
_ => {
*self = Self::AccessPoint(Default::default());
self.as_ap_conf_mut()
}
}
}
/// Retrieves mutable references to both the `ClientConfiguration`
/// and `AccessPointConfiguration`.
pub fn as_mixed_conf_mut(
&mut self,
) -> (&mut ClientConfiguration, &mut AccessPointConfiguration) {
match self {
Self::Mixed(client_conf, ref mut ap_conf) => (client_conf, ap_conf),
Self::AccessPoint(_) => {
let prev = mem::replace(self, Self::None);
match prev {
Self::AccessPoint(ap_conf) => {
*self = Self::Mixed(Default::default(), ap_conf);
self.as_mixed_conf_mut()
}
_ => unreachable!(),
}
}
Self::Client(_) => {
let prev = mem::replace(self, Self::None);
match prev {
Self::Client(client_conf) => {
*self = Self::Mixed(client_conf, Default::default());
self.as_mixed_conf_mut()
}
_ => unreachable!(),
}
}
_ => {
*self = Self::Mixed(Default::default(), Default::default());
self.as_mixed_conf_mut()
}
}
}
}
trait AuthMethodExt {
fn to_raw(&self) -> wifi_auth_mode_t;
fn from_raw(raw: wifi_auth_mode_t) -> Self;
}
impl AuthMethodExt for AuthMethod {
fn to_raw(&self) -> wifi_auth_mode_t {
match self {
AuthMethod::None => include::wifi_auth_mode_t_WIFI_AUTH_OPEN,
AuthMethod::WEP => include::wifi_auth_mode_t_WIFI_AUTH_WEP,
AuthMethod::WPA => include::wifi_auth_mode_t_WIFI_AUTH_WPA_PSK,
AuthMethod::WPA2Personal => include::wifi_auth_mode_t_WIFI_AUTH_WPA2_PSK,
AuthMethod::WPAWPA2Personal => include::wifi_auth_mode_t_WIFI_AUTH_WPA_WPA2_PSK,
AuthMethod::WPA2Enterprise => include::wifi_auth_mode_t_WIFI_AUTH_WPA2_ENTERPRISE,
AuthMethod::WPA3Personal => include::wifi_auth_mode_t_WIFI_AUTH_WPA3_PSK,
AuthMethod::WPA2WPA3Personal => include::wifi_auth_mode_t_WIFI_AUTH_WPA2_WPA3_PSK,
AuthMethod::WAPIPersonal => include::wifi_auth_mode_t_WIFI_AUTH_WAPI_PSK,
}
}
fn from_raw(raw: wifi_auth_mode_t) -> Self {
match raw {
include::wifi_auth_mode_t_WIFI_AUTH_OPEN => AuthMethod::None,
include::wifi_auth_mode_t_WIFI_AUTH_WEP => AuthMethod::WEP,
include::wifi_auth_mode_t_WIFI_AUTH_WPA_PSK => AuthMethod::WPA,
include::wifi_auth_mode_t_WIFI_AUTH_WPA2_PSK => AuthMethod::WPA2Personal,
include::wifi_auth_mode_t_WIFI_AUTH_WPA_WPA2_PSK => AuthMethod::WPAWPA2Personal,
include::wifi_auth_mode_t_WIFI_AUTH_WPA2_ENTERPRISE => AuthMethod::WPA2Enterprise,
include::wifi_auth_mode_t_WIFI_AUTH_WPA3_PSK => AuthMethod::WPA3Personal,
include::wifi_auth_mode_t_WIFI_AUTH_WPA2_WPA3_PSK => AuthMethod::WPA2WPA3Personal,
include::wifi_auth_mode_t_WIFI_AUTH_WAPI_PSK => AuthMethod::WAPIPersonal,
_ => unreachable!(),
}
}
}
/// Wifi Mode (Sta and/or Ap)
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum WifiMode {
/// Station mode.
Sta,
/// Access Point mode.
Ap,
/// Both Station and Access Point modes.
ApSta,
}
impl WifiMode {
pub(crate) fn current() -> Result<Self, WifiError> {
let mut mode = wifi_mode_t_WIFI_MODE_NULL;
esp_wifi_result!(unsafe { esp_wifi_get_mode(&mut mode) })?;
Self::try_from(mode)
}
/// Returns true if this mode works as a client
pub fn is_sta(&self) -> bool {
match self {
Self::Sta | Self::ApSta => true,
Self::Ap => false,
}
}
/// Returns true if this mode works as an access point
pub fn is_ap(&self) -> bool {
match self {
Self::Sta => false,
Self::Ap | Self::ApSta => true,
}
}
}
impl TryFrom<&Configuration> for WifiMode {
type Error = WifiError;
/// Based on the current `Configuration`, derives a `WifiMode` based on it.
fn try_from(config: &Configuration) -> Result<Self, Self::Error> {
let mode = match config {
Configuration::None => return Err(WifiError::UnknownWifiMode),
Configuration::AccessPoint(_) => Self::Ap,
Configuration::Client(_) => Self::Sta,
Configuration::Mixed(_, _) => Self::ApSta,
Configuration::EapClient(_) => Self::Sta,
};
Ok(mode)
}
}
impl TryFrom<wifi_mode_t> for WifiMode {
type Error = WifiError;
/// Converts a `wifi_mode_t` C-type into a `WifiMode`.
fn try_from(value: wifi_mode_t) -> Result<Self, Self::Error> {
#[allow(non_upper_case_globals)]
match value {
include::wifi_mode_t_WIFI_MODE_STA => Ok(Self::Sta),
include::wifi_mode_t_WIFI_MODE_AP => Ok(Self::Ap),
include::wifi_mode_t_WIFI_MODE_APSTA => Ok(Self::ApSta),
_ => Err(WifiError::UnknownWifiMode),
}
}
}
impl From<WifiMode> for wifi_mode_t {
fn from(val: WifiMode) -> Self {
#[allow(non_upper_case_globals)]
match val {
WifiMode::Sta => wifi_mode_t_WIFI_MODE_STA,
WifiMode::Ap => wifi_mode_t_WIFI_MODE_AP,
WifiMode::ApSta => wifi_mode_t_WIFI_MODE_APSTA,
}
}
}
const DATA_FRAME_SIZE: usize = MTU + ETHERNET_FRAME_HEADER_SIZE;
const RX_QUEUE_SIZE: usize = crate::CONFIG.rx_queue_size;
const TX_QUEUE_SIZE: usize = crate::CONFIG.tx_queue_size;
pub(crate) static DATA_QUEUE_RX_AP: Locked<VecDeque<EspWifiPacketBuffer>> =
Locked::new(VecDeque::new());
pub(crate) static DATA_QUEUE_RX_STA: Locked<VecDeque<EspWifiPacketBuffer>> =
Locked::new(VecDeque::new());
/// Common errors.
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum WifiError {
/// Wi-Fi module is not initialized or not initialized for `Wi-Fi`
/// operations.
NotInitialized,
/// Internal Wi-Fi error.
InternalError(InternalWifiError),
/// The device disconnected from the network or failed to connect to it.
Disconnected,
/// Unknown Wi-Fi mode (not Sta/Ap/ApSta).
UnknownWifiMode,
/// Unsupported operation or mode.
Unsupported,
}
/// Events generated by the WiFi driver.
#[repr(i32)]
#[derive(Debug, FromPrimitive, EnumSetType)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum WifiEvent {
/// Wi-Fi is ready for operation.
WifiReady = 0,
/// Scan operation has completed.
ScanDone,
/// Station mode started.
StaStart,
/// Station mode stopped.
StaStop,
/// Station connected to a network.
StaConnected,
/// Station disconnected from a network.
StaDisconnected,
/// Station authentication mode changed.
StaAuthmodeChange,