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
//: QueueHandle_t ! UART peripheral control
//!
//! Controls UART peripherals (UART0, UART1, UART2).
//! Notice that UART0 is typically already used for loading firmware and logging.
//! Therefore use UART1 and UART2 in your application.
//! Any pin can be used for `rx` and `tx`.
//!
//! # Example
//!
//! Create a serial peripheral and write to serial port.
//! ```
//! use std::fmt::Write;
//! use esp_idf_hal::prelude::*;
//! use esp_idf_hal::uart;
//!
//! let peripherals = Peripherals::take().unwrap();
//! let pins = peripherals.pins;
//!
//! let config = uart::config::Config::default().baudrate(Hertz(115_200));
//!
//! let mut uart: uart::UartDriver = uart::UartDriver::new(
//!     peripherals.uart1,
//!     pins.gpio1,
//!     pins.gpio3,
//!     Option::<AnyIOPin>::None,
//!     Option::<AnyIOPin>::None,
//!     &config
//! ).unwrap();
//!
//! for i in 0..10 {
//!     writeln!(uart, "{:}", format!("count {:}", i)).unwrap();
//! }
//! ```
//!
//! # TODO
//! - Add all extra features esp32 supports (eg rs485, etc. etc.)
//! - Free APB lock when TX is idle (and no RX used)
//! - Address errata 3.17: UART fifo_cnt is inconsistent with FIFO pointer

use core::borrow::BorrowMut;
use core::ffi::CStr;
use core::marker::PhantomData;
use core::mem::ManuallyDrop;
use core::ptr;
use core::sync::atomic::{AtomicU8, Ordering};

use crate::cpu::Core;
use crate::delay::{self, NON_BLOCK};
use crate::interrupt::InterruptType;
use crate::io::EspIOError;
use crate::task::asynch::Notification;
use crate::task::queue::Queue;
use crate::units::*;
use crate::{gpio::*, task};

use embedded_hal_nb::serial::ErrorKind;
use esp_idf_sys::*;

use crate::peripheral::Peripheral;

const UART_FIFO_SIZE: usize = SOC_UART_FIFO_LEN as usize;

pub type UartConfig = config::Config;

/// UART configuration
pub mod config {
    use crate::{interrupt::InterruptType, units::*};
    use enumset::{enum_set, EnumSet, EnumSetType};
    use esp_idf_sys::*;

    /// Number of data bits
    #[derive(PartialEq, Eq, Copy, Clone, Debug)]
    pub enum DataBits {
        DataBits5,
        DataBits6,
        DataBits7,
        DataBits8,
    }

    impl From<DataBits> for uart_word_length_t {
        fn from(data_bits: DataBits) -> Self {
            match data_bits {
                DataBits::DataBits5 => uart_word_length_t_UART_DATA_5_BITS,
                DataBits::DataBits6 => uart_word_length_t_UART_DATA_6_BITS,
                DataBits::DataBits7 => uart_word_length_t_UART_DATA_7_BITS,
                DataBits::DataBits8 => uart_word_length_t_UART_DATA_8_BITS,
            }
        }
    }

    impl From<uart_word_length_t> for DataBits {
        #[allow(non_upper_case_globals)]
        fn from(word_length: uart_word_length_t) -> Self {
            match word_length {
                uart_word_length_t_UART_DATA_5_BITS => DataBits::DataBits5,
                uart_word_length_t_UART_DATA_6_BITS => DataBits::DataBits6,
                uart_word_length_t_UART_DATA_7_BITS => DataBits::DataBits7,
                uart_word_length_t_UART_DATA_8_BITS => DataBits::DataBits8,
                _ => unreachable!(),
            }
        }
    }

    /// Number of data bits
    #[derive(PartialEq, Eq, Copy, Clone, Debug)]
    pub enum FlowControl {
        None,
        RTS,
        CTS,
        CTSRTS,
        MAX,
    }

    impl From<FlowControl> for uart_hw_flowcontrol_t {
        fn from(flow_control: FlowControl) -> Self {
            match flow_control {
                FlowControl::None => uart_hw_flowcontrol_t_UART_HW_FLOWCTRL_DISABLE,
                FlowControl::RTS => uart_hw_flowcontrol_t_UART_HW_FLOWCTRL_RTS,
                FlowControl::CTS => uart_hw_flowcontrol_t_UART_HW_FLOWCTRL_CTS,
                FlowControl::CTSRTS => uart_hw_flowcontrol_t_UART_HW_FLOWCTRL_CTS_RTS,
                FlowControl::MAX => uart_hw_flowcontrol_t_UART_HW_FLOWCTRL_MAX,
            }
        }
    }

    impl From<uart_hw_flowcontrol_t> for FlowControl {
        #[allow(non_upper_case_globals)]
        fn from(flow_control: uart_hw_flowcontrol_t) -> Self {
            match flow_control {
                uart_hw_flowcontrol_t_UART_HW_FLOWCTRL_DISABLE => FlowControl::None,
                uart_hw_flowcontrol_t_UART_HW_FLOWCTRL_RTS => FlowControl::RTS,
                uart_hw_flowcontrol_t_UART_HW_FLOWCTRL_CTS => FlowControl::CTS,
                uart_hw_flowcontrol_t_UART_HW_FLOWCTRL_CTS_RTS => FlowControl::CTSRTS,
                uart_hw_flowcontrol_t_UART_HW_FLOWCTRL_MAX => FlowControl::MAX,
                _ => unreachable!(),
            }
        }
    }

    /// Parity check
    #[derive(PartialEq, Eq, Copy, Clone, Debug)]
    pub enum Parity {
        ParityNone,
        ParityEven,
        ParityOdd,
    }

    impl From<Parity> for uart_parity_t {
        fn from(parity: Parity) -> Self {
            match parity {
                Parity::ParityNone => uart_parity_t_UART_PARITY_DISABLE,
                Parity::ParityEven => uart_parity_t_UART_PARITY_EVEN,
                Parity::ParityOdd => uart_parity_t_UART_PARITY_ODD,
            }
        }
    }

    impl From<uart_parity_t> for Parity {
        #[allow(non_upper_case_globals)]
        fn from(parity: uart_parity_t) -> Self {
            match parity {
                uart_parity_t_UART_PARITY_DISABLE => Parity::ParityNone,
                uart_parity_t_UART_PARITY_EVEN => Parity::ParityEven,
                uart_parity_t_UART_PARITY_ODD => Parity::ParityOdd,
                _ => unreachable!(),
            }
        }
    }

    /// Number of stop bits
    #[derive(PartialEq, Eq, Copy, Clone, Debug)]
    pub enum StopBits {
        /// 1 stop bit
        STOP1,
        /// 1.5 stop bits
        STOP1P5,
        /// 2 stop bits
        STOP2,
    }

    impl From<StopBits> for uart_stop_bits_t {
        fn from(stop_bits: StopBits) -> Self {
            match stop_bits {
                StopBits::STOP1 => uart_stop_bits_t_UART_STOP_BITS_1,
                StopBits::STOP1P5 => uart_stop_bits_t_UART_STOP_BITS_1_5,
                StopBits::STOP2 => uart_stop_bits_t_UART_STOP_BITS_2,
            }
        }
    }

    impl From<uart_stop_bits_t> for StopBits {
        #[allow(non_upper_case_globals)]
        fn from(stop_bits: uart_stop_bits_t) -> Self {
            match stop_bits {
                uart_stop_bits_t_UART_STOP_BITS_1 => StopBits::STOP1,
                uart_stop_bits_t_UART_STOP_BITS_1_5 => StopBits::STOP1P5,
                uart_stop_bits_t_UART_STOP_BITS_2 => StopBits::STOP2,
                _ => unreachable!(),
            }
        }
    }

    /// UART source clock
    #[derive(PartialEq, Eq, Copy, Clone, Debug)]
    pub enum SourceClock {
        /// UART source clock from `APB`
        #[cfg(any(
            esp_idf_soc_uart_support_apb_clk,
            esp_idf_soc_uart_support_pll_f40m_clk,
            esp_idf_version_major = "4",
        ))]
        APB,
        /// UART source clock from `RTC`
        #[cfg(esp_idf_soc_uart_support_rtc_clk)]
        RTC,
        /// UART source clock from `XTAL`
        #[cfg(esp_idf_soc_uart_support_xtal_clk)]
        Crystal,
        /// UART source clock from `XTAL`
        #[allow(non_camel_case_types)]
        #[cfg(esp_idf_soc_uart_support_pll_f80m_clk)]
        PLL_F80M,
        /// UART source clock from `REF_TICK`
        #[cfg(esp_idf_soc_uart_support_ref_tick)]
        RefTick,
    }

    impl SourceClock {
        pub const fn default() -> Self {
            #[cfg(not(esp_idf_version_major = "4"))]
            const DEFAULT: uart_sclk_t = soc_periph_uart_clk_src_legacy_t_UART_SCLK_DEFAULT;
            #[cfg(esp_idf_version_major = "4")]
            const DEFAULT: uart_sclk_t = uart_sclk_t_UART_SCLK_APB;
            Self::from_raw(DEFAULT)
        }

        pub const fn from_raw(source_clock: uart_sclk_t) -> Self {
            match source_clock {
                #[cfg(any(
                    esp_idf_soc_uart_support_apb_clk,
                    esp_idf_soc_uart_support_pll_f40m_clk,
                    esp_idf_version_major = "4",
                ))]
                APB_SCLK => SourceClock::APB,
                #[cfg(esp_idf_soc_uart_support_rtc_clk)]
                RTC_SCLK => SourceClock::RTC,
                #[cfg(esp_idf_soc_uart_support_xtal_clk)]
                XTAL_SCLK => SourceClock::Crystal,
                #[cfg(esp_idf_soc_uart_support_pll_f80m_clk)]
                PLL_F80M => SourceClock::PLL_F80M,
                #[cfg(esp_idf_soc_uart_support_ref_tick)]
                REF_TICK_SCLK => SourceClock::RefTick,
                _ => unreachable!(),
            }
        }

        #[cfg(not(esp_idf_version_major = "4"))]
        pub fn frequency(self) -> Result<Hertz, EspError> {
            let mut frequency: u32 = 0;
            esp_result! {
                unsafe { uart_get_sclk_freq(self.into(), &mut frequency) },
                Hertz(frequency)
            }
        }
    }

    #[cfg(all(not(esp_idf_version_major = "4"), esp_idf_soc_uart_support_apb_clk))]
    const APB_SCLK: uart_sclk_t = soc_periph_uart_clk_src_legacy_t_UART_SCLK_APB;
    #[cfg(all(
        not(esp_idf_version_major = "4"),
        not(esp_idf_soc_uart_support_apb_clk),
        esp_idf_soc_uart_support_pll_f40m_clk,
    ))]
    const APB_SCLK: uart_sclk_t = soc_periph_uart_clk_src_legacy_t_UART_SCLK_PLL_F40M;
    #[cfg(esp_idf_version_major = "4")]
    const APB_SCLK: uart_sclk_t = uart_sclk_t_UART_SCLK_APB;

    #[cfg(all(not(esp_idf_version_major = "4"), esp_idf_soc_uart_support_rtc_clk))]
    const RTC_SCLK: uart_sclk_t = soc_periph_uart_clk_src_legacy_t_UART_SCLK_RTC;
    #[cfg(all(esp_idf_version_major = "4", esp_idf_soc_uart_support_rtc_clk))]
    const RTC_SCLK: uart_sclk_t = uart_sclk_t_UART_SCLK_RTC;

    #[cfg(all(not(esp_idf_version_major = "4"), esp_idf_soc_uart_support_xtal_clk))]
    const XTAL_SCLK: uart_sclk_t = soc_periph_uart_clk_src_legacy_t_UART_SCLK_XTAL;
    #[cfg(all(esp_idf_version_major = "4", esp_idf_soc_uart_support_xtal_clk))]
    const XTAL_SCLK: uart_sclk_t = uart_sclk_t_UART_SCLK_XTAL;

    #[cfg(all(
        not(esp_idf_version_major = "4"),
        esp_idf_soc_uart_support_pll_f80m_clk
    ))]
    const PLL_F80M_SCLK: uart_sclk_t = soc_periph_uart_clk_src_legacy_t_UART_SCLK_PLL_F80M;
    #[cfg(all(esp_idf_version_major = "4", esp_idf_soc_uart_support_pll_f80m_clk))]
    const PLL_F80M_SCLK: uart_sclk_t = uart_sclk_t_UART_SCLK_PLL_F80M;

    #[cfg(all(not(esp_idf_version_major = "4"), esp_idf_soc_uart_support_ref_tick))]
    const REF_TICK_SCLK: uart_sclk_t = soc_periph_uart_clk_src_legacy_t_UART_SCLK_REF_TICK;
    #[cfg(all(esp_idf_version_major = "4", esp_idf_soc_uart_support_ref_tick))]
    const REF_TICK_SCLK: uart_sclk_t = uart_sclk_t_UART_SCLK_REF_TICK;

    impl Default for SourceClock {
        fn default() -> Self {
            SourceClock::default()
        }
    }

    impl From<SourceClock> for uart_sclk_t {
        fn from(source_clock: SourceClock) -> Self {
            match source_clock {
                #[cfg(any(
                    esp_idf_soc_uart_support_apb_clk,
                    esp_idf_soc_uart_support_pll_f40m_clk,
                    esp_idf_version_major = "4",
                ))]
                SourceClock::APB => APB_SCLK,
                #[cfg(esp_idf_soc_uart_support_rtc_clk)]
                SourceClock::RTC => RTC_SCLK,
                #[cfg(esp_idf_soc_uart_support_xtal_clk)]
                SourceClock::Crystal => XTAL_SCLK,
                #[cfg(esp_idf_soc_uart_support_pll_f80m_clk)]
                SourceClock::PLL_F80M => PLL_F80M_SCLK,
                #[cfg(esp_idf_soc_uart_support_ref_tick)]
                SourceClock::RefTick => REF_TICK_SCLK,
            }
        }
    }

    impl From<uart_sclk_t> for SourceClock {
        fn from(source_clock: uart_sclk_t) -> Self {
            Self::from_raw(source_clock)
        }
    }

    /// Configures the interrupts the UART driver should enable
    /// in order to be able to quickly inform us about the
    /// related event.
    #[derive(Debug, Clone)]
    pub struct EventConfig {
        /// If `Some(number_of_words)`, an interrupt will trigger
        /// after `number_of_words` could have been transmitted
        /// (unit is baudrate dependant).
        ///
        /// If `None` or `Some(0)` interrupt will be disabled.
        pub receive_timeout: Option<u8>,
        /// Sets the threshold at which an interrupt will
        /// be generated (the hardware receive FIFO contains more words than
        /// this number).
        ///
        /// If set to `None` interrupt will be disabled.
        pub rx_fifo_full: Option<u8>,
        /// Sets the threshold **below** which an interrupt will
        /// be generated (the hardware transmit FIFO contains less words than
        /// this number).
        ///
        /// If set to `None` interrupt will be disabled.
        /// Should not be set to `0` as the interrupt will trigger constantly.
        pub tx_fifo_empty: Option<u8>,
        /// Other interrupts to enable
        pub flags: EnumSet<EventFlags>,
        /// Allow using struct syntax,
        /// but signal users other fields may be added
        /// so `..Default::default()` should be used.
        #[doc(hidden)]
        pub _non_exhaustive: (),
    }

    impl EventConfig {
        pub const fn new() -> Self {
            EventConfig {
                receive_timeout: Some(10),
                rx_fifo_full: Some(120),
                tx_fifo_empty: Some(10),
                flags: enum_set!(
                    EventFlags::RxFifoFull
                        | EventFlags::RxFifoTimeout
                        | EventFlags::RxFifoOverflow
                        | EventFlags::BreakDetected
                        | EventFlags::ParityError
                ),
                _non_exhaustive: (),
            }
        }
    }

    impl Default for EventConfig {
        fn default() -> Self {
            EventConfig::new()
        }
    }

    impl From<EventConfig> for crate::sys::uart_intr_config_t {
        fn from(cfg: EventConfig) -> Self {
            let mut intr_enable_mask = cfg.flags;

            if cfg.receive_timeout.map(|to| to > 0).unwrap_or(false) {
                intr_enable_mask.insert(EventFlags::RxFifoTimeout);
            } else {
                intr_enable_mask.remove(EventFlags::RxFifoTimeout);
            }

            if cfg.rx_fifo_full.is_some() {
                intr_enable_mask.insert(EventFlags::RxFifoFull);
            } else {
                intr_enable_mask.remove(EventFlags::RxFifoFull);
            }

            if cfg.tx_fifo_empty.is_some() {
                intr_enable_mask.insert(EventFlags::TxFifoEmpty);
            } else {
                intr_enable_mask.remove(EventFlags::TxFifoEmpty);
            }

            crate::sys::uart_intr_config_t {
                intr_enable_mask: intr_enable_mask.as_repr(),
                rx_timeout_thresh: cfg.receive_timeout.unwrap_or(0),
                txfifo_empty_intr_thresh: cfg.tx_fifo_empty.unwrap_or(0),
                rxfifo_full_thresh: cfg.rx_fifo_full.unwrap_or(0),
            }
        }
    }

    #[derive(Debug, EnumSetType)]
    #[enumset(repr = "u32")]
    #[non_exhaustive]
    pub enum EventFlags {
        #[doc(hidden)]
        RxFifoFull = 0,
        #[doc(hidden)]
        TxFifoEmpty = 1,
        ParityError = 2,
        FrameError = 3,
        RxFifoOverflow = 4,
        DsrChange = 5,
        CtsChange = 6,
        BreakDetected = 7,
        #[doc(hidden)]
        RxFifoTimeout = 8,
        SwXon = 9,
        SwXoff = 10,
        GlitchDetected = 11,
        TxBreakDone = 12,
        TxBreakIdle = 13,
        TxDone = 14,
        Rs485ParityError = 15,
        Rs485FrameError = 16,
        Rs485Clash = 17,
        CmdCharDetected = 18,
    }

    /// UART configuration
    #[derive(Debug, Clone)]
    pub struct Config {
        pub baudrate: Hertz,
        pub data_bits: DataBits,
        pub parity: Parity,
        pub stop_bits: StopBits,
        pub flow_control: FlowControl,
        pub flow_control_rts_threshold: u8,
        pub source_clock: SourceClock,
        /// Configures the flags to use for interrupt allocation,
        /// e.g. priority to use for the interrupt.
        ///
        /// Note that you should not set `Iram` here, because it will
        /// be automatically set depending on the value of `CONFIG_UART_ISR_IN_IRAM`.
        pub intr_flags: EnumSet<InterruptType>,
        /// Configures the interrupts the driver should enable.
        pub event_config: EventConfig,
        /// The size of the software rx buffer. Must be bigger than the hardware FIFO.
        pub rx_fifo_size: usize,
        /// The size of the software tx buffer. Must be bigger than the hardware FIFO
        /// or 0 to disable transmit buffering (note that this will make write operations
        /// block until data has been sent out).
        pub tx_fifo_size: usize,
        /// Number of events that should fit into the event queue.
        /// Specify 0 to prevent the creation of an event queue.
        pub queue_size: usize,
        /// Allow using struct syntax,
        /// but signal users other fields may be added
        /// so `..Default::default()` should be used.
        #[doc(hidden)]
        pub _non_exhaustive: (),
    }

    impl Config {
        pub const fn new() -> Config {
            Config {
                baudrate: Hertz(19_200),
                data_bits: DataBits::DataBits8,
                parity: Parity::ParityNone,
                stop_bits: StopBits::STOP1,
                flow_control: FlowControl::None,
                flow_control_rts_threshold: 122,
                source_clock: SourceClock::default(),
                intr_flags: EnumSet::EMPTY,
                event_config: EventConfig::new(),
                rx_fifo_size: super::UART_FIFO_SIZE * 2,
                tx_fifo_size: super::UART_FIFO_SIZE * 2,
                queue_size: 10,
                _non_exhaustive: (),
            }
        }

        #[must_use]
        pub fn baudrate(mut self, baudrate: Hertz) -> Self {
            self.baudrate = baudrate;
            self
        }

        #[must_use]
        pub fn parity_none(mut self) -> Self {
            self.parity = Parity::ParityNone;
            self
        }

        #[must_use]
        pub fn parity_even(mut self) -> Self {
            self.parity = Parity::ParityEven;
            self
        }

        #[must_use]
        pub fn parity_odd(mut self) -> Self {
            self.parity = Parity::ParityOdd;
            self
        }

        #[must_use]
        pub fn data_bits(mut self, data_bits: DataBits) -> Self {
            self.data_bits = data_bits;
            self
        }

        #[must_use]
        pub fn stop_bits(mut self, stop_bits: StopBits) -> Self {
            self.stop_bits = stop_bits;
            self
        }

        #[must_use]
        pub fn flow_control(mut self, flow_control: FlowControl) -> Self {
            self.flow_control = flow_control;
            self
        }

        #[must_use]
        /// This setting only has effect if flow control is enabled.
        /// It determines how many bytes must be received before `RTS` line is asserted.
        /// Notice that count starts from `0` which means that `RTS` is asserted after every received byte.
        pub fn flow_control_rts_threshold(mut self, flow_control_rts_threshold: u8) -> Self {
            self.flow_control_rts_threshold = flow_control_rts_threshold;
            self
        }

        #[must_use]
        pub fn source_clock(mut self, source_clock: SourceClock) -> Self {
            self.source_clock = source_clock;
            self
        }

        #[must_use]
        pub fn tx_fifo_size(mut self, tx_fifo_size: usize) -> Self {
            self.tx_fifo_size = tx_fifo_size;
            self
        }

        #[must_use]
        pub fn rx_fifo_size(mut self, rx_fifo_size: usize) -> Self {
            self.rx_fifo_size = rx_fifo_size;
            self
        }

        #[must_use]
        pub fn queue_size(mut self, queue_size: usize) -> Self {
            self.queue_size = queue_size;
            self
        }
    }

    impl Default for Config {
        fn default() -> Config {
            Config::new()
        }
    }
}

pub trait Uart {
    fn port() -> uart_port_t;
}

crate::embedded_hal_error!(
    SerialError,
    embedded_hal_nb::serial::Error,
    embedded_hal_nb::serial::ErrorKind
);

#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct UartEvent {
    raw: uart_event_t,
}

impl UartEvent {
    pub fn payload(&self) -> UartEventPayload {
        #[allow(non_upper_case_globals)]
        match self.raw.type_ {
            uart_event_type_t_UART_DATA => UartEventPayload::Data {
                size: self.raw.size,
                timeout: self.raw.timeout_flag,
            },
            uart_event_type_t_UART_BREAK => UartEventPayload::Break,
            uart_event_type_t_UART_BUFFER_FULL => UartEventPayload::RxBufferFull,
            uart_event_type_t_UART_FIFO_OVF => UartEventPayload::RxFifoOverflow,
            uart_event_type_t_UART_FRAME_ERR => UartEventPayload::FrameError,
            uart_event_type_t_UART_PARITY_ERR => UartEventPayload::ParityError,
            uart_event_type_t_UART_DATA_BREAK => UartEventPayload::DataBreak,
            uart_event_type_t_UART_PATTERN_DET => UartEventPayload::PatternDetected,
            _ => UartEventPayload::Unknown,
        }
    }
}

#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub enum UartEventPayload {
    /// UART data was received and/or a timeout was triggered
    Data {
        /// The number of bytes received
        size: usize,
        /// Whether a timeout has occurred.
        /// It is possible that bytes have been received
        /// and this is set to `true` in case the driver
        /// processed both interrupts at the same time.
        timeout: bool,
    },
    /// Represents DATA event with timeout_flag set
    Break,
    RxBufferFull,
    RxFifoOverflow,
    FrameError,
    ParityError,
    DataBreak,
    PatternDetected,
    Unknown,
}

/// Serial abstraction
pub struct UartDriver<'d> {
    port: u8,
    queue: Option<Queue<UartEvent>>,
    _p: PhantomData<&'d mut ()>,
}

unsafe impl<'d> Send for UartDriver<'d> {}
unsafe impl<'d> Sync for UartDriver<'d> {}

/// Serial receiver
pub struct UartRxDriver<'d> {
    port: u8,
    owner: Owner,
    queue: Option<Queue<UartEvent>>,
    _p: PhantomData<&'d mut ()>,
}

/// Serial transmitter
pub struct UartTxDriver<'d> {
    port: u8,
    owner: Owner,
    queue: Option<Queue<UartEvent>>,
    _p: PhantomData<&'d mut ()>,
}

impl<'d> UartDriver<'d> {
    /// Create a new serial driver
    pub fn new<UART: Uart>(
        uart: impl Peripheral<P = UART> + 'd,
        tx: impl Peripheral<P = impl OutputPin> + 'd,
        rx: impl Peripheral<P = impl InputPin> + 'd,
        cts: Option<impl Peripheral<P = impl InputPin> + 'd>,
        rts: Option<impl Peripheral<P = impl OutputPin> + 'd>,
        config: &config::Config,
    ) -> Result<Self, EspError> {
        let mut q_handle_raw = ptr::null_mut();
        let q_handle = if config.queue_size > 0 {
            Some(&mut q_handle_raw)
        } else {
            None
        };
        new_common(uart, Some(tx), Some(rx), cts, rts, config, q_handle)?;

        // SAFTEY: okay because Queue borrows self
        // SAFETY: we can safely use UartEvent instead of uart_event_t because of repr(transparent)
        let queue = match q_handle_raw.is_null() {
            false => Some(unsafe { Queue::new_borrowed(q_handle_raw) }),
            true => None,
        };

        Ok(Self {
            port: UART::port() as _,
            queue,
            _p: PhantomData,
        })
    }

    /// Retrieves the event queue for this UART. Returns `None` if
    /// the config specified 0 for `queue_size`.
    pub fn event_queue(&self) -> Option<&Queue<UartEvent>> {
        self.queue.as_ref()
    }

    /// Change the number of stop bits
    pub fn change_stop_bits(&self, stop_bits: config::StopBits) -> Result<&Self, EspError> {
        change_stop_bits(self.port(), stop_bits).map(|_| self)
    }

    /// Returns the current number of stop bits
    pub fn stop_bits(&self) -> Result<config::StopBits, EspError> {
        stop_bits(self.port())
    }

    /// Change the number of data bits
    pub fn change_data_bits(&self, data_bits: config::DataBits) -> Result<&Self, EspError> {
        change_data_bits(self.port(), data_bits).map(|_| self)
    }

    /// Return the current number of data bits
    pub fn data_bits(&self) -> Result<config::DataBits, EspError> {
        data_bits(self.port())
    }

    /// Change the type of parity checking
    pub fn change_parity(&self, parity: config::Parity) -> Result<&Self, EspError> {
        change_parity(self.port(), parity).map(|_| self)
    }

    /// Returns the current type of parity checking
    pub fn parity(&self) -> Result<config::Parity, EspError> {
        parity(self.port())
    }

    /// Change the baudrate.
    ///
    /// Will automatically select the clock source. When possible the reference clock (1MHz) will
    /// be used, because this is constant when the clock source/frequency changes.
    /// However if one of the clock frequencies is below 10MHz or if the baudrate is above
    /// the reference clock or if the baudrate cannot be set within 1.5%
    /// then use the APB clock.
    pub fn change_baudrate<T: Into<Hertz> + Copy>(&self, baudrate: T) -> Result<&Self, EspError> {
        change_baudrate(self.port(), baudrate).map(|_| self)
    }

    /// Returns the current baudrate
    pub fn baudrate(&self) -> Result<Hertz, EspError> {
        baudrate(self.port())
    }

    /// Split the serial driver in separate TX and RX drivers
    pub fn split(&mut self) -> (UartTxDriver<'_>, UartRxDriver<'_>) {
        (
            UartTxDriver {
                port: self.port,
                owner: Owner::Borrowed,
                queue: self
                    .queue
                    .as_ref()
                    .map(|queue| unsafe { Queue::new_borrowed(queue.as_raw()) }),
                _p: PhantomData,
            },
            UartRxDriver {
                port: self.port,
                owner: Owner::Borrowed,
                queue: self
                    .queue
                    .as_ref()
                    .map(|queue| unsafe { Queue::new_borrowed(queue.as_raw()) }),
                _p: PhantomData,
            },
        )
    }

    /// Split the serial driver in separate TX and RX drivers.
    ///
    /// Unlike [`split`], the halves are owned and reference counted.
    pub fn into_split(self) -> (UartTxDriver<'d>, UartRxDriver<'d>) {
        let port = self.port;
        let tx_queue = self
            .queue
            .as_ref()
            .map(|queue| unsafe { Queue::new_borrowed(queue.as_raw()) });
        let rx_queue = self
            .queue
            .as_ref()
            .map(|queue| unsafe { Queue::new_borrowed(queue.as_raw()) });
        let _ = ManuallyDrop::new(self);
        REFS[port as usize].fetch_add(2, Ordering::SeqCst);
        (
            UartTxDriver {
                port,
                owner: Owner::Shared,
                queue: tx_queue,
                _p: PhantomData,
            },
            UartRxDriver {
                port,
                owner: Owner::Shared,
                queue: rx_queue,
                _p: PhantomData,
            },
        )
    }

    /// Read multiple bytes into a slice
    pub fn read(&self, buf: &mut [u8], timeout: TickType_t) -> Result<usize, EspError> {
        self.rx().read(buf, timeout)
    }

    /// Write multiple bytes from a slice
    pub fn write(&self, bytes: &[u8]) -> Result<usize, EspError> {
        self.tx().write(bytes)
    }

    /// Write multiple bytes from a slice directly to the TX FIFO hardware.
    /// Returns the number of bytes written, where 0 would mean that the TX FIFO is full.
    ///
    /// NOTE: In case the UART TX buffer is enabled, this method might have unpredictable results
    /// when used together with method `write`, as the latter will push the data to be sent to the
    /// TX buffer first.
    ///
    /// To avoid this, always call `wait_done` after the last call to `write` and before
    /// calling this method.
    pub fn write_nb(&self, bytes: &[u8]) -> Result<usize, EspError> {
        self.tx().write_nb(bytes)
    }

    /// Clears the receive buffer.
    #[deprecated(since = "0.41.3", note = "Use UartDriver::clear_rx instead")]
    pub fn flush_read(&self) -> Result<(), EspError> {
        self.rx().clear()
    }

    /// Clears the receive buffer.
    pub fn clear_rx(&self) -> Result<(), EspError> {
        self.rx().clear()
    }

    /// Waits for the transmission to complete.
    #[deprecated(since = "0.41.3", note = "Use UartDriver::wait_tx_done instead")]
    pub fn flush_write(&self) -> Result<(), EspError> {
        self.tx().wait_done(delay::BLOCK)
    }

    /// Waits until the transmission is complete or until the specified timeout expires.
    pub fn wait_tx_done(&self, timeout: TickType_t) -> Result<(), EspError> {
        self.tx().wait_done(timeout)
    }

    pub fn port(&self) -> uart_port_t {
        self.port as _
    }

    /// Get count of remaining bytes in the receive ring buffer
    pub fn remaining_read(&self) -> Result<usize, EspError> {
        remaining_unread_bytes(self.port())
    }

    /// Get count of remaining capacity in the transmit ring buffer
    #[cfg(any(
        not(esp_idf_version_major = "4"),
        all(
            esp_idf_version_minor = "4",
            not(any(esp_idf_version_patch = "0", esp_idf_version_patch = "1")),
        ),
    ))]
    pub fn remaining_write(&self) -> Result<usize, EspError> {
        remaining_write_capacity(self.port())
    }

    fn rx(&self) -> ManuallyDrop<UartRxDriver<'_>> {
        ManuallyDrop::new(UartRxDriver {
            port: self.port,
            owner: Owner::Borrowed,
            queue: self
                .queue
                .as_ref()
                .map(|queue| unsafe { Queue::new_borrowed(queue.as_raw()) }),
            _p: PhantomData,
        })
    }

    fn tx(&self) -> ManuallyDrop<UartTxDriver<'_>> {
        ManuallyDrop::new(UartTxDriver {
            port: self.port,
            owner: Owner::Borrowed,
            queue: self
                .queue
                .as_ref()
                .map(|queue| unsafe { Queue::new_borrowed(queue.as_raw()) }),
            _p: PhantomData,
        })
    }
}

impl<'d> Drop for UartDriver<'d> {
    fn drop(&mut self) {
        delete_driver(self.port()).unwrap();
    }
}

impl<'d> embedded_io::ErrorType for UartDriver<'d> {
    type Error = EspIOError;
}

impl<'d> embedded_io::Read for UartDriver<'d> {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
        UartDriver::read(self, buf, delay::BLOCK).map_err(EspIOError)
    }
}

impl<'d> embedded_io::Write for UartDriver<'d> {
    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
        UartDriver::write(self, buf).map_err(EspIOError)
    }

    fn flush(&mut self) -> Result<(), Self::Error> {
        UartDriver::wait_tx_done(self, delay::BLOCK).map_err(EspIOError)
    }
}

impl<'d> embedded_hal_0_2::serial::Read<u8> for UartDriver<'d> {
    type Error = SerialError;

    fn read(&mut self) -> nb::Result<u8, Self::Error> {
        embedded_hal_0_2::serial::Read::read(&mut *self.rx())
    }
}

impl<'d> embedded_hal_0_2::serial::Write<u8> for UartDriver<'d> {
    type Error = SerialError;

    fn flush(&mut self) -> nb::Result<(), Self::Error> {
        embedded_hal_0_2::serial::Write::flush(&mut *self.tx())
    }

    fn write(&mut self, byte: u8) -> nb::Result<(), Self::Error> {
        embedded_hal_0_2::serial::Write::write(&mut *self.tx(), byte)
    }
}

impl<'d> embedded_hal_nb::serial::ErrorType for UartDriver<'d> {
    type Error = SerialError;
}

impl<'d> embedded_hal_nb::serial::Read<u8> for UartDriver<'d> {
    fn read(&mut self) -> nb::Result<u8, Self::Error> {
        embedded_hal_nb::serial::Read::read(&mut *self.rx())
    }
}

impl<'d> embedded_hal_nb::serial::Write<u8> for UartDriver<'d> {
    fn write(&mut self, byte: u8) -> nb::Result<(), Self::Error> {
        embedded_hal_nb::serial::Write::write(&mut *self.tx(), byte)
    }

    fn flush(&mut self) -> nb::Result<(), Self::Error> {
        embedded_hal_nb::serial::Write::flush(&mut *self.tx())
    }
}

impl<'d> core::fmt::Write for UartDriver<'d> {
    fn write_str(&mut self, s: &str) -> core::fmt::Result {
        self.tx().write_str(s)
    }
}

impl<'d> UartRxDriver<'d> {
    /// Create a new serial receiver
    pub fn new<UART: Uart>(
        uart: impl Peripheral<P = UART> + 'd,
        rx: impl Peripheral<P = impl InputPin> + 'd,
        cts: Option<impl Peripheral<P = impl InputPin> + 'd>,
        rts: Option<impl Peripheral<P = impl OutputPin> + 'd>,
        config: &config::Config,
    ) -> Result<Self, EspError> {
        let mut q_handle_raw = ptr::null_mut();
        let q_handle = if config.queue_size > 0 {
            Some(&mut q_handle_raw)
        } else {
            None
        };
        new_common(
            uart,
            None::<AnyOutputPin>,
            Some(rx),
            cts,
            rts,
            config,
            q_handle,
        )?;

        // SAFTEY: okay because Queue borrows self
        // SAFETY: we can safely use UartEvent instead of uart_event_t because of repr(transparent)
        let queue = match q_handle_raw.is_null() {
            false => Some(unsafe { Queue::new_borrowed(q_handle_raw) }),
            true => None,
        };

        Ok(Self {
            port: UART::port() as _,
            owner: Owner::Owned,
            queue,
            _p: PhantomData,
        })
    }

    /// Retrieves the event queue for this UART. Returns `None` if
    /// the config specified 0 for `queue_size`.
    pub fn event_queue(&self) -> Option<&Queue<UartEvent>> {
        self.queue.as_ref()
    }

    /// Change the number of stop bits
    pub fn change_stop_bits(&self, stop_bits: config::StopBits) -> Result<&Self, EspError> {
        change_stop_bits(self.port(), stop_bits).map(|_| self)
    }

    /// Returns the current number of stop bits
    pub fn stop_bits(&self) -> Result<config::StopBits, EspError> {
        stop_bits(self.port())
    }

    /// Change the number of data bits
    pub fn change_data_bits(&self, data_bits: config::DataBits) -> Result<&Self, EspError> {
        change_data_bits(self.port(), data_bits).map(|_| self)
    }

    /// Return the current number of data bits
    pub fn data_bits(&self) -> Result<config::DataBits, EspError> {
        data_bits(self.port())
    }

    /// Change the type of parity checking
    pub fn change_parity(&self, parity: config::Parity) -> Result<&Self, EspError> {
        change_parity(self.port(), parity).map(|_| self)
    }

    /// Returns the current type of parity checking
    pub fn parity(&self) -> Result<config::Parity, EspError> {
        parity(self.port())
    }

    /// Change the baudrate.
    ///
    /// Will automatically select the clock source. When possible the reference clock (1MHz) will
    /// be used, because this is constant when the clock source/frequency changes.
    /// However if one of the clock frequencies is below 10MHz or if the baudrate is above
    /// the reference clock or if the baudrate cannot be set within 1.5%
    /// then use the APB clock.
    pub fn change_baudrate<T: Into<Hertz> + Copy>(&self, baudrate: T) -> Result<&Self, EspError> {
        change_baudrate(self.port(), baudrate).map(|_| self)
    }

    /// Returns the current baudrate
    pub fn baudrate(&self) -> Result<Hertz, EspError> {
        baudrate(self.port())
    }

    /// Read multiple bytes into a slice; block until specified timeout
    pub fn read(&self, buf: &mut [u8], delay: TickType_t) -> Result<usize, EspError> {
        // uart_read_bytes() returns error (-1) or how many bytes were read out
        // 0 means timeout and nothing is yet read out
        let len = unsafe {
            uart_read_bytes(
                self.port(),
                buf.as_mut_ptr().cast(),
                buf.len() as u32,
                delay,
            )
        };

        if len >= 0 {
            Ok(len as usize)
        } else {
            Err(EspError::from_infallible::<ESP_ERR_INVALID_STATE>())
        }
    }

    /// Clears the receive buffer.
    #[deprecated(since = "0.41.3", note = "Use `UartRxDriver::clear` instead")]
    pub fn flush(&self) -> Result<(), EspError> {
        self.clear()
    }

    pub fn clear(&self) -> Result<(), EspError> {
        esp!(unsafe { uart_flush_input(self.port()) })?;

        Ok(())
    }

    pub fn port(&self) -> uart_port_t {
        self.port as _
    }

    /// Get count of remaining bytes in the receive ring buffer
    pub fn count(&self) -> Result<usize, EspError> {
        remaining_unread_bytes(self.port())
    }
}

impl<'d> Drop for UartRxDriver<'d> {
    fn drop(&mut self) {
        self.owner.drop_impl(self.port()).unwrap()
    }
}

impl<'d> embedded_io::ErrorType for UartRxDriver<'d> {
    type Error = EspIOError;
}

impl<'d> embedded_io::Read for UartRxDriver<'d> {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
        UartRxDriver::read(self, buf, delay::BLOCK).map_err(EspIOError)
    }
}

impl<'d> embedded_hal_0_2::serial::Read<u8> for UartRxDriver<'d> {
    type Error = SerialError;

    fn read(&mut self) -> nb::Result<u8, Self::Error> {
        let mut buf = [0_u8];

        let result = UartRxDriver::read(self, &mut buf, NON_BLOCK);

        check_nb(result, buf[0])
    }
}

impl<'d> embedded_hal_nb::serial::ErrorType for UartRxDriver<'d> {
    type Error = SerialError;
}

impl<'d> embedded_hal_nb::serial::Read<u8> for UartRxDriver<'d> {
    fn read(&mut self) -> nb::Result<u8, Self::Error> {
        let mut buf = [0_u8];

        let result = UartRxDriver::read(self, &mut buf, NON_BLOCK);

        check_nb(result, buf[0])
    }
}

impl<'d> UartTxDriver<'d> {
    /// Create a new serial transmitter
    pub fn new<UART: Uart>(
        uart: impl Peripheral<P = UART> + 'd,
        tx: impl Peripheral<P = impl OutputPin> + 'd,
        cts: Option<impl Peripheral<P = impl InputPin> + 'd>,
        rts: Option<impl Peripheral<P = impl OutputPin> + 'd>,
        config: &config::Config,
    ) -> Result<Self, EspError> {
        let mut q_handle_raw = ptr::null_mut();
        let q_handle = if config.queue_size > 0 {
            Some(&mut q_handle_raw)
        } else {
            None
        };
        new_common(
            uart,
            Some(tx),
            None::<AnyInputPin>,
            cts,
            rts,
            config,
            q_handle,
        )?;

        // SAFTEY: okay because Queue borrows self
        // SAFETY: we can safely use UartEvent instead of uart_event_t because of repr(transparent)
        let queue = match q_handle_raw.is_null() {
            false => Some(unsafe { Queue::new_borrowed(q_handle_raw) }),
            true => None,
        };

        Ok(Self {
            port: UART::port() as _,
            owner: Owner::Owned,
            queue,
            _p: PhantomData,
        })
    }

    /// Retrieves the event queue for this UART. Returns `None` if
    /// the config specified 0 for `queue_size`.
    pub fn event_queue(&self) -> Option<&Queue<UartEvent>> {
        self.queue.as_ref()
    }

    /// Change the number of stop bits
    pub fn change_stop_bits(&self, stop_bits: config::StopBits) -> Result<&Self, EspError> {
        change_stop_bits(self.port(), stop_bits).map(|_| self)
    }

    /// Returns the current number of stop bits
    pub fn stop_bits(&self) -> Result<config::StopBits, EspError> {
        stop_bits(self.port())
    }

    /// Change the number of data bits
    pub fn change_data_bits(&self, data_bits: config::DataBits) -> Result<&Self, EspError> {
        change_data_bits(self.port(), data_bits).map(|_| self)
    }

    /// Return the current number of data bits
    pub fn data_bits(&self) -> Result<config::DataBits, EspError> {
        data_bits(self.port())
    }

    /// Change the type of parity checking
    pub fn change_parity(&self, parity: config::Parity) -> Result<&Self, EspError> {
        change_parity(self.port(), parity).map(|_| self)
    }

    /// Returns the current type of parity checking
    pub fn parity(&self) -> Result<config::Parity, EspError> {
        parity(self.port())
    }

    /// Change the baudrate.
    ///
    /// Will automatically select the clock source. When possible the reference clock (1MHz) will
    /// be used, because this is constant when the clock source/frequency changes.
    /// However if one of the clock frequencies is below 10MHz or if the baudrate is above
    /// the reference clock or if the baudrate cannot be set within 1.5%
    /// then use the APB clock.
    pub fn change_baudrate<T: Into<Hertz> + Copy>(&self, baudrate: T) -> Result<&Self, EspError> {
        change_baudrate(self.port(), baudrate).map(|_| self)
    }

    /// Returns the current baudrate
    pub fn baudrate(&self) -> Result<Hertz, EspError> {
        baudrate(self.port())
    }

    /// Write multiple bytes from a slice
    pub fn write(&mut self, bytes: &[u8]) -> Result<usize, EspError> {
        // `uart_write_bytes()` returns error (-1) or how many bytes were written
        let len = unsafe { uart_write_bytes(self.port(), bytes.as_ptr().cast(), bytes.len()) };

        if len >= 0 {
            Ok(len as usize)
        } else {
            Err(EspError::from_infallible::<ESP_ERR_INVALID_STATE>())
        }
    }

    /// Write multiple bytes from a slice directly to the TX FIFO hardware.
    /// Returns the number of bytes written, where 0 would mean that the TX FIFO is full.
    ///
    /// NOTE: In case the UART TX buffer is enabled, this method might have unpredictable results
    /// when used together with method `write`, as the latter will push the data to be sent to the
    /// TX buffer first.
    ///
    /// To avoid this, always call `wait_done` after the last call to `write` and before
    /// calling this method.
    pub fn write_nb(&self, bytes: &[u8]) -> Result<usize, EspError> {
        let ret = unsafe { uart_tx_chars(self.port(), bytes.as_ptr().cast(), bytes.len() as _) };

        if ret < 0 {
            esp!(ret)?;
        }

        Ok(ret as usize)
    }

    /// Waits until the transmission is complete or until the specified timeout expires.
    pub fn wait_done(&self, timeout: TickType_t) -> Result<(), EspError> {
        esp!(unsafe { uart_wait_tx_done(self.port(), timeout) })?;

        Ok(())
    }

    /// Waits until the transmission is complete.
    #[deprecated(since = "0.41.3", note = "Use `UartTxDriver::wait_done` instead")]
    pub fn flush(&mut self) -> Result<(), EspError> {
        self.wait_done(delay::BLOCK)
    }

    pub fn port(&self) -> uart_port_t {
        self.port as _
    }

    /// Get count of remaining capacity in the transmit ring buffer
    #[cfg(any(
        not(esp_idf_version_major = "4"),
        all(
            esp_idf_version_minor = "4",
            not(any(esp_idf_version_patch = "0", esp_idf_version_patch = "1")),
        ),
    ))]
    pub fn count(&self) -> Result<usize, EspError> {
        remaining_write_capacity(self.port())
    }
}

impl<'d> Drop for UartTxDriver<'d> {
    fn drop(&mut self) {
        self.owner.drop_impl(self.port()).unwrap()
    }
}

impl<'d> embedded_io::Write for UartTxDriver<'d> {
    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
        UartTxDriver::write(self, buf).map_err(EspIOError)
    }

    fn flush(&mut self) -> Result<(), Self::Error> {
        UartTxDriver::wait_done(self, delay::BLOCK).map_err(EspIOError)
    }
}

impl<'d> embedded_io::ErrorType for UartTxDriver<'d> {
    type Error = EspIOError;
}

impl<'d> embedded_hal_0_2::serial::Write<u8> for UartTxDriver<'d> {
    type Error = SerialError;

    fn flush(&mut self) -> nb::Result<(), Self::Error> {
        check_nb_timeout(UartTxDriver::wait_done(self, delay::NON_BLOCK))
    }

    fn write(&mut self, byte: u8) -> nb::Result<(), Self::Error> {
        check_nb(UartTxDriver::write_nb(self, &[byte]), ())
    }
}

impl<'d> embedded_hal_nb::serial::ErrorType for UartTxDriver<'d> {
    type Error = SerialError;
}

impl<'d> embedded_hal_nb::serial::Write<u8> for UartTxDriver<'d> {
    fn flush(&mut self) -> nb::Result<(), Self::Error> {
        check_nb_timeout(UartTxDriver::wait_done(self, delay::NON_BLOCK))
    }

    fn write(&mut self, byte: u8) -> nb::Result<(), Self::Error> {
        check_nb(UartTxDriver::write_nb(self, &[byte]), ())
    }
}

impl<'d> core::fmt::Write for UartTxDriver<'d> {
    fn write_str(&mut self, s: &str) -> core::fmt::Result {
        let buf = s.as_bytes();
        let mut offset = 0;

        while offset < buf.len() {
            offset += self.write(buf).map_err(|_| core::fmt::Error)?
        }

        Ok(())
    }
}

pub struct AsyncUartDriver<'d, T>
where
    T: BorrowMut<UartDriver<'d>>,
{
    driver: T,
    task: TaskHandle_t,
    _data: PhantomData<&'d ()>,
}

impl<'d> AsyncUartDriver<'d, UartDriver<'d>> {
    pub fn new(
        uart: impl Peripheral<P = impl Uart> + 'd,
        tx: impl Peripheral<P = impl OutputPin> + 'd,
        rx: impl Peripheral<P = impl InputPin> + 'd,
        cts: Option<impl Peripheral<P = impl InputPin> + 'd>,
        rts: Option<impl Peripheral<P = impl OutputPin> + 'd>,
        config: &config::Config,
    ) -> Result<Self, EspError> {
        Self::wrap(UartDriver::new(uart, tx, rx, cts, rts, config)?)
    }
}

impl<'d, T> AsyncUartDriver<'d, T>
where
    T: BorrowMut<UartDriver<'d>>,
{
    pub fn wrap(driver: T) -> Result<Self, EspError> {
        Self::wrap_custom(driver, None, None)
    }

    pub fn wrap_custom(
        driver: T,
        priority: Option<u8>,
        pin_to_core: Option<Core>,
    ) -> Result<Self, EspError> {
        let task = new_task_common(
            driver.borrow().port,
            driver.borrow().event_queue(),
            priority,
            pin_to_core,
        )?;

        Ok(Self {
            driver,
            task,
            _data: PhantomData,
        })
    }

    pub fn driver(&self) -> &UartDriver<'d> {
        self.driver.borrow()
    }

    pub fn driver_mut(&mut self) -> &mut UartDriver<'d> {
        self.driver.borrow_mut()
    }

    /// Split the serial driver in separate TX and RX drivers
    pub fn split(
        &mut self,
    ) -> (
        AsyncUartTxDriver<'_, UartTxDriver<'_>>,
        AsyncUartRxDriver<'_, UartRxDriver<'_>>,
    ) {
        let (tx, rx) = self.driver_mut().split();

        (
            AsyncUartTxDriver {
                driver: tx,
                task: None,
                _data: PhantomData,
            },
            AsyncUartRxDriver {
                driver: rx,
                task: None,
                _data: PhantomData,
            },
        )
    }

    pub async fn read(&self, buf: &mut [u8]) -> Result<usize, EspError> {
        if buf.is_empty() {
            Ok(0)
        } else {
            loop {
                let res = self.driver.borrow().read(buf, delay::NON_BLOCK);

                match res {
                    Ok(len) if len > 0 => return Ok(len),
                    Err(e) if e.code() != ESP_ERR_TIMEOUT => return Err(e),
                    _ => (),
                }

                let port = self.driver.borrow().port as usize;
                READ_NOTIFS[port].wait().await;
            }
        }
    }

    pub async fn write(&self, bytes: &[u8]) -> Result<usize, EspError> {
        if bytes.is_empty() {
            Ok(0)
        } else {
            loop {
                let res = self.driver.borrow().write_nb(bytes);

                match res {
                    Ok(len) if len > 0 => return Ok(len),
                    Err(e) => return Err(e),
                    _ => (),
                }

                // We cannot properly wait for the TX FIFO queue to become non-full
                // because the ESP IDF UART ISR does not notify us on that
                //
                // Instead, spin a busy loop, however still allowing other futures to be polled too.
                crate::task::yield_now().await;
            }
        }
    }

    pub async fn wait_tx_done(&self) -> Result<(), EspError> {
        loop {
            let res = self.driver.borrow().wait_tx_done(delay::NON_BLOCK);

            match res {
                Ok(()) => return Ok(()),
                Err(e) if e.code() != ESP_ERR_TIMEOUT => return Err(e),
                _ => (),
            }

            // We cannot properly wait for the TX FIFO queue to become empty
            // because the ESP IDF UART ISR does not notify us on that
            //
            // Instead, spin a busy loop, however still allowing other futures to be polled too.
            crate::task::yield_now().await;
        }
    }
}

unsafe impl<'d, T> Send for AsyncUartDriver<'d, T> where T: BorrowMut<UartDriver<'d>> + Send {}
unsafe impl<'d, T> Sync for AsyncUartDriver<'d, T> where T: BorrowMut<UartDriver<'d>> + Send + Sync {}

impl<'d, T> Drop for AsyncUartDriver<'d, T>
where
    T: BorrowMut<UartDriver<'d>>,
{
    fn drop(&mut self) {
        drop_task_common(self.task, self.driver.borrow().port);
    }
}

impl<'d, T> embedded_io::ErrorType for AsyncUartDriver<'d, T>
where
    T: BorrowMut<UartDriver<'d>>,
{
    type Error = EspIOError;
}

impl<'d, T> embedded_io_async::Read for AsyncUartDriver<'d, T>
where
    T: BorrowMut<UartDriver<'d>>,
{
    async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
        AsyncUartDriver::read(self, buf).await.map_err(EspIOError)
    }
}

impl<'d, T> embedded_io_async::Write for AsyncUartDriver<'d, T>
where
    T: BorrowMut<UartDriver<'d>>,
{
    async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
        AsyncUartDriver::write(self, buf).await.map_err(EspIOError)
    }

    async fn flush(&mut self) -> Result<(), Self::Error> {
        AsyncUartDriver::wait_tx_done(self)
            .await
            .map_err(EspIOError)
    }
}

pub struct AsyncUartRxDriver<'d, T>
where
    T: BorrowMut<UartRxDriver<'d>>,
{
    driver: T,
    task: Option<TaskHandle_t>,
    _data: PhantomData<&'d ()>,
}

impl<'d> AsyncUartRxDriver<'d, UartRxDriver<'d>> {
    pub fn new(
        uart: impl Peripheral<P = impl Uart> + 'd,
        rx: impl Peripheral<P = impl InputPin> + 'd,
        cts: Option<impl Peripheral<P = impl InputPin> + 'd>,
        rts: Option<impl Peripheral<P = impl OutputPin> + 'd>,
        config: &config::Config,
    ) -> Result<Self, EspError> {
        Self::wrap(UartRxDriver::new(uart, rx, cts, rts, config)?)
    }
}

impl<'d, T> AsyncUartRxDriver<'d, T>
where
    T: BorrowMut<UartRxDriver<'d>>,
{
    pub fn wrap(driver: T) -> Result<Self, EspError> {
        Self::wrap_custom(driver, None, None)
    }

    pub fn wrap_custom(
        driver: T,
        priority: Option<u8>,
        pin_to_core: Option<Core>,
    ) -> Result<Self, EspError> {
        let task = new_task_common(
            driver.borrow().port,
            driver.borrow().event_queue(),
            priority,
            pin_to_core,
        )?;

        Ok(Self {
            driver,
            task: Some(task),
            _data: PhantomData,
        })
    }

    pub fn driver(&self) -> &UartRxDriver<'d> {
        self.driver.borrow()
    }

    pub fn driver_mut(&mut self) -> &mut UartRxDriver<'d> {
        self.driver.borrow_mut()
    }

    pub async fn read(&self, buf: &mut [u8]) -> Result<usize, EspError> {
        if buf.is_empty() {
            Ok(0)
        } else {
            loop {
                let res = self.driver.borrow().read(buf, delay::NON_BLOCK);

                match res {
                    Ok(len) if len > 0 => return Ok(len),
                    Err(e) if e.code() != ESP_ERR_TIMEOUT => return Err(e),
                    _ => (),
                }

                let port = self.driver.borrow().port as usize;
                READ_NOTIFS[port].wait().await;
            }
        }
    }
}

impl<'d, T> Drop for AsyncUartRxDriver<'d, T>
where
    T: BorrowMut<UartRxDriver<'d>>,
{
    fn drop(&mut self) {
        if let Some(task) = self.task {
            drop_task_common(task, self.driver.borrow().port);
        }
    }
}

impl<'d, T> embedded_io::ErrorType for AsyncUartRxDriver<'d, T>
where
    T: BorrowMut<UartRxDriver<'d>>,
{
    type Error = EspIOError;
}

impl<'d, T> embedded_io_async::Read for AsyncUartRxDriver<'d, T>
where
    T: BorrowMut<UartRxDriver<'d>>,
{
    async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
        AsyncUartRxDriver::read(self, buf).await.map_err(EspIOError)
    }
}

pub struct AsyncUartTxDriver<'d, T>
where
    T: BorrowMut<UartTxDriver<'d>>,
{
    driver: T,
    task: Option<TaskHandle_t>,
    _data: PhantomData<&'d ()>,
}

impl<'d> AsyncUartTxDriver<'d, UartTxDriver<'d>> {
    pub fn new(
        uart: impl Peripheral<P = impl Uart> + 'd,
        tx: impl Peripheral<P = impl OutputPin> + 'd,
        cts: Option<impl Peripheral<P = impl InputPin> + 'd>,
        rts: Option<impl Peripheral<P = impl OutputPin> + 'd>,
        config: &config::Config,
    ) -> Result<Self, EspError> {
        Self::wrap(UartTxDriver::new(uart, tx, cts, rts, config)?)
    }
}

impl<'d, T> AsyncUartTxDriver<'d, T>
where
    T: BorrowMut<UartTxDriver<'d>>,
{
    pub fn wrap(driver: T) -> Result<Self, EspError> {
        Self::wrap_custom(driver, None, None)
    }

    pub fn wrap_custom(
        driver: T,
        priority: Option<u8>,
        pin_to_core: Option<Core>,
    ) -> Result<Self, EspError> {
        let task = new_task_common(
            driver.borrow().port,
            driver.borrow().event_queue(),
            priority,
            pin_to_core,
        )?;

        Ok(Self {
            driver,
            task: Some(task),
            _data: PhantomData,
        })
    }

    pub fn driver(&self) -> &UartTxDriver<'d> {
        self.driver.borrow()
    }

    pub fn driver_mut(&mut self) -> &mut UartTxDriver<'d> {
        self.driver.borrow_mut()
    }

    pub async fn write(&self, bytes: &[u8]) -> Result<usize, EspError> {
        if bytes.is_empty() {
            Ok(0)
        } else {
            loop {
                let res = self.driver.borrow().write_nb(bytes);

                match res {
                    Ok(len) if len > 0 => return Ok(len),
                    Err(e) => return Err(e),
                    _ => (),
                }

                // We cannot properly wait for the TX FIFO queue to become non-full
                // because the ESP IDF UART ISR does not notify us on that
                //
                // Instead, spin a busy loop, however still allowing other futures to be polled too.
                crate::task::yield_now().await;
            }
        }
    }

    pub async fn wait_done(&self) -> Result<(), EspError> {
        loop {
            let res = self.driver.borrow().wait_done(delay::NON_BLOCK);

            match res {
                Ok(()) => return Ok(()),
                Err(e) if e.code() != ESP_ERR_TIMEOUT => return Err(e),
                _ => (),
            }

            // We cannot properly wait for the TX FIFO queue to become empty
            // because the ESP IDF UART ISR does not notify us on that
            //
            // Instead, spin a busy loop, however still allowing other futures to be polled too.
            crate::task::yield_now().await;
        }
    }
}

impl<'d, T> Drop for AsyncUartTxDriver<'d, T>
where
    T: BorrowMut<UartTxDriver<'d>>,
{
    fn drop(&mut self) {
        if let Some(task) = self.task {
            drop_task_common(task, self.driver.borrow().port);
        }
    }
}

impl<'d, T> embedded_io::ErrorType for AsyncUartTxDriver<'d, T>
where
    T: BorrowMut<UartTxDriver<'d>>,
{
    type Error = EspIOError;
}

impl<'d, T> embedded_io_async::Write for AsyncUartTxDriver<'d, T>
where
    T: BorrowMut<UartTxDriver<'d>>,
{
    async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
        AsyncUartTxDriver::write(self, buf)
            .await
            .map_err(EspIOError)
    }

    async fn flush(&mut self) -> Result<(), Self::Error> {
        AsyncUartTxDriver::wait_done(self).await.map_err(EspIOError)
    }
}

fn new_task_common(
    port: u8,
    queue: Option<&Queue<UartEvent>>,
    priority: Option<u8>,
    pin_to_core: Option<Core>,
) -> Result<TaskHandle_t, EspError> {
    if let Some(queue) = queue {
        let port = port as usize;

        unsafe {
            QUEUES[port] = queue.as_raw() as _;
        }

        let res = unsafe {
            task::create(
                process_events,
                CStr::from_bytes_until_nul(b"UART - Events task\0").unwrap(),
                2048,
                port as _,
                priority.unwrap_or(6),
                pin_to_core,
            )
        };

        if res.is_err() {
            unsafe {
                QUEUES[port] = core::ptr::null();
            }
        }

        res
    } else {
        Err(EspError::from_infallible::<ESP_ERR_INVALID_ARG>())
    }
}

fn drop_task_common(task: TaskHandle_t, port: u8) {
    unsafe {
        task::destroy(task);
        QUEUES[port as usize] = core::ptr::null_mut();

        READ_NOTIFS[port as usize].reset();
        WRITE_NOTIFS[port as usize].reset();
        TX_NOTIFS[port as usize].reset();
    }
}

extern "C" fn process_events(arg: *mut core::ffi::c_void) {
    let port: usize = arg as _;
    let queue: Queue<UartEvent> = unsafe { Queue::new_borrowed(QUEUES[port] as _) };

    loop {
        if let Some((event, _)) = queue.recv_front(delay::BLOCK) {
            match event.payload() {
                UartEventPayload::Data { .. }
                | UartEventPayload::RxBufferFull
                | UartEventPayload::RxFifoOverflow => {
                    READ_NOTIFS[port].notify_lsb();
                }
                UartEventPayload::Break | UartEventPayload::DataBreak => {
                    WRITE_NOTIFS[port].notify_lsb();
                    TX_NOTIFS[port].notify_lsb();
                }
                _ => (),
            }
        }
    }
}

fn new_common<UART: Uart>(
    _uart: impl Peripheral<P = UART>,
    tx: Option<impl Peripheral<P = impl OutputPin>>,
    rx: Option<impl Peripheral<P = impl InputPin>>,
    cts: Option<impl Peripheral<P = impl InputPin>>,
    rts: Option<impl Peripheral<P = impl OutputPin>>,
    config: &config::Config,
    queue: Option<&mut QueueHandle_t>,
) -> Result<(), EspError> {
    let tx = tx.map(|tx| tx.into_ref());
    let rx = rx.map(|rx| rx.into_ref());
    let cts = cts.map(|cts| cts.into_ref());
    let rts = rts.map(|rts| rts.into_ref());

    #[allow(clippy::needless_update)]
    let uart_config = uart_config_t {
        baud_rate: config.baudrate.0 as i32,
        data_bits: config.data_bits.into(),
        parity: config.parity.into(),
        stop_bits: config.stop_bits.into(),
        flow_ctrl: config.flow_control.into(),
        rx_flow_ctrl_thresh: config.flow_control_rts_threshold,
        // ESP-IDF 5.0 and 5.1
        #[cfg(all(
            esp_idf_version_major = "5",
            any(esp_idf_version_minor = "0", esp_idf_version_minor = "1")
        ))]
        source_clk: config.source_clock.into(),
        // All others
        #[cfg(not(all(
            esp_idf_version_major = "5",
            any(esp_idf_version_minor = "0", esp_idf_version_minor = "1")
        )))]
        __bindgen_anon_1: uart_config_t__bindgen_ty_1 {
            source_clk: config.source_clock.into(),
        },
        ..Default::default()
    };

    esp!(unsafe { uart_param_config(UART::port(), &uart_config) })?;

    esp!(unsafe {
        uart_set_pin(
            UART::port(),
            tx.as_ref().map_or(-1, |p| p.pin()),
            rx.as_ref().map_or(-1, |p| p.pin()),
            rts.as_ref().map_or(-1, |p| p.pin()),
            cts.as_ref().map_or(-1, |p| p.pin()),
        )
    })?;

    esp!(unsafe {
        uart_driver_install(
            UART::port(),
            if rx.is_some() {
                config.rx_fifo_size as _
            } else {
                0
            },
            if tx.is_some() {
                config.tx_fifo_size as _
            } else {
                0
            },
            config.queue_size as _,
            queue.map(|q| q as *mut _).unwrap_or(ptr::null_mut()),
            InterruptType::to_native(config.intr_flags) as i32,
        )
    })?;

    // Configure interrupts after installing the driver
    // so it won't get overwritten.
    let usr_intrs = config.event_config.clone().into();
    esp!(unsafe { uart_intr_config(UART::port(), &usr_intrs as *const _) })?;

    Ok(())
}

fn stop_bits(port: uart_port_t) -> Result<config::StopBits, EspError> {
    let mut stop_bits: uart_stop_bits_t = 0;
    esp_result!(
        unsafe { uart_get_stop_bits(port, &mut stop_bits) },
        stop_bits.into()
    )
}

fn change_stop_bits(port: uart_port_t, stop_bits: config::StopBits) -> Result<(), EspError> {
    esp!(unsafe { uart_set_stop_bits(port, stop_bits.into()) })
}

fn data_bits(port: uart_port_t) -> Result<config::DataBits, EspError> {
    let mut data_bits: uart_word_length_t = 0;
    esp_result!(
        unsafe { uart_get_word_length(port, &mut data_bits) },
        data_bits.into()
    )
}

fn change_data_bits(port: uart_port_t, data_bits: config::DataBits) -> Result<(), EspError> {
    esp!(unsafe { uart_set_word_length(port, data_bits.into()) })
}

fn parity(port: uart_port_t) -> Result<config::Parity, EspError> {
    let mut parity: uart_parity_t = 0;
    esp_result!(unsafe { uart_get_parity(port, &mut parity) }, parity.into())
}

fn change_parity(port: uart_port_t, parity: config::Parity) -> Result<(), EspError> {
    esp!(unsafe { uart_set_parity(port, parity.into()) })
}

fn baudrate(port: uart_port_t) -> Result<Hertz, EspError> {
    let mut baudrate: u32 = 0;
    esp_result!(
        unsafe { uart_get_baudrate(port, &mut baudrate) },
        baudrate.into()
    )
}

fn change_baudrate<T: Into<Hertz> + Copy>(port: uart_port_t, baudrate: T) -> Result<(), EspError> {
    esp!(unsafe { uart_set_baudrate(port, baudrate.into().into()) })
}

fn delete_driver(port: uart_port_t) -> Result<(), EspError> {
    esp!(unsafe { uart_driver_delete(port) })
}

pub fn remaining_unread_bytes(port: uart_port_t) -> Result<usize, EspError> {
    let mut size = 0;
    esp_result!(unsafe { uart_get_buffered_data_len(port, &mut size) }, size)
}

#[cfg(any(
    not(esp_idf_version_major = "4"),
    all(
        esp_idf_version_minor = "4",
        not(any(esp_idf_version_patch = "0", esp_idf_version_patch = "1")),
    ),
))]
pub fn remaining_write_capacity(port: uart_port_t) -> Result<usize, EspError> {
    let mut size = 0;
    esp_result!(
        unsafe { uart_get_tx_buffer_free_size(port, &mut size) },
        size
    )
}

enum Owner {
    Owned,
    Borrowed,
    Shared,
}

impl Owner {
    fn drop_impl(&self, port: uart_port_t) -> Result<(), EspError> {
        let needs_drop = match self {
            Owner::Owned => true,
            Owner::Borrowed => false,
            Owner::Shared => REFS[port as usize].fetch_sub(1, Ordering::SeqCst) == 0,
        };
        needs_drop.then(|| delete_driver(port)).unwrap_or(Ok(()))
    }
}

macro_rules! impl_uart {
    ($uart:ident: $port:expr) => {
        crate::impl_peripheral!($uart);

        impl Uart for $uart {
            fn port() -> uart_port_t {
                $port
            }
        }
    };
}

fn check_nb<T>(result: Result<usize, EspError>, value: T) -> nb::Result<T, SerialError> {
    match result {
        Ok(len) => {
            if len > 0 {
                Ok(value)
            } else {
                Err(nb::Error::WouldBlock)
            }
        }
        Err(err) if err.code() == ESP_ERR_TIMEOUT => Err(nb::Error::WouldBlock),
        Err(err) => Err(nb::Error::Other(SerialError::new(ErrorKind::Other, err))),
    }
}

fn check_nb_timeout(result: Result<(), EspError>) -> nb::Result<(), SerialError> {
    match result {
        Ok(()) => Ok(()),
        Err(err) if err.code() == ESP_ERR_TIMEOUT => Err(nb::Error::WouldBlock),
        Err(err) => Err(nb::Error::Other(SerialError::new(ErrorKind::Other, err))),
    }
}

impl_uart!(UART0: 0);
impl_uart!(UART1: 1);
#[cfg(any(esp32, esp32s3))]
impl_uart!(UART2: 2);

#[allow(clippy::declare_interior_mutable_const)]
const NO_REFS: AtomicU8 = AtomicU8::new(0);
static REFS: [AtomicU8; SOC_UART_NUM as usize] = [NO_REFS; SOC_UART_NUM as usize];

#[allow(clippy::declare_interior_mutable_const)]
const NOTIF: Notification = Notification::new();
static READ_NOTIFS: [Notification; SOC_UART_NUM as usize] = [NOTIF; SOC_UART_NUM as usize];
static WRITE_NOTIFS: [Notification; SOC_UART_NUM as usize] = [NOTIF; SOC_UART_NUM as usize];
static TX_NOTIFS: [Notification; SOC_UART_NUM as usize] = [NOTIF; SOC_UART_NUM as usize];
static mut QUEUES: [*const core::ffi::c_void; SOC_UART_NUM as usize] =
    [core::ptr::null(); SOC_UART_NUM as usize];