Skip to main content

xmodem_proto/
lib.rs

1//! Sans-IO XModem for talking to HP calculators: 128-byte and 1k blocks,
2//! checksum and CRC-16, both roles.
3//!
4//! The crate never touches a port, a clock or a file. The caller owns all
5//! three: it reads and writes the link, supplies the current [`Instant`]
6//! ([`time::Instant`]) and loads or stores file contents. [`Transfer`] is a
7//! pure state machine in between, with the same seam as `kermit-proto`.
8//!
9//! - Sender ([`Command::Send`]): the calculator runs `XRECV`. We wait for its
10//!   start character, NAK (checksum), `C` (CRC-16) or `D` (HP's CRC,
11//!   [`Check::HpCrc`]), and use whichever it asks for. The 49G asks with `D`,
12//!   the 48GX with NAK.
13//! - Receiver ([`Command::Receive`]): the calculator runs `XSEND`. We send `D`
14//!   (by default; see [`Config::check`]) [`Config::crc_attempts`] times, then
15//!   fall back to NAK (checksum). The 49G answers `D`, the 48GX only NAK;
16//!   neither answers `C`.
17//!
18//! HP specifics live in the caller: starting `XRECV`/`XSEND` on the
19//! calculator, and stripping the padding of the last block (the receiver hands
20//! back every byte it received; [`Event::FileEnd`] says how much padding there
21//! can be).
22//!
23//! # Starting a transfer on the calculator
24//!
25//! `XRECV` and `XSEND` do not run inside the Kermit server: sent as a Kermit
26//! `C` packet, both fail with "Port Not Available" on the 49G and the 48GX,
27//! even after `CLOSEIO`. The server answers the `C` packet with its usual
28//! reply (S, X, D packets carrying the error and the stack, which still holds
29//! the name) and stays in server mode. The calculator must leave the server
30//! (Kermit FINISH, or ON) and run the command itself, e.g. typed on the
31//! keyboard. The machine tolerates a Kermit packet in the pipe before the
32//! first start character or block. Verified on the emulated 49G and 48GX
33//! (traces `49g-server-xrecv`, `48gx-server-xsend`).
34//!
35//! # The seam
36//!
37//! - [`Transfer::start`] begins a transfer. A receiver's first start character
38//!   is queued at once; a sender waits for the receiver.
39//! - [`Transfer::handle_input`] feeds bytes read from the link, in any
40//!   chunking. Bytes of a Kermit packet (SOH .. CR) that arrive before the
41//!   transfer starts are skipped.
42//! - [`Transfer::handle_timeout`] tells the machine that time has passed; call
43//!   it when [`Transfer::next_timeout`] is reached (it does nothing early).
44//! - [`Transfer::poll_output`] hands out the next write: one whole block, one
45//!   control byte, or the CAN sequence. The transport must put each on the
46//!   wire as one unit, without inter-byte gaps, because gaps overrun the HP's
47//!   receiver. `write_all` alone does not promise that (it may issue several
48//!   writes); it is enough where one write of a buffer this size is not
49//!   split, as on a TCP socket to an emulator or a serial port with a large
50//!   enough output buffer.
51//! - [`Transfer::poll_event`] yields [`Event`]s: `Started`, `Progress`, a
52//!   receiver's `FileEnd`, and finally exactly one `Done` or `Error`.
53//! - [`Transfer::next_timeout`] is the earliest instant at which the machine
54//!   wants to be called again (reply deadline, start-character interval,
55//!   inter-byte timeout, quiet line before a NAK, end of the linger). Use it
56//!   as the read timeout.
57//!
58//! Every call that can queue output takes `now`, so retransmit deadlines are
59//! computed from the caller's clock. After `Done` or `Error` keep calling
60//! `poll_output` until it returns `None`: the final ACK or the CANs may still
61//! be queued. A receiver then lingers for [`Config::linger`] to re-ACK a
62//! retransmitted EOT in case the final ACK was lost; keep driving it until
63//! [`Transfer::next_timeout`] is `None`, or [`Transfer::start`] the next
64//! transfer, which ends the linger.
65//!
66//! # Time and WebAssembly
67//!
68//! The state machine never reads a clock: every call that needs the time
69//! takes `now` from the caller. The type is [`time::Instant`], which is
70//! `std::time::Instant` on every target except `wasm32`, where it is
71//! `web_time::Instant` from the [`web-time`](https://docs.rs/web-time) crate
72//! (`std::time::Instant::now()` panics on `wasm32-unknown-unknown`). A wasm
73//! caller names it as `xmodem_proto::time::Instant` and creates it with
74//! `Instant::now()`, which `web-time` backs with `performance.now()` in the
75//! browser. [`time::Duration`] is `core::time::Duration` everywhere.
76//!
77//! # Driver loop
78//!
79//! ```no_run
80//! use std::io::{ErrorKind, Read, Write};
81//! use std::net::TcpStream;
82//! use std::time::{Duration, Instant};
83//! use xmodem_proto::{Command, Config, Event, Transfer};
84//!
85//! fn main() -> std::io::Result<()> {
86//!     let mut link = TcpStream::connect("localhost:4848")?;
87//!     let mut xfer = Transfer::new(Config::default());
88//!     xfer.start(Instant::now(), Command::Receive)
89//!         .map_err(std::io::Error::other)?;
90//!     let mut finished = false;
91//!     let mut buf = [0u8; 2048];
92//!     loop {
93//!         let now = Instant::now();
94//!         while let Some(bytes) = xfer.poll_output(now) {
95//!             // A whole block per call; the link must not split it.
96//!             link.write_all(&bytes)?;
97//!         }
98//!         while let Some(event) = xfer.poll_event() {
99//!             match event {
100//!                 Event::FileEnd { data, .. } => std::fs::write("file.hp", data)?,
101//!                 Event::Done | Event::Error(_) => finished = true,
102//!                 _ => {}
103//!             }
104//!         }
105//!         let wait = match xfer.next_timeout() {
106//!             Some(t) => t.saturating_duration_since(now),
107//!             None if finished => break, // idle and nothing left to write
108//!             None => Duration::from_millis(100),
109//!         };
110//!         link.set_read_timeout(Some(wait.max(Duration::from_millis(10))))?;
111//!         match link.read(&mut buf) {
112//!             Ok(0) => break,
113//!             Ok(n) => xfer.handle_input(Instant::now(), &buf[..n]),
114//!             Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {
115//!                 xfer.handle_timeout(Instant::now())
116//!             }
117//!             Err(e) => return Err(e),
118//!         }
119//!     }
120//!     Ok(())
121//! }
122//! ```
123//!
124//! The block layer is public for tools and tests: [`codec`] (control bytes,
125//! framing, checksum and CRC-16).
126//!
127//! [`Instant`]: time::Instant
128
129pub mod codec;
130#[cfg(test)]
131mod trace_tests;
132mod transfer;
133
134/// The clock types of the seam: `std::time` everywhere except `wasm32`,
135/// where they come from `web-time` (see the crate docs, "Time and
136/// WebAssembly").
137pub mod time {
138    #[cfg(not(target_arch = "wasm32"))]
139    pub use std::time::{Duration, Instant};
140    #[cfg(target_arch = "wasm32")]
141    pub use web_time::{Duration, Instant};
142}
143
144pub use codec::{BlockSize, Check};
145pub use transfer::{Command, Config, Error, Event, StartError, Transfer};