Skip to main content

satx_core/
xserv.rs

1//! XSERV: the command server on top of XModem (49g+/50g, the 49G after
2//! ROM 1.10, and the XSrvr48 library on the 48): packet framing, commands,
3//! the directory listing, the detection probe, and a client over the link.
4//!
5//! **Tested on a real 49G** (ROM 1.18, 2026-11-08): `satx xserv mem`, `ls`,
6//! `get`, `put` and `eval` worked, and 4 KB took 8.4 s against
7//! Kermit's 16.7 s. **And on the emulated 49G** (Saturnus, ROM 2.15,
8//! 2026-11-08): typed `XSERV` shows "Xmodem server"; every command below,
9//! `Q` included, and the Kermit server nested through `E` (`SERVER`, then
10//! Kermit's FINISH returns to XSERV). Not yet tried on a 49g+ or 50g. The
11//! framing follows the wiki's description of HP's own client code (wiki:
12//! protocols/xserv). The framing and parsing here are sans-IO; the client
13//! ([`XservSession`], and the XSERV operations of
14//! [`Machine`](crate::machine::Machine)) talks to the crate's internal
15//! link, as the Kermit and XModem code do.
16//!
17//! # Framing
18//!
19//! A packet is a 2-byte length (high byte first), the bytes, and a 1-byte
20//! checksum: the sum of the bytes mod 256. The receiving side answers ACK,
21//! or NAK to get the packet again (the client retries a command packet up
22//! to 5 times and a reply up to 4).
23//!
24//! # Commands
25//!
26//! The host sends one command byte once the line is quiet, then, depending
27//! on the command, a command packet ([`XservCommand::packet`]) and an XModem
28//! transfer or a reply packet:
29//!
30//! | Byte | Command | Then |
31//! | --- | --- | --- |
32//! | `P` | [`XservCommand::Put`] | packet with the name, XModem send by the host |
33//! | `G` | [`XservCommand::Get`] | packet with the name, XModem receive by the host |
34//! | `E` | [`XservCommand::Execute`] | packet with RPL text |
35//! | `M` | [`XservCommand::Memory`] | reply packet: the free memory as text, `245478.` |
36//! | `L` | [`XservCommand::List`] | reply packet, one [`DirRecord`] per variable |
37//! | `Q` | [`XservCommand::Quit`] | nothing: XSERV ends (ROM 2.15) |
38//!
39//! # A busy calculator
40//!
41//! `E` is ACKed before its RPL runs, and while it runs the calculator drops
42//! the bytes it gets: an `L` sent 0.3 s into a 5 s loop never got an answer,
43//! an `M` sent every second got one answer, when the loop was done
44//! (emulated 49G, 2026-11-08). The client therefore resends `M` and `L`
45//! when nothing comes back within [`XservOptions::answer`], and before
46//! `E`, `G` or `P` after anything that may have left the calculator busy
47//! it asks `M` until it answers: a command byte lost while the packet that
48//! follows it is read as command bytes would do harm. Before `Q` it asks
49//! for at most 5 s (a lost `Q` would read as "XSERV has ended").
50//!
51//! # Detection
52//!
53//! A Kermit server ignores a lone `M` (the real 49G's and the emulated
54//! 48SX's, 48GX's and 49G's) and XSERV ignores the Kermit packets of a
55//! speed search, so a host can send `M` first and listen:
56//! [`memory_reply`] tells XSERV's answer in what came back.
57
58use std::fmt;
59
60use xmodem_proto::codec::{ACK, NAK};
61
62use crate::calc::validate_name;
63use crate::charset::{decode, encode, encode_command};
64use crate::link::Link;
65use crate::object::ObjectType;
66use crate::reply::{Entry, parse_real};
67use crate::time::Duration;
68#[cfg(not(target_arch = "wasm32"))]
69use crate::time::Instant;
70#[cfg(not(target_arch = "wasm32"))]
71use crate::transport::Transport;
72use crate::xmodem::{self, XmodemOptions, XmodemReceived, XmodemReport};
73use crate::{Error, Result};
74
75/// Most data bytes a packet can carry (16-bit length).
76pub const MAX_DATA: usize = 0xFFFF;
77
78/// Why a packet or a directory listing could not be built or read.
79#[derive(Clone, Debug, PartialEq, Eq)]
80pub enum FrameError {
81    /// More than [`MAX_DATA`] bytes to send.
82    TooLong(usize),
83    /// The frame or record ends early.
84    Truncated,
85    /// Bytes after the checksum of a single frame.
86    TrailingBytes(usize),
87    /// The checksum byte does not match the data.
88    BadChecksum {
89        /// Sum of the data bytes mod 256.
90        expected: u8,
91        /// The checksum byte received.
92        got: u8,
93    },
94}
95
96impl fmt::Display for FrameError {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        match self {
99            FrameError::TooLong(n) => write!(f, "{n} bytes do not fit one XSERV packet"),
100            FrameError::Truncated => f.write_str("XSERV packet or record ends early"),
101            FrameError::TrailingBytes(n) => write!(f, "{n} bytes after the XSERV packet"),
102            FrameError::BadChecksum { expected, got } => {
103                write!(f, "XSERV checksum {got:#04x}, expected {expected:#04x}")
104            }
105        }
106    }
107}
108
109impl std::error::Error for FrameError {}
110
111/// Sum of `data` mod 256.
112pub fn checksum(data: &[u8]) -> u8 {
113    data.iter().fold(0u8, |acc, &b| acc.wrapping_add(b))
114}
115
116/// Frame `data` as one packet: length (high byte first), data, checksum.
117pub fn encode_packet(data: &[u8]) -> std::result::Result<Vec<u8>, FrameError> {
118    let len = u16::try_from(data.len()).map_err(|_| FrameError::TooLong(data.len()))?;
119    let mut out = Vec::with_capacity(data.len() + 3);
120    out.extend_from_slice(&len.to_be_bytes());
121    out.extend_from_slice(data);
122    out.push(checksum(data));
123    Ok(out)
124}
125
126/// Read exactly one complete packet and return its data.
127pub fn decode_packet(frame: &[u8]) -> std::result::Result<Vec<u8>, FrameError> {
128    let mut deframer = Deframer::new();
129    deframer.push(frame);
130    let data = deframer.next_packet().ok_or(FrameError::Truncated)??;
131    match deframer.pending() {
132        0 => Ok(data),
133        n => Err(FrameError::TrailingBytes(n)),
134    }
135}
136
137/// Splits a byte stream into packets, in any chunking.
138#[derive(Clone, Debug, Default)]
139pub struct Deframer {
140    buf: Vec<u8>,
141}
142
143impl Deframer {
144    /// Empty deframer.
145    pub fn new() -> Self {
146        Deframer::default()
147    }
148
149    /// Append bytes read from the link.
150    pub fn push(&mut self, bytes: &[u8]) {
151        self.buf.extend_from_slice(bytes);
152    }
153
154    /// Bytes buffered but not yet returned as a packet.
155    pub fn pending(&self) -> usize {
156        self.buf.len()
157    }
158
159    /// Drop everything buffered (after a NAK, the sender starts over).
160    pub fn clear(&mut self) {
161        self.buf.clear();
162    }
163
164    /// The next complete packet's data, or why it is bad (answer NAK); `None`
165    /// until a whole packet is buffered. A bad packet is consumed.
166    pub fn next_packet(&mut self) -> Option<std::result::Result<Vec<u8>, FrameError>> {
167        let (&hi, &lo) = (self.buf.first()?, self.buf.get(1)?);
168        let len = usize::from(u16::from_be_bytes([hi, lo]));
169        let got = *self.buf.get(2 + len)?;
170        let frame: Vec<u8> = self.buf.drain(..3 + len).collect();
171        let data = frame.get(2..2 + len).unwrap_or_default().to_vec();
172        let expected = checksum(&data);
173        Some(if got == expected {
174            Ok(data)
175        } else {
176            Err(FrameError::BadChecksum { expected, got })
177        })
178    }
179}
180
181/// An XSERV command.
182#[derive(Clone, Debug, PartialEq, Eq)]
183pub enum XservCommand {
184    /// `P`: store the file that follows by XModem as variable NAME.
185    Put(String),
186    /// `G`: send variable NAME by XModem.
187    Get(String),
188    /// `E`: execute RPL text, e.g. `HOME DIR1` to change directory.
189    Execute(String),
190    /// `M`: the free memory in bytes, as a reply packet holding the number
191    /// as text (`245478.`, the 49G's trailing point).
192    Memory,
193    /// `L`: list the current directory, as a reply packet of
194    /// [`DirRecord`]s.
195    List,
196    /// `Q`: end XSERV, no reply (Conn4x's client code; on the emulated 49G,
197    /// ROM 2.15, the calculator is back at its stack after it).
198    Quit,
199}
200
201impl XservCommand {
202    /// The command byte.
203    pub fn byte(&self) -> u8 {
204        match self {
205            XservCommand::Put(_) => b'P',
206            XservCommand::Get(_) => b'G',
207            XservCommand::Execute(_) => b'E',
208            XservCommand::Memory => b'M',
209            XservCommand::List => b'L',
210            XservCommand::Quit => b'Q',
211        }
212    }
213
214    /// The command packet that follows the command byte, framed; `None` for
215    /// `M`, `L` and `Q`. Names must be valid variable names; names and RPL text
216    /// are encoded in the HP character set (RPL text may use ASCII
217    /// trigraphs such as `\->`).
218    pub fn packet(&self) -> Result<Option<Vec<u8>>> {
219        let data = match self {
220            XservCommand::Put(name) | XservCommand::Get(name) => {
221                validate_name(name)?;
222                encode(name)?
223            }
224            XservCommand::Execute(text) => encode_command(text)?,
225            XservCommand::Memory | XservCommand::List | XservCommand::Quit => return Ok(None),
226        };
227        encode_packet(&data)
228            .map(Some)
229            .map_err(|e| Error::Reply(e.to_string()))
230    }
231
232    /// Whether the calculator answers with a reply packet.
233    pub fn has_reply(&self) -> bool {
234        matches!(self, XservCommand::Memory | XservCommand::List)
235    }
236}
237
238/// One variable in an `L` reply.
239#[derive(Clone, Debug, PartialEq, Eq)]
240pub struct DirRecord {
241    /// Name, decoded from the HP character set.
242    pub name: String,
243    /// Low 16 bits of the object's prolog, e.g. `0x2A96` for a directory,
244    /// `0x2A2C` for a string.
245    pub prolog: u16,
246    /// Size in nibbles.
247    pub size_nibbles: u32,
248    /// The object's CRC as the calculator reports it.
249    pub crc: u16,
250}
251
252impl DirRecord {
253    /// Whether the prolog is a directory's (#2A96).
254    pub fn is_directory(&self) -> bool {
255        self.prolog == 0x2A96
256    }
257
258    /// The type name as the Kermit server's `G D` listing prints it
259    /// (`Real Number`, `Directory`); `Object #2A4E` for a prolog not known.
260    pub fn kind(&self) -> String {
261        ObjectType::from_prolog(u32::from(self.prolog)).map_or_else(
262            || format!("Object #{:04X}", self.prolog),
263            |t| t.name().to_string(),
264        )
265    }
266
267    /// The size as the Kermit server's `G D` listing gives it, in bytes:
268    /// the object's nibbles, which XSERV gives, and the variable's entry in
269    /// its directory, 4.5 bytes and one per name character (the name's
270    /// length before and after it, 2 nibbles each, and the 5-nibble link).
271    /// Checked on seven variables of the emulated 49G, ROM 2.15
272    /// (2026-11-08): one- to eight-character names, two directories, a
273    /// list, a string, reals and a program, every one as Kermit's.
274    pub fn size(&self) -> f64 {
275        let name = encode(&self.name).map_or(self.name.chars().count(), |b| b.len());
276        f64::from(self.size_nibbles) / 2.0 + 4.5 + name as f64
277    }
278
279    /// The record as a listing entry, sized and named as the Kermit
280    /// server's ([`DirRecord::size`], [`DirRecord::kind`]).
281    pub fn entry(&self) -> Entry {
282        Entry {
283            name: self.name.clone(),
284            size: self.size(),
285            kind: self.kind(),
286            checksum: self.crc,
287        }
288    }
289}
290
291/// Parse the data of an `L` reply: per variable, 1 byte name length, the
292/// name, 2 bytes prolog (low 16 bits, low byte first), 3 bytes size in
293/// nibbles (low byte first), 2 bytes CRC, low byte first too (the Kermit
294/// server's checksums of the same variables, emulated 49G, 2026-11-08).
295pub fn parse_dir_list(data: &[u8]) -> std::result::Result<Vec<DirRecord>, FrameError> {
296    let mut records = Vec::new();
297    let mut rest = data;
298    while let Some((&len, tail)) = rest.split_first() {
299        let len = usize::from(len);
300        let record = tail.get(..len + 7).ok_or(FrameError::Truncated)?;
301        let (name, fields) = record.split_at(len);
302        let byte = |i: usize| fields.get(i).copied().unwrap_or_default();
303        records.push(DirRecord {
304            name: decode(name),
305            prolog: u16::from_le_bytes([byte(0), byte(1)]),
306            size_nibbles: u32::from_le_bytes([byte(2), byte(3), byte(4), 0]),
307            crc: u16::from_le_bytes([byte(5), byte(6)]),
308        });
309        rest = tail.get(len + 7..).unwrap_or_default();
310    }
311    Ok(records)
312}
313
314/// The free memory in an answer to `M` heard on the link: the first
315/// well-formed packet in `heard` (garbage before it is skipped: an idle
316/// Kermit server's NAK, a reply at the wrong speed) whose data reads as a
317/// number. `None` when there is none, or not all of it yet.
318pub fn memory_reply(heard: &[u8]) -> Option<f64> {
319    (0..heard.len()).find_map(|at| {
320        let rest = heard.get(at..)?;
321        let (&hi, &lo) = (rest.first()?, rest.get(1)?);
322        let len = usize::from(u16::from_be_bytes([hi, lo]));
323        // The number is a few digits: a longer "packet" is noise.
324        if !(1..=MEMORY_REPLY_MAX).contains(&len) {
325            return None;
326        }
327        let data = rest.get(2..2 + len)?;
328        if *rest.get(2 + len)? != checksum(data) {
329            return None;
330        }
331        parse_real(std::str::from_utf8(data).ok()?)
332    })
333}
334
335/// The longest `M` reply [`memory_reply`] takes.
336const MEMORY_REPLY_MAX: usize = 24;
337
338/// How long `Q` waits for a busy calculator (`M` asked until it answers)
339/// before it goes out anyway: just after a nested Kermit server's FINISH,
340/// XSERV answers about 1 s later.
341const QUIT_SETTLE: Duration = Duration::from_secs(5);
342
343/// Tries for a command packet before giving up (HP's client: 5).
344const COMMAND_TRIES: u32 = 5;
345/// Bad replies before giving up (HP's client: 4).
346const REPLY_FAILURES: u32 = 4;
347
348/// Timing of an XSERV client.
349#[derive(Clone, Debug)]
350pub struct XservOptions {
351    /// How long the line must be quiet before a command byte.
352    pub quiet: Duration,
353    /// How long a command waits for the first byte of its answer (the reply
354    /// packet, or the ACK of its packet) before it is sent again.
355    pub answer: Duration,
356    /// How long `M` and `L` are sent again while nothing answers: a
357    /// calculator running the RPL of an `E` answers once it is done.
358    pub busy: Duration,
359    /// How long the rest of a packet may take once it has started, and the
360    /// ACK of a command packet.
361    pub timeout: Duration,
362}
363
364impl Default for XservOptions {
365    /// 200 ms quiet, 1.5 s for the first byte, 60 s busy, 5 s timeout. The
366    /// emulated 49G answers `M` and `L` within 0.15 s, and ACKs a command
367    /// packet at once.
368    fn default() -> Self {
369        XservOptions {
370            quiet: Duration::from_millis(200),
371            answer: Duration::from_millis(1500),
372            busy: Duration::from_secs(60),
373            timeout: Duration::from_secs(5),
374        }
375    }
376}
377
378/// The client's state between commands.
379#[derive(Clone, Debug)]
380pub(crate) struct XservState {
381    pub(crate) options: XservOptions,
382    /// The calculator may still be busy (after an `E`, a transfer, a nested
383    /// Kermit session): ask `M` before a command with a packet.
384    pub(crate) settle: bool,
385}
386
387impl XservState {
388    pub(crate) fn new(options: XservOptions) -> Self {
389        XservState {
390            options,
391            settle: true,
392        }
393    }
394}
395
396/// What the calculator answered to a command byte.
397enum Answer {
398    /// A reply packet (ACKed).
399    Packet(Vec<u8>),
400    /// Nothing at all within the wait.
401    Silence,
402}
403
404/// Wait until the line has been quiet for `quiet` (late bytes of an
405/// earlier exchange are dropped).
406async fn quiet(link: &Link, quiet: Duration) -> Result<()> {
407    link.drain(quiet).await?;
408    Ok(())
409}
410
411/// Read one reply packet: [`Answer::Silence`] when no byte comes within
412/// `first`; a good packet is ACKed, a bad one NAKed (the calculator sends it
413/// again) up to [`REPLY_FAILURES`] times.
414async fn read_reply(link: &Link, first: Duration, timeout: Duration) -> Result<Answer> {
415    let mut deframer = Deframer::new();
416    let mut failures = 0;
417    let mut heard = false;
418    let mut deadline = link.now() + first;
419    loop {
420        while let Some(packet) = deframer.next_packet() {
421            match packet {
422                Ok(data) => {
423                    link.write(vec![ACK])?;
424                    link.flush().await?;
425                    return Ok(Answer::Packet(data));
426                }
427                Err(e) => {
428                    failures += 1;
429                    if failures >= REPLY_FAILURES {
430                        return Err(Error::Reply(format!("XSERV reply: {e}")));
431                    }
432                    deframer.clear();
433                    link.write(vec![NAK])?;
434                    link.flush().await?;
435                    deadline = link.now() + timeout;
436                }
437            }
438        }
439        let bytes = link.read(Some(deadline)).await?;
440        if bytes.is_empty() {
441            if !heard {
442                return Ok(Answer::Silence);
443            }
444            failures += 1;
445            if failures >= REPLY_FAILURES {
446                return Err(Error::Reply(format!(
447                    "XSERV reply: nothing complete after {REPLY_FAILURES} tries"
448                )));
449            }
450            deframer.clear();
451            link.write(vec![NAK])?;
452            link.flush().await?;
453            deadline = link.now() + timeout;
454            continue;
455        }
456        heard = true;
457        deframer.push(&bytes);
458        deadline = link.now() + timeout;
459    }
460}
461
462/// Send `M` or `L` and read its reply, sending the byte again while nothing
463/// answers, for up to [`XservOptions::busy`].
464async fn ask(link: &Link, options: &XservOptions, byte: u8) -> Result<Vec<u8>> {
465    let give_up = link.now() + options.busy;
466    loop {
467        quiet(link, options.quiet).await?;
468        link.write(vec![byte])?;
469        link.flush().await?;
470        if let Answer::Packet(data) = read_reply(link, options.answer, options.timeout).await? {
471            return Ok(data);
472        }
473        if link.now() >= give_up {
474            return Err(Error::Reply(format!(
475                "XSERV {}: no answer within {:.0} s; is XSERV running on the calculator?",
476                char::from(byte),
477                options.busy.as_secs_f64()
478            )));
479        }
480    }
481}
482
483/// `true` on ACK, `false` on NAK or nothing within `timeout`; other bytes
484/// are skipped.
485async fn wait_ack(link: &Link, timeout: Duration) -> Result<bool> {
486    let deadline = link.now() + timeout;
487    loop {
488        let bytes = link.read(Some(deadline)).await?;
489        if bytes.is_empty() {
490            return Ok(false);
491        }
492        for b in bytes {
493            match b {
494                ACK => return Ok(true),
495                NAK => return Ok(false),
496                _ => {}
497            }
498        }
499    }
500}
501
502/// Send `command` (the command byte, and its packet until ACKed); for `M`
503/// and `L` return the reply's data. See the module documentation for when
504/// it waits for a busy calculator.
505pub(crate) async fn command(
506    link: &Link,
507    state: &mut XservState,
508    command: &XservCommand,
509) -> Result<Option<Vec<u8>>> {
510    let options = state.options.clone();
511    if command.has_reply() {
512        let data = ask(link, &options, command.byte()).await?;
513        state.settle = false;
514        return Ok(Some(data));
515    }
516    let packet = command.packet()?;
517    if state.settle {
518        if packet.is_some() {
519            ask(link, &options, b'M').await?;
520        } else {
521            // Q: a calculator that does not answer any more (XSERV ended
522            // with ON) gets it anyway, after a short wait.
523            let mut short = options.clone();
524            short.busy = short.busy.min(QUIT_SETTLE);
525            match ask(link, &short, b'M').await {
526                Ok(_) | Err(Error::Reply(_)) => {}
527                Err(e) => return Err(e),
528            }
529        }
530        state.settle = false;
531    }
532    let Some(packet) = packet else {
533        // Q: nothing comes back.
534        quiet(link, options.quiet).await?;
535        link.write(vec![command.byte()])?;
536        link.flush().await?;
537        state.settle = true;
538        return Ok(None);
539    };
540    quiet(link, options.quiet).await?;
541    link.write(vec![command.byte()])?;
542    link.flush().await?;
543    // From here on the calculator may be busy, whatever happens.
544    state.settle = true;
545    for _ in 0..COMMAND_TRIES {
546        link.write(packet.clone())?;
547        link.flush().await?;
548        if wait_ack(link, options.timeout).await? {
549            return Ok(None);
550        }
551        quiet(link, options.quiet).await?;
552    }
553    Err(Error::Reply(format!(
554        "XSERV {}: no ACK for the command packet after {COMMAND_TRIES} tries",
555        char::from(command.byte())
556    )))
557}
558
559/// The listing of the current directory (`L`).
560pub(crate) async fn list(link: &Link, state: &mut XservState) -> Result<Vec<DirRecord>> {
561    let data = command(link, state, &XservCommand::List)
562        .await?
563        .unwrap_or_default();
564    parse_dir_list(&data).map_err(|e| Error::Reply(format!("XSERV L: {e}")))
565}
566
567/// The free memory in bytes (`M`).
568pub(crate) async fn memory(link: &Link, state: &mut XservState) -> Result<f64> {
569    let data = command(link, state, &XservCommand::Memory)
570        .await?
571        .unwrap_or_default();
572    std::str::from_utf8(&data)
573        .ok()
574        .and_then(parse_real)
575        .ok_or_else(|| {
576            Error::Reply(format!(
577                "XSERV M: {:?} is no number",
578                String::from_utf8_lossy(&data)
579            ))
580        })
581}
582
583/// Send `M` once and wait `wait` for the answer: the free memory, or `None`
584/// when nothing that reads as one comes (no XSERV there). Late input is
585/// dropped first; what arrives besides the answer is ignored.
586pub(crate) async fn probe(
587    link: &Link,
588    state: &mut XservState,
589    wait: Duration,
590) -> Result<Option<f64>> {
591    quiet(link, state.options.quiet).await?;
592    link.write(vec![b'M'])?;
593    link.flush().await?;
594    let deadline = link.now() + wait;
595    let mut heard = Vec::new();
596    loop {
597        if let Some(free) = memory_reply(&heard) {
598            link.write(vec![ACK])?;
599            link.flush().await?;
600            state.settle = false;
601            return Ok(Some(free));
602        }
603        let bytes = link.read(Some(deadline)).await?;
604        if bytes.is_empty() {
605            return Ok(None);
606        }
607        heard.extend_from_slice(&bytes);
608    }
609}
610
611/// End XSERV (`Q`, after `M` answers while the calculator may be busy, as
612/// before other commands, but for at most 5 s), then ask `M` once: `true`
613/// when nothing answers (XSERV has ended), `false` when it still runs (a
614/// ROM without `Q`).
615pub(crate) async fn quit(link: &Link, state: &mut XservState) -> Result<bool> {
616    command(link, state, &XservCommand::Quit).await?;
617    let wait = state.options.answer;
618    Ok(probe(link, state, wait).await?.is_none())
619}
620
621/// Download `name` from the current directory (`G`, then XModem).
622pub(crate) async fn get(
623    link: &Link,
624    state: &mut XservState,
625    name: &str,
626    options: &XmodemOptions,
627) -> Result<XmodemReceived> {
628    command(link, state, &XservCommand::Get(name.to_string())).await?;
629    xmodem::receive(link, options).await
630}
631
632/// Upload `data` as `name` into the current directory (`P`, then XModem).
633pub(crate) async fn put(
634    link: &Link,
635    state: &mut XservState,
636    name: &str,
637    data: &[u8],
638    options: &XmodemOptions,
639) -> Result<XmodemReport> {
640    command(link, state, &XservCommand::Put(name.to_string())).await?;
641    xmodem::send(link, options, data).await
642}
643
644/// The XModem options of an XSERV transfer: the 49G's (HP's CRC, 1k
645/// blocks), the transfer starting at once, so the start window is
646/// `start_timeout`.
647pub fn transfer_options(start_timeout: Duration) -> XmodemOptions {
648    let mut options = XmodemOptions::for_model(crate::Model::Hp49G).unwrap_or_default();
649    options.start_timeout = start_timeout;
650    options
651}
652
653/// A calculator running XSERV, over a blocking [`Transport`] with the
654/// system clock. For a link driven from outside, see the XSERV operations
655/// of [`Machine`](crate::machine::Machine), which run the same code.
656#[cfg(not(target_arch = "wasm32"))]
657pub struct XservSession {
658    transport: Box<dyn Transport>,
659    link: Link,
660    state: XservState,
661}
662
663#[cfg(not(target_arch = "wasm32"))]
664impl std::fmt::Debug for XservSession {
665    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
666        f.debug_struct("XservSession")
667            .field("options", &self.state.options)
668            .finish_non_exhaustive()
669    }
670}
671
672#[cfg(not(target_arch = "wasm32"))]
673impl XservSession {
674    /// Wrap an open link.
675    pub fn new(transport: Box<dyn Transport>, options: XservOptions) -> Self {
676        XservSession {
677            transport,
678            link: Link::new(Instant::now()),
679            state: XservState::new(options),
680        }
681    }
682
683    /// Give the link back.
684    pub fn into_transport(self) -> Box<dyn Transport> {
685        self.transport
686    }
687
688    fn drive<T>(
689        &mut self,
690        f: impl AsyncFnOnce(&Link, &mut XservState) -> T,
691        progress: &mut dyn FnMut(&crate::link::Progress),
692    ) -> T {
693        let link = self.link.clone();
694        let state = &mut self.state;
695        crate::link::drive(self.transport.as_mut(), &link, f(&link, state), progress)
696    }
697
698    /// Send `M` and wait `wait` for XSERV's answer: the free memory, or
699    /// `None` when nothing answers as XSERV does.
700    pub fn probe(&mut self, wait: Duration) -> Result<Option<f64>> {
701        self.drive(async |l, s| probe(l, s, wait).await, &mut |_| {})
702    }
703
704    /// The listing of the current directory (`L`).
705    pub fn list(&mut self) -> Result<Vec<DirRecord>> {
706        self.drive(async |l, s| list(l, s).await, &mut |_| {})
707    }
708
709    /// The free memory in bytes (`M`).
710    pub fn memory(&mut self) -> Result<f64> {
711        self.drive(async |l, s| memory(l, s).await, &mut |_| {})
712    }
713
714    /// Run RPL text (`E`); its results stay on the calculator's stack.
715    pub fn execute(&mut self, rpl: &str) -> Result<()> {
716        let cmd = XservCommand::Execute(rpl.to_string());
717        self.drive(
718            async |l, s| command(l, s, &cmd).await.map(|_| ()),
719            &mut |_| {},
720        )
721    }
722
723    /// End XSERV (`Q`): `true` when it has ended, `false` when it still
724    /// answers.
725    pub fn quit(&mut self) -> Result<bool> {
726        self.drive(async |l, s| quit(l, s).await, &mut |_| {})
727    }
728
729    /// Download `name` from the current directory.
730    pub fn get(
731        &mut self,
732        name: &str,
733        options: &XmodemOptions,
734        progress: &mut dyn FnMut(&xmodem_proto::Event),
735    ) -> Result<XmodemReceived> {
736        self.drive(async |l, s| get(l, s, name, options).await, &mut |p| {
737            if let crate::link::Progress::Xmodem(e) = p {
738                progress(e);
739            }
740        })
741    }
742
743    /// Upload `data` as `name` into the current directory.
744    pub fn put(
745        &mut self,
746        name: &str,
747        data: &[u8],
748        options: &XmodemOptions,
749        progress: &mut dyn FnMut(&xmodem_proto::Event),
750    ) -> Result<XmodemReport> {
751        self.drive(
752            async |l, s| put(l, s, name, data, options).await,
753            &mut |p| {
754                if let crate::link::Progress::Xmodem(e) = p {
755                    progress(e);
756                }
757            },
758        )
759    }
760}
761
762#[cfg(test)]
763#[allow(clippy::unwrap_used, clippy::expect_used)]
764mod tests {
765    use super::*;
766
767    #[test]
768    fn encode_by_hand() {
769        // "AB": length 0x0002, 0x41 + 0x42 = 0x83.
770        assert_eq!(
771            encode_packet(b"AB").unwrap(),
772            [0x00, 0x02, b'A', b'B', 0x83]
773        );
774        assert_eq!(encode_packet(b"").unwrap(), [0x00, 0x00, 0x00]);
775        // 300 bytes of 0xFF: length 0x012C, sum 300 * 255 mod 256 = 0xD4.
776        let big = encode_packet(&[0xFF; 300]).unwrap();
777        assert_eq!(&big[..2], &[0x01, 0x2C]);
778        assert_eq!(big.len(), 303);
779        assert_eq!(big[302], 0xD4);
780        assert_eq!(
781            encode_packet(&vec![0; MAX_DATA + 1]),
782            Err(FrameError::TooLong(MAX_DATA + 1))
783        );
784        assert_eq!(
785            encode_packet(&vec![0; MAX_DATA]).unwrap().len(),
786            MAX_DATA + 3
787        );
788    }
789
790    #[test]
791    fn decode_by_hand() {
792        assert_eq!(
793            decode_packet(&[0x00, 0x02, b'A', b'B', 0x83]).unwrap(),
794            b"AB"
795        );
796        assert_eq!(
797            decode_packet(&[0x00, 0x02, b'A', b'B', 0x84]),
798            Err(FrameError::BadChecksum {
799                expected: 0x83,
800                got: 0x84
801            })
802        );
803        assert_eq!(
804            decode_packet(&[0x00, 0x02, b'A']),
805            Err(FrameError::Truncated)
806        );
807        assert_eq!(decode_packet(&[0x00]), Err(FrameError::Truncated));
808        assert_eq!(
809            decode_packet(&[0x00, 0x00, 0x00, 0x07]),
810            Err(FrameError::TrailingBytes(1))
811        );
812    }
813
814    #[test]
815    fn deframer_handles_any_chunking() {
816        let mut wire = encode_packet(b"HOME").unwrap();
817        wire.extend(encode_packet(&[0x10; 256]).unwrap());
818        let mut d = Deframer::new();
819        let mut got = Vec::new();
820        for byte in &wire {
821            d.push(&[*byte]);
822            while let Some(p) = d.next_packet() {
823                got.push(p.unwrap());
824            }
825        }
826        assert_eq!(got, vec![b"HOME".to_vec(), vec![0x10; 256]]);
827        assert_eq!(d.pending(), 0);
828    }
829
830    #[test]
831    fn deframer_consumes_a_bad_packet() {
832        let mut d = Deframer::new();
833        d.push(&[0x00, 0x01, b'x', 0x00]);
834        d.push(&encode_packet(b"y").unwrap());
835        assert!(matches!(
836            d.next_packet(),
837            Some(Err(FrameError::BadChecksum { .. }))
838        ));
839        assert_eq!(d.next_packet(), Some(Ok(b"y".to_vec())));
840        d.push(&[0x00]);
841        d.clear();
842        assert_eq!(d.next_packet(), None);
843    }
844
845    #[test]
846    fn commands() {
847        let put = XservCommand::Put("ABC".into());
848        assert_eq!(put.byte(), b'P');
849        // 0x41 + 0x42 + 0x43 = 0xC6.
850        assert_eq!(
851            put.packet().unwrap(),
852            Some(vec![0x00, 0x03, b'A', b'B', b'C', 0xC6])
853        );
854        assert_eq!(XservCommand::Get("X".into()).byte(), b'G');
855        assert_eq!(
856            XservCommand::Get("X".into()).packet().unwrap(),
857            Some(vec![0x00, 0x01, b'X', b'X'])
858        );
859        assert!(XservCommand::Get("1X".into()).packet().is_err());
860        assert!(XservCommand::Put("A B".into()).packet().is_err());
861
862        // `\->` becomes the HP's arrow (0x8D).
863        let exec = XservCommand::Execute("\\->A".into());
864        assert_eq!(exec.byte(), b'E');
865        assert_eq!(
866            exec.packet().unwrap(),
867            Some(vec![0x00, 0x02, 0x8D, b'A', 0x8D + b'A'])
868        );
869        assert_eq!(XservCommand::Memory.byte(), b'M');
870        assert_eq!(XservCommand::List.byte(), b'L');
871        assert_eq!(XservCommand::Memory.packet().unwrap(), None);
872        assert_eq!(XservCommand::List.packet().unwrap(), None);
873        assert_eq!(XservCommand::Quit.byte(), b'Q');
874        assert_eq!(XservCommand::Quit.packet().unwrap(), None);
875        assert!(!XservCommand::Quit.has_reply());
876        assert!(XservCommand::List.has_reply() && XservCommand::Memory.has_reply());
877        assert!(!put.has_reply());
878    }
879
880    #[test]
881    fn dir_list_by_hand() {
882        let data = [
883            // "DIR1": directory #2A96, 22 nibbles, CRC 0x1234.
884            &[4][..],
885            b"DIR1",
886            &[0x96, 0x2A, 22, 0, 0, 0x34, 0x12],
887            // "S": string #2A2C, 0x012345 nibbles, CRC 0xBEEF.
888            &[1],
889            b"S",
890            &[0x2C, 0x2A, 0x45, 0x23, 0x01, 0xEF, 0xBE],
891        ]
892        .concat();
893        let list = parse_dir_list(&data).unwrap();
894        assert_eq!(
895            list,
896            vec![
897                DirRecord {
898                    name: "DIR1".into(),
899                    prolog: 0x2A96,
900                    size_nibbles: 22,
901                    crc: 0x1234
902                },
903                DirRecord {
904                    name: "S".into(),
905                    prolog: 0x2A2C,
906                    size_nibbles: 0x012345,
907                    crc: 0xBEEF
908                },
909            ]
910        );
911        assert!(list[0].is_directory() && !list[1].is_directory());
912        assert_eq!(parse_dir_list(&[]).unwrap(), vec![]);
913        assert_eq!(
914            parse_dir_list(&data[..data.len() - 1]),
915            Err(FrameError::Truncated)
916        );
917        // HP characters in names are decoded (0x8D is the arrow).
918        let arrow = parse_dir_list(&[1, 0x8D, 0, 0, 0, 0, 0, 0, 0]).unwrap();
919        assert_eq!(arrow[0].name, "→");
920    }
921
922    #[test]
923    fn a_record_has_the_kermit_size_and_kind() {
924        // Emulated 49G, ROM 2.15: XSERV 10.5 bytes, Kermit 16 for `A`; 22.5
925        // and 31 for directory SUBD; 10.5 and 23 for ABCDEFGH.
926        let r = |name: &str, prolog: u16, nibbles: u32| DirRecord {
927            name: name.into(),
928            prolog,
929            size_nibbles: nibbles,
930            crc: 0x7847,
931        };
932        assert_eq!(r("A", 0x2933, 21).size(), 16.0);
933        assert_eq!(r("SUBD", 0x2A96, 45).size(), 31.0);
934        assert_eq!(r("ABCDEFGH", 0x2933, 21).size(), 23.0);
935        let e = r("SUBD", 0x2A96, 45).entry();
936        assert_eq!(e.kind, "Directory");
937        assert!(e.is_directory());
938        assert_eq!(e.checksum, 0x7847);
939        assert_eq!(r("X", 0x2A2C, 10).kind(), "String");
940        assert_eq!(r("X", 0x1234, 10).kind(), "Object #1234");
941    }
942
943    #[test]
944    fn the_memory_reply_is_found_in_what_was_heard() {
945        let reply = encode_packet(b"245478.").unwrap();
946        assert_eq!(memory_reply(&reply), Some(245_478.0));
947        // An idle Kermit NAK before it, and the rest of the line after.
948        let mut heard = b"\x01# N3\r".to_vec();
949        heard.extend(&reply);
950        heard.extend(b"xyz");
951        assert_eq!(memory_reply(&heard), Some(245_478.0));
952        assert_eq!(memory_reply(&reply[..reply.len() - 1]), None);
953        let mut bad = reply.clone();
954        *bad.last_mut().unwrap() ^= 1;
955        assert_eq!(memory_reply(&bad), None);
956        assert_eq!(memory_reply(&encode_packet(b"hello").unwrap()), None);
957        assert_eq!(memory_reply(b"\x01# N3\r"), None);
958        assert_eq!(memory_reply(&[]), None);
959    }
960
961    use crate::transport::MemoryTransport;
962    use std::sync::{Arc, Mutex};
963
964    type Log = Arc<Mutex<Vec<Vec<u8>>>>;
965
966    fn fast() -> XservOptions {
967        XservOptions {
968            quiet: Duration::from_millis(1),
969            answer: Duration::from_millis(30),
970            busy: Duration::from_millis(400),
971            timeout: Duration::from_millis(30),
972        }
973    }
974
975    /// A session against `peer`, which sees and answers every write.
976    fn session(
977        mut peer: impl FnMut(&[u8]) -> Vec<Vec<u8>> + Send + 'static,
978    ) -> (XservSession, Log) {
979        let log: Log = Arc::default();
980        let seen = log.clone();
981        let t = MemoryTransport::new(move |w| {
982            seen.lock().unwrap().push(w.to_vec());
983            peer(w)
984        });
985        (XservSession::new(Box::new(t), fast()), log)
986    }
987
988    #[test]
989    fn a_probe_acks_the_answer_and_finds_nothing_in_silence() {
990        let (mut s, log) = session(|w| match w {
991            b"M" => vec![encode_packet(b"1000.").unwrap()],
992            _ => vec![],
993        });
994        assert_eq!(s.probe(Duration::from_millis(50)).unwrap(), Some(1000.0));
995        assert_eq!(*log.lock().unwrap(), [b"M".to_vec(), vec![ACK]]);
996        let (mut s, log) = session(|_| vec![]);
997        assert_eq!(s.probe(Duration::from_millis(50)).unwrap(), None);
998        assert_eq!(*log.lock().unwrap(), [b"M".to_vec()]);
999    }
1000
1001    /// The calculator drops two `L` bytes while it is busy, then answers:
1002    /// the client sends it again.
1003    #[test]
1004    fn a_busy_calculator_gets_the_command_again() {
1005        let records = [&[1][..], b"S", &[0x2C, 0x2A, 0x0A, 0, 0, 0xEF, 0xBE]].concat();
1006        let reply = encode_packet(&records).unwrap();
1007        let mut dropped = 2;
1008        let (mut s, log) = session(move |w| match w {
1009            b"L" if dropped > 0 => {
1010                dropped -= 1;
1011                vec![]
1012            }
1013            b"L" => vec![reply.clone()],
1014            _ => vec![],
1015        });
1016        let list = s.list().unwrap();
1017        assert_eq!(list[0].name, "S");
1018        assert_eq!(
1019            *log.lock().unwrap(),
1020            [b"L".to_vec(), b"L".to_vec(), b"L".to_vec(), vec![ACK]]
1021        );
1022    }
1023
1024    /// Nothing answers at all: an error naming XSERV, after the busy time.
1025    #[test]
1026    fn no_answer_gives_up() {
1027        let (mut s, _) = session(|_| vec![]);
1028        let err = s.memory().unwrap_err();
1029        assert!(err.to_string().contains("is XSERV running"), "{err}");
1030    }
1031
1032    /// Before the first command with a packet, and after an `E`, the client
1033    /// asks `M` until the calculator answers; after an `L` it does not.
1034    #[test]
1035    fn a_command_packet_waits_for_a_ready_calculator() {
1036        let listing = encode_packet(&[]).unwrap();
1037        let (mut s, log) = session(move |w| match w {
1038            b"M" => vec![encode_packet(b"5.").unwrap()],
1039            b"L" => vec![listing.clone()],
1040            [b'E' | b'P' | b'G'] | [ACK] => vec![],
1041            _ => vec![vec![ACK]],
1042        });
1043        s.execute("HOME").unwrap();
1044        s.execute("'X' PURGE").unwrap();
1045        assert!(s.list().unwrap().is_empty());
1046        s.execute("1").unwrap();
1047        let sent: Vec<Vec<u8>> = log.lock().unwrap().clone();
1048        let bytes: Vec<&[u8]> = sent.iter().map(Vec::as_slice).collect();
1049        let home = encode_packet(b"HOME").unwrap();
1050        let purge = encode_packet(b"'X' PURGE").unwrap();
1051        let one = encode_packet(b"1").unwrap();
1052        assert_eq!(
1053            bytes,
1054            [
1055                &b"M"[..],
1056                &[ACK],
1057                b"E",
1058                &home,
1059                b"M",
1060                &[ACK],
1061                b"E",
1062                &purge,
1063                b"L",
1064                &[ACK],
1065                b"E",
1066                &one,
1067            ]
1068        );
1069    }
1070
1071    /// `Q` waits for the calculator to answer `M` first (it may still be
1072    /// busy), then the `M` after it says whether XSERV ended.
1073    #[test]
1074    fn quit_says_whether_xserv_ended() {
1075        let mut ended = false;
1076        let mut busy = 2;
1077        let (mut s, log) = session(move |w| match w {
1078            b"Q" => {
1079                ended = true;
1080                vec![]
1081            }
1082            b"M" if busy > 0 => {
1083                busy -= 1;
1084                vec![]
1085            }
1086            b"M" if !ended => vec![encode_packet(b"5.").unwrap()],
1087            _ => vec![],
1088        });
1089        assert!(s.quit().unwrap());
1090        let m = b"M".to_vec();
1091        assert_eq!(
1092            *log.lock().unwrap(),
1093            [m.clone(), m.clone(), m.clone(), vec![ACK], b"Q".to_vec(), m]
1094        );
1095        let (mut s, _) = session(|w| match w {
1096            b"M" => vec![encode_packet(b"5.").unwrap()],
1097            _ => vec![],
1098        });
1099        assert!(!s.quit().unwrap());
1100        // Nothing answers at all (XSERV ended with ON): Q goes out anyway.
1101        let (mut s, log) = session(|_| vec![]);
1102        assert!(s.quit().unwrap());
1103        assert!(log.lock().unwrap().contains(&b"Q".to_vec()));
1104    }
1105
1106    /// A NAKed command packet is sent again; a reply with a bad checksum is
1107    /// NAKed and read again.
1108    #[test]
1109    fn naks_both_ways() {
1110        let mut naks = 1;
1111        let (mut s, log) = session(move |w| match w {
1112            b"M" => vec![encode_packet(b"5.").unwrap()],
1113            [b'E'] | [ACK] => vec![],
1114            _ if naks > 0 => {
1115                naks -= 1;
1116                vec![vec![NAK]]
1117            }
1118            _ => vec![vec![ACK]],
1119        });
1120        s.execute("X").unwrap();
1121        let packet = encode_packet(b"X").unwrap();
1122        assert_eq!(
1123            *log.lock().unwrap(),
1124            [
1125                b"M".to_vec(),
1126                vec![ACK],
1127                b"E".to_vec(),
1128                packet.clone(),
1129                packet
1130            ]
1131        );
1132
1133        let good = encode_packet(b"42").unwrap();
1134        let mut bad = good.clone();
1135        *bad.last_mut().unwrap() ^= 0xFF;
1136        let (mut s, log) = session(move |w| match w {
1137            b"M" => vec![bad.clone()],
1138            [NAK] => vec![good.clone()],
1139            _ => vec![],
1140        });
1141        assert_eq!(s.memory().unwrap(), 42.0);
1142        assert_eq!(*log.lock().unwrap(), [b"M".to_vec(), vec![NAK], vec![ACK]]);
1143    }
1144}