kermit_proto/lib.rs
1//! Sans-IO Kermit protocol for talking to HP calculators.
2//!
3//! The crate never touches a port, a clock or a file. The caller owns all
4//! three: it reads and writes the link, supplies the current [`Instant`]
5//! ([`time::Instant`]) and loads or stores file contents. [`Client`] is a
6//! pure state machine in between.
7//!
8//! Two roles. [`Client`]: we are the host (user Kermit), the calculator is
9//! the server (the 48 and 49). [`Server`]: the calculator is the client and
10//! we are the "disk drive" it sends to and gets from (the 38G, 39G and 40G;
11//! wiki: protocols/aplet-transfer). Both share the codec, the prefixing and
12//! the Send-Init negotiation, and the same seam; what follows describes the
13//! client, and the [`Server`] docs say where the server differs.
14//!
15//! # The seam
16//!
17//! - [`Client::start`] begins a transaction ([`Command`]); the first packet is
18//! queued at once. It returns a [`StartError`] while a transaction is
19//! running or if the command does not fit in one packet.
20//! - [`Client::handle_input`] feeds bytes read from the link, in any chunking.
21//! - [`Client::handle_timeout`] tells the client that time has passed; call it
22//! when [`Client::next_timeout`] is reached (or whenever a read times out;
23//! it does nothing early).
24//! - [`Client::poll_output`] hands out the next packet to write. Each result is
25//! exactly one packet including padding and EOL. The transport must put it
26//! on the wire as one unit, without inter-byte gaps, because gaps overrun
27//! the HP's receiver. `write_all` alone does not promise that (it may
28//! issue several writes); it is enough where one write of a short buffer
29//! is not split, as on a TCP socket to an emulator or a serial port with
30//! a large enough output buffer.
31//! - [`Client::poll_event`] yields [`Event`]s: file starts, data, progress,
32//! server text and finally exactly one `Done` or `Error`.
33//! - [`Client::next_timeout`] is the earliest instant at which the client wants
34//! to be called again: a delayed packet becomes due (`packet_pause`), the
35//! retransmit deadline expires or the linger after a receive ends. Use it
36//! as the read timeout.
37//!
38//! Every call that can queue output takes `now`, so delays and deadlines are
39//! computed from the caller's clock. After `Done` or `Error` keep calling
40//! `poll_output` until it returns `None`: the final ACK or an E packet may
41//! still be queued. After a receive (`Get`, or a long reply to `Host` or
42//! `Directory`) the client lingers for [`Config::linger`] to re-ACK a
43//! retransmitted `B` in case the final ACK was lost; keep driving it until
44//! [`Client::next_timeout`] is `None`, or [`Client::start`] the next command,
45//! which ends the linger.
46//!
47//! In server mode the HP periodically NAKs packet 0 while idle, so a stale NAK
48//! can be in the pipe right after connecting. Discarding input for about
49//! 0.5 s after opening the link is the transport's job; the state machine
50//! also tolerates a stale NAK that slips through (it waits
51//! [`Config::nak_grace`] before resending).
52//!
53//! A server runs a host command (`C`) when it receives it and cannot tell a
54//! retransmission from a new command. [`Config::first_packet_retries`]
55//! limits the resends of the packet that starts a transaction separately:
56//! `Some(0)` sends a `C` once, while the reply packets after the server's
57//! `S` keep [`Config::retries`].
58//!
59//! A server also NAKs a command packet it rejects, and that NAK is
60//! byte-identical to the idle server's periodic one. With
61//! [`Config::first_packet_nak_window`] set, a NAK that arrives within the
62//! window after the packet went out (its time on the wire plus slack) is
63//! taken as a rejection: it allows exactly one resend beyond
64//! [`Config::first_packet_retries`], after [`Config::first_packet_nak_grace`]
65//! and only if no answer arrived by then. A NAK sooner than the packet's
66//! wire time ([`Config::first_packet_nak_byte_time`] per byte) cannot answer
67//! it and is stale, like later NAKs; a second NAK and timeouts never resend.
68//! The residual risk is a periodic NAK the idle server sends just after our
69//! packet's wire time, inside the window, while it took the packet: the
70//! command then runs twice if its answer takes longer than the grace.
71//!
72//! # Time and WebAssembly
73//!
74//! The state machine never reads a clock: every call that needs the time
75//! takes `now` from the caller. The type is [`time::Instant`], which is
76//! `std::time::Instant` on every target except `wasm32`, where it is
77//! `web_time::Instant` from the [`web-time`](https://docs.rs/web-time) crate
78//! (`std::time::Instant::now()` panics on `wasm32-unknown-unknown`). A wasm
79//! caller names it as `kermit_proto::time::Instant` and creates it with
80//! `Instant::now()`, which `web-time` backs with `performance.now()` in the
81//! browser. [`time::Duration`] is `core::time::Duration` everywhere.
82//!
83//! # Driver loop
84//!
85//! ```no_run
86//! use std::io::{ErrorKind, Read, Write};
87//! use std::net::TcpStream;
88//! use std::time::{Duration, Instant};
89//! use kermit_proto::{Client, Command, Config, Event};
90//!
91//! fn main() -> std::io::Result<()> {
92//! let mut link = TcpStream::connect("localhost:4848")?;
93//! let mut client = Client::new(Config::default());
94//! client
95//! .start(Instant::now(), Command::Host(b"6 7 *".to_vec()))
96//! .map_err(std::io::Error::other)?;
97//! let mut finished = false;
98//! let mut buf = [0u8; 512];
99//! loop {
100//! let now = Instant::now();
101//! while let Some(packet) = client.poll_output(now) {
102//! // A whole packet per call; the link must not split it.
103//! link.write_all(&packet)?;
104//! }
105//! while let Some(event) = client.poll_event() {
106//! match event {
107//! Event::ServerText(text) => println!("{}", String::from_utf8_lossy(&text)),
108//! Event::Done | Event::Error(_) => finished = true,
109//! _ => {}
110//! }
111//! }
112//! let wait = match client.next_timeout() {
113//! Some(t) => t.saturating_duration_since(now),
114//! None if finished => break, // idle and nothing left to write
115//! None => Duration::from_millis(100),
116//! };
117//! link.set_read_timeout(Some(wait.max(Duration::from_millis(10))))?;
118//! match link.read(&mut buf) {
119//! Ok(0) => break,
120//! Ok(n) => client.handle_input(Instant::now(), &buf[..n]),
121//! Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {
122//! client.handle_timeout(Instant::now())
123//! }
124//! Err(e) => return Err(e),
125//! }
126//! }
127//! Ok(())
128//! }
129//! ```
130//!
131//! The lower layers are public for tools and tests: [`codec`] (framing and
132//! block checks), [`prefix`] (control/8th-bit/repeat prefixing), [`params`]
133//! (Send-Init negotiation) and [`trace`] (the text trace format).
134//!
135//! [`Instant`]: time::Instant
136
137mod client;
138pub mod codec;
139pub mod params;
140pub mod prefix;
141mod server;
142#[cfg(test)]
143mod server_trace_tests;
144pub mod trace;
145#[cfg(test)]
146mod trace_tests;
147
148/// The clock types of the seam: `std::time` everywhere except `wasm32`,
149/// where they come from `web-time` (see the crate docs, "Time and
150/// WebAssembly").
151pub mod time {
152 #[cfg(not(target_arch = "wasm32"))]
153 pub use std::time::{Duration, Instant};
154 #[cfg(target_arch = "wasm32")]
155 pub use web_time::{Duration, Instant};
156}
157
158pub use client::{Client, Command, Config, Error, Event, OutgoingFile, StartError};
159pub use codec::BlockCheck;
160pub use params::InitParams;
161pub use server::{NoRequest, Server, ServerConfig, ServerEvent};