From c8c4199c5ca534155c4d31dc6fe5987f870b6de0 Mon Sep 17 00:00:00 2001 From: BobBot Date: Thu, 12 Nov 2026 23:36:32 +0000 Subject: [PATCH] =?UTF-8?q?feat(ecs):=20slice=202=20=E2=80=94=20Mattonella?= =?UTF-8?q?State=20register=20image=20+=20Mattonella=20model?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - state.rs: ports of mattonella_state.py (569 L), _dac_setting.py and the RegisterField byte plumbing — full 0x6C register image (64 pixel bytes, globals 0x40-0x4B, pairwise finetune-DAC nibbles 0x4C-0x6B) with exact range checks and enum parsing (ChannelMode, CalibrationTime) - mattonella.rs: port of mattonella.py (426 L) — DACInterface (enable bit 7 + 7-bit value RMW), 20 class-level descriptors, pixel batch ops (power/frontend/adj/ctrl/mask/ftdac), calibrate, full-state read/write - 9 integration tests; verified from_bytes(to_bytes(s)) == s round-trip - fake data_server moved to tests/common and fixed to advance the subaddress on multi-byte reads/writes (consecutive registers) - divergences D1-D5 documented in docs/porting-notes.md - workspace: 30 tests green --- MEMORY.md | 1 + README.md | 11 +- crates/innesco-ecs/src/lib.rs | 7 + crates/innesco-ecs/src/mattonella.rs | 390 ++++++++++++++++++ crates/innesco-ecs/src/state.rs | 408 +++++++++++++++++++ crates/innesco-ecs/tests/common/mod.rs | 106 +++++ crates/innesco-ecs/tests/ecs_tests.rs | 99 +---- crates/innesco-ecs/tests/mattonella_tests.rs | 284 +++++++++++++ docs/porting-notes.md | 21 + 9 files changed, 1227 insertions(+), 100 deletions(-) create mode 100644 crates/innesco-ecs/src/mattonella.rs create mode 100644 crates/innesco-ecs/src/state.rs create mode 100644 crates/innesco-ecs/tests/common/mod.rs create mode 100644 crates/innesco-ecs/tests/mattonella_tests.rs diff --git a/MEMORY.md b/MEMORY.md index 22d028f..bcd5d12 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -10,3 +10,4 @@ - 2026-11-12: initial port, golden tests green, pushed to Gitea main. - 2026-11-12: arm64 musl build verified (static, AArch64); craft-anything-cli installed. - 2026-11-12: slice 1 of OP3 (innesco-ecs: _fields/board/pixel) — 21 tests green; 2 faithful-port findings (enum non-round-trip, crystal hi/lo aliasing). Decisions: polars-rs + S3 crucial (OP1), CI deprioritized. Reminder cron 2026-11-18 09:00 for raw frames. +- 2026-11-12: slice 2 of OP3 (mattonella_state + mattonella + _dac_setting) — 30 tests green; state round-trip verified; divergences D1-D5 documented. diff --git a/README.md b/README.md index d9b079b..4decb36 100644 --- a/README.md +++ b/README.md @@ -66,13 +66,18 @@ skip-and-count instead of abort on malformed packets). Port: axum + tokio in a separate crate with feature flag (library stays dependency-free). `/state` and `/daq` depend on #3; the other four can be ported independently. -3. **Board/slow-control model** — **IN PROGRESS, slice 1 done**: +3. **Board/slow-control model** — **IN PROGRESS, slices 1-2 done**: - ✅ slice 1: `_fields.py` (199 L) + `board.py` (89) + `pixel.py` (77) → `crates/innesco-ecs` (7 integration tests against a fake data_server, incl. RMW semantics and the crystal-config sequencer; two faithful-port findings documented in docs/porting-notes.md #7/#8). - - next: (2) mattonella(+state) 995 L → (3) asic_state 626 → (4) quadrant 502 - → (5) daq+DataProcessor 574. Mirror-1:1 first, type-state validation later. + - ✅ slice 2: `mattonella_state.py` (569 L) + `mattonella.py` (426 L) + + `_dac_setting.py` → `state.rs` (full 0x6C-byte register image with + exact `RegisterField` serialization) + `mattonella.rs` (`DACInterface`, + 20 mattonella descriptors, pixel batch ops, calibration, full-state + I/O). 9 more tests; verified round-trip `from_bytes(to_bytes(s)) == s`. + - next: (3) asic_state 626 L → (4) quadrant 502 L → (5) daq+DataProcessor + 574 L. Mirror-1:1 first, type-state validation later. 4. **Real-board validation**: no qemu here, no network to the boards. (a) *A raw frame dump from a real acquisition* (even small) → decoder validated on physical data as an official golden test — **highest value, diff --git a/crates/innesco-ecs/src/lib.rs b/crates/innesco-ecs/src/lib.rs index e98e35a..79e9569 100644 --- a/crates/innesco-ecs/src/lib.rs +++ b/crates/innesco-ecs/src/lib.rs @@ -15,8 +15,15 @@ mod board; mod fields; +mod mattonella; mod pixel; +mod state; pub use board::Board; pub use fields::{FieldAddress, FieldContext, FieldError, I2cField, Kind}; +pub use mattonella::{DACInterface, Mattonella, TEST_MODES}; pub use pixel::Pixel; +pub use state::{ + CalibrationTime, ChannelMode, DACSetting, MattonellaState, PixelState, StateError, + MATTONELLA_STATE_BYTES_LENGTH, N_PIXELS, +}; diff --git a/crates/innesco-ecs/src/mattonella.rs b/crates/innesco-ecs/src/mattonella.rs new file mode 100644 index 0000000..ca66950 --- /dev/null +++ b/crates/innesco-ecs/src/mattonella.rs @@ -0,0 +1,390 @@ +//! Rust port of `innesco/ecs/mattonella.py` — mattonella-level registers, +//! the DAC interface, pixel batch operations, calibration and full-state I/O. +//! +//! The Python class-level descriptors (address bound to the instance's +//! `_mattonella_id` via `from_attribute`) become associated consts built on +//! `FieldAddress::MattonellaId`, resolved with [`Mattonella::ctx`]. + +use innesco_protocol::{Connection, Request}; + +use crate::fields::{FieldAddress, FieldContext, FieldError, I2cField}; +use crate::pixel::Pixel; +use crate::state::{MattonellaState, MATTONELLA_STATE_BYTES_LENGTH, N_PIXELS}; + +/// Enum table shared by `test1_mode` / `test2_mode` (mattonella.py). +pub const TEST_MODES: &[(u8, &str)] = &[ + (0x00, "DAQ TMR GPO"), + (0x40, "DAQ HIT-OR"), + (0x80, "TDC Pulse"), + (0xC0, "ATP Pulse"), +]; + +/// One of the six per-mattonella DACs (Python `DACInterface`): `enable` is +/// bit 7, `value` the low 7 bits of the same register byte. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DACInterface { + pub address: u8, + pub subaddress: u8, + pub description: &'static str, +} + +impl DACInterface { + fn enable_field(&self) -> I2cField { + I2cField::bool_( + FieldAddress::Fixed(self.address), + Some(FieldAddress::Fixed(self.subaddress)), + 0x80, + ) + } + + fn value_field(&self) -> I2cField { + I2cField::int( + FieldAddress::Fixed(self.address), + Some(FieldAddress::Fixed(self.subaddress)), + 0, + 0x7F, + ) + } + + /// DAC enable (bit 7). Read-modify-write preserves the 7-bit value. + pub fn read_enable(&self, conn: &mut Connection) -> Result { + self.enable_field().read_bool(conn, FieldContext::default()) + } + + pub fn set_enable(&self, conn: &mut Connection, on: bool) -> Result<(), FieldError> { + self.enable_field().write_bool(conn, FieldContext::default(), on) + } + + /// DAC value (bits 6–0). Read-modify-write preserves the enable bit. + pub fn read_value(&self, conn: &mut Connection) -> Result { + self.value_field().read_int(conn, FieldContext::default()) + } + + pub fn set_value(&self, conn: &mut Connection, value: u8) -> Result<(), FieldError> { + self.value_field().write_int(conn, FieldContext::default(), value) + } +} + +/// One mattonella: per-instance registers at `address = mattonella_id` +/// (subaddresses 0x40–0x70), 64 [`Pixel`]s and six [`DACInterface`]s. +pub struct Mattonella { + pub mattonella_id: u8, + pub pixels: Vec, + pub dac_vth_high: DACInterface, + pub dac_vth_low: DACInterface, + pub dac_vinj_high: DACInterface, + pub dac_vinj_low: DACInterface, + pub dac_vldo: DACInterface, + pub dac_vfb: DACInterface, +} + +impl Mattonella { + /// Global TDC enable (0x40, bit 6). + pub const TDC_ENABLE: I2cField = + I2cField::bool_(FieldAddress::MattonellaId, Some(FieldAddress::Fixed(0x40)), 0x40); + /// Global TOT enable (0x40, bit 5). + pub const TOT_ENABLE: I2cField = + I2cField::bool_(FieldAddress::MattonellaId, Some(FieldAddress::Fixed(0x40)), 0x20); + /// Test mode 1 (0x41, bits 7–6). + pub const TEST1_MODE: I2cField = + I2cField::enum_(FieldAddress::MattonellaId, Some(FieldAddress::Fixed(0x41)), 0xC0, TEST_MODES); + /// Target of the pixel for test slot 1 (0x41, bits 5–0). + pub const TEST1_TARGET: I2cField = + I2cField::int(FieldAddress::MattonellaId, Some(FieldAddress::Fixed(0x41)), 0, 0x3F); + /// Test mode 2 (0x42, bits 7–6). + pub const TEST2_MODE: I2cField = + I2cField::enum_(FieldAddress::MattonellaId, Some(FieldAddress::Fixed(0x42)), 0xC0, TEST_MODES); + /// Target of the pixel for test slot 2 (0x42, bits 5–0). + pub const TEST2_TARGET: I2cField = + I2cField::int(FieldAddress::MattonellaId, Some(FieldAddress::Fixed(0x42)), 0, 0x3F); + /// 0x43 bit 7 (only one pixel at a time!). + pub const CONNECT_TO_PAD: I2cField = + I2cField::bool_(FieldAddress::MattonellaId, Some(FieldAddress::Fixed(0x43)), 0x80); + /// 0x43 bit 6 (only one pixel at a time!). + pub const ENABLE_V_THRESHOLD: I2cField = + I2cField::bool_(FieldAddress::MattonellaId, Some(FieldAddress::Fixed(0x43)), 0x40); + /// 0x43 bit 5 (only one pixel at a time!). + pub const ENABLE_V_LDO: I2cField = + I2cField::bool_(FieldAddress::MattonellaId, Some(FieldAddress::Fixed(0x43)), 0x20); + /// 0x43 bit 4 (only one pixel at a time!). + pub const ENABLE_V_FEEDBACK: I2cField = + I2cField::bool_(FieldAddress::MattonellaId, Some(FieldAddress::Fixed(0x43)), 0x10); + /// 0x43 bit 3 (pixel reset at each timestamp rollover). + pub const TIMEOUT_ENABLE: I2cField = + I2cField::bool_(FieldAddress::MattonellaId, Some(FieldAddress::Fixed(0x43)), 0x08); + /// 0x43 bit 2. + pub const CALIBRATION_ENABLE: I2cField = + I2cField::bool_(FieldAddress::MattonellaId, Some(FieldAddress::Fixed(0x43)), 0x04); + /// 0x43 bits 1–0 (global calibration time). + pub const CALIBRATION_TIME: I2cField = + I2cField::int(FieldAddress::MattonellaId, Some(FieldAddress::Fixed(0x43)), 0, 0x03); + /// 0x44 bit 7. + pub const AFE_LOOPBACK_ENABLE: I2cField = + I2cField::bool_(FieldAddress::MattonellaId, Some(FieldAddress::Fixed(0x44)), 0x80); + /// 0x44 bit 6. + pub const AFE_AUTO_ENABLE: I2cField = + I2cField::bool_(FieldAddress::MattonellaId, Some(FieldAddress::Fixed(0x44)), 0x40); + /// 0x44 bits 5–3 (Lorenzo's AFEs). + pub const DAC_IDISC: I2cField = + I2cField::int(FieldAddress::MattonellaId, Some(FieldAddress::Fixed(0x44)), 3, 0x07); + /// 0x44 bits 2–0 (Lorenzo's AFEs). + pub const DAC_ICSA: I2cField = + I2cField::int(FieldAddress::MattonellaId, Some(FieldAddress::Fixed(0x44)), 0, 0x07); + /// 0x45 bit 7. + pub const EXTERNAL_DAC_ENABLE: I2cField = + I2cField::bool_(FieldAddress::MattonellaId, Some(FieldAddress::Fixed(0x45)), 0x80); + /// 0x45 bit 6. + pub const V_INJ_ENABLE: I2cField = + I2cField::bool_(FieldAddress::MattonellaId, Some(FieldAddress::Fixed(0x45)), 0x40); + /// 0x45 bits 5–4. + pub const V_INJ_MUX: I2cField = + I2cField::int(FieldAddress::MattonellaId, Some(FieldAddress::Fixed(0x45)), 4, 0x03); + /// 0x45 bits 3–0 (Lorenzo's AFEs). + pub const DAC_KRUM: I2cField = + I2cField::int(FieldAddress::MattonellaId, Some(FieldAddress::Fixed(0x45)), 0, 0x0F); + + pub fn new(mattonella_id: u8) -> Self { + Mattonella { + mattonella_id, + pixels: (0..N_PIXELS as u8) + .map(|pixel_id| Pixel::new(mattonella_id, pixel_id)) + .collect(), + dac_vth_high: DACInterface { + address: mattonella_id, + subaddress: 0x46, + description: "DAC Vth high", + }, + dac_vth_low: DACInterface { + address: mattonella_id, + subaddress: 0x47, + description: "DAC Vth low", + }, + dac_vinj_high: DACInterface { + address: mattonella_id, + subaddress: 0x48, + description: "DAC Vinj high", + }, + dac_vinj_low: DACInterface { + address: mattonella_id, + subaddress: 0x49, + description: "DAC Vinj low", + }, + dac_vldo: DACInterface { + address: mattonella_id, + subaddress: 0x4A, + description: "DAC Vldo", + }, + dac_vfb: DACInterface { + address: mattonella_id, + subaddress: 0x4B, + description: "DAC Vfb", + }, + } + } + + /// Python `id` property. + pub const fn id(&self) -> u8 { + self.mattonella_id + } + + /// `FieldContext` resolving the class-level descriptors to this board. + pub const fn ctx(&self) -> FieldContext { + FieldContext { mattonella_id: self.mattonella_id, pixel_id: 0 } + } + + fn read_pixels(&self, conn: &mut Connection) -> Result, FieldError> { + let resp = conn.send(&Request::ReadSub { + address: self.mattonella_id, + subaddress: 0x00, + length: N_PIXELS as u16, + })?; + if resp.is_error() { + return Err(FieldError::Server { status: resp.status, message: resp.message() }); + } + Ok(resp.i2c_data().to_vec()) + } + + fn write_pixels(&self, conn: &mut Connection, payload: Vec) -> Result<(), FieldError> { + let resp = conn.send(&Request::WriteSub { + address: self.mattonella_id, + subaddress: 0x00, + payload, + })?; + if resp.is_error() { + return Err(FieldError::Server { status: resp.status, message: resp.message() }); + } + Ok(()) + } + + /// `set_pixel_power`: read all 64 pixel bytes, set/clear the power bit + /// (0x40) of each, write back. + pub fn set_pixel_power(&self, conn: &mut Connection, on: bool) -> Result<(), FieldError> { + let current = self.read_pixels(conn)?; + let payload = current + .iter() + .map(|cs| if on { 0x40 | cs } else { cs & !0x40 }) + .collect(); + self.write_pixels(conn, payload) + } + + /// `set_pixel_frontend`: same, for the frontend bit (0x80). + pub fn set_pixel_frontend(&self, conn: &mut Connection, on: bool) -> Result<(), FieldError> { + let current = self.read_pixels(conn)?; + let payload = current + .iter() + .map(|cs| if on { 0x80 | cs } else { cs & !0x80 }) + .collect(); + self.write_pixels(conn, payload) + } + + /// `set_pixel_adj`: adjustment (bits 5–4) of every pixel, 0–3. + pub fn set_pixel_adj(&self, conn: &mut Connection, value: u8) -> Result<(), FieldError> { + if value > 3 { + return Err(FieldError::InvalidValue { + value: value.to_string(), + reason: "out of valid range 0-3".into(), + }); + } + let current = self.read_pixels(conn)?; + let payload = current + .iter() + .map(|cs| (0x30 & (value << 4)) | (cs & !0x30)) + .collect(); + self.write_pixels(conn, payload) + } + + /// `set_pixel_ctrl`: control value (bits 3–0) of every pixel, 0–15. + pub fn set_pixel_ctrl(&self, conn: &mut Connection, value: u8) -> Result<(), FieldError> { + if value > 0x0F { + return Err(FieldError::InvalidValue { + value: value.to_string(), + reason: "out of valid range 0-15".into(), + }); + } + let current = self.read_pixels(conn)?; + let payload = current + .iter() + .map(|cs| (0x0F & value) | (cs & !0x0F)) + .collect(); + self.write_pixels(conn, payload) + } + + /// `set_pixel_mask`: direct write (no RMW) of 64 pixel bytes computed + /// from the mask; defaults `frontend_on=true, adj=1, ctrl=0`. + pub fn set_pixel_mask( + &self, + conn: &mut Connection, + pixel_mask: &[bool], + frontend_on: bool, + adj_value: u8, + ctrl_value: u8, + ) -> Result<(), FieldError> { + if pixel_mask.len() != N_PIXELS { + return Err(FieldError::InvalidValue { + value: pixel_mask.len().to_string(), + reason: "pixel mask length is not equal to 64".into(), + }); + } + if adj_value > 3 { + return Err(FieldError::InvalidValue { + value: adj_value.to_string(), + reason: "out of valid range 0-3".into(), + }); + } + if ctrl_value > 0x0F { + return Err(FieldError::InvalidValue { + value: ctrl_value.to_string(), + reason: "out of valid range 0-15".into(), + }); + } + let payload = pixel_mask + .iter() + .map(|power_on| { + ((frontend_on as u8) << 7) | ((*power_on as u8) << 6) | (adj_value << 4) | ctrl_value + }) + .collect(); + self.write_pixels(conn, payload) + } + + /// `set_pixel_ftdac`: 64 nibble values (0–15) packed pairwise into the + /// 32 registers at subaddress 0x4C (even pixel = low nibble). + pub fn set_pixel_ftdac(&self, conn: &mut Connection, values: &[u8]) -> Result<(), FieldError> { + if values.len() != N_PIXELS { + return Err(FieldError::InvalidValue { + value: values.len().to_string(), + reason: "values list must contain exactly 64 elements".into(), + }); + } + if let Some(bad) = values.iter().find(|v| **v > 0x0F) { + return Err(FieldError::InvalidValue { + value: bad.to_string(), + reason: "finetune DAC value out of valid range 0-15".into(), + }); + } + let payload: Vec = (0..N_PIXELS / 2) + .map(|i| (values[2 * i] & 0x0F) | ((values[2 * i + 1] & 0x0F) << 4)) + .collect(); + let resp = conn.send(&Request::WriteSub { + address: self.mattonella_id, + subaddress: 0x4C, + payload, + })?; + if resp.is_error() { + return Err(FieldError::Server { status: resp.status, message: resp.message() }); + } + Ok(()) + } + + /// `calibrate`: `((dco & 0x01) << 4) | (1 << pixel_group)` at sub 0x70. + pub fn calibrate(&self, conn: &mut Connection, dco: u8, pixel_group: u8) -> Result<(), FieldError> { + if dco > 1 { + return Err(FieldError::InvalidValue { + value: dco.to_string(), + reason: "out of valid range 0-1".into(), + }); + } + if pixel_group > 3 { + return Err(FieldError::InvalidValue { + value: pixel_group.to_string(), + reason: "out of valid range 0-3".into(), + }); + } + let resp = conn.send(&Request::WriteSub { + address: self.mattonella_id, + subaddress: 0x70, + payload: vec![((dco & 0x01) << 4) | (1 << pixel_group)], + })?; + if resp.is_error() { + return Err(FieldError::Server { status: resp.status, message: resp.message() }); + } + Ok(()) + } + + /// `read`: full 0x6C-byte register image → `MattonellaState` (Python + /// raises `IOError` on a non-zero I2C status; here `FieldError::Server`). + pub fn read(&self, conn: &mut Connection) -> Result { + let resp = conn.send(&Request::ReadSub { + address: self.mattonella_id, + subaddress: 0x00, + length: MATTONELLA_STATE_BYTES_LENGTH as u16, + })?; + if resp.is_error() { + return Err(FieldError::Server { status: resp.status, message: resp.message() }); + } + Ok(MattonellaState::from_bytes(resp.i2c_data())?) + } + + /// `write`: serialize the state and write all 0x6C bytes at sub 0x00. + pub fn write(&self, conn: &mut Connection, state: &MattonellaState) -> Result<(), FieldError> { + let payload = state.to_bytes()?; + let resp = conn.send(&Request::WriteSub { + address: self.mattonella_id, + subaddress: 0x00, + payload: payload.to_vec(), + })?; + if resp.is_error() { + return Err(FieldError::Server { status: resp.status, message: resp.message() }); + } + Ok(()) + } +} diff --git a/crates/innesco-ecs/src/state.rs b/crates/innesco-ecs/src/state.rs new file mode 100644 index 0000000..2033857 --- /dev/null +++ b/crates/innesco-ecs/src/state.rs @@ -0,0 +1,408 @@ +//! Rust port of `innesco/ecs/mattonella_state.py` (+ `_dac_setting.py`). +//! +//! `MattonellaState` is the full `0x6C`-byte register image of a mattonella: +//! 64 pixel bytes (subaddresses 0x00–0x3F), the global registers +//! (0x40–0x4B) and the per-pixel finetune-DAC nibbles (0x4C–0x6B). +//! Serialization mirrors the Python `RegisterField.update_bytes` / +//! `from_bytes` plumbing of `_register_field.py` exactly: values are +//! range-checked against `n_bits` (Python `InvalidRange`) and applied as +//! `byte = (byte & ~mask) | ((value << shift) & mask)`. + +use crate::fields::FieldError; + +/// Errors from state serialization (Python `ValueError` / `InvalidRange`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StateError { + /// Wrong buffer length (`MattonellaState::from_bytes`). + Length { got: usize, expected: usize }, + /// Value out of range for its field (`RegisterField` `InvalidRange`). + OutOfRange { value: u32, n_bits: u32, field: &'static str }, + /// Raw code not a member of `ChannelMode` / `CalibrationTime`. + InvalidEnum { raw: u8, field: &'static str }, +} + +impl std::fmt::Display for StateError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + StateError::Length { got, expected } => { + write!(f, "data length {got} does not match expected length {expected} for MattonellaState") + } + StateError::OutOfRange { value, n_bits, field } => { + write!(f, "value {value} out of range for field with {n_bits} bits ({field})") + } + StateError::InvalidEnum { raw, field } => { + write!(f, "value {raw} is not a valid {field} enum member") + } + } + } +} + +impl std::error::Error for StateError {} + +impl From for FieldError { + fn from(e: StateError) -> Self { + match e { + StateError::Length { got, expected } => FieldError::InvalidValue { + value: format!("{got} bytes"), + reason: format!("does not match expected length {expected} for MattonellaState"), + }, + StateError::OutOfRange { value, n_bits, field } => FieldError::InvalidValue { + value: value.to_string(), + reason: format!("out of range for field with {n_bits} bits ({field})"), + }, + StateError::InvalidEnum { raw, field } => FieldError::InvalidValue { + value: raw.to_string(), + reason: format!("not a valid {field} enum member"), + }, + } + } +} + +/// Total register-image length (`MATTONELLA_STATE_BYTES_LENGTH = 0x6C`). +pub const MATTONELLA_STATE_BYTES_LENGTH: usize = 0x6C; +/// Pixels per mattonella. +pub const N_PIXELS: usize = 64; + +/// `DACSetting` (`_dac_setting.py`): enable bit (0x80) + 7-bit value packed +/// into one register byte. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DACSetting { + pub enable: bool, + pub value: u8, +} + +impl DACSetting { + pub const fn new(enable: bool, value: u8) -> Self { + DACSetting { enable, value } + } + + /// `raw_value` getter: 0–127 range check (Python raises `ValueError`), + /// then `0x80 | value`. + pub fn raw_value(&self) -> Result { + if self.value > 0x7F { + return Err(StateError::OutOfRange { + value: self.value as u32, + n_bits: 7, + field: "DACSetting.value", + }); + } + Ok(if self.enable { 0x80 } else { 0x00 } | self.value) + } + + /// `raw_value` setter. + pub const fn from_raw(raw: u8) -> Self { + DACSetting { enable: raw & 0x80 != 0, value: raw & 0x7F } + } +} + +impl Default for DACSetting { + fn default() -> Self { + DACSetting { enable: false, value: 64 } + } +} + +/// `ChannelMode` (IntEnum in `mattonella_state.py`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum ChannelMode { + TestDaqTmrGpo = 0, + TestDaqHitor = 1, + TestTdcPulse = 2, + TestAtpPulse = 3, +} + +/// `CalibrationTime` (IntEnum in `mattonella_state.py`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum CalibrationTime { + Cal400Ns = 0, + Cal800Ns = 1, + Cal1600Ns = 2, + Cal3200Ns = 3, +} + +fn channel_mode(raw: u8, field: &'static str) -> Result { + match raw { + 0 => Ok(ChannelMode::TestDaqTmrGpo), + 1 => Ok(ChannelMode::TestDaqHitor), + 2 => Ok(ChannelMode::TestTdcPulse), + 3 => Ok(ChannelMode::TestAtpPulse), + other => Err(StateError::InvalidEnum { raw: other, field }), + } +} + +fn calibration_time(raw: u8, field: &'static str) -> Result { + match raw { + 0 => Ok(CalibrationTime::Cal400Ns), + 1 => Ok(CalibrationTime::Cal800Ns), + 2 => Ok(CalibrationTime::Cal1600Ns), + 3 => Ok(CalibrationTime::Cal3200Ns), + other => Err(StateError::InvalidEnum { raw: other, field }), + } +} + +/// `PixelState`: the four register bits of one pixel plus its finetune-DAC +/// nibble. Defaults mirror the Python dataclass (adj=1, ctrl=15, ftdac=7). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PixelState { + pub frontend: bool, + pub power: bool, + pub adj: u8, + pub ctrl: u8, + pub finetune_dac: u8, +} + +impl Default for PixelState { + fn default() -> Self { + PixelState { frontend: false, power: false, adj: 1, ctrl: 15, finetune_dac: 7 } + } +} + +impl PixelState { + /// Serialize into the register image (Python `PixelState.update_bytes`). + pub fn update_bytes(&self, ret: &mut [u8], pixel_id: usize) -> Result<(), StateError> { + apply(ret, pixel_id, 1, 7, self.frontend as u32, "pixel.frontend")?; + apply(ret, pixel_id, 1, 6, self.power as u32, "pixel.power")?; + apply(ret, pixel_id, 2, 4, self.adj as u32, "pixel.adj")?; + apply(ret, pixel_id, 4, 0, self.ctrl as u32, "pixel.ctrl")?; + let shift = if pixel_id % 2 == 0 { 0 } else { 4 }; + apply(ret, 0x4C + pixel_id / 2, 4, shift, self.finetune_dac as u32, "pixel.finetune_dac") + } + + /// Parse one pixel out of the register image (Python `from_bytes`). + pub fn from_bytes(data: &[u8], pixel_id: usize) -> Self { + let shift = if pixel_id % 2 == 0 { 0 } else { 4 }; + PixelState { + frontend: extract(data, pixel_id, 1, 7) != 0, + power: extract(data, pixel_id, 1, 6) != 0, + adj: extract(data, pixel_id, 2, 4), + ctrl: extract(data, pixel_id, 4, 0), + finetune_dac: extract(data, 0x4C + pixel_id / 2, 4, shift), + } + } +} + +/// Full mattonella register image (Python `MattonellaState`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MattonellaState { + pub pixels: [PixelState; N_PIXELS], + /// 0x40 bits 3–0: global DCO0 fine control. + pub global_ctrl: u8, + /// 0x40 bits 5–4: global DCO0 coarse adjustment. + pub global_adj: u8, + /// 0x40 bit 6. + pub enable_tdc: bool, + /// 0x40 bit 7 (TDC double-edge counting). + pub enable_de_tdc: bool, + /// 0x41 bits 5–0: test injection target (first slot). + pub injection_target_0: u8, + /// 0x41 bits 7–6: test injection mode (first slot). + pub injection_mode_0: ChannelMode, + /// 0x42 bits 5–0: test injection target (second slot). + pub injection_target_1: u8, + /// 0x42 bits 7–6: test injection mode (second slot). + pub injection_mode_1: ChannelMode, + /// 0x43 bits 1–0. + pub calibration_time: CalibrationTime, + /// 0x43 bit 2. + pub calibration_enable: bool, + /// 0x43 bit 3 (pixel reset at timestamp rollover). + pub enable_timeout: bool, + /// 0x43 bit 4. + pub enable_vfb: bool, + /// 0x43 bit 5. + pub enable_vldo: bool, + /// 0x43 bit 6. + pub enable_vth: bool, + /// 0x43 bit 7 (connect mattonella to the pad). + pub connect_to_pad: bool, + /// 0x44 bits 2–0 (Lorenzo's AFEs). + pub dac_icsa: u8, + /// 0x44 bits 5–3 (Lorenzo's AFEs). + pub dac_idisc: u8, + /// 0x44 bit 6. + pub enable_afe_auto: bool, + /// 0x44 bit 7. + pub enable_afe_loopback: bool, + /// 0x45 bits 3–0 (Lorenzo's AFEs). + pub dac_i_krum: u8, + /// 0x45 bits 5–4. + pub v_inj_mux: u8, + /// 0x45 bit 6. + pub enable_v_inj: bool, + /// 0x45 bit 7 (voltages set by external DACs). + pub external_dac: bool, + /// 0x46 — defaults to `DACSetting { enable: true, value: 90 }`. + pub dac_vth_high: DACSetting, + /// 0x47 — defaults to `DACSetting { enable: true, value: 40 }`. + pub dac_vth_low: DACSetting, + /// 0x48 — defaults to `DACSetting { enable: true, value: 33 }`. + pub dac_vinj_high: DACSetting, + /// 0x49 — defaults to `DACSetting { enable: true, value: 0 }`. + pub dac_vinj_low: DACSetting, + /// 0x4A — defaults to `DACSetting { enable: true, value: 70 }`. + pub dac_vldo: DACSetting, + /// 0x4B — defaults to `DACSetting { enable: true, value: 90 }`. + pub dac_vfb: DACSetting, +} + +impl Default for MattonellaState { + fn default() -> Self { + MattonellaState { + pixels: [PixelState::default(); N_PIXELS], + global_ctrl: 13, + global_adj: 1, + enable_tdc: false, + enable_de_tdc: false, + injection_target_0: 0, + injection_mode_0: ChannelMode::TestDaqTmrGpo, + injection_target_1: 0, + injection_mode_1: ChannelMode::TestDaqTmrGpo, + calibration_time: CalibrationTime::Cal400Ns, + calibration_enable: false, + enable_timeout: false, + enable_vfb: true, + enable_vldo: true, + enable_vth: true, + connect_to_pad: false, + dac_icsa: 7, + dac_idisc: 7, + enable_afe_auto: false, + enable_afe_loopback: false, + dac_i_krum: 10, + v_inj_mux: 0, + enable_v_inj: false, + external_dac: false, + dac_vth_high: DACSetting::new(true, 90), + dac_vth_low: DACSetting::new(true, 40), + dac_vinj_high: DACSetting::new(true, 33), + dac_vinj_low: DACSetting::new(true, 0), + dac_vldo: DACSetting::new(true, 70), + dac_vfb: DACSetting::new(true, 90), + } + } +} + +impl MattonellaState { + /// Serialize the full register image (Python `to_bytes`): starts from a + /// zeroed buffer and applies every field, pixels first. + pub fn to_bytes(&self) -> Result<[u8; MATTONELLA_STATE_BYTES_LENGTH], StateError> { + let mut ret = [0u8; MATTONELLA_STATE_BYTES_LENGTH]; + + for (i, pixel) in self.pixels.iter().enumerate() { + pixel.update_bytes(&mut ret, i)?; + } + + apply(&mut ret, 0x40, 4, 0, self.global_ctrl as u32, "global_ctrl")?; + apply(&mut ret, 0x40, 2, 4, self.global_adj as u32, "global_adj")?; + apply(&mut ret, 0x40, 1, 6, self.enable_tdc as u32, "enable_tdc")?; + apply(&mut ret, 0x40, 1, 7, self.enable_de_tdc as u32, "enable_de_tdc")?; + apply(&mut ret, 0x41, 6, 0, self.injection_target_0 as u32, "injection_target_0")?; + apply(&mut ret, 0x41, 2, 6, self.injection_mode_0 as u8 as u32, "injection_mode_0")?; + apply(&mut ret, 0x42, 6, 0, self.injection_target_1 as u32, "injection_target_1")?; + apply(&mut ret, 0x42, 2, 6, self.injection_mode_1 as u8 as u32, "injection_mode_1")?; + apply(&mut ret, 0x43, 2, 0, self.calibration_time as u8 as u32, "calibration_time")?; + apply(&mut ret, 0x43, 1, 2, self.calibration_enable as u32, "calibration_enable")?; + apply(&mut ret, 0x43, 1, 3, self.enable_timeout as u32, "enable_timeout")?; + apply(&mut ret, 0x43, 1, 4, self.enable_vfb as u32, "enable_vfb")?; + apply(&mut ret, 0x43, 1, 5, self.enable_vldo as u32, "enable_vldo")?; + apply(&mut ret, 0x43, 1, 6, self.enable_vth as u32, "enable_vth")?; + apply(&mut ret, 0x43, 1, 7, self.connect_to_pad as u32, "connect_to_pad")?; + apply(&mut ret, 0x44, 3, 0, self.dac_icsa as u32, "dac_icsa")?; + apply(&mut ret, 0x44, 3, 3, self.dac_idisc as u32, "dac_idisc")?; + apply(&mut ret, 0x44, 1, 6, self.enable_afe_auto as u32, "enable_afe_auto")?; + apply(&mut ret, 0x44, 1, 7, self.enable_afe_loopback as u32, "enable_afe_loopback")?; + apply(&mut ret, 0x45, 4, 0, self.dac_i_krum as u32, "dac_i_krum")?; + apply(&mut ret, 0x45, 2, 4, self.v_inj_mux as u32, "v_inj_mux")?; + apply(&mut ret, 0x45, 1, 6, self.enable_v_inj as u32, "enable_v_inj")?; + apply(&mut ret, 0x45, 1, 7, self.external_dac as u32, "external_dac")?; + + // DACSetting fields serialize through their raw byte (n_bits = 8). + for (sub, dac, name) in [ + (0x46, self.dac_vth_high, "dac_vth_high"), + (0x47, self.dac_vth_low, "dac_vth_low"), + (0x48, self.dac_vinj_high, "dac_vinj_high"), + (0x49, self.dac_vinj_low, "dac_vinj_low"), + (0x4A, self.dac_vldo, "dac_vldo"), + (0x4B, self.dac_vfb, "dac_vfb"), + ] { + apply(&mut ret, sub, 8, 0, dac.raw_value()? as u32, name)?; + } + + Ok(ret) + } + + /// Parse a full register image (Python `from_bytes`): the length must be + /// exactly `MATTONELLA_STATE_BYTES_LENGTH`; every field is extracted from + /// the buffer, enum codes must be valid members. + pub fn from_bytes(data: &[u8]) -> Result { + if data.len() != MATTONELLA_STATE_BYTES_LENGTH { + return Err(StateError::Length { + got: data.len(), + expected: MATTONELLA_STATE_BYTES_LENGTH, + }); + } + + let mut pixels = [PixelState::default(); N_PIXELS]; + for (i, pixel) in pixels.iter_mut().enumerate() { + *pixel = PixelState::from_bytes(data, i); + } + + Ok(MattonellaState { + pixels, + global_ctrl: extract(data, 0x40, 4, 0), + global_adj: extract(data, 0x40, 2, 4), + enable_tdc: extract(data, 0x40, 1, 6) != 0, + enable_de_tdc: extract(data, 0x40, 1, 7) != 0, + injection_target_0: extract(data, 0x41, 6, 0), + injection_mode_0: channel_mode(extract(data, 0x41, 2, 6), "injection_mode_0")?, + injection_target_1: extract(data, 0x42, 6, 0), + injection_mode_1: channel_mode(extract(data, 0x42, 2, 6), "injection_mode_1")?, + calibration_time: calibration_time(extract(data, 0x43, 2, 0), "calibration_time")?, + calibration_enable: extract(data, 0x43, 1, 2) != 0, + enable_timeout: extract(data, 0x43, 1, 3) != 0, + enable_vfb: extract(data, 0x43, 1, 4) != 0, + enable_vldo: extract(data, 0x43, 1, 5) != 0, + enable_vth: extract(data, 0x43, 1, 6) != 0, + connect_to_pad: extract(data, 0x43, 1, 7) != 0, + dac_icsa: extract(data, 0x44, 3, 0), + dac_idisc: extract(data, 0x44, 3, 3), + enable_afe_auto: extract(data, 0x44, 1, 6) != 0, + enable_afe_loopback: extract(data, 0x44, 1, 7) != 0, + dac_i_krum: extract(data, 0x45, 4, 0), + v_inj_mux: extract(data, 0x45, 2, 4), + enable_v_inj: extract(data, 0x45, 1, 6) != 0, + external_dac: extract(data, 0x45, 1, 7) != 0, + dac_vth_high: DACSetting::from_raw(data[0x46]), + dac_vth_low: DACSetting::from_raw(data[0x47]), + dac_vinj_high: DACSetting::from_raw(data[0x48]), + dac_vinj_low: DACSetting::from_raw(data[0x49]), + dac_vldo: DACSetting::from_raw(data[0x4A]), + dac_vfb: DACSetting::from_raw(data[0x4B]), + }) + } +} + +/// `RegisterField.update_bytes` byte plumbing: range-check `value` against +/// `n_bits` (Python `InvalidRange`), then RMW the target byte. +fn apply( + ret: &mut [u8], + sub: usize, + n_bits: u32, + shift: u32, + value: u32, + field: &'static str, +) -> Result<(), StateError> { + if value >= (1 << n_bits) { + return Err(StateError::OutOfRange { value, n_bits, field }); + } + let mask = (((1u16 << n_bits) - 1) << shift) as u16; + ret[sub] = (((ret[sub] as u16) & !mask | ((value << shift) as u16 & mask)) & 0xFF) as u8; + Ok(()) +} + +/// `RegisterField.from_bytes` byte plumbing: `(data[sub] & mask) >> shift`. +fn extract(data: &[u8], sub: usize, n_bits: u32, shift: u32) -> u8 { + let mask = (((1u16 << n_bits) - 1) << shift) as u8; + (data[sub] & mask) >> shift +} diff --git a/crates/innesco-ecs/tests/common/mod.rs b/crates/innesco-ecs/tests/common/mod.rs new file mode 100644 index 0000000..ed5fb3d --- /dev/null +++ b/crates/innesco-ecs/tests/common/mod.rs @@ -0,0 +1,106 @@ +//! Shared test double: a fake `data_server` over TCP with a HashMap +//! register file keyed by (address, subaddress). + +use std::collections::HashMap; +use std::io::{Read, Write}; +use std::net::TcpListener; +use std::time::Duration; + +use innesco_protocol::Connection; + +/// Fake data_server: HashMap register file + operation log. +pub struct FakeServer { + pub handle: std::thread::JoinHandle<()>, + pub port: u16, + /// shared state: register file (addr, sub) -> byte + regs: std::sync::Arc>>, + // Ping log is only inspected by the ecs (slice 1) tests. + #[allow(dead_code)] + pings: std::sync::Arc>>>, +} + +impl FakeServer { + pub fn start() -> Self { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let regs = std::sync::Arc::new(std::sync::Mutex::new(HashMap::new())); + let pings = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let (r, p) = (regs.clone(), pings.clone()); + let handle = std::thread::spawn(move || { + let (mut sock, _) = listener.accept().unwrap(); + loop { + let mut hdr = [0u8; 5]; + if sock.read_exact(&mut hdr).is_err() { + break; + } + let opcode = hdr[0]; + let len = u32::from_be_bytes([hdr[1], hdr[2], hdr[3], hdr[4]]) as usize; + let mut data = vec![0u8; len]; + sock.read_exact(&mut data).unwrap(); + match opcode { + 0xC1 => { + p.lock().unwrap().push(data.clone()); + let mut resp = vec![0u8]; + resp.extend_from_slice(&(data.len() as u32).to_be_bytes()); + resp.extend_from_slice(&data); + sock.write_all(&resp).unwrap(); + } + 0x10 | 0x12 => { + // Write: data = addr [, sub] payload + let (addr, sub, payload) = if opcode == 0x12 { + (data[0], data[1], &data[2..]) + } else { + (data[0], 0xFF, &data[1..]) + }; + for (i, v) in payload.iter().enumerate() { + // No-subaddress ops address the register directly; + // multi-byte no-sub writes are not used here. + let s = if sub == 0xFF { 0xFF } else { sub + i as u8 }; + r.lock().unwrap().insert((addr, s), *v); + } + sock.write_all(&[0, 0, 0, 0, 0]).unwrap(); + } + 0x11 | 0x13 => { + // Read: data = addr [, sub] len + let (addr, sub, length) = if opcode == 0x13 { + (data[0], data[1], u16::from_be_bytes([data[2], data[3]])) + } else { + (data[0], 0xFF, u16::from_be_bytes([data[1], data[2]])) + }; + let mut payload = vec![0u8]; // i2c status + for i in 0..length { + // Registers are consecutive from the subaddress. + let s = if sub == 0xFF { 0xFF } else { sub + i as u8 }; + let default = 0u8; + payload.push(*r.lock().unwrap().get(&(addr, s)).unwrap_or(&default)); + } + let mut resp = vec![0u8]; + resp.extend_from_slice(&(payload.len() as u32).to_be_bytes()); + resp.extend_from_slice(&payload); + sock.write_all(&resp).unwrap(); + } + _ => sock.write_all(&[1, 0, 0, 0, 4, b'e', b'r', b'r', b'!']).unwrap(), + } + } + }); + FakeServer { handle, port, regs, pings } + } + + pub fn connect(&self) -> Connection { + Connection::connect("127.0.0.1", self.port, Duration::from_secs(5)).unwrap() + } + + pub fn get(&self, addr: u8, sub: u8) -> u8 { + *self.regs.lock().unwrap().get(&(addr, sub)).unwrap_or(&0) + } + + pub fn set(&self, addr: u8, sub: u8, value: u8) { + self.regs.lock().unwrap().insert((addr, sub), value); + } + + // Ping log is only inspected by the ecs (slice 1) tests. + #[allow(dead_code)] + pub fn ping_count(&self) -> usize { + self.pings.lock().unwrap().len() + } +} diff --git a/crates/innesco-ecs/tests/ecs_tests.rs b/crates/innesco-ecs/tests/ecs_tests.rs index 4280fc4..22541e1 100644 --- a/crates/innesco-ecs/tests/ecs_tests.rs +++ b/crates/innesco-ecs/tests/ecs_tests.rs @@ -5,105 +5,10 @@ //! payload, Pings echo. This exercises the exact wire behaviour of the //! read-modify-write semantics ported from `_fields.py`. -use std::collections::HashMap; -use std::io::{Read, Write}; -use std::net::TcpListener; -use std::time::Duration; +mod common; +use common::FakeServer; use innesco_ecs::{Board, FieldContext, Pixel}; -use innesco_protocol::Connection; - -/// Fake data_server: HashMap register file + operation log. -struct FakeServer { - handle: std::thread::JoinHandle<()>, - port: u16, - /// shared state: register file (addr, sub) -> byte - regs: std::sync::Arc>>, - pings: std::sync::Arc>>>, -} - -impl FakeServer { - fn start() -> Self { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let port = listener.local_addr().unwrap().port(); - let regs = std::sync::Arc::new(std::sync::Mutex::new(HashMap::new())); - let pings = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); - let (r, p) = (regs.clone(), pings.clone()); - let handle = std::thread::spawn(move || { - let (mut sock, _) = listener.accept().unwrap(); - loop { - let mut hdr = [0u8; 5]; - if sock.read_exact(&mut hdr).is_err() { - break; - } - let opcode = hdr[0]; - let len = u32::from_be_bytes([hdr[1], hdr[2], hdr[3], hdr[4]]) as usize; - let mut data = vec![0u8; len]; - sock.read_exact(&mut data).unwrap(); - match opcode { - 0xC1 => { - p.lock().unwrap().push(data.clone()); - let mut resp = vec![0u8]; - resp.extend_from_slice(&(data.len() as u32).to_be_bytes()); - resp.extend_from_slice(&data); - sock.write_all(&resp).unwrap(); - } - 0x10 | 0x12 => { - // Write: data = addr [, sub] payload - let (addr, sub, payload) = if opcode == 0x12 { - (data[0], data[1], &data[2..]) - } else { - (data[0], 0xFF, &data[1..]) - }; - for (i, v) in payload.iter().enumerate() { - // No-subaddress ops address the register directly; - // multi-byte no-sub writes are not used by slice 1. - let s = if sub == 0xFF && i == 0 { 0xFF } else { sub }; - r.lock().unwrap().insert((addr, s), *v); - } - sock.write_all(&[0, 0, 0, 0, 0]).unwrap(); - } - 0x11 | 0x13 => { - // Read: data = addr [, sub] len - let (addr, sub, length) = if opcode == 0x13 { - (data[0], data[1], u16::from_be_bytes([data[2], data[3]])) - } else { - (data[0], 0xFF, u16::from_be_bytes([data[1], data[2]])) - }; - let mut payload = vec![0u8]; // i2c status - for _ in 0..length { - let s = if sub == 0xFF { 0xFF } else { sub }; - let default = 0u8; - payload.push(*r.lock().unwrap().get(&(addr, s)).unwrap_or(&default)); - } - let mut resp = vec![0u8]; - resp.extend_from_slice(&(payload.len() as u32).to_be_bytes()); - resp.extend_from_slice(&payload); - sock.write_all(&resp).unwrap(); - } - _ => sock.write_all(&[1, 0, 0, 0, 4, b'e', b'r', b'r', b'!']).unwrap(), - } - } - }); - FakeServer { handle, port, regs, pings } - } - - fn connect(&self) -> Connection { - Connection::connect("127.0.0.1", self.port, Duration::from_secs(5)).unwrap() - } - - fn get(&self, addr: u8, sub: u8) -> u8 { - *self.regs.lock().unwrap().get(&(addr, sub)).unwrap_or(&0) - } - - fn set(&self, addr: u8, sub: u8, value: u8) { - self.regs.lock().unwrap().insert((addr, sub), value); - } - - fn ping_count(&self) -> usize { - self.pings.lock().unwrap().len() - } -} const CTX: FieldContext = FieldContext { mattonella_id: 0, pixel_id: 0 }; diff --git a/crates/innesco-ecs/tests/mattonella_tests.rs b/crates/innesco-ecs/tests/mattonella_tests.rs new file mode 100644 index 0000000..871e31b --- /dev/null +++ b/crates/innesco-ecs/tests/mattonella_tests.rs @@ -0,0 +1,284 @@ +//! Integration tests for the mattonella-level model (slice 2): +//! `MattonellaState` serialization, `Mattonella` full-state I/O, pixel batch +//! operations, calibration and the DAC interface — against the fake +//! `data_server`. + +mod common; +use common::FakeServer; + +use innesco_ecs::{ + CalibrationTime, ChannelMode, DACSetting, Mattonella, MattonellaState, PixelState, + MATTONELLA_STATE_BYTES_LENGTH, N_PIXELS, +}; + +#[test] +fn state_default_register_image() { + let bytes = MattonellaState::default().to_bytes().unwrap(); + + assert_eq!(bytes.len(), MATTONELLA_STATE_BYTES_LENGTH); + // Global registers (0x40-0x4B). + assert_eq!(bytes[0x40], 0x1D, "global_ctrl=13 | global_adj=1<<4"); + assert_eq!(bytes[0x41], 0x00, "target 0 | mode TEST_DAQ_TMR_GPO"); + assert_eq!(bytes[0x42], 0x00); + assert_eq!(bytes[0x43], 0x70, "vfb|vldo|vth enabled, cal off"); + assert_eq!(bytes[0x44], 0x3F, "icsa=7 | idisc=7<<3"); + assert_eq!(bytes[0x45], 0x0A, "i_krum=10"); + assert_eq!(bytes[0x46], 0xDA, "vth_high: enable | 90"); + assert_eq!(bytes[0x47], 0xA8, "vth_low: enable | 40"); + assert_eq!(bytes[0x48], 0xA1, "vinj_high: enable | 33"); + assert_eq!(bytes[0x49], 0x80, "vinj_low: enable | 0"); + assert_eq!(bytes[0x4A], 0xC6, "vldo: enable | 70"); + assert_eq!(bytes[0x4B], 0xDA, "vfb: enable | 90"); + // Pixel bytes (0x00-0x3F): adj=1, ctrl=15 -> 0x1F. + for sub in 0..0x40usize { + assert_eq!(bytes[sub], 0x1F, "pixel byte {sub}"); + } + // Finetune nibbles (0x4C-0x6B): pairs of 7 -> 0x77. + for sub in 0x4C..0x6C { + assert_eq!(bytes[sub], 0x77, "ftdac byte {sub:02X}"); + } +} + +#[test] +fn state_roundtrip_and_mutations() { + let mut state = MattonellaState::default(); + state.pixels[0].power = true; + state.pixels[2].finetune_dac = 9; // even pixel -> low nibble of 0x4D + state.pixels[63].finetune_dac = 3; // odd pixel -> high nibble of 0x6B + state.global_ctrl = 9; + state.injection_target_0 = 42; + state.injection_mode_0 = ChannelMode::TestTdcPulse; + state.calibration_time = CalibrationTime::Cal1600Ns; + state.enable_timeout = true; + state.dac_vth_low = DACSetting::new(false, 100); + + let bytes = state.to_bytes().unwrap(); + assert_eq!(bytes[0x00], 0x5F, "default 0x1F + power bit"); + assert_eq!(bytes[0x4D], 0x79, "pixel 2 low nibble 9, pixel 3 high 7"); + assert_eq!(bytes[0x6B], 0x37, "pixel 62 low 7, pixel 63 high 3"); + assert_eq!(bytes[0x40], 0x19, "global_ctrl=9 | adj=1<<4"); + assert_eq!(bytes[0x41], 0xAA, "target 42 | mode TDC Pulse (2<<6)"); + assert_eq!(bytes[0x43], 0x7A, "0x70 | timeout 0x08 | cal time 2"); + assert_eq!(bytes[0x47], 0x64, "vth_low disabled, value 100"); + + let back = MattonellaState::from_bytes(&bytes).unwrap(); + assert_eq!(back, state); +} + +#[test] +fn state_validation_errors() { + // Wrong length on from_bytes. + let err = MattonellaState::from_bytes(&[0u8; 107]).unwrap_err(); + assert!(matches!(err, innesco_ecs::StateError::Length { got: 107, expected: 0x6C })); + + // Field range checks mirror RegisterField's InvalidRange. + let mut state = MattonellaState::default(); + state.pixels[0].adj = 4; // 2-bit field + assert!(state.to_bytes().is_err()); + + let mut state = MattonellaState::default(); + state.pixels[0].ctrl = 16; // 4-bit field + assert!(state.to_bytes().is_err()); + + let mut state = MattonellaState::default(); + state.dac_icsa = 8; // 3-bit field + assert!(state.to_bytes().is_err()); + + // DACSetting.raw_value range check (Python ValueError). + assert!(DACSetting::new(true, 128).raw_value().is_err()); + assert_eq!(DACSetting::from_raw(0xFF), DACSetting::new(true, 0x7F)); + + // PixelState defaults match the Python dataclass. + assert_eq!( + PixelState::default(), + PixelState { frontend: false, power: false, adj: 1, ctrl: 15, finetune_dac: 7 } + ); + assert_eq!(N_PIXELS, 64); +} + +#[test] +fn mattonella_read_write_full_state() { + let server = FakeServer::start(); + let mut conn = server.connect(); + let m = Mattonella::new(2); + + // Preload the register image of a custom state, then read it back. + let state = MattonellaState { + enable_de_tdc: true, + injection_target_1: 17, + injection_mode_1: ChannelMode::TestAtpPulse, + dac_vldo: DACSetting::new(false, 5), + ..MattonellaState::default() + }; + let image = state.to_bytes().unwrap(); + for (sub, b) in image.iter().enumerate() { + server.set(2, sub as u8, *b); + } + + let read_back = m.read(&mut conn).unwrap(); + assert_eq!(read_back, state); + + // write(): serialize a modified state and check the register file. + let mut modified = state; + modified.global_adj = 2; + modified.pixels[10].ctrl = 1; + let expected = modified.to_bytes().unwrap(); + m.write(&mut conn, &modified).unwrap(); + for (sub, b) in expected.iter().enumerate() { + assert_eq!(server.get(2, sub as u8), *b, "sub {sub:02X}"); + } + + drop(conn); + server.handle.join().unwrap(); +} + +#[test] +fn mattonella_pixel_batch_ops() { + let server = FakeServer::start(); + let mut conn = server.connect(); + let m = Mattonella::new(3); + for sub in 0..64u8 { + server.set(3, sub, 0xFF); + } + + m.set_pixel_power(&mut conn, false).unwrap(); + for sub in 0..64u8 { + assert_eq!(server.get(3, sub), 0xBF, "power cleared, sub {sub}"); + } + m.set_pixel_power(&mut conn, true).unwrap(); + assert_eq!(server.get(3, 0), 0xFF); + + m.set_pixel_frontend(&mut conn, false).unwrap(); + assert_eq!(server.get(3, 5), 0x7F, "frontend cleared"); + + m.set_pixel_adj(&mut conn, 2).unwrap(); + assert_eq!(server.get(3, 5), 0x6F, "0x20 | (0x7F & ~0x30)"); + + m.set_pixel_ctrl(&mut conn, 7).unwrap(); + assert_eq!(server.get(3, 5), 0x67, "0x07 | (0x6F & ~0x0F)"); + + // Range validation (Python ValueError). + assert!(m.set_pixel_adj(&mut conn, 4).is_err()); + assert!(m.set_pixel_ctrl(&mut conn, 16).is_err()); + + drop(conn); + server.handle.join().unwrap(); +} + +#[test] +fn mattonella_mask_and_ftdac() { + let server = FakeServer::start(); + let mut conn = server.connect(); + let m = Mattonella::new(4); + + // set_pixel_mask: direct write, no RMW. + let mask: Vec = (0..64).map(|i| i % 2 == 0).collect(); + m.set_pixel_mask(&mut conn, &mask, false, 0, 9).unwrap(); + assert_eq!(server.get(4, 0), 0x49, "power on: 0x40 | ctrl 9"); + assert_eq!(server.get(4, 1), 0x09, "power off: ctrl 9"); + assert_eq!(server.get(4, 63), 0x09); + assert!(m.set_pixel_mask(&mut conn, &mask[..63], false, 0, 9).is_err()); + assert!(m.set_pixel_mask(&mut conn, &mask, false, 4, 9).is_err()); + assert!(m.set_pixel_mask(&mut conn, &mask, false, 0, 16).is_err()); + + // set_pixel_ftdac: 64 nibbles packed pairwise at 0x4C. + let values: Vec = (0..64u8).map(|i| i % 16).collect(); + m.set_pixel_ftdac(&mut conn, &values).unwrap(); + assert_eq!(server.get(4, 0x4C), 0x10, "pixel 0 = 0 (low), pixel 1 = 1 (high)"); + assert_eq!(server.get(4, 0x4D), 0x32); + assert_eq!(server.get(4, 0x6B), 0xFE, "pixel 62 = 0x0E, pixel 63 = 0x0F"); + let mut bad = values.clone(); + bad[5] = 16; + assert!(m.set_pixel_ftdac(&mut conn, &bad).is_err()); + assert!(m.set_pixel_ftdac(&mut conn, &values[..63]).is_err()); + + drop(conn); + server.handle.join().unwrap(); +} + +#[test] +fn mattonella_calibrate() { + let server = FakeServer::start(); + let mut conn = server.connect(); + let m = Mattonella::new(5); + + m.calibrate(&mut conn, 1, 2).unwrap(); + assert_eq!(server.get(5, 0x70), 0x14, "(dco<<4) | (1<