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
//! Sans-IO Kermit protocol for talking to HP calculators.
//!
//! The crate never touches a port, a clock or a file. The caller owns all
//! three: it reads and writes the link, supplies the current [`Instant`]
//! ([`time::Instant`]) and loads or stores file contents. [`Client`] is a
//! pure state machine in between.
//!
//! Only client mode is implemented: we are the host (user Kermit), the
//! calculator is the server.
//!
//! # The seam
//!
//! - [`Client::start`] begins a transaction ([`Command`]); the first packet is
//! queued at once. It returns a [`StartError`] while a transaction is
//! running or if the command does not fit in one packet.
//! - [`Client::handle_input`] feeds bytes read from the link, in any chunking.
//! - [`Client::handle_timeout`] tells the client that time has passed; call it
//! when [`Client::next_timeout`] is reached (or whenever a read times out;
//! it does nothing early).
//! - [`Client::poll_output`] hands out the next packet to write. Each result is
//! exactly one packet including padding and EOL. The transport must put it
//! on the wire as one unit, without inter-byte gaps, because gaps overrun
//! the HP's receiver. `write_all` alone does not promise that (it may
//! issue several writes); it is enough where one write of a short buffer
//! is not split, as on a TCP socket to an emulator or a serial port with
//! a large enough output buffer.
//! - [`Client::poll_event`] yields [`Event`]s: file starts, data, progress,
//! server text and finally exactly one `Done` or `Error`.
//! - [`Client::next_timeout`] is the earliest instant at which the client wants
//! to be called again: a delayed packet becomes due (`packet_pause`), the
//! retransmit deadline expires or the linger after a receive ends. Use it
//! as the read timeout.
//!
//! Every call that can queue output takes `now`, so delays and deadlines are
//! computed from the caller's clock. After `Done` or `Error` keep calling
//! `poll_output` until it returns `None`: the final ACK or an E packet may
//! still be queued. After a receive (`Get`, or a long reply to `Host` or
//! `Directory`) the client lingers for [`Config::linger`] to re-ACK a
//! retransmitted `B` in case the final ACK was lost; keep driving it until
//! [`Client::next_timeout`] is `None`, or [`Client::start`] the next command,
//! which ends the linger.
//!
//! In server mode the HP periodically NAKs packet 0 while idle, so a stale NAK
//! can be in the pipe right after connecting. Discarding input for about
//! 0.5 s after opening the link is the transport's job; the state machine
//! also tolerates a stale NAK that slips through (it waits
//! [`Config::nak_grace`] before resending).
//!
//! A server runs a host command (`C`) when it receives it and cannot tell a
//! retransmission from a new command. [`Config::first_packet_retries`]
//! limits the resends of the packet that starts a transaction separately:
//! `Some(0)` sends a `C` once, while the reply packets after the server's
//! `S` keep [`Config::retries`].
//!
//! A server also NAKs a command packet it rejects, and that NAK is
//! byte-identical to the idle server's periodic one. With
//! [`Config::first_packet_nak_window`] set, a NAK that arrives within the
//! window after the packet went out (its time on the wire plus slack) is
//! taken as a rejection: it allows exactly one resend beyond
//! [`Config::first_packet_retries`], after [`Config::first_packet_nak_grace`]
//! and only if no answer arrived by then. A NAK sooner than the packet's
//! wire time ([`Config::first_packet_nak_byte_time`] per byte) cannot answer
//! it and is stale, like later NAKs; a second NAK and timeouts never resend.
//! The residual risk is a periodic NAK the idle server sends just after our
//! packet's wire time, inside the window, while it took the packet: the
//! command then runs twice if its answer takes longer than the grace.
//!
//! # Time and WebAssembly
//!
//! The state machine never reads a clock: every call that needs the time
//! takes `now` from the caller. The type is [`time::Instant`], which is
//! `std::time::Instant` on every target except `wasm32`, where it is
//! `web_time::Instant` from the [`web-time`](https://docs.rs/web-time) crate
//! (`std::time::Instant::now()` panics on `wasm32-unknown-unknown`). A wasm
//! caller names it as `kermit_proto::time::Instant` and creates it with
//! `Instant::now()`, which `web-time` backs with `performance.now()` in the
//! browser. [`time::Duration`] is `core::time::Duration` everywhere.
//!
//! # Driver loop
//!
//! ```no_run
//! use std::io::{ErrorKind, Read, Write};
//! use std::net::TcpStream;
//! use std::time::{Duration, Instant};
//! use kermit_proto::{Client, Command, Config, Event};
//!
//! fn main() -> std::io::Result<()> {
//! let mut link = TcpStream::connect("localhost:4848")?;
//! let mut client = Client::new(Config::default());
//! client
//! .start(Instant::now(), Command::Host(b"6 7 *".to_vec()))
//! .map_err(std::io::Error::other)?;
//! let mut finished = false;
//! let mut buf = [0u8; 512];
//! loop {
//! let now = Instant::now();
//! while let Some(packet) = client.poll_output(now) {
//! // A whole packet per call; the link must not split it.
//! link.write_all(&packet)?;
//! }
//! while let Some(event) = client.poll_event() {
//! match event {
//! Event::ServerText(text) => println!("{}", String::from_utf8_lossy(&text)),
//! Event::Done | Event::Error(_) => finished = true,
//! _ => {}
//! }
//! }
//! let wait = match client.next_timeout() {
//! Some(t) => t.saturating_duration_since(now),
//! None if finished => break, // idle and nothing left to write
//! None => Duration::from_millis(100),
//! };
//! link.set_read_timeout(Some(wait.max(Duration::from_millis(10))))?;
//! match link.read(&mut buf) {
//! Ok(0) => break,
//! Ok(n) => client.handle_input(Instant::now(), &buf[..n]),
//! Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {
//! client.handle_timeout(Instant::now())
//! }
//! Err(e) => return Err(e),
//! }
//! }
//! Ok(())
//! }
//! ```
//!
//! The lower layers are public for tools and tests: [`codec`] (framing and
//! block checks), [`prefix`] (control/8th-bit/repeat prefixing), [`params`]
//! (Send-Init negotiation) and [`trace`] (the text trace format).
//!
//! [`Instant`]: time::Instant
/// The clock types of the seam: `std::time` everywhere except `wasm32`,
/// where they come from `web-time` (see the crate docs, "Time and
/// WebAssembly").
pub use ;
pub use BlockCheck;
pub use InitParams;