zproto 0.4.2

A library from communicating with Zaber products in Rust.
Documentation
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
//! Types for opening and using a serial port with the ASCII protocol.

pub mod handlers;
pub mod iter;
mod options;
#[cfg(test)]
mod test;

#[cfg(any(test, doc, feature = "mock"))]
use crate::backend::Mock;
use crate::backend::{Backend, Serial, UNKNOWN_BACKEND_NAME};
#[allow(clippy::wildcard_imports)]
use crate::error::*;
#[cfg(unstable)]
use crate::{
	ascii::chain::Chain,
	routine::{IntoRoutine, Routine},
};
use crate::{
	ascii::{
		checksum::Lrc,
		command::{Command, CommandWriter, MaxPacketSize, Target},
		id,
		packet::{Packet, PacketKind},
		response::{
			check::{self, NotChecked},
			Alert, AnyResponse, Info, Reply, Response, ResponseBuilder, Status,
		},
	},
	timeout_guard::TimeoutGuard,
};

use handlers::{Handlers, LocalHandlers, SendHandlers};
#[cfg(any(test, doc, feature = "mock"))]
pub use options::OpenMockOptions;
pub use options::{OpenGeneralOptions, OpenSerialOptions, OpenTcpOptions};
use std::{
	convert::TryFrom,
	io,
	net::{TcpStream, ToSocketAddrs},
	time::Duration,
};

/// The direction a packet was sent.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum Direction {
	/// The packet was transmitted to a device.
	Tx,
	/// The packet was received from a device.
	Recv,
}

/// The default tag to mark types
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum DefaultTag {}

/// The type of [`Port`] that implements `Send`.
pub type SendPort<'a, B, Tag = DefaultTag> = Port<'a, B, Tag, SendHandlers<'a>>;

/// A port configured to use the ASCII protocol.
///
/// See the [`ascii`] module-level documentation for details on how to use a `Port`.
///
/// A port is parameterized by three types:
///
/// 1. `B`: the type of [`Backend`] used to send/receive packets.
///    * Use the convenience methods [`open_serial`] and [`open_tcp`] to construct
///      a serial port (`Port<Serial>`) or a TCP port (`Port<TcpStream>`). To
///      customize the construction of these types, or to construct a port with a
///      dynamic backend, use the [`OpenSerialOptions`] and [`OpenTcpOptions`] builder
///      types.
/// 2. `Tag`: an optional type for "tagging" the port.
///    * This has a default and can be ignored if you only ever have one port open.
///      When working with multiple ports simultaneously, the `Tag` type can be used
///      to statically differentiate them and improve your programs type safety. Use
///      the [`into_tagged`] method to change a port's `Tag` type.
/// 3. `H`: the type of event [handlers].
///    * This has a default and can be ignored in single-threaded contexts.
///      There are two types for event handlers: one that implements `Send` and one
///      that does not (the default). To convert a port into a type that implements
///      `Send`, use the [`try_into_send`] method.
///
/// [`ascii`]: crate::ascii
/// [`into_tagged`]: Port::into_tagged
/// [`try_into_send`]: Port::try_into_send
/// [`open_serial`]: Port::open_serial
/// [`open_tcp`]: Port::open_tcp
pub struct Port<'a, B, Tag = DefaultTag, H = LocalHandlers<'a>> {
	/// The underlying backend
	backend: B,
	/// The message ID generator
	ids: id::Counter,
	/// Whether commands should include message IDs or not.
	generate_id: bool,
	/// Whether commands should include checksums or not.
	generate_checksum: bool,
	/// The maximum command packet size.
	max_packet_size: MaxPacketSize,
	/// If populated, the error that has "poisoned" the port. This error MUST be
	/// reported before the port is used for communication again.
	///
	/// A port becomes "poisoned" when an error occurs that
	///
	///  * cannot be recovered from,
	///  * panicking is ill advised,
	///  * and it is safe to delay reporting of the error until the next attempt
	///    to communicate over the port.
	///
	/// For instance, if a [`TimeoutGuard`] cannot restore the original timeout
	/// in its Drop implementation, rather than panicking (which would almost
	/// certainly cause the program to abort rather than unwind the stack) it
	/// can poison the port.
	poison: Option<io::Error>,
	/// The builder used to concatenate packets in to responses.
	builder: ResponseBuilder,
	/// User supplied event handlers
	handlers: H,
	/// The type differentiating this Port for other Ports at compile time.
	tag: std::marker::PhantomData<Tag>,
	/// Marker for the lifetime
	lifetime: std::marker::PhantomData<&'a ()>,
}

impl<B: Backend, Tag, H> std::fmt::Debug for Port<'_, B, Tag, H> {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		f.debug_struct("Port")
			.field("name", &self.backend.name())
			.finish_non_exhaustive()
	}
}

impl<'a> Port<'a, Serial> {
	/// Open the serial port at the specified path using the default options.
	///
	/// Alternatively, use [`Port::open_serial_options`] to customize how the port is opened.
	///
	/// ## Example
	///
	/// ```rust
	/// # use zproto::ascii::Port;
	/// # fn wrapper() -> Result<(), Box<dyn std::error::Error>> {
	/// let mut port = Port::open_serial("/dev/ttyUSB0")?;
	/// // Or equivalently
	/// let mut port = Port::open_serial_options().open("/dev/ttyUSB0")?;
	/// # Ok(())
	/// # }
	/// ```
	pub fn open_serial(path: &str) -> Result<Port<'a, Serial>, AsciiError> {
		OpenSerialOptions::new().open(path)
	}

	/// Get an [`OpenSerialOptions`] to customize how a serial port is opened.
	pub fn open_serial_options() -> OpenSerialOptions {
		OpenSerialOptions::default()
	}
}

impl<'a> Port<'a, TcpStream> {
	/// Open the TCP port at the specified address using the default options.
	///
	/// Alternatively, use [`Port::open_tcp_options`] to customize how the port is opened.
	///
	/// ## Example
	///
	/// ```rust
	/// # use zproto::ascii::Port;
	/// # fn wrapper() -> Result<(), Box<dyn std::error::Error>> {
	/// let mut port = Port::open_tcp("198.168.0.1:55550")?;
	/// // Or equivalently
	/// let mut port = Port::open_tcp_options().open("198.168.0.1:55550")?;
	/// # Ok(())
	/// # }
	/// ```
	pub fn open_tcp<A: ToSocketAddrs>(address: A) -> Result<Port<'a, TcpStream>, io::Error> {
		OpenTcpOptions::default().open(address)
	}

	/// Get an [`OpenTcpOptions`] to customize how a TCP port is opened.
	pub fn open_tcp_options() -> OpenTcpOptions {
		OpenTcpOptions::default()
	}
}

impl<'a, B: Backend> Port<'a, B> {
	/// Open a port with the specified `backend` using the default options.
	///
	/// For [`Serial`] or [`TcpStream`] backends, use [`Port::open_serial`] and [`Port::open_tcp`] instead.
	/// Those methods make configuring those backends easier.
	///
	/// Alternatively, use [`Port::open_general_options`] to customize how the port is opened.
	///
	/// ## Example
	///
	/// ```rust
	/// # use zproto::{ascii::Port, backend::Backend};
	/// # fn wrapper<B: Backend>(my_backend: B) {
	/// let mut port = Port::open_general(my_backend);
	/// # }
	/// # fn wrapper2<B: Backend>(my_backend: B) {
	/// // Or equivalently
	/// let mut port = Port::open_general_options().open(my_backend);
	/// # }
	/// ```
	pub fn open_general(backend: B) -> Port<'a, B> {
		OpenGeneralOptions::default().open(backend)
	}
}
impl Port<'_, ()> {
	/// Get an [`OpenGeneralOptions`] to customize how the port is opened.
	pub fn open_general_options() -> OpenGeneralOptions {
		OpenGeneralOptions::default()
	}
}

#[cfg(any(test, doc, feature = "mock"))]
#[cfg_attr(all(doc, feature = "doc_cfg"), doc(cfg(feature = "mock")))]
impl<'a> Port<'a, Mock> {
	/// Open a Port with a [`Mock`] [`Backend`].
	///
	/// This is useful for writing unit/integration tests when an actual device is not available.
	/// Unlike other `Port::open*` functions, Message IDs and checksums are disabled by default to allow for easier testing.
	///
	/// See the [`Mock`]'s documentation for more details on its behaviour.
	///
	/// # Example
	///
	/// ```
	/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
	/// # #[cfg(feature = "mock")] // Only test the code if the "mock" feature is enabled
	/// # {
	/// # use zproto::ascii::Port;
	/// let mut port = Port::open_mock();
	/// port.backend_mut().push(b"@01 1 OK IDLE -- 1234\r\n");
	/// let reply = port.command_reply((1, 1, "get pos"))?.flag_ok()?;
	/// assert_eq!(reply.data().parse::<i32>().unwrap(), 1234);
	/// # }
	/// # Ok(())
	/// # }
	/// ```
	pub fn open_mock() -> Port<'a, Mock> {
		OpenMockOptions::new().open()
	}

	/// Get an [`OpenMockOptions`] to customize how a mock port is opened.
	pub fn open_mock_options() -> OpenMockOptions {
		OpenMockOptions::default()
	}
}

impl<'a, B, Tag, H> Port<'a, B, Tag, H>
where
	B: Backend,
	H: Handlers,
	H::PacketHandler: FnMut(&[u8], Direction) + 'a,
	H::UnexpectedAlertHandler: FnMut(Alert) -> Result<(), Alert> + 'a,
{
	/// Create a `Port` from a [`Backend`] type.
	fn from_backend(
		backend: B,
		generate_id: bool,
		generate_checksum: bool,
		max_packet_size: MaxPacketSize,
	) -> Self {
		Port {
			backend,
			ids: id::Counter::default(),
			generate_id,
			generate_checksum,
			max_packet_size,
			poison: None,
			builder: ResponseBuilder::default(),
			handlers: H::default(),
			tag: std::marker::PhantomData,
			lifetime: std::marker::PhantomData,
		}
	}

	/// Check if the port is poisoned and report the error if it exists.
	fn check_poisoned(&mut self) -> Result<(), io::Error> {
		if let Some(poison) = self.poison.take() {
			Err(poison)
		} else {
			Ok(())
		}
	}

	/// Convert the type of this port by "tagging" it with the type `T`.
	///
	/// This does not change the runtime behaviour of the port; it only changes
	/// how the compiler treats the port and the types generated from the port
	/// during compilation.
	///
	/// This is primarily used for differentiating multiple `Port`s from each
	/// other and preventing them from being used where they should not be.
	#[cfg_attr(
		unstable,
		doc = "

# Examples

When communicating with products over more than one port it can be easy
to pass the wrong port to the [`Routine`]s generated from a port's
[`Chain`]. In the best case, the command fails at run time, but in many
cases it simply results in incorrect data.

```
# use zproto::{ascii::Port, backend::Backend, error::AsciiError};
# fn wrapper<B: Backend>(mut port_a: Port<B>, mut port_b: Port<B>) -> Result<(), AsciiError> {
use zproto::ascii::setting::v_latest::SystemSerial;

let chain = port_a.chain()?;
for device in &chain {
    let get_system_serial = device.settings().get(SystemSerial);
    let _serial = port_b.run(get_system_serial)?;
    //            ^^^^^^ OOPS! This is the wrong port!
}
# Ok(())
# }
```

However, by tagging each port's type, we change the type of the port and
the types of the routines generated from it, turning the above runtime
error into a compiler error.

```compile_fail
# use zproto::{ascii::Port, backend::Backend, error::AsciiError};
# fn wrapper<B: Backend>(mut port_a: Port<B>, mut port_b: Port<B>) -> Result<(), AsciiError> {
use zproto::ascii::setting::v_latest::SystemSerial;

struct PortA;
let mut port_a = port_a.into_tagged::<PortA>();
let chain = port_a.chain()?; // Has a different type
for device in &chain {
    let get_system_serial = device.settings().get(SystemSerial); // Has a different type
    // Yay! This no longer compiles because the type of port_b is
    // incompatible with the type of get_system_serial.
    let _id = port_b.run(get_system_serial)?;
    // ERROR:        ^^^ the trait `Routine<Port<B>>` is not implemented for
    //                   `Get<SystemSerial, PortA>`
}
# Ok(())
# }
```

Using tagged ports can also be useful for ensuring functions receive
appropriate types.

```
# use zproto::ascii::{Port, chain::Chain};
fn do_something<Backend, Tag>(port: &mut Port<Backend, Tag>, chain: &Chain<Tag>) {
    // The chain is guaranteed to be associated with the port, assuming
    // each type Tag is a only used to tag one port.
    todo!()
}
```"
	)]
	pub fn into_tagged<T>(self) -> Port<'a, B, T, H> {
		Port {
			backend: self.backend,
			ids: self.ids,
			generate_id: self.generate_id,
			generate_checksum: self.generate_checksum,
			max_packet_size: self.max_packet_size,
			poison: self.poison,
			builder: self.builder,
			handlers: self.handlers,
			tag: std::marker::PhantomData,
			lifetime: std::marker::PhantomData,
		}
	}

	/// Convert this port into one that implements `Send` and can therefore be
	/// sent to another thread.
	///
	/// Returns an error if `Send` bounds could not be added. This is, if any
	/// event handlers are currently set. As such, it is recommended to call
	/// [`Port::try_into_send`] before setting handlers.
	///
	/// The [`Port::set_packet_handler`] and [`Port::set_unexpected_alert_handler`]
	/// methods on the new port will have an additional `Send` bound on any function
	/// used as an event handler.
	///
	/// # Example
	///
	/// ```
	/// # use zproto::{ascii::Port, backend::Backend};
	/// # use std::{error::Error, fmt::Debug};
	/// # fn wrapper<B: Backend + Debug + Send + 'static>(
	/// #     port: Port<'static, B>
	/// # ) -> Result<(), Box<dyn Error>> {
	/// use std::sync::{Arc, Mutex};
	///
	/// let port = Port::open_serial("...")?.try_into_send()?;
	/// let port = Arc::new(Mutex::new(port));
	///
	/// let mut handles = vec![];
	/// for i in 0..10 {
	///     let port = port.clone();
	///     let handle = std::thread::spawn(move || {
	///         let mut guard = port.lock().unwrap();
	///         // do something with the port ...
	///     });
	///     handles.push(handle);
	/// }
	///
	/// for handle in handles {
	///     let _ = handle.join();
	/// }
	/// # Ok(())
	/// # }
	/// ```
	pub fn try_into_send(mut self) -> Result<SendPort<'a, B, Tag>, TryIntoSendError>
	where
		B: Send,
	{
		if self.handlers.packet().is_some() || self.handlers.unexpected_alert().is_some() {
			return Err(TryIntoSendError::new());
		}
		Ok(Port {
			backend: self.backend,
			ids: self.ids,
			generate_id: self.generate_id,
			generate_checksum: self.generate_checksum,
			max_packet_size: self.max_packet_size,
			poison: self.poison,
			builder: self.builder,
			handlers: SendHandlers::default(),
			tag: std::marker::PhantomData,
			lifetime: std::marker::PhantomData,
		})
	}

	/// Send a command. A reply is not read.
	///
	/// On success, the generated message ID (if any) is returned.
	///
	/// If necessary, the command will be split into multiple packets so that no
	/// packet is longer than [`max_packet_size`](Self::max_packet_size).
	///
	/// ## Example
	///
	/// ```rust
	/// # use zproto::{ascii::Port, backend::Backend};
	/// # fn wrapper<B: Backend>(mut port: Port<B>) -> Result<(), Box<dyn std::error::Error>> {
	/// // Send the empty command.
	/// port.command("")?;
	/// # Ok(())
	/// # }
	/// ```
	pub fn command<C: Command>(&mut self, cmd: C) -> Result<Option<u8>, AsciiError> {
		self.check_poisoned()?;

		let mut buffer = Vec::new();
		let mut writer = CommandWriter::new(
			&cmd,
			&mut self.ids,
			self.generate_id,
			self.generate_checksum,
			self.max_packet_size,
		)?;
		let mut more_packets = true;
		while more_packets {
			more_packets = writer.write_packet(&mut buffer)?;
			log::debug!(
				"{} TX:   {}",
				self.backend
					.name()
					.unwrap_or_else(|| UNKNOWN_BACKEND_NAME.to_string()),
				String::from_utf8_lossy(buffer.as_slice()).trim_end()
			);
			self.backend.write_all(buffer.as_slice())?;
			if let Some(callback) = self.handlers.packet() {
				(callback)(buffer.as_slice(), Direction::Tx);
			}
			buffer.clear();
		}
		Ok(writer.id)
	}

	/// Transmit a command and receive a reply.
	///
	/// If necessary, the command will be split into multiple packets so that no packet is longer than
	/// [`max_packet_size`](Self::max_packet_size).
	///
	/// If the reply is split across multiple packets, the continuation messages will automatically be read.
	///
	/// The contents of the reply are not checked, as the [`NotChecked<Reply>`](NotChecked) return type indicates.
	/// To access the reply, the caller must check the contents of reply via one of the methods on [`NotChecked`].
	/// ## Example
	///
	/// ```rust
	/// # use zproto::{ascii::{Port, response::Reply}, backend::Backend};
	/// # fn wrapper<B: Backend>(mut port: Port<B>) -> Result<Reply, Box<dyn std::error::Error>> {
	/// let reply = port.command_reply("get maxspeed")?.check_minimal()?;
	/// # Ok(reply)
	/// # }
	/// ```
	pub fn command_reply<C>(&mut self, cmd: C) -> Result<NotChecked<Reply>, AsciiError>
	where
		C: Command,
	{
		self.internal_command_reply(&cmd)
	}

	/// Transmit a command and receive a reply.
	///
	/// If necessary, the command will be split into multiple packets so that no packet is longer than
	/// [`max_packet_size`](Self::max_packet_size).
	///
	/// If any response is spread across multiple packets, continuation packets will be read.
	fn internal_command_reply(
		&mut self,
		cmd: &dyn Command,
	) -> Result<NotChecked<Reply>, AsciiError> {
		let id = self.command(cmd)?;
		self.pre_receive_response();
		let response = self.receive_response(HeaderCheck::Matches {
			target: cmd.target(),
			id,
		})?;
		self.post_receive_response()?;
		Ok(response)
	}

	/// Transmit a command and then receive a reply and all subsequent info messages.
	///
	/// The reply and info messages are checked with the custom [`checker`](check::Check).
	///
	/// If necessary, the command will be split into multiple packets so that no packet is longer than
	/// [`max_packet_size`](Self::max_packet_size). If the reply or info messages are split across multiple
	/// packets, the continuation messages will automatically be read.
	///
	/// To avoid collecting the info messages into a vector use [`command_reply_infos_iter`](Port::command_reply_infos_iter).
	///
	/// ## Example
	///
	/// ```
	/// # use zproto::{
	/// #     ascii::{response::{check, AnyResponse}, Port},
	/// #     backend::Backend,
	/// #     error::{AsciiCheckError, AsciiError}
	/// # };
	/// # fn wrapper<B: Backend>(port: &mut Port<B>) -> Result<(), AsciiError> {
	/// let (reply, info_messages) = port.command_reply_infos(
	///    (1, "stream buffer 1 print"),
	///    check::minimal(),
	/// )?;
	/// # Ok(())
	/// # }
	/// ```
	pub fn command_reply_infos<C, K>(
		&mut self,
		cmd: C,
		checker: K,
	) -> Result<(Reply, Vec<Info>), AsciiError>
	where
		C: Command,
		K: check::Check<AnyResponse>,
	{
		let checker: &dyn check::Check<_> = &checker;
		let reply_checker = |reply| {
			checker
				.check(AnyResponse::from(reply))
				.map(|response| Reply::try_from(response).unwrap())
				.map_err(|err| AsciiCheckError::try_from(err).unwrap())
		};
		let info_checker = |info| {
			checker
				.check(AnyResponse::from(info))
				.map(|response| Info::try_from(response).unwrap())
				.map_err(|err| AsciiCheckError::try_from(err).unwrap())
		};
		let (reply, info_iter) = self.command_reply_infos_iter(cmd)?;
		let reply = reply.check(reply_checker)?;
		let mut infos = Vec::new();
		for result in info_iter {
			let info = result?.check(info_checker)?;
			infos.push(info);
		}
		Ok((reply, infos))
	}

	/// Transmit a command and return it's reply and an iterator to read all subsequent info messages when used.
	///
	/// If necessary, the command will be split into multiple packets so that no packet is longer than
	/// [`max_packet_size`](Self::max_packet_size). If the reply or info messages are split across multiple
	/// packets, the continuation messages will automatically be read.
	///
	/// The iterator produces a `Result<NotChecked<Info>>`, which must be handled by the caller on each iteration.
	///
	/// To simply check and collect all the info messages into a vector, use [`command_reply_infos`](Port::command_reply_infos).
	///
	/// ## Under The Hood
	///
	/// A common pattern in the ASCII protocol is to send additional information
	/// in info messages after replying to a command. In order to reliably
	/// receive all the info messages elicited by the command, an empty command
	/// (`/`) is sent to the same device. The reply to that message is
	/// guaranteed to come after the info messages from the previous command
	/// and so receipt of that reply signals the end of the previous command's
	/// info messages.
	///
	/// ## Errors
	///
	/// An error is returned if
	///   * any response other than the single reply and info messages elicited by the command are received or
	///   * a reply to the final empty command is never received.
	///
	/// ## Example
	///
	/// ```
	/// # use zproto::{
	/// #     ascii::{response::{check, AnyResponse}, Port},
	/// #     backend::Backend,
	/// #     error::{AsciiCheckError, AsciiError}
	/// # };
	/// # fn wrapper<B: Backend>(port: &mut Port<B>) -> Result<(), AsciiError> {
	/// let (reply, info_iter) = port.command_reply_infos_iter((1, "stream buffer 1 print"))?;
	/// let reply = reply.flag_ok()?;
	/// for result in info_iter {
	///     let info = result?.check_minimal()?;
	///     println!("{info:?}");
	/// }
	/// # Ok(())
	/// # }
	/// ```
	// The return type is complex, but making a type alias doesn't make it better.
	#[allow(clippy::type_complexity)]
	pub fn command_reply_infos_iter<C: Command>(
		&mut self,
		cmd: C,
	) -> Result<
		(
			NotChecked<Reply>,
			iter::InfosUntilSentinel<'_, 'a, B, Tag, H>,
		),
		AsciiError,
	> {
		self.internal_command_reply_infos_iter(&cmd)
	}

	// The return type is complex, but making a type alias doesn't make it better.
	#[allow(clippy::type_complexity)]
	fn internal_command_reply_infos_iter(
		&mut self,
		cmd: &dyn Command,
	) -> Result<
		(
			NotChecked<Reply>,
			iter::InfosUntilSentinel<'_, 'a, B, Tag, H>,
		),
		AsciiError,
	> {
		let target = cmd.target();
		let reply = self.internal_command_reply(cmd)?;
		let old_generate_id = self.set_message_ids(true);
		let result = self.command((target, ""));
		self.set_message_ids(old_generate_id);
		let sentinel_id = result?;
		let info_id = reply.id();
		Ok((
			reply,
			iter::InfosUntilSentinel::new(self, target, info_id, sentinel_id),
		))
	}

	/// Transmit a command, receive n replies, and check each reply with the [`strict`](check::strict) check.
	///
	/// If necessary, the command will be split into multiple packets so that no packet is longer than
	/// [`max_packet_size`](Self::max_packet_size).
	///
	/// If any of the replies are split across multiple packets, the continuation messages will automatically be read.
	///
	/// To avoid collecting the responses into a vector use [`command_reply_n_iter`](Port::command_reply_n_iter).
	///
	/// ## Example
	///
	/// ```rust
	/// # use zproto::{ascii::Port, backend::Backend};
	/// # fn wrapper<B: Backend>(mut port: Port<B>) -> Result<(), Box<dyn std::error::Error>> {
	/// use zproto::ascii::response::check::flag_ok;
	///
	/// let replies = port.command_reply_n("get system.serial", 5, flag_ok())?;
	/// # Ok(())
	/// # }
	/// ```
	pub fn command_reply_n<C, K>(
		&mut self,
		cmd: C,
		n: usize,
		checker: K,
	) -> Result<Vec<Reply>, AsciiError>
	where
		C: Command,
		K: check::Check<Reply>,
	{
		let mut replies = Vec::new();
		let checker: &dyn check::Check<_> = &checker;
		for result in self.internal_command_reply_n_iter(&cmd, n)? {
			replies.push(result?.check(checker)?);
		}
		Ok(replies)
	}

	/// Transmit a command and get an iterator that will read `n` responses of type `R` from the port when used.
	///
	/// If the response is split across multiple packets, the continuation messages will automatically be read.
	///
	/// The iterator produces a `Result<NotChecked<Reply>>`, which must be handled by the caller on each iteration.
	///
	/// To simply check and collect all the replies into a vector, use [`command_reply_n`](Port::command_reply_n).
	///
	/// ## Example
	///
	/// ```
	/// # use zproto::{ascii::{response::Info, Port}, backend::Backend};
	/// # fn wrapper<B: Backend>(mut port: Port<B>) -> Result<(), Box<dyn std::error::Error>> {
	/// for result in port.command_reply_n_iter("get device.id", 3)? {
	///     /// Handle any communication errors and check the contents of the reply.
	///     let reply = result?.flag_ok()?;
	///     println!("{}", reply.data());
	/// }
	/// # Ok(())
	/// # }
	/// ```
	pub fn command_reply_n_iter<C>(
		&mut self,
		cmd: C,
		n: usize,
	) -> Result<iter::NResponses<'_, 'a, B, Reply, Tag, H>, AsciiError>
	where
		C: Command,
	{
		self.internal_command_reply_n_iter(&cmd, n)
	}

	/// Transmit a command and get an iterator that will read `n` replies.
	///
	/// If necessary, the command will be split into multiple packets so that no packet is longer than
	/// [`max_packet_size`](Self::max_packet_size).
	///
	/// If any response is spread across multiple packets, continuation packets will be read.
	fn internal_command_reply_n_iter(
		&mut self,
		cmd: &dyn Command,
		n: usize,
	) -> Result<iter::NResponses<'_, 'a, B, Reply, Tag, H>, AsciiError> {
		let id = self.command(cmd)?;
		Ok(self.internal_response_n_iter(
			n,
			HeaderCheck::Matches {
				target: cmd.target(),
				id,
			},
		))
	}

	/// Transmit a command, receive replies until the port times out, and check each reply with the custom [`Check`](check::Check).
	///
	/// If necessary, the command will be split into multiple packets so that no packet is longer than
	/// [`max_packet_size`](Self::max_packet_size).
	///
	/// If any of the replies are split across multiple packets, the continuation messages will automatically be read.
	///
	/// To avoid collecting the responses into a vector use [`command_replies_until_timeout_iter`](Port::command_replies_until_timeout_iter).
	///
	/// ## Example
	///
	/// ```
	/// # use zproto::{ascii::Port, backend::Backend};
	/// # fn wrapper<B: Backend>(mut port: Port<B>) -> Result<(), Box<dyn std::error::Error>> {
	/// use zproto::ascii::response::check::flag_ok;
	///
	/// let replies = port.command_replies_until_timeout(
	///     "get system.serial",
	///     flag_ok(),
	/// )?;
	/// # Ok(())
	/// # }
	/// ```
	pub fn command_replies_until_timeout<C, K>(
		&mut self,
		cmd: C,
		checker: K,
	) -> Result<Vec<Reply>, AsciiError>
	where
		C: Command,
		K: check::Check<Reply>,
	{
		let mut replies = Vec::new();
		let checker: &dyn check::Check<_> = &checker;
		for result in self.internal_command_replies_until_timeout_iter(&cmd)? {
			replies.push(result?.check(checker)?);
		}
		Ok(replies)
	}

	/// Transmit a command and get an iterator that, when used, will read replies from the port until it times out.
	///
	/// If the response is split across multiple packets, the continuation messages will automatically be read.
	///
	/// The iterator produces a `Result<NotChecked<Reply>>`, which must be handled by the caller on each iteration.
	///
	/// To simply check and collect all the replies into a vector, use [`command_replies_until_timeout`](Port::command_replies_until_timeout).
	///
	/// ## Example
	///
	/// ```
	/// # use zproto::{ascii::{response::Info, Port}, backend::Backend};
	/// # fn wrapper<B: Backend>(mut port: Port<B>) -> Result<(), Box<dyn std::error::Error>> {
	/// for result in port.command_replies_until_timeout_iter("get device.id")? {
	///     /// Handle any communication errors and check the contents of the reply.
	///     let reply = result?.flag_ok()?;
	///     println!("{}", reply.data());
	/// }
	/// # Ok(())
	/// # }
	/// ```
	pub fn command_replies_until_timeout_iter<C>(
		&mut self,
		cmd: C,
	) -> Result<iter::ResponsesUntilTimeout<'_, 'a, B, Reply, Tag, H>, AsciiError>
	where
		C: Command,
	{
		self.internal_command_replies_until_timeout_iter(&cmd)
	}

	/// Transmit a command and get an iterator that, when used, will read replies from the port until it times out.
	///
	/// If necessary, the command will be split into multiple packets so that no packet is longer than
	/// [`max_packet_size`](Self::max_packet_size).
	///
	/// If any response is spread across multiple packets, continuation packets will be read.
	fn internal_command_replies_until_timeout_iter(
		&mut self,
		cmd: &dyn Command,
	) -> Result<iter::ResponsesUntilTimeout<'_, 'a, B, Reply, Tag, H>, AsciiError> {
		let id = self.command(cmd)?;
		Ok(
			self.internal_responses_until_timeout_iter(HeaderCheck::Matches {
				target: cmd.target(),
				id,
			}),
		)
	}

	/// Read the bytes for a packet.
	fn read_packet_bytes(&mut self) -> Result<Vec<u8>, AsciiError> {
		use crate::ascii::packet::AsciiExt as _;

		let mut buf = Vec::with_capacity(100);
		let mut found_start = false;

		// Read the first byte at the original timeout,
		let byte = std::io::Read::bytes(&mut self.backend).next().unwrap()?;
		if byte.is_packet_start() {
			buf.push(byte);
			found_start = true;
		}

		// Read the reset of the bytes at the inter-char timeout, unless the
		// specified timeout is even shorter. Packets should be sent all at
		// once, so the time between bytes should be smaller than the time
		// between packets.
		let timeout = self.backend.read_timeout()?;
		let inter_char_timeout = Duration::from_millis(300);
		let effective_timeout = timeout.unwrap_or(Duration::MAX);
		let use_inter_char_timeout = inter_char_timeout < effective_timeout;
		if use_inter_char_timeout {
			self.backend.set_read_timeout(Some(inter_char_timeout))?;
		}
		let result = || -> Result<(), AsciiError> {
			for byte in std::io::Read::bytes(&mut self.backend) {
				let byte = byte?;
				if byte.is_packet_start() {
					if found_start {
						// We are already in the middle of a packet. Something has gone wrong.
						return Err(AsciiPacketMissingEndError::new(buf.clone()).into());
					}
					found_start = true;
				}
				if found_start {
					buf.push(byte);
				}
				if byte == crate::ascii::packet::LINE_FEED {
					break;
				}
			}
			Ok(())
		}();
		// Make sure to restore the timeout if we need to
		if use_inter_char_timeout {
			self.backend.set_read_timeout(timeout)?;
		}
		if !found_start {
			return Err(AsciiPacketMissingStartError::new(buf).into());
		}
		if buf.is_empty() || *buf.last().unwrap() != crate::ascii::packet::LINE_FEED {
			return Err(AsciiPacketMissingEndError::new(buf).into());
		}
		result.map(move |()| buf)
	}

	/// Receive a response [`Packet`]
	///
	/// The packet's LRC is verified, and guaranteed not to be a Command packet.
	/// The contents of the packet are otherwise unchecked.
	fn response_packet(&mut self) -> Result<Packet, AsciiError> {
		let backend_name = self
			.backend
			.name()
			.unwrap_or_else(|| UNKNOWN_BACKEND_NAME.to_string());

		let raw_packet = self.read_packet_bytes()?;
		// Log the packet
		log::debug!(
			"{} RECV: {}",
			&backend_name,
			String::from_utf8_lossy(&raw_packet).trim_end()
		);

		if let Some(callback) = self.handlers.packet() {
			(callback)(raw_packet.as_slice(), Direction::Recv);
		}

		// Parse the packet.
		let packet = Packet::try_from(&*raw_packet)?;
		// Verify the checksum, if one exists
		if let Some(checksum) = packet.checksum() {
			if !Lrc::verify(packet.hashed_content(), checksum) {
				return Err(AsciiInvalidChecksumError::new(packet).into());
			}
		}
		// Make sure it isn't a command packet
		if packet.kind() == PacketKind::Command {
			Err(AsciiUnexpectedPacketError::new(packet).into())
		} else {
			Ok(packet)
		}
	}

	/// Read packets until we build up a complete response message.
	fn build_response(&mut self) -> Result<AnyResponse, AsciiError> {
		loop {
			// See if we already have a response built.
			if let Some(response) = self.builder.get_complete_response() {
				return Ok(response);
			}

			// There is no response built so we we need to read in another packet.
			// If doing so causes the port to timeout, or produce any other error,
			// we should report it immediately. At most we have a partially
			// completed response that will be lost.
			let packet = self.response_packet()?;
			self.builder.push(packet)?;
		}
	}

	/// Perform any work necessary to start reading responses with [`receive_response`].
	/// In particular it clears the `builder`.
	///
	/// This function should be called before the first time [`receive_response`]
	/// is called.
	#[inline]
	fn pre_receive_response(&mut self) {
		self.builder.clear();
	}

	/// Perform any work necessary to clean up after receiving one or more
	/// responses with [`receive_response`]. In particular, it will ensure the
	/// builder is empty and raise an error for any data remaining in the
	/// builder.
	///
	/// This function should be called after the last time [`receive_response`]
	/// is called.
	fn post_receive_response(&mut self) -> Result<(), AsciiError> {
		let mut inner = || -> Result<(), AsciiError> {
			if let Some(response) = self.builder.get_complete_response() {
				return Err(AsciiUnexpectedResponseError::new(response).into());
			}
			if let Some(packet) = self.builder.get_incomplete_response_packet() {
				return Err(AsciiUnexpectedPacketError::new(packet).into());
			}
			// There must not be any data remaining.
			Ok(())
		};

		if let Some(callback) = &mut self.handlers.unexpected_alert() {
			// There is an handler for alerts, check if we need to call it for any remaining responses.
			loop {
				match inner() {
					Ok(()) => return Ok(()), // There is no data remaining
					Err(AsciiError::UnexpectedResponse(err)) => {
						let response = err.into();
						match response {
							AnyResponse::Alert(alert) => match (callback)(alert) {
								// The handler accepted the alert, so continue checking any other messages.
								Ok(()) => {}
								// The handler did not accept the alert, so return the error.
								Err(alert) => {
									self.builder.clear();
									return Err(AsciiUnexpectedResponseError::new(alert).into());
								}
							},
							// Although this is an unexpected response, it isn't an alert.
							response => {
								self.builder.clear();
								return Err(AsciiUnexpectedResponseError::new(response).into());
							}
						}
					}
					// This isn't an unexpected response
					err => {
						self.builder.clear();
						return err;
					}
				}
			}
		} else {
			// There is no handle for unexpected response, so simply report any
			// errors directly to the caller.
			let result = inner();
			self.builder.clear();
			result
		}
	}

	/// Receiving a response.
	///
	/// Prior to calling this function for the first time, `pre_receive_response`
	/// should be called. After the last call to this function,
	/// `post_receive_response` should be called. Both of these functions
	/// ensure `self.builder` is in the appropriate state and that all errors
	/// are appropriately handled.
	///
	/// If the response is spread across multiple packets, continuation packets will be read.
	/// `header_check` should be a function that produces data for validating the response's header.
	///
	/// If the `header_check` passes, the message will be converted to the desired message type `R`.
	fn receive_response<R>(
		&mut self,
		header_check: HeaderCheck,
	) -> Result<NotChecked<R>, AsciiError>
	where
		R: Response,
		AnyResponse: From<<R as TryFrom<AnyResponse>>::Error>,
		AsciiError: From<AsciiCheckError<R>>,
	{
		self.check_poisoned()?;
		loop {
			let result = || -> Result<NotChecked<R>, AsciiError> {
				let mut response = self.build_response()?;
				response = header_check.check(response)?;
				R::try_from(response)
					.map(NotChecked::new)
					.map_err(AsciiUnexpectedResponseError::new)
					.map_err(From::from)
			}();
			if let Some(callback) = &mut self.handlers.unexpected_alert() {
				// There is an handler for alerts, check if we need to call it.
				match result {
					Err(AsciiError::UnexpectedResponse(err)) => {
						let response = err.into();
						match response {
							AnyResponse::Alert(alert) => match (callback)(alert) {
								// The handler accepted the alert, so receive another response.
								Ok(()) => {}
								// The handler did not accept the alert, so return the error.
								Err(alert) => {
									return Err(AsciiUnexpectedResponseError::new(alert).into());
								}
							},
							// Although this is an unexpected response, it isn't an alert.
							_ => return Err(AsciiUnexpectedResponseError::new(response).into()),
						}
					}
					// This isn't an unexpected response
					_ => return result,
				}
			} else {
				// There is no handler to try
				return result;
			}
		}
	}

	fn internal_response_n_iter<R>(
		&mut self,
		n: usize,
		header_check: HeaderCheck,
	) -> iter::NResponses<'_, 'a, B, R, Tag, H>
	where
		R: Response,
	{
		iter::NResponses::new(self, header_check, n)
	}

	/// Receive a response.
	///
	/// The type of response must be specified: [`Reply`], [`Info`], [`Alert`], or [`AnyResponse`].
	///
	/// If the response is split across multiple packets, the continuation messages will automatically be read.
	///
	/// ## Example
	///
	/// ```rust
	/// # use zproto::{ascii::{response::{Reply, Info}, Port}, backend::Backend};
	/// # fn wrapper<B: Backend>(mut port: Port<B>) -> Result<(), Box<dyn std::error::Error>> {
	/// let reply: Reply = port.response()?.check_minimal()?;
	/// let info: Info = port.response()?.check_minimal()?;
	/// # Ok(())
	/// # }
	/// ```
	pub fn response<R>(&mut self) -> Result<NotChecked<R>, AsciiError>
	where
		R: Response,
		AnyResponse: From<<R as TryFrom<AnyResponse>>::Error>,
		AsciiError: From<AsciiCheckError<R>>,
	{
		self.pre_receive_response();
		let response = self.receive_response(HeaderCheck::DoNotCheck)?;
		self.post_receive_response()?;
		Ok(response)
	}

	/// Generate an iterator that will read `n` response of type `R` from the port when used.
	///
	/// The type of response must be specified: [`Reply`], [`Info`], [`Alert`], or [`AnyResponse`].
	///
	/// If the response is split across multiple packets, the continuation messages will automatically be read.
	///
	/// The iterator produces a `Result<NotChecked<R>>`, which must be handled by the caller on each iteration.
	///
	/// To simply check and collect all the responses into a vector, use [`response_n`](Port::response_n).
	///
	/// ## Example
	///
	/// ```
	/// # use zproto::{ascii::{response::Info, Port}, backend::Backend};
	/// # fn do_something_with(_info: Info) {}
	/// # fn wrapper<B: Backend>(mut port: Port<B>) -> Result<(), Box<dyn std::error::Error>> {
	/// for result in port.response_n_iter(3) {
	///     /// Handle any communication errors and check the contents of the response.
	///     let response: Info = result?.check_minimal()?;
	///     do_something_with(response);
	/// }
	/// # Ok(())
	/// # }
	/// ```
	pub fn response_n_iter<R>(&mut self, n: usize) -> iter::NResponses<'_, 'a, B, R, Tag, H>
	where
		R: Response,
	{
		self.internal_response_n_iter(n, HeaderCheck::DoNotCheck)
	}

	/// Receive `n` responses, collecting them into a vector. Each one is checked with the custom [`Check`](check::Check).
	///
	/// The type of response must be specified: [`Reply`], [`Info`], [`Alert`], or [`AnyResponse`].
	///
	/// If the response is split across multiple packets, the continuation messages will automatically be read.
	///
	/// To avoid collecting the responses into a vector use [`response_n_iter`](Port::response_n_iter).
	///
	/// ## Example
	///
	/// ```rust
	/// # use zproto::{ascii::{response::Info, Port}, backend::Backend};
	/// # fn wrapper<B: Backend>(mut port: Port<B>) -> Result<(), Box<dyn std::error::Error>> {
	/// use zproto::ascii::response::check::unchecked;
	/// let reply: Vec<Info> = port.response_n(3, unchecked())?;
	/// # Ok(())
	/// # }
	/// ```
	pub fn response_n<R, K>(&mut self, n: usize, checker: K) -> Result<Vec<R>, AsciiError>
	where
		R: Response,
		K: check::Check<R>,
		AnyResponse: From<<R as TryFrom<AnyResponse>>::Error>,
		AsciiError: From<AsciiCheckError<R>>,
	{
		let mut responses = Vec::new();
		let checker: &dyn check::Check<R> = &checker;
		for result in self.internal_response_n_iter(n, HeaderCheck::DoNotCheck) {
			responses.push(result?.check(checker)?);
		}
		Ok(responses)
	}

	/// Receive responses until the port times out and validate each one with the custom [`Check`](check::Check).
	///
	/// The type of response must be specified: [`Reply`], [`Info`], [`Alert`], or [`AnyResponse`].
	///
	/// If any of the responses are split across multiple packets, the continuation messages will automatically be read.
	///
	/// ## Example
	///
	/// ```rust
	/// # use zproto::ascii::{response::AnyResponse, Port};
	/// # use zproto::backend::Backend;
	/// # fn wrapper<B: Backend>(mut port: Port<B>) -> Result<(), Box<dyn std::error::Error>> {
	/// use zproto::ascii::response::check::minimal;
	/// let reply: Vec<AnyResponse> = port.responses_until_timeout(minimal())?;
	/// # Ok(())
	/// # }
	/// ```
	pub fn responses_until_timeout<R, K>(&mut self, checker: K) -> Result<Vec<R>, AsciiError>
	where
		R: Response,
		K: check::Check<R>,
		AnyResponse: From<<R as TryFrom<AnyResponse>>::Error>,
		AsciiError: From<AsciiCheckError<R>>,
	{
		let mut responses = Vec::new();
		let checker: &dyn check::Check<_> = &checker;
		for result in self.internal_responses_until_timeout_iter(HeaderCheck::DoNotCheck) {
			responses.push(result?.check(checker)?);
		}
		Ok(responses)
	}

	/// Generate an iterator that will read responses of type `R` from the port until it times out.
	///
	/// The type of response must be specified: [`Reply`], [`Info`], [`Alert`], or [`AnyResponse`].
	///
	/// If the response is split across multiple packets, the continuation messages will automatically be read.
	///
	/// The iterator produces a `Result<NotChecked<R>>`, which must be handled by the caller on each iteration.
	///
	/// To simply check and collect all the responses into a vector, use [`responses_until_timeout`](Port::responses_until_timeout).
	///
	/// ## Example
	///
	/// ```
	/// # use zproto::{ascii::{response::Info, Port}, backend::Backend};
	/// # fn do_something_with(_info: Info) {}
	/// # fn wrapper<B: Backend>(mut port: Port<B>) -> Result<(), Box<dyn std::error::Error>> {
	/// for result in port.responses_until_timeout_iter() {
	///     /// Handle any communication errors and check the contents of the response.
	///     let response: Info = result?.check_minimal()?;
	///     do_something_with(response);
	/// }
	/// # Ok(())
	/// # }
	/// ```
	pub fn responses_until_timeout_iter<R>(
		&mut self,
	) -> iter::ResponsesUntilTimeout<'_, 'a, B, R, Tag, H>
	where
		R: Response,
	{
		self.internal_responses_until_timeout_iter(HeaderCheck::DoNotCheck)
	}

	fn internal_responses_until_timeout_iter<R>(
		&mut self,
		header_check: HeaderCheck,
	) -> iter::ResponsesUntilTimeout<'_, 'a, B, R, Tag, H>
	where
		R: Response,
	{
		iter::ResponsesUntilTimeout::new(self, header_check)
	}

	/// Return a iterator that will repeatedly send `command` and read a reply.
	///
	/// ## Example
	///
	/// ```
	/// # use zproto::ascii::{Port, response::Reply};
	/// # use zproto::backend::Backend;
	/// # use zproto::error::AsciiError;
	/// # fn wrapper<B: Backend>(port: &mut Port<'_, B>) -> Result<(), AsciiError> {
	/// for result in port.poll("get pos") {
	///     let reply = result?.flag_ok()?;
	///     let pos: i32 = reply.data().parse().unwrap();
	///     println!("{pos}");
	///     if pos > 50_000 {
	///         break
	///     }
	/// }
	/// # Ok(())
	/// # }
	/// ```
	pub fn poll<C>(&mut self, command: C) -> iter::Poll<'_, 'a, B, C, Tag, H>
	where
		C: Command,
	{
		iter::Poll {
			port: self,
			command,
		}
	}

	/// Send the specified command repeatedly until the predicate returns true
	/// for a reply.
	///
	/// The first reply to satisfy the predicate is returned. The contents of
	/// the replies are checked with the specified `checker`.
	///
	/// If necessary, the command will be split into multiple packets so that no
	/// packet is longer than [`max_packet_size`](Self::max_packet_size).
	///
	/// If any of the replies are split across multiple packets, the
	/// continuation messages will automatically be read.
	///
	/// ## Example
	///
	/// ```rust
	/// # use zproto::{ascii::{response::check, Port}, backend::Backend};
	/// # fn wrapper<B: Backend>(mut port: Port<B>) -> Result<(), Box<dyn std::error::Error>> {
	/// port.poll_until(
	///     (1, 1, ""),
	///     check::flag_ok(),
	///     |reply| reply.warning() != "FZ"
	/// )?;
	/// # Ok(())
	/// # }
	/// ```
	pub fn poll_until<C, K, F>(
		&mut self,
		cmd: C,
		checker: K,
		predicate: F,
	) -> Result<Reply, AsciiError>
	where
		C: Command,
		K: check::Check<Reply>,
		F: FnMut(&Reply) -> bool,
	{
		self.internal_poll_until(&cmd, &checker, predicate)
	}

	/// Send the specified command repeatedly until the predicate returns true
	/// for a reply.
	///
	/// If necessary, the command will be split into multiple packets so that no
	/// packet is longer than [`max_packet_size`](Self::max_packet_size).
	///
	/// If any response is spread across multiple packets, continuation packets will be read.
	fn internal_poll_until<F>(
		&mut self,
		cmd: &dyn Command,
		checker: &dyn check::Check<Reply>,
		mut predicate: F,
	) -> Result<Reply, AsciiError>
	where
		F: FnMut(&Reply) -> bool,
	{
		let mut reply;
		loop {
			reply = self.internal_command_reply(cmd)?.check(checker)?;
			if predicate(&reply) {
				break;
			}
		}
		Ok(reply)
	}

	/// Poll the target with the empty command until the returned status is IDLE.
	///
	/// The first reply with the IDLE status is returned. The contents of
	/// the replies are checked with the specified `checker`.
	///
	/// ## Example
	///
	/// ```
	/// # use zproto::{ascii::{response::check, Port}, backend::Backend};
	/// # fn wrapper<B: Backend>(mut port: Port<B>) -> Result<(), Box<dyn std::error::Error>> {
	/// port.poll_until_idle((1,1), check::flag_ok())?;
	/// # Ok(())
	/// # }
	/// ```
	pub fn poll_until_idle<T, K>(&mut self, target: T, checker: K) -> Result<Reply, AsciiError>
	where
		T: Into<Target>,
		K: check::Check<Reply>,
	{
		self.internal_poll_until(&(target.into(), ""), &checker, |reply| {
			reply.status() == Status::Idle
		})
	}

	/// Set the port timeout and return a "scope guard" that will reset the timeout when it goes out of scope.
	///
	/// If not timeout is specified, reads can block indefinitely.
	///
	/// While the guard is in scope, the port can only be accessed through the guard.
	/// However, because the guard implements [`Deref`](std::ops::Deref) and [`DerefMut`](std::ops::DerefMut) callers can treat the guard as the port.
	///
	/// ## Example
	/// ```rust
	/// # use zproto::{error::AsciiError, ascii::{Port, response::Reply}, backend::Backend};
	/// # use std::time::Duration;
	/// # fn helper<B: Backend>(mut port: Port<B>) -> Result<Reply, AsciiError> {
	/// {
	///     let mut guard = port.timeout_guard(Some(Duration::from_secs(3)))?;
	///     // All commands within this scope will use a 3 second timeout
	///     guard.command_reply("system reset")?.flag_ok()?;
	///
	/// }  // The guard is dropped and the timeout is reset.
	///
	/// // This command-reply uses the original timeout
	/// # Ok(
	/// port.command_reply("get device.id")?.flag_ok()?
	/// # )
	/// # }
	/// ```
	pub fn timeout_guard(
		&mut self,
		timeout: Option<Duration>,
	) -> Result<TimeoutGuard<'_, B, Self>, io::Error> {
		self.check_poisoned()?;

		TimeoutGuard::new(self, timeout)
	}

	/// Set whether commands sent on this port should include a checksum or not.
	///
	/// The previous value is returned.
	pub fn set_checksums(&mut self, value: bool) -> bool {
		std::mem::replace(&mut self.generate_checksum, value)
	}

	/// Get whether the port will include checksums or not in commands.
	pub fn checksums(&self) -> bool {
		self.generate_checksum
	}

	/// Set whether commands sent on this port should include an automatically generated message ID or not.
	///
	/// The previous value is returned.
	pub fn set_message_ids(&mut self, value: bool) -> bool {
		std::mem::replace(&mut self.generate_id, value)
	}

	/// Get whether the port will include message IDs or not in commands.
	pub fn message_ids(&self) -> bool {
		self.generate_id
	}

	/// Set the maximum command packet size.
	///
	/// The previous value is returned.
	pub fn set_max_packet_size(&mut self, value: MaxPacketSize) -> MaxPacketSize {
		std::mem::replace(&mut self.max_packet_size, value)
	}

	/// Get the maximum command packet size.
	pub fn max_packet_size(&self) -> MaxPacketSize {
		self.max_packet_size
	}

	/// Set the read timeout and return the old timeout.
	///
	/// If timeout is `None`, reads will block indefinitely.
	pub fn set_read_timeout(
		&mut self,
		timeout: Option<Duration>,
	) -> Result<Option<Duration>, io::Error> {
		let old = self.backend.read_timeout()?;
		self.backend.set_read_timeout(timeout)?;
		Ok(old)
	}

	/// Get the read timeout.
	///
	/// If it is `None`, reads will block indefinitely.
	pub fn read_timeout(&self) -> Result<Option<Duration>, io::Error> {
		self.backend.read_timeout()
	}

	/// Get the "name" of the port's backend.
	///
	/// This is often the "name" passed to [`Port::open_serial`] or [`Port::open_tcp`].
	pub fn name(&self) -> Option<String> {
		self.backend.name()
	}

	/// Get a referenced to the backend.
	pub fn backend(&self) -> &B {
		&self.backend
	}

	/// Get a mutable reference to the backend.
	pub fn backend_mut(&mut self) -> &mut B {
		&mut self.backend
	}

	/// Consume the port and return the underlying backend.
	///
	/// Note that any data the port has buffered will be lost. Callers should
	/// ensure that all expected data has been sent and received.
	pub fn into_backend(self) -> B {
		self.backend
	}

	/// Create a [`Chain`].
	#[cfg(unstable)]
	pub fn chain(&mut self) -> Result<Chain<Tag>, AsciiError> {
		Chain::new(self)
	}

	/// Converts the specified `item` into a [`Routine`] and runs it, returning the result.
	#[cfg(unstable)]
	pub fn run<R: IntoRoutine<Self>>(&mut self, item: R) -> Result<R::Output, R::Error> {
		item.into_routine().run(self)
	}

	/// Set a callback that will be called immediately after any ASCII packet is
	/// sent or received.
	///
	/// If a previous callback was set, it is returned.
	///
	/// To clear a previously registered callback use [`clear_packet_handler`](Port::clear_packet_handler).
	///
	/// The callback will be passed the raw bytes of a possible packet and the
	/// direction of the packet. The bytes are not guaranteed to be a valid
	/// ASCII packet. Parse the bytes with [`Packet`] or [`Tokens`](crate::ascii::packet::Tokens)
	/// to inspect the contents of the packet.
	///
	/// Note, the Port already logs packets (along with other metadata) via the
	/// [`log`] crate, so logging is best handled via a log handler, such as
	/// [`simple_logger`](https://crates.io/crates/simple_logger), rather than
	/// a packet callback. However, there are instances when you need access to
	/// the packets directly (for instance, to show them in an application),
	/// which is when a packet callback is most useful.
	///
	/// ## Examples
	///
	/// Any closure can be used as a callback.
	///
	/// ```
	/// # use zproto::ascii::Port;
	/// #
	/// # fn wrapper() -> Result<(), Box<dyn std::error::Error>> {
	/// # let mut port = Port::open_serial("...")?;
	/// port.set_packet_handler(|packet, dir| {
	///     println!("{dir:?}: {packet:?}");
	/// });
	/// # Ok(())
	/// # }
	/// ```
	///
	/// However, if the closure captures any variables those variables must
	/// either be moved into the closure with the `move` keyword (e.g., `move |packet, dir| {...}`)
	/// or live at least as long as the `Port` instance. Additionally, if those
	/// variables are mutated but also accessed outside of the closure, then a
	/// [`RefCell`](std::cell::RefCell)/[`Mutex`](std::sync::Mutex) should be
	/// used to facilitate the sharing.
	///
	/// ```
	/// # use zproto::ascii::Port;
	/// # use std::cell::RefCell;
	/// #
	/// # fn wrapper() -> Result<(), Box<dyn std::error::Error>> {
	/// let packet_list = RefCell::new(Vec::new());
	/// let mut port = Port::open_serial("...")?;
	/// port.set_packet_handler(|packet, _| {
	///     if let Ok(mut packets) = packet_list.try_borrow_mut() {
	///         packets.push(String::from_utf8_lossy(packet).into_owned());
	///     }
	/// });
	///
	/// port.command_reply((1, "home"));
	///
	/// for packet_str in packet_list.borrow().iter() {
	///     println!("{packet_str}");
	/// }
	/// # Ok(())
	/// # }
	/// ```
	pub fn set_packet_handler<F>(&mut self, callback: F) -> Option<H::PacketHandler>
	where
		H::PacketHandler: crate::convert::From<F>,
	{
		std::mem::replace(
			self.handlers.packet(),
			Some(crate::convert::From::from(callback)),
		)
	}

	/// Clear any callback registered via [`set_packet_handler`](Port::set_packet_handler) and return it.
	pub fn clear_packet_handler(&mut self) -> Option<H::PacketHandler> {
		self.handlers.packet().take()
	}

	/// Set a callback that will be called whenever an unexpected Alert is
	/// received.
	///
	/// If a previous callback was set, it is returned.
	///
	/// To clear a previously registered callback use [`clear_unexpected_alert_handler`](Port::clear_unexpected_alert_handler).
	///
	/// If the callback consumes the alert, returning `Ok(())`, the unexpected
	/// alert will not be reported to the caller of whatever method read the
	/// alert, and another response will be read in its place. If the callback
	/// does not consume the alert, returning it as an `Err`, whatever method
	/// read the alert will return it as an [`AsciiUnexpectedResponseError`].
	///
	/// Note that a `Port` does not try to read a response unless the caller
	/// explicitly calls a method to do so. So any Alert sent while the `Port`
	/// is not reading will not trigger this callback. Furthermore, explicitly
	/// reading an alert will also not trigger this callback -- only unexpected
	/// alert messages will trigger this callback.
	///
	/// ## Example
	///
	///
	/// ```
	/// # use std::cell::Cell;
	/// #
	/// # fn wrapper() -> Result<(), Box<dyn std::error::Error>> {
	/// use zproto::ascii::{Port, response::check::minimal};
	///
	/// let mut port = Port::open_serial("...")?;
	///
	/// // Read a potentially large number of info messages. However, to ensure
	/// // that the read isn't interrupted by any unexpected alerts, first
	/// // configure the port to effectively ignore the alerts it may receive by
	/// // dropping them.
	/// port.set_unexpected_alert_handler(|_alert| Ok(()));
	/// let (_reply, _infos) = port.command_reply_infos((1, "storage all print"), minimal())?;
	/// // ...
	/// # Ok(())
	/// # }
	/// ```
	pub fn set_unexpected_alert_handler<F>(
		&mut self,
		callback: F,
	) -> Option<H::UnexpectedAlertHandler>
	where
		H::UnexpectedAlertHandler: crate::convert::From<F>,
	{
		std::mem::replace(
			self.handlers.unexpected_alert(),
			Some(crate::convert::From::from(callback)),
		)
	}

	/// Clear any callback registered via [`set_unexpected_alert_handler`](Port::set_unexpected_alert_handler) and return it.
	pub fn clear_unexpected_alert_handler(&mut self) -> Option<H::UnexpectedAlertHandler> {
		self.handlers.unexpected_alert().take()
	}
}

impl<'a, B, Tag, H> io::Write for Port<'a, B, Tag, H>
where
	B: Backend,
	H: Handlers,
	H::PacketHandler: FnMut(&[u8], Direction) + 'a,
	H::UnexpectedAlertHandler: FnMut(Alert) -> Result<(), Alert> + 'a,
{
	fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
		self.check_poisoned()?;
		self.backend.write(buf)
	}

	fn flush(&mut self) -> io::Result<()> {
		self.check_poisoned()?;
		self.backend.flush()
	}
}

impl<'a, B, Tag, H> io::Read for Port<'a, B, Tag, H>
where
	B: Backend,
	H: Handlers,
	H::PacketHandler: FnMut(&[u8], Direction) + 'a,
	H::UnexpectedAlertHandler: FnMut(Alert) -> Result<(), Alert> + 'a,
{
	fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
		self.check_poisoned()?;
		self.backend.read(buf)
	}
}

impl<B: Backend, Tag, H> crate::timeout_guard::Port<B> for Port<'_, B, Tag, H> {
	fn backend_mut(&mut self) -> &mut B {
		&mut self.backend
	}
	fn poison(&mut self, e: io::Error) {
		self.poison = Some(e);
	}
}

/// How the header of a message should be checked.
#[derive(Debug, Copy, Clone)]
pub(super) enum HeaderCheck {
	/// Do not check the header
	DoNotCheck,
	/// Check that the header has a target and ID that matches these.
	Matches { target: Target, id: Option<u8> },
	/// Check that all responses have the specified target. Replies should have
	/// the `sentinel_id` and info messages should have the `info_id`.
	InfoSentinelReplyMatches {
		target: Target,
		info_id: Option<u8>,
		sentinel_id: Option<u8>,
	},
}

impl HeaderCheck {
	fn check(self, response: AnyResponse) -> Result<AnyResponse, AsciiError> {
		use HeaderCheck as HC;
		match self {
			HC::DoNotCheck => Ok(response),
			HC::Matches { target, id } => {
				if !response.target().elicited_by_command_to(target) || response.id() != id {
					Err(AsciiUnexpectedResponseError::new(response).into())
				} else {
					Ok(response)
				}
			}
			HC::InfoSentinelReplyMatches {
				target,
				info_id,
				sentinel_id,
			} => {
				if !response.target().elicited_by_command_to(target) {
					return Err(AsciiUnexpectedResponseError::new(response).into());
				}
				match response {
					AnyResponse::Info(ref info) if info.id() == info_id => Ok(response),
					AnyResponse::Reply(ref reply) if reply.id() == sentinel_id => Ok(response),
					_ => Err(AsciiUnexpectedResponseError::new(response).into()),
				}
			}
		}
	}
}