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 chrono::Duration;
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    // changes to this should update BraidMetadataSchemaTag
84    /// Host time at which the measurement was requested.
85    pub start_timestamp: chrono::DateTime<chrono::Utc>,
86    /// Triggerbox pulse number.
87    pub framecount: i64,
88    /// Fraction of the current pulse elapsed, scaled to 0-255.
89    pub tcnt: u8,
90    /// Host time at which the measurement was received.
91    pub stop_timestamp: chrono::DateTime<chrono::Utc>,
92}
93
94/// A Braid Triggerbox device.
95pub struct TriggerboxDevice {
96    icr1_and_prescaler: Option<TopAndPrescaler>,
97    version_check_done: bool,
98    qi: u8,
99    queries: BTreeMap<u8, chrono::DateTime<chrono::Utc>>,
100    ser: tokio_serial::SerialStream,
101    outq: Receiver<Cmd>,
102    vquery_time: chrono::DateTime<chrono::Utc>,
103    last_time: chrono::DateTime<chrono::Utc>,
104    past_data: Vec<(f64, f64)>,
105    allow_requesting_clock_sync: bool,
106    on_new_model_cb: ClockModelCallback,
107    triggerbox_data_tx: Option<Sender<TriggerClockInfoRow>>,
108    max_acceptable_measurement_error: Duration,
109    query_dt: Duration,
110}
111
112impl std::fmt::Debug for TriggerboxDevice {
113    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114        f.debug_struct("TriggerboxDevice")
115            .field("icr1_and_prescaler", &self.icr1_and_prescaler)
116            .field("version_check_done", &self.version_check_done)
117            .field("ser", &self.ser)
118            .finish_non_exhaustive()
119    }
120}
121
122/// A command for the triggerbox.
123#[derive(Debug, Clone)]
124pub enum Cmd {
125    /// Set the trigger rate.
126    TopAndPrescaler(TopAndPrescaler),
127    /// Stop the trigger pulses and reset the pulse number.
128    StopPulsesAndReset,
129    /// Start the trigger pulses.
130    StartPulses,
131    /// Store a device name on the device.
132    SetDeviceName(InnerNameType),
133    /// Set the analog outputs (in volts).
134    SetAOut((f64, f64)),
135}
136
137/// A sample returned by the device.
138#[derive(Debug, PartialEq, Eq)]
139struct TimedSample {
140    value: u8,
141    pulsenumber: u32,
142    count: u16,
143}
144
145/// A packet sent by the device.
146#[derive(Debug, PartialEq, Eq)]
147enum DevicePacket {
148    Timestamp(TimedSample),
149    Version(TimedSample),
150    /// Confirmation of new analog output values.
151    AOutConfirm(TimedSample),
152    /// A byte which does not start a valid packet was dropped.
153    Skipped(SkipReason),
154}
155
156/// Why a byte received from the device was dropped.
157#[derive(Debug, PartialEq, Eq)]
158enum SkipReason {
159    UnknownPacketType(u8),
160    BadPayloadLength { packet_type: u8, payload_len: u8 },
161    ChecksumMismatch,
162}
163
164/// Every packet sent by the device has a 7 byte payload.
165const PAYLOAD_LEN: u8 = 7;
166
167/// Remove the first packet from `buf` and return it.
168///
169/// If `buf` does not start with a valid packet, the first byte is removed and
170/// [`DevicePacket::Skipped`] is returned, so that the next call can find the
171/// start of the next packet. Returns `None` if `buf` does not yet hold a
172/// complete packet.
173fn take_packet(buf: &mut Vec<u8>) -> Option<DevicePacket> {
174    // A packet is a header (type and payload length), the payload and a
175    // checksum.
176    let [packet_type, payload_len, rest @ ..] = buf.as_slice() else {
177        return None;
178    };
179    let (packet_type, payload_len) = (*packet_type, *payload_len);
180
181    let skip_reason = if !matches!(packet_type, b'P' | b'V' | b'O') {
182        Some(SkipReason::UnknownPacketType(packet_type))
183    } else if payload_len != PAYLOAD_LEN {
184        Some(SkipReason::BadPayloadLength {
185            packet_type,
186            payload_len,
187        })
188    } else {
189        let (payload, tail) = rest.split_first_chunk::<7>()?;
190        let [expected_chksum, ..] = tail else {
191            return None;
192        };
193        let actual_chksum = payload.iter().fold(0u8, |acc, x| acc.wrapping_add(*x));
194        if actual_chksum == *expected_chksum {
195            let [value, p0, p1, p2, p3, c0, c1] = *payload;
196            let sample = TimedSample {
197                value,
198                pulsenumber: u32::from_le_bytes([p0, p1, p2, p3]),
199                count: u16::from_le_bytes([c0, c1]),
200            };
201            let packet = match packet_type {
202                b'P' => DevicePacket::Timestamp(sample),
203                b'V' => DevicePacket::Version(sample),
204                _ => DevicePacket::AOutConfirm(sample),
205            };
206            // header (2) + payload + checksum (1)
207            buf.drain(..usize::from(PAYLOAD_LEN).saturating_add(3));
208            return Some(packet);
209        }
210        Some(SkipReason::ChecksumMismatch)
211    };
212
213    buf.drain(..1);
214    skip_reason.map(DevicePacket::Skipped)
215}
216
217/// Truncate `x` towards zero to a `u16`, or `None` if out of range.
218fn f64_to_u16_checked(x: f64) -> Option<u16> {
219    if (0.0..65536.0).contains(&x) {
220        #[expect(
221            clippy::cast_possible_truncation,
222            clippy::cast_sign_loss,
223            reason = "range checked above, truncation is intended"
224        )]
225        Some(x as u16)
226    } else {
227        None
228    }
229}
230
231/// Truncate `x` towards zero to a `u8`, or `None` if out of range.
232fn f64_to_u8_checked(x: f64) -> Option<u8> {
233    f64_to_u16_checked(x).and_then(|x| u8::try_from(x).ok())
234}
235
236/// Convert a voltage to a 12-bit DAC value, clamping to the DAC range.
237fn volts_to_dac(volts: f64) -> u16 {
238    // Convert voltage to fraction and clamp.
239    let frac = (volts / 4.096).clamp(0.0, 1.0);
240    // Compute integer DAC value. (A NaN voltage gives zero.)
241    f64_to_u16_checked((frac * 4095.0).round()).unwrap_or(0)
242}
243
244impl TriggerboxDevice {
245    /// Connect to the triggerbox at `opts.device_path`.
246    ///
247    /// # Errors
248    ///
249    /// Returns an error if the options are out of range, or if the device
250    /// cannot be opened, does not respond or does not have the name
251    /// `opts.assert_device_name` (if given).
252    pub async fn new(
253        on_new_model_cb: ClockModelCallback,
254        outq: Receiver<Cmd>,
255        triggerbox_data_tx: Option<Sender<TriggerClockInfoRow>>,
256        opts: TriggerboxOptions,
257    ) -> Result<Self> {
258        let TriggerboxOptions {
259            device_path,
260            query_dt,
261            assert_device_name,
262            max_acceptable_measurement_error,
263            sleep_dur,
264        } = opts;
265        let baud_rate = 115_200;
266        let max_acceptable_measurement_error = Duration::from_std(max_acceptable_measurement_error)
267            .context("max_acceptable_measurement_error out of range")?;
268        let query_dt = Duration::from_std(query_dt).context("query_dt out of range")?;
269        let now = chrono::Utc::now();
270
271        // wait 1 second before first version query
272        let vquery_time = add_duration(now, Duration::seconds(1))?;
273        let last_time = add_duration(vquery_time, Duration::seconds(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 = chrono::Utc::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 = chrono::Utc::now();
443
444            if self.version_check_done {
445                if self.allow_requesting_clock_sync
446                    && (now.signed_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.signed_duration_since(self.vquery_time) > Duration::seconds(1) {
467                    version_check_started = false;
468                }
469                // give up after 20 seconds
470                if now.signed_duration_since(connect_time) > Duration::seconds(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 = chrono::Utc::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.signed_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 = Duration::microseconds(
516            max_error
517                .num_microseconds()
518                .context("measurement error out of range")?
519                / 2,
520        );
521        let ino_time_estimate = add_duration(send_timestamp, half_max_error)?;
522
523        let Some(s) = &self.icr1_and_prescaler else {
524            warn!("No clock measurements until framerate set.");
525            return Ok(());
526        };
527
528        let frac = f64::from(count) / f64::from(s.avr_icr1());
529        if !(0.0..=1.0).contains(&frac) {
530            warn!("ignoring clock sample with invalid count {count}");
531            return Ok(());
532        }
533        let ino_stamp = f64::from(pulsenumber) + frac;
534
535        if let Some(tbox_tx) = &self.triggerbox_data_tx {
536            // send our newly acquired data to be saved to disk
537            let to_save = TriggerClockInfoRow {
538                start_timestamp: send_timestamp,
539                framecount: i64::from(pulsenumber),
540                tcnt: f64_to_u8_checked(frac * 255.0).unwrap_or(u8::MAX),
541                stop_timestamp: now,
542            };
543            if let Err(e) = tbox_tx.send(to_save).await {
544                warn!("ignoring {e}");
545            }
546        }
547
548        // delete old data
549        while self.past_data.len() >= 100 {
550            self.past_data.remove(0);
551        }
552
553        self.past_data.push((
554            ino_stamp,
555            datetime_conversion::datetime_to_f64(&ino_time_estimate),
556        ));
557
558        if self.past_data.len() >= 5 {
559            let (gain, offset, residuals) =
560                fit_time_model(&self.past_data).map_err(|e| anyhow::anyhow!("lstsq err: {e}"))?;
561
562            let n_measurements = u32::try_from(self.past_data.len())?;
563            let per_point_residual = residuals / f64::from(n_measurements);
564            // TODO only accept this if residuals less than some amount?
565            debug!(
566                "new: ClockModel{{gain: {gain}, offset: {offset}}}, per_point_residual: {per_point_residual}"
567            );
568            (self.on_new_model_cb)(Some(ClockModel {
569                gain,
570                offset,
571                residuals,
572                n_measurements: u64::from(n_measurements),
573            }));
574        }
575        Ok(())
576    }
577
578    fn handle_version(&mut self, sample: &TimedSample) -> Result<()> {
579        let value = sample.value;
580        trace!("got returned version with value: {value}");
581        if value != DEVICE_FIRMWARE_VERSION {
582            anyhow::bail!(
583                "triggerbox firmware version {value} is not supported (expected version \
584                {DEVICE_FIRMWARE_VERSION})"
585            );
586        }
587        self.vquery_time = chrono::Utc::now();
588        self.version_check_done = true;
589        info!("connected to triggerbox firmware version {value}");
590        Ok(())
591    }
592
593    async fn handle_data_from_device(&mut self, buf: &mut Vec<u8>) -> Result<()> {
594        while let Some(packet) = take_packet(buf) {
595            match packet {
596                DevicePacket::Timestamp(sample) => self.handle_returned_timestamp(sample).await?,
597                DevicePacket::Version(sample) => self.handle_version(&sample)?,
598                DevicePacket::AOutConfirm(sample) => {
599                    debug!("ignoring AOUT confirmation {}", sample.value);
600                }
601                DevicePacket::Skipped(reason) => {
602                    warn!("dropped a byte received from the device: {reason:?}");
603                }
604            }
605        }
606        Ok(())
607    }
608}
609
610fn update_read_buffer(n_bytes_read: usize, read_buf: &[u8], buf: &mut Vec<u8>) {
611    for &byte in read_buf.iter().take(n_bytes_read) {
612        trace!("read byte {byte} (char {})", char::from(byte));
613        buf.push(byte);
614    }
615}
616
617fn add_duration(
618    t: chrono::DateTime<chrono::Utc>,
619    d: Duration,
620) -> Result<chrono::DateTime<chrono::Utc>> {
621    t.checked_add_signed(d).context("time out of range")
622}
623
624fn fit_time_model(past_data: &[(f64, f64)]) -> Result<(f64, f64, f64), &'static str> {
625    use na::{OMatrix, OVector, U2};
626
627    let mut a: Vec<f64> = Vec::with_capacity(past_data.len().saturating_mul(2));
628    let mut b: Vec<f64> = Vec::with_capacity(past_data.len());
629
630    for row in past_data {
631        a.push(row.0);
632        a.push(1.0);
633        b.push(row.1);
634    }
635    let a = OMatrix::<f64, na::Dyn, U2>::from_row_slice(&a);
636    let b = OVector::<f64, na::Dyn>::from_row_slice(&b);
637
638    let epsilon = 1e-10;
639    let results = lstsq::lstsq(&a, &b, epsilon)?;
640
641    let gain = results.solution.x;
642    let offset = results.solution.y;
643    let residuals = results.residuals;
644
645    Ok((gain, offset, residuals))
646}
647
648/// Options for [`run_triggerbox`].
649#[derive(Clone, Debug)]
650pub struct TriggerboxOptions {
651    /// Path of the serial device.
652    pub device_path: String,
653    /// Interval between clock measurements.
654    pub query_dt: std::time::Duration,
655    /// If given, the required device name.
656    pub assert_device_name: NameType,
657    /// Clock measurements which take longer than this are discarded.
658    pub max_acceptable_measurement_error: std::time::Duration,
659    /// Time to wait for the device to reset after opening it.
660    pub sleep_dur: std::time::Duration,
661}
662
663/// Connect to a triggerbox and run until `outq` is closed.
664///
665/// # Errors
666///
667/// Returns an error if connecting to or communicating with the device fails.
668pub async fn run_triggerbox(
669    on_new_model_cb: ClockModelCallback,
670    outq: Receiver<Cmd>,
671    triggerbox_data_tx: Option<Sender<TriggerClockInfoRow>>,
672    opts: TriggerboxOptions,
673) -> Result<()> {
674    let triggerbox = TriggerboxDevice::new(on_new_model_cb, outq, triggerbox_data_tx, opts).await?;
675    triggerbox.run_forever().await
676}
677
678fn get_rate(rate_ideal: f64, prescaler: Prescaler) -> (u16, f64) {
679    let xtal = 16e6; // 16 MHz clock
680    let base_clock = xtal / prescaler.as_f64();
681    let new_top_ideal = base_clock / rate_ideal;
682    let new_icr1_f64 = new_top_ideal.round().clamp(0.0, f64::from(u16::MAX));
683    // A NaN rate gives zero.
684    let new_icr1 = f64_to_u16_checked(new_icr1_f64).unwrap_or(0);
685    let rate_actual = base_clock / f64::from(new_icr1);
686    (new_icr1, rate_actual)
687}
688
689/// Given an ideal frame rate (in frames per second), compute the triggerbox
690/// command which best approximates this frame rate.
691///
692/// Returns the triggerbox command and the expected actual frame rate (in frames
693/// per second).
694#[must_use]
695pub fn make_trig_fps_cmd(rate_ideal: f64) -> (Cmd, f64) {
696    let (top_8, rate_actual_8) = get_rate(rate_ideal, Prescaler::Scale8);
697    let (top_64, rate_actual_64) = get_rate(rate_ideal, Prescaler::Scale64);
698
699    let error_8 = (rate_ideal - rate_actual_8).abs();
700    let error_64 = (rate_ideal - rate_actual_64).abs();
701
702    let (top, rate_actual, prescaler) = if error_8 < error_64 {
703        (top_8, rate_actual_8, Prescaler::Scale8)
704    } else {
705        (top_64, rate_actual_64, Prescaler::Scale64)
706    };
707
708    (
709        Cmd::TopAndPrescaler(TopAndPrescaler::new_avr(top, prescaler)),
710        rate_actual,
711    )
712}
713
714#[cfg(test)]
715mod tests {
716    use super::*;
717
718    fn packet(packet_type: u8, payload: &[u8]) -> Vec<u8> {
719        let mut buf = vec![packet_type, u8::try_from(payload.len()).unwrap()];
720        buf.extend_from_slice(payload);
721        buf.push(payload.iter().fold(0u8, |acc, x| acc.wrapping_add(*x)));
722        buf
723    }
724
725    #[test]
726    fn test_fit_time_model() {
727        let epsilon = 1e-12;
728
729        let data = vec![(0.0, 0.0), (1.0, 1.0), (2.0, 2.0), (3.0, 3.0)];
730        let (gain, offset, _residuals) = fit_time_model(&data).unwrap();
731        assert!((gain - 1.0).abs() < epsilon);
732        assert!((offset - 0.0).abs() < epsilon);
733
734        let data = vec![(0.0, 12.0), (1.0, 22.0), (2.0, 32.0), (3.0, 42.0)];
735        let (gain, offset, _residuals) = fit_time_model(&data).unwrap();
736        assert!((gain - 10.0).abs() < epsilon);
737        assert!((offset - 12.0).abs() < epsilon);
738    }
739
740    fn sample(value: u8, pulsenumber: u32, count: u16) -> TimedSample {
741        TimedSample {
742            value,
743            pulsenumber,
744            count,
745        }
746    }
747
748    #[test]
749    fn take_packets() {
750        let mut buf = packet(b'P', &[3, 1, 0, 0, 0, 2, 0]);
751        buf.extend(packet(b'V', &[14, 0, 0, 0, 0, 0, 0]));
752        buf.extend(packet(b'O', &[b'x', 0, 0, 0, 0, 0, 0]));
753        // A partial packet.
754        buf.extend(&[b'P', 7, 0]);
755
756        assert_eq!(
757            take_packet(&mut buf),
758            Some(DevicePacket::Timestamp(sample(3, 1, 2)))
759        );
760        assert_eq!(
761            take_packet(&mut buf),
762            Some(DevicePacket::Version(sample(14, 0, 0)))
763        );
764        assert_eq!(
765            take_packet(&mut buf),
766            Some(DevicePacket::AOutConfirm(sample(b'x', 0, 0)))
767        );
768        assert_eq!(take_packet(&mut buf), None);
769        assert_eq!(buf, [b'P', 7, 0]);
770    }
771
772    /// Take packets until `buf` is exhausted, returning the valid ones and the
773    /// number of skipped bytes.
774    fn take_all(buf: &mut Vec<u8>) -> (Vec<DevicePacket>, usize) {
775        let (skipped, packets): (Vec<_>, Vec<_>) = std::iter::from_fn(|| take_packet(buf))
776            .partition(|packet| matches!(packet, DevicePacket::Skipped(_)));
777        (packets, skipped.len())
778    }
779
780    #[test]
781    fn take_packet_resynchronizes() {
782        let good = packet(b'P', &[9, 8, 0, 0, 0, 6, 0]);
783
784        // A packet with a bad checksum, then a good packet.
785        let mut buf = packet(b'P', &[1, 2, 3, 4, 5, 6, 7]);
786        *buf.last_mut().unwrap() ^= 0xFF;
787        assert_eq!(
788            take_packet(&mut buf.clone()),
789            Some(DevicePacket::Skipped(SkipReason::ChecksumMismatch))
790        );
791        buf.extend(&good);
792        let (packets, n_skipped) = take_all(&mut buf);
793        assert_eq!(packets, [DevicePacket::Timestamp(sample(9, 8, 6))]);
794        assert_eq!(n_skipped, 10);
795        assert_eq!(buf, Vec::<u8>::new());
796
797        // A packet with a bad payload length, then a good packet.
798        let mut buf = packet(b'V', &[1, 2, 3]);
799        assert_eq!(
800            take_packet(&mut buf.clone()),
801            Some(DevicePacket::Skipped(SkipReason::BadPayloadLength {
802                packet_type: b'V',
803                payload_len: 3
804            }))
805        );
806        buf.extend(&good);
807        let (packets, _) = take_all(&mut buf);
808        assert_eq!(packets, [DevicePacket::Timestamp(sample(9, 8, 6))]);
809
810        // Garbage, then a good packet.
811        let mut buf = b"garbage".to_vec();
812        buf.extend(&good);
813        let (packets, n_skipped) = take_all(&mut buf);
814        assert_eq!(packets, [DevicePacket::Timestamp(sample(9, 8, 6))]);
815        assert_eq!(n_skipped, 7);
816    }
817
818    #[test]
819    fn name_type() {
820        assert_eq!(to_name_type("abc").unwrap(), *b"abc\0\0\0\0\0");
821        assert_eq!(to_name_type("abcdefgh").unwrap(), *b"abcdefgh");
822        assert!(to_name_type("abcdefghi").is_err());
823    }
824
825    #[test]
826    fn dac_values() {
827        assert_eq!(volts_to_dac(-1.0), 0);
828        assert_eq!(volts_to_dac(0.0), 0);
829        assert_eq!(volts_to_dac(4.096), 4095);
830        assert_eq!(volts_to_dac(100.0), 4095);
831        assert_eq!(volts_to_dac(f64::NAN), 0);
832    }
833
834    #[test]
835    fn trig_fps_cmd() {
836        let (_cmd, rate_actual) = make_trig_fps_cmd(100.0);
837        assert!((rate_actual - 100.0).abs() < 1e-6);
838        // Extreme requests are clamped rather than panicking.
839        for rate in [0.0, 1e-6, 1e12, f64::NAN, f64::INFINITY] {
840            let _ = make_trig_fps_cmd(rate);
841        }
842    }
843}