1use std::collections::VecDeque;
11use std::time::{Duration, Instant};
12
13use crate::sysex::Framer;
14
15#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
18pub enum OpError {
19 #[error("synth rejected {what}{}", at(*index))]
21 Nak {
22 what: &'static str,
24 index: Option<u16>,
26 },
27 #[error("synth reported error {code:#04x} for {what}{}", at(*index))]
29 Device {
30 code: u8,
32 what: &'static str,
34 index: Option<u16>,
36 },
37 #[error("no reply to {what}{}", at(*index))]
39 Timeout {
40 what: &'static str,
42 index: Option<u16>,
44 },
45 #[error("malformed data in reply to {what}: {error}")]
47 BadData {
48 what: &'static str,
50 error: String,
52 },
53 #[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#[derive(Debug, Clone)]
64pub struct Step<X> {
65 pub msg: Vec<u8>,
67 pub expect: X,
70 pub timeout: Duration,
72 pub what: &'static str,
74 pub index: Option<u16>,
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
80pub enum Outcome<E> {
81 Unrelated,
83 Done(Option<E>),
85 Failed(OpError),
87}
88
89pub trait Protocol {
91 type Op;
93 type Event;
95 type Expect: Copy;
97 fn expand(&self, op: Self::Op) -> Vec<Step<Self::Expect>>;
99 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 fn progress(done: usize, total: usize) -> Self::Event;
109 fn done() -> Self::Event;
111 fn failed(e: OpError) -> Self::Event;
113}
114
115pub 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 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 pub fn protocol(&self) -> &P {
143 &self.protocol
144 }
145
146 pub fn submit(&mut self, op: P::Op) {
148 self.queue.push_back(op);
149 }
150
151 pub fn is_idle(&self) -> bool {
153 self.queue.is_empty() && self.steps.is_empty() && self.in_flight.is_none()
154 }
155
156 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 pub fn next_deadline(&self) -> Option<Instant> {
177 self.in_flight.as_ref().map(|(s, t)| *t + s.timeout)
178 }
179
180 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 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 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 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 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}