Skip to main content

oscyl_driver/
engine.rs

1//! Generic sans-IO request/reply engine.
2//!
3//! Callers submit ops, move bytes with [`Engine::poll_transmit`] and
4//! [`Engine::handle_input`], drive time with [`Engine::handle_timeout`], and
5//! read results from [`Engine::poll_event`]. A [`Protocol`] expands each op
6//! into [`Step`]s and classifies replies; the engine keeps exactly one step
7//! in flight, abandons the rest of an op on its first failure, and reports
8//! progress after every completed step.
9
10use std::collections::VecDeque;
11use std::time::{Duration, Instant};
12
13use crate::sysex::Framer;
14
15/// Why an op failed. `what` names the step ("program write") and `index`
16/// its slot, when it has one.
17#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
18pub enum OpError {
19    /// The synth refused the step.
20    #[error("synth rejected {what}{}", at(*index))]
21    Nak {
22        /// The step.
23        what: &'static str,
24        /// The step's slot, if any.
25        index: Option<u16>,
26    },
27    /// The synth answered with an error code.
28    #[error("synth reported error {code:#04x} for {what}{}", at(*index))]
29    Device {
30        /// The synth's error code.
31        code: u8,
32        /// The step.
33        what: &'static str,
34        /// The step's slot, if any.
35        index: Option<u16>,
36    },
37    /// The step's reply did not come before its timeout.
38    #[error("no reply to {what}{}", at(*index))]
39    Timeout {
40        /// The step.
41        what: &'static str,
42        /// The step's slot, if any.
43        index: Option<u16>,
44    },
45    /// The reply came, but its data is wrong.
46    #[error("malformed data in reply to {what}: {error}")]
47    BadData {
48        /// The step.
49        what: &'static str,
50        /// What is wrong with the data.
51        error: String,
52    },
53    /// The op was dropped before it ended (e.g. its synth was unplugged).
54    #[error("cancelled")]
55    Cancelled,
56}
57
58fn at(index: Option<u16>) -> String {
59    index.map(|i| format!(" (program {i})")).unwrap_or_default()
60}
61
62/// One message to send and the reply that completes it.
63#[derive(Debug, Clone)]
64pub struct Step<X> {
65    /// The bytes to send.
66    pub msg: Vec<u8>,
67    /// What [`Protocol::on_message`] needs to know which reply completes
68    /// the step.
69    pub expect: X,
70    /// Bounds a dead link; never paces traffic.
71    pub timeout: Duration,
72    /// The step, for people ("program write"). Errors name it.
73    pub what: &'static str,
74    /// The step's slot, if any. Errors name it.
75    pub index: Option<u16>,
76}
77
78/// How a received message relates to the step in flight.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub enum Outcome<E> {
81    /// Not an answer to this step (e.g. a dump the user sent by hand).
82    Unrelated,
83    /// The step completed, optionally with a result.
84    Done(Option<E>),
85    /// The step failed; the rest of the op is abandoned.
86    Failed(OpError),
87}
88
89/// A synth's request/reply rules.
90pub trait Protocol {
91    /// An operation that a caller submits.
92    type Op;
93    /// A result that the engine reports.
94    type Event;
95    /// What a step waits for; see [`Step::expect`].
96    type Expect: Copy;
97    /// The steps that make up `op`, in the order the engine sends them.
98    fn expand(&self, op: Self::Op) -> Vec<Step<Self::Expect>>;
99    /// Classify one complete SysEx message against the step in flight.
100    fn on_message(
101        &self,
102        msg: &[u8],
103        expect: Self::Expect,
104        what: &'static str,
105        index: Option<u16>,
106    ) -> Outcome<Self::Event>;
107    /// The event for `done` steps of `total` done.
108    fn progress(done: usize, total: usize) -> Self::Event;
109    /// The event for an op whose every step succeeded.
110    fn done() -> Self::Event;
111    /// The event for an op that failed with `e`.
112    fn failed(e: OpError) -> Self::Event;
113}
114
115/// The engine: it runs a [`Protocol`]'s ops one step at a time, sans IO.
116/// See the module's documentation.
117pub struct Engine<P: Protocol> {
118    protocol: P,
119    queue: VecDeque<P::Op>,
120    steps: VecDeque<Step<P::Expect>>,
121    total: usize,
122    in_flight: Option<(Step<P::Expect>, Instant)>,
123    framer: Framer,
124    events: VecDeque<P::Event>,
125}
126
127impl<P: Protocol> Engine<P> {
128    /// An engine that runs `protocol`, with nothing queued.
129    pub fn new(protocol: P) -> Engine<P> {
130        Engine {
131            protocol,
132            queue: VecDeque::new(),
133            steps: VecDeque::new(),
134            total: 0,
135            in_flight: None,
136            framer: Framer::new(),
137            events: VecDeque::new(),
138        }
139    }
140
141    /// The protocol that the engine runs.
142    pub fn protocol(&self) -> &P {
143        &self.protocol
144    }
145
146    /// Queues `op` after the ops already queued.
147    pub fn submit(&mut self, op: P::Op) {
148        self.queue.push_back(op);
149    }
150
151    /// True when nothing is queued or in flight.
152    pub fn is_idle(&self) -> bool {
153        self.queue.is_empty() && self.steps.is_empty() && self.in_flight.is_none()
154    }
155
156    /// Next message to send, if the line is free.
157    pub fn poll_transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
158        if self.in_flight.is_some() {
159            return None;
160        }
161        while self.steps.is_empty() {
162            let op = self.queue.pop_front()?;
163            self.steps = self.protocol.expand(op).into();
164            self.total = self.steps.len();
165            if self.steps.is_empty() {
166                self.events.push_back(P::done());
167            }
168        }
169        let step = self.steps.pop_front()?;
170        let msg = step.msg.clone();
171        self.in_flight = Some((step, now));
172        Some(msg)
173    }
174
175    /// When the in-flight request stops waiting for its reply.
176    pub fn next_deadline(&self) -> Option<Instant> {
177        self.in_flight.as_ref().map(|(s, t)| *t + s.timeout)
178    }
179
180    /// Fails the step in flight, and the rest of its op, if its timeout
181    /// passed by `now`.
182    pub fn handle_timeout(&mut self, now: Instant) {
183        let expired = self
184            .in_flight
185            .as_ref()
186            .is_some_and(|(s, t)| now >= *t + s.timeout);
187        if expired {
188            let (step, _) = self.in_flight.take().expect("checked above");
189            self.fail(OpError::Timeout {
190                what: step.what,
191                index: step.index,
192            });
193        }
194    }
195
196    /// Bytes from the synth, in fragments of any size. Each complete SysEx
197    /// message goes to [`Protocol::on_message`].
198    pub fn handle_input(&mut self, bytes: &[u8]) {
199        for msg in self.framer.push(bytes) {
200            self.on_message(&msg);
201        }
202    }
203
204    /// The next event, in order.
205    pub fn poll_event(&mut self) -> Option<P::Event> {
206        self.events.pop_front()
207    }
208
209    fn on_message(&mut self, msg: &[u8]) {
210        let Some((step, _)) = &self.in_flight else {
211            return;
212        };
213        match self
214            .protocol
215            .on_message(msg, step.expect, step.what, step.index)
216        {
217            Outcome::Unrelated => {}
218            Outcome::Failed(e) => {
219                self.in_flight = None;
220                self.fail(e);
221            }
222            Outcome::Done(event) => {
223                self.in_flight = None;
224                self.events.extend(event);
225                let done = self.total - self.steps.len();
226                self.events.push_back(P::progress(done, self.total));
227                if self.steps.is_empty() {
228                    self.events.push_back(P::done());
229                }
230            }
231        }
232    }
233
234    /// Abandon the rest of the current op.
235    fn fail(&mut self, e: OpError) {
236        self.steps.clear();
237        self.events.push_back(P::failed(e));
238    }
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244    use std::time::{Duration, Instant};
245
246    /// Test protocol: an op is a list of bytes; each byte `b` is sent as
247    /// `F0 b F7` and completed by the same message coming back.
248    struct Echo;
249
250    #[derive(Debug, PartialEq)]
251    enum Ev {
252        Got(u8),
253        Progress(usize, usize),
254        Done,
255        Failed(OpError),
256    }
257
258    impl Protocol for Echo {
259        type Op = Vec<u8>;
260        type Event = Ev;
261        type Expect = u8;
262        fn expand(&self, op: Vec<u8>) -> Vec<Step<u8>> {
263            op.into_iter()
264                .map(|b| Step {
265                    msg: vec![0xF0, b, 0xF7],
266                    expect: b,
267                    timeout: Duration::from_secs(1),
268                    what: "echo",
269                    index: Some(b as u16),
270                })
271                .collect()
272        }
273        fn on_message(
274            &self,
275            msg: &[u8],
276            expect: u8,
277            _what: &'static str,
278            _index: Option<u16>,
279        ) -> Outcome<Ev> {
280            match msg {
281                [0xF0, b, 0xF7] if *b == expect => Outcome::Done(Some(Ev::Got(*b))),
282                _ => Outcome::Unrelated,
283            }
284        }
285        fn progress(done: usize, total: usize) -> Ev {
286            Ev::Progress(done, total)
287        }
288        fn done() -> Ev {
289            Ev::Done
290        }
291        fn failed(e: OpError) -> Ev {
292            Ev::Failed(e)
293        }
294    }
295
296    fn events(e: &mut Engine<Echo>) -> Vec<Ev> {
297        std::iter::from_fn(|| e.poll_event()).collect()
298    }
299
300    #[test]
301    fn one_in_flight() {
302        let t = Instant::now();
303        let mut e = Engine::new(Echo);
304        e.submit(vec![1, 2]);
305        assert_eq!(e.poll_transmit(t), Some(vec![0xF0, 1, 0xF7]));
306        assert_eq!(e.poll_transmit(t), None);
307        e.handle_input(&[0xF0, 1, 0xF7]);
308        assert_eq!(e.poll_transmit(t), Some(vec![0xF0, 2, 0xF7]));
309    }
310
311    #[test]
312    fn progress_then_done() {
313        let t = Instant::now();
314        let mut e = Engine::new(Echo);
315        e.submit(vec![1, 2]);
316        e.poll_transmit(t);
317        e.handle_input(&[0xF0, 1, 0xF7]);
318        e.poll_transmit(t);
319        e.handle_input(&[0xF0, 2, 0xF7]);
320        assert_eq!(
321            events(&mut e),
322            vec![
323                Ev::Got(1),
324                Ev::Progress(1, 2),
325                Ev::Got(2),
326                Ev::Progress(2, 2),
327                Ev::Done
328            ]
329        );
330        assert!(e.is_idle());
331    }
332
333    #[test]
334    fn unrelated_message_is_ignored() {
335        let t = Instant::now();
336        let mut e = Engine::new(Echo);
337        e.submit(vec![1]);
338        e.poll_transmit(t);
339        e.handle_input(&[0xF0, 9, 0xF7]);
340        assert!(events(&mut e).is_empty());
341        assert!(!e.is_idle());
342    }
343
344    #[test]
345    fn timeout_abandons_rest_of_op_then_next_op_runs() {
346        let t = Instant::now();
347        let mut e = Engine::new(Echo);
348        e.submit(vec![1, 2]);
349        e.submit(vec![3]);
350        e.poll_transmit(t);
351        assert_eq!(e.next_deadline(), Some(t + Duration::from_secs(1)));
352        e.handle_timeout(t + Duration::from_secs(1));
353        assert_eq!(
354            events(&mut e),
355            vec![Ev::Failed(OpError::Timeout {
356                what: "echo",
357                index: Some(1)
358            })]
359        );
360        assert_eq!(e.poll_transmit(t), Some(vec![0xF0, 3, 0xF7]));
361    }
362}