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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
//! WiFi support
use core::marker::PhantomData;
use core::str::Utf8Error;
use core::time::Duration;
use core::{cmp, ffi, fmt};

extern crate alloc;
use alloc::boxed::Box;
use alloc::sync::Arc;

use ::log::*;

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, Protocol, 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)]
    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],
        };

        let mut result = wifi_sta_config_t {
            ssid: [0; 32],
            password: [0; 64],
            scan_method: 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: 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,
            },
            pmf_cfg: wifi_pmf_config_t {
                capable: false,
                required: false,
            },
            ..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_sta_config_t>> for ClientConfiguration {
    fn from(conf: Newtype<wifi_sta_config_t>) -> Self {
        Self {
            ssid: from_cstr(&conf.0.ssid).try_into().unwrap(),
            bssid: if conf.0.bssid_set {
                Some(conf.0.bssid)
            } else {
                None
            },
            auth_method: Option::<AuthMethod>::from(Newtype(conf.0.threshold.authmode)).unwrap(),
            password: from_cstr(&conf.0.password).try_into().unwrap(),
            channel: if conf.0.channel != 0 {
                Some(conf.0.channel)
            } else {
                None
            },
        }
    }
}

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::max(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 {
                from_cstr(&conf.0.ssid).try_into().unwrap()
            } 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: from_cstr(&conf.0.password).try_into().unwrap(),
            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)]
    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, &[u8]) -> 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)]
        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 _,
            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 _,
            //tx_ba_win: WIFI_DEFAULT_TX_BA_WIN 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",
                    not(esp_idf_version_minor = "3"),
                    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 _,
            ..Default::default()
        };
        esp!(unsafe { esp_wifi_init(&cfg) })?;

        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;

        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> {
        debug!("Start requested");

        esp!(unsafe { esp_wifi_start() })?;

        debug!("Starting");

        Ok(())
    }

    /// As per [`crate::sys::esp_wifi_stop`](crate::sys::esp_wifi_stop)
    pub fn stop(&mut self) -> Result<(), EspError> {
        debug!("Stop requested");

        esp!(unsafe { esp_wifi_stop() })?;

        debug!("Stopping");

        Ok(())
    }

    /// As per [`crate::sys::esp_wifi_connect`](crate::sys::esp_wifi_connect)
    pub fn connect(&mut self) -> Result<(), EspError> {
        debug!("Connect requested");

        esp!(unsafe { esp_wifi_connect() })?;

        debug!("Connecting");

        Ok(())
    }

    /// As per [`crate::sys::esp_wifi_disconnect`](crate::sys::esp_wifi_disconnect)
    pub fn disconnect(&mut self) -> Result<(), EspError> {
        debug!("Disconnect requested");

        esp!(unsafe { esp_wifi_disconnect() })?;

        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)]
    /// Returns the <`Configuration`> currently in use
    pub fn get_configuration(&self) -> Result<Configuration, EspError> {
        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!(),
        };

        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> {
        debug!("Setting configuration: {:?}", conf);

        match conf {
            Configuration::None => {
                unsafe {
                    esp!(esp_wifi_set_mode(wifi_mode_t_WIFI_MODE_NULL))?;
                }
                debug!("Wifi mode NULL set");
            }
            Configuration::AccessPoint(ap_conf) => {
                unsafe {
                    esp!(esp_wifi_set_mode(wifi_mode_t_WIFI_MODE_AP))?;
                }
                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))?;
                }
                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))?;
                }
                debug!("Wifi mode APSTA set");

                self.set_sta_conf(client_conf)?;
                self.set_ap_conf(ap_conf)?;
            }
        }

        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> {
        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> {
        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| 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)?;

        self.status.lock().scan = WifiScanStatus::Idle;

        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| 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, &[u8]) -> Result<(), EspError> + Send + 'static,
        T: FnMut(WifiDeviceId, &[u8], bool) + Send + 'static,
    {
        self.internal_set_callbacks(rx_callback, tx_callback)
    }

    /// 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)
    ///
    /// # Safety
    ///
    /// This method - in contrast to method `set_callbacks` - allows the user to pass
    /// non-static callbacks/closures. This enables users to borrow
    /// - in the closure - variables that live on the stack - or more generally - in the same
    /// scope where the service is created.
    ///
    /// HOWEVER: care should be taken NOT to call `core::mem::forget()` on the service,
    /// as that would immediately lead to an UB (crash).
    /// Also note that forgetting the service might happen with `Rc` and `Arc`
    /// when circular references are introduced: https://github.com/rust-lang/rust/issues/24456
    ///
    /// The reason is that the closure is actually sent to a hidden ESP IDF thread.
    /// This means that if the service is forgotten, Rust is free to e.g. unwind the stack
    /// and the closure now owned by this other thread will end up with references to variables that no longer exist.
    ///
    /// The destructor of the service takes care - prior to the service being dropped and e.g.
    /// the stack being unwind - to remove the closure from the hidden thread and destroy it.
    /// Unfortunately, when the service is forgotten, the un-subscription does not happen
    /// and invalid references are left dangling.
    ///
    /// This "local borrowing" will only be possible to express in a safe way once/if `!Leak` types
    /// are introduced to Rust (i.e. the impossibility to "forget" a type and thus not call its destructor).
    pub unsafe fn set_nonstatic_callbacks<R, T>(
        &mut self,
        rx_callback: R,
        tx_callback: T,
    ) -> Result<(), EspError>
    where
        R: FnMut(WifiDeviceId, &[u8]) -> Result<(), EspError> + Send + 'd,
        T: FnMut(WifiDeviceId, &[u8], bool) + Send + 'd,
    {
        self.internal_set_callbacks(rx_callback, tx_callback)
    }

    fn internal_set_callbacks<R, T>(
        &mut self,
        mut rx_callback: R,
        mut tx_callback: T,
    ) -> Result<(), EspError>
    where
        R: FnMut(WifiDeviceId, &[u8]) -> Result<(), EspError> + Send + 'd,
        T: FnMut(WifiDeviceId, &[u8], bool) + Send + 'd,
    {
        let _ = self.disconnect();
        let _ = self.stop();

        #[allow(clippy::type_complexity)]
        let rx_callback: Box<
            Box<dyn FnMut(WifiDeviceId, &[u8]) -> Result<(), EspError> + Send + 'd>,
        > = Box::new(Box::new(move |device_id, data| {
            rx_callback(device_id, data)
        }));

        #[allow(clippy::type_complexity)]
        let tx_callback: Box<Box<dyn FnMut(WifiDeviceId, &[u8], bool) + Send + 'd>> =
            Box::new(Box::new(move |device_id, data, status| {
                tx_callback(device_id, data, status)
            }));

        #[allow(clippy::type_complexity)]
        let rx_callback: Box<
            Box<dyn FnMut(WifiDeviceId, &[u8]) -> Result<(), EspError> + Send + 'static>,
        > = unsafe { core::mem::transmute(rx_callback) };

        #[allow(clippy::type_complexity)]
        let tx_callback: Box<Box<dyn FnMut(WifiDeviceId, &[u8], bool) + Send + 'static>> =
            unsafe { core::mem::transmute(tx_callback) };

        unsafe {
            RX_CALLBACK = Some(rx_callback);
            TX_CALLBACK = Some(tx_callback);

            esp!(esp_wifi_internal_reg_rxcb(
                WifiDeviceId::Ap.into(),
                Some(Self::handle_rx_ap),
            ))?;

            esp!(esp_wifi_internal_reg_rxcb(
                WifiDeviceId::Sta.into(),
                Some(Self::handle_rx_sta),
            ))?;

            esp!(esp_wifi_set_tx_done_cb(Some(Self::handle_tx)))?;
        }

        Ok(())
    }

    /// As per [`crate::sys::esp_wifi_internal_tx`](crate::sys::esp_wifi_internal_tx)
    pub fn send(&mut self, device_id: WifiDeviceId, frame: &[u8]) -> Result<(), EspError> {
        esp!(unsafe {
            esp_wifi_internal_tx(device_id.into(), frame.as_ptr() as *mut _, frame.len() as _)
        })
    }

    /// Get information of AP which the ESP32 station is associated with.
    /// Useful to get the current signal strength of the AP.
    pub fn get_ap_info(&mut self) -> Result<AccessPointInfo, EspError> {
        let mut ap_info_raw: wifi_ap_record_t = wifi_ap_record_t::default();
        // If Sta not connected throws EspError(12303)
        esp!(unsafe { esp_wifi_sta_get_ap_info(&mut ap_info_raw) })?;
        let ap_info: AccessPointInfo = Newtype(&ap_info_raw).try_into().unwrap();

        debug!("AP Info: {:?}", ap_info);
        Ok(ap_info)
    }

    /// Set RSSI threshold below which APP will get an WifiEvent::StaBssRssiLow,
    /// as per [`crate::sys::esp_wifi_set_rssi_threshold`](crate::sys::esp_wifi_set_rssi_threshold)
    /// `rssi_threshold`: threshold value in dbm between -100 to 0
    ///
    /// # 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();
    /// wifi_driver.connect().unwrap();
    ///
    /// let rssi_low = -40;
    /// wifi_driver.driver_mut().set_sta_rssi_low(rssi_low).unwrap();
    ///
    /// // Subscribe to RSSI events.
    /// let rssi_low_signal = Arc::new(channel_bridge::notification::Notification::new());
    /// let _sub = {
    ///     let rssi_low_signal = rssi_low_signal.clone();
    ///     sysloop.subscribe::<WifiEvent>(move |event| {
    ///         if *event == WifiEvent::StaBssRssiLow {
    ///             rssi_low_signal.notify();
    ///         }
    ///     }).unwrap()
    /// };
    ///
    /// rssi_low_signal.wait().await;
    /// // do stuff with the information
    ///
    /// // set_rssi_threshold() has to be called again after every StaBssRssiLow event received.
    /// ```
    pub fn set_rssi_threshold(&mut self, rssi_threshold: i8) -> Result<(), EspError> {
        esp!(unsafe { esp_wifi_set_rssi_threshold(rssi_threshold.into()) })
    }

    /// Returns the MAC address of the interface, as per
    /// [`crate::sys::esp_wifi_get_mac`](crate::sys::esp_wifi_get_mac)
    pub fn get_mac(&self, interface: WifiDeviceId) -> Result<[u8; 6], EspError> {
        let mut mac = [0u8; 6];

        esp!(unsafe { esp_wifi_get_mac(interface.into(), mac.as_mut_ptr() as *mut _) })?;

        Ok(mac)
    }

    /// Seta the MAC address of the interface, as per
    /// [`crate::sys::esp_wifi_set_mac`](crate::sys::esp_wifi_set_mac)
    pub fn set_mac(&mut self, interface: WifiDeviceId, mac: [u8; 6]) -> Result<(), EspError> {
        esp!(unsafe { esp_wifi_set_mac(interface.into(), mac.as_ptr() as *mut _) })
    }

    /// Enable and start WPS
    pub fn start_wps(&mut self, config: &WpsConfig) -> Result<(), EspError> {
        let config = Newtype::<esp_wps_config_t>::try_from(config)?;

        match self.get_configuration()? {
            Configuration::None => esp!(unsafe { esp_wifi_set_mode(wifi_mode_t_WIFI_MODE_STA) })?,
            Configuration::AccessPoint(_) => {
                esp!(unsafe { esp_wifi_set_mode(wifi_mode_t_WIFI_MODE_APSTA) })?
            }
            _ => (),
        }

        esp!(unsafe { esp_wifi_wps_enable(&config.0 as *const _) })?;
        esp!(unsafe { esp_wifi_wps_start(0) })?;

        self.status.lock().wps = None;

        Ok(())
    }

    /// Gets the WPS status as a [`WPS Event`] and disables WPS.
    fn stop_wps(&mut self) -> Result<WpsStatus, EspError> {
        let mut status = self.status.lock();
        if let Some(status) = status.wps.take() {
            esp!(unsafe { esp_wifi_wps_disable() })?;
            Ok(status)
        } else {
            Err(EspError::from_infallible::<ESP_ERR_INVALID_STATE>())
        }
    }

    fn is_wps_finished(&self) -> Result<bool, EspError> {
        Ok(self.status.lock().wps.is_some())
    }

    fn get_sta_conf(&self) -> Result<ClientConfiguration, EspError> {
        let mut wifi_config: wifi_config_t = Default::default();
        esp!(unsafe { esp_wifi_get_config(wifi_interface_t_WIFI_IF_STA, &mut wifi_config) })?;

        let result: ClientConfiguration = unsafe { Newtype(wifi_config.sta).into() };

        debug!("Providing STA configuration: {:?}", &result);

        Ok(result)
    }

    fn set_sta_conf(&mut self, conf: &ClientConfiguration) -> Result<(), EspError> {
        debug!("Checking current STA configuration");
        let current_config = self.get_sta_conf()?;

        if current_config != *conf {
            debug!("Setting STA configuration: {:?}", conf);

            let mut wifi_config = wifi_config_t {
                sta: Newtype::<wifi_sta_config_t>::try_from(conf)?.0,
            };

            esp!(unsafe { esp_wifi_set_config(wifi_interface_t_WIFI_IF_STA, &mut wifi_config) })?;
        } else {
            debug!("Same STA configuration already present");
        }

        debug!("STA configuration done");

        Ok(())
    }

    fn get_ap_conf(&self) -> Result<AccessPointConfiguration, EspError> {
        let mut wifi_config: wifi_config_t = Default::default();
        esp!(unsafe { esp_wifi_get_config(wifi_interface_t_WIFI_IF_AP, &mut wifi_config) })?;

        let result: AccessPointConfiguration = unsafe { Newtype(wifi_config.ap).into() };

        debug!("Providing AP configuration: {:?}", &result);

        Ok(result)
    }

    fn set_ap_conf(&mut self, conf: &AccessPointConfiguration) -> Result<(), EspError> {
        debug!("Checking current AP configuration");
        let current_config = self.get_ap_conf()?;

        if current_config != *conf {
            debug!("Setting AP configuration: {:?}", conf);

            let mut wifi_config = wifi_config_t {
                ap: Newtype::<wifi_ap_config_t>::try_from(conf)?.0,
            };

            esp!(unsafe { esp_wifi_set_config(wifi_interface_t_WIFI_IF_AP, &mut wifi_config) })?;
        } else {
            debug!("Same AP configuration already present");
        }

        debug!("AP configuration done");

        Ok(())
    }

    fn clear_all(&mut self) -> Result<(), EspError> {
        let _ = self.disconnect();
        let _ = self.stop();

        unsafe {
            esp!(esp_wifi_deinit())?;
        }

        unsafe {
            // Callbacks are already deregistered by `esp_wifi_deinit`, just null-ify our own refs
            RX_CALLBACK = None;
            TX_CALLBACK = None;
        }

        debug!("Driver deinitialized");

        Ok(())
    }

    fn get_scan_count(&mut self) -> Result<usize, EspError> {
        let mut found_ap: u16 = 0;
        esp!(unsafe { esp_wifi_scan_get_ap_num(&mut found_ap as *mut _) })?;

        debug!("Found {} access points", found_ap);

        Ok(found_ap as usize)
    }

    fn fetch_scan_result(
        &mut self,
        ap_infos_raw: &mut [wifi_ap_record_t],
    ) -> Result<usize, EspError> {
        debug!("About to get info for found access points");

        let mut ap_count: u16 = ap_infos_raw.len() as u16;

        esp!(unsafe { esp_wifi_scan_get_ap_records(&mut ap_count, ap_infos_raw.as_mut_ptr(),) })?;

        debug!("Got info for {} access points", ap_count);

        Ok(ap_count as usize)
    }

    unsafe extern "C" fn handle_rx_ap(
        buf: *mut ffi::c_void,
        len: u16,
        eb: *mut ffi::c_void,
    ) -> esp_err_t {
        Self::handle_rx(WifiDeviceId::Ap, buf, len, eb)
    }

    unsafe extern "C" fn handle_rx_sta(
        buf: *mut ffi::c_void,
        len: u16,
        eb: *mut ffi::c_void,
    ) -> esp_err_t {
        Self::handle_rx(WifiDeviceId::Sta, buf, len, eb)
    }

    unsafe fn handle_rx(
        device_id: WifiDeviceId,
        buf: *mut ffi::c_void,
        len: u16,
        eb: *mut ffi::c_void,
    ) -> esp_err_t {
        let res = RX_CALLBACK.as_mut().unwrap()(
            device_id,
            core::slice::from_raw_parts(buf as *mut _, len as usize),
        );

        esp_wifi_internal_free_rx_buffer(eb);

        match res {
            Ok(_) => ESP_OK,
            Err(e) => e.code(),
        }
    }

    unsafe extern "C" fn handle_tx(ifidx: u8, data: *mut u8, len: *mut u16, tx_status: bool) {
        TX_CALLBACK.as_mut().unwrap()(
            (ifidx as wifi_interface_t).into(),
            core::slice::from_raw_parts(data as *const _, len as usize),
            tx_status,
        );
    }
}

unsafe impl<'d> Send for WifiDriver<'d> {}

impl<'d> NonBlocking for WifiDriver<'d> {
    fn is_scan_done(&self) -> Result<bool, EspError> {
        WifiDriver::is_scan_done(self)
    }

    fn start_scan(
        &mut self,
        scan_config: &config::ScanConfig,
        blocking: bool,
    ) -> Result<(), EspError> {
        WifiDriver::start_scan(self, scan_config, blocking)
    }

    fn stop_scan(&mut self) -> Result<(), EspError> {
        WifiDriver::stop_scan(self)
    }

    fn get_scan_result_n<const N: usize>(
        &mut self,
    ) -> Result<(heapless::Vec<AccessPointInfo, N>, usize), EspError> {
        WifiDriver::get_scan_result_n(self)
    }

    #[cfg(feature = "alloc")]
    fn get_scan_result(&mut self) -> Result<alloc::vec::Vec<AccessPointInfo>, EspError> {
        WifiDriver::get_scan_result(self)
    }

    fn start_wps(&mut self, config: &WpsConfig) -> Result<(), EspError> {
        WifiDriver::start_wps(self, config)
    }

    fn stop_wps(&mut self) -> Result<WpsStatus, EspError> {
        WifiDriver::stop_wps(self)
    }

    fn is_wps_finished(&self) -> Result<bool, EspError> {
        WifiDriver::is_wps_finished(self)
    }
}

impl<'d> Drop for WifiDriver<'d> {
    fn drop(&mut self) {
        self.clear_all().unwrap();

        debug!("WifiDriver Dropped");
    }
}

impl<'d> Wifi for WifiDriver<'d> {
    type Error = EspError;

    fn get_capabilities(&self) -> Result<EnumSet<Capability>, Self::Error> {
        WifiDriver::get_capabilities(self)
    }

    fn is_started(&self) -> Result<bool, Self::Error> {
        WifiDriver::is_started(self)
    }

    fn is_connected(&self) -> Result<bool, Self::Error> {
        WifiDriver::is_connected(self)
    }

    fn get_configuration(&self) -> Result<Configuration, Self::Error> {
        WifiDriver::get_configuration(self)
    }

    fn set_configuration(&mut self, conf: &Configuration) -> Result<(), Self::Error> {
        WifiDriver::set_configuration(self, conf)
    }

    fn start(&mut self) -> Result<(), Self::Error> {
        WifiDriver::start(self)
    }

    fn stop(&mut self) -> Result<(), Self::Error> {
        WifiDriver::stop(self)
    }

    fn connect(&mut self) -> Result<(), Self::Error> {
        WifiDriver::connect(self)
    }

    fn disconnect(&mut self) -> Result<(), Self::Error> {
        WifiDriver::disconnect(self)
    }

    fn scan_n<const N: usize>(
        &mut self,
    ) -> Result<(heapless::Vec<AccessPointInfo, N>, usize), Self::Error> {
        WifiDriver::scan_n(self)
    }

    #[cfg(feature = "alloc")]
    fn scan(&mut self) -> Result<alloc::vec::Vec<AccessPointInfo>, Self::Error> {
        WifiDriver::scan(self)
    }
}

/// `EspWifi` wraps a `WifiDriver` Data Link layer instance, and binds the OSI
/// Layer 3 (network) facilities of ESP IDF to it. In other words, it connects
/// the ESP IDF AP and STA Netif interfaces to the Wifi driver. This allows users
/// to utilize the Rust STD APIs for working with TCP and UDP sockets.
///
/// This struct should be the default option for a Wifi driver in all use cases
/// but the niche one where bypassing the ESP IDF Netif and lwIP stacks is
/// desirable. E.g., using `smoltcp` or other custom IP stacks on top of the
/// ESP IDF Wifi radio.
#[cfg(esp_idf_comp_esp_netif_enabled)]
pub struct EspWifi<'d> {
    ap_netif: EspNetif,
    sta_netif: EspNetif,
    driver: WifiDriver<'d>,
}

#[cfg(esp_idf_comp_esp_netif_enabled)]
impl<'d> EspWifi<'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::wrap(WifiDriver::new(modem, sysloop, nvs)?)
    }

    #[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::wrap(WifiDriver::new(modem, sysloop)?)
    }

    pub fn wrap(driver: WifiDriver<'d>) -> Result<Self, EspError> {
        Self::wrap_all(
            driver,
            EspNetif::new(NetifStack::Sta)?,
            EspNetif::new(NetifStack::Ap)?,
        )
    }

    pub fn wrap_all(
        driver: WifiDriver<'d>,
        sta_netif: EspNetif,
        ap_netif: EspNetif,
    ) -> Result<Self, EspError> {
        let mut this = Self {
            driver,
            sta_netif,
            ap_netif,
        };

        this.attach_netif()?;

        Ok(this)
    }

    /// Replaces the network interfaces with the given ones. Returns the old ones.
    pub fn swap_netif(
        &mut self,
        sta_netif: EspNetif,
        ap_netif: EspNetif,
    ) -> Result<(EspNetif, EspNetif), EspError> {
        self.detach_netif()?;

        let old_sta = core::mem::replace(&mut self.sta_netif, sta_netif);
        let old_ap = core::mem::replace(&mut self.ap_netif, ap_netif);

        self.attach_netif()?;

        Ok((old_sta, old_ap))
    }

    /// Replaces the STA network interface with the provided one and returns the
    /// existing network interface.
    pub fn swap_netif_sta(&mut self, sta_netif: EspNetif) -> Result<EspNetif, EspError> {
        self.detach_netif()?;

        let old = core::mem::replace(&mut self.sta_netif, sta_netif);

        self.attach_netif()?;

        Ok(old)
    }

    /// Replaces the AP network interface with the provided one and returns the
    /// existing network interface.
    pub fn swap_netif_ap(&mut self, ap_netif: EspNetif) -> Result<EspNetif, EspError> {
        self.detach_netif()?;

        let old = core::mem::replace(&mut self.ap_netif, ap_netif);

        self.attach_netif()?;

        Ok(old)
    }

    /// Returns the underlying [`WifiDriver`]
    pub fn driver(&self) -> &WifiDriver<'d> {
        &self.driver
    }

    /// Returns the underlying [`WifiDriver`], as mutable
    pub fn driver_mut(&mut self) -> &mut WifiDriver<'d> {
        &mut self.driver
    }

    /// Returns the underlying [`EspNetif`] for client mode
    pub fn sta_netif(&self) -> &EspNetif {
        &self.sta_netif
    }

    /// Returns the underlying [`EspNetif`] for client mode, as mutable
    pub fn sta_netif_mut(&mut self) -> &mut EspNetif {
        &mut self.sta_netif
    }

    /// Returns the underlying [`EspNetif`] for AP mode
    pub fn ap_netif(&self) -> &EspNetif {
        &self.ap_netif
    }

    /// Returns the underlying [`EspNetif`] for AP mode, as mutable
    pub fn ap_netif_mut(&mut self) -> &mut EspNetif {
        &mut self.ap_netif
    }

    /// As per [`WifiDriver::get_capabilities()`]
    pub fn get_capabilities(&self) -> Result<EnumSet<Capability>, EspError> {
        self.driver().get_capabilities()
    }

    /// As per [`WifiDriver::is_started()`]
    pub fn is_started(&self) -> Result<bool, EspError> {
        self.driver().is_started()
    }

    /// As per [`WifiDriver::is_connected()`]
    pub fn is_connected(&self) -> Result<bool, EspError> {
        self.driver().is_connected()
    }

    /// Returns `true` when the driver has a connection, it has enabled either
    /// client or AP mode, and either the client or AP network interface is up.
    pub fn is_up(&self) -> Result<bool, EspError> {
        if !self.driver().is_connected()? {
            Ok(false)
        } else {
            let ap_enabled = self.driver().is_ap_enabled()?;
            let sta_enabled = self.driver().is_sta_enabled()?;

            Ok((!ap_enabled || self.ap_netif().is_up()?)
                && (!sta_enabled || self.sta_netif().is_up()?))
        }
    }

    /// As per [`WifiDriver::get_configuration()`]
    pub fn get_configuration(&self) -> Result<Configuration, EspError> {
        self.driver().get_configuration()
    }

    /// As per [`WifiDriver::set_configuration()`]
    pub fn set_configuration(&mut self, conf: &Configuration) -> Result<(), EspError> {
        self.driver_mut().set_configuration(conf)
    }

    /// As per [`WifiDriver::start()`]
    pub fn start(&mut self) -> Result<(), EspError> {
        self.driver_mut().start()
    }

    /// As per [`WifiDriver::stop()`]
    pub fn stop(&mut self) -> Result<(), EspError> {
        self.driver_mut().stop()
    }

    /// As per [`WifiDriver::connect()`]
    pub fn connect(&mut self) -> Result<(), EspError> {
        self.driver_mut().connect()
    }

    /// As per [`WifiDriver::disconnect()`]
    pub fn disconnect(&mut self) -> Result<(), EspError> {
        self.driver_mut().disconnect()
    }

    /// As per [`WifiDriver::is_scan_done()`]
    pub fn is_scan_done(&self) -> Result<bool, EspError> {
        self.driver().is_scan_done()
    }

    /// As per [`WifiDriver::scan_n()`]
    pub fn scan_n<const N: usize>(
        &mut self,
    ) -> Result<(heapless::Vec<AccessPointInfo, N>, usize), EspError> {
        self.driver_mut().scan_n()
    }

    /// As per [`WifiDriver::scan()`]
    #[cfg(feature = "alloc")]
    pub fn scan(&mut self) -> Result<alloc::vec::Vec<AccessPointInfo>, EspError> {
        self.driver_mut().scan()
    }

    /// As per [`WifiDriver::start_scan()`].
    pub fn start_scan(
        &mut self,
        scan_config: &config::ScanConfig,
        blocking: bool,
    ) -> Result<(), EspError> {
        self.driver_mut().start_scan(scan_config, blocking)
    }

    /// As per [`WifiDriver::stop_scan()`].
    pub fn stop_scan(&mut self) -> Result<(), EspError> {
        self.driver_mut().stop_scan()
    }

    /// As per [`WifiDriver::get_scan_result_n()`].
    pub fn get_scan_result_n<const N: usize>(
        &mut self,
    ) -> Result<(heapless::Vec<AccessPointInfo, N>, usize), EspError> {
        self.driver_mut().get_scan_result_n()
    }

    /// As per [`WifiDriver::get_scan_result()`].
    #[cfg(feature = "alloc")]
    pub fn get_scan_result(&mut self) -> Result<alloc::vec::Vec<AccessPointInfo>, EspError> {
        self.driver_mut().get_scan_result()
    }

    /// As per [`WifiDriver::start_wps()`]
    pub fn start_wps(&mut self, config: &WpsConfig) -> Result<(), EspError> {
        self.driver_mut().start_wps(config)
    }

    pub fn stop_wps(&mut self) -> Result<WpsStatus, EspError> {
        self.driver_mut().stop_wps()
    }

    pub fn is_wps_finished(&self) -> Result<bool, EspError> {
        self.driver().is_wps_finished()
    }

    /// As per [`WifiDriver::get_mac()`].
    pub fn get_mac(&self, interface: WifiDeviceId) -> Result<[u8; 6], EspError> {
        self.driver().get_mac(interface)
    }

    /// As per [`WifiDriver::set_mac()`].
    pub fn set_mac(&mut self, interface: WifiDeviceId, mac: [u8; 6]) -> Result<(), EspError> {
        self.driver_mut().set_mac(interface, mac)
    }

    fn attach_netif(&mut self) -> Result<(), EspError> {
        let _ = self.driver.stop();

        esp!(unsafe { esp_netif_attach_wifi_ap(self.ap_netif.handle()) })?;
        esp!(unsafe { esp_wifi_set_default_wifi_ap_handlers() })?;

        esp!(unsafe { esp_netif_attach_wifi_station(self.sta_netif.handle()) })?;
        esp!(unsafe { esp_wifi_set_default_wifi_sta_handlers() })?;

        Ok(())
    }

    fn detach_netif(&mut self) -> Result<(), EspError> {
        let _ = self.driver.stop();

        esp!(unsafe {
            esp_wifi_clear_default_wifi_driver_and_handlers(
                self.ap_netif.handle() as *mut ffi::c_void
            )
        })?;

        esp!(unsafe {
            esp_wifi_clear_default_wifi_driver_and_handlers(
                self.sta_netif.handle() as *mut ffi::c_void
            )
        })?;

        Ok(())
    }
}

#[cfg(esp_idf_comp_esp_netif_enabled)]
impl<'d> Drop for EspWifi<'d> {
    fn drop(&mut self) {
        self.detach_netif().unwrap();

        info!("EspWifi dropped");
    }
}

#[cfg(esp_idf_comp_esp_netif_enabled)]
unsafe impl<'d> Send for EspWifi<'d> {}

#[cfg(esp_idf_comp_esp_netif_enabled)]
impl<'d> NonBlocking for EspWifi<'d> {
    fn is_scan_done(&self) -> Result<bool, EspError> {
        EspWifi::is_scan_done(self)
    }

    fn start_scan(
        &mut self,
        scan_config: &config::ScanConfig,
        blocking: bool,
    ) -> Result<(), EspError> {
        EspWifi::start_scan(self, scan_config, blocking)
    }

    fn stop_scan(&mut self) -> Result<(), EspError> {
        EspWifi::stop_scan(self)
    }

    fn get_scan_result_n<const N: usize>(
        &mut self,
    ) -> Result<(heapless::Vec<AccessPointInfo, N>, usize), EspError> {
        EspWifi::get_scan_result_n(self)
    }

    #[cfg(feature = "alloc")]
    fn get_scan_result(&mut self) -> Result<alloc::vec::Vec<AccessPointInfo>, EspError> {
        EspWifi::get_scan_result(self)
    }

    fn start_wps(&mut self, config: &WpsConfig) -> Result<(), EspError> {
        EspWifi::start_wps(self, config)
    }

    fn stop_wps(&mut self) -> Result<WpsStatus, EspError> {
        EspWifi::stop_wps(self)
    }

    fn is_wps_finished(&self) -> Result<bool, EspError> {
        EspWifi::is_wps_finished(self)
    }
}

#[cfg(esp_idf_comp_esp_netif_enabled)]
impl<'d> Wifi for EspWifi<'d> {
    type Error = EspError;

    fn get_capabilities(&self) -> Result<EnumSet<Capability>, Self::Error> {
        EspWifi::get_capabilities(self)
    }

    fn is_started(&self) -> Result<bool, Self::Error> {
        EspWifi::is_started(self)
    }

    fn is_connected(&self) -> Result<bool, Self::Error> {
        EspWifi::is_connected(self)
    }

    fn get_configuration(&self) -> Result<Configuration, Self::Error> {
        EspWifi::get_configuration(self)
    }

    fn set_configuration(&mut self, conf: &Configuration) -> Result<(), Self::Error> {
        EspWifi::set_configuration(self, conf)
    }

    fn start(&mut self) -> Result<(), Self::Error> {
        EspWifi::start(self)
    }

    fn stop(&mut self) -> Result<(), Self::Error> {
        EspWifi::stop(self)
    }

    fn connect(&mut self) -> Result<(), Self::Error> {
        EspWifi::connect(self)
    }

    fn disconnect(&mut self) -> Result<(), Self::Error> {
        EspWifi::disconnect(self)
    }

    fn scan_n<const N: usize>(
        &mut self,
    ) -> Result<(heapless::Vec<AccessPointInfo, N>, usize), Self::Error> {
        EspWifi::scan_n(self)
    }

    fn scan(&mut self) -> Result<alloc::vec::Vec<AccessPointInfo>, Self::Error> {
        EspWifi::scan(self)
    }
}

#[cfg(esp_idf_comp_esp_netif_enabled)]
impl<'d> NetifStatus for EspWifi<'d> {
    fn is_up(&self) -> Result<bool, EspError> {
        EspWifi::is_up(self)
    }
}

#[derive(Copy, Clone)]
#[repr(transparent)]
pub struct WpsCredentialsRef(wifi_event_sta_wps_er_success_t__bindgen_ty_1);

#[cfg(not(any(
    esp_idf_version_major = "4",
    all(
        esp_idf_version_major = "5",
        any(esp_idf_version_minor = "0", esp_idf_version_minor = "1")
    ),
)))]
#[derive(Copy, Clone, Debug)]
#[repr(C)]
pub struct HomeChannelChange {
    old_chan: u8,
    old_snd: WifiSecondChan,
    new_chan: u8,
    new_snd: WifiSecondChan,
}

#[cfg(not(any(
    esp_idf_version_major = "4",
    all(
        esp_idf_version_major = "5",
        any(esp_idf_version_minor = "0", esp_idf_version_minor = "1")
    ),
)))]
#[derive(Copy, Clone, Debug)]
enum WifiSecondChan {
    None = 0,
    Above,
    Below,
}

#[cfg(not(any(
    esp_idf_version_major = "4",
    all(
        esp_idf_version_major = "5",
        any(esp_idf_version_minor = "0", esp_idf_version_minor = "1")
    ),
)))]
impl TryFrom<u32> for WifiSecondChan {
    type Error = &'static str;

    fn try_from(value: u32) -> Result<Self, Self::Error> {
        #![allow(non_upper_case_globals)]
        match value {
            wifi_second_chan_t_WIFI_SECOND_CHAN_NONE => Ok(Self::None),
            wifi_second_chan_t_WIFI_SECOND_CHAN_ABOVE => Ok(Self::Above),
            wifi_second_chan_t_WIFI_SECOND_CHAN_BELOW => Ok(Self::Below),
            _ => Err("Invalid"),
        }
    }
}

impl WpsCredentialsRef {
    pub fn ssid(&self) -> &CStr {
        unsafe { CStr::from_ptr(self.0.ssid.as_ptr() as *const _) }
    }

    pub fn passphrase(&self) -> &CStr {
        unsafe { CStr::from_ptr(self.0.passphrase.as_ptr() as *const _) }
    }
}

impl fmt::Debug for WpsCredentialsRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WpsCredentialsRef")
            .field("ssid", &self.ssid())
            .finish()
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WpsCredentials {
    pub ssid: heapless::String<32>,
    pub passphrase: heapless::String<64>,
}

impl TryFrom<&WpsCredentialsRef> for WpsCredentials {
    type Error = EspError;

    fn try_from(credentials: &WpsCredentialsRef) -> Result<Self, Self::Error> {
        let err = EspError::from_infallible::<ESP_ERR_INVALID_ARG>();

        Ok(Self {
            ssid: credentials
                .ssid()
                .to_str()
                .map_err(|_| err)
                .and_then(|credentials| credentials.try_into().map_err(|_| err))?,
            passphrase: credentials
                .passphrase()
                .to_str()
                .map_err(|_| err)
                .and_then(|credentials| credentials.try_into().map_err(|_| err))?,
        })
    }
}

#[derive(Copy, Clone, Debug)]
pub enum WifiEvent<'a> {
    Ready,

    ScanDone,

    StaStarted,
    StaStopped,
    StaConnected,
    StaDisconnected,
    StaAuthmodeChanged,
    StaBssRssiLow,
    StaBeaconTimeout,
    StaWpsSuccess(&'a [WpsCredentialsRef]),
    StaWpsFailed,
    StaWpsTimeout,
    StaWpsPin(Option<u32>),
    StaWpsPbcOverlap,

    ApStarted,
    ApStopped,
    ApStaConnected,
    ApStaDisconnected,
    ApProbeRequestReceived,

    FtmReport,
    ActionTxStatus,
    RocDone,

    #[cfg(not(any(
        esp_idf_version_major = "4",
        all(
            esp_idf_version_major = "5",
            any(esp_idf_version_minor = "0", esp_idf_version_minor = "1")
        ),
    )))]
    HomeChannelChange(HomeChannelChange),
}

unsafe impl<'a> EspEventSource for WifiEvent<'a> {
    fn source() -> Option<&'static ffi::CStr> {
        Some(unsafe { ffi::CStr::from_ptr(WIFI_EVENT) })
    }
}

impl<'a> EspEventDeserializer for WifiEvent<'a> {
    type Data<'d> = WifiEvent<'d>;

    #[allow(non_upper_case_globals, non_snake_case)]
    fn deserialize<'d>(data: &crate::eventloop::EspEvent<'d>) -> WifiEvent<'d> {
        let event_id = data.event_id as u32;

        match event_id {
            wifi_event_t_WIFI_EVENT_WIFI_READY => WifiEvent::Ready,
            wifi_event_t_WIFI_EVENT_SCAN_DONE => WifiEvent::ScanDone,
            wifi_event_t_WIFI_EVENT_STA_START => WifiEvent::StaStarted,
            wifi_event_t_WIFI_EVENT_STA_STOP => WifiEvent::StaStopped,
            wifi_event_t_WIFI_EVENT_STA_CONNECTED => WifiEvent::StaConnected,
            wifi_event_t_WIFI_EVENT_STA_DISCONNECTED => WifiEvent::StaDisconnected,
            wifi_event_t_WIFI_EVENT_STA_AUTHMODE_CHANGE => WifiEvent::StaAuthmodeChanged,
            wifi_event_t_WIFI_EVENT_STA_WPS_ER_SUCCESS => {
                let payload = unsafe {
                    (data.payload.unwrap() as *const _ as *const wifi_event_sta_wps_er_success_t)
                        .as_ref()
                };

                let credentials = payload
                    .map(|payload| &payload.ap_cred[..payload.ap_cred_cnt as _])
                    .unwrap_or(&[]);

                WifiEvent::StaWpsSuccess(unsafe { core::mem::transmute(credentials) })
            }
            wifi_event_t_WIFI_EVENT_STA_WPS_ER_FAILED => WifiEvent::StaWpsFailed,
            wifi_event_t_WIFI_EVENT_STA_WPS_ER_TIMEOUT => WifiEvent::StaWpsTimeout,
            wifi_event_t_WIFI_EVENT_STA_WPS_ER_PIN => {
                let payload = unsafe {
                    (data.payload.unwrap() as *const _ as *const wifi_event_sta_wps_er_pin_t)
                        .as_ref()
                };
                let pin = payload
                    .and_then(|x| core::str::from_utf8(&x.pin_code).ok())
                    .and_then(|x| x.parse().ok());
                WifiEvent::StaWpsPin(pin)
            }
            wifi_event_t_WIFI_EVENT_STA_WPS_ER_PBC_OVERLAP => WifiEvent::StaWpsPbcOverlap,
            wifi_event_t_WIFI_EVENT_AP_START => WifiEvent::ApStarted,
            wifi_event_t_WIFI_EVENT_AP_STOP => WifiEvent::ApStopped,
            wifi_event_t_WIFI_EVENT_AP_STACONNECTED => WifiEvent::ApStaConnected,
            wifi_event_t_WIFI_EVENT_AP_STADISCONNECTED => WifiEvent::ApStaDisconnected,
            wifi_event_t_WIFI_EVENT_AP_PROBEREQRECVED => WifiEvent::ApProbeRequestReceived,
            wifi_event_t_WIFI_EVENT_FTM_REPORT => WifiEvent::FtmReport,
            wifi_event_t_WIFI_EVENT_STA_BSS_RSSI_LOW => WifiEvent::StaBssRssiLow,
            wifi_event_t_WIFI_EVENT_ACTION_TX_STATUS => WifiEvent::ActionTxStatus,
            wifi_event_t_WIFI_EVENT_STA_BEACON_TIMEOUT => WifiEvent::StaBeaconTimeout,
            wifi_event_t_WIFI_EVENT_ROC_DONE => WifiEvent::RocDone,
            #[cfg(not(any(
                esp_idf_version_major = "4",
                all(
                    esp_idf_version_major = "5",
                    any(esp_idf_version_minor = "0", esp_idf_version_minor = "1")
                ),
            )))]
            wifi_event_t_WIFI_EVENT_HOME_CHANNEL_CHANGE => {
                let payload = unsafe {
                    (data.payload.unwrap() as *const _ as *const wifi_event_home_channel_change_t)
                        .as_ref()
                }
                .unwrap();

                WifiEvent::HomeChannelChange(HomeChannelChange {
                    old_chan: payload.old_chan,
                    old_snd: payload.old_snd.try_into().unwrap(),
                    new_chan: payload.new_chan,
                    new_snd: payload.new_snd.try_into().unwrap(),
                })
            }
            _ => panic!("unknown event ID: {}", event_id),
        }
    }
}

const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
const WPS_TIMEOUT: Duration = Duration::from_secs(120);

/// Wraps a [`WifiDriver`] or [`EspWifi`], and offers strictly synchronous (blocking)
/// function calls for their functionality.
// TODO: add an example about wrapping an existing instance of wifidriver/espwifi,
// as well as using that instance once the BlockingWifi drops it.
pub struct BlockingWifi<T> {
    wifi: T,
    event_loop: crate::eventloop::EspSystemEventLoop,
}

impl<T> BlockingWifi<T>
where
    T: Wifi<Error = EspError> + NonBlocking,
{
    pub fn wrap(wifi: T, event_loop: EspSystemEventLoop) -> Result<Self, EspError> {
        Ok(Self { wifi, event_loop })
    }

    /// Returns the underlying [`WifiDriver`] or [`EspWifi`]
    pub fn wifi(&self) -> &T {
        &self.wifi
    }

    /// Returns the underlying [`WifiDriver`] or [`EspWifi`], as mutable
    pub fn wifi_mut(&mut self) -> &mut T {
        &mut self.wifi
    }

    /// As per [`WifiDriver::get_capabilities()`]
    pub fn get_capabilities(&self) -> Result<EnumSet<Capability>, EspError> {
        self.wifi.get_capabilities()
    }

    /// As per [`WifiDriver::get_configuration()`]
    pub fn get_configuration(&self) -> Result<Configuration, EspError> {
        self.wifi.get_configuration()
    }

    /// As per [`WifiDriver::set_configuration()`]
    pub fn set_configuration(&mut self, conf: &Configuration) -> Result<(), EspError> {
        self.wifi.set_configuration(conf)
    }

    /// As per [`WifiDriver::is_started()`]
    pub fn is_started(&self) -> Result<bool, EspError> {
        self.wifi.is_started()
    }

    /// As per [`WifiDriver::is_connected()`]
    pub fn is_connected(&self) -> Result<bool, EspError> {
        self.wifi.is_connected()
    }

    /// As per [`WifiDriver::start()`], but as a blocking call that returns
    /// once the wifi driver has started.
    pub fn start(&mut self) -> Result<(), EspError> {
        self.wifi.start()?;
        self.wifi_wait_while(|| self.wifi.is_started().map(|s| !s), None)
    }

    /// As per [`WifiDriver::stop()`], but as a blocking call that returns
    /// once the wifi driver has stopped.
    pub fn stop(&mut self) -> Result<(), EspError> {
        self.wifi.stop()?;
        self.wifi_wait_while(|| self.wifi.is_started(), None)
    }

    /// As per [`WifiDriver::connect()`], but as a blocking call that returns
    /// once the wifi driver is connected.
    pub fn connect(&mut self) -> Result<(), EspError> {
        self.wifi.connect()?;
        self.wifi_wait_while(
            || self.wifi.is_connected().map(|s| !s),
            Some(CONNECT_TIMEOUT),
        )
    }

    /// As per [`WifiDriver::disconnect()`], but as a blocking call that returns
    /// once the wifi driver has disconnected.
    pub fn disconnect(&mut self) -> Result<(), EspError> {
        self.wifi.disconnect()?;
        self.wifi_wait_while(|| self.wifi.is_connected(), None)
    }

    /// As per [`WifiDriver::scan_n()`]
    pub fn scan_n<const N: usize>(
        &mut self,
    ) -> Result<(heapless::Vec<AccessPointInfo, N>, usize), EspError> {
        self.wifi.scan_n()
    }

    /// As per [`WifiDriver::scan()`]
    #[cfg(feature = "alloc")]
    pub fn scan(&mut self) -> Result<alloc::vec::Vec<AccessPointInfo>, EspError> {
        self.wifi.scan()
    }

    /// Performs a blocking wait until certain condition provided by the user
    /// in the form of a `matcher` callback becomes false. Most often than not
    /// that condition would be related to the state of the Wifi driver. In
    /// other words, whether the driver is started, stopped, (dis)connected and
    /// so on.
    ///
    /// Note that the waiting is not done internally using busy-looping and/or
    /// timeouts. Rather, the condition (`matcher`) is evaluated initially, and
    /// if it returns `true`, it is re-evaluated each time the ESP IDF C Wifi
    /// driver posts a Wifi event on the system event loop. The reasoning behind
    /// this is that changes to the state of the Wifi driver are always
    /// accompanied by posting Wifi events.
    pub fn wifi_wait_while<F: Fn() -> Result<bool, EspError>>(
        &self,
        matcher: F,
        timeout: Option<Duration>,
    ) -> Result<(), EspError> {
        let wait = Wait::new::<WifiEvent>(&self.event_loop)?;

        wait.wait_while(matcher, timeout)
    }

    /// Start WPS and perform a blocking wait until it connects, fails or times
    /// out. A [`WpsStatus`] is returned that contains the success status of the
    /// WPS connection. When the credentials of only one access point are
    /// received, the WiFi driver configuration will automatically be set to
    /// that access point. If multiple credentials were received, a
    /// `WpsStatus::Success` will be returned with a vector containing those
    /// credentials. The caller must then handle those credentials and set the
    /// configuration manually.
    pub fn start_wps(&mut self, config: &WpsConfig) -> Result<WpsStatus, EspError> {
        self.wifi.start_wps(config)?;
        self.wifi_wait_while(
            || self.wifi.is_wps_finished().map(|x| !x),
            Some(WPS_TIMEOUT),
        )?;
        Ok(self.wifi.stop_wps().unwrap_or(WpsStatus::Timeout))
    }
}

#[cfg(esp_idf_comp_esp_netif_enabled)]
impl<T> BlockingWifi<T>
where
    T: NetifStatus,
{
    /// As per [`EspWifi::is_up()`].
    pub fn is_up(&self) -> Result<bool, EspError> {
        self.wifi.is_up()
    }

    /// Waits until the underlaying network interface is up.
    pub fn wait_netif_up(&self) -> Result<(), EspError> {
        self.ip_wait_while(|| self.wifi.is_up().map(|s| !s), Some(CONNECT_TIMEOUT))
    }

    /// As [`BlockingWifi::wifi_wait_while()`], but for `EspWifi` events
    /// related to the IP layer, instead of `WifiDriver` events on the data link layer.
    pub fn ip_wait_while<F: Fn() -> Result<bool, EspError>>(
        &self,
        matcher: F,
        timeout: Option<core::time::Duration>,
    ) -> Result<(), EspError> {
        let wait = crate::eventloop::Wait::new::<IpEvent>(&self.event_loop)?;

        wait.wait_while(matcher, timeout)
    }
}

impl<T> Wifi for BlockingWifi<T>
where
    T: Wifi<Error = EspError> + NonBlocking,
{
    type Error = EspError;

    fn get_capabilities(&self) -> Result<EnumSet<Capability>, Self::Error> {
        BlockingWifi::get_capabilities(self)
    }

    fn get_configuration(&self) -> Result<Configuration, Self::Error> {
        BlockingWifi::get_configuration(self)
    }

    fn set_configuration(&mut self, conf: &Configuration) -> Result<(), Self::Error> {
        BlockingWifi::set_configuration(self, conf)
    }

    fn is_started(&self) -> Result<bool, Self::Error> {
        BlockingWifi::is_started(self)
    }

    fn is_connected(&self) -> Result<bool, Self::Error> {
        BlockingWifi::is_connected(self)
    }

    fn start(&mut self) -> Result<(), Self::Error> {
        BlockingWifi::start(self)
    }

    fn stop(&mut self) -> Result<(), Self::Error> {
        BlockingWifi::stop(self)
    }

    fn connect(&mut self) -> Result<(), Self::Error> {
        BlockingWifi::connect(self)
    }

    fn disconnect(&mut self) -> Result<(), Self::Error> {
        BlockingWifi::disconnect(self)
    }

    fn scan_n<const N: usize>(
        &mut self,
    ) -> Result<(heapless::Vec<AccessPointInfo, N>, usize), Self::Error> {
        BlockingWifi::scan_n(self)
    }

    #[cfg(feature = "alloc")]
    fn scan(&mut self) -> Result<alloc::vec::Vec<AccessPointInfo>, Self::Error> {
        BlockingWifi::scan(self)
    }
}

#[cfg(esp_idf_comp_esp_netif_enabled)]
impl<T> NetifStatus for BlockingWifi<T>
where
    T: NetifStatus,
{
    fn is_up(&self) -> Result<bool, EspError> {
        BlockingWifi::is_up(self)
    }
}

/// Wraps a [`WifiDriver`] or [`EspWifi`], and offers strictly `async`
/// (non-blocking) function calls for their functionality.
#[cfg(all(feature = "alloc", esp_idf_comp_esp_timer_enabled))]
pub struct AsyncWifi<T> {
    wifi: T,
    event_loop: crate::eventloop::EspSystemEventLoop,
    timer_service: crate::timer::EspTaskTimerService,
}

#[cfg(all(feature = "alloc", esp_idf_comp_esp_timer_enabled))]
impl<T> AsyncWifi<T>
where
    T: Wifi<Error = EspError> + NonBlocking,
{
    pub fn wrap(
        wifi: T,
        event_loop: EspSystemEventLoop,
        timer_service: EspTaskTimerService,
    ) -> Result<Self, EspError> {
        Ok(Self {
            wifi,
            event_loop,
            timer_service,
        })
    }

    /// Returns the underlying [`WifiDriver`] or [`EspWifi`]
    pub fn wifi(&self) -> &T {
        &self.wifi
    }

    /// Returns the underlying [`WifiDriver`] or [`EspWifi`], as mutable
    pub fn wifi_mut(&mut self) -> &mut T {
        &mut self.wifi
    }

    /// As per [`WifiDriver::get_capabilities()`]
    pub fn get_capabilities(&self) -> Result<EnumSet<Capability>, EspError> {
        self.wifi.get_capabilities()
    }

    /// As per [`WifiDriver::get_configuration()`]
    pub fn get_configuration(&self) -> Result<Configuration, EspError> {
        self.wifi.get_configuration()
    }

    /// As per [`WifiDriver::set_configuration()`]
    pub fn set_configuration(&mut self, conf: &Configuration) -> Result<(), EspError> {
        self.wifi.set_configuration(conf)
    }

    /// As per [`WifiDriver::is_started()`]
    pub fn is_started(&self) -> Result<bool, EspError> {
        self.wifi.is_started()
    }

    /// As per [`WifiDriver::is_connected()`]
    pub fn is_connected(&self) -> Result<bool, EspError> {
        self.wifi.is_connected()
    }

    /// As per [`WifiDriver::start()`], but as an async call that awaits until
    /// the wifi driver has started.
    pub async fn start(&mut self) -> Result<(), EspError> {
        self.wifi.start()?;
        self.wifi_wait(|this| this.wifi.is_started().map(|s| !s), None)
            .await
    }

    /// As per [`WifiDriver::stop()`], but as an async call that awaits until
    /// the wifi driver has stopped.
    pub async fn stop(&mut self) -> Result<(), EspError> {
        self.wifi.stop()?;
        self.wifi_wait(|this| this.wifi.is_started(), None).await
    }

    /// As per [`WifiDriver::connect()`], but as an async call that awaits until
    /// the wifi driver has connected.
    pub async fn connect(&mut self) -> Result<(), EspError> {
        self.wifi.connect()?;
        self.wifi_wait(
            |this| this.wifi.is_connected().map(|s| !s),
            Some(CONNECT_TIMEOUT),
        )
        .await
    }

    /// As per [`WifiDriver::disconnect()`], but as an async call that awaits until
    /// the wifi driver has disconnected.
    pub async fn disconnect(&mut self) -> Result<(), EspError> {
        self.wifi.disconnect()?;
        self.wifi_wait(|this| this.wifi.is_connected(), None).await
    }

    /// As per [`WifiDriver::start_scan()`] plus [`WifiDriver::get_scan_result_n()`],
    /// as an async call that awaits until the scan is complete.
    pub async fn scan_n<const N: usize>(
        &mut self,
    ) -> Result<(heapless::Vec<AccessPointInfo, N>, usize), EspError> {
        self.wifi.start_scan(&Default::default(), false)?;

        self.wifi_wait(|this| this.wifi.is_scan_done().map(|s| !s), None)
            .await?;

        self.wifi.get_scan_result_n()
    }

    /// As per [`WifiDriver::start_scan()`] plus [`WifiDriver::get_scan_result()`],
    /// as an async call that awaits until the scan is complete.
    #[cfg(feature = "alloc")]
    pub async fn scan(&mut self) -> Result<alloc::vec::Vec<AccessPointInfo>, EspError> {
        self.wifi.start_scan(&Default::default(), false)?;

        self.wifi_wait(|this| this.wifi.is_scan_done().map(|s| !s), None)
            .await?;

        self.wifi.get_scan_result()
    }

    /// Awaits for a certain condition provided by the user in the form of a
    /// `matcher` callback to become false. Most often than not that condition
    /// would be related to the state of the Wifi driver. In other words,
    /// whether the driver is started, stopped, (dis)connected and so on.
    ///
    /// Note that the waiting is not done internally using busy-looping and/or
    /// timeouts. Rather, the condition (`matcher`) is evaluated initially, and
    /// if it returns `true`, it is re-evaluated each time the ESP IDF C Wifi
    /// driver posts a Wifi event on the system event loop. The reasoning behind
    /// this is that changes to the state of the Wifi driver are always
    /// accompanied by posting Wifi events.
    pub async fn wifi_wait<F: FnMut(&mut Self) -> Result<bool, EspError>>(
        &mut self,
        mut matcher: F,
        timeout: Option<Duration>,
    ) -> Result<(), EspError> {
        let mut wait = crate::eventloop::AsyncWait::<WifiEvent, _>::new(
            &self.event_loop,
            &self.timer_service,
        )?;

        wait.wait_while(|| matcher(self), timeout).await
    }

    /// Start WPS and perform a wait asynchronously until it connects, fails or
    /// times out. A [`WpsStatus`] is returned that contains the success status
    /// of the WPS connection. When the credentials of only one access point are
    /// received, the WiFi driver configuration will automatically be set to
    /// that access point. If multiple credentials were received, a
    /// `WpsStatus::Success` will be returned with a vector containing those
    /// credentials. The caller must then handle those credentials and set the
    /// configuration manually.
    pub async fn start_wps(&mut self, config: &WpsConfig<'_>) -> Result<WpsStatus, EspError> {
        self.wifi.start_wps(config)?;
        self.wifi_wait(
            |this| this.wifi.is_wps_finished().map(|x| !x),
            Some(WPS_TIMEOUT),
        )
        .await?;
        Ok(self.wifi.stop_wps().unwrap_or(WpsStatus::Timeout))
    }
}

#[cfg(all(feature = "alloc", esp_idf_comp_esp_timer_enabled))]
#[cfg(esp_idf_comp_esp_netif_enabled)]
impl<T> AsyncWifi<T>
where
    T: NetifStatus,
{
    /// As per [`EspWifi::is_up()`].
    pub fn is_up(&self) -> Result<bool, EspError> {
        self.wifi.is_up()
    }

    /// Waits until the underlaying network interface is up.
    pub async fn wait_netif_up(&mut self) -> Result<(), EspError> {
        self.ip_wait_while(|this| this.wifi.is_up().map(|s| !s), Some(CONNECT_TIMEOUT))
            .await
    }

    /// As [`AsyncWifi::wifi_wait()`], but for `EspWifi` events related to the
    /// IP layer, instead of `WifiDriver` events on the data link layer.
    pub async fn ip_wait_while<F: FnMut(&mut Self) -> Result<bool, EspError>>(
        &mut self,
        mut matcher: F,
        timeout: Option<core::time::Duration>,
    ) -> Result<(), EspError> {
        let mut wait =
            crate::eventloop::AsyncWait::<IpEvent, _>::new(&self.event_loop, &self.timer_service)?;

        wait.wait_while(|| matcher(self), timeout).await
    }
}

#[cfg(all(feature = "alloc", esp_idf_comp_esp_timer_enabled))]
impl<T> embedded_svc::wifi::asynch::Wifi for AsyncWifi<T>
where
    T: Wifi<Error = EspError> + NonBlocking,
{
    type Error = T::Error;

    async fn get_capabilities(&self) -> Result<EnumSet<Capability>, Self::Error> {
        AsyncWifi::get_capabilities(self)
    }

    async fn get_configuration(&self) -> Result<Configuration, Self::Error> {
        AsyncWifi::get_configuration(self)
    }

    async fn set_configuration(&mut self, conf: &Configuration) -> Result<(), Self::Error> {
        AsyncWifi::set_configuration(self, conf)
    }

    async fn start(&mut self) -> Result<(), Self::Error> {
        AsyncWifi::start(self).await
    }

    async fn stop(&mut self) -> Result<(), Self::Error> {
        AsyncWifi::stop(self).await
    }

    async fn connect(&mut self) -> Result<(), Self::Error> {
        AsyncWifi::connect(self).await
    }

    async fn disconnect(&mut self) -> Result<(), Self::Error> {
        AsyncWifi::disconnect(self).await
    }

    async fn is_started(&self) -> Result<bool, Self::Error> {
        AsyncWifi::is_started(self)
    }

    async fn is_connected(&self) -> Result<bool, Self::Error> {
        AsyncWifi::is_connected(self)
    }

    async fn scan_n<const N: usize>(
        &mut self,
    ) -> Result<(heapless::Vec<AccessPointInfo, N>, usize), Self::Error> {
        AsyncWifi::scan_n(self).await
    }

    #[cfg(feature = "alloc")]
    async fn scan(&mut self) -> Result<alloc::vec::Vec<AccessPointInfo>, Self::Error> {
        AsyncWifi::scan(self).await
    }
}

#[cfg(esp_idf_comp_esp_netif_enabled)]
impl<'d> crate::netif::asynch::NetifStatus for EspWifi<'d> {
    async fn is_up(&self) -> Result<bool, EspError> {
        EspWifi::is_up(self)
    }
}

#[cfg(all(feature = "alloc", esp_idf_comp_esp_timer_enabled))]
#[cfg(esp_idf_comp_esp_netif_enabled)]
impl<T> crate::netif::asynch::NetifStatus for AsyncWifi<T>
where
    T: NetifStatus,
{
    async fn is_up(&self) -> Result<bool, EspError> {
        AsyncWifi::is_up(self)
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum WifiStaStatus {
    Stopped,
    Started,
    Connected,
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum WifiApStatus {
    Stopped,
    Started,
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum WifiScanStatus {
    Idle,
    Started,
    Done,
}

#[derive(Debug)]
pub struct WpsConfig<'a> {
    pub wps_type: WpsType,
    pub factory_info: WpsFactoryInfo<'a>,
}

impl TryFrom<&WpsConfig<'_>> for Newtype<esp_wps_config_t> {
    type Error = EspError;

    fn try_from(config: &WpsConfig<'_>) -> Result<Self, Self::Error> {
        let factory_info = Newtype::<wps_factory_information_t>::try_from(&config.factory_info)?.0;
        Ok(Newtype(esp_wps_config_t {
            wps_type: config.wps_type.as_raw_type(),
            factory_info,
            #[cfg(not(esp_idf_version_major = "4"))]
            pin: config.wps_type.as_pin(),
        }))
    }
}

#[derive(Clone, Debug)]
pub struct WpsFactoryInfo<'a> {
    pub manufacturer: &'a str,
    pub model_number: &'a str,
    pub model_name: &'a str,
    pub device_name: &'a str,
}

impl TryFrom<&WpsFactoryInfo<'_>> for Newtype<wps_factory_information_t> {
    type Error = EspError;

    fn try_from(info: &WpsFactoryInfo<'_>) -> Result<Self, Self::Error> {
        let mut result = Newtype(wps_factory_information_t {
            manufacturer: [0; 65],
            model_number: [0; 33],
            model_name: [0; 33],
            device_name: [0; 33],
        });

        set_str(
            c_char_to_u8_slice_mut(&mut result.0.manufacturer),
            info.manufacturer,
        )?;
        set_str(
            c_char_to_u8_slice_mut(&mut result.0.model_number),
            info.model_number,
        )?;
        set_str(
            c_char_to_u8_slice_mut(&mut result.0.model_name),
            info.model_name,
        )?;
        set_str(
            c_char_to_u8_slice_mut(&mut result.0.device_name),
            info.device_name,
        )?;

        Ok(result)
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum WpsType {
    Pbc,
    Pin(u32),
}

impl WpsType {
    fn as_raw_type(&self) -> wps_type_t {
        match self {
            WpsType::Pbc => wps_type_WPS_TYPE_PBC,
            WpsType::Pin(_) => wps_type_WPS_TYPE_PIN,
        }
    }

    #[cfg(not(esp_idf_version_major = "4"))]
    fn as_pin(&self) -> [ffi::c_char; 9] {
        match self {
            WpsType::Pbc => [0; 9],
            WpsType::Pin(pin) => {
                let mut result = [0; 9];
                let mut pin = *pin;
                let mut rem: u32;
                for i in 0..8 {
                    rem = pin % 10;
                    pin /= 10;
                    result[7 - i] = (rem as ffi::c_char) + 48;
                }
                result
            }
        }
    }
}

#[derive(Clone, Debug)]
pub enum WpsStatus {
    SuccessConnected,
    SuccessMultipleAccessPoints(alloc::vec::Vec<WpsCredentials>),
    Failure,
    Timeout,
    Pin(Option<u32>),
    PbcOverlap,
}

impl TryFrom<&WifiEvent<'_>> for WpsStatus {
    type Error = EspError;

    fn try_from(event: &WifiEvent) -> Result<Self, Self::Error> {
        match event {
            WifiEvent::StaWpsSuccess(credentials) => {
                if credentials.is_empty() {
                    Ok(WpsStatus::SuccessConnected)
                } else {
                    Ok(WpsStatus::SuccessMultipleAccessPoints(
                        credentials
                            .iter()
                            .filter_map(|c| c.try_into().ok())
                            .collect::<alloc::vec::Vec<WpsCredentials>>(),
                    ))
                }
            }
            WifiEvent::StaWpsFailed => Ok(WpsStatus::Failure),
            WifiEvent::StaWpsTimeout => Ok(WpsStatus::Timeout),
            WifiEvent::StaWpsPin(pin) => Ok(WpsStatus::Pin(*pin)),
            WifiEvent::StaWpsPbcOverlap => Ok(WpsStatus::PbcOverlap),
            _ => Err(EspError::from_infallible::<ESP_ERR_INVALID_ARG>()),
        }
    }
}