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
#![allow(dead_code)]

use std::io::{Read, Write};
#[cfg(feature = "jsonrpc")]
use std::os::unix::net::UnixStream;
use std::sync::{
    atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicU8, Ordering},
    mpsc, Arc,
};
use std::thread;
use std::time;

use parking_lot::{Mutex, MutexGuard};
use serialport::TTYPort;

#[cfg(feature = "jsonrpc")]
use smol_jsonrpc::{Error as RpcError, Request, Response};

#[cfg(feature = "jsonrpc")]
use ssp::jsonrpc::{jsonrpc_id, set_jsonrpc_id};
use ssp::{CommandOps, MessageOps, ResponseOps, Result};

use crate::{continue_on_err, encryption_key};

mod inner;

/// Timeout for waiting for lock on a mutex (milliseconds).
pub const LOCK_TIMEOUT_MS: u64 = 5_000;
/// Timeout for waiting for serial communication (milliseconds).
pub const SERIAL_TIMEOUT_MS: u64 = 10_000;
/// Minimum polling interval between messages (milliseconds).
pub const MIN_POLLING_MS: u64 = 500;
/// Medium polling interval between messages (milliseconds).
pub const MED_POLLING_MS: u64 = 650;
/// Maximum polling interval between messages (milliseconds).
#[allow(dead_code)]
pub const MAX_POLLING_MS: u64 = 1_000;
/// Timeout for retrieving an event from a queue (milliseconds)
pub const QUEUE_TIMEOUT_MS: u128 = 50;
/// Default serial connection BAUD rate (bps).
pub const BAUD_RATE: u32 = 9_600;

pub(crate) static SEQ_FLAG: AtomicBool = AtomicBool::new(false);
static POLLING_INIT: AtomicBool = AtomicBool::new(false);

static ESCROWED: AtomicBool = AtomicBool::new(false);
static ESCROWED_AMOUNT: AtomicU32 = AtomicU32::new(0);

static ENABLED: AtomicBool = AtomicBool::new(false);

static CASHBOX_ATTACHED: AtomicBool = AtomicBool::new(true);

// Time when a device reset was initiated.
static RESET_TIME: AtomicU64 = AtomicU64::new(0);
// Timeout for waiting for the device to reset (seconds).
const RESET_TIMEOUT_SECS: u64 = 60;

static PROTOCOL_VERSION: AtomicU8 = AtomicU8::new(6);

static INTERACTIVE: AtomicBool = AtomicBool::new(false);

static DISPENSING: AtomicBool = AtomicBool::new(false);

pub(crate) fn sequence_flag() -> ssp::SequenceFlag {
    SEQ_FLAG.load(Ordering::Relaxed).into()
}

pub(crate) fn set_sequence_flag(flag: ssp::SequenceFlag) {
    SEQ_FLAG.store(flag.into(), Ordering::SeqCst);
}

// Whether the polling routine has started.
fn polling_inited() -> bool {
    POLLING_INIT.load(Ordering::Relaxed)
}

// Sets the flag indicating whether the polling routine started.
fn set_polling_inited(inited: bool) {
    POLLING_INIT.store(inited, Ordering::SeqCst);
}

pub(crate) fn escrowed() -> bool {
    ESCROWED.load(Ordering::Relaxed)
}

pub(crate) fn set_escrowed(escrowed: bool) -> bool {
    let last = ESCROWED.load(Ordering::Relaxed);
    ESCROWED.store(escrowed, Ordering::SeqCst);
    last
}

pub(crate) fn enabled() -> bool {
    ENABLED.load(Ordering::Relaxed)
}

pub(crate) fn set_enabled(enabled: bool) {
    ENABLED.store(enabled, Ordering::SeqCst);
}

pub(crate) fn escrowed_amount() -> ssp::ChannelValue {
    ESCROWED_AMOUNT.load(Ordering::Relaxed).into()
}

pub(crate) fn set_escrowed_amount(amount: ssp::ChannelValue) -> ssp::ChannelValue {
    let last = ssp::ChannelValue::from(ESCROWED_AMOUNT.load(Ordering::Relaxed));
    ESCROWED_AMOUNT.store(amount.into(), Ordering::SeqCst);
    last
}

/// Gets whether the csahboxed is attached to the device.
pub fn cashbox_attached() -> bool {
    CASHBOX_ATTACHED.load(Ordering::Relaxed)
}

/// Sets whether the csahboxed is attached to the device.
pub fn set_cashbox_attached(attached: bool) -> bool {
    let last = cashbox_attached();
    CASHBOX_ATTACHED.store(attached, Ordering::SeqCst);
    last
}

pub(crate) fn resetting() -> bool {
    reset_time() != 0
}

pub(crate) fn reset_time() -> u64 {
    RESET_TIME.load(Ordering::Relaxed)
}

pub(crate) fn set_reset_time(time: u64) -> u64 {
    let last = reset_time();
    RESET_TIME.store(time, Ordering::SeqCst);
    last
}

pub(crate) fn protocol_version() -> ssp::ProtocolVersion {
    PROTOCOL_VERSION.load(Ordering::Relaxed).into()
}

pub(crate) fn set_protocol_version(protocol: ssp::ProtocolVersion) -> ssp::ProtocolVersion {
    let last = protocol_version();
    PROTOCOL_VERSION.store(protocol.into(), Ordering::SeqCst);
    last
}

pub(crate) fn interactive() -> bool {
    INTERACTIVE.load(Ordering::Relaxed)
}

pub(crate) fn set_interactive(val: bool) -> bool {
    let last = interactive();
    INTERACTIVE.store(val, Ordering::SeqCst);
    last
}

pub(crate) fn dispensing() -> bool {
    DISPENSING.load(Ordering::Relaxed)
}

pub(crate) fn set_dispensing(val: bool) {
    DISPENSING.store(val, Ordering::SeqCst);
}

/// Polling interactivity mode.
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PollMode {
    /// Automically handle polling events.
    Auto,
    /// Interactively handle polling events.
    Interactive,
}

/// Receiver end of the device-sent event queue.
///
/// Owner of the receiver can regularly attempt to pop events from the queue,
/// and decide how to handle any returned event(s).
///
/// Example:
///
/// ```rust, no_run
/// # use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
/// # fn main() -> ssp::Result<()> {
/// let stop_polling = Arc::new(AtomicBool::new(false));
/// let poll_mode = ssp_server::PollMode::Interactive;
///
/// let mut handle = ssp_server::DeviceHandle::new("/dev/ttyUSB0")?;
///
/// let rx: ssp_server::PushEventReceiver = handle.start_background_polling_with_queue(
///     Arc::clone(&stop_polling),
///     poll_mode,
/// )?;
///
/// // Pop events from the queue
/// loop {
///     while let Ok(event) = rx.pop_event() {
///         log::debug!("Received an event: {event}");
///         // do stuff in response to the event...
///     }
/// }
/// # Ok(())
/// # }
/// ```
pub struct PushEventReceiver(pub mpsc::Receiver<ssp::Event>);

impl PushEventReceiver {
    /// Creates a new [PushEventReceiver] from the provided `queue`.
    pub fn new(queue: mpsc::Receiver<ssp::Event>) -> Self {
        Self(queue)
    }

    /// Attempt to pop an event from the queue.
    ///
    /// Returns `Err(_)` if an event could not be retrieved before the timeout.
    pub fn pop_event(&self) -> Result<ssp::Event> {
        let now = time::Instant::now();
        let queue = &self.0;

        while now.elapsed().as_millis() < QUEUE_TIMEOUT_MS {
            if let Ok(evt) = queue.try_recv() {
                return Ok(evt);
            }
        }

        Err(ssp::Error::QueueTimeout)
    }
}

/// Handle for communicating with a SSP-enabled device over serial.
///
/// ```no_run
/// let _handle = ssp_server::DeviceHandle::new("/dev/ttyUSB0").unwrap();
/// ```
pub struct DeviceHandle {
    serial_port: Arc<Mutex<TTYPort>>,
    generator: ssp::GeneratorKey,
    modulus: ssp::ModulusKey,
    random: ssp::RandomKey,
    fixed_key: ssp::FixedKey,
    key: Arc<Mutex<Option<ssp::AesKey>>>,
}

impl DeviceHandle {
    /// Creates a new [DeviceHandle] with a serial connection over the supplied serial device.
    pub fn new(serial_path: &str) -> Result<Self> {
        // For details on the following setup, see sections 5.4 & 7 in the SSP implementation guide
        let serial_port = Arc::new(Mutex::new(
            serialport::new(serial_path, BAUD_RATE)
                // disable flow control serial lines
                .flow_control(serialport::FlowControl::None)
                // eight-bit data size
                .data_bits(serialport::DataBits::Eight)
                // no control bit parity
                .parity(serialport::Parity::None)
                // two bit stop
                .stop_bits(serialport::StopBits::Two)
                // serial device times out after 10 seconds, so do we
                .timeout(time::Duration::from_millis(SERIAL_TIMEOUT_MS))
                // get back a TTY port for POSIX systems, Windows is not supported
                .open_native()?,
        ));

        let mut prime_gen = ssp::primes::Generator::from_entropy();

        let mut generator = ssp::GeneratorKey::from_generator(&mut prime_gen);
        let mut modulus = ssp::ModulusKey::from_generator(&mut prime_gen);

        // Modulus key must be smaller than the Generator key
        let mod_inner = modulus.as_inner();
        let gen_inner = generator.as_inner();

        if gen_inner > mod_inner {
            modulus = gen_inner.into();
            generator = mod_inner.into();
        }

        let random = ssp::RandomKey::from_entropy();
        let fixed_key = ssp::FixedKey::from_inner(ssp::DEFAULT_FIXED_KEY_U64);
        let key = Arc::new(Mutex::new(None));

        Ok(Self {
            serial_port,
            generator,
            modulus,
            random,
            fixed_key,
            key,
        })
    }

    /// Starts background polling routine to regularly send [PollCommand] messages to the device.
    ///
    /// **Args**
    ///
    /// - `stop_polling`: used to control when the polling routine should stop sending polling messages.
    ///
    /// If background polling has already started, the function just returns.
    ///
    /// Example:
    ///
    /// ```rust, no_run
    /// # use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
    /// # fn main() -> ssp::Result<()> {
    /// let stop_polling = Arc::new(AtomicBool::new(false));
    ///
    /// let handle = ssp_server::DeviceHandle::new("/dev/ttyUSB0")?;
    ///
    /// handle.start_background_polling(Arc::clone(&stop_polling))?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn start_background_polling(&self, stop_polling: Arc<AtomicBool>) -> Result<()> {
        if polling_inited() {
            Err(ssp::Error::PollingReinit)
        } else {
            // Set the global flag to disallow multiple background polling threads.
            set_polling_inited(true);

            let serial_port = Arc::clone(&self.serial_port);
            let end_polling = Arc::clone(&stop_polling);
            let key = Arc::clone(&self.key);

            thread::spawn(move || -> Result<()> {
                let mut now = time::Instant::now();

                while !end_polling.load(Ordering::Relaxed) {
                    if now.elapsed().as_millis() > MED_POLLING_MS as u128 {
                        now = time::Instant::now();

                        if resetting() {
                            continue;
                        }

                        let mut locked_port = continue_on_err!(
                            Self::lock_serial_port(&serial_port),
                            "Failed to lock serial port in background polling routine"
                        );
                        let key = continue_on_err!(
                            Self::lock_encryption_key(&key),
                            "Failed to lock encryption key in background polling routine"
                        );

                        let mut message = ssp::PollCommand::new();

                        let res = if let Some(key) = key.as_ref() {
                            continue_on_err!(
                                Self::poll_encrypted_message(&mut locked_port, &mut message, key),
                                "Failed poll command in background polling routine"
                            )
                        } else {
                            continue_on_err!(
                                Self::poll_message_variant(&mut locked_port, &mut message),
                                "Failed poll command in background polling routine"
                            )
                        };

                        let status = res.as_response().response_status();

                        if status.is_ok() {
                            let poll_res = continue_on_err!(
                                res.into_poll_response(),
                                "Failed to convert poll response in background polling routine"
                            );
                            let last_statuses = poll_res.last_response_statuses();

                            log::debug!("Successful poll command, last statuses: {last_statuses}");
                        } else {
                            log::warn!("Failed poll command, response status: {status}");
                        }
                    }

                    thread::sleep(time::Duration::from_millis(MED_POLLING_MS / 3));
                }

                // Now that polling finished, reset the flag to allow another background routine to
                // start.
                set_polling_inited(false);

                Ok(())
            });

            Ok(())
        }
    }

    /// Starts background polling routine to regularly send [PollCommand] messages to the device,
    /// with an additional event queue for sending push events from the device to the host.
    ///
    /// **Args**
    ///
    /// - `stop_polling`: used to control when the polling routine should stop sending polling messages.
    ///
    /// If background polling has already started, the function just returns.
    ///
    /// Returns an event queue receiver that the caller can use to receive device-sent events.
    ///
    /// Example:
    ///
    /// ```rust, no_run
    /// # use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
    /// # fn main() -> ssp::Result<()> {
    /// let stop_polling = Arc::new(AtomicBool::new(false));
    /// let poll_mode = ssp_server::PollMode::Interactive;
    ///
    /// let handle = ssp_server::DeviceHandle::new("/dev/ttyUSB0")?;
    ///
    /// let rx = handle.start_background_polling_with_queue(
    ///     Arc::clone(&stop_polling),
    ///     poll_mode,
    /// )?;
    ///
    /// // Pop events from the queue
    /// loop {
    ///     while let Ok(event) = rx.pop_event() {
    ///         log::debug!("Received an event: {event}");
    ///         // do stuff in response to the event...
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn start_background_polling_with_queue(
        &self,
        stop_polling: Arc<AtomicBool>,
        poll_mode: PollMode,
    ) -> Result<PushEventReceiver> {
        if polling_inited() {
            Err(ssp::Error::PollingReinit)
        } else {
            // Set the global flag to disallow multiple background polling threads.
            set_polling_inited(true);

            if poll_mode == PollMode::Interactive {
                set_interactive(true);
            }

            let serial_port = Arc::clone(&self.serial_port);
            let end_polling = Arc::clone(&stop_polling);
            let key = Arc::clone(&self.key);

            let (tx, rx) = mpsc::channel();

            thread::spawn(move || -> Result<()> {
                let mut now = time::Instant::now();

                while !end_polling.load(Ordering::Relaxed) {
                    if now.elapsed().as_millis() >= MIN_POLLING_MS as u128 {
                        now = time::Instant::now();

                        if resetting() {
                            thread::sleep(time::Duration::from_secs(1));
                            continue;
                        }

                        let mut locked_port = continue_on_err!(
                            Self::lock_serial_port(&serial_port),
                            "Failed to lock serial port in background polling routine"
                        );

                        let key = continue_on_err!(
                            Self::lock_encryption_key(&key),
                            "Failed to lock encryption key in background polling routine"
                        );

                        if escrowed() {
                            // Do not automatically poll when device has a bill in escrow,
                            // and the user is in interactive mode.
                            //
                            // Sending a poll with bill in escrow stacks the bill.
                            //
                            // Sit in a busy loop until the user sends a stack/reject command.

                            // Send hold command to keep note in escrow until `stack` or `reject`
                            // is sent.

                            let mut message = ssp::HoldCommand::new();

                            continue_on_err!(
                                Self::poll_message(&mut locked_port, &mut message, key.as_ref()),
                                "Failed hold command"
                            );

                            thread::sleep(time::Duration::from_millis(MIN_POLLING_MS));

                            continue;
                        }

                        if dispensing() {
                            // Do not automatically poll when device is dispensing notes
                            thread::sleep(time::Duration::from_millis(MIN_POLLING_MS));

                            continue;
                        }

                        let mut message = ssp::PollCommand::new();

                        let res = continue_on_err!(
                            Self::poll_message(&mut locked_port, &mut message, key.as_ref()),
                            "Failed poll command"
                        );

                        let status = res.as_response().response_status();
                        if status.is_ok() {
                            let poll_res = continue_on_err!(
                                res.into_poll_response(),
                                "Failed to convert poll response in background polling routine"
                            );

                            Self::parse_events(&poll_res, &tx)?;
                        } else if status.to_u8() == 0 {
                            log::info!("Device returned a null response: {}", res.as_response());
                            log::trace!("Response data: {:x?}", res.as_response().buf());
                        } else {
                            log::warn!("Failed poll command, response status: {status}");
                        }
                    }

                    thread::sleep(time::Duration::from_millis(MIN_POLLING_MS));
                }

                // Now that polling finished, reset the flag to allow another background routine to
                // start.
                set_polling_inited(false);

                Ok(())
            });

            Ok(PushEventReceiver::new(rx))
        }
    }

    fn poll_resetting(
        serial_port: &mut TTYPort,
        key: Option<&ssp::AesKey>,
        tx: Option<&mpsc::Sender<ssp::Event>>,
    ) -> Result<()> {
        use std::ops::Sub;

        let reset_time = time::Instant::now().sub(time::Duration::from_secs(reset_time()));
        let mut message = ssp::PollCommand::new();

        while (1..RESET_TIMEOUT_SECS).contains(&reset_time.elapsed().as_secs()) {
            let elapsed = reset_time.elapsed().as_secs();
            let res = continue_on_err!(
                Self::poll_message(serial_port, &mut message, key),
                format!("Device is still resetting, elapsed time: {elapsed}")
            );
            if res.as_response().response_status().is_ok() {
                set_reset_time(0);

                if let Some(tx) = tx {
                    continue_on_err!(
                        tx.send(ssp::Event::from(ssp::ResetEvent::new())),
                        "Failed to send Reset event"
                    );
                }

                break;
            }
        }

        Ok(())
    }

    #[cfg(feature = "jsonrpc")]
    pub fn on_message(&mut self, stream: &mut UnixStream) -> Result<ssp::Method> {
        stream.set_nonblocking(true)?;

        let mut message_buf = vec![0u8; 1024];
        let mut idx = 0;

        while let Ok(ret) = stream.read(&mut message_buf) {
            if ret == 0 {
                // Client hung up the socket, so let the caller know to shutdown the stream
                return Ok(ssp::Method::Shutdown);
            }

            if idx >= message_buf.len() {
                message_buf.resize(2 * message_buf.len(), 0u8);
            }

            idx += ret;

            if message_buf.contains(&b'\n') {
                break;
            }
        }

        let message_string = std::str::from_utf8(message_buf[..idx].as_ref()).unwrap_or("");
        if message_string.is_empty() || message_string.contains("ready") {
            return Ok(ssp::Method::Enable);
        }

        for message in message_string.split('\n') {
            if !message.is_empty() {
                log::debug!("Received message: {message}");

                let message = match serde_json::from_str::<Request>(message) {
                    Ok(msg) => msg,
                    Err(err) => {
                        log::warn!("Expected valid JSON-RPC request, error: {err}");
                        continue;
                    }
                };

                log::debug!("Message: {message:?}");
                let event = ssp::Event::from(&message);
                let method = event.method();
                log::debug!("Message method: {method}");

                let jsonrpc_id = message.id().unwrap_or(jsonrpc_id());
                set_jsonrpc_id(jsonrpc_id);

                match method {
                    ssp::Method::Accept => self.on_enable(stream, &event)?,
                    ssp::Method::Stop => self.on_disable(stream, &event)?,
                    ssp::Method::Enable => self.on_enable_payout(stream, &event)?,
                    ssp::Method::Disable => self.on_disable_payout(stream, &event)?,
                    ssp::Method::Reject => self.on_reject(stream, &event)?,
                    ssp::Method::Stack => self.on_stack(stream, &event)?,
                    ssp::Method::StackerFull => self.on_stacker_full(stream, &event)?,
                    ssp::Method::Status => self.on_status(stream, &event)?,
                    ssp::Method::Reset => self.on_reset(stream, &event)?,
                    ssp::Method::Dispense => self.on_dispense(stream, &event)?,
                    _ => return Err(ssp::Error::JsonRpc("unsupported method".into())),
                }

                return Ok(method);
            }
        }

        Ok(ssp::Method::Disable)
    }

    /// Message handler for [Disable](ssp::Event::DisableEvent) events.
    ///
    /// Exposed to help with creating a custom message handler.
    #[cfg(feature = "jsonrpc")]
    pub fn on_disable(&self, stream: &mut UnixStream, _event: &ssp::Event) -> Result<()> {
        self.disable()?;

        let mut res = Response::from(ssp::Event::from(ssp::DisableEvent::new()));
        res.set_id(jsonrpc_id());

        let res_str = serde_json::to_string(&res)? + "\n";

        stream.write_all(res_str.as_bytes())?;

        Ok(())
    }

    /// Message handler for [Disable](ssp::Event::DisableEvent) events.
    ///
    /// Exposed to help with creating a custom message handler.
    #[cfg(feature = "jsonrpc")]
    pub fn on_disable_payout(&self, stream: &mut UnixStream, _event: &ssp::Event) -> Result<()> {
        self.disable_payout()?;

        let mut res = Response::from(ssp::Event::from(ssp::DisableEvent::new()));
        res.set_id(jsonrpc_id());

        let res_str = serde_json::to_string(&res)? + "\n";

        stream.write_all(res_str.as_bytes())?;

        Ok(())
    }

    /// Message handler for [Enable](ssp::Event::EnableEvent) events.
    ///
    /// Exposed to help with creating a custom message handler.
    #[cfg(feature = "jsonrpc")]
    pub fn on_enable(&self, stream: &mut UnixStream, event: &ssp::Event) -> Result<()> {
        // perform full init sequence,
        // only sending EnableCommand does not bring the device online...
        let enable_event = ssp::EnableEvent::try_from(event)?;
        self.enable()?;

        let mut res = Response::from(ssp::Event::from(enable_event));
        res.set_id(jsonrpc_id());

        let res_str = serde_json::to_string(&res)? + "\n";

        stream.write_all(res_str.as_bytes())?;

        Ok(())
    }

    /// Message handler for [Enable](ssp::Event::EnableEvent) events.
    ///
    /// Exposed to help with creating a custom message handler.
    #[cfg(feature = "jsonrpc")]
    pub fn on_enable_payout(&self, stream: &mut UnixStream, event: &ssp::Event) -> Result<()> {
        // perform full init sequence,
        // only sending EnableCommand does not bring the device online...
        let enable_event = ssp::EnableEvent::try_from(event)?;
        self.enable_payout()?;

        let mut res = Response::from(ssp::Event::from(enable_event));
        res.set_id(jsonrpc_id());

        let res_str = serde_json::to_string(&res)? + "\n";

        stream.write_all(res_str.as_bytes())?;

        Ok(())
    }

    /// Message handler for [Reject](ssp::Event::RejectEvent) events.
    ///
    /// Exposed to help with creating a custom message handler.
    #[cfg(feature = "jsonrpc")]
    pub fn on_reject(&self, stream: &mut UnixStream, _event: &ssp::Event) -> Result<()> {
        self.reject()?;

        let mut res = Response::from(ssp::Event::from(ssp::RejectEvent::new()));
        res.set_id(jsonrpc_id());

        let mut res_str = serde_json::to_string(&res)?;
        res_str += "\n";

        stream.write_all(res_str.as_bytes())?;

        Ok(())
    }

    /// Message handler for [Stack](ssp::Event::StackEvent) events.
    ///
    /// Exposed to help with creating a custom message handler.
    #[cfg(feature = "jsonrpc")]
    pub fn on_stack(&self, stream: &mut UnixStream, _event: &ssp::Event) -> Result<()> {
        let value = self.stack()?;

        let mut res = Response::from(ssp::Event::from(ssp::StackEvent::from(value)));
        res.set_id(jsonrpc_id());

        let mut res_str = serde_json::to_string(&res)?;
        res_str += "\n";

        stream.write_all(res_str.as_bytes())?;

        Ok(())
    }

    /// Message handler for [StackerFull](ssp::Event::StackerFullEvent) events.
    ///
    /// Exposed to help with creating a custom message handler.
    #[cfg(feature = "jsonrpc")]
    pub fn on_stacker_full(&self, _stream: &mut UnixStream, _event: &ssp::Event) -> Result<()> {
        Err(ssp::Error::JsonRpc(
            "StackerFull handler unimplemented".into(),
        ))
    }

    /// Message handler for [Status](ssp::Event::StatusEvent) events.
    ///
    /// Exposed to help with creating a custom message handler.
    #[cfg(feature = "jsonrpc")]
    pub fn on_status(&self, stream: &mut UnixStream, _event: &ssp::Event) -> Result<()> {
        let (data, dataset_version) = {
            let mut serial_port = self.serial_port()?;
            let key = self.encryption_key()?;

            log::trace!(
                "full status: {}",
                self.setup_request_inner(&mut serial_port, key.as_ref())?
            );

            (
                self.unit_data_inner(&mut serial_port, key.as_ref())?,
                Self::dataset_version_inner(&mut serial_port, key.as_ref())?,
            )
        };

        let cashbox_attached = cashbox_attached();
        let status = ssp::DeviceStatus::from(data)
            .with_dataset_version(dataset_version.dataset_version()?)
            .with_cashbox_attached(cashbox_attached);

        let event = if cashbox_attached {
            ssp::StatusEvent::new(status)
        } else {
            ssp::StatusEvent::new(status.with_response_status(ssp::ResponseStatus::CashboxRemoved))
        };

        let mut res = Response::from(ssp::Event::from(event));
        res.set_id(jsonrpc_id());

        let res_str = serde_json::to_string(&res)? + "\n";

        stream.write_all(res_str.as_bytes())?;

        Ok(())
    }

    /// Message handler for [Status](ssp::Event::StatusEvent) events.
    ///
    /// Exposed to help with creating a custom message handler.
    #[cfg(feature = "jsonrpc")]
    pub fn on_reset(&self, stream: &mut UnixStream, _event: &ssp::Event) -> Result<()> {
        match self.full_reset() {
            Ok(_) => {
                let res =
                    Response::from(ssp::Event::from(ssp::ResetEvent::new())).with_id(jsonrpc_id());

                let res_str = serde_json::to_string(&res)? + "\n";

                log::debug!("Successfully reset device: {res_str}");

                stream.write_all(res_str.as_bytes())?;

                Ok(())
            }
            Err(err) => Err(err),
        }
    }

    /// Performs the full reset protocol to restart a device.
    pub fn full_reset(&self) -> Result<()> {
        use serialport::SerialPort;

        self.reset()?;

        let now = time::Instant::now();

        // Wait a bit for the device to reset, and re-open the port.
        thread::sleep(time::Duration::from_secs(20));

        let mut serial_port = self.serial_port()?;
        // Clear the serial port to simulate closing and opening the port
        serial_port.clear(serialport::ClearBuffer::All)?;

        while now.elapsed().as_secs() < RESET_TIMEOUT_SECS {
            if let Ok(res) = self.sync_inner(&mut serial_port, None) {
                if res.response_status().is_ok() {
                    set_reset_time(0);

                    if let Err(err) =
                        self.enable_device_inner(&mut serial_port, protocol_version(), None)
                    {
                        log::error!("Error enabling device after reset: {err}");
                    }

                    if interactive() {
                        // if the server is running in interactive mode, disable until the client
                        // re-enables the device.
                        if let Err(err) = self.disable_inner(&mut serial_port, None) {
                            log::error!("Error disabling device after reset: {err}");
                        }
                    }

                    let poll_res = self.poll_inner(&mut serial_port, None)?;
                    if poll_res.response_status().is_ok() {
                        log::debug!("Successfully reset device");

                        return Ok(());
                    } else {
                        return Err(ssp::Error::InvalidStatus((
                            poll_res.response_status(),
                            ssp::ResponseStatus::Ok,
                        )));
                    }
                }
            }
        }

        Err(ssp::Error::JsonRpc("failed to reset device".into()))
    }

    /// Gets whether the device is currently dispensing notes.
    pub fn dispensing(&self) -> bool {
        dispensing()
    }

    /// Message handle for dispense request using a
    /// [PayoutDenominationList](ssp::PayoutDenominationList).
    ///
    /// User is responsible for parsing a request into a valid list.
    ///
    /// Exposed to help with creating a custom message handler.
    #[cfg(feature = "jsonrpc")]
    pub fn on_dispense(&self, stream: &mut UnixStream, event: &ssp::Event) -> Result<()> {
        log::trace!("Dispense event: {event:?}");

        let payload = event.payload();
        log::trace!("PayoutByDenomination payload: {payload}");

        let inner_event = payload.as_dispense_event()?;
        log::trace!("PayoutByDenomination event: {inner_event}");

        let payout_denom = inner_event.as_inner();
        log::trace!("PayoutByDenomination request: {payout_denom}");

        let mut serial_port = self.serial_port()?;
        let key_guard = self.encryption_key()?;
        let key = key_guard.as_ref();

        self.enable_inner(&mut serial_port, key)?;
        self.enable_payout_inner(&mut serial_port, key)?;

        set_dispensing(true);

        let mut payout =
            ssp::PayoutByDenominationCommand::new().with_payout_denominations(payout_denom);

        let res = if let Err(err) =
            self.payout_by_denomination_inner(&mut serial_port, &mut payout, key)
        {
            Response::new()
                .with_id(jsonrpc_id())
                .with_error(RpcError::new().with_message(format!("{err}").as_str()))
        } else {
            Response::new().with_id(jsonrpc_id())
        };

        self.disable_payout_inner(&mut serial_port, key)?;
        self.disable_inner(&mut serial_port, key)?;

        set_dispensing(false);

        let res_str = serde_json::to_string(&res)? + "\n";

        stream.write_all(res_str.as_bytes())?;

        Ok(())
    }

    /// Acquires a lock on the serial port used for communication with the acceptor device.
    pub fn serial_port(&self) -> Result<MutexGuard<'_, TTYPort>> {
        Self::lock_serial_port(&self.serial_port)
    }

    pub(crate) fn lock_serial_port(
        serial_port: &Arc<Mutex<TTYPort>>,
    ) -> Result<MutexGuard<'_, TTYPort>> {
        serial_port
            .try_lock_for(time::Duration::from_millis(SERIAL_TIMEOUT_MS))
            .ok_or(ssp::Error::SerialPort(
                "timed out locking serial port".into(),
            ))
    }

    /// Acquires a lock on the AES encryption key.
    pub fn encryption_key(&self) -> Result<MutexGuard<'_, Option<ssp::AesKey>>> {
        Self::lock_encryption_key(&self.key)
    }

    pub(crate) fn lock_encryption_key(
        key: &Arc<Mutex<Option<ssp::AesKey>>>,
    ) -> Result<MutexGuard<'_, Option<ssp::AesKey>>> {
        key.try_lock_for(time::Duration::from_millis(LOCK_TIMEOUT_MS))
            .ok_or(ssp::Error::Io("timed out locking encryption key".into()))
    }

    /// Creates a new [GeneratorKey](ssp::GeneratorKey) from system entropy.
    pub fn new_generator_key(&mut self) {
        self.generator = ssp::GeneratorKey::from_entropy();
        self.reset_key();
    }

    /// Creates a new [ModulusKey](ssp::ModulusKey) from system entropy.
    pub fn new_modulus_key(&mut self) {
        let mut modulus = ssp::ModulusKey::from_entropy();

        // Modulus key must be smaller than the Generator key
        let gen_inner = self.generator.as_inner();
        let mod_inner = modulus.as_inner();

        if gen_inner < mod_inner {
            self.generator = mod_inner.into();
            modulus = gen_inner.into();
        }

        self.modulus = modulus;

        self.reset_key();
    }

    /// Creates a new [RandomKey](ssp::RandomKey) from system entropy.
    pub fn new_random_key(&mut self) {
        self.random = ssp::RandomKey::from_entropy();
        self.reset_key();
    }

    fn generator_key(&self) -> &ssp::GeneratorKey {
        &self.generator
    }

    fn modulus_key(&self) -> &ssp::ModulusKey {
        &self.modulus
    }

    fn random_key(&self) -> &ssp::RandomKey {
        &self.random
    }

    fn set_key(&mut self, inter_key: ssp::IntermediateKey) -> Result<()> {
        let mut key = self.encryption_key()?;

        let mut new_key = ssp::AesKey::from(&self.fixed_key);
        let enc_key =
            ssp::EncryptionKey::from_keys(&inter_key, self.random_key(), self.modulus_key());

        new_key[8..].copy_from_slice(enc_key.as_inner().to_le_bytes().as_ref());

        key.replace(new_key);

        Ok(())
    }

    /// Resets the Encryption key to none, requires a new key negotiation before performing eSSP
    /// operations.
    pub fn reset_key(&mut self) -> Option<ssp::AesKey> {
        if let Ok(mut key) = self.encryption_key() {
            key.take()
        } else {
            None
        }
    }

    fn status_res(res: &dyn ssp::ResponseOps) -> Result<()> {
        let status = res.response_status();
        if status.is_ok() {
            Ok(())
        } else {
            Err(ssp::Error::Status(status))
        }
    }

    /// Performs key negotiation to start a new eSSP session.
    ///
    /// Uses currently set [GeneratorKey] and [ModulusKey].
    pub fn negotiate_key(&mut self) -> Result<()> {
        Self::status_res(&self.sync()?)?;
        Self::status_res(&self.set_generator()?)?;
        Self::status_res(&self.set_modulus()?)?;
        Self::status_res(&self.request_key_exchange()?)?;

        Ok(())
    }

    /// Renegotiates the encryption key for a new eSSP session.
    pub fn renegotiate_key(&mut self) -> Result<()> {
        self.new_generator_key();
        self.new_modulus_key();
        self.new_random_key();

        ssp::reset_sequence_count();

        self.negotiate_key()
    }

    /// Sends a command to stack a bill in escrow.
    pub fn stack(&self) -> Result<ssp::ChannelValue> {
        let mut serial_port = self.serial_port()?;

        let mut message = ssp::PollCommand::new();
        let res = Self::poll_message(&mut serial_port, &mut message, encryption_key!(self))?;

        let status = res.as_response().response_status();
        if status.is_ok() {
            set_escrowed(false);
            Ok(set_escrowed_amount(ssp::ChannelValue::default()))
        } else {
            Err(ssp::Error::InvalidStatus((status, ssp::ResponseStatus::Ok)))
        }
    }

    /// Send a [SetInhibitsCommand](ssp::SetInhibitsCommand) message to the device.
    ///
    /// No response is returned.
    ///
    /// The caller should wait a reasonable amount of time for the device
    /// to come back online before sending additional messages.
    pub fn set_inhibits(
        &self,
        enable_list: ssp::EnableBitfieldList,
    ) -> Result<ssp::SetInhibitsResponse> {
        let mut serial_port = self.serial_port()?;
        self.set_inhibits_inner(&mut serial_port, enable_list, encryption_key!(self))
    }

    fn set_inhibits_inner(
        &self,
        serial_port: &mut TTYPort,
        enable_list: ssp::EnableBitfieldList,
        key: Option<&ssp::AesKey>,
    ) -> Result<ssp::SetInhibitsResponse> {
        let mut message = ssp::SetInhibitsCommand::new();
        message.set_inhibits(enable_list)?;

        let res = Self::poll_message(serial_port, &mut message, key)?;

        res.into_set_inhibits_response()
    }

    /// Send a [ResetCommand](ssp::ResetCommand) message to the device.
    ///
    /// No response is returned.
    ///
    /// The caller should wait a reasonable amount of time for the device
    /// to come back online before sending additional messages.
    pub fn reset(&self) -> Result<()> {
        let mut serial_port = self.serial_port()?;

        let mut message = ssp::ResetCommand::new();

        Self::set_message_sequence_flag(&mut message);

        serial_port.write_all(message.as_bytes())?;

        set_reset_time(
            time::SystemTime::now()
                .duration_since(time::UNIX_EPOCH)?
                .as_secs(),
        );

        Ok(())
    }

    /// Send a [PollCommand](ssp::PollCommand) message to the device.
    pub fn poll(&self) -> Result<ssp::PollResponse> {
        let mut serial_port = self.serial_port()?;

        self.poll_inner(&mut serial_port, encryption_key!(self))
    }

    fn poll_inner(
        &self,
        serial_port: &mut TTYPort,
        key: Option<&ssp::AesKey>,
    ) -> Result<ssp::PollResponse> {
        let mut message = ssp::PollCommand::new();

        Self::set_message_sequence_flag(&mut message);

        let response = Self::poll_message(serial_port, &mut message, key)?;

        response.into_poll_response()
    }

    /// Send a [PollWithAckCommand](ssp::PollWithAckCommand) message to the device.
    pub fn poll_with_ack(&self) -> Result<ssp::PollWithAckResponse> {
        let mut serial_port = self.serial_port()?;

        let mut message = ssp::PollWithAckCommand::new();

        Self::set_message_sequence_flag(&mut message);

        let response = Self::poll_message(&mut serial_port, &mut message, encryption_key!(self))?;

        response.into_poll_with_ack_response()
    }

    /// Send a [EventAckCommand](ssp::EventAckCommand) message to the device.
    pub fn event_ack(&self) -> Result<ssp::EventAckResponse> {
        let mut serial_port = self.serial_port()?;

        let mut message = ssp::EventAckCommand::new();

        Self::set_message_sequence_flag(&mut message);

        let response = Self::poll_message(&mut serial_port, &mut message, encryption_key!(self))?;

        response.into_event_ack_response()
    }

    /// Send a [RejectCommand](ssp::RejectCommand) message to the device.
    pub fn reject(&self) -> Result<ssp::RejectResponse> {
        let mut serial_port = self.serial_port()?;

        let mut message = ssp::RejectCommand::new();

        Self::set_message_sequence_flag(&mut message);

        let response = Self::poll_message(&mut serial_port, &mut message, encryption_key!(self))?;

        let res = response.into_reject_response()?;

        let status = res.response_status();

        if status.is_ok() {
            set_escrowed(false);
            set_escrowed_amount(ssp::ChannelValue::default());

            Ok(res)
        } else {
            Err(ssp::Error::InvalidStatus((status, ssp::ResponseStatus::Ok)))
        }
    }

    /// Send a [SyncCommand](ssp::SyncCommand) message to the device.
    pub fn sync(&self) -> Result<ssp::SyncResponse> {
        let mut serial_port = self.serial_port()?;

        self.sync_inner(&mut serial_port, encryption_key!(self))
    }

    fn sync_inner(
        &self,
        serial_port: &mut TTYPort,
        key: Option<&ssp::AesKey>,
    ) -> Result<ssp::SyncResponse> {
        let mut message = ssp::SyncCommand::new();

        set_sequence_flag(ssp::SequenceFlag::from(1));

        let response = Self::poll_message(serial_port, &mut message, key)?;

        set_sequence_flag(ssp::SequenceFlag::from(0));

        response.into_sync_response()
    }

    /// Starts the device by performing the full initialization sequence.
    pub fn enable_device(
        &self,
        protocol_version: ssp::ProtocolVersion,
    ) -> Result<ssp::EnableResponse> {
        let mut serial_port = self.serial_port()?;

        self.enable_device_inner(&mut serial_port, protocol_version, encryption_key!(self))
    }

    fn enable_device_inner(
        &self,
        serial_port: &mut TTYPort,
        protocol_version: ssp::ProtocolVersion,
        key: Option<&ssp::AesKey>,
    ) -> Result<ssp::EnableResponse> {
        self.host_protocol_version_inner(serial_port, protocol_version, key)?;
        set_protocol_version(protocol_version);

        let status = self.setup_request_inner(serial_port, key)?;
        log::trace!("Status: {status}");

        let serial = self.serial_number_inner(serial_port, key)?;
        log::trace!("Serial number: {serial}");

        let res = self.enable_inner(serial_port, key)?;

        let unit_type = status.unit_type().as_inner();
        if (unit_type == 0x06 || unit_type == 0x07) && key.is_some() {
            // if encryption mode is enabled, attempt to enable the device with EnablePayout
            self.enable_payout_inner(serial_port, key)?;
        }

        let enable_list = ssp::EnableBitfieldList::from([
            ssp::EnableBitfield::from(0xff),
            ssp::EnableBitfield::from(0xff),
        ]);

        self.set_inhibits_inner(serial_port, enable_list, key)?;
        self.channel_value_data_inner(serial_port, key)?;

        Ok(res)
    }

    /// Send a [EnableCommand](ssp::EnableCommand) message to the device.
    pub fn enable(&self) -> Result<ssp::EnableResponse> {
        let mut serial_port = self.serial_port()?;
        self.enable_inner(&mut serial_port, encryption_key!(self))
    }

    fn enable_inner(
        &self,
        serial_port: &mut TTYPort,
        key: Option<&ssp::AesKey>,
    ) -> Result<ssp::EnableResponse> {
        let mut message = ssp::EnableCommand::new();

        let response = Self::poll_message(serial_port, &mut message, key)?;

        set_enabled(true);

        response.into_enable_response()
    }

    /// Send a [EnablePayoutCommand](ssp::EnablePayoutCommand) message to the device.
    pub fn enable_payout(&self) -> Result<ssp::EnablePayoutResponse> {
        let mut serial_port = self.serial_port()?;
        self.enable_payout_inner(&mut serial_port, encryption_key!(self))
    }

    fn enable_payout_inner(
        &self,
        serial_port: &mut TTYPort,
        key: Option<&ssp::AesKey>,
    ) -> Result<ssp::EnablePayoutResponse> {
        let mut message =
            ssp::EnablePayoutCommand::new().with_option(ssp::EnablePayoutOption::from(0b11));

        let response = Self::poll_message(serial_port, &mut message, key)?;

        set_enabled(true);

        response.into_enable_payout_response()
    }

    /// Send a [DisableCommand](ssp::DisableCommand) message to the device.
    pub fn disable(&self) -> Result<ssp::DisableResponse> {
        let mut serial_port = self.serial_port()?;
        self.disable_inner(&mut serial_port, encryption_key!(self))
    }

    fn disable_inner(
        &self,
        serial_port: &mut TTYPort,
        key: Option<&ssp::AesKey>,
    ) -> Result<ssp::DisableResponse> {
        let mut message = ssp::DisableCommand::new();

        let response = Self::poll_message(serial_port, &mut message, key)?;

        set_enabled(false);

        response.into_disable_response()
    }

    /// Send a [DisablePayoutCommand](ssp::DisablePayoutCommand) message to the device.
    pub fn disable_payout(&self) -> Result<ssp::DisablePayoutResponse> {
        let mut serial_port = self.serial_port()?;
        self.disable_payout_inner(&mut serial_port, encryption_key!(self))
    }

    fn disable_payout_inner(
        &self,
        serial_port: &mut TTYPort,
        key: Option<&ssp::AesKey>,
    ) -> Result<ssp::DisablePayoutResponse> {
        let mut message = ssp::DisablePayoutCommand::new();

        let response = Self::poll_message(serial_port, &mut message, key)?;

        set_enabled(false);

        response.into_disable_payout_response()
    }

    /// Send a [DisplayOffCommand](ssp::DisplayOffCommand) message to the device.
    pub fn display_off(&self) -> Result<ssp::DisplayOffResponse> {
        let mut serial_port = self.serial_port()?;

        let mut message = ssp::DisplayOffCommand::new();

        let response = Self::poll_message(&mut serial_port, &mut message, encryption_key!(self))?;

        response.into_display_off_response()
    }

    /// Send a [DisplayOnCommand](ssp::DisplayOnCommand) message to the device.
    pub fn display_on(&self) -> Result<ssp::DisplayOnResponse> {
        let mut serial_port = self.serial_port()?;

        let mut message = ssp::DisplayOnCommand::new();

        let response = Self::poll_message(&mut serial_port, &mut message, encryption_key!(self))?;

        response.into_display_on_response()
    }

    /// Send an [EmptyCommand](ssp::EmptyCommand) message to the device.
    pub fn empty(&self) -> Result<ssp::EmptyResponse> {
        let mut serial_port = self.serial_port()?;

        let mut message = ssp::EmptyCommand::new();

        if let Some(key) = (*self.encryption_key()?).as_ref() {
            let res = Self::poll_encrypted_message(&mut serial_port, &mut message, key)?;

            res.into_empty_response()
        } else {
            Err(ssp::Error::Encryption(ssp::ResponseStatus::KeyNotSet))
        }
    }

    /// Send an [SmartEmptyCommand](ssp::SmartEmptyCommand) message to the device.
    pub fn smart_empty(&self) -> Result<ssp::SmartEmptyResponse> {
        let mut serial_port = self.serial_port()?;

        let mut message = ssp::SmartEmptyCommand::new();

        if let Some(key) = self.encryption_key()?.as_ref() {
            let res = Self::poll_encrypted_message(&mut serial_port, &mut message, key)?;

            res.into_smart_empty_response()
        } else {
            Err(ssp::Error::Encryption(ssp::ResponseStatus::KeyNotSet))
        }
    }

    /// Send an [HostProtocolVersionCommand](ssp::HostProtocolVersionCommand) message to the device.
    pub fn host_protocol_version(
        &self,
        protocol_version: ssp::ProtocolVersion,
    ) -> Result<ssp::HostProtocolVersionResponse> {
        let mut serial_port = self.serial_port()?;

        self.host_protocol_version_inner(&mut serial_port, protocol_version, encryption_key!(self))
    }

    fn host_protocol_version_inner(
        &self,
        serial_port: &mut TTYPort,
        protocol_version: ssp::ProtocolVersion,
        key: Option<&ssp::AesKey>,
    ) -> Result<ssp::HostProtocolVersionResponse> {
        let mut message = ssp::HostProtocolVersionCommand::new();
        message.set_version(protocol_version);

        let response = Self::poll_message(serial_port, &mut message, key)?;

        response.into_host_protocol_version_response()
    }

    /// Send a [SerialNumberCommand](ssp::SerialNumberCommand) message to the device.
    pub fn serial_number(&self) -> Result<ssp::SerialNumberResponse> {
        let mut serial_port = self.serial_port()?;
        self.serial_number_inner(&mut serial_port, encryption_key!(self))
    }

    fn serial_number_inner(
        &self,
        serial_port: &mut TTYPort,
        key: Option<&ssp::AesKey>,
    ) -> Result<ssp::SerialNumberResponse> {
        let mut message = ssp::SerialNumberCommand::new();

        let res = Self::poll_message(serial_port, &mut message, key)?;

        res.into_serial_number_response()
    }

    /// Send a [SetGeneratorCommand](ssp::SetGeneratorCommand) message to the device.
    ///
    /// If the response is an `Err(_)`, or the response status is not
    /// [RsponseStatus::Ok](ssp::ResponseStatus::Ok), the caller should call
    /// [new_generator_key](Self::new_generator_key), and try again.
    pub fn set_generator(&self) -> Result<ssp::SetGeneratorResponse> {
        let mut serial_port = self.serial_port()?;

        let mut message = ssp::SetGeneratorCommand::new();
        message.set_generator(self.generator_key());

        let response = Self::poll_message(&mut serial_port, &mut message, None)?;

        response.into_set_generator_response()
    }

    /// Send a [SetModulusCommand](ssp::SetModulusCommand) message to the device.
    ///
    /// If the response is an `Err(_)`, or the response status is not
    /// [RsponseStatus::Ok](ssp::ResponseStatus::Ok), the caller should call
    /// [new_modulus_key](Self::new_modulus_key), and try again.
    pub fn set_modulus(&mut self) -> Result<ssp::SetModulusResponse> {
        let mut serial_port = self.serial_port()?;

        let mut message = ssp::SetModulusCommand::new();
        message.set_modulus(self.modulus_key());

        let response = Self::poll_message(&mut serial_port, &mut message, None)?;

        response.into_set_modulus_response()
    }

    /// Send a [RequestKeyExchangeCommand](ssp::RequestKeyExchangeCommand) message to the device.
    ///
    /// If the response is an `Err(_)`, or the response status is not
    /// [RsponseStatus::Ok](ssp::ResponseStatus::Ok), the caller should call
    /// [new_random_key](Self::new_random_key), and try again.
    pub fn request_key_exchange(&mut self) -> Result<ssp::RequestKeyExchangeResponse> {
        let res = {
            let mut serial_port = self.serial_port()?;

            let mut message = ssp::RequestKeyExchangeCommand::new();

            let inter_key = ssp::IntermediateKey::from_keys(
                self.generator_key(),
                self.random_key(),
                self.modulus_key(),
            );
            message.set_intermediate_key(&inter_key);

            let response = Self::poll_message(&mut serial_port, &mut message, None)?;

            response.into_request_key_exchange_response()?
        };

        // If the exchange was successful, set the new encryption key.
        if res.response_status().is_ok() {
            self.set_key(res.intermediate_key())?;
        }

        Ok(res)
    }

    /// Send a [SetEncryptionKeyCommand](ssp::SetEncryptionKeyCommand) message to the device.
    ///
    /// If the response is an `Err(_)`, or the response status is not
    /// [RsponseStatus::Ok](ssp::ResponseStatus::Ok), the caller should call
    /// [new_modulus_key](Self::new_modulus_key), and try again.
    pub fn set_encryption_key(&mut self) -> Result<ssp::SetEncryptionKeyResponse> {
        let mut message = ssp::SetEncryptionKeyCommand::new();

        let fixed_key = ssp::FixedKey::from_entropy();
        message.set_fixed_key(&fixed_key);

        let res = if let Some(key) = encryption_key!(self) {
            let mut serial_port = self.serial_port()?;
            Self::poll_encrypted_message(&mut serial_port, &mut message, key)
        } else {
            Err(ssp::Error::Encryption(ssp::ResponseStatus::KeyNotSet))
        };

        match res {
            Ok(m) => {
                self.fixed_key = fixed_key;
                m.into_set_encryption_key_response()
            }
            Err(err) => Err(err),
        }
    }

    /// Send a [EncryptionResetCommand](ssp::EncryptionResetCommand) message to the device.
    pub fn encryption_reset(&mut self) -> Result<ssp::EncryptionResetResponse> {
        let mut serial_port = self.serial_port()?;

        let mut message = ssp::EncryptionResetCommand::new();

        let response = Self::poll_message(&mut serial_port, &mut message, None)?;

        if response.as_response().response_status() == ssp::ResponseStatus::CommandCannotBeProcessed
        {
            Err(ssp::Error::Encryption(
                ssp::ResponseStatus::CommandCannotBeProcessed,
            ))
        } else {
            response.into_encryption_reset_response()
        }
    }

    /// Send a [SetupRequestCommand](ssp::SetupRequestCommand) message to the device.
    pub fn setup_request(&self) -> Result<ssp::SetupRequestResponse> {
        let mut serial_port = self.serial_port()?;
        self.setup_request_inner(&mut serial_port, encryption_key!(self))
    }

    fn setup_request_inner(
        &self,
        serial_port: &mut TTYPort,
        key: Option<&ssp::AesKey>,
    ) -> Result<ssp::SetupRequestResponse> {
        let mut message = ssp::SetupRequestCommand::new();

        let response = Self::poll_message(serial_port, &mut message, key)?;

        let res = response.into_setup_request_response()?;

        // configure global channel values
        let chan_vals = match res.protocol_version()? as u8 {
            0..=5 | 0xff => res.channel_values()?,
            _ => res.channel_values_long()?,
        };

        ssp::configure_channels(chan_vals.as_ref())?;

        Ok(res)
    }

    /// Send a [UnitDataCommand](ssp::UnitDataCommand) message to the device.
    pub fn unit_data(&self) -> Result<ssp::UnitDataResponse> {
        let mut serial_port = self.serial_port()?;

        self.unit_data_inner(&mut serial_port, encryption_key!(self))
    }

    fn unit_data_inner(
        &self,
        serial_port: &mut TTYPort,
        key: Option<&ssp::AesKey>,
    ) -> Result<ssp::UnitDataResponse> {
        let mut message = ssp::UnitDataCommand::new();

        let response = Self::poll_message(serial_port, &mut message, key)?;

        response.into_unit_data_response()
    }

    pub fn dataset_version(&self) -> Result<ssp::DatasetVersionResponse> {
        let mut serial_port = self.serial_port()?;

        Self::dataset_version_inner(&mut serial_port, encryption_key!(self))
    }

    pub fn dataset_version_inner(
        serial_port: &mut TTYPort,
        key: Option<&ssp::AesKey>,
    ) -> Result<ssp::DatasetVersionResponse> {
        let mut message = ssp::DatasetVersionCommand::new();

        let response = Self::poll_message(serial_port, &mut message, key)?;

        response.into_dataset_version_response()
    }

    /// Send a [ChannelValueDataCommand](ssp::ChannelValueDataCommand) message to the device.
    pub fn channel_value_data(&self) -> Result<ssp::ChannelValueDataResponse> {
        let mut serial_port = self.serial_port()?;

        self.channel_value_data_inner(&mut serial_port, encryption_key!(self))
    }

    fn channel_value_data_inner(
        &self,
        serial_port: &mut TTYPort,
        key: Option<&ssp::AesKey>,
    ) -> Result<ssp::ChannelValueDataResponse> {
        let mut message = ssp::ChannelValueDataCommand::new();

        let response = Self::poll_message(serial_port, &mut message, key)?;

        let res = response.into_channel_value_data_response()?;

        ssp::configure_channels(res.channel_values()?.as_ref())?;

        Ok(res)
    }

    /// Send a [LastRejectCodeCommand](ssp::LastRejectCodeCommand) message to the device.
    pub fn last_reject_code(&self) -> Result<ssp::LastRejectCodeResponse> {
        let mut serial_port = self.serial_port()?;

        let mut message = ssp::LastRejectCodeCommand::new();

        let response = Self::poll_message(&mut serial_port, &mut message, encryption_key!(self))?;

        response.into_last_reject_code_response()
    }

    /// Send a [HoldCommand](ssp::HoldCommand) message to the device.
    pub fn hold(&self) -> Result<ssp::HoldResponse> {
        let mut serial_port = self.serial_port()?;

        let mut message = ssp::HoldCommand::new();

        let response = Self::poll_message(&mut serial_port, &mut message, encryption_key!(self))?;

        response.into_hold_response()
    }

    /// Send a [GetBarcodeReaderConfigurationCommand](ssp::GetBarcodeReaderConfigurationCommand) message to the device.
    pub fn get_barcode_reader_configuration(
        &self,
    ) -> Result<ssp::GetBarcodeReaderConfigurationResponse> {
        let mut serial_port = self.serial_port()?;

        let mut message = ssp::GetBarcodeReaderConfigurationCommand::new();

        let response = Self::poll_message(&mut serial_port, &mut message, encryption_key!(self))?;

        response.into_get_barcode_reader_configuration_response()
    }

    /// Gets whether the device has barcode readers present.
    pub fn has_barcode_reader(&self) -> Result<bool> {
        let mut serial_port = self.serial_port()?;

        let mut message = ssp::GetBarcodeReaderConfigurationCommand::new();

        let response = Self::poll_message(&mut serial_port, &mut message, encryption_key!(self))?;

        Ok(response
            .as_get_barcode_reader_configuration_response()?
            .hardware_status()
            != ssp::BarcodeHardwareStatus::None)
    }

    /// Send a [SetBarcodeReaderConfigurationCommand](ssp::SetBarcodeReaderConfigurationCommand) message to the device.
    pub fn set_barcode_reader_configuration(
        &self,
        config: ssp::BarcodeConfiguration,
    ) -> Result<ssp::SetBarcodeReaderConfigurationResponse> {
        let mut serial_port = self.serial_port()?;

        let mut message = ssp::SetBarcodeReaderConfigurationCommand::new();
        message.set_configuration(config);

        let response = Self::poll_message(&mut serial_port, &mut message, encryption_key!(self))?;

        response.into_set_barcode_reader_configuration_response()
    }

    /// Send a [GetBarcodeInhibitCommand](ssp::GetBarcodeInhibitCommand) message to the device.
    pub fn get_barcode_inhibit(&self) -> Result<ssp::GetBarcodeInhibitResponse> {
        let mut serial_port = self.serial_port()?;

        let mut message = ssp::GetBarcodeInhibitCommand::new();

        let response = Self::poll_message(&mut serial_port, &mut message, encryption_key!(self))?;

        response.into_get_barcode_inhibit_response()
    }

    /// Send a [SetBarcodeInhibitCommand](ssp::SetBarcodeInhibitCommand) message to the device.
    pub fn set_barcode_inhibit(
        &self,
        inhibit: ssp::BarcodeCurrencyInhibit,
    ) -> Result<ssp::SetBarcodeInhibitResponse> {
        let mut serial_port = self.serial_port()?;

        let mut message = ssp::SetBarcodeInhibitCommand::new();
        message.set_inhibit(inhibit);

        let response = Self::poll_message(&mut serial_port, &mut message, encryption_key!(self))?;

        response.into_set_barcode_inhibit_response()
    }

    /// Send a [GetBarcodeDataCommand](ssp::GetBarcodeDataCommand) message to the device.
    pub fn get_barcode_data(&self) -> Result<ssp::GetBarcodeDataResponse> {
        let mut serial_port = self.serial_port()?;

        let mut message = ssp::GetBarcodeDataCommand::new();

        let response = Self::poll_message(&mut serial_port, &mut message, encryption_key!(self))?;

        response.into_get_barcode_data_response()
    }

    /// Send a [ConfigureBezelCommand](ssp::ConfigureBezelCommand) message to the device.
    pub fn configure_bezel(
        &self,
        rgb: ssp::RGB,
        storage: ssp::BezelConfigStorage,
    ) -> Result<ssp::ConfigureBezelResponse> {
        let mut serial_port = self.serial_port()?;

        let mut message = ssp::ConfigureBezelCommand::new();
        message.set_rgb(rgb);
        message.set_config_storage(storage);

        let response = Self::poll_message(&mut serial_port, &mut message, encryption_key!(self))?;

        response.into_configure_bezel_response()
    }

    /// Dispenses notes from the device by sending a [PayoutByDenominationCommand] message.
    ///
    /// **NOTE**: this command requires encryption mode.
    ///
    /// Parameters:
    ///
    /// - `list`: list of [`PayoutDenomination`] requests
    ///
    /// Returns:
    ///
    /// - `Ok(())`
    /// - Err([`Error`](ssp::Error)) if an error occured
    pub fn payout_by_denomination(&self, list: &ssp::PayoutDenominationList) -> Result<()> {
        let mut serial_port = self.serial_port()?;
        let mut message = ssp::PayoutByDenominationCommand::new()
            .with_payout_denominations(list)
            .with_payout_option(ssp::PayoutOption::PayoutAmount);

        self.payout_by_denomination_inner(&mut serial_port, &mut message, encryption_key!(self))
    }

    pub(crate) fn payout_by_denomination_inner(
        &self,
        serial_port: &mut TTYPort,
        message: &mut ssp::PayoutByDenominationCommand,
        key: Option<&ssp::AesKey>,
    ) -> Result<()> {
        let mut test_cmd = message.with_payout_option(ssp::PayoutOption::TestPayoutAmount);
        let test_res = Self::poll_message(serial_port, &mut test_cmd, key)?;

        log::trace!("Test payout response: {}", test_res.as_response());
        thread::sleep(time::Duration::from_millis(50));

        match test_res.as_response().response_status() {
            ssp::ResponseStatus::Ok => {
                let response = Self::poll_message(serial_port, message, key)?;

                log::trace!("Payout response: {}", response.as_response());
                match response.as_response().response_status() {
                    ssp::ResponseStatus::Ok => Ok(()),
                    status => Err(ssp::Error::Status(status)),
                }
            }
            status => Err(ssp::Error::Status(status)),
        }
    }

    fn set_message_sequence_flag(message: &mut dyn CommandOps) {
        let mut sequence_id = message.sequence_id();
        sequence_id.set_flag(sequence_flag());
        message.set_sequence_id(sequence_id);
    }

    fn poll_message_variant(
        serial_port: &mut TTYPort,
        message: &mut dyn CommandOps,
    ) -> Result<ssp::MessageVariant> {
        use ssp::message::index;

        Self::set_message_sequence_flag(message);

        log::trace!(
            "Message type: {}, SEQID: {}",
            message.message_type(),
            message.sequence_id()
        );

        log::trace!("Polled message: {:x?}", message.as_bytes());

        let mut attempt = 0;
        while let Err(_err) = serial_port.write_all(message.as_bytes()) {
            attempt += 1;
            log::warn!("Failed to send message, attempt #{attempt}");

            thread::sleep(time::Duration::from_millis(MIN_POLLING_MS));

            message.toggle_sequence_id();
        }

        // Set the global sequence flag to the opposite value for the next message
        set_sequence_flag(!message.sequence_id().flag());

        let mut buf = [0u8; ssp::len::MAX_MESSAGE];

        serial_port
            .read_exact(buf[..index::SEQ_ID].as_mut())
            .map_err(|err| {
                log::warn!("Error reading initial response bytes: {err}");
                err
            })?;

        let stx = buf[index::STX];
        if stx != ssp::STX {
            return Err(ssp::Error::InvalidSTX(stx));
        }

        serial_port.read_exact(buf[index::SEQ_ID..=index::LEN].as_mut())?;

        let buf_len = buf[index::LEN] as usize;
        let total = buf_len + ssp::len::METADATA;
        let mut remaining = index::DATA + buf_len + 2; // data + CRC-16 bytes

        serial_port.read_exact(buf[index::DATA..remaining].as_mut())?;

        log::trace!("Polled response: {:x?}", &buf[..remaining]);

        // check for byte stuffing
        let mut extra = buf[index::DATA..remaining]
            .iter()
            .filter(|&c| c == &ssp::STX)
            .count()
            / 2;

        // read extra bytes off the buffer to account for byte stuffing
        while extra != 0 {
            log::trace!("Extra bytes: {extra}");
            if remaining >= ssp::len::MAX_MESSAGE || remaining + extra >= ssp::len::MAX_MESSAGE {
                return Err(ssp::Error::InvalidLength((
                    remaining + extra,
                    ssp::len::MAX_MESSAGE,
                )));
            }

            serial_port.read_exact(buf[remaining..remaining + extra].as_mut())?;
            extra = buf[remaining..remaining + extra]
                .iter()
                .filter(|&c| c == &ssp::STX)
                .count()
                / 2;
            remaining = remaining.saturating_add(extra);
        }

        // remove any byte stuffing
        if buf[index::DATA..remaining].contains(&ssp::STX) {
            log::trace!("Polled response (with stuffing): {:x?}", &buf[..remaining]);
            ssp::unstuff(buf[index::DATA..remaining].as_mut(), total - index::DATA)?;
        }

        ssp::MessageVariant::from_buf(buf[..total].as_ref(), message.message_type())
    }

    fn poll_encrypted_message(
        serial_port: &mut TTYPort,
        message: &mut dyn CommandOps,
        key: &ssp::AesKey,
    ) -> Result<ssp::MessageVariant> {
        let mut enc_cmd = ssp::EncryptedCommand::new();
        enc_cmd.set_message_data(message)?;

        let mut wrapped = enc_cmd.encrypt(key);
        Self::set_message_sequence_flag(&mut wrapped);

        log::trace!("Encrypted message: {wrapped}");
        log::trace!("Encrypted data: {:x?}", wrapped.data());

        // recalculate the checksum to include a possible change for the sequence flag
        let is_stuffed = wrapped.is_stuffed();

        // first, remove any byte stuffing
        if is_stuffed {
            wrapped.unstuff_encrypted_data()?;
        }

        // calculate the new checksum
        wrapped.calculate_checksum();

        // re-add any byte stuffing
        if is_stuffed {
            wrapped.stuff_encrypted_data()?;
        }

        let response = Self::poll_message_variant(serial_port, &mut wrapped)?;

        if response.as_response().response_status() == ssp::ResponseStatus::KeyNotSet {
            return Err(ssp::Error::Encryption(ssp::ResponseStatus::KeyNotSet));
        }
        log::trace!("Raw response: {:x?}", response.as_response().buf());

        let wrapped_res = response.into_wrapped_encrypted_message()?;
        log::trace!("Encrypted response: {:x?}", wrapped_res.buf());

        // received an encrypted response, decrypt and process
        let dec_res = ssp::EncryptedResponse::decrypt(key, wrapped_res);
        log::trace!("Decrypted response: {dec_res}");
        log::trace!("Decrypted data: {:x?}", dec_res.message_data());

        let mut res = ssp::MessageVariant::new(message.command());
        res.as_response_mut().set_data(dec_res.message_data())?;
        res.as_response_mut().calculate_checksum();

        Ok(res)
    }

    fn poll_message(
        serial_port: &mut TTYPort,
        message: &mut dyn CommandOps,
        key: Option<&ssp::AesKey>,
    ) -> Result<ssp::MessageVariant> {
        if let Some(key) = key {
            log::trace!("Polling encrypted message: {:x?}", message.buf());
            Self::poll_encrypted_message(serial_port, message, key)
        } else {
            log::trace!("Polling clear-text message: {:x?}", message.buf());
            Self::poll_message_variant(serial_port, message)
        }
    }
}