Skip to main content

open_stomp/
queue.rs

1//! Request pacing (docs/protocol/sysex.md): the pedal handles one SysEx request at a time, so requests and
2//! writes are queued and each waits for its reply or ack before the next is sent, like the
3//! official app. Live CCs/PCs carry no reply and need no queue.
4//!
5//! [`RequestQueue`] is the pure state machine (no I/O, time passed in) that
6//! [`device`](crate::device) drives; use it directly to talk to the pedal over your own MIDI
7//! transport:
8//!
9//! ```
10//! use std::time::{Duration, Instant};
11//! use open_stomp::queue::{RequestQueue, handshake};
12//! use open_stomp::Msg;
13//!
14//! let mut q = RequestQueue::new(Duration::from_secs(1));
15//! q.start_sync(handshake());
16//! // loop: send what the queue releases ...
17//! while let Some(req) = q.pop() {
18//!     // out.send(req.bytes())?;
19//!     q.sent(req, Instant::now());
20//! }
21//! // ... and feed it every complete message from the pedal
22//! let reply = [0xF0, 0x00, 0x21, 0x7A, 0x10, 0x56, 0x31, 0xF7];
23//! assert!(q.on_message(&Msg::parse(&reply)).is_some());
24//! assert_eq!(q.progress(), (1, handshake().len()));
25//! ```
26
27use std::collections::VecDeque;
28use std::time::{Duration, Instant};
29
30use crate::midi::{Cmd, Msg, req};
31
32/// What answers a request.
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub enum Expect {
35    /// Short frame reply of this kind with a payload (`0x10` version, `0x60` product).
36    Short(u8),
37    /// NEP reply (`dir` 2) to this cmd.
38    Reply(u8),
39    /// NEP write ack (`dir` 3) for this cmd.
40    Ack(u8),
41}
42
43impl Expect {
44    /// What the pedal sends back for an outgoing message, `None` for CCs/PCs (no reply).
45    pub fn of(bytes: &[u8]) -> Option<Expect> {
46        Some(match Msg::parse(bytes) {
47            Msg::Short { kind: 0x00, .. } => Expect::Short(0x10),
48            Msg::Short { kind, .. } => Expect::Short(kind),
49            // the pedal answers a chain write with the new order instead of an ack
50            Msg::Nep { cmd, dir: 1, .. } if cmd == Cmd::Chain as u8 => Expect::Reply(cmd),
51            Msg::Nep { cmd, dir: 1, .. } => Expect::Ack(cmd),
52            Msg::Nep { cmd, .. } => Expect::Reply(cmd),
53            _ => return None,
54        })
55    }
56
57    pub fn matches(self, msg: &Msg) -> bool {
58        match (self, msg) {
59            (Expect::Short(k), Msg::Short { kind, payload }) => *kind == k && !payload.is_empty(),
60            (Expect::Reply(c), Msg::Nep { cmd, dir, .. }) => *cmd == c && *dir == 2,
61            (Expect::Ack(c), Msg::Nep { cmd, dir, .. }) => *cmd == c && *dir == 3,
62            _ => false,
63        }
64    }
65}
66
67/// One queued outgoing message.
68#[derive(Clone, Debug, PartialEq, Eq)]
69pub struct Request {
70    bytes: Vec<u8>,
71    expect: Option<Expect>,
72    /// Part of the startup sync (counts towards its progress).
73    sync: bool,
74}
75
76impl Request {
77    pub fn bytes(&self) -> &[u8] {
78        &self.bytes
79    }
80
81    /// `None`: nothing comes back (CC/PC), done once sent.
82    pub fn expect(&self) -> Option<Expect> {
83        self.expect
84    }
85
86    pub fn is_sync(&self) -> bool {
87        self.sync
88    }
89}
90
91/// How an in-flight request ended.
92#[derive(Clone, Debug, PartialEq, Eq)]
93pub struct Done {
94    pub request: Request,
95    /// The reply arrived (`false`: timed out).
96    pub answered: bool,
97}
98
99/// Queue of SysEx requests and writes with at most one in flight.
100#[derive(Debug)]
101pub struct RequestQueue {
102    queue: VecDeque<Request>,
103    in_flight: Option<(Request, Instant)>,
104    timeout: Duration,
105    sync_total: usize,
106    sync_done: usize,
107}
108
109/// The official app's startup reads (docs/protocol/commands.md), all read-only. Presets come before the edit
110/// buffer so the active preset can be identified by matching the edit buffer against them
111/// (see [`DeviceState`](crate::DeviceState)).
112pub fn handshake() -> Vec<Vec<u8>> {
113    let mut reqs = vec![req::version(), req::product(), req::settings(), req::cur_state(), req::drum()];
114    reqs.extend((0..10).map(req::ir_slot));
115    reqs.extend((0..10).map(req::user_amp));
116    reqs.extend((0..99).map(req::preset));
117    reqs.extend([req::edit_buffer(), req::looper(), req::tuner()]);
118    reqs
119}
120
121/// Follow-up reads after pedal-side changes that carry no data themselves: a preset saved on the
122/// pedal (re-read it and the edit buffer), the tuner toggled (read its state) and the chain
123/// reordered on the pedal (read the new order).
124pub fn follow_up(msg: &Msg) -> Vec<Vec<u8>> {
125    match msg {
126        Msg::Notify { what, .. } if *what == Cmd::Chain as u8 => vec![req::chain()],
127        Msg::Notify { what, payload } if *what == Cmd::Preset as u8 => {
128            let i = payload.first().copied().unwrap_or(0);
129            vec![req::preset(i), req::edit_buffer()]
130        }
131        Msg::Notify { what, .. } if *what == Cmd::Tuner as u8 => vec![req::tuner()],
132        _ => vec![],
133    }
134}
135
136impl RequestQueue {
137    /// `timeout`: how long to wait for a reply before moving on (the official app uses 1 s).
138    pub fn new(timeout: Duration) -> Self {
139        RequestQueue { queue: VecDeque::new(), in_flight: None, timeout, sync_total: 0, sync_done: 0 }
140    }
141
142    /// Drop everything queued and in flight, and any sync in progress.
143    pub fn clear(&mut self) {
144        self.queue.clear();
145        self.in_flight = None;
146        self.sync_total = 0;
147        self.sync_done = 0;
148    }
149
150    /// Start a sync: replaces the queue with `reqs`, whose replies count towards [`progress`].
151    ///
152    /// [`progress`]: RequestQueue::progress
153    pub fn start_sync(&mut self, reqs: Vec<Vec<u8>>) {
154        self.clear();
155        self.sync_total = reqs.len();
156        for bytes in reqs {
157            self.read(bytes);
158        }
159    }
160
161    /// Queue a read. Ignored when the same request is already waiting.
162    pub fn read(&mut self, bytes: Vec<u8>) {
163        if !self.queue.iter().any(|r| r.bytes == bytes) {
164            let expect = Expect::of(&bytes);
165            self.queue.push_back(Request { bytes, expect, sync: self.sync_total > 0 });
166        }
167    }
168
169    /// Queue a write (or any message that must keep its place after queued SysEx). Settings and the
170    /// chain order are rewritten whole on every change, so a queued write of either is replaced by
171    /// the newer one.
172    pub fn write(&mut self, bytes: Vec<u8>) {
173        let whole = |b: &[u8]| match Msg::parse(b) {
174            Msg::Nep { cmd, dir: 1, .. } if cmd == Cmd::System as u8 || cmd == Cmd::Chain as u8 => Some(cmd),
175            _ => None,
176        };
177        let expect = Expect::of(&bytes);
178        if let Some(c) = whole(&bytes)
179            && let Some(r) = self.queue.iter_mut().find(|r| whole(&r.bytes) == Some(c))
180        {
181            r.bytes = bytes;
182            return;
183        }
184        self.queue.push_back(Request { bytes, expect, sync: false });
185    }
186
187    /// The next message to send, if nothing is in flight. Pass it to [`sent`] once transmitted.
188    ///
189    /// [`sent`]: RequestQueue::sent
190    pub fn pop(&mut self) -> Option<Request> {
191        if self.in_flight.is_some() {
192            return None;
193        }
194        self.queue.pop_front()
195    }
196
197    /// Record that `r` went out at `now`; it is in flight until answered or timed out.
198    pub fn sent(&mut self, r: Request, now: Instant) {
199        if r.expect.is_some() {
200            self.in_flight = Some((r, now));
201        }
202    }
203
204    /// Feed a complete incoming message. Returns the request it answers, if any.
205    pub fn on_message(&mut self, msg: &Msg) -> Option<Done> {
206        let (r, _) = self.in_flight.as_ref()?;
207        if !r.expect.is_some_and(|e| e.matches(msg)) {
208            return None;
209        }
210        let (request, _) = self.in_flight.take()?;
211        self.finish(request, true)
212    }
213
214    /// Expire the in-flight request if it has waited longer than the timeout.
215    pub fn expire(&mut self, now: Instant) -> Option<Done> {
216        let (_, t) = self.in_flight.as_ref()?;
217        if now.saturating_duration_since(*t) <= self.timeout {
218            return None;
219        }
220        let (request, _) = self.in_flight.take()?;
221        self.finish(request, false)
222    }
223
224    fn finish(&mut self, request: Request, answered: bool) -> Option<Done> {
225        if request.sync && self.sync_total > 0 {
226            self.sync_done += 1;
227            if self.sync_done >= self.sync_total {
228                self.sync_total = 0;
229                self.sync_done = 0;
230            }
231        }
232        Some(Done { request, answered })
233    }
234
235    /// `(done, total)` of the current sync; `(0, 0)` when none is running.
236    pub fn progress(&self) -> (usize, usize) {
237        (self.sync_done, self.sync_total)
238    }
239
240    pub fn in_flight(&self) -> Option<&Request> {
241        self.in_flight.as_ref().map(|(r, _)| r)
242    }
243
244    /// Messages waiting (not counting the one in flight).
245    pub fn len(&self) -> usize {
246        self.queue.len()
247    }
248
249    pub fn is_empty(&self) -> bool {
250        self.queue.is_empty() && self.in_flight.is_none()
251    }
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257    use crate::midi::host;
258    use crate::records::Settings;
259
260    fn t0() -> Instant {
261        Instant::now()
262    }
263
264    #[test]
265    fn one_in_flight_until_answered() {
266        let mut q = RequestQueue::new(Duration::from_secs(1));
267        q.read(req::settings());
268        q.read(req::drum());
269        q.read(req::settings()); // duplicate, ignored
270        assert_eq!(q.len(), 2);
271        let r = q.pop().unwrap();
272        assert_eq!(r.expect(), Some(Expect::Reply(0x14)));
273        q.sent(r, t0());
274        assert!(q.pop().is_none());
275        // unrelated traffic doesn't release it
276        assert!(q.on_message(&Msg::parse(&[0xB0, 0x12, 5])).is_none());
277        assert!(q.on_message(&Msg::parse(&req::settings())).is_none()); // dir 0, not a reply
278        let done = q.on_message(&Msg::Nep { cmd: 0x14, dir: 2, payload: vec![0; 20] }).unwrap();
279        assert!(done.answered);
280        assert_eq!(q.pop().unwrap().bytes(), &req::drum()[..]);
281    }
282
283    #[test]
284    fn live_messages_are_not_in_flight() {
285        let mut q = RequestQueue::new(Duration::from_secs(1));
286        q.write(host::program(3));
287        q.write(host::cc(0x12, 50));
288        let r = q.pop().unwrap();
289        assert_eq!(r.expect(), None);
290        q.sent(r, t0());
291        assert!(q.in_flight().is_none());
292        assert!(q.pop().is_some());
293    }
294
295    #[test]
296    fn timeout_moves_on_and_counts_sync() {
297        let mut q = RequestQueue::new(Duration::from_millis(100));
298        q.start_sync(vec![req::version(), req::product()]);
299        let start = t0();
300        let r = q.pop().unwrap();
301        assert_eq!(r.expect(), Some(Expect::Short(0x10)));
302        q.sent(r, start);
303        assert!(q.expire(start + Duration::from_millis(50)).is_none());
304        let done = q.expire(start + Duration::from_millis(150)).unwrap();
305        assert!(!done.answered && done.request.is_sync());
306        assert_eq!(q.progress(), (1, 2));
307        let r = q.pop().unwrap();
308        q.sent(r, start);
309        // product reply: F0 00 21 7A 60 <name> F7
310        let reply = [0xF0, 0, 0x21, 0x7A, 0x60, b'J', b'M', b'E', 0xF7];
311        assert!(q.on_message(&Msg::parse(&reply)).unwrap().answered);
312        assert_eq!(q.progress(), (0, 0));
313    }
314
315    #[test]
316    fn chain_writes_wait_for_reply_and_coalesce() {
317        let mut q = RequestQueue::new(Duration::from_secs(1));
318        let a = host::chain(&[6, 0, 1, 2, 7, 4, 3, 5]).unwrap();
319        let b = host::chain(&[6, 0, 1, 2, 7, 3, 5, 4]).unwrap();
320        q.write(a.clone());
321        q.write(b.clone());
322        assert_eq!(q.len(), 1);
323        let r = q.pop().unwrap();
324        assert_eq!((r.bytes(), r.expect()), (&b[..], Some(Expect::Reply(0x0D))));
325        q.sent(r, Instant::now());
326        // the pedal's answer to a chain write (2026-12-03)
327        let reply = [0xF0, 0, 0x21, 0x7A, 0x70, 0x0D, 2, 6, 0, 1, 2, 7, 3, 5, 4, 0xF7];
328        assert!(q.on_message(&Msg::parse(&reply)).unwrap().answered);
329    }
330
331    #[test]
332    fn settings_writes_coalesce() {
333        let mut q = RequestQueue::new(Duration::from_secs(1));
334        q.write(host::program(1));
335        let mut s = Settings { raw: vec![0; 17], ..Default::default() };
336        q.write(host::settings_write(&s));
337        s.input_trim = 13;
338        q.write(host::settings_write(&s));
339        assert_eq!(q.len(), 2);
340        q.pop();
341        assert_eq!(q.pop().unwrap().bytes(), &host::settings_write(&s)[..]);
342    }
343
344    #[test]
345    fn handshake_matches_official_app() {
346        let h = handshake();
347        assert_eq!(h.len(), 5 + 10 + 10 + 99 + 3);
348        assert!(h.iter().all(|r| Expect::of(r).is_some()), "every handshake read expects a reply");
349    }
350
351    #[test]
352    fn follow_ups() {
353        let saved = Msg::Notify { what: 0x0B, payload: vec![7] };
354        assert_eq!(follow_up(&saved), vec![req::preset(7), req::edit_buffer()]);
355        assert_eq!(follow_up(&Msg::Notify { what: 0x6F, payload: vec![] }), vec![req::tuner()]);
356        // sent by the pedal after each move of a block on its chain screen
357        let moved = Msg::parse(&[0xF0, 0, 0x21, 0x7A, 0x70, 0x7E, 2, 0x0D, 2, 0, 0, 0, 0, 0, 0, 0xF7]);
358        assert_eq!(follow_up(&moved), vec![req::chain()]);
359        assert!(follow_up(&Msg::Pc { ch: 0, prog: 1 }).is_empty());
360    }
361}