cal_model/session.rs
1//! The calibration session: read-modify-write over an XCP transport, with
2//! page switching, snapshots, restore, and diffs.
3//!
4//! # The transport is a trait, not a wire protocol
5//!
6//! [`XcpTransport`] is two methods — read bytes at an ECU address, write
7//! bytes at an ECU address — plus an optional
8//! [`set_page`](XcpTransport::set_page). Everything above it (addressing,
9//! element coding, conversions, limits, paging) is this crate's job;
10//! everything below it (CTO framing, block mode, CAN IDs, transport-layer
11//! timing) is `xcp_core`'s and the caller's. A bench mock, a UDP XCP slave,
12//! and a SocketCAN bridge all satisfy the same three methods, which is what
13//! makes the session testable without an ECU — see [`crate::mock`].
14//!
15//! [`CalibrationSession`] also exposes the `xcp_core` command frames for
16//! each operation ([`upload_frames`](CalibrationSession::upload_frames),
17//! [`download_frames`](CalibrationSession::download_frames),
18//! [`set_cal_page_frame`](CalibrationSession::set_cal_page_frame)), so a
19//! caller that *is* a wire bridge builds the right frames instead of
20//! inventing them.
21//!
22//! # Writes are verified, not trusted
23//!
24//! `write_characteristic` checks the A2L limits, inverts the COMPU_METHOD,
25//! checks that the deposit can represent the result, reads back what it
26//! wrote, and fails if the read-back differs. A calibration tool that
27//! reports a write it cannot confirm is worse than one that reports an
28//! error.
29
30use crate::error::CalError;
31use crate::project::CalibrationProject;
32use std::fmt;
33
34/// Byte-level ECU memory access, as a calibration session needs it.
35pub trait XcpTransport {
36 /// Read `len` bytes at ECU address `addr`.
37 ///
38 /// # Errors
39 ///
40 /// [`CalError::Transport`] when the slave or the link failed; the
41 /// session surfaces the transport's own message unchanged.
42 fn read(&mut self, addr: u32, len: u8) -> Result<Vec<u8>, CalError>;
43
44 /// Write `data` at ECU address `addr`.
45 ///
46 /// # Errors
47 ///
48 /// [`CalError::Transport`] when the slave or the link failed.
49 fn write(&mut self, addr: u32, data: &[u8]) -> Result<(), CalError>;
50
51 /// Switch the slave's active calibration page (`SET_CAL_PAGE`).
52 ///
53 /// The default implementation accepts the switch without doing anything:
54 /// a transport over an ECU with a single calibration page has nothing to
55 /// do. A transport that multiplexes pages (or that forwards the command
56 /// to a real slave) overrides it.
57 ///
58 /// # Errors
59 ///
60 /// [`CalError::Transport`] when the slave rejected the switch.
61 fn set_page(&mut self, _page: u32) -> Result<(), CalError> {
62 Ok(())
63 }
64
65 /// This transport as `Any`, for a caller that wants to reach a concrete
66 /// implementation through the trait object (a test asserting on
67 /// [`MockTransport`](crate::mock::MockTransport)'s recorded traffic, say).
68 ///
69 /// The default returns `None` — an implementation opts in by overriding
70 /// it with `Some(self)`, so the trait stays object-safe and adding this
71 /// was never a breaking change.
72 fn as_any(&self) -> Option<&dyn std::any::Any> {
73 None
74 }
75}
76
77/// One captured value of one characteristic element.
78#[derive(Debug, Clone, PartialEq)]
79pub struct SnapshotValue {
80 /// The memory bit pattern.
81 pub raw: u64,
82 /// The physical value the conversion produced.
83 pub physical: f64,
84}
85
86/// One characteristic as captured: every element it deposits.
87#[derive(Debug, Clone, PartialEq)]
88pub struct SnapshotEntry {
89 /// The module the characteristic lives in.
90 pub module: String,
91 /// The characteristic name.
92 pub name: String,
93 /// Its elements, in deposit order.
94 pub elements: Vec<SnapshotValue>,
95}
96
97impl SnapshotEntry {
98 /// The physical value of element `index`.
99 #[must_use]
100 pub fn physical(&self, index: usize) -> Option<f64> {
101 self.elements.get(index).map(|v| v.physical)
102 }
103
104 /// `name` or `name[index]`, the way a report refers to one element.
105 #[must_use]
106 pub fn element_name(&self, index: usize) -> String {
107 element_name(&self.name, self.elements.len(), index)
108 }
109}
110
111impl fmt::Display for SnapshotEntry {
112 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113 write!(
114 f,
115 " {}.{} ({} element{})",
116 self.module,
117 self.name,
118 self.elements.len(),
119 if self.elements.len() == 1 { "" } else { "s" }
120 )?;
121 for (index, value) in self.elements.iter().enumerate() {
122 write!(
123 f,
124 "\n [{index}] raw 0x{:X} physical {:.6}",
125 value.raw, value.physical
126 )?;
127 }
128 Ok(())
129 }
130}
131
132/// A captured calibration set: the values of every named characteristic,
133/// with the page they were read on.
134#[derive(Debug, Clone, PartialEq, Default)]
135pub struct Snapshot {
136 /// The calibration page that was active when the capture started.
137 pub page: u32,
138 /// The captured characteristics, in capture order.
139 pub entries: Vec<SnapshotEntry>,
140}
141
142impl Snapshot {
143 /// An empty snapshot on page `page`.
144 #[must_use]
145 pub fn empty(page: u32) -> Self {
146 Self {
147 page,
148 entries: Vec::new(),
149 }
150 }
151
152 /// The entry for `name` in `module`.
153 #[must_use]
154 pub fn entry(&self, module: &str, name: &str) -> Option<&SnapshotEntry> {
155 self.entries
156 .iter()
157 .find(|e| e.module == module && e.name == name)
158 }
159
160 /// The entry for `name`, searched across every module.
161 #[must_use]
162 pub fn find(&self, name: &str) -> Option<&SnapshotEntry> {
163 self.entries.iter().find(|e| e.name == name)
164 }
165
166 /// The physical value of `name`'s first element.
167 #[must_use]
168 pub fn physical(&self, name: &str) -> Option<f64> {
169 self.find(name).and_then(|entry| entry.physical(0))
170 }
171
172 /// Total number of elements captured.
173 #[must_use]
174 pub fn element_count(&self) -> usize {
175 self.entries.iter().map(|e| e.elements.len()).sum()
176 }
177}
178
179impl fmt::Display for Snapshot {
180 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181 writeln!(
182 f,
183 "calibration snapshot: page {}, {} characteristic(s), {} element(s)",
184 self.page,
185 self.entries.len(),
186 self.element_count()
187 )?;
188 for entry in &self.entries {
189 writeln!(f, "{entry}")?;
190 }
191 Ok(())
192 }
193}
194
195/// One change between two calibration states.
196#[derive(Debug, Clone, PartialEq)]
197pub struct CalibrationDelta {
198 /// The changed parameter: `characteristic`, or `characteristic[index]`
199 /// for a multi-element deposit.
200 pub name: String,
201 /// The value before the change (`NaN` when the parameter was not in the
202 /// "before" snapshot).
203 pub before: f64,
204 /// The value after the change.
205 pub after: f64,
206 /// `after - before` (`NaN` when `before` is `NaN`).
207 pub delta: f64,
208 /// Whether `after` is inside the A2L limits of the characteristic.
209 pub within_limits: bool,
210}
211
212impl CalibrationDelta {
213 /// `true` when this parameter was absent from the "before" snapshot.
214 #[must_use]
215 pub fn is_new(&self) -> bool {
216 self.before.is_nan()
217 }
218
219 /// `true` when nothing moved.
220 #[must_use]
221 pub fn is_unchanged(&self) -> bool {
222 !self.is_new() && self.delta == 0.0
223 }
224}
225
226impl fmt::Display for CalibrationDelta {
227 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228 let verdict = if self.within_limits {
229 "ok"
230 } else {
231 "OUT OF LIMITS"
232 };
233 if self.is_new() {
234 write!(
235 f,
236 "{:<28} {:>14} {:>14.6} {:>14} {verdict} (new)",
237 self.name, "-", self.after, "-"
238 )
239 } else {
240 write!(
241 f,
242 "{:<28} {:>14.6} {:>14.6} {:>+14.6} {verdict}",
243 self.name, self.before, self.after, self.delta
244 )
245 }
246 }
247}
248
249/// Render a diff report: one header line, then one row per delta, then a
250/// summary.
251#[must_use]
252pub fn render_deltas(deltas: &[CalibrationDelta]) -> String {
253 use std::fmt::Write as _;
254
255 let mut out = String::new();
256 let _ = writeln!(
257 out,
258 "{:<28} {:>14} {:>14} {:>14} limits",
259 "parameter", "before", "after", "delta"
260 );
261 for delta in deltas {
262 let _ = writeln!(out, "{delta}");
263 }
264 let changed = deltas.iter().filter(|d| !d.is_unchanged()).count();
265 let out_of_limits = deltas.iter().filter(|d| !d.within_limits).count();
266 let _ = writeln!(
267 out,
268 "-- {changed} changed, {} unchanged, {out_of_limits} out of limits",
269 deltas.len() - changed
270 );
271 out
272}
273
274/// Diff two calibration states: `before` → `after`, one entry per element,
275/// limit-checked against `project`'s current A2L limits.
276///
277/// A parameter present in `after` but not in `before` is reported with
278/// `before == NaN` ([`CalibrationDelta::is_new`]); a parameter only in
279/// `before` (removed between the two captures) is not reported, because the
280/// report describes the state being moved to.
281#[must_use]
282pub fn diff_snapshots(
283 before: Option<&Snapshot>,
284 after: &Snapshot,
285 project: &CalibrationProject,
286) -> Vec<CalibrationDelta> {
287 let mut deltas = Vec::new();
288 for entry in &after.entries {
289 let before_entry = before.and_then(|b| b.entry(&entry.module, &entry.name));
290 let characteristic = project.characteristic(&entry.module, &entry.name).ok();
291 for (index, value) in entry.elements.iter().enumerate() {
292 let before_value = before_entry
293 .and_then(|b| b.elements.get(index))
294 .map_or(f64::NAN, |v| v.physical);
295 let delta = if before_value.is_nan() {
296 f64::NAN
297 } else {
298 value.physical - before_value
299 };
300 let within_limits = characteristic.is_none_or(|c| c.within_limits(value.physical));
301 deltas.push(CalibrationDelta {
302 name: entry.element_name(index),
303 before: before_value,
304 after: value.physical,
305 delta,
306 within_limits,
307 });
308 }
309 }
310 deltas
311}
312
313/// A calibration session against one ECU, over one transport.
314pub struct CalibrationSession<'a> {
315 project: &'a CalibrationProject,
316 transport: Box<dyn XcpTransport + 'a>,
317 page: u32,
318 resources: xcp_core::ResourceMode,
319 baseline: Option<Snapshot>,
320}
321
322impl<'a> CalibrationSession<'a> {
323 /// Open a session on `project` over `transport`.
324 ///
325 /// `mode` is the slave's resource bitmask. When it is non-empty the
326 /// session requires [`ResourceMode::CAL_PAGE`](xcp_core::ResourceMode::CAL_PAGE)
327 /// and refuses to connect otherwise — a slave that advertises no CAL/PAG
328 /// resource cannot be calibrated, and finding that out at connect time
329 /// is much cheaper than finding it out at the first write. Pass the empty
330 /// mask ([`ResourceMode::CONNECT_NORMAL`]) to skip the check, which is
331 /// what a caller does when the transport is not completing a real CONNECT
332 /// handshake.
333 ///
334 /// # Errors
335 ///
336 /// [`CalError::Xcp`] — [`xcp_core::XcpError::AccessDenied`] — when the
337 /// resource mask excludes CAL/PAG.
338 pub fn connect(
339 project: &'a CalibrationProject,
340 transport: Box<dyn XcpTransport + 'a>,
341 mode: xcp_core::ResourceMode,
342 ) -> Result<Self, CalError> {
343 if !mode.is_empty() && !mode.cal_page() {
344 return Err(CalError::Xcp(xcp_core::XcpError::AccessDenied));
345 }
346 Ok(Self {
347 project,
348 transport,
349 page: 0,
350 resources: mode,
351 baseline: None,
352 })
353 }
354
355 /// The project this session calibrates.
356 #[must_use]
357 pub const fn project(&self) -> &'a CalibrationProject {
358 self.project
359 }
360
361 /// The transport, borrowed.
362 #[must_use]
363 pub fn transport(&self) -> &dyn XcpTransport {
364 self.transport.as_ref()
365 }
366
367 /// The transport, mutably borrowed.
368 pub fn transport_mut(&mut self) -> &mut (dyn XcpTransport + 'a) {
369 self.transport.as_mut()
370 }
371
372 /// The negotiated resource mask.
373 #[must_use]
374 pub const fn resources(&self) -> xcp_core::ResourceMode {
375 self.resources
376 }
377
378 /// The active calibration page.
379 #[must_use]
380 pub const fn cal_page(&self) -> u32 {
381 self.page
382 }
383
384 /// Switch the slave's active calibration page.
385 ///
386 /// # Errors
387 ///
388 /// [`CalError::Transport`] when the transport rejected the switch; the
389 /// session's page is left unchanged in that case, so a failed switch
390 /// cannot silently redirect a later write to the wrong page.
391 pub fn set_cal_page(&mut self, page: u32) -> Result<(), CalError> {
392 self.transport.set_page(page)?;
393 self.page = page;
394 Ok(())
395 }
396
397 /// The `SET_MTA` + `UPLOAD` frames for a read of `len` bytes at `addr`,
398 /// in the project's deposit byte order.
399 #[must_use]
400 pub fn upload_frames(&self, addr: u32, len: u8) -> Vec<u8> {
401 xcp_core::upload_with(self.project.deposit_byte_order(), addr, 0, len)
402 }
403
404 /// The `SET_MTA` + `DOWNLOAD` frames for a write of `data` at `addr`, in
405 /// the project's deposit byte order.
406 #[must_use]
407 pub fn download_frames(&self, addr: u32, data: &[u8]) -> Vec<u8> {
408 xcp_core::download_with(self.project.deposit_byte_order(), addr, 0, data)
409 }
410
411 /// The `SET_CAL_PAGE` frame for `page` (switch on the ECU, all
412 /// segments).
413 #[must_use]
414 pub fn set_cal_page_frame(&self, page: u32) -> Vec<u8> {
415 xcp_core::set_cal_page(self.project.deposit_byte_order(), 0x03, page as u16)
416 }
417
418 /// Read a characteristic and return the physical value of its first
419 /// element.
420 ///
421 /// # Errors
422 ///
423 /// [`CalError::Transport`] on a bus failure, [`CalError::Unsupported`]
424 /// for an unresolvable conversion or a deposit the UPLOAD cannot carry,
425 /// plus the lookup errors.
426 pub fn read_characteristic(&mut self, module: &str, name: &str) -> Result<f64, CalError> {
427 let raws = self.read_characteristic_raw(module, name)?;
428 match raws.first() {
429 Some(&raw) => self.project.to_physical(module, name, raw),
430 // `elements == 0` is not rejected at declare_elements time (a
431 // zero-element curve is a legal if useless declaration), so the
432 // read path refuses it rather than indexing.
433 None => Err(CalError::Unsupported {
434 subject: format!("characteristic `{}`", qualified(module, name)),
435 reason: "the deposit declares no elements".to_string(),
436 }),
437 }
438 }
439
440 /// Read every element of a characteristic and return their physical
441 /// values — the curve or map as one read.
442 ///
443 /// # Errors
444 ///
445 /// As [`read_characteristic`](Self::read_characteristic).
446 pub fn read_characteristic_elements(
447 &mut self,
448 module: &str,
449 name: &str,
450 ) -> Result<Vec<f64>, CalError> {
451 let raws = self.read_characteristic_raw(module, name)?;
452 let characteristic = self.project.characteristic(module, name)?;
453 self.project.physical_values(characteristic, &raws)
454 }
455
456 /// Read every element of a characteristic and return its raw bit
457 /// patterns.
458 ///
459 /// # Errors
460 ///
461 /// [`CalError::Transport`], [`CalError::Unsupported`] (including a
462 /// deposit larger than one 255-byte UPLOAD), plus the lookup errors.
463 pub fn read_characteristic_raw(
464 &mut self,
465 module: &str,
466 name: &str,
467 ) -> Result<Vec<u64>, CalError> {
468 let characteristic = self.project.characteristic(module, name)?;
469 let len = upload_len(characteristic)?;
470 let data = self.transport.read(characteristic.address, len)?;
471 self.project.read_raw(characteristic, &data)
472 }
473
474 /// Write a physical value to a characteristic's first element, and read
475 /// it back to confirm the ECU latched it.
476 ///
477 /// The value is limit-checked and inverted through the COMPU_METHOD
478 /// before anything reaches the bus, so a rejected write costs no
479 /// traffic.
480 ///
481 /// # Errors
482 ///
483 /// [`CalError::LimitViolation`] for an out-of-limit value,
484 /// [`CalError::OutOfBounds`] when the deposit cannot represent it,
485 /// [`CalError::Transport`] on a bus failure or a read-back mismatch,
486 /// plus the lookup errors.
487 pub fn write_characteristic(
488 &mut self,
489 module: &str,
490 name: &str,
491 physical: f64,
492 ) -> Result<(), CalError> {
493 self.write_characteristic_element(module, name, 0, physical)
494 }
495
496 /// Write a physical value to one element of a characteristic and read
497 /// it back to confirm.
498 ///
499 /// # Errors
500 ///
501 /// As [`write_characteristic`](Self::write_characteristic).
502 pub fn write_characteristic_element(
503 &mut self,
504 module: &str,
505 name: &str,
506 index: usize,
507 physical: f64,
508 ) -> Result<(), CalError> {
509 let raw = self.project.to_raw(module, name, physical)?;
510 self.write_characteristic_raw(module, name, index, raw)?;
511 let confirm = self.read_characteristic_raw(module, name)?;
512 let latched = confirm.get(index).copied().unwrap_or(u64::MAX);
513 if latched != raw {
514 return Err(CalError::Transport(format!(
515 "write-back mismatch for `{}.{}` element {index}: wrote 0x{raw:X}, read 0x{latched:X}",
516 module, name
517 )));
518 }
519 Ok(())
520 }
521
522 /// Write a raw bit pattern to one element, without limit checking or
523 /// read-back — the path a snapshot restore takes, where the value was
524 /// already validated when it was captured.
525 ///
526 /// A multi-element deposit is read, one element replaced, and written
527 /// back whole: a calibration engineer adjusting curve point 3 must not
528 /// lose points 1, 2, and 4.
529 ///
530 /// # Errors
531 ///
532 /// [`CalError::OutOfBounds`] when `index` is past the end of the
533 /// deposit, [`CalError::Transport`] on a bus failure, plus the lookup
534 /// errors.
535 pub fn write_characteristic_raw(
536 &mut self,
537 module: &str,
538 name: &str,
539 index: usize,
540 raw: u64,
541 ) -> Result<(), CalError> {
542 let characteristic = self.project.characteristic(module, name)?;
543 let elements = characteristic.elements.max(1);
544 if index >= elements {
545 return Err(CalError::OutOfBounds {
546 name: qualified(module, name),
547 value: index as f64,
548 lower: 0.0,
549 upper: (elements - 1) as f64,
550 });
551 }
552 let mut raws = if characteristic.elements > 1 {
553 self.read_characteristic_raw(module, name)?
554 } else {
555 vec![0_u64; elements]
556 };
557 raws.resize(elements, 0);
558 if let Some(slot) = raws.get_mut(index) {
559 *slot = raw;
560 }
561 let data = self.project.write_raw(characteristic, &raws)?;
562 self.transport.write(characteristic.address, &data)
563 }
564
565 /// Read a measurement and return its physical value.
566 ///
567 /// # Errors
568 ///
569 /// [`CalError::Transport`] on a bus failure, [`CalError::Unsupported`]
570 /// for an unresolvable conversion, plus the lookup errors.
571 pub fn read_measurement(&mut self, module: &str, name: &str) -> Result<f64, CalError> {
572 let measurement = self.project.measurement(module, name)?;
573 let len = measurement.size_bytes();
574 if len == 0 || len > usize::from(u8::MAX) {
575 return Err(CalError::Unsupported {
576 subject: format!("measurement `{}.{}`", module, name),
577 reason: format!("{len}-byte measurement cannot be read in one UPLOAD"),
578 });
579 }
580 #[allow(clippy::cast_possible_truncation)]
581 let data = self.transport.read(measurement.address, len as u8)?;
582 let raw = decode_scalar(&data, measurement.is_signed());
583 let conversion = measurement.conversion.resolved(self.project.tables())?;
584 Ok(conversion.apply(raw))
585 }
586
587 /// Capture the named characteristics, searching every module for each
588 /// name (first declaration wins).
589 ///
590 /// The snapshot records the page it was taken on, so
591 /// [`restore`](Self::restore) puts the ECU back where it found it.
592 ///
593 /// # Errors
594 ///
595 /// As [`read_characteristic_raw`](Self::read_characteristic_raw), and
596 /// [`CalError::UnknownCharacteristic`] for a name no module declares.
597 pub fn snapshot(&mut self, names: &[&str]) -> Result<Snapshot, CalError> {
598 let mut entries = Vec::with_capacity(names.len());
599 for name in names {
600 let (module_name, characteristic) = self.project.locate(name)?;
601 let module = module_name.to_string();
602 let raws = self.read_characteristic_raw(module_name, name)?;
603 entries.push(SnapshotEntry {
604 module,
605 name: characteristic.name.clone(),
606 elements: self.snapshot_values(characteristic, &raws)?,
607 });
608 }
609 Ok(Snapshot {
610 page: self.page,
611 entries,
612 })
613 }
614
615 /// Capture every characteristic of one module.
616 ///
617 /// # Errors
618 ///
619 /// As [`snapshot`](Self::snapshot).
620 pub fn snapshot_module(&mut self, module: &str) -> Result<Snapshot, CalError> {
621 let declared = self.project.module(module)?;
622 let names: Vec<String> = declared.characteristic_names().map(String::from).collect();
623 let borrowed: Vec<&str> = names.iter().map(String::as_str).collect();
624 let mut snapshot = self.snapshot(&borrowed)?;
625 for entry in &mut snapshot.entries {
626 entry.module = module.to_string();
627 }
628 Ok(snapshot)
629 }
630
631 /// Restore a captured calibration set: switch to the snapshot's page,
632 /// then write every captured raw value back verbatim.
633 ///
634 /// Raws are written, not physical values, so a restore is bit-exact and
635 /// cannot drift through a second round of inversion.
636 ///
637 /// # Errors
638 ///
639 /// [`CalError::Transport`], [`CalError::UnknownModule`] /
640 /// [`CalError::UnknownCharacteristic`] when the project no longer
641 /// declares a captured parameter, plus the write errors.
642 pub fn restore(&mut self, snapshot: &Snapshot) -> Result<(), CalError> {
643 self.set_cal_page(snapshot.page)?;
644 for entry in &snapshot.entries {
645 let characteristic = self.project.characteristic(&entry.module, &entry.name)?;
646 let raws: Vec<u64> = entry.elements.iter().map(|v| v.raw).collect();
647 let data = self.project.write_raw(characteristic, &raws)?;
648 self.transport.write(characteristic.address, &data)?;
649 }
650 Ok(())
651 }
652
653 /// Diff this session's **baseline** snapshot against `other`, one entry
654 /// per element.
655 ///
656 /// `&self` cannot read the bus, so the "before" side is the baseline
657 /// installed by [`set_baseline`](Self::set_baseline) (or
658 /// [`capture_baseline`](Self::capture_baseline)). With no baseline set,
659 /// every parameter is reported as new. Use [`diff_snapshots`] to diff two
660 /// snapshots you already hold.
661 ///
662 /// `within_limits` is evaluated against the project's current A2L
663 /// limits, so a baseline captured before a limit was tightened is
664 /// reported against the limit that now applies.
665 #[must_use]
666 pub fn diff(&self, other: &Snapshot) -> Vec<CalibrationDelta> {
667 diff_snapshots(self.baseline.as_ref(), other, self.project)
668 }
669
670 /// Install the baseline every [`diff`](Self::diff) measures against.
671 pub fn set_baseline(&mut self, snapshot: Snapshot) {
672 self.baseline = Some(snapshot);
673 }
674
675 /// The installed baseline, when one is set.
676 #[must_use]
677 pub fn baseline(&self) -> Option<&Snapshot> {
678 self.baseline.as_ref()
679 }
680
681 /// Capture a baseline over every characteristic of every module and
682 /// install it.
683 ///
684 /// # Errors
685 ///
686 /// [`CalError::Transport`], [`CalError::UnknownModule`] /
687 /// [`CalError::UnknownCharacteristic`], [`CalError::Unsupported`] — as
688 /// [`snapshot`](Self::snapshot).
689 pub fn capture_baseline(&mut self) -> Result<(), CalError> {
690 let modules: Vec<String> = self.project.module_names().map(String::from).collect();
691 let mut entries = Vec::new();
692 let page = self.page;
693 for module in modules {
694 let mut snapshot = self.snapshot_module(&module)?;
695 entries.append(&mut snapshot.entries);
696 }
697 self.baseline = Some(Snapshot { page, entries });
698 Ok(())
699 }
700
701 /// Convert raws into snapshot values.
702 fn snapshot_values(
703 &self,
704 characteristic: &crate::model::Characteristic,
705 raws: &[u64],
706 ) -> Result<Vec<SnapshotValue>, CalError> {
707 let conversion = self.project.resolved_conversion(characteristic)?;
708 Ok(raws
709 .iter()
710 .map(|&raw| SnapshotValue {
711 raw,
712 physical: conversion.apply(characteristic.raw_value(raw)),
713 })
714 .collect())
715 }
716}
717
718impl fmt::Debug for CalibrationSession<'_> {
719 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
720 f.debug_struct("CalibrationSession")
721 .field("page", &self.page)
722 .field("resources", &self.resources.to_string())
723 .finish_non_exhaustive()
724 }
725}
726
727/// UPLOAD length for a characteristic's whole deposit record.
728///
729/// The record includes the bytes *before* `FNC_VALUES POSITION`, which the
730/// layout reserves for other members of the record — the same span
731/// [`CalibrationProject::write_raw`] produces, so a read and a write of the
732/// same characteristic are the same length on the wire.
733fn upload_len(characteristic: &crate::model::Characteristic) -> Result<u8, CalError> {
734 let size = usize::from(characteristic.deposit_position) + characteristic.size_bytes();
735 if size == 0 || size > usize::from(u8::MAX) {
736 return Err(CalError::Unsupported {
737 subject: format!("characteristic `{}`", characteristic.name),
738 reason: format!("deposit of {size} bytes cannot be read in one UPLOAD"),
739 });
740 }
741 #[allow(clippy::cast_possible_truncation)]
742 Ok(size as u8)
743}
744
745/// Decode one signed or unsigned integer from a measurement payload.
746fn decode_scalar(data: &[u8], is_signed: bool) -> f64 {
747 let mut value = 0_u64;
748 for (index, &byte) in data.iter().enumerate() {
749 value |= u64::from(byte) << (index * 8);
750 }
751 let bits = u32::try_from(data.len() * 8).unwrap_or(32);
752 if is_signed && bits > 0 && bits < 64 && value & (1_u64 << (bits - 1)) != 0 {
753 #[allow(clippy::cast_possible_wrap)]
754 let extended = (value | (u64::MAX << bits)) as i64;
755 extended as f64
756 } else {
757 #[allow(clippy::cast_precision_loss)]
758 {
759 value as f64
760 }
761 }
762}
763
764/// `name` for a single element, `name[index]` for a multi-element one.
765fn element_name(name: &str, elements: usize, index: usize) -> String {
766 if elements <= 1 {
767 name.to_string()
768 } else {
769 format!("{name}[{index}]")
770 }
771}
772
773/// `module.name`.
774fn qualified(module: &str, name: &str) -> String {
775 format!("{module}.{name}")
776}