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
//! SPI peripheral control
//!
//! SPI0 is reserved for accessing flash and sram and therefore not usable for other purposes.
//! SPI1 shares its external pins with SPI0 and therefore has severe restrictions in use.
//!
//! SPI2 & 3 can be used freely.
//!
//! The CS pin can be controlled by hardware on esp32 variants (contrary to the description of embedded_hal).
//!
//! Look at the following table to determine which driver best suits your requirements:
//!
//! |   |                  | SpiDeviceDriver::new | SpiDeviceDriver::new (no CS) | SpiSoftCsDeviceDriver::new | SpiBusDriver::new |
//! |---|------------------|----------------------|------------------------------|----------------------------|-------------------|
//! |   | Managed CS       |       Hardware       |              N               |     Software triggered     |         N         |
//! |   | 1 device         |           Y          |              Y               |              Y             |         Y         |
//! |   | 1-3 devices      |           Y          |              N               |              Y             |         N         |
//! |   | 4-6 devices      |    Only on esp32CX   |              N               |              Y             |         N         |
//! |   | More than 6      |           N          |              N               |              Y             |         N         |
//! |   | DMA              |           N          |              N               |              N             |         N         |
//! |   | Polling transmit |           Y          |              Y               |              Y             |         Y         |
//! |   | ISR transmit     |           Y          |              Y               |              Y             |         Y         |
//! |   | Async support*   |           Y          |              Y               |              Y             |         Y         |
//!
//! * True non-blocking async possible only when all devices attached to the SPI bus are used in async mode (i.e. calling methods `xxx_async()`
//!   instead of their blocking `xxx()` counterparts)
//!
//! The [Transfer::transfer], [Write::write] and [WriteIter::write_iter] functions lock the
//! APB frequency and therefore the requests are always run at the requested baudrate.
//! The primitive [FullDuplex::read] and [FullDuplex::send] do not lock the APB frequency and
//! therefore may run at a different frequency.
//!
//! # TODO
//! - Quad SPI
//! - Slave SPI

use core::borrow::{Borrow, BorrowMut};
use core::cell::Cell;
use core::cell::UnsafeCell;
use core::cmp::{max, min, Ordering};
use core::future::Future;
use core::iter::once;
use core::marker::PhantomData;
use core::ptr;

use embassy_sync::mutex::Mutex;
use embedded_hal::spi::{SpiBus, SpiDevice};

use esp_idf_sys::*;
use heapless::Deque;

use crate::delay::{self, Ets, BLOCK};
use crate::gpio::{
    AnyIOPin, AnyOutputPin, InputPin, Level, Output, OutputMode, OutputPin, PinDriver,
};
use crate::interrupt::asynch::HalIsrNotification;
use crate::interrupt::InterruptType;
use crate::peripheral::Peripheral;
use crate::task::embassy_sync::EspRawMutex;
use crate::task::CriticalSection;

pub use embedded_hal::spi::Operation;

crate::embedded_hal_error!(
    SpiError,
    embedded_hal::spi::Error,
    embedded_hal::spi::ErrorKind
);

pub trait Spi: Send {
    fn device() -> spi_host_device_t;
}

/// A marker interface implemented by all SPI peripherals except SPI1 which
/// should use a fixed set of pins
pub trait SpiAnyPins: Spi {}

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Dma {
    Disabled,
    Channel1(usize),
    Channel2(usize),
    Auto(usize),
}

impl From<Dma> for spi_dma_chan_t {
    fn from(dma: Dma) -> Self {
        match dma {
            Dma::Channel1(_) => 1,
            Dma::Channel2(_) => 2,
            Dma::Auto(_) => 3,
            _ => 0,
        }
    }
}

impl Dma {
    pub const fn max_transfer_size(&self) -> usize {
        let max_transfer_size = match self {
            Dma::Disabled => TRANS_LEN,
            Dma::Channel1(size) | Dma::Channel2(size) | Dma::Auto(size) => *size,
        };
        match max_transfer_size {
            0 => panic!("The max transfer size must be greater than 0"),
            x if x % 4 != 0 => panic!("The max transfer size must be a multiple of 4"),
            _ => max_transfer_size,
        }
    }
}

pub type SpiDriverConfig = config::DriverConfig;
pub type SpiConfig = config::Config;

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

    use super::Dma;

    pub use embedded_hal::spi::{Mode, Phase, Polarity, MODE_0, MODE_1, MODE_2, MODE_3};

    pub struct V02Type<T>(pub T);

    impl From<V02Type<embedded_hal_0_2::spi::Polarity>> for Polarity {
        fn from(polarity: V02Type<embedded_hal_0_2::spi::Polarity>) -> Self {
            match polarity.0 {
                embedded_hal_0_2::spi::Polarity::IdleHigh => Polarity::IdleHigh,
                embedded_hal_0_2::spi::Polarity::IdleLow => Polarity::IdleLow,
            }
        }
    }

    impl From<V02Type<embedded_hal_0_2::spi::Phase>> for Phase {
        fn from(phase: V02Type<embedded_hal_0_2::spi::Phase>) -> Self {
            match phase.0 {
                embedded_hal_0_2::spi::Phase::CaptureOnFirstTransition => {
                    Phase::CaptureOnFirstTransition
                }
                embedded_hal_0_2::spi::Phase::CaptureOnSecondTransition => {
                    Phase::CaptureOnSecondTransition
                }
            }
        }
    }

    impl From<V02Type<embedded_hal_0_2::spi::Mode>> for Mode {
        fn from(mode: V02Type<embedded_hal_0_2::spi::Mode>) -> Self {
            Self {
                polarity: V02Type(mode.0.polarity).into(),
                phase: V02Type(mode.0.phase).into(),
            }
        }
    }

    /// Specify the communication mode with the device
    #[derive(Debug, Copy, Clone, Eq, PartialEq)]
    pub enum Duplex {
        /// Full duplex is the default
        Full,
        /// Half duplex in some cases
        Half,
        /// Use MOSI (=spid) for both sending and receiving data (implies half duplex)
        Half3Wire,
    }

    impl Duplex {
        pub fn as_flags(&self) -> u32 {
            match self {
                Duplex::Full => 0,
                Duplex::Half => SPI_DEVICE_HALFDUPLEX,
                Duplex::Half3Wire => SPI_DEVICE_HALFDUPLEX | SPI_DEVICE_3WIRE,
            }
        }
    }

    /// Specifies the order in which the bits of data should be transfered/received
    #[derive(Debug, Copy, Clone, Eq, PartialEq)]
    pub enum BitOrder {
        /// Most significant bit first (default)
        MsbFirst,
        /// Least significant bit first
        LsbFirst,
        /// Least significant bit first, when sending
        TxLsbFirst,
        /// Least significant bit first, when receiving
        RxLsbFirst,
    }

    impl BitOrder {
        pub fn as_flags(&self) -> u32 {
            match self {
                Self::MsbFirst => 0,
                Self::LsbFirst => SPI_DEVICE_BIT_LSBFIRST,
                Self::TxLsbFirst => SPI_DEVICE_TXBIT_LSBFIRST,
                Self::RxLsbFirst => SPI_DEVICE_RXBIT_LSBFIRST,
            }
        }
    }

    /// SPI Driver configuration
    #[derive(Debug, Clone)]
    pub struct DriverConfig {
        pub dma: Dma,
        pub intr_flags: EnumSet<InterruptType>,
    }

    impl DriverConfig {
        pub fn new() -> Self {
            Default::default()
        }

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

        #[must_use]
        pub fn intr_flags(mut self, intr_flags: EnumSet<InterruptType>) -> Self {
            self.intr_flags = intr_flags;
            self
        }
    }

    impl Default for DriverConfig {
        fn default() -> Self {
            Self {
                dma: Dma::Disabled,
                intr_flags: EnumSet::<InterruptType>::empty(),
            }
        }
    }

    /// SPI Device configuration
    #[derive(Debug, Clone)]
    pub struct Config {
        pub baudrate: Hertz,
        pub data_mode: Mode,
        /// This property can be set to configure a SPI Device for being write only
        /// Thus the flag SPI_DEVICE_NO_DUMMY will be passed on initialization and
        /// it will unlock the possibility of using 80Mhz as the bus freq
        /// See https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/spi_master.html#timing-considerations
        pub write_only: bool,
        pub duplex: Duplex,
        pub bit_order: BitOrder,
        pub cs_active_high: bool,
        /// On Half-Duplex transactions: `cs_pre_delay_us % 16`  corresponds to the number of SPI bit-cycles cs should be activated before the transmission.
        /// On Full-Duplex transactions: `cs_pre_delay_us != 0`  will add 1 microsecond of cs activation before transmission
        pub cs_pre_delay_us: Option<u16>, // u16 as per the C struct has a uint16_t, cf: esp-idf/components/driver/spi/include/driver/spi_master.h spi_device_interface_config_t
        ///< Amount of SPI bit-cycles the cs should stay active after the transmission (0-16)
        pub cs_post_delay_us: Option<u8>, // u8 as per the C struct had a uint8_t, cf: esp-idf/components/driver/spi/include/driver/spi_master.h spi_device_interface_config_t
        pub input_delay_ns: i32,
        pub polling: bool,
        pub allow_pre_post_delays: bool,
        pub queue_size: usize,
    }

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

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

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

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

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

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

        #[must_use]
        pub fn cs_active_high(mut self) -> Self {
            self.cs_active_high = true;
            self
        }

        /// On Half-Duplex transactions: `cs_pre_delay_us % 16`  corresponds to the number of SPI bit-cycles cs should be activated before the transmission
        /// On Full-Duplex transactions: `cs_pre_delay_us != 0`  will add 1 microsecond of cs activation before transmission
        #[must_use]
        pub fn cs_pre_delay_us(mut self, delay_us: u16) -> Self {
            self.cs_pre_delay_us = Some(delay_us);
            self
        }

        /// Add an aditional Amount of SPI bit-cycles the cs should be activated after the transmission (0-16).
        /// This only works on half-duplex transactions.
        #[must_use]
        pub fn cs_post_delay_us(mut self, delay_us: u8) -> Self {
            self.cs_post_delay_us = Some(delay_us);
            self
        }

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

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

        #[must_use]
        pub fn allow_pre_post_delays(mut self, allow_pre_post_delays: bool) -> Self {
            self.allow_pre_post_delays = allow_pre_post_delays;
            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() -> Self {
            Self {
                baudrate: Hertz(1_000_000),
                data_mode: embedded_hal::spi::MODE_0,
                write_only: false,
                cs_active_high: false,
                duplex: Duplex::Full,
                bit_order: BitOrder::MsbFirst,
                cs_pre_delay_us: None,
                cs_post_delay_us: None,
                input_delay_ns: 0,
                polling: true,
                allow_pre_post_delays: false,
                queue_size: 1,
            }
        }
    }
}

pub struct SpiDriver<'d> {
    host: u8,
    max_transfer_size: usize,
    #[allow(dead_code)]
    bus_async_lock: Mutex<EspRawMutex, ()>,
    _p: PhantomData<&'d mut ()>,
}

impl<'d> SpiDriver<'d> {
    /// Create new instance of SPI controller for SPI1
    ///
    /// SPI1 can only use fixed pin for SCLK, SDO and SDI as they are shared with SPI0.
    #[cfg(esp32)]
    pub fn new_spi1(
        _spi: impl Peripheral<P = SPI1> + 'd,
        sclk: impl Peripheral<P = crate::gpio::Gpio6> + 'd,
        sdo: impl Peripheral<P = crate::gpio::Gpio7> + 'd,
        sdi: Option<impl Peripheral<P = crate::gpio::Gpio8> + 'd>,
        config: &config::DriverConfig,
    ) -> Result<Self, EspError> {
        let max_transfer_size = Self::new_internal(SPI1::device(), Some(sclk), sdo, sdi, config)?;

        Ok(Self {
            host: SPI1::device() as _,
            max_transfer_size,
            bus_async_lock: Mutex::new(()),
            _p: PhantomData,
        })
    }

    /// Create new instance of SPI controller for all others
    pub fn new<SPI: SpiAnyPins>(
        _spi: impl Peripheral<P = SPI> + 'd,
        sclk: impl Peripheral<P = impl OutputPin> + 'd,
        sdo: impl Peripheral<P = impl OutputPin> + 'd,
        sdi: Option<impl Peripheral<P = impl InputPin> + 'd>,
        config: &config::DriverConfig,
    ) -> Result<Self, EspError> {
        let max_transfer_size = Self::new_internal(SPI::device(), Some(sclk), sdo, sdi, config)?;

        Ok(Self {
            host: SPI::device() as _,
            max_transfer_size,
            bus_async_lock: Mutex::new(()),
            _p: PhantomData,
        })
    }

    pub fn new_without_sclk<SPI: SpiAnyPins>(
        _spi: impl Peripheral<P = SPI> + 'd,
        sdo: impl Peripheral<P = impl OutputPin> + 'd,
        sdi: Option<impl Peripheral<P = impl InputPin> + 'd>,
        config: &config::DriverConfig,
    ) -> Result<Self, EspError> {
        let max_transfer_size =
            Self::new_internal(SPI::device(), Option::<AnyIOPin>::None, sdo, sdi, config)?;

        Ok(Self {
            host: SPI::device() as _,
            max_transfer_size,
            bus_async_lock: Mutex::new(()),
            _p: PhantomData,
        })
    }

    pub fn host(&self) -> spi_host_device_t {
        self.host as _
    }

    fn new_internal(
        host: spi_host_device_t,
        sclk: Option<impl Peripheral<P = impl OutputPin> + 'd>,
        sdo: impl Peripheral<P = impl OutputPin> + 'd,
        sdi: Option<impl Peripheral<P = impl InputPin> + 'd>,
        config: &config::DriverConfig,
    ) -> Result<usize, EspError> {
        let sdo = sdo.into_ref();
        let sdi = sdi.map(|sdi| sdi.into_ref());
        let sclk = sclk.map(|sclk| sclk.into_ref());

        let max_transfer_sz = config.dma.max_transfer_size();
        let dma_chan: spi_dma_chan_t = config.dma.into();

        #[allow(clippy::needless_update)]
        let bus_config = spi_bus_config_t {
            flags: SPICOMMON_BUSFLAG_MASTER,
            sclk_io_num: sclk.as_ref().map_or(-1, |p| p.pin()),

            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 {
                mosi_io_num: sdo.pin(),
                //data0_io_num: -1,
            },
            __bindgen_anon_2: spi_bus_config_t__bindgen_ty_2 {
                miso_io_num: sdi.as_ref().map_or(-1, |p| p.pin()),
                //data1_io_num: -1,
            },
            __bindgen_anon_3: spi_bus_config_t__bindgen_ty_3 {
                quadwp_io_num: -1,
                //data2_io_num: -1,
            },
            __bindgen_anon_4: spi_bus_config_t__bindgen_ty_4 {
                quadhd_io_num: -1,
                //data3_io_num: -1,
            },
            max_transfer_sz: max_transfer_sz as i32,
            intr_flags: InterruptType::to_native(config.intr_flags) as _,
            ..Default::default()
        };

        esp!(unsafe { spi_bus_initialize(host, &bus_config, dma_chan) })?;

        Ok(max_transfer_sz)
    }
}

impl<'d> Drop for SpiDriver<'d> {
    fn drop(&mut self) {
        esp!(unsafe { spi_bus_free(self.host()) }).unwrap();
    }
}

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

pub struct SpiBusDriver<'d, T>
where
    T: BorrowMut<SpiDriver<'d>>,
{
    _lock: BusLock,
    handle: spi_device_handle_t,
    driver: T,
    polling: bool,
    queue_size: usize,
    _d: PhantomData<&'d ()>,
}

impl<'d, T> SpiBusDriver<'d, T>
where
    T: BorrowMut<SpiDriver<'d>>,
{
    pub fn new(driver: T, config: &config::Config) -> Result<Self, EspError> {
        let conf = spi_device_interface_config_t {
            spics_io_num: -1,
            clock_speed_hz: config.baudrate.0 as i32,
            mode: data_mode_to_u8(config.data_mode),
            queue_size: config.queue_size as i32,
            flags: if config.write_only {
                SPI_DEVICE_NO_DUMMY
            } else {
                0_u32
            } | config.duplex.as_flags()
                | config.bit_order.as_flags(),
            cs_ena_pretrans: config.cs_pre_delay_us.unwrap_or(0),
            cs_ena_posttrans: config.cs_post_delay_us.unwrap_or(0),
            post_cb: Some(spi_notify),
            ..Default::default()
        };

        let mut handle: spi_device_handle_t = ptr::null_mut();
        esp!(unsafe { spi_bus_add_device(driver.borrow().host(), &conf, &mut handle as *mut _) })?;

        let lock = BusLock::new(handle)?;

        Ok(Self {
            _lock: lock,
            handle,
            driver,
            polling: config.polling,
            queue_size: config.queue_size,
            _d: PhantomData,
        })
    }

    pub fn read(&mut self, words: &mut [u8]) -> Result<(), EspError> {
        // Full-Duplex Mode:
        // The internal hardware 16*4 u8 FIFO buffer (shared for read/write) is not cleared
        // between transactions (read/write/transfer)
        // This can lead to rewriting the internal buffer to MOSI on a read call

        let chunk_size = self.driver.borrow().max_transfer_size;

        let transactions = spi_read_transactions(words, chunk_size);
        spi_transmit(self.handle, transactions, self.polling, self.queue_size)?;

        Ok(())
    }

    #[cfg(not(esp_idf_spi_master_isr_in_iram))]
    pub async fn read_async(&mut self, words: &mut [u8]) -> Result<(), EspError> {
        let chunk_size = self.driver.borrow().max_transfer_size;

        let transactions = spi_read_transactions(words, chunk_size);
        core::pin::pin!(spi_transmit_async(
            self.handle,
            transactions,
            self.queue_size
        ))
        .await?;

        Ok(())
    }

    pub fn write(&mut self, words: &[u8]) -> Result<(), EspError> {
        // Full-Duplex Mode:
        // The internal hardware 16*4 u8 FIFO buffer (shared for read/write) is not cleared
        // between transactions ( read/write/transfer)
        // This can lead to re-reading the last internal buffer MOSI msg, in case the Slave fails to send a msg

        let chunk_size = self.driver.borrow().max_transfer_size;

        let transactions = spi_write_transactions(words, chunk_size);
        spi_transmit(self.handle, transactions, self.polling, self.queue_size)?;

        Ok(())
    }

    #[cfg(not(esp_idf_spi_master_isr_in_iram))]
    pub async fn write_async(&mut self, words: &[u8]) -> Result<(), EspError> {
        let chunk_size = self.driver.borrow().max_transfer_size;

        let transactions = spi_write_transactions(words, chunk_size);
        core::pin::pin!(spi_transmit_async(
            self.handle,
            transactions,
            self.queue_size
        ))
        .await?;

        Ok(())
    }

    pub fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), EspError> {
        // In non-DMA mode, it will internally split the transfers every 64 bytes (max_transf_len).
        // - If the read and write buffers are not of the same length, it will first transfer the common buffer length
        // and then (separately aligned) the remaining buffer.
        // - Expect a delay time between every internally split (64-byte or remainder) package.

        // Half-Duplex & Half-3-Duplex Mode:
        // Data will be split into 64-byte write/read sections.
        // Example: write: [u8;96] - read [u8; 160]
        // Package 1: write 64, read 64 -> Package 2: write 32, read 32 -> Package 3: write 0, read 64.
        // Note that the first "package" is a 128-byte clock out while the later are respectively 64 bytes.

        let chunk_size = self.driver.borrow().max_transfer_size;

        let transactions = spi_transfer_transactions(read, write, chunk_size);
        spi_transmit(self.handle, transactions, self.polling, self.queue_size)?;

        Ok(())
    }

    #[cfg(not(esp_idf_spi_master_isr_in_iram))]
    pub async fn transfer_async(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), EspError> {
        let chunk_size = self.driver.borrow().max_transfer_size;

        let transactions = spi_transfer_transactions(read, write, chunk_size);
        core::pin::pin!(spi_transmit_async(
            self.handle,
            transactions,
            self.queue_size
        ))
        .await?;

        Ok(())
    }

    pub fn transfer_in_place(&mut self, words: &mut [u8]) -> Result<(), EspError> {
        let chunk_size = self.driver.borrow().max_transfer_size;

        let transactions = spi_transfer_in_place_transactions(words, chunk_size);
        spi_transmit(self.handle, transactions, self.polling, self.queue_size)?;

        Ok(())
    }

    #[cfg(not(esp_idf_spi_master_isr_in_iram))]
    pub async fn transfer_in_place_async(&mut self, words: &mut [u8]) -> Result<(), EspError> {
        let chunk_size = self.driver.borrow().max_transfer_size;

        let transactions = spi_transfer_in_place_transactions(words, chunk_size);
        core::pin::pin!(spi_transmit_async(
            self.handle,
            transactions,
            self.queue_size
        ))
        .await?;

        Ok(())
    }

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

impl<'d, T> Drop for SpiBusDriver<'d, T>
where
    T: BorrowMut<SpiDriver<'d>>,
{
    fn drop(&mut self) {
        esp!(unsafe { spi_bus_remove_device(self.handle) }).unwrap();
    }
}

impl<'d, T> embedded_hal::spi::ErrorType for SpiBusDriver<'d, T>
where
    T: BorrowMut<SpiDriver<'d>>,
{
    type Error = SpiError;
}

impl<'d, T> SpiBus for SpiBusDriver<'d, T>
where
    T: BorrowMut<SpiDriver<'d>>,
{
    fn read(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
        SpiBusDriver::read(self, words).map_err(to_spi_err)
    }

    fn write(&mut self, words: &[u8]) -> Result<(), Self::Error> {
        SpiBusDriver::write(self, words).map_err(to_spi_err)
    }

    fn flush(&mut self) -> Result<(), Self::Error> {
        SpiBusDriver::flush(self).map_err(to_spi_err)
    }

    fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), Self::Error> {
        SpiBusDriver::transfer(self, read, write).map_err(to_spi_err)
    }

    fn transfer_in_place(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
        SpiBusDriver::transfer_in_place(self, words).map_err(to_spi_err)
    }
}

#[cfg(not(esp_idf_spi_master_isr_in_iram))]
impl<'d, T> embedded_hal_async::spi::SpiBus for SpiBusDriver<'d, T>
where
    T: BorrowMut<SpiDriver<'d>>,
{
    async fn read(&mut self, buf: &mut [u8]) -> Result<(), Self::Error> {
        SpiBusDriver::read_async(self, buf)
            .await
            .map_err(to_spi_err)
    }

    async fn write(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
        SpiBusDriver::write_async(self, buf)
            .await
            .map_err(to_spi_err)
    }

    async fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), Self::Error> {
        SpiBusDriver::transfer_async(self, read, write)
            .await
            .map_err(to_spi_err)
    }

    async fn transfer_in_place(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
        SpiBusDriver::transfer_in_place_async(self, words)
            .await
            .map_err(to_spi_err)
    }

    async fn flush(&mut self) -> Result<(), Self::Error> {
        SpiBusDriver::flush(self).map_err(to_spi_err)
    }
}

enum SpiOperation {
    Transaction(spi_transaction_t),
    Delay(u32),
}

impl SpiOperation {
    pub fn transaction(self) -> Option<spi_transaction_t> {
        if let Self::Transaction(transaction) = self {
            Some(transaction)
        } else {
            None
        }
    }
}

pub type SpiSingleDeviceDriver<'d> = SpiDeviceDriver<'d, SpiDriver<'d>>;

pub struct SpiDeviceDriver<'d, T>
where
    T: Borrow<SpiDriver<'d>> + 'd,
{
    handle: spi_device_handle_t,
    driver: T,
    cs_pin_configured: bool,
    polling: bool,
    allow_pre_post_delays: bool,
    queue_size: usize,
    _d: PhantomData<&'d ()>,
}

impl<'d> SpiDeviceDriver<'d, SpiDriver<'d>> {
    #[cfg(esp32)]
    pub fn new_single_spi1(
        spi: impl Peripheral<P = SPI1> + 'd,
        sclk: impl Peripheral<P = crate::gpio::Gpio6> + 'd,
        sdo: impl Peripheral<P = crate::gpio::Gpio7> + 'd,
        sdi: Option<impl Peripheral<P = crate::gpio::Gpio8> + 'd>,
        cs: Option<impl Peripheral<P = impl OutputPin> + 'd>,
        bus_config: &config::DriverConfig,
        config: &config::Config,
    ) -> Result<Self, EspError> {
        Self::new(
            SpiDriver::new_spi1(spi, sclk, sdo, sdi, bus_config)?,
            cs,
            config,
        )
    }

    pub fn new_single<SPI: SpiAnyPins>(
        spi: impl Peripheral<P = SPI> + 'd,
        sclk: impl Peripheral<P = impl OutputPin> + 'd,
        sdo: impl Peripheral<P = impl OutputPin> + 'd,
        sdi: Option<impl Peripheral<P = impl InputPin> + 'd>,
        cs: Option<impl Peripheral<P = impl OutputPin> + 'd>,
        bus_config: &config::DriverConfig,
        config: &config::Config,
    ) -> Result<Self, EspError> {
        Self::new(SpiDriver::new(spi, sclk, sdo, sdi, bus_config)?, cs, config)
    }
}

impl<'d, T> SpiDeviceDriver<'d, T>
where
    T: Borrow<SpiDriver<'d>> + 'd,
{
    pub fn new(
        driver: T,
        cs: Option<impl Peripheral<P = impl OutputPin> + 'd>,
        config: &config::Config,
    ) -> Result<Self, EspError> {
        let cs = cs.map(|cs| cs.into_ref().pin()).unwrap_or(-1);

        let conf = spi_device_interface_config_t {
            spics_io_num: cs,
            clock_speed_hz: config.baudrate.0 as i32,
            mode: data_mode_to_u8(config.data_mode),
            queue_size: config.queue_size as i32,
            input_delay_ns: config.input_delay_ns,
            flags: if config.write_only {
                SPI_DEVICE_NO_DUMMY
            } else {
                0_u32
            } | if config.cs_active_high {
                SPI_DEVICE_POSITIVE_CS
            } else {
                0_u32
            } | config.duplex.as_flags()
                | config.bit_order.as_flags(),
            post_cb: Some(spi_notify),
            cs_ena_pretrans: config.cs_pre_delay_us.unwrap_or(0),
            cs_ena_posttrans: config.cs_post_delay_us.unwrap_or(0),
            ..Default::default()
        };

        let mut handle: spi_device_handle_t = ptr::null_mut();
        esp!(unsafe { spi_bus_add_device(driver.borrow().host(), &conf, &mut handle as *mut _) })?;

        Ok(Self {
            handle,
            driver,
            cs_pin_configured: cs >= 0,
            polling: config.polling,
            allow_pre_post_delays: config.allow_pre_post_delays,
            queue_size: config.queue_size,
            _d: PhantomData,
        })
    }

    pub fn device(&self) -> spi_device_handle_t {
        self.handle
    }

    pub fn transaction(&mut self, operations: &mut [Operation<'_, u8>]) -> Result<(), EspError> {
        self.run(
            self.hardware_cs_ctl(operations.iter_mut().map(copy_operation))?,
            operations.iter_mut().map(copy_operation),
        )
    }

    #[cfg(not(esp_idf_spi_master_isr_in_iram))]
    pub async fn transaction_async(
        &mut self,
        operations: &mut [Operation<'_, u8>],
    ) -> Result<(), EspError> {
        core::pin::pin!(self.run_async(
            self.hardware_cs_ctl(operations.iter_mut().map(copy_operation))?,
            operations.iter_mut().map(copy_operation),
        ))
        .await
    }

    pub fn read(&mut self, read: &mut [u8]) -> Result<(), EspError> {
        self.transaction(&mut [Operation::Read(read)])
    }

    #[cfg(not(esp_idf_spi_master_isr_in_iram))]
    pub async fn read_async(&mut self, read: &mut [u8]) -> Result<(), EspError> {
        core::pin::pin!(self.transaction_async(&mut [Operation::Read(read)])).await
    }

    pub fn write(&mut self, write: &[u8]) -> Result<(), EspError> {
        self.transaction(&mut [Operation::Write(write)])
    }

    #[cfg(not(esp_idf_spi_master_isr_in_iram))]
    pub async fn write_async(&mut self, write: &[u8]) -> Result<(), EspError> {
        core::pin::pin!(self.transaction_async(&mut [Operation::Write(write)])).await
    }

    pub fn transfer_in_place(&mut self, buf: &mut [u8]) -> Result<(), EspError> {
        self.transaction(&mut [Operation::TransferInPlace(buf)])
    }

    #[cfg(not(esp_idf_spi_master_isr_in_iram))]
    pub async fn transfer_in_place_async(&mut self, buf: &mut [u8]) -> Result<(), EspError> {
        core::pin::pin!(self.transaction_async(&mut [Operation::TransferInPlace(buf)])).await
    }

    pub fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), EspError> {
        self.transaction(&mut [Operation::Transfer(read, write)])
    }

    #[cfg(not(esp_idf_spi_master_isr_in_iram))]
    pub async fn transfer_async(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), EspError> {
        core::pin::pin!(self.transaction_async(&mut [Operation::Transfer(read, write)])).await
    }

    fn run<'a, 'c, 'p, P, M>(
        &mut self,
        mut cs_pin: CsCtl<'c, 'p, P, M>,
        operations: impl Iterator<Item = Operation<'a, u8>> + 'a,
    ) -> Result<(), EspError>
    where
        P: OutputPin,
        M: OutputMode,
    {
        let _lock = if cs_pin.needs_bus_lock() {
            Some(BusLock::new(self.device())?)
        } else {
            None
        };

        cs_pin.raise_cs()?;

        let mut spi_operations = self
            .spi_operations(operations)
            .enumerate()
            .map(|(index, mut operation)| {
                cs_pin.configure(&mut operation, index);
                operation
            })
            .peekable();

        let delay_impl = crate::delay::Delay::new_default();
        let mut result = Ok(());

        while spi_operations.peek().is_some() {
            if let Some(SpiOperation::Delay(delay)) = spi_operations.peek() {
                delay_impl.delay_us(*delay / 1000);
                spi_operations.next();
            } else {
                let transactions = core::iter::from_fn(|| {
                    spi_operations
                        .next_if(|operation| matches!(operation, SpiOperation::Transaction(_)))
                })
                .fuse()
                .filter_map(|operation| operation.transaction());

                result = spi_transmit(self.handle, transactions, self.polling, self.queue_size);

                if result.is_err() {
                    break;
                }
            }
        }

        cs_pin.lower_cs()?;

        result
    }

    #[allow(dead_code)]
    async fn run_async<'a, 'c, 'p, P, M>(
        &self,
        mut cs_pin: CsCtl<'c, 'p, P, M>,
        operations: impl Iterator<Item = Operation<'a, u8>> + 'a,
    ) -> Result<(), EspError>
    where
        P: OutputPin,
        M: OutputMode,
    {
        let _async_bus_lock = if cs_pin.needs_bus_lock() {
            Some(self.driver.borrow().bus_async_lock.lock().await)
        } else {
            None
        };

        let _lock = if cs_pin.needs_bus_lock() {
            Some(BusLock::new(self.device())?)
        } else {
            None
        };

        cs_pin.raise_cs()?;

        let delay_impl = crate::delay::Delay::new_default(); // TODO: Need to wait asnchronously if in async mode
        let mut result = Ok(());

        let mut spi_operations = self
            .spi_operations(operations)
            .enumerate()
            .map(|(index, mut operation)| {
                cs_pin.configure(&mut operation, index);
                operation
            })
            .peekable();

        while spi_operations.peek().is_some() {
            if let Some(SpiOperation::Delay(delay)) = spi_operations.peek() {
                delay_impl.delay_us(*delay);
                spi_operations.next();
            } else {
                let transactions = core::iter::from_fn(|| {
                    spi_operations
                        .next_if(|operation| matches!(operation, SpiOperation::Transaction(_)))
                })
                .fuse()
                .filter_map(|operation| operation.transaction());

                result = core::pin::pin!(spi_transmit_async(
                    self.handle,
                    transactions,
                    self.queue_size
                ))
                .await;

                if result.is_err() {
                    break;
                }
            }
        }

        cs_pin.lower_cs()?;

        result
    }

    fn hardware_cs_ctl<'a, 'c, 'p>(
        &self,
        operations: impl Iterator<Item = Operation<'a, u8>> + 'a,
    ) -> Result<CsCtl<'c, 'p, AnyOutputPin, Output>, EspError> {
        let (total_count, transactions_count, first_transaction, last_transaction) =
            self.spi_operations_stats(operations);

        if !self.allow_pre_post_delays
            && self.cs_pin_configured
            && transactions_count > 0
            && (first_transaction != Some(0) || last_transaction != Some(total_count - 1))
        {
            Err(EspError::from_infallible::<ESP_ERR_INVALID_ARG>())?;
        }

        Ok(CsCtl::Hardware {
            enabled: self.cs_pin_configured,
            transactions_count,
            last_transaction,
        })
    }

    fn spi_operations_stats<'a>(
        &self,
        operations: impl Iterator<Item = Operation<'a, u8>> + 'a,
    ) -> (usize, usize, Option<usize>, Option<usize>) {
        self.spi_operations(operations).enumerate().fold(
            (0, 0, None, None),
            |(total_count, transactions_count, first_transaction, last_transaction),
             (index, operation)| {
                if matches!(operation, SpiOperation::Transaction(_)) {
                    (
                        total_count + 1,
                        transactions_count + 1,
                        Some(first_transaction.unwrap_or(index)),
                        Some(index),
                    )
                } else {
                    (
                        total_count + 1,
                        transactions_count,
                        first_transaction,
                        last_transaction,
                    )
                }
            },
        )
    }

    fn spi_operations<'a>(
        &self,
        operations: impl Iterator<Item = Operation<'a, u8>> + 'a,
    ) -> impl Iterator<Item = SpiOperation> + 'a {
        enum OperationsIter<R, W, T, I, D> {
            Read(R),
            Write(W),
            Transfer(T),
            TransferInPlace(I),
            Delay(D),
        }

        impl<R, W, T, I, D> Iterator for OperationsIter<R, W, T, I, D>
        where
            R: Iterator<Item = SpiOperation>,
            W: Iterator<Item = SpiOperation>,
            T: Iterator<Item = SpiOperation>,
            I: Iterator<Item = SpiOperation>,
            D: Iterator<Item = SpiOperation>,
        {
            type Item = SpiOperation;

            fn next(&mut self) -> Option<Self::Item> {
                match self {
                    Self::Read(iter) => iter.next(),
                    Self::Write(iter) => iter.next(),
                    Self::Transfer(iter) => iter.next(),
                    Self::TransferInPlace(iter) => iter.next(),
                    Self::Delay(iter) => iter.next(),
                }
            }
        }

        let chunk_size = self.driver.borrow().max_transfer_size;

        operations.flat_map(move |op| match op {
            Operation::Read(words) => OperationsIter::Read(
                spi_read_transactions(words, chunk_size).map(SpiOperation::Transaction),
            ),
            Operation::Write(words) => OperationsIter::Write(
                spi_write_transactions(words, chunk_size).map(SpiOperation::Transaction),
            ),
            Operation::Transfer(read, write) => OperationsIter::Transfer(
                spi_transfer_transactions(read, write, chunk_size).map(SpiOperation::Transaction),
            ),
            Operation::TransferInPlace(words) => OperationsIter::TransferInPlace(
                spi_transfer_in_place_transactions(words, chunk_size)
                    .map(SpiOperation::Transaction),
            ),
            Operation::DelayNs(delay) => {
                OperationsIter::Delay(core::iter::once(SpiOperation::Delay(delay)))
            }
        })
    }
}

impl<'d, T> Drop for SpiDeviceDriver<'d, T>
where
    T: Borrow<SpiDriver<'d>> + 'd,
{
    fn drop(&mut self) {
        esp!(unsafe { spi_bus_remove_device(self.handle) }).unwrap();
    }
}

unsafe impl<'d, T> Send for SpiDeviceDriver<'d, T> where T: Send + Borrow<SpiDriver<'d>> + 'd {}

impl<'d, T> embedded_hal::spi::ErrorType for SpiDeviceDriver<'d, T>
where
    T: Borrow<SpiDriver<'d>> + 'd,
{
    type Error = SpiError;
}

impl<'d, T> SpiDevice for SpiDeviceDriver<'d, T>
where
    T: Borrow<SpiDriver<'d>> + 'd,
{
    fn read(&mut self, buf: &mut [u8]) -> Result<(), Self::Error> {
        Self::read(self, buf).map_err(to_spi_err)
    }

    fn write(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
        Self::write(self, buf).map_err(to_spi_err)
    }

    fn transaction(&mut self, operations: &mut [Operation<'_, u8>]) -> Result<(), Self::Error> {
        Self::transaction(self, operations).map_err(to_spi_err)
    }
}

impl<'d, T> embedded_hal_0_2::blocking::spi::Transfer<u8> for SpiDeviceDriver<'d, T>
where
    T: Borrow<SpiDriver<'d>> + 'd,
{
    type Error = SpiError;

    fn transfer<'w>(&mut self, words: &'w mut [u8]) -> Result<&'w [u8], Self::Error> {
        self.transfer_in_place(words)?;

        Ok(words)
    }
}

impl<'d, T> embedded_hal_0_2::blocking::spi::Write<u8> for SpiDeviceDriver<'d, T>
where
    T: Borrow<SpiDriver<'d>> + 'd,
{
    type Error = SpiError;

    fn write(&mut self, words: &[u8]) -> Result<(), Self::Error> {
        self.write(words).map_err(to_spi_err)
    }
}

/// All data is chunked into max(iter.len(), 64)
impl<'d, T> embedded_hal_0_2::blocking::spi::WriteIter<u8> for SpiDeviceDriver<'d, T>
where
    T: Borrow<SpiDriver<'d>> + 'd,
{
    type Error = SpiError;

    fn write_iter<WI>(&mut self, words: WI) -> Result<(), Self::Error>
    where
        WI: IntoIterator<Item = u8>,
    {
        let mut lock = None;

        let mut words = words.into_iter().peekable();
        let mut buf = [0_u8; TRANS_LEN];

        loop {
            let mut offset = 0_usize;

            while offset < buf.len() {
                if let Some(word) = words.next() {
                    buf[offset] = word;
                    offset += 1;
                } else {
                    break;
                }
            }

            if offset == 0 {
                break;
            }

            let mut transaction =
                spi_create_transaction(core::ptr::null_mut(), buf[..offset].as_ptr(), offset, 0);

            if lock.is_none() && words.peek().is_some() {
                lock = Some(BusLock::new(self.handle)?);
            }

            set_keep_cs_active(
                &mut transaction,
                self.cs_pin_configured && words.peek().is_some(),
            );

            spi_transmit(
                self.handle,
                once(transaction),
                self.polling,
                self.queue_size,
            )?;
        }

        Ok(())
    }
}

impl<'d, T> embedded_hal_0_2::blocking::spi::Transactional<u8> for SpiDeviceDriver<'d, T>
where
    T: Borrow<SpiDriver<'d>> + 'd,
{
    type Error = SpiError;

    fn exec(
        &mut self,
        operations: &mut [embedded_hal_0_2::blocking::spi::Operation<'_, u8>],
    ) -> Result<(), Self::Error> {
        self.run(
            self.hardware_cs_ctl(operations.iter_mut().map(|op| match op {
                embedded_hal_0_2::blocking::spi::Operation::Write(words) => Operation::Write(words),
                embedded_hal_0_2::blocking::spi::Operation::Transfer(words) => {
                    Operation::TransferInPlace(words)
                }
            }))?,
            operations.iter_mut().map(|op| match op {
                embedded_hal_0_2::blocking::spi::Operation::Write(words) => Operation::Write(words),
                embedded_hal_0_2::blocking::spi::Operation::Transfer(words) => {
                    Operation::TransferInPlace(words)
                }
            }),
        )
        .map_err(to_spi_err)
    }
}

#[cfg(not(esp_idf_spi_master_isr_in_iram))]
impl<'d, T> embedded_hal_async::spi::SpiDevice for SpiDeviceDriver<'d, T>
where
    T: Borrow<SpiDriver<'d>> + 'd,
{
    async fn read(&mut self, buf: &mut [u8]) -> Result<(), Self::Error> {
        Self::read_async(self, buf).await.map_err(to_spi_err)
    }

    async fn write(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
        Self::write_async(self, buf).await.map_err(to_spi_err)
    }

    async fn transaction(
        &mut self,
        operations: &mut [Operation<'_, u8>],
    ) -> Result<(), Self::Error> {
        Self::transaction_async(self, operations)
            .await
            .map_err(to_spi_err)
    }
}

pub struct SpiSharedDeviceDriver<'d, T>
where
    T: Borrow<SpiDriver<'d>> + 'd,
{
    driver: UnsafeCell<SpiDeviceDriver<'d, T>>,
    lock: CriticalSection,
    #[allow(dead_code)]
    async_lock: Mutex<EspRawMutex, ()>,
}

impl<'d, T> SpiSharedDeviceDriver<'d, T>
where
    T: Borrow<SpiDriver<'d>> + 'd,
{
    pub fn new(driver: T, config: &config::Config) -> Result<Self, EspError> {
        Ok(Self::wrap(SpiDeviceDriver::new(
            driver,
            Option::<AnyOutputPin>::None,
            config,
        )?))
    }

    pub const fn wrap(device: SpiDeviceDriver<'d, T>) -> Self {
        Self {
            driver: UnsafeCell::new(device),
            lock: CriticalSection::new(),
            async_lock: Mutex::new(()),
        }
    }

    pub fn lock<R>(&self, f: impl FnOnce(&mut SpiDeviceDriver<'d, T>) -> R) -> R {
        let _guard = self.lock.enter();

        let device = unsafe { self.driver_mut() };

        f(device)
    }

    pub fn release(self) -> SpiDeviceDriver<'d, T> {
        self.driver.into_inner()
    }

    #[allow(clippy::mut_from_ref)]
    unsafe fn driver_mut(&self) -> &mut SpiDeviceDriver<'d, T> {
        &mut *self.driver.get()
    }
}

pub struct SpiSoftCsDeviceDriver<'d, DEVICE, DRIVER> {
    shared_device: DEVICE,
    cs_pin: PinDriver<'d, AnyOutputPin, Output>,
    pre_delay_us: Option<u32>,
    post_delay_us: Option<u32>,
    _p: PhantomData<fn() -> DRIVER>,
}

impl<'d, DEVICE, DRIVER> SpiSoftCsDeviceDriver<'d, DEVICE, DRIVER>
where
    DEVICE: Borrow<SpiSharedDeviceDriver<'d, DRIVER>>,
    DRIVER: Borrow<SpiDriver<'d>> + 'd,
{
    pub fn new(
        shared_device: DEVICE,
        cs: impl Peripheral<P = impl OutputPin> + 'd,
        cs_level: Level,
    ) -> Result<Self, EspError> {
        crate::into_ref!(cs);

        let mut cs_pin: PinDriver<AnyOutputPin, Output> = PinDriver::output(cs.map_into())?;

        cs_pin.set_level(cs_level)?;

        Ok(Self {
            shared_device,
            cs_pin,
            pre_delay_us: None,
            post_delay_us: None,
            _p: PhantomData,
        })
    }

    /// Add an aditional Amount of SPI bit-cycles the cs should be activated before the transmission (0-16).
    /// This only works on half-duplex transactions.
    pub fn cs_pre_delay_us(&mut self, delay_us: u32) -> &mut Self {
        self.pre_delay_us = Some(delay_us);

        self
    }

    /// Add an aditional delay of x in uSeconds after transaction
    /// between last clk out and chip select
    pub fn cs_post_delay_us(&mut self, delay_us: u32) -> &mut Self {
        self.post_delay_us = Some(delay_us);

        self
    }

    pub fn transaction(&mut self, operations: &mut [Operation<'_, u8>]) -> Result<(), EspError> {
        self.run(operations.iter_mut().map(copy_operation))
    }

    #[cfg(not(esp_idf_spi_master_isr_in_iram))]
    pub async fn transaction_async(
        &mut self,
        operations: &mut [Operation<'_, u8>],
    ) -> Result<(), EspError> {
        core::pin::pin!(self.run_async(operations.iter_mut().map(copy_operation))).await
    }

    pub fn read(&mut self, read: &mut [u8]) -> Result<(), EspError> {
        self.transaction(&mut [Operation::Read(read)])
    }

    #[cfg(not(esp_idf_spi_master_isr_in_iram))]
    pub async fn read_async(&mut self, read: &mut [u8]) -> Result<(), EspError> {
        core::pin::pin!(self.transaction_async(&mut [Operation::Read(read)])).await
    }

    pub fn write(&mut self, write: &[u8]) -> Result<(), EspError> {
        self.transaction(&mut [Operation::Write(write)])
    }

    #[cfg(not(esp_idf_spi_master_isr_in_iram))]
    pub async fn write_async(&mut self, write: &[u8]) -> Result<(), EspError> {
        core::pin::pin!(self.transaction_async(&mut [Operation::Write(write)])).await
    }

    pub fn transfer_in_place(&mut self, buf: &mut [u8]) -> Result<(), EspError> {
        self.transaction(&mut [Operation::TransferInPlace(buf)])
    }

    #[cfg(not(esp_idf_spi_master_isr_in_iram))]
    pub async fn transfer_in_place_async(&mut self, buf: &mut [u8]) -> Result<(), EspError> {
        core::pin::pin!(self.transaction_async(&mut [Operation::TransferInPlace(buf)])).await
    }

    pub fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), EspError> {
        self.transaction(&mut [Operation::Transfer(read, write)])
    }

    #[cfg(not(esp_idf_spi_master_isr_in_iram))]
    pub async fn transfer_async(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), EspError> {
        core::pin::pin!(self.transaction_async(&mut [Operation::Transfer(read, write)])).await
    }

    fn run<'a>(
        &mut self,
        operations: impl Iterator<Item = Operation<'a, u8>> + 'a,
    ) -> Result<(), EspError> {
        let cs_pin = CsCtl::Software {
            cs: &mut self.cs_pin,
            pre_delay: self.pre_delay_us,
            post_delay: self.post_delay_us,
        };

        self.shared_device
            .borrow()
            .lock(move |device| device.run(cs_pin, operations))
    }

    #[allow(dead_code)]
    async fn run_async<'a>(
        &mut self,
        operations: impl Iterator<Item = Operation<'a, u8>> + 'a,
    ) -> Result<(), EspError> {
        let cs_pin = CsCtl::Software {
            cs: &mut self.cs_pin,
            pre_delay: self.pre_delay_us,
            post_delay: self.post_delay_us,
        };

        let device = self.shared_device.borrow();

        let _async_guard = device.async_lock.lock().await;
        let _guard = device.lock.enter();

        let driver = unsafe { device.driver_mut() };

        driver.run_async(cs_pin, operations).await
    }
}

impl<'d, DEVICE, DRIVER> embedded_hal::spi::ErrorType for SpiSoftCsDeviceDriver<'d, DEVICE, DRIVER>
where
    DEVICE: Borrow<SpiSharedDeviceDriver<'d, DRIVER>> + 'd,
    DRIVER: Borrow<SpiDriver<'d>> + 'd,
{
    type Error = SpiError;
}

impl<'d, DEVICE, DRIVER> SpiDevice for SpiSoftCsDeviceDriver<'d, DEVICE, DRIVER>
where
    DEVICE: Borrow<SpiSharedDeviceDriver<'d, DRIVER>> + 'd,
    DRIVER: Borrow<SpiDriver<'d>> + 'd,
{
    fn read(&mut self, buf: &mut [u8]) -> Result<(), Self::Error> {
        Self::read(self, buf).map_err(to_spi_err)
    }

    fn write(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
        Self::write(self, buf).map_err(to_spi_err)
    }

    fn transaction(&mut self, operations: &mut [Operation<'_, u8>]) -> Result<(), Self::Error> {
        Self::transaction(self, operations).map_err(to_spi_err)
    }
}

#[cfg(not(esp_idf_spi_master_isr_in_iram))]
impl<'d, DEVICE, DRIVER> embedded_hal_async::spi::SpiDevice
    for SpiSoftCsDeviceDriver<'d, DEVICE, DRIVER>
where
    DEVICE: Borrow<SpiSharedDeviceDriver<'d, DRIVER>> + 'd,
    DRIVER: Borrow<SpiDriver<'d>> + 'd,
{
    async fn read(&mut self, buf: &mut [u8]) -> Result<(), Self::Error> {
        Self::read_async(self, buf).await.map_err(to_spi_err)
    }

    async fn write(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
        Self::write_async(self, buf).await.map_err(to_spi_err)
    }

    async fn transaction(
        &mut self,
        operations: &mut [Operation<'_, u8>],
    ) -> Result<(), Self::Error> {
        Self::transaction_async(self, operations)
            .await
            .map_err(to_spi_err)
    }
}

fn to_spi_err(err: EspError) -> SpiError {
    SpiError::other(err)
}

// Limit to 64, as we sometimes allocate a buffer of size TRANS_LEN on the stack, so we have to keep it small
// SOC_SPI_MAXIMUM_BUFFER_SIZE equals 64 or 72 (esp32s2) anyway
const TRANS_LEN: usize = if SOC_SPI_MAXIMUM_BUFFER_SIZE < 64_u32 {
    SOC_SPI_MAXIMUM_BUFFER_SIZE as _
} else {
    64_usize
};

// Whilst ESP-IDF doesn't have a documented maximum for queued transactions, we need a compile time
// max to be able to place the transactions on the stack (without recursion hacks) and not be
// forced to use box. Perhaps this is something the user can inject in, via generics or slice.
// This means a spi_device_interface_config_t.queue_size higher than this constant will be clamped
// down in practice.
const MAX_QUEUED_TRANSACTIONS: usize = 6;

struct BusLock(spi_device_handle_t);

impl BusLock {
    fn new(device: spi_device_handle_t) -> Result<Self, EspError> {
        esp!(unsafe { spi_device_acquire_bus(device, BLOCK) })?;

        Ok(Self(device))
    }
}

impl Drop for BusLock {
    fn drop(&mut self) {
        unsafe {
            spi_device_release_bus(self.0);
        }
    }
}

enum CsCtl<'c, 'p, P, M>
where
    P: OutputPin,
    M: OutputMode,
{
    Hardware {
        enabled: bool,
        transactions_count: usize,
        last_transaction: Option<usize>,
    },
    Software {
        cs: &'c mut PinDriver<'p, P, M>,
        pre_delay: Option<u32>,
        post_delay: Option<u32>,
    },
}

impl<'c, 'p, P, M> CsCtl<'c, 'p, P, M>
where
    P: OutputPin,
    M: OutputMode,
{
    fn needs_bus_lock(&self) -> bool {
        match self {
            Self::Hardware {
                transactions_count, ..
            } => *transactions_count > 1,
            Self::Software { .. } => true,
        }
    }

    fn raise_cs(&mut self) -> Result<(), EspError> {
        if let CsCtl::Software { cs, pre_delay, .. } = self {
            cs.toggle()?;

            // TODO: Need to wait asnchronously if in async mode
            if let Some(delay) = pre_delay {
                Ets::delay_us(*delay);
            }
        }

        Ok(())
    }

    fn lower_cs(&mut self) -> Result<(), EspError> {
        if let CsCtl::Software { cs, post_delay, .. } = self {
            cs.toggle()?;

            // TODO: Need to wait asnchronously if in async mode
            if let Some(delay) = post_delay {
                Ets::delay_us(*delay);
            }
        }

        Ok(())
    }

    fn configure(&self, operation: &mut SpiOperation, index: usize) {
        if let SpiOperation::Transaction(transaction) = operation {
            self.configure_transaction(transaction, index)
        }
    }

    fn configure_transaction(&self, transaction: &mut spi_transaction_t, index: usize) {
        if let Self::Hardware {
            enabled,
            last_transaction,
            ..
        } = self
        {
            set_keep_cs_active(transaction, *enabled && Some(index) != *last_transaction);
        }
    }
}

fn spi_read_transactions(
    words: &mut [u8],
    chunk_size: usize,
) -> impl Iterator<Item = spi_transaction_t> + '_ {
    words.chunks_mut(chunk_size).map(|chunk| {
        spi_create_transaction(
            chunk.as_mut_ptr(),
            core::ptr::null(),
            chunk.len(),
            chunk.len(),
        )
    })
}

fn spi_write_transactions(
    words: &[u8],
    chunk_size: usize,
) -> impl Iterator<Item = spi_transaction_t> + '_ {
    words
        .chunks(chunk_size)
        .map(|chunk| spi_create_transaction(core::ptr::null_mut(), chunk.as_ptr(), chunk.len(), 0))
}

fn spi_transfer_in_place_transactions(
    words: &mut [u8],
    chunk_size: usize,
) -> impl Iterator<Item = spi_transaction_t> + '_ {
    words.chunks_mut(chunk_size).map(|chunk| {
        spi_create_transaction(
            chunk.as_mut_ptr(),
            chunk.as_mut_ptr(),
            chunk.len(),
            chunk.len(),
        )
    })
}

fn spi_transfer_transactions<'a>(
    read: &'a mut [u8],
    write: &'a [u8],
    chunk_size: usize,
) -> impl Iterator<Item = spi_transaction_t> + 'a {
    enum OperationsIter<E, R, W> {
        Equal(E),
        ReadLonger(R),
        WriteLonger(W),
    }

    impl<E, R, W> Iterator for OperationsIter<E, R, W>
    where
        E: Iterator<Item = spi_transaction_t>,
        R: Iterator<Item = spi_transaction_t>,
        W: Iterator<Item = spi_transaction_t>,
    {
        type Item = spi_transaction_t;

        fn next(&mut self) -> Option<Self::Item> {
            match self {
                Self::Equal(iter) => iter.next(),
                Self::ReadLonger(iter) => iter.next(),
                Self::WriteLonger(iter) => iter.next(),
            }
        }
    }

    match read.len().cmp(&write.len()) {
        Ordering::Equal => {
            OperationsIter::Equal(spi_transfer_equal_transactions(read, write, chunk_size))
        }
        Ordering::Greater => {
            let (read, read_trail) = read.split_at_mut(write.len());

            OperationsIter::ReadLonger(
                spi_transfer_equal_transactions(read, write, chunk_size)
                    .chain(spi_read_transactions(read_trail, chunk_size)),
            )
        }
        Ordering::Less => {
            let (write, write_trail) = write.split_at(read.len());

            OperationsIter::WriteLonger(
                spi_transfer_equal_transactions(read, write, chunk_size)
                    .chain(spi_write_transactions(write_trail, chunk_size)),
            )
        }
    }
}

fn spi_transfer_equal_transactions<'a>(
    read: &'a mut [u8],
    write: &'a [u8],
    chunk_size: usize,
) -> impl Iterator<Item = spi_transaction_t> + 'a {
    read.chunks_mut(chunk_size)
        .zip(write.chunks(chunk_size))
        .map(|(read_chunk, write_chunk)| {
            spi_create_transaction(
                read_chunk.as_mut_ptr(),
                write_chunk.as_ptr(),
                max(read_chunk.len(), write_chunk.len()),
                read_chunk.len(),
            )
        })
}

// These parameters assume full duplex.
fn spi_create_transaction(
    read: *mut u8,
    write: *const u8,
    transaction_length: usize,
    rx_length: usize,
) -> spi_transaction_t {
    spi_transaction_t {
        flags: 0,
        __bindgen_anon_1: spi_transaction_t__bindgen_ty_1 {
            tx_buffer: write as *const _,
        },
        __bindgen_anon_2: spi_transaction_t__bindgen_ty_2 {
            rx_buffer: read as *mut _,
        },
        length: (transaction_length * 8) as _,
        rxlength: (rx_length * 8) as _,
        ..Default::default()
    }
}

fn set_keep_cs_active(transaction: &mut spi_transaction_t, _keep_cs_active: bool) {
    if _keep_cs_active {
        transaction.flags |= SPI_TRANS_CS_KEEP_ACTIVE
    }
}

fn spi_transmit(
    handle: spi_device_handle_t,
    transactions: impl Iterator<Item = spi_transaction_t>,
    polling: bool,
    queue_size: usize,
) -> Result<(), EspError> {
    if polling {
        for mut transaction in transactions {
            esp!(unsafe { spi_device_polling_transmit(handle, &mut transaction as *mut _) })?;
        }
    } else {
        pub type Queue = Deque<spi_transaction_t, MAX_QUEUED_TRANSACTIONS>;

        let mut queue = Queue::new();
        let queue_size = min(MAX_QUEUED_TRANSACTIONS, queue_size);

        let push = |queue: &mut Queue, transaction| {
            let _ = queue.push_back(transaction);
            esp!(unsafe { spi_device_queue_trans(handle, queue.back_mut().unwrap(), delay::BLOCK) })
        };

        let pop = |queue: &mut Queue| {
            let mut rtrans = ptr::null_mut();
            esp!(unsafe { spi_device_get_trans_result(handle, &mut rtrans, delay::BLOCK) })?;

            if rtrans != queue.front_mut().unwrap() {
                unreachable!();
            }
            queue.pop_front().unwrap();

            Ok(())
        };

        let pop_all = |queue: &mut Queue| {
            while !queue.is_empty() {
                pop(queue)?;
            }

            Ok(())
        };

        for transaction in transactions {
            if queue.len() == queue_size {
                // If the queue is full, we wait for the first transaction in the queue
                pop(&mut queue)?;
            }

            // Write transaction to a stable memory location
            push(&mut queue, transaction)?;
        }

        pop_all(&mut queue)?;
    }

    Ok(())
}

#[allow(dead_code)]
async fn spi_transmit_async(
    handle: spi_device_handle_t,
    transactions: impl Iterator<Item = spi_transaction_t>,
    queue_size: usize,
) -> Result<(), EspError> {
    pub type Queue = Deque<(spi_transaction_t, HalIsrNotification), MAX_QUEUED_TRANSACTIONS>;

    let mut queue = Queue::new();
    let queue = &mut queue;

    let queue_size = min(MAX_QUEUED_TRANSACTIONS, queue_size);
    let queued = Cell::new(0_usize);

    let fut = &mut core::pin::pin!(async {
        let push = |queue: &mut Queue, transaction| {
            queue
                .push_back((transaction, HalIsrNotification::new()))
                .map_err(|_| EspError::from_infallible::<{ ESP_ERR_INVALID_STATE }>())?;
            queued.set(queue.len());

            let last = queue.back_mut().unwrap();
            last.0.user = &last.1 as *const _ as *mut _;
            match esp!(unsafe { spi_device_queue_trans(handle, &mut last.0, delay::NON_BLOCK) }) {
                Err(e) if e.code() == ESP_ERR_TIMEOUT => unreachable!(),
                other => other,
            }
        };

        let pop = |queue: &mut Queue| {
            let mut rtrans = ptr::null_mut();
            match esp!(unsafe {
                spi_device_get_trans_result(handle, &mut rtrans, delay::NON_BLOCK)
            }) {
                Err(e) if e.code() == ESP_ERR_TIMEOUT => unreachable!(),
                other => other,
            }?;

            if rtrans != &mut queue.front_mut().unwrap().0 {
                unreachable!();
            }

            queue.pop_front().unwrap();
            queued.set(queue.len());

            Ok(())
        };

        for transaction in transactions {
            if queue.len() == queue_size {
                // If the queue is full, we wait for the first transaction in the queue
                queue.front_mut().unwrap().1.wait().await;
                pop(queue)?;
            }

            // Write transaction to a stable memory location
            push(queue, transaction)?;
        }

        while !queue.is_empty() {
            queue.front_mut().unwrap().1.wait().await;
            pop(queue)?;
        }

        Ok(())
    });

    with_completion(fut, |completed| {
        if !completed {
            for _ in 0..queued.get() {
                let mut rtrans = ptr::null_mut();
                esp!(unsafe { spi_device_get_trans_result(handle, &mut rtrans, delay::BLOCK) })
                    .unwrap();
            }
        }
    })
    .await
}

extern "C" fn spi_notify(transaction: *mut spi_transaction_t) {
    if let Some(transaction) = unsafe { transaction.as_ref() } {
        if let Some(notification) = unsafe {
            (transaction.user as *mut HalIsrNotification as *const HalIsrNotification).as_ref()
        } {
            notification.notify_lsb();
        }
    }
}

fn copy_operation<'b>(operation: &'b mut Operation<'_, u8>) -> Operation<'b, u8> {
    match operation {
        Operation::Read(read) => Operation::Read(read),
        Operation::Write(write) => Operation::Write(write),
        Operation::Transfer(read, write) => Operation::Transfer(read, write),
        Operation::TransferInPlace(write) => Operation::TransferInPlace(write),
        Operation::DelayNs(delay) => Operation::DelayNs(*delay),
    }
}

fn data_mode_to_u8(data_mode: config::Mode) -> u8 {
    (((data_mode.polarity == config::Polarity::IdleHigh) as u8) << 1)
        | ((data_mode.phase == config::Phase::CaptureOnSecondTransition) as u8)
}

#[allow(dead_code)]
async fn with_completion<F, D>(fut: F, dtor: D) -> F::Output
where
    F: Future,
    D: FnMut(bool),
{
    struct Completion<D>
    where
        D: FnMut(bool),
    {
        dtor: D,
        completed: bool,
    }

    impl<D> Drop for Completion<D>
    where
        D: FnMut(bool),
    {
        fn drop(&mut self) {
            (self.dtor)(self.completed);
        }
    }

    let mut completion = Completion {
        dtor,
        completed: false,
    };

    let result = fut.await;

    completion.completed = true;

    result
}

macro_rules! impl_spi {
    ($spi:ident: $device:expr) => {
        crate::impl_peripheral!($spi);

        impl Spi for $spi {
            #[inline(always)]
            fn device() -> spi_host_device_t {
                $device
            }
        }
    };
}

macro_rules! impl_spi_any_pins {
    ($spi:ident) => {
        impl SpiAnyPins for $spi {}
    };
}

impl_spi!(SPI1: spi_host_device_t_SPI1_HOST);
impl_spi!(SPI2: spi_host_device_t_SPI2_HOST);
#[cfg(any(esp32, esp32s2, esp32s3))]
impl_spi!(SPI3: spi_host_device_t_SPI3_HOST);

impl_spi_any_pins!(SPI2);
#[cfg(any(esp32, esp32s2, esp32s3))]
impl_spi_any_pins!(SPI3);