esp-idf-svc 0.52.1

Implementation of the embedded-svc traits for ESP-IDF (Espressif's IoT Development Framework)
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
// TODO:
// - Prio A: Status report (we have driver::role() now; more, e.g. ipv6 notifications?)
// - Prio B: API to enable the Joiner workflow (need to read on that, but not needed for Matter; CONFIG_OPENTHREAD_JOINER - also native OpenThread API https://github.com/espressif/esp-idf/issues/13475)
// - Prio B: API to to enable the Commissioner workflow (need to read on that, but not needed for Matter; CONFIG_OPENTHREAD_COMMISSIONER - also native OpenThread API https://github.com/espressif/esp-idf/issues/13475)

use core::cell::UnsafeCell;
use core::ffi::{self, c_void, CStr};
use core::fmt::Debug;
use core::marker::PhantomData;
use core::ops::{Deref, DerefMut};
use core::ptr::addr_of_mut;

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

#[allow(unused)]
use ::log::{debug, info};

use crate::eventloop::{EspEventDeserializer, EspEventSource, EspSystemEventLoop};
use crate::hal::delay;
use crate::hal::gpio::{InputPin, OutputPin};
use crate::hal::uart::Uart;
#[cfg(all(esp_idf_comp_esp_netif_enabled, not(esp_idf_openthread_radio)))]
use crate::handle::RawHandle;
use crate::io::vfs::MountedEventfs;
#[cfg(all(esp_idf_comp_esp_netif_enabled, not(esp_idf_openthread_radio)))]
use crate::netif::*;
use crate::nvs::EspDefaultNvsPartition;
use crate::private::mutex::{Condvar, Mutex};
use crate::sys::*;
use crate::thread::srp::OtSrp;

pub use srp::*;

extern crate alloc;

mod srp;

/// A trait shared between the `Host` and `RCP` modes providing the option for these
/// to do additional initialization.
pub trait Mode {
    fn init();
}

/// The driver will operate in Radio Co-Processor mode
///
/// The chip needs to be connected via UART or SPI to the host
#[cfg(esp_idf_soc_ieee802154_supported)]
#[derive(Debug)]
pub struct RCP(());

#[cfg(esp_idf_soc_ieee802154_supported)]
impl Mode for RCP {
    fn init() {
        //#[cfg(esp_idf_openthread_ncp_vendor_hook)]
        {
            extern "C" {
                fn otAppNcpInit(instance: *mut otInstance);
            }

            unsafe {
                otAppNcpInit(esp_openthread_get_instance());
            }
        }
    }
}

/// The driver will operate as a host
///
/// This means that - unless the chip has a native Thread suppoort -
/// it needs to be connected via UART or SPI to another chip which does have
/// native Thread support and which is configured to operate in RCP mode
#[derive(Debug)]
pub struct Host(());

impl Mode for Host {
    fn init() {}
}

pub mod config {
    use crate::hal::uart::config::*;
    use crate::hal::units::*;

    /// A safe baud rate for the UART
    #[cfg(all(esp32c2, esp_idf_xtal_freq_26))]
    pub const UART_SAFE_BAUD_RATE: Hertz = Hertz(74880);

    /// A safe baud rate for the UART
    #[cfg(not(all(esp32c2, esp_idf_xtal_freq_26)))]
    pub const UART_SAFE_BAUD_RATE: Hertz = Hertz(115200);

    /// A safe default UART configuration
    pub fn uart_default_cfg() -> Config {
        Config::new()
            .baudrate(UART_SAFE_BAUD_RATE)
            .data_bits(DataBits::DataBits8)
            .parity_none()
            .stop_bits(StopBits::STOP1)
            .flow_control(FlowControl::None)
            .flow_control_rts_threshold(0)
    }
}

macro_rules! ot_esp {
    ($err:expr) => {{
        $crate::sys::esp!($crate::thread::ot_esp_code($err as u32))
    }};
}

pub(crate) use ot_esp;

#[allow(non_upper_case_globals, non_snake_case)]
pub(crate) const fn ot_esp_code(ot_code: u32) -> esp_err_t {
    match ot_code {
        crate::sys::otError_OT_ERROR_NONE => crate::sys::ESP_OK as _,
        crate::sys::otError_OT_ERROR_FAILED => crate::sys::ESP_FAIL as _,
        _ => crate::sys::ESP_FAIL as _, // For now
    }
}

pub(crate) fn ot_esp_err(ot_code: u32) -> EspError {
    EspError::from(ot_esp_code(ot_code)).unwrap()
}

/// Active scan result
pub struct ActiveScanResult<'a>(&'a otActiveScanResult);

impl<'a> ActiveScanResult<'a> {
    /// IEEE 802.15.4 Extended Address
    pub fn extended_address(&self) -> &'a [u8] {
        &self.0.mExtAddress.m8
    }

    /// Thread Network Name
    pub fn network_name_cstr(&self) -> &'a CStr {
        unsafe { ffi::CStr::from_ptr(&self.0.mNetworkName.m8 as *const _ as *const _) }
    }

    /// Thread Extended PAN ID
    pub fn extended_pan_id(&self) -> &[u8] {
        &self.0.mExtendedPanId.m8
    }

    /// Steering Data
    pub fn steering_data(&self) -> &[u8] {
        &self.0.mSteeringData.m8
    }

    /// IEEE 802.15.4 PAN ID
    pub fn pan_id(&self) -> u16 {
        self.0.mPanId
    }

    /// Joiner UDP Port
    pub fn joiner_udp_port(&self) -> u16 {
        self.0.mJoinerUdpPort
    }

    /// IEEE 802.15.4 Channel
    pub fn channel(&self) -> u8 {
        self.0.mChannel
    }

    /// The max RSSI (dBm)
    pub fn max_rssi(&self) -> i8 {
        self.0.mRssi
    }

    /// LQI
    pub fn lqi(&self) -> u8 {
        self.0.mLqi
    }

    /// Version
    pub fn version(&self) -> u8 {
        self.0.mVersion() as _
    }

    /// Native Commissioner
    pub fn native_commissioner(&self) -> bool {
        self.0.mIsNative()
    }

    /// Join permitted
    pub fn join_permitted(&self) -> bool {
        self.0.mIsJoinable()
    }
}

/// Energy scan result
pub struct EnergyScanResult<'a>(&'a otEnergyScanResult);

impl EnergyScanResult<'_> {
    /// IEEE 802.15.4 Channel
    pub fn channel(&self) -> u8 {
        self.0.mChannel
    }

    /// The max RSSI (dBm)
    pub fn max_rssi(&self) -> i8 {
        self.0.mMaxRssi
    }
}

/// The current role of the device in the Thread network
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum Role {
    Disabled,
    Detached,
    Child,
    Router,
    Leader,
}

#[allow(non_upper_case_globals, non_snake_case)]
impl From<otDeviceRole> for Role {
    fn from(role: otDeviceRole) -> Self {
        match role {
            otDeviceRole_OT_DEVICE_ROLE_DISABLED => Role::Disabled,
            otDeviceRole_OT_DEVICE_ROLE_DETACHED => Role::Detached,
            otDeviceRole_OT_DEVICE_ROLE_CHILD => Role::Child,
            otDeviceRole_OT_DEVICE_ROLE_ROUTER => Role::Router,
            otDeviceRole_OT_DEVICE_ROLE_LEADER => Role::Leader,
            _ => Role::Disabled,
        }
    }
}

/// The Ipv6 packet received from Thread via the `ThreadDriver::set_rx_callback` method
pub struct Ipv6Packet<'a>(&'a otMessage);

impl Ipv6Packet<'_> {
    pub fn raw(&self) -> &otMessage {
        self.0
    }

    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> usize {
        unsafe { otMessageGetLength(self.0) as _ }
    }

    pub fn offset(&self) -> usize {
        unsafe { otMessageGetOffset(self.0) as _ }
    }

    pub fn read(&self, offset: usize, buf: &mut [u8]) -> usize {
        let len = self.len();

        unsafe { otMessageRead(self.0, offset as _, buf.as_mut_ptr() as *mut _, len as _) as _ }
    }
}

/// The incoming Ipv6 data received from Thread via the `ThreadDriver::set_rx_callback` method
pub enum Ipv6Incoming<'a> {
    /// A notification that an IPv6 address was added to the device
    AddressAdded(core::net::Ipv6Addr),
    /// A notification that an IPv6 address was removed from the device
    AddressRemoved(core::net::Ipv6Addr),
    /// An incoming raw IPv6 packet
    Data(Ipv6Packet<'a>),
}

/// This struct provides a safe wrapper over the ESP IDF Thread 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 Thread radio.
///
/// For most use cases, utilizing `EspThread` - which provides a networking (IP)
/// layer as well - should be preferred. Using `ThreadDriver` directly is beneficial
/// only when one would like to utilize a custom, non-STD network stack like `smoltcp`.
///
/// The driver can work in two modes:
/// - RCP (Radio Co-Processor) mode: The driver operates as a co-processor to the host,
///   which is expected to be another chip connected to ours via SPI or UART. This is
///   of course only supported with MCUs that do have a Thread radio, like esp32c2 and esp32c6
/// - Host mode: The driver operates as a host, and if the chip does not have a Thread radio
///   it has to be connected via SPI or USB to a chip which runs the Thread stack in RCP mode
pub struct ThreadDriver<'d, T>
where
    T: Mode,
{
    inner: UnsafeCell<Box<ThreadDriverInner>>,
    //_subscription: EspSubscription<'static, System>,
    _nvs: EspDefaultNvsPartition,
    _mounted_event_fs: Arc<MountedEventfs>,
    _mode: T,
    _p: PhantomData<&'d mut ()>,
}

impl<'d> ThreadDriver<'d, Host> {
    /// Create a new Thread Host driver instance utilizing the
    /// native Thread radio on the MCU
    #[cfg(esp_idf_soc_ieee802154_supported)]
    pub fn new<M: crate::hal::modem::ThreadModemPeripheral + 'd>(
        modem: M,
        sysloop: EspSystemEventLoop,
        nvs: EspDefaultNvsPartition,
        mounted_event_fs: Arc<MountedEventfs>,
    ) -> Result<Self, EspError> {
        Self::internal_new(
            Self::host_native_cfg(modem),
            sysloop,
            nvs,
            mounted_event_fs,
            Host(()),
        )
    }

    /// Create a new Thread Host driver instance utilizing an SPI connection
    /// to another MCU running the Thread stack in RCP mode.
    #[cfg(not(esp_idf_version_major = "4"))]
    #[allow(clippy::too_many_arguments)]
    pub fn new_spi<S: crate::hal::spi::Spi + 'd>(
        spi: S,
        mosi: impl InputPin + 'd,
        miso: impl OutputPin + 'd,
        sclk: impl InputPin + OutputPin + 'd,
        cs: Option<impl InputPin + OutputPin + 'd>,
        intr: Option<impl InputPin + OutputPin + 'd>,
        config: &crate::hal::spi::config::Config,
        sysloop: EspSystemEventLoop,
        nvs: EspDefaultNvsPartition,
        mounted_event_fs: Arc<MountedEventfs>,
    ) -> Result<Self, EspError> {
        Self::internal_new(
            Self::host_spi_cfg(spi, mosi, miso, sclk, cs, intr, config),
            sysloop,
            nvs,
            mounted_event_fs,
            Host(()),
        )
    }

    /// Create a new Thread Host driver instance utilizing a UART connection
    /// to another MCU running the Thread stack in RCP mode.
    pub fn new_uart<U: Uart + 'd>(
        uart: U,
        tx: impl OutputPin + 'd,
        rx: impl InputPin + 'd,
        config: &crate::hal::uart::config::Config,
        sysloop: EspSystemEventLoop,
        nvs: EspDefaultNvsPartition,
        mounted_event_fs: Arc<MountedEventfs>,
    ) -> Result<Self, EspError> {
        Self::internal_new(
            Self::host_uart_cfg(uart, tx, rx, config),
            sysloop,
            nvs,
            mounted_event_fs,
            Host(()),
        )
    }

    /// Enable or disable the network interface of the Thread driver
    pub fn enable_ipv6(&self, enable: bool) -> Result<(), EspError> {
        let _lock = self.inner();

        ot_esp!(unsafe { otIp6SetEnabled(esp_openthread_get_instance(), enable) })
    }

    /// Enable or disable Thread
    ///
    /// When enabling, this should be called after the network interface is enabled
    pub fn enable_thread(&self, enable: bool) -> Result<(), EspError> {
        let _lock = self.inner();

        ot_esp!(unsafe { otThreadSetEnabled(esp_openthread_get_instance(), enable) })
    }

    /// Retrieve the current role of the device in the Thread network
    pub fn role(&self) -> Result<Role, EspError> {
        let _lock = self.inner();

        Ok(unsafe { otThreadGetDeviceRole(esp_openthread_get_instance()) }.into())
    }

    /// Initialize the Thread command-line interface (CLI) for debugging purposes.
    ///
    /// NOTE: This function can only be called once.
    #[cfg(esp_idf_openthread_cli)]
    pub fn init_cli(&mut self) -> Result<(), EspError> {
        // TODO: Can only be called once; track this

        unsafe {
            esp_openthread_cli_init();
        }

        #[cfg(esp_idf_openthread_cli_esp_extension)]
        unsafe {
            esp_cli_custom_command_init();
        }

        unsafe {
            esp_openthread_cli_create_task();
        }

        Ok(())
    }

    /// Retrieve the active TOD (Thread Operational Dataset) in the user-supplied buffer
    ///
    /// Return the size of the TOD data written to the buffer
    ///
    /// The TOD is in Thread TLV format.
    pub fn tod(&self, buf: &mut [u8]) -> Result<usize, EspError> {
        let mut inner = self.inner();

        Self::internal_tod(&mut inner, true, buf)
    }

    /// Retrieve the pending TOD (Thread Operational Dataset) in the user-supplied buffer
    ///
    /// Return the size of the TOD data written to the buffer
    ///
    /// The TOD is in Thread TLV format.
    pub fn pending_tod(&self, buf: &mut [u8]) -> Result<usize, EspError> {
        let mut inner = self.inner();

        Self::internal_tod(&mut inner, false, buf)
    }

    /// Set the active TOD (Thread Operational Dataset) to the provided data
    ///
    /// The TOD data should be in Thread TLV format.
    pub fn set_tod(&self, tod: &[u8]) -> Result<(), EspError> {
        let mut inner = self.inner();

        Self::fill_dataset_tlv(&mut inner.dataset_buf, tod)?;

        Self::internal_set_tod(&mut inner, true)
    }

    /// Set the pending TOD (Thread Operational Dataset) to the provided data
    ///
    /// The TOD data should be in Thread TLV format.
    pub fn set_pending_tod(&self, tod: &[u8]) -> Result<(), EspError> {
        let mut inner = self.inner();

        Self::fill_dataset_tlv(&mut inner.dataset_buf, tod)?;

        Self::internal_set_tod(&mut inner, false)
    }

    /// Set the active TOD (Thread Operational Dataset) to the provided data
    ///
    /// The TOD data should be in Thread TLV format.
    pub fn set_tod_hexstr(&self, tod: &str) -> Result<(), EspError> {
        let mut inner = self.inner();

        Self::fill_dataset_tlv_hexstr(&mut inner.dataset_buf, tod)?;

        Self::internal_set_tod(&mut inner, true)
    }

    /// Set the pending TOD (Thread Operational Dataset) to the provided data
    ///
    /// The TOD data should be in Thread TLV format.
    pub fn set_pending_tod_hexstr(&self, tod: &str) -> Result<(), EspError> {
        let mut inner = self.inner();

        Self::fill_dataset_tlv_hexstr(&mut inner.dataset_buf, tod)?;

        Self::internal_set_tod(&mut inner, false)
    }

    /// Set the active TOD (Thread Operational Dataset) according to the
    /// `CONFIG_OPENTHREAD_` TOD-related parameters compiled into the app
    /// during build (via `sdkconfig*`)
    #[cfg(not(esp_idf_version_major = "4"))]
    pub fn set_tod_from_cfg(&self) -> Result<(), EspError> {
        let _lock = self.inner();

        ot_esp!(unsafe { esp_openthread_auto_start(core::ptr::null_mut()) })
    }

    /// Perform an active scan for Thread networks
    ///
    /// The callback will be called for each found network
    /// At the end of the scan, the callback will be called with `None`
    pub fn scan<F: FnMut(Option<ActiveScanResult>) + Send + 'static>(
        &self,
        callback: F,
    ) -> Result<(), EspError> {
        let mut inner = self.inner();

        if inner.scan_cb.is_some() {
            return Err(EspError::from_infallible::<ESP_ERR_INVALID_STATE>());
        }

        #[allow(clippy::type_complexity)]
        let mut callback: Box<Box<dyn FnMut(Option<ActiveScanResult>) + Send + 'static>> =
            Box::new(Box::new(callback));

        ot_esp!(unsafe {
            otLinkActiveScan(
                esp_openthread_get_instance(),
                0xffff_ffffu32, // All channels
                200,            // ms scan per channel
                Some(Self::on_active_scan_result),
                callback.as_mut() as *mut _ as *mut c_void,
            )
        })?;

        inner.scan_cb = Some(callback);

        Ok(())
    }

    /// Check if an active scan is in progress
    pub fn is_scan_in_progress(&self) -> Result<bool, EspError> {
        let _lock = self.inner();

        Ok(unsafe { otLinkIsActiveScanInProgress(esp_openthread_get_instance()) })
    }

    /// Perform an energy scan for Thread networks
    ///
    /// The callback will be called for each found network
    /// At the end of the scan, the callback will be called with `None`
    pub fn energy_scan<F: FnMut(Option<EnergyScanResult>) + Send + 'static>(
        &self,
        callback: F,
    ) -> Result<(), EspError> {
        let mut inner = self.inner();

        if inner.energy_cb.is_some() {
            return Err(EspError::from_infallible::<ESP_ERR_INVALID_STATE>());
        }

        #[allow(clippy::type_complexity)]
        let mut callback: Box<Box<dyn FnMut(Option<EnergyScanResult>) + Send + 'static>> =
            Box::new(Box::new(callback));

        ot_esp!(unsafe {
            otLinkEnergyScan(
                esp_openthread_get_instance(),
                0xffff_ffffu32, // All channels
                200,            // ms scan per channel
                Some(Self::on_energy_scan_result),
                callback.as_mut() as *mut _ as *mut c_void,
            )
        })?;

        inner.energy_cb = Some(callback);

        Ok(())
    }

    /// Check if an energy scan is in progress
    pub fn is_energy_scan_in_progress(&self) -> Result<bool, EspError> {
        let _lock = self.inner();

        Ok(unsafe { otLinkIsEnergyScanInProgress(esp_openthread_get_instance()) })
    }

    /// Send an Ipv6 raw packet over Thread
    pub fn tx(&self, packet: &[u8]) -> Result<(), EspError> {
        let _lock = self.inner();

        let message =
            unsafe { otIp6NewMessage(esp_openthread_get_instance(), core::ptr::null_mut()) };
        if message.is_null() {
            Err(EspError::from_infallible::<ESP_FAIL>())?;
        }

        let result = ot_esp!(unsafe {
            otMessageAppend(message, packet.as_ptr() as *const _, packet.len() as _)
        })
        .and_then(|_| ot_esp!(unsafe { otIp6Send(esp_openthread_get_instance(), message) }));

        unsafe { otMessageFree(message) };

        result
    }

    /// Set a callback function for receiving Ipv6 raw packets from Thread
    pub fn set_rx_callback<R>(&self, callback: Option<R>) -> Result<(), EspError>
    where
        R: FnMut(Ipv6Incoming) + Send + 'static,
    {
        let mut inner = self.inner();

        Self::internal_set_rx_callback(&mut inner, callback)
    }

    /// Set a callback function for receiving Ipv6 raw packets from Thread
    ///
    /// # Safety
    ///
    /// This method - in contrast to method `set_rx_callback` - allows the user to pass
    /// non-static callback/closure. 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 fn set_nonstatic_rx_callback<R>(&self, callback: Option<R>) -> Result<(), EspError>
    where
        R: FnMut(Ipv6Incoming) + Send + 'd,
    {
        let mut inner = self.inner();

        Self::internal_set_rx_callback(&mut inner, callback)
    }

    // NOTE: Methods starting with `internal_` have to be called only when the OpenThread lock is held

    fn internal_set_rx_callback<R>(
        inner: &mut ThreadDriverInner,
        callback: Option<R>,
    ) -> Result<(), EspError>
    where
        R: FnMut(Ipv6Incoming) + Send + 'd,
    {
        if let Some(callback) = callback {
            #[allow(clippy::type_complexity)]
            let callback: Box<Box<dyn FnMut(Ipv6Incoming) + Send + 'd>> =
                Box::new(Box::new(callback));

            #[allow(clippy::type_complexity)]
            let mut callback: Box<Box<dyn FnMut(Ipv6Incoming) + Send + 'static>> =
                unsafe { core::mem::transmute(callback) };

            let callback_ptr = callback.as_mut() as *mut _ as *mut c_void;

            inner.ipv6_cb = Some(callback);

            unsafe {
                otIp6SetAddressCallback(
                    esp_openthread_get_instance(),
                    Some(Self::on_address),
                    callback_ptr,
                );
                otIp6SetReceiveCallback(
                    esp_openthread_get_instance(),
                    Some(Self::on_packet),
                    callback_ptr,
                );
                otIp6SetReceiveFilterEnabled(esp_openthread_get_instance(), true);

                // TODO otIcmp6SetEchoMode(esp_openthread_get_instance(), OT_ICMP6_ECHO_HANDLER_RLOC_ALOC_ONLY);
            }
        } else {
            unsafe {
                otIp6SetAddressCallback(esp_openthread_get_instance(), None, core::ptr::null_mut());
                otIp6SetReceiveCallback(esp_openthread_get_instance(), None, core::ptr::null_mut());
                otIp6SetReceiveFilterEnabled(esp_openthread_get_instance(), true);
                // TODO otIcmp6SetEchoMode(esp_openthread_get_instance(), OT_ICMP6_ECHO_HANDLER_RLOC_ALOC_ONLY);
            }

            inner.ipv6_cb = None;
        }

        Ok(())
    }

    fn internal_tod(
        inner: &mut ThreadDriverInner,
        active: bool,
        buf: &mut [u8],
    ) -> Result<usize, EspError> {
        let dataset_buf = &mut inner.dataset_buf;

        ot_esp!(unsafe {
            if active {
                otDatasetGetActiveTlvs(esp_openthread_get_instance(), dataset_buf)
            } else {
                otDatasetGetPendingTlvs(esp_openthread_get_instance(), dataset_buf)
            }
        })?;

        let len = dataset_buf.mLength as usize;
        if buf.len() < len {
            Err(EspError::from_infallible::<ESP_ERR_INVALID_ARG>())?;
        }

        buf[..len].copy_from_slice(&dataset_buf.mTlvs[..len]);

        Ok(len)
    }

    fn internal_set_tod(inner: &mut ThreadDriverInner, active: bool) -> Result<(), EspError> {
        ot_esp!(unsafe {
            if active {
                otDatasetSetActiveTlvs(esp_openthread_get_instance(), &inner.dataset_buf)
            } else {
                otDatasetSetPendingTlvs(esp_openthread_get_instance(), &inner.dataset_buf)
            }
        })?;

        Ok(())
    }

    fn fill_dataset_tlv(
        dataset_buf: &mut otOperationalDatasetTlvs,
        data: &[u8],
    ) -> Result<(), EspError> {
        if data.len() > core::mem::size_of_val(&dataset_buf.mTlvs) {
            Err(EspError::from_infallible::<ESP_ERR_INVALID_ARG>())?;
        }

        dataset_buf.mLength = data.len() as _;
        dataset_buf.mTlvs[..data.len()].copy_from_slice(data);

        Ok(())
    }

    /// Populates the internal OT TLV dataset structure with the given dataset in HEX-TLV str format.
    fn fill_dataset_tlv_hexstr(
        dataset_buf: &mut otOperationalDatasetTlvs,
        dataset: &str,
    ) -> Result<(), EspError> {
        let dataset = dataset.trim();
        let mut offset = 0;

        for (chf, chs) in dataset
            .chars()
            .step_by(2)
            .zip(dataset.chars().skip(1).step_by(2))
        {
            let byte = (chf
                .to_digit(16)
                .ok_or(ot_esp_err(otError_OT_ERROR_INVALID_ARGS))?
                << 4)
                | chs
                    .to_digit(16)
                    .ok_or(ot_esp_err(otError_OT_ERROR_INVALID_ARGS))?;

            if offset >= dataset_buf.mTlvs.len() {
                Err(ot_esp_err(otError_OT_ERROR_NO_BUFS))?;
            }

            dataset_buf.mTlvs[offset] = byte as _;
            offset += 1;
        }

        dataset_buf.mLength = offset as _;

        Ok(())
    }

    unsafe extern "C" fn on_address(
        address_info: *const otIp6AddressInfo,
        is_added: bool,
        context: *mut c_void,
    ) {
        let inner = unsafe { (context as *mut ThreadDriverInner).as_mut().unwrap() };

        if let Some(ipv6_cb) = inner.ipv6_cb.as_mut() {
            let address_info = unsafe { address_info.as_ref() }.unwrap();
            let ot_address = unsafe { address_info.mAddress.as_ref() }.unwrap();

            let address = core::net::Ipv6Addr::from(ot_address.mFields.m8);

            if is_added {
                ipv6_cb(Ipv6Incoming::AddressAdded(address));
            } else {
                ipv6_cb(Ipv6Incoming::AddressRemoved(address));
            }
        }
    }

    unsafe extern "C" fn on_packet(message: *mut otMessage, context: *mut c_void) {
        let inner = unsafe { (context as *mut ThreadDriverInner).as_mut().unwrap() };

        if let Some(ipv6_cb) = inner.ipv6_cb.as_mut() {
            ipv6_cb(Ipv6Incoming::Data(Ipv6Packet(
                unsafe { message.as_ref() }.unwrap(),
            )));
        }

        otMessageFree(message);
    }

    unsafe extern "C" fn on_active_scan_result(
        result: *mut otActiveScanResult,
        context: *mut c_void,
    ) {
        let inner = unsafe { (context as *mut ThreadDriverInner).as_mut().unwrap() };

        if let Some(scan_cb) = inner.scan_cb.as_mut() {
            if result.is_null() {
                scan_cb(None);
            } else {
                scan_cb(Some(ActiveScanResult(unsafe { result.as_ref() }.unwrap())));
            }
        }

        if result.is_null() {
            inner.scan_cb = None;
        }
    }

    unsafe extern "C" fn on_energy_scan_result(
        result: *mut otEnergyScanResult,
        context: *mut c_void,
    ) {
        let inner = unsafe { (context as *mut ThreadDriverInner).as_mut().unwrap() };

        if let Some(energy_cb) = inner.energy_cb.as_mut() {
            if result.is_null() {
                energy_cb(None);
            } else {
                energy_cb(Some(EnergyScanResult(unsafe { result.as_ref() }.unwrap())));
            }
        }

        if result.is_null() {
            inner.energy_cb = None;
        }
    }

    #[cfg(esp_idf_soc_ieee802154_supported)]
    fn host_native_cfg<M: crate::hal::modem::ThreadModemPeripheral + 'd>(
        _modem: M,
    ) -> esp_openthread_platform_config_t {
        esp_openthread_platform_config_t {
            radio_config: esp_openthread_radio_config_t {
                radio_mode: esp_openthread_radio_mode_t_RADIO_MODE_NATIVE,
                ..Default::default()
            },
            host_config: esp_openthread_host_connection_config_t {
                host_connection_mode:
                    esp_openthread_host_connection_mode_t_HOST_CONNECTION_MODE_NONE,
                ..Default::default()
            },
            port_config: Self::PORT_CONFIG,
        }
    }

    #[cfg(not(esp_idf_version_major = "4"))]
    #[allow(clippy::too_many_arguments)]
    fn host_spi_cfg<S: crate::hal::spi::Spi + 'd>(
        _spi: S,
        mosi: impl InputPin + 'd,
        miso: impl OutputPin + 'd,
        sclk: impl InputPin + OutputPin + 'd,
        cs: Option<impl InputPin + OutputPin + 'd>,
        intr: Option<impl InputPin + OutputPin + 'd>,
        config: &crate::hal::spi::config::Config,
    ) -> esp_openthread_platform_config_t {
        let cs_pin = if let Some(cs) = cs { cs.pin() as _ } else { -1 };

        let intr_pin = if let Some(intr) = intr {
            intr.pin() as _
        } else {
            -1
        };

        let mut icfg: spi_device_interface_config_t = config.into();
        icfg.spics_io_num = cs_pin as _;

        esp_openthread_platform_config_t {
            radio_config: esp_openthread_radio_config_t {
                radio_mode: esp_openthread_radio_mode_t_RADIO_MODE_SPI_RCP,
                __bindgen_anon_1: esp_openthread_radio_config_t__bindgen_ty_1 {
                    radio_spi_config: esp_openthread_spi_host_config_t {
                        host_device: S::device() as _,
                        dma_channel: spi_common_dma_t_SPI_DMA_CH_AUTO,
                        #[cfg(not(esp_idf_version_at_least_6_0_0))]
                        spi_interface: spi_bus_config_t {
                            __bindgen_anon_1: spi_bus_config_t__bindgen_ty_1 {
                                mosi_io_num: mosi.pin() as _,
                            },
                            __bindgen_anon_2: spi_bus_config_t__bindgen_ty_2 {
                                miso_io_num: miso.pin() as _,
                            },
                            sclk_io_num: sclk.pin() as _,
                            ..Default::default()
                        },
                        #[cfg(esp_idf_version_at_least_6_0_0)]
                        spi_interface: spi_bus_config_t {
                            __bindgen_anon_1: spi_bus_config_t__bindgen_ty_1 {
                                __bindgen_anon_1: spi_bus_config_t__bindgen_ty_1__bindgen_ty_1 {
                                    data4_io_num: -1,
                                    data5_io_num: -1,
                                    data6_io_num: -1,
                                    data7_io_num: -1,
                                    __bindgen_anon_1:
                                        spi_bus_config_t__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1 {
                                            mosi_io_num: mosi.pin() as _,
                                        },
                                    __bindgen_anon_2:
                                        spi_bus_config_t__bindgen_ty_1__bindgen_ty_1__bindgen_ty_2 {
                                            miso_io_num: miso.pin() as _,
                                        },
                                    __bindgen_anon_3:
                                        spi_bus_config_t__bindgen_ty_1__bindgen_ty_1__bindgen_ty_3 {
                                            quadwp_io_num: -1,
                                        },
                                    __bindgen_anon_4:
                                        spi_bus_config_t__bindgen_ty_1__bindgen_ty_1__bindgen_ty_4 {
                                            quadhd_io_num: -1,
                                        },
                                    sclk_io_num: sclk.pin() as _,
                                },
                            },
                            ..Default::default()
                        },
                        spi_device: icfg,
                        intr_pin,
                    },
                },
            },
            host_config: esp_openthread_host_connection_config_t {
                host_connection_mode:
                    esp_openthread_host_connection_mode_t_HOST_CONNECTION_MODE_NONE,
                ..Default::default()
            },
            port_config: Self::PORT_CONFIG,
        }
    }

    fn host_uart_cfg<U: Uart + 'd>(
        _uart: U,
        tx: impl OutputPin + 'd,
        rx: impl InputPin + 'd,
        config: &crate::hal::uart::config::Config,
    ) -> esp_openthread_platform_config_t {
        #[cfg(esp_idf_version_major = "4")]
        let cfg = esp_openthread_platform_config_t {
            radio_config: esp_openthread_radio_config_t {
                radio_mode: esp_openthread_radio_mode_t_RADIO_MODE_UART_RCP,
                radio_uart_config: esp_openthread_uart_config_t {
                    port: U::port() as _,
                    uart_config: config.into(),
                    rx_pin: rx.pin() as _,
                    tx_pin: tx.pin() as _,
                },
            },
            host_config: esp_openthread_host_connection_config_t {
                host_connection_mode:
                    esp_openthread_host_connection_mode_t_HOST_CONNECTION_MODE_NONE,
                ..Default::default()
            },
            port_config: Self::PORT_CONFIG,
        };

        #[cfg(not(esp_idf_version_major = "4"))]
        let cfg = esp_openthread_platform_config_t {
            radio_config: esp_openthread_radio_config_t {
                radio_mode: esp_openthread_radio_mode_t_RADIO_MODE_UART_RCP,
                __bindgen_anon_1: esp_openthread_radio_config_t__bindgen_ty_1 {
                    radio_uart_config: esp_openthread_uart_config_t {
                        port: U::port() as _,
                        uart_config: config.into(),
                        rx_pin: rx.pin() as _,
                        tx_pin: tx.pin() as _,
                    },
                },
            },
            host_config: esp_openthread_host_connection_config_t {
                host_connection_mode:
                    esp_openthread_host_connection_mode_t_HOST_CONNECTION_MODE_NONE,
                ..Default::default()
            },
            port_config: Self::PORT_CONFIG,
        };

        cfg
    }
}

#[cfg(esp_idf_soc_ieee802154_supported)]
impl<'d> ThreadDriver<'d, RCP> {
    /// Create a new Thread RCP driver instance utilizing an SPI connection
    /// to another MCU running the Thread Host stack.
    #[cfg(not(esp_idf_version_major = "4"))]
    #[allow(clippy::too_many_arguments)]
    pub fn new_rcp_spi<
        M: crate::hal::modem::ThreadModemPeripheral + 'd,
        S: crate::hal::spi::Spi + 'd,
    >(
        modem: M,
        spi: S,
        mosi: impl InputPin + 'd,
        miso: impl OutputPin + 'd,
        sclk: impl InputPin + OutputPin + 'd,
        cs: Option<impl InputPin + OutputPin + 'd>,
        intr: Option<impl InputPin + OutputPin + 'd>,
        sysloop: EspSystemEventLoop,
        nvs: EspDefaultNvsPartition,
        mounted_event_fs: Arc<MountedEventfs>,
    ) -> Result<Self, EspError> {
        Self::internal_new(
            Self::rcp_spi_cfg(modem, spi, mosi, miso, sclk, cs, intr),
            sysloop,
            nvs,
            mounted_event_fs,
            RCP(()),
        )
    }

    /// Create a new Thread RCP driver instance utilizing a UART connection
    /// to another MCU running the Thread Host stack.
    #[allow(clippy::too_many_arguments)]
    pub fn new_rcp_uart<M: crate::hal::modem::ThreadModemPeripheral + 'd, U: Uart + 'd>(
        modem: M,
        uart: U,
        tx: impl OutputPin + 'd,
        rx: impl InputPin + 'd,
        config: &crate::hal::uart::config::Config,
        sysloop: EspSystemEventLoop,
        nvs: EspDefaultNvsPartition,
        mounted_event_fs: Arc<MountedEventfs>,
    ) -> Result<Self, EspError> {
        Self::internal_new(
            Self::rcp_uart_cfg(modem, uart, tx, rx, config),
            sysloop,
            nvs,
            mounted_event_fs,
            RCP(()),
        )
    }

    #[cfg(not(esp_idf_version_major = "4"))]
    #[allow(clippy::too_many_arguments)]
    fn rcp_spi_cfg<
        M: crate::hal::modem::ThreadModemPeripheral + 'd,
        S: crate::hal::spi::Spi + 'd,
    >(
        _modem: M,
        _spi: S,
        mosi: impl InputPin + 'd,
        miso: impl OutputPin + 'd,
        sclk: impl InputPin + OutputPin + 'd,
        cs: Option<impl InputPin + OutputPin + 'd>,
        intr: Option<impl InputPin + OutputPin + 'd>,
    ) -> esp_openthread_platform_config_t {
        let cs_pin = if let Some(cs) = cs { cs.pin() as _ } else { -1 };

        let intr_pin = if let Some(intr) = intr {
            intr.pin() as _
        } else {
            -1
        };

        esp_openthread_platform_config_t {
            radio_config: esp_openthread_radio_config_t {
                radio_mode: esp_openthread_radio_mode_t_RADIO_MODE_NATIVE,
                ..Default::default()
            },
            host_config: esp_openthread_host_connection_config_t {
                host_connection_mode:
                    esp_openthread_host_connection_mode_t_HOST_CONNECTION_MODE_RCP_UART,
                __bindgen_anon_1: esp_openthread_host_connection_config_t__bindgen_ty_1 {
                    spi_slave_config: esp_openthread_spi_slave_config_t {
                        host_device: S::device() as _,
                        #[cfg(not(esp_idf_version_at_least_6_0_0))]
                        bus_config: spi_bus_config_t {
                            __bindgen_anon_1: spi_bus_config_t__bindgen_ty_1 {
                                mosi_io_num: mosi.pin() as _,
                            },
                            __bindgen_anon_2: spi_bus_config_t__bindgen_ty_2 {
                                miso_io_num: miso.pin() as _,
                            },
                            sclk_io_num: sclk.pin() as _,
                            ..Default::default()
                        },
                        #[cfg(esp_idf_version_at_least_6_0_0)]
                        bus_config: spi_bus_config_t {
                            __bindgen_anon_1: spi_bus_config_t__bindgen_ty_1 {
                                __bindgen_anon_1: spi_bus_config_t__bindgen_ty_1__bindgen_ty_1 {
                                    data4_io_num: -1,
                                    data5_io_num: -1,
                                    data6_io_num: -1,
                                    data7_io_num: -1,
                                    __bindgen_anon_1:
                                        spi_bus_config_t__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1 {
                                            mosi_io_num: mosi.pin() as _,
                                        },
                                    __bindgen_anon_2:
                                        spi_bus_config_t__bindgen_ty_1__bindgen_ty_1__bindgen_ty_2 {
                                            miso_io_num: miso.pin() as _,
                                        },
                                    __bindgen_anon_3:
                                        spi_bus_config_t__bindgen_ty_1__bindgen_ty_1__bindgen_ty_3 {
                                            quadwp_io_num: -1,
                                        },
                                    __bindgen_anon_4:
                                        spi_bus_config_t__bindgen_ty_1__bindgen_ty_1__bindgen_ty_4 {
                                            quadhd_io_num: -1,
                                        },
                                    sclk_io_num: sclk.pin() as _,
                                },
                            },
                            ..Default::default()
                        },
                        slave_config: spi_slave_interface_config_t {
                            spics_io_num: cs_pin as _,
                            ..Default::default()
                        },
                        intr_pin,
                    },
                },
            },
            port_config: Self::PORT_CONFIG,
        }
    }

    fn rcp_uart_cfg<M: crate::hal::modem::ThreadModemPeripheral + 'd, U: Uart + 'd>(
        _modem: M,
        _uart: U,
        tx: impl OutputPin + 'd,
        rx: impl InputPin + 'd,
        config: &crate::hal::uart::config::Config,
    ) -> esp_openthread_platform_config_t {
        #[cfg(esp_idf_version_major = "4")]
        let cfg = esp_openthread_platform_config_t {
            radio_config: esp_openthread_radio_config_t {
                radio_mode: esp_openthread_radio_mode_t_RADIO_MODE_NATIVE,
                ..Default::default()
            },
            host_config: esp_openthread_host_connection_config_t {
                host_connection_mode:
                    esp_openthread_host_connection_mode_t_HOST_CONNECTION_MODE_RCP_UART,
                host_uart_config: esp_openthread_uart_config_t {
                    port: U::port() as _,
                    uart_config: config.into(),
                    rx_pin: rx.pin() as _,
                    tx_pin: tx.pin() as _,
                },
            },
            port_config: Self::PORT_CONFIG,
        };

        #[cfg(not(esp_idf_version_major = "4"))]
        let cfg = esp_openthread_platform_config_t {
            radio_config: esp_openthread_radio_config_t {
                radio_mode: esp_openthread_radio_mode_t_RADIO_MODE_NATIVE,
                ..Default::default()
            },
            host_config: esp_openthread_host_connection_config_t {
                host_connection_mode:
                    esp_openthread_host_connection_mode_t_HOST_CONNECTION_MODE_RCP_UART,
                __bindgen_anon_1: esp_openthread_host_connection_config_t__bindgen_ty_1 {
                    host_uart_config: esp_openthread_uart_config_t {
                        port: U::port() as _,
                        uart_config: config.into(),
                        rx_pin: rx.pin() as _,
                        tx_pin: tx.pin() as _,
                    },
                },
            },
            port_config: Self::PORT_CONFIG,
        };

        cfg
    }
}

impl<T> ThreadDriver<'_, T>
where
    T: Mode,
{
    const PORT_CONFIG: esp_openthread_port_config_t = esp_openthread_port_config_t {
        storage_partition_name: b"nvs\0" as *const _ as *const _,
        netif_queue_size: 10,
        task_queue_size: 10,
    };

    /// Initialize the coexistence between the Thread stack and a Wifi/BT stack on the modem
    #[cfg(all(esp_idf_openthread_radio_native, esp_idf_soc_ieee802154_supported))]
    pub fn init_coex(&mut self) -> Result<(), EspError> {
        let _lock = self.inner();

        Self::internal_init_coex()
    }

    /// Start the Thread driver
    ///
    /// If the driver is already started, an error is returned.
    pub fn start(&mut self) -> Result<(), EspError> {
        {
            let mut inner = self.inner();

            if *inner.started.lock() {
                Err(EspError::from_infallible::<ESP_ERR_INVALID_STATE>())?;
            }

            #[allow(clippy::manual_c_str_literals)]
            unsafe {
                crate::hal::task::create(
                    Self::run,
                    CStr::from_bytes_with_nul_unchecked(b"ThreadDriver Runner\0"),
                    12288,
                    &mut *inner as *mut _ as *mut _,
                    6,
                    None,
                )?;
            }
        }

        loop {
            let inner = unsafe { self.inner.get().as_mut().unwrap() };

            let started = inner.started.lock();

            if *started {
                break;
            }

            inner.started_condvar.wait(started);
        }

        info!("ThreadDriver started");

        Ok(())
    }

    /// Stop the Thread driver
    ///
    /// If the driver is not started, an error is returned.
    pub fn stop(&mut self) -> Result<(), EspError> {
        {
            let inner = self.inner();

            if !*inner.started.lock() {
                Err(EspError::from_infallible::<ESP_ERR_INVALID_STATE>())?;
            }

            #[allow(unused_mut)]
            #[allow(unused_assignments)]
            let mut stop_supported = false;

            #[cfg(any(
                esp_idf_version_at_least_5_5_0,
                all(esp_idf_version = "5.1", esp_idf_version_at_least_5_1_7),
                all(esp_idf_version = "5.2", esp_idf_version_at_least_5_2_6),
                all(esp_idf_version = "5.3", esp_idf_version_at_least_5_3_4),
                all(esp_idf_version = "5.4", esp_idf_version_at_least_5_4_3)
            ))]
            {
                unsafe {
                    esp_openthread_mainloop_exit();
                }

                stop_supported = true;
            }

            if !stop_supported {
                panic!("Stopping the Thread driver is supported since ESP-IDF patch-level 5.3.3+, 5.4.3+ and 5.5.1+. Please update to a newer version or don't call `stop`.")
            }
        }

        loop {
            let inner = unsafe { self.inner.get().as_mut().unwrap() };

            let started = inner.started.lock();

            if !*started {
                break;
            }

            inner.started_condvar.wait(started);
        }

        info!("ThreadDriver stopped");

        Ok(())
    }

    /// Check if the Thread driver is started
    pub fn is_started(&self) -> Result<bool, EspError> {
        let inner = self.inner();

        let started = *inner.started.lock();

        Ok(started)
    }

    /// Return a mutable reference to the inner driver state
    /// by locking the OpenThread lock first.
    #[allow(clippy::mut_from_ref)]
    fn inner(&self) -> ThreadDriverInnerGuard<'_> {
        ThreadDriverInnerGuard {
            inner: unsafe { &mut *self.inner.get() },
            _lock: OtLock::acquire().unwrap(),
        }
    }

    // NOTE: Methods starting with `internal_` have to be called only when the OpenThread lock is held

    #[cfg(all(esp_idf_openthread_radio_native, esp_idf_soc_ieee802154_supported))]
    fn internal_init_coex() -> Result<(), EspError> {
        #[cfg(esp_idf_esp_coex_sw_coexist_enable)]
        {
            esp!(unsafe { esp_coex_wifi_i154_enable() })?;
        }

        Ok(())
    }

    fn internal_new(
        cfg: esp_openthread_platform_config_t,
        _sysloop: EspSystemEventLoop,
        nvs: EspDefaultNvsPartition,
        mounted_event_fs: Arc<MountedEventfs>,
        mode: T,
    ) -> Result<Self, EspError> {
        let mut inner = {
            let mut inner = Box::new_uninit();

            unsafe {
                ThreadDriverInner::init(inner.as_mut_ptr(), cfg);

                inner.assume_init()
            }
        };

        esp!(unsafe { esp_openthread_init(&inner.cfg) })?;

        let instance = unsafe { esp_openthread_get_instance() };

        #[cfg(not(esp_idf_openthread_radio))]
        unsafe {
            otLoggingSetLevel(CONFIG_LOG_DEFAULT_LEVEL as _);
        }

        let srp = &mut inner.srp;

        unsafe {
            crate::sys::otSrpClientSetCallback(
                instance,
                Some(OtSrp::plat_c_srp_state_change_callback),
                srp as *mut _ as *mut _,
            )
        }

        T::init();

        info!("ThreadDriver initialized");

        Ok(Self {
            inner: UnsafeCell::new(inner),
            _nvs: nvs,
            _mounted_event_fs: mounted_event_fs,
            _mode: mode,
            _p: PhantomData,
        })
    }

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

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

        Ok(())
    }

    extern "C" fn run(arg: *mut core::ffi::c_void) {
        {
            let _lock = OtLock::acquire().unwrap();

            let inner = unsafe { (arg as *mut ThreadDriverInner).as_mut().unwrap() };

            *inner.started.lock() = true;
            inner.started_condvar.notify_all();
        }

        unsafe {
            esp_openthread_launch_mainloop();
        }

        {
            let _lock = OtLock::acquire().unwrap();

            let inner = unsafe { (arg as *mut ThreadDriverInner).as_mut().unwrap() };

            *inner.started.lock() = false;
            inner.started_condvar.notify_all();
        }

        unsafe { crate::hal::task::destroy(core::ptr::null_mut()) }
    }
}

impl<T> Drop for ThreadDriver<'_, T>
where
    T: Mode,
{
    fn drop(&mut self) {
        self.internal_deinit().unwrap();
        info!("ThreadDriver deinitialized");
    }
}

unsafe impl<T> Send for ThreadDriver<'_, T> where T: Mode {}
unsafe impl<T> Sync for ThreadDriver<'_, T> where T: Mode {}

struct ThreadDriverInner {
    cfg: esp_openthread_platform_config_t,
    dataset_buf: otOperationalDatasetTlvs,
    srp: OtSrp,
    #[allow(clippy::type_complexity)]
    ipv6_cb: Option<Box<Box<dyn FnMut(Ipv6Incoming) + Send + 'static>>>,
    #[allow(clippy::type_complexity)]
    scan_cb: Option<Box<Box<dyn FnMut(Option<ActiveScanResult>) + Send + 'static>>>,
    #[allow(clippy::type_complexity)]
    energy_cb: Option<Box<Box<dyn FnMut(Option<EnergyScanResult>) + Send + 'static>>>,
    started: Mutex<bool>,
    started_condvar: Condvar,
}

impl ThreadDriverInner {
    unsafe fn init(this: *mut Self, cfg: esp_openthread_platform_config_t) {
        addr_of_mut!((*this).cfg).write(cfg);
        addr_of_mut!((*this).dataset_buf).write_bytes(0, 1);

        OtSrp::init(addr_of_mut!((*this).srp));

        addr_of_mut!((*this).ipv6_cb).write(None);
        addr_of_mut!((*this).scan_cb).write(None);
        addr_of_mut!((*this).energy_cb).write(None);
        addr_of_mut!((*this).started).write(Mutex::new(false));
        addr_of_mut!((*this).started_condvar).write(Condvar::new());
    }
}

struct ThreadDriverInnerGuard<'a> {
    inner: &'a mut ThreadDriverInner,
    _lock: OtLock,
}

impl Deref for ThreadDriverInnerGuard<'_> {
    type Target = ThreadDriverInner;

    fn deref(&self) -> &Self::Target {
        self.inner
    }
}

impl DerefMut for ThreadDriverInnerGuard<'_> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.inner
    }
}

struct OtLock(PhantomData<*const ()>);

impl OtLock {
    pub fn acquire() -> Result<Self, EspError> {
        if !unsafe { esp_openthread_lock_acquire(delay::BLOCK) } {
            Err(EspError::from_infallible::<ESP_ERR_TIMEOUT>())?;
        }

        Ok(Self(PhantomData))
    }
}

impl Drop for OtLock {
    fn drop(&mut self) {
        unsafe {
            esp_openthread_lock_release();
        }
    }
}

/// Trait shared between the modes of operation of the `EspThread` instance
pub trait NetifMode {
    fn init(&mut self) -> Result<(), EspError>;
    fn deinit(&mut self) -> Result<(), EspError>;
}

/// The regular mode of operation for the `EspThread` instance
///
/// This is the only available mode if the Border Router functionality in ESP-IDF is not enabled
pub struct Node(());

impl NetifMode for Node {
    fn init(&mut self) -> Result<(), EspError> {
        Ok(())
    }

    fn deinit(&mut self) -> Result<(), EspError> {
        Ok(())
    }
}

/// The Border Router mode of operation for the `EspThread` instance
#[cfg(all(esp_idf_comp_esp_netif_enabled, esp_idf_openthread_border_router))]
pub struct BorderRouter(());

#[cfg(all(esp_idf_comp_esp_netif_enabled, esp_idf_openthread_border_router))]
impl NetifMode for BorderRouter {
    fn init(&mut self) -> Result<(), EspError> {
        #[cfg(not(esp_idf_version_major = "4"))]
        {
            esp!(unsafe { esp_openthread_border_router_init() })?;
        }

        // TODO: This is probably best left to the user to call, as it is
        // not strictly necessary for the border router to function
        // #[cfg(any(esp_idf_comp_mdns_enabled, esp_idf_comp_espressif__mdns_enabled))]
        // {
        //     esp!(unsafe { mdns_init() })?;
        //     esp!(unsafe { mdns_hostname_set(b"esp-ot-br\0" as *const _ as *const _) })?;
        // }

        debug!("Border router initialized");

        Ok(())
    }

    fn deinit(&mut self) -> Result<(), EspError> {
        esp!(unsafe { esp_openthread_border_router_deinit() })?;

        debug!("Border router deinitialized");

        Ok(())
    }
}

/// `EspThread` wraps a `ThreadDriver` 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 Netif interface to the Thread 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 Thread 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 Thread radio.
#[cfg(all(esp_idf_comp_esp_netif_enabled, not(esp_idf_openthread_radio)))]
pub struct EspThread<'d, T>
where
    T: NetifMode,
{
    driver: ThreadDriver<'d, Host>,
    netif: EspNetif,
    mode: T,
}

#[cfg(all(esp_idf_comp_esp_netif_enabled, not(esp_idf_openthread_radio)))]
impl<'d> EspThread<'d, Node> {
    /// Create a new `EspThread` instance utilizing the native Thread radio on the MCU
    #[cfg(esp_idf_soc_ieee802154_supported)]
    pub fn new<M: crate::hal::modem::ThreadModemPeripheral + 'd>(
        modem: M,
        sysloop: EspSystemEventLoop,
        nvs: EspDefaultNvsPartition,
        mounted_event_fs: Arc<MountedEventfs>,
    ) -> Result<Self, EspError> {
        Self::wrap(ThreadDriver::new(modem, sysloop, nvs, mounted_event_fs)?)
    }

    /// Create a new `EspThread` instance utilizing an SPI connection to another MCU
    /// which is expected to run the Thread RCP driver mode over SPI
    #[cfg(not(esp_idf_version_major = "4"))]
    #[allow(clippy::too_many_arguments)]
    pub fn new_spi<S: crate::hal::spi::Spi + 'd>(
        _spi: S,
        mosi: impl InputPin + 'd,
        miso: impl OutputPin + 'd,
        sclk: impl InputPin + OutputPin + 'd,
        cs: Option<impl InputPin + OutputPin + 'd>,
        intr: Option<impl InputPin + OutputPin + 'd>,
        config: &crate::hal::spi::config::Config,
        _sysloop: EspSystemEventLoop,
        nvs: EspDefaultNvsPartition,
        mounted_event_fs: Arc<MountedEventfs>,
    ) -> Result<Self, EspError> {
        Self::wrap(ThreadDriver::new_spi(
            _spi,
            mosi,
            miso,
            sclk,
            cs,
            intr,
            config,
            _sysloop,
            nvs,
            mounted_event_fs,
        )?)
    }

    /// Create a new `EspThread` instance utilizing a UART connection to another MCU
    /// which is expected to run the Thread RCP driver mode over UART
    pub fn new_uart<U: Uart + 'd>(
        _uart: U,
        tx: impl OutputPin + 'd,
        rx: impl InputPin + 'd,
        config: &crate::hal::uart::config::Config,
        _sysloop: EspSystemEventLoop,
        nvs: EspDefaultNvsPartition,
        mounted_event_fs: Arc<MountedEventfs>,
    ) -> Result<Self, EspError> {
        Self::wrap(ThreadDriver::new_uart(
            _uart,
            tx,
            rx,
            config,
            _sysloop,
            nvs,
            mounted_event_fs,
        )?)
    }

    /// Wrap an already created Thread L2 driver instance
    pub fn wrap(driver: ThreadDriver<'d, Host>) -> Result<Self, EspError> {
        Self::wrap_all(driver, EspNetif::new(NetifStack::Thread)?)
    }

    /// Wrap an already created Thread L2 driver instance and a network interface
    pub fn wrap_all(driver: ThreadDriver<'d, Host>, netif: EspNetif) -> Result<Self, EspError> {
        Self::internal_init(driver, netif, Node(()))
    }
}

#[cfg(all(esp_idf_comp_esp_netif_enabled, esp_idf_openthread_border_router))]
impl<'d> EspThread<'d, BorderRouter> {
    /// Set or clear the backbone network interface to be used by the Border Router instance.
    ///
    /// This method _must_ be called _before_ the Border Router is constructed
    /// and _after_ the Border Router is dropped.
    ///
    /// # Safety
    ///
    /// This method is unsafe, because the framework will internally store a raw pointer
    /// to the provided `EspNetif` instance, and use it later when the Border Router
    /// is initialized. If the provided `EspNetif` instance is dropped before
    /// the Border Router is dropped, a use-after-free will occur.
    ///
    /// Make sure that the following conditions are met:
    /// - The provided `EspNetif` instance outlives the Thread Border Router instance;
    /// - The method is called _before_ both the Thread driver (`ThreadDriver`) and the `EspThread` instances are constructed;
    /// - Additionally, that the driver behind the provided `EspNetif` instance is _already started_ (e.g. `EspWifi::start()` or `EspEth::start()` had been called).
    #[cfg(not(esp_idf_version_major = "4"))]
    pub unsafe fn set_backbone_netif(backbone_netif: Option<&EspNetif>) {
        unsafe {
            esp_openthread_set_backbone_netif(
                backbone_netif
                    .map(|netif| netif.handle())
                    .unwrap_or(core::ptr::null_mut()),
            );
        }
    }

    /// Create a new `EspThread` Border Router instance utilizing the native Thread radio on the MCU
    #[cfg(esp_idf_soc_ieee802154_supported)]
    pub fn new_br<M: crate::hal::modem::ThreadModemPeripheral + 'd>(
        modem: M,
        sysloop: EspSystemEventLoop,
        nvs: EspDefaultNvsPartition,
        mounted_event_fs: Arc<MountedEventfs>,
    ) -> Result<Self, EspError> {
        Self::wrap_br(ThreadDriver::new(modem, sysloop, nvs, mounted_event_fs)?)
    }

    /// Create a new `EspThread` Border Router instance utilizing an SPI connection to another MCU
    /// which is expected to run the Thread RCP driver mode over SPI
    #[cfg(not(esp_idf_version_major = "4"))]
    #[allow(clippy::too_many_arguments)]
    pub fn new_br_spi<S: crate::hal::spi::Spi + 'd>(
        _spi: S,
        mosi: impl InputPin + 'd,
        miso: impl OutputPin + 'd,
        sclk: impl InputPin + OutputPin + 'd,
        cs: Option<impl InputPin + OutputPin + 'd>,
        intr: Option<impl InputPin + OutputPin + 'd>,
        config: &crate::hal::spi::config::Config,
        _sysloop: EspSystemEventLoop,
        nvs: EspDefaultNvsPartition,
        mounted_event_fs: Arc<MountedEventfs>,
    ) -> Result<Self, EspError> {
        Self::wrap_br(ThreadDriver::new_spi(
            _spi,
            mosi,
            miso,
            sclk,
            cs,
            intr,
            config,
            _sysloop,
            nvs,
            mounted_event_fs,
        )?)
    }

    /// Create a new `EspThread` Border Router instance utilizing a UART connection to another MCU
    /// which is expected to run the Thread RCP driver mode over UART
    #[allow(clippy::too_many_arguments)]
    pub fn new_br_uart<U: Uart + 'd>(
        _uart: U,
        tx: impl OutputPin + 'd,
        rx: impl InputPin + 'd,
        config: &crate::hal::uart::config::Config,
        _sysloop: EspSystemEventLoop,
        nvs: EspDefaultNvsPartition,
        mounted_event_fs: Arc<MountedEventfs>,
    ) -> Result<Self, EspError> {
        Self::wrap_br(ThreadDriver::new_uart(
            _uart,
            tx,
            rx,
            config,
            _sysloop,
            nvs,
            mounted_event_fs,
        )?)
    }

    /// Wrap an already created Thread L2 driver instance and a backbone network interface
    /// to the outside world
    pub fn wrap_br(driver: ThreadDriver<'d, Host>) -> Result<Self, EspError> {
        Self::wrap_br_all(driver, EspNetif::new(NetifStack::Thread)?)
    }

    /// Wrap an already created Thread L2 driver instance, a network interface to be used for the
    /// Thread network, and a backbone network interface to the outside world
    pub fn wrap_br_all(driver: ThreadDriver<'d, Host>, netif: EspNetif) -> Result<Self, EspError> {
        Self::internal_init(driver, netif, BorderRouter(()))
    }
}

#[cfg(all(esp_idf_comp_esp_netif_enabled, not(esp_idf_openthread_radio)))]
impl<'d, T> EspThread<'d, T>
where
    T: NetifMode,
{
    /// Return a reference to the underlying [`ThreadDriver`]
    pub fn driver(&self) -> &ThreadDriver<'d, Host> {
        &self.driver
    }

    /// Return a mutable reference to the underlying [`ThreadDriver`]
    pub fn driver_mut(&mut self) -> &mut ThreadDriver<'d, Host> {
        &mut self.driver
    }

    /// Initialize the coexistence between the Thread stack and a Wifi/BT stack on the modem
    #[cfg(all(esp_idf_openthread_radio_native, esp_idf_soc_ieee802154_supported))]
    pub fn init_coex(&mut self) -> Result<(), EspError> {
        self.driver.init_coex()
    }

    /// Return a reference to the underlying [`EspNetif`]
    pub fn netif(&self) -> &EspNetif {
        &self.netif
    }

    /// Enable or disable the Thread network interface
    pub fn enable_ipv6(&self, enabled: bool) -> Result<(), EspError> {
        self.driver().enable_ipv6(enabled)
    }

    /// Enable or disable Thread
    ///
    /// When enabling, this should be called after the network interface is enabled
    pub fn enable_thread(&self, enabled: bool) -> Result<(), EspError> {
        self.driver().enable_thread(enabled)
    }

    /// Retrieve the current role of the device in the Thread network
    pub fn role(&self) -> Result<Role, EspError> {
        self.driver().role()
    }

    /// Retrieve the active TOD (Thread Operational Dataset) in the user-supplied buffer
    ///
    /// Return the size of the TOD data written to the buffer
    ///
    /// The TOD is in Thread TLV format.
    pub fn tod(&self, buf: &mut [u8]) -> Result<usize, EspError> {
        self.driver().tod(buf)
    }

    /// Retrieve the pending TOD (Thread Operational Dataset) in the user-supplied buffer
    ///
    /// Return the size of the TOD data written to the buffer
    ///
    /// The TOD is in Thread TLV format.
    pub fn pending_tod(&self, buf: &mut [u8]) -> Result<usize, EspError> {
        self.driver().pending_tod(buf)
    }

    /// Set the active TOD (Thread Operational Dataset) to the provided data
    ///
    /// The TOD data should be in Thread TLV format.
    pub fn set_tod(&self, tod: &[u8]) -> Result<(), EspError> {
        self.driver().set_tod(tod)
    }

    /// Set the active TOD (Thread Operational Dataset) to the provided data
    ///
    /// The TOD data should be in Thread TLV format.
    pub fn set_tod_hexstr(&self, tod: &str) -> Result<(), EspError> {
        self.driver().set_tod_hexstr(tod)
    }

    /// Set the pending TOD (Thread Operational Dataset) to the provided data
    ///
    /// The TOD data should be in Thread TLV format.
    pub fn set_pending_tod(&self, tod: &[u8]) -> Result<(), EspError> {
        self.driver().set_pending_tod(tod)
    }

    /// Set the pending TOD (Thread Operational Dataset) to the provided data
    ///
    /// The TOD data should be in Thread TLV format.
    pub fn set_pending_tod_hexstr(&self, tod: &str) -> Result<(), EspError> {
        self.driver().set_pending_tod_hexstr(tod)
    }

    /// Set the active TOD (Thread Operational Dataset) according to the
    /// `CONFIG_OPENTHREAD_` TOD-related parameters compiled into the app
    /// during build (via `sdkconfig*`)
    #[cfg(not(esp_idf_version_major = "4"))]
    pub fn set_tod_from_cfg(&self) -> Result<(), EspError> {
        self.driver().set_tod_from_cfg()
    }

    /// Perform an active scan for Thread networks
    /// The callback will be called for each found network
    ///
    /// At the end of the scan, the callback will be called with `None`
    pub fn scan<F: FnMut(Option<ActiveScanResult>) + Send + 'static>(
        &self,
        callback: F,
    ) -> Result<(), EspError> {
        self.driver().scan(callback)
    }

    /// Check if an active scan is in progress
    pub fn is_scan_in_progress(&self) -> Result<bool, EspError> {
        self.driver().is_scan_in_progress()
    }

    /// Perform an energy scan for Thread networks
    /// The callback will be called for each found network
    ///
    /// At the end of the scan, the callback will be called with `None`
    pub fn energy_scan<F: FnMut(Option<EnergyScanResult>) + Send + 'static>(
        &self,
        callback: F,
    ) -> Result<(), EspError> {
        self.driver().energy_scan(callback)
    }

    /// Check if an energy scan is in progress
    pub fn is_energy_scan_in_progress(&self) -> Result<bool, EspError> {
        self.driver().is_energy_scan_in_progress()
    }

    /// Start the Thread driver
    ///
    /// If the driver is already started, an error is returned.
    pub fn start(&mut self) -> Result<(), EspError> {
        self.driver_mut().start()
    }

    /// Stop the Thread driver
    ///
    /// If the driver is not started, an error is returned.
    pub fn stop(&mut self) -> Result<(), EspError> {
        self.driver_mut().start()
    }

    /// Check if the Thread driver is started
    pub fn is_started(&self) -> Result<bool, EspError> {
        self.driver().is_started()
    }

    // NOTE: Methods starting with `internal_` have to be called only when the OpenThread lock is held

    fn internal_init(
        driver: ThreadDriver<'d, Host>,
        netif: EspNetif,
        mut mode: T,
    ) -> Result<Self, EspError> {
        let inner = driver.inner();

        let glue = unsafe { esp_openthread_netif_glue_init(&inner.cfg) };
        assert!(!glue.is_null());

        esp!(unsafe { esp_netif_attach(netif.handle() as *mut _, glue) })?;

        mode.init()?;

        info!("EspThread initialized");

        Ok(Self {
            netif,
            mode,
            driver,
        })
    }

    fn internal_deinit(&mut self) -> Result<(), EspError> {
        let _lock = self.driver.inner();

        self.mode.deinit()?;

        unsafe {
            esp_openthread_netif_glue_deinit();
        }

        Ok(())
    }
}

#[cfg(all(esp_idf_comp_esp_netif_enabled, not(esp_idf_openthread_radio)))]
impl<T> Drop for EspThread<'_, T>
where
    T: NetifMode,
{
    fn drop(&mut self) {
        self.internal_deinit().unwrap();
        info!("EspThread deinitialized");
    }
}

#[cfg(all(esp_idf_comp_esp_netif_enabled, not(esp_idf_openthread_radio)))]
unsafe impl<T> Send for EspThread<'_, T> where T: NetifMode {}
#[cfg(all(esp_idf_comp_esp_netif_enabled, not(esp_idf_openthread_radio)))]
unsafe impl<T> Sync for EspThread<'_, T> where T: NetifMode {}

/// Events reported by the Thread stack on the system event loop
#[derive(Copy, Clone, Debug)]
pub enum ThreadEvent {
    /// Thread stack started
    Started,
    /// Thread stack stopped
    Stopped,
    /// Thread stack detached
    #[cfg(not(esp_idf_version_major = "4"))]
    Detached,
    /// Thread stack attached
    #[cfg(not(esp_idf_version_major = "4"))]
    Attached,
    /// Thread role changed
    #[cfg(not(esp_idf_version_major = "4"))]
    RoleChanged {
        current_role: Role,
        previous_role: Role,
    },
    /// Thread network interface up
    IfUp,
    /// Thread network interface down
    IfDown,
    /// Thread got IPv6 address
    GotIpv6,
    /// Thread lost IPv6 address
    LostIpv6,
    /// Thread multicast group joined
    MulticastJoined,
    /// Thread multicast group left
    MulticastLeft,
    /// Thread TREL IPv6 address added
    #[cfg(not(esp_idf_version_major = "4"))]
    TrelIpv6Added,
    /// Thread TREL IPv6 address removed
    #[cfg(not(esp_idf_version_major = "4"))]
    TrelIpv6Removed,
    /// Thread TREL multicast group joined
    #[cfg(not(esp_idf_version_major = "4"))]
    TrelMulticastJoined,
    /// Thread DNS server set
    // Since 5.1
    #[cfg(all(
        not(esp_idf_version_major = "4"),
        not(all(esp_idf_version_major = "5", esp_idf_version_minor = "0"))
    ))]
    DnsServerSet,
    /// Thread Meshcop E Publish started
    // Since 5.2.2
    #[cfg(any(
        not(any(esp_idf_version_major = "4", esp_idf_version_major = "5")),
        all(
            esp_idf_version_major = "5",
            not(esp_idf_version_minor = "0"),
            not(esp_idf_version_minor = "1"),
            not(all(
                esp_idf_version_minor = "2",
                any(esp_idf_version_patch = "0", esp_idf_version_patch = "1")
            )),
        ),
    ))]
    MeshcopEPublishStarted,
    /// Thread Meshcop E Remove started
    // Since 5.2.2
    #[cfg(any(
        not(any(esp_idf_version_major = "4", esp_idf_version_major = "5")),
        all(
            esp_idf_version_major = "5",
            not(esp_idf_version_minor = "0"),
            not(esp_idf_version_minor = "1"),
            not(all(
                esp_idf_version_minor = "2",
                any(esp_idf_version_patch = "0", esp_idf_version_patch = "1")
            )),
        ),
    ))]
    MeshcopERemoveStarted,
    #[cfg(any(
        esp_idf_version_patch_at_least_5_1_6,
        esp_idf_version_patch_at_least_5_2_4,
        esp_idf_version_patch_at_least_5_3_2,
        esp_idf_version_at_least_5_4_0
    ))]
    DatasetChanged,
}

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

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

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

        match event_id {
            esp_openthread_event_t_OPENTHREAD_EVENT_START => ThreadEvent::Started,
            esp_openthread_event_t_OPENTHREAD_EVENT_STOP => ThreadEvent::Stopped,
            #[cfg(not(esp_idf_version_major = "4"))]
            esp_openthread_event_t_OPENTHREAD_EVENT_DETACHED => ThreadEvent::Detached,
            #[cfg(not(esp_idf_version_major = "4"))]
            esp_openthread_event_t_OPENTHREAD_EVENT_ATTACHED => ThreadEvent::Attached,
            #[cfg(not(esp_idf_version_major = "4"))]
            esp_openthread_event_t_OPENTHREAD_EVENT_ROLE_CHANGED => {
                let payload = unsafe {
                    (data.payload.unwrap() as *const _
                        as *const esp_openthread_role_changed_event_t)
                        .as_ref()
                }
                .unwrap();

                ThreadEvent::RoleChanged {
                    current_role: payload.current_role.into(),
                    previous_role: payload.previous_role.into(),
                }
            }
            esp_openthread_event_t_OPENTHREAD_EVENT_IF_UP => ThreadEvent::IfUp,
            esp_openthread_event_t_OPENTHREAD_EVENT_IF_DOWN => ThreadEvent::IfDown,
            esp_openthread_event_t_OPENTHREAD_EVENT_GOT_IP6 => ThreadEvent::GotIpv6,
            esp_openthread_event_t_OPENTHREAD_EVENT_LOST_IP6 => ThreadEvent::LostIpv6,
            esp_openthread_event_t_OPENTHREAD_EVENT_MULTICAST_GROUP_JOIN => {
                ThreadEvent::MulticastJoined
            }
            esp_openthread_event_t_OPENTHREAD_EVENT_MULTICAST_GROUP_LEAVE => {
                ThreadEvent::MulticastLeft
            }
            #[cfg(not(esp_idf_version_major = "4"))]
            esp_openthread_event_t_OPENTHREAD_EVENT_TREL_ADD_IP6 => ThreadEvent::TrelIpv6Added,
            #[cfg(not(esp_idf_version_major = "4"))]
            esp_openthread_event_t_OPENTHREAD_EVENT_TREL_REMOVE_IP6 => ThreadEvent::TrelIpv6Removed,
            #[cfg(not(esp_idf_version_major = "4"))]
            esp_openthread_event_t_OPENTHREAD_EVENT_TREL_MULTICAST_GROUP_JOIN => {
                ThreadEvent::TrelMulticastJoined
            }
            #[cfg(all(
                not(esp_idf_version_major = "4"),
                not(all(esp_idf_version_major = "5", esp_idf_version_minor = "0"))
            ))]
            esp_openthread_event_t_OPENTHREAD_EVENT_SET_DNS_SERVER => ThreadEvent::DnsServerSet,
            // Since 5.2.2
            #[cfg(any(
                not(any(esp_idf_version_major = "4", esp_idf_version_major = "5")),
                all(
                    esp_idf_version_major = "5",
                    not(esp_idf_version_minor = "0"),
                    not(esp_idf_version_minor = "1"),
                    not(all(
                        esp_idf_version_minor = "2",
                        any(esp_idf_version_patch = "0", esp_idf_version_patch = "1")
                    )),
                ),
            ))]
            esp_openthread_event_t_OPENTHREAD_EVENT_PUBLISH_MESHCOP_E => {
                ThreadEvent::MeshcopEPublishStarted
            }
            // Since 5.2.2
            #[cfg(any(
                not(any(esp_idf_version_major = "4", esp_idf_version_major = "5")),
                all(
                    esp_idf_version_major = "5",
                    not(esp_idf_version_minor = "0"),
                    not(esp_idf_version_minor = "1"),
                    not(all(
                        esp_idf_version_minor = "2",
                        any(esp_idf_version_patch = "0", esp_idf_version_patch = "1")
                    )),
                ),
            ))]
            esp_openthread_event_t_OPENTHREAD_EVENT_REMOVE_MESHCOP_E => {
                ThreadEvent::MeshcopERemoveStarted
            }
            #[cfg(any(
                esp_idf_version_patch_at_least_5_1_6,
                esp_idf_version_patch_at_least_5_2_4,
                esp_idf_version_patch_at_least_5_3_2,
                esp_idf_version_at_least_5_4_0
            ))]
            esp_openthread_event_t_OPENTHREAD_EVENT_DATASET_CHANGED => ThreadEvent::DatasetChanged,
            _ => panic!("unknown event ID: {event_id}"),
        }
    }
}