Skip to main content

braid_triggerbox/
lib.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Host-side driver for the Braid camera synchronization triggerbox.
4
5mod datetime_conversion;
6
7mod arduino_udev;
8use crate::arduino_udev::serial_handshake;
9
10use anyhow::{Context, Result};
11use jiff::{SignedDuration, Timestamp};
12use log::{debug, error, info, trace, warn};
13
14use nalgebra as na;
15
16use std::collections::BTreeMap;
17use tokio::{
18    io::{AsyncReadExt, AsyncWriteExt},
19    sync::mpsc::{Receiver, Sender},
20};
21
22use braid_triggerbox_comms::{DEVICE_FIRMWARE_VERSION, Prescaler, TopAndPrescaler};
23
24// ----- name type handling
25
26/// Length of the device name (in bytes).
27pub const DEVICE_NAME_LEN: usize = 8;
28
29/// A device name.
30pub type InnerNameType = [u8; DEVICE_NAME_LEN];
31/// An optional device name.
32pub type NameType = Option<InnerNameType>;
33
34/// Callback called with each new clock model, or `None` when the model is
35/// reset.
36pub type ClockModelCallback = Box<dyn FnMut(Option<ClockModel>) + Send>;
37
38/// Convert a string to a device name.
39///
40/// # Errors
41///
42/// Returns an error if `x` is longer than [`DEVICE_NAME_LEN`] bytes.
43pub fn to_name_type(x: &str) -> Result<InnerNameType> {
44    let bytes = x.as_bytes();
45    if bytes.len() > DEVICE_NAME_LEN {
46        anyhow::bail!("Maximum name length ({DEVICE_NAME_LEN} chars) exceeded.");
47    }
48    let mut name = [0; DEVICE_NAME_LEN];
49    for (dest, src) in name.iter_mut().zip(bytes) {
50        *dest = *src;
51    }
52    Ok(name)
53}
54
55/// Format a device name for display.
56#[must_use]
57pub fn name_display(name: &NameType) -> String {
58    if let Some(name) = name {
59        format!("\"{}\"", String::from_utf8_lossy(name))
60    } else {
61        "none".into()
62    }
63}
64
65// ------ clock model types
66
67/// A linear model relating triggerbox pulse number to host time.
68#[derive(Debug, PartialEq, Clone)]
69pub struct ClockModel {
70    /// Seconds per pulse.
71    pub gain: f64,
72    /// Host time (in seconds since the UNIX epoch) of pulse zero.
73    pub offset: f64,
74    /// Sum of squared residuals of the fit.
75    pub residuals: f64,
76    /// Number of measurements used for the fit.
77    pub n_measurements: u64,
78}
79
80/// A raw clock measurement.
81#[derive(Debug)]
82pub struct TriggerClockInfoRow {
83    /// Host time at which the measurement was requested.
84    pub start_timestamp: Timestamp,
85    /// Triggerbox pulse number.
86    pub framecount: i64,
87    /// Fraction of the current pulse elapsed, scaled to 0-255.
88    pub tcnt: u8,
89    /// Host time at which the measurement was received.
90    pub stop_timestamp: Timestamp,
91}
92
93/// A Braid Triggerbox device.
94pub struct TriggerboxDevice {
95    icr1_and_prescaler: Option<TopAndPrescaler>,
96    version_check_done: bool,
97    qi: u8,
98    queries: BTreeMap<u8, Timestamp>,
99    ser: tokio_serial::SerialStream,
100    outq: Receiver<Cmd>,
101    vquery_time: Timestamp,
102    last_time: Timestamp,
103    past_data: Vec<(f64, f64)>,
104    allow_requesting_clock_sync: bool,
105    on_new_model_cb: ClockModelCallback,
106    triggerbox_data_tx: Option<Sender<TriggerClockInfoRow>>,
107    max_acceptable_measurement_error: SignedDuration,
108    query_dt: SignedDuration,
109}
110
111impl std::fmt::Debug for TriggerboxDevice {
112    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113        f.debug_struct("TriggerboxDevice")
114            .field("icr1_and_prescaler", &self.icr1_and_prescaler)
115            .field("version_check_done", &self.version_check_done)
116            .field("ser", &self.ser)
117            .finish_non_exhaustive()
118    }
119}
120
121/// A command for the triggerbox.
122#[derive(Debug, Clone)]
123pub enum Cmd {
124    /// Set the trigger rate.
125    TopAndPrescaler(TopAndPrescaler),
126    /// Stop the trigger pulses and reset the pulse number.
127    StopPulsesAndReset,
128    /// Start the trigger pulses.
129    StartPulses,
130    /// Store a device name on the device.
131    SetDeviceName(InnerNameType),
132    /// Set the analog outputs (in volts).
133    SetAOut((f64, f64)),
134}
135
136/// A sample returned by the device.
137#[derive(Debug, PartialEq, Eq)]
138struct TimedSample {
139    value: u8,
140    pulsenumber: u32,
141    count: u16,
142}
143
144/// A packet sent by the device.
145#[derive(Debug, PartialEq, Eq)]
146enum DevicePacket {
147    Timestamp(TimedSample),
148    Version(TimedSample),
149    /// Confirmation of new analog output values.
150    AOutConfirm(TimedSample),
151    /// A byte which does not start a valid packet was dropped.
152    Skipped(SkipReason),
153}
154
155/// Why a byte received from the device was dropped.
156#[derive(Debug, PartialEq, Eq)]
157enum SkipReason {
158    UnknownPacketType(u8),
159    BadPayloadLength { packet_type: u8, payload_len: u8 },
160    ChecksumMismatch,
161}
162
163/// Every packet sent by the device has a 7 byte payload.
164const PAYLOAD_LEN: u8 = 7;
165
166/// Remove the first packet from `buf` and return it.
167///
168/// If `buf` does not start with a valid packet, the first byte is removed and
169/// [`DevicePacket::Skipped`] is returned, so that the next call can find the
170/// start of the next packet. Returns `None` if `buf` does not yet hold a
171/// complete packet.
172fn take_packet(buf: &mut Vec<u8>) -> Option<DevicePacket> {
173    // A packet is a header (type and payload length), the payload and a
174    // checksum.
175    let [packet_type, payload_len, rest @ ..] = buf.as_slice() else {
176        return None;
177    };
178    let (packet_type, payload_len) = (*packet_type, *payload_len);
179
180    let skip_reason = if !matches!(packet_type, b'P' | b'V' | b'O') {
181        Some(SkipReason::UnknownPacketType(packet_type))
182    } else if payload_len != PAYLOAD_LEN {
183        Some(SkipReason::BadPayloadLength {
184            packet_type,
185            payload_len,
186        })
187    } else {
188        let (payload, tail) = rest.split_first_chunk::<7>()?;
189        let [expected_chksum, ..] = tail else {
190            return None;
191        };
192        let actual_chksum = payload.iter().fold(0u8, |acc, x| acc.wrapping_add(*x));
193        if actual_chksum == *expected_chksum {
194            let [value, p0, p1, p2, p3, c0, c1] = *payload;
195            let sample = TimedSample {
196                value,
197                pulsenumber: u32::from_le_bytes([p0, p1, p2, p3]),
198                count: u16::from_le_bytes([c0, c1]),
199            };
200            let packet = match packet_type {
201                b'P' => DevicePacket::Timestamp(sample),
202                b'V' => DevicePacket::Version(sample),
203                _ => DevicePacket::AOutConfirm(sample),
204            };
205            // header (2) + payload + checksum (1)
206            buf.drain(..usize::from(PAYLOAD_LEN).saturating_add(3));
207            return Some(packet);
208        }
209        Some(SkipReason::ChecksumMismatch)
210    };
211
212    buf.drain(..1);
213    skip_reason.map(DevicePacket::Skipped)
214}
215
216/// Truncate `x` towards zero to a `u16`, or `None` if out of range.
217fn f64_to_u16_checked(x: f64) -> Option<u16> {
218    if (0.0..65536.0).contains(&x) {
219        #[expect(
220            clippy::cast_possible_truncation,
221            clippy::cast_sign_loss,
222            reason = "range checked above, truncation is intended"
223        )]
224        Some(x as u16)
225    } else {
226        None
227    }
228}
229
230/// Truncate `x` towards zero to a `u8`, or `None` if out of range.
231fn f64_to_u8_checked(x: f64) -> Option<u8> {
232    f64_to_u16_checked(x).and_then(|x| u8::try_from(x).ok())
233}
234
235/// Convert a voltage to a 12-bit DAC value, clamping to the DAC range.
236fn volts_to_dac(volts: f64) -> u16 {
237    // Convert voltage to fraction and clamp.
238    let frac = (volts / 4.096).clamp(0.0, 1.0);
239    // Compute integer DAC value. (A NaN voltage gives zero.)
240    f64_to_u16_checked((frac * 4095.0).round()).unwrap_or(0)
241}
242
243impl TriggerboxDevice {
244    /// Connect to the triggerbox at `opts.device_path`.
245    ///
246    /// # Errors
247    ///
248    /// Returns an error if the options are out of range, or if the device
249    /// cannot be opened, does not respond or does not have the name
250    /// `opts.assert_device_name` (if given).
251    pub async fn new(
252        on_new_model_cb: ClockModelCallback,
253        outq: Receiver<Cmd>,
254        triggerbox_data_tx: Option<Sender<TriggerClockInfoRow>>,
255        opts: TriggerboxOptions,
256    ) -> Result<Self> {
257        let TriggerboxOptions {
258            device_path,
259            query_dt,
260            assert_device_name,
261            max_acceptable_measurement_error,
262            sleep_dur,
263        } = opts;
264        let baud_rate = 115_200;
265        let max_acceptable_measurement_error =
266            SignedDuration::try_from(max_acceptable_measurement_error)
267                .context("max_acceptable_measurement_error out of range")?;
268        let query_dt = SignedDuration::try_from(query_dt).context("query_dt out of range")?;
269        let now = Timestamp::now();
270
271        // wait 1 second before first version query
272        let vquery_time = add_duration(now, SignedDuration::from_secs(1))?;
273        let last_time = add_duration(vquery_time, SignedDuration::from_secs(1))?;
274
275        debug!("Opening device at path {device_path}");
276
277        let (ser, name) = match tokio::time::timeout(
278            std::time::Duration::from_secs(15),
279            serial_handshake(&device_path, baud_rate, sleep_dur),
280        )
281        .await
282        {
283            Ok(r) => r,
284            Err(elapsed) => Err(anyhow::Error::from(elapsed)),
285        }
286        .with_context(|| format!("opening device {device_path}"))?;
287
288        if let Some(name) = &name {
289            let name_str = String::from_utf8_lossy(name);
290            debug!("Connected to device named \"{name_str}\".");
291        } else {
292            debug!("Connected to unnamed device.");
293        }
294
295        if assert_device_name.is_some() && name != assert_device_name {
296            anyhow::bail!(
297                "Found name {}, but expected {}. ({:?} vs {:?}.)",
298                name_display(&name),
299                name_display(&assert_device_name),
300                name,
301                assert_device_name,
302            );
303        }
304
305        Ok(Self {
306            icr1_and_prescaler: None,
307            version_check_done: false,
308            qi: 0,
309            queries: BTreeMap::new(),
310            ser,
311            outq,
312            vquery_time,
313            last_time,
314            past_data: Vec::new(),
315            allow_requesting_clock_sync: false,
316            on_new_model_cb,
317            triggerbox_data_tx,
318            max_acceptable_measurement_error,
319            query_dt,
320        })
321    }
322
323    async fn write(&mut self, buf: &[u8]) -> tokio::io::Result<()> {
324        trace!("sending: \"{}\"", String::from_utf8_lossy(buf));
325        for byte in buf {
326            trace!("sending byte: {byte}");
327        }
328        AsyncWriteExt::write_all(&mut self.ser, buf).await?;
329        Ok(())
330    }
331
332    async fn handle_host_command(&mut self, cmd: Cmd) -> Result<()> {
333        debug!("got command {cmd:?}");
334        match cmd {
335            Cmd::TopAndPrescaler(new_value) => {
336                self.set_top_and_prescaler(new_value).await?;
337            }
338            Cmd::StopPulsesAndReset => {
339                debug!("will reset counters. dropping outstanding info requests.");
340                self.allow_requesting_clock_sync = false;
341                self.queries.clear();
342                self.past_data.clear();
343                (self.on_new_model_cb)(None);
344                self.write(b"S0").await?;
345            }
346            Cmd::StartPulses => {
347                self.allow_requesting_clock_sync = true;
348                self.write(b"S1").await?;
349            }
350            Cmd::SetDeviceName(name) => {
351                // The device reads exactly two hex digits.
352                let computed_crc = format!("{:02X}", arduino_udev::CRC_MAXIM.checksum(&name));
353                trace!("computed CRC: {computed_crc:?}");
354
355                self.write(b"N=").await?;
356                self.write(&name).await?;
357                self.write(computed_crc.as_bytes()).await?;
358            }
359            Cmd::SetAOut((volts1, volts2)) => {
360                let val1 = volts_to_dac(volts1);
361                let val2 = volts_to_dac(volts2);
362
363                self.write(b"O=").await?;
364                self.write(&val1.to_le_bytes()).await?;
365                self.write(&val2.to_le_bytes()).await?;
366                self.write(b"x").await?;
367
368                // Now wait for return value.
369                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
370
371                let mut buf = vec![0; 100];
372                let len = self.ser.read(&mut buf).await?;
373                buf.truncate(len);
374                debug!("AOUT ignoring values: {buf:?}");
375            }
376        }
377        Ok(())
378    }
379
380    /// Run forever, handling interaction with the triggerbox hardware device.
381    ///
382    /// Drop all instances of the `Sender<Cmd>` which could send messages to the
383    /// `Receiver<Cmd>` passed to [`Self::new`] to exit.
384    ///
385    /// # Errors
386    ///
387    /// Returns an error if communication with the device fails.
388    pub async fn run_forever(mut self: TriggerboxDevice) -> Result<()> {
389        let query_dt = self.query_dt;
390
391        let connect_time = Timestamp::now();
392
393        let mut buf: Vec<u8> = Vec::new();
394        let mut read_buf: Vec<u8> = vec![0; 100];
395        let mut version_check_started = false;
396        let mut new_data = false;
397        let mut interval = tokio::time::interval(std::time::Duration::from_millis(100));
398
399        loop {
400            if self.version_check_done {
401                tokio::select! {
402                    // Handle command queue iff version check done.
403                    opt_cmd_tup = self.outq.recv() => {
404                        if let Some(cmd) = opt_cmd_tup {
405                            self.handle_host_command(cmd).await?;
406                        } else {
407                            // no more commands, sender hung up
408                            info!("exiting run loop");
409                            return Ok(());
410                        }
411                    },
412                    res_r = self.ser.read(&mut read_buf) => {
413                        let n_bytes_read = res_r?;
414                        if n_bytes_read > 0 {
415                            update_read_buffer(n_bytes_read, &read_buf, &mut buf);
416                            new_data = true;
417                        }
418                    },
419                    _ = interval.tick() => {}
420                }
421            } else {
422                // Same as above except `self.outq` is not checked. This is done
423                // at startup before the version number is confirmed.
424                tokio::select! {
425                    res_r = self.ser.read(&mut read_buf) => {
426                        let n_bytes_read = res_r?;
427                        if n_bytes_read > 0 {
428                            update_read_buffer(n_bytes_read, &read_buf, &mut buf);
429                            new_data = true;
430                        }
431                    },
432                    _ = interval.tick() => {}
433                }
434            }
435
436            // handle pending data, if any
437            if new_data {
438                self.handle_data_from_device(&mut buf).await?;
439                new_data = false;
440            }
441
442            let now = Timestamp::now();
443
444            if self.version_check_done {
445                if self.allow_requesting_clock_sync
446                    && (now.duration_since(self.last_time) > query_dt)
447                {
448                    // request sample
449                    debug!("making clock sample request. qi: {}, now: {now}", self.qi);
450                    self.queries.insert(self.qi, now);
451                    let send_buf = [b'P', self.qi];
452                    self.write(&send_buf).await?;
453                    self.qi = self.qi.wrapping_add(1);
454                    self.last_time = now;
455                }
456            } else {
457                // request firmware version
458                if !version_check_started && now >= self.vquery_time {
459                    info!("checking firmware version");
460                    self.write(b"V?").await?;
461                    version_check_started = true;
462                    self.vquery_time = now;
463                }
464
465                // retry every second
466                if now.duration_since(self.vquery_time) > SignedDuration::from_secs(1) {
467                    version_check_started = false;
468                }
469                // give up after 20 seconds
470                if now.duration_since(connect_time) > SignedDuration::from_secs(20) {
471                    return Err(anyhow::anyhow!("no version response"));
472                }
473            }
474        }
475    }
476
477    async fn set_top_and_prescaler(&mut self, new_value: TopAndPrescaler) -> Result<()> {
478        let [icr1_lo, icr1_hi] = new_value.avr_icr1().to_le_bytes();
479        let buf = [icr1_lo, icr1_hi, new_value.prescaler_key()];
480
481        self.icr1_and_prescaler = Some(new_value);
482
483        self.write(b"T=").await?;
484        self.write(&buf).await?;
485        Ok(())
486    }
487
488    async fn handle_returned_timestamp(&mut self, sample: TimedSample) -> Result<()> {
489        let TimedSample {
490            value: qi,
491            pulsenumber,
492            count,
493        } = sample;
494        debug!("got returned timestamp with qi: {qi}, pulsenumber: {pulsenumber}, count: {count}");
495        let now = Timestamp::now();
496        if self.queries.len() > 50 {
497            self.queries.clear();
498            error!("too many outstanding queries");
499        }
500
501        let Some(send_timestamp) = self.queries.remove(&qi) else {
502            warn!("could not find original data for query {qi:?}");
503            return Ok(());
504        };
505        trace!("this query has send_timestamp: {send_timestamp}");
506
507        let max_error = now.duration_since(send_timestamp);
508        if max_error > self.max_acceptable_measurement_error {
509            debug!("clock sample took {max_error:?}. Ignoring value.");
510            return Ok(());
511        }
512
513        trace!("max_error: {max_error:?}");
514
515        let half_max_error = max_error
516            .checked_div(2)
517            .context("measurement error out of range")?;
518        let ino_time_estimate = add_duration(send_timestamp, half_max_error)?;
519
520        let Some(s) = &self.icr1_and_prescaler else {
521            warn!("No clock measurements until framerate set.");
522            return Ok(());
523        };
524
525        let frac = f64::from(count) / f64::from(s.avr_icr1());
526        if !(0.0..=1.0).contains(&frac) {
527            warn!("ignoring clock sample with invalid count {count}");
528            return Ok(());
529        }
530        let ino_stamp = f64::from(pulsenumber) + frac;
531
532        if let Some(tbox_tx) = &self.triggerbox_data_tx {
533            // send our newly acquired data to be saved to disk
534            let to_save = TriggerClockInfoRow {
535                start_timestamp: send_timestamp,
536                framecount: i64::from(pulsenumber),
537                tcnt: f64_to_u8_checked(frac * 255.0).unwrap_or(u8::MAX),
538                stop_timestamp: now,
539            };
540            if let Err(e) = tbox_tx.send(to_save).await {
541                warn!("ignoring {e}");
542            }
543        }
544
545        // delete old data
546        while self.past_data.len() >= 100 {
547            self.past_data.remove(0);
548        }
549
550        self.past_data.push((
551            ino_stamp,
552            datetime_conversion::timestamp_to_f64(ino_time_estimate),
553        ));
554
555        if self.past_data.len() >= 5 {
556            let (gain, offset, residuals) =
557                fit_time_model(&self.past_data).map_err(|e| anyhow::anyhow!("lstsq err: {e}"))?;
558
559            let n_measurements = u32::try_from(self.past_data.len())?;
560            let per_point_residual = residuals / f64::from(n_measurements);
561            // TODO only accept this if residuals less than some amount?
562            debug!(
563                "new: ClockModel{{gain: {gain}, offset: {offset}}}, per_point_residual: {per_point_residual}"
564            );
565            (self.on_new_model_cb)(Some(ClockModel {
566                gain,
567                offset,
568                residuals,
569                n_measurements: u64::from(n_measurements),
570            }));
571        }
572        Ok(())
573    }
574
575    fn handle_version(&mut self, sample: &TimedSample) -> Result<()> {
576        let value = sample.value;
577        trace!("got returned version with value: {value}");
578        if value != DEVICE_FIRMWARE_VERSION {
579            anyhow::bail!(
580                "triggerbox firmware version {value} is not supported (expected version \
581                {DEVICE_FIRMWARE_VERSION})"
582            );
583        }
584        self.vquery_time = Timestamp::now();
585        self.version_check_done = true;
586        info!("connected to triggerbox firmware version {value}");
587        Ok(())
588    }
589
590    async fn handle_data_from_device(&mut self, buf: &mut Vec<u8>) -> Result<()> {
591        while let Some(packet) = take_packet(buf) {
592            match packet {
593                DevicePacket::Timestamp(sample) => self.handle_returned_timestamp(sample).await?,
594                DevicePacket::Version(sample) => self.handle_version(&sample)?,
595                DevicePacket::AOutConfirm(sample) => {
596                    debug!("ignoring AOUT confirmation {}", sample.value);
597                }
598                DevicePacket::Skipped(reason) => {
599                    warn!("dropped a byte received from the device: {reason:?}");
600                }
601            }
602        }
603        Ok(())
604    }
605}
606
607fn update_read_buffer(n_bytes_read: usize, read_buf: &[u8], buf: &mut Vec<u8>) {
608    for &byte in read_buf.iter().take(n_bytes_read) {
609        trace!("read byte {byte} (char {})", char::from(byte));
610        buf.push(byte);
611    }
612}
613
614fn add_duration(t: Timestamp, d: SignedDuration) -> Result<Timestamp> {
615    t.checked_add(d).context("time out of range")
616}
617
618fn fit_time_model(past_data: &[(f64, f64)]) -> Result<(f64, f64, f64), &'static str> {
619    use na::{OMatrix, OVector, U2};
620
621    let mut a: Vec<f64> = Vec::with_capacity(past_data.len().saturating_mul(2));
622    let mut b: Vec<f64> = Vec::with_capacity(past_data.len());
623
624    for row in past_data {
625        a.push(row.0);
626        a.push(1.0);
627        b.push(row.1);
628    }
629    let a = OMatrix::<f64, na::Dyn, U2>::from_row_slice(&a);
630    let b = OVector::<f64, na::Dyn>::from_row_slice(&b);
631
632    let epsilon = 1e-10;
633    let results = lstsq::lstsq(&a, &b, epsilon)?;
634
635    let gain = results.solution.x;
636    let offset = results.solution.y;
637    let residuals = results.residuals;
638
639    Ok((gain, offset, residuals))
640}
641
642/// Options for [`run_triggerbox`].
643#[derive(Clone, Debug)]
644pub struct TriggerboxOptions {
645    /// Path of the serial device.
646    pub device_path: String,
647    /// Interval between clock measurements.
648    pub query_dt: std::time::Duration,
649    /// If given, the required device name.
650    pub assert_device_name: NameType,
651    /// Clock measurements which take longer than this are discarded.
652    pub max_acceptable_measurement_error: std::time::Duration,
653    /// Time to wait for the device to reset after opening it.
654    pub sleep_dur: std::time::Duration,
655}
656
657/// Connect to a triggerbox and run until `outq` is closed.
658///
659/// # Errors
660///
661/// Returns an error if connecting to or communicating with the device fails.
662pub async fn run_triggerbox(
663    on_new_model_cb: ClockModelCallback,
664    outq: Receiver<Cmd>,
665    triggerbox_data_tx: Option<Sender<TriggerClockInfoRow>>,
666    opts: TriggerboxOptions,
667) -> Result<()> {
668    let triggerbox = TriggerboxDevice::new(on_new_model_cb, outq, triggerbox_data_tx, opts).await?;
669    triggerbox.run_forever().await
670}
671
672fn get_rate(rate_ideal: f64, prescaler: Prescaler) -> (u16, f64) {
673    let xtal = 16e6; // 16 MHz clock
674    let base_clock = xtal / prescaler.as_f64();
675    let new_top_ideal = base_clock / rate_ideal;
676    let new_icr1_f64 = new_top_ideal.round().clamp(0.0, f64::from(u16::MAX));
677    // A NaN rate gives zero.
678    let new_icr1 = f64_to_u16_checked(new_icr1_f64).unwrap_or(0);
679    let rate_actual = base_clock / f64::from(new_icr1);
680    (new_icr1, rate_actual)
681}
682
683/// Given an ideal frame rate (in frames per second), compute the triggerbox
684/// command which best approximates this frame rate.
685///
686/// Returns the triggerbox command and the expected actual frame rate (in frames
687/// per second).
688#[must_use]
689pub fn make_trig_fps_cmd(rate_ideal: f64) -> (Cmd, f64) {
690    let (top_8, rate_actual_8) = get_rate(rate_ideal, Prescaler::Scale8);
691    let (top_64, rate_actual_64) = get_rate(rate_ideal, Prescaler::Scale64);
692
693    let error_8 = (rate_ideal - rate_actual_8).abs();
694    let error_64 = (rate_ideal - rate_actual_64).abs();
695
696    let (top, rate_actual, prescaler) = if error_8 < error_64 {
697        (top_8, rate_actual_8, Prescaler::Scale8)
698    } else {
699        (top_64, rate_actual_64, Prescaler::Scale64)
700    };
701
702    (
703        Cmd::TopAndPrescaler(TopAndPrescaler::new_avr(top, prescaler)),
704        rate_actual,
705    )
706}
707
708#[cfg(test)]
709mod tests {
710    use super::*;
711
712    fn packet(packet_type: u8, payload: &[u8]) -> Vec<u8> {
713        let mut buf = vec![packet_type, u8::try_from(payload.len()).unwrap()];
714        buf.extend_from_slice(payload);
715        buf.push(payload.iter().fold(0u8, |acc, x| acc.wrapping_add(*x)));
716        buf
717    }
718
719    #[test]
720    fn test_fit_time_model() {
721        let epsilon = 1e-12;
722
723        let data = vec![(0.0, 0.0), (1.0, 1.0), (2.0, 2.0), (3.0, 3.0)];
724        let (gain, offset, _residuals) = fit_time_model(&data).unwrap();
725        assert!((gain - 1.0).abs() < epsilon);
726        assert!((offset - 0.0).abs() < epsilon);
727
728        let data = vec![(0.0, 12.0), (1.0, 22.0), (2.0, 32.0), (3.0, 42.0)];
729        let (gain, offset, _residuals) = fit_time_model(&data).unwrap();
730        assert!((gain - 10.0).abs() < epsilon);
731        assert!((offset - 12.0).abs() < epsilon);
732    }
733
734    fn sample(value: u8, pulsenumber: u32, count: u16) -> TimedSample {
735        TimedSample {
736            value,
737            pulsenumber,
738            count,
739        }
740    }
741
742    #[test]
743    fn take_packets() {
744        let mut buf = packet(b'P', &[3, 1, 0, 0, 0, 2, 0]);
745        buf.extend(packet(b'V', &[14, 0, 0, 0, 0, 0, 0]));
746        buf.extend(packet(b'O', &[b'x', 0, 0, 0, 0, 0, 0]));
747        // A partial packet.
748        buf.extend(&[b'P', 7, 0]);
749
750        assert_eq!(
751            take_packet(&mut buf),
752            Some(DevicePacket::Timestamp(sample(3, 1, 2)))
753        );
754        assert_eq!(
755            take_packet(&mut buf),
756            Some(DevicePacket::Version(sample(14, 0, 0)))
757        );
758        assert_eq!(
759            take_packet(&mut buf),
760            Some(DevicePacket::AOutConfirm(sample(b'x', 0, 0)))
761        );
762        assert_eq!(take_packet(&mut buf), None);
763        assert_eq!(buf, [b'P', 7, 0]);
764    }
765
766    /// Take packets until `buf` is exhausted, returning the valid ones and the
767    /// number of skipped bytes.
768    fn take_all(buf: &mut Vec<u8>) -> (Vec<DevicePacket>, usize) {
769        let (skipped, packets): (Vec<_>, Vec<_>) = std::iter::from_fn(|| take_packet(buf))
770            .partition(|packet| matches!(packet, DevicePacket::Skipped(_)));
771        (packets, skipped.len())
772    }
773
774    #[test]
775    fn take_packet_resynchronizes() {
776        let good = packet(b'P', &[9, 8, 0, 0, 0, 6, 0]);
777
778        // A packet with a bad checksum, then a good packet.
779        let mut buf = packet(b'P', &[1, 2, 3, 4, 5, 6, 7]);
780        *buf.last_mut().unwrap() ^= 0xFF;
781        assert_eq!(
782            take_packet(&mut buf.clone()),
783            Some(DevicePacket::Skipped(SkipReason::ChecksumMismatch))
784        );
785        buf.extend(&good);
786        let (packets, n_skipped) = take_all(&mut buf);
787        assert_eq!(packets, [DevicePacket::Timestamp(sample(9, 8, 6))]);
788        assert_eq!(n_skipped, 10);
789        assert_eq!(buf, Vec::<u8>::new());
790
791        // A packet with a bad payload length, then a good packet.
792        let mut buf = packet(b'V', &[1, 2, 3]);
793        assert_eq!(
794            take_packet(&mut buf.clone()),
795            Some(DevicePacket::Skipped(SkipReason::BadPayloadLength {
796                packet_type: b'V',
797                payload_len: 3
798            }))
799        );
800        buf.extend(&good);
801        let (packets, _) = take_all(&mut buf);
802        assert_eq!(packets, [DevicePacket::Timestamp(sample(9, 8, 6))]);
803
804        // Garbage, then a good packet.
805        let mut buf = b"garbage".to_vec();
806        buf.extend(&good);
807        let (packets, n_skipped) = take_all(&mut buf);
808        assert_eq!(packets, [DevicePacket::Timestamp(sample(9, 8, 6))]);
809        assert_eq!(n_skipped, 7);
810    }
811
812    #[test]
813    fn name_type() {
814        assert_eq!(to_name_type("abc").unwrap(), *b"abc\0\0\0\0\0");
815        assert_eq!(to_name_type("abcdefgh").unwrap(), *b"abcdefgh");
816        assert!(to_name_type("abcdefghi").is_err());
817    }
818
819    #[test]
820    fn dac_values() {
821        assert_eq!(volts_to_dac(-1.0), 0);
822        assert_eq!(volts_to_dac(0.0), 0);
823        assert_eq!(volts_to_dac(4.096), 4095);
824        assert_eq!(volts_to_dac(100.0), 4095);
825        assert_eq!(volts_to_dac(f64::NAN), 0);
826    }
827
828    #[test]
829    fn trig_fps_cmd() {
830        let (_cmd, rate_actual) = make_trig_fps_cmd(100.0);
831        assert!((rate_actual - 100.0).abs() < 1e-6);
832        // Extreme requests are clamped rather than panicking.
833        for rate in [0.0, 1e-6, 1e12, f64::NAN, f64::INFINITY] {
834            let _ = make_trig_fps_cmd(rate);
835        }
836    }
837}