#![allow(unused_parens)]
use crate::float24::Float24;
use crate::pec15::PEC15;
use crate::polling::{NoPolling, PollMethod};
use embedded_hal::spi::{Operation, SpiDevice};
use heapless::Vec;
use modular_bitfield::prelude::*;
pub const T_BOOT_US: u32 = 100_000;
pub const T_READY_US: u32 = 20;
pub const T_MLCK_US: u32 = 130_000;
pub(crate) struct DcmdId {
read: bool,
pecc: u8,
}
impl DcmdId {
pub(crate) fn read(pecc: u8) -> Self {
Self::new(true, pecc)
}
pub(crate) fn write(pecc: u8) -> Self {
Self::new(false, pecc)
}
pub(crate) fn new(read: bool, pecc: u8) -> Self {
Self {
read,
pecc: pecc & 0x0F,
}
}
}
impl From<DcmdId> for u8 {
fn from(id: DcmdId) -> Self {
let p3 = (id.pecc >> 3) & 1;
let p2 = (id.pecc >> 2) & 1;
let p1 = (id.pecc >> 1) & 1;
let p0 = id.pecc & 1;
let rw = u8::from(id.read);
let not_rw = rw ^ 1;
(rw << 7) | (not_rw << 6) | ((p3 ^ p2) << 5) | (p3 << 4) | (p2 << 3) | ((p1 ^ p0) << 2) | (p1 << 1) | p0
}
}
const N_PER_PEC: usize = 16;
const FIFO_SAMPLES_PER_BURST: usize = N_PER_PEC / 3;
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum Page {
Page0 = 0,
Page1 = 1,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[repr(u8)]
pub enum RegAddressP0 {
Charge1 = 0x00, Energy1 = 0x06, Time1 = 0x0C, Charge2 = 0x10,
Energy2 = 0x16,
Time2 = 0x1C,
Charge3 = 0x24, Time3 = 0x2C,
Energy4 = 0x34, Time4 = 0x3C,
WkupAck = 0x70,
Status = 0x80,
StatVT = 0x81,
StatIP = 0x82,
StatC = 0x83,
StatE = 0x84,
StatCEOF = 0x85,
StatTB = 0x86,
StatVCC = 0x87,
Current1 = 0x90, Power1 = 0x93,
Current2 = 0x96,
Power2 = 0x99,
Current1Avg = 0x9C,
Bat = 0xA0, Temp = 0xA2,
Vcc = 0xA4,
Slot1 = 0xA6,
Slot2 = 0xA8,
Vref = 0xAA,
Current2Avg = 0xAC,
Gpio4HbCtrl = 0xE8,
Slot1MuxN = 0xEB,
Slot1MuxP = 0xEC,
Slot2MuxN = 0xED,
Slot2MuxP = 0xEE,
ExtFaults = 0xDC,
Occ1Ctrl = 0xDE,
Occ2Ctrl = 0xDF,
Faults = 0xDD,
OpCtrl = 0xF0,
FCurGpioCtrl = 0xF1,
FGpioCtrl = 0xF2,
FaMuxN = 0xF3,
FaMuxP = 0xF4,
FaCtrl = 0xF5,
FifoI1 = 0xF7,
FifoI2 = 0xF8,
FifoBat = 0xF9,
FifoAux = 0xFA,
RdcvIAddr = 0xFC,
RegsCtrl = 0xFF,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[repr(u8)]
pub enum RegAddressP1 {
C1Th = 0x00,
C1Tl = 0x06,
Tb1Th = 0x0C,
E1Th = 0x10,
E1Tl = 0x16,
C2Th = 0x20,
C2Tl = 0x26,
Tb2Th = 0x2C,
E2Th = 0x30,
E2Tl = 0x36,
C3Th = 0x44,
Tb3Th = 0x4C,
C3Tl = 0x54,
E4Th = 0x64,
Tb4Th = 0x6C,
E4Tl = 0x74,
I1Th = 0x80,
I1Tl = 0x82,
P1Th = 0x84,
P1Tl = 0x86,
I2Th = 0x88,
I2Tl = 0x8A,
P2Th = 0x8C,
P2Tl = 0x8E,
BatTh = 0x90,
BatTl = 0x92,
TempTh = 0x94,
TempTl = 0x96,
VccTh = 0x98,
VccTl = 0x9A,
Slot1Th = 0xA0,
Slot1Tl = 0xA2,
Slot2Th = 0xA4,
Slot2Tl = 0xA6,
Rs1Tc2 = 0x5C,
Rs2Tc2 = 0x7C,
Rref1 = 0xAA,
Rref2 = 0xAD,
Ntc1A = 0xD0,
Ntc1B = 0xD3,
Ntc1C = 0xD6,
Rs1Tc = 0xD9,
Rs1T0 = 0xDC,
AdcConf = 0xDF,
Ntc2A = 0xE0,
Ntc2B = 0xE3,
Ntc2C = 0xE6,
Rs2Tc = 0xE9,
Rs2T0 = 0xEC,
Rs1Gc = 0xB0,
Rs2Gc = 0xB3,
RsRatio = 0xB6,
BatGc = 0xB9,
Mux1Gc = 0xC0,
Mux2Gc = 0xC3,
Mux3Gc = 0xC6,
Mux4Gc = 0xC9,
MuxNset1 = 0xBC,
MuxPset1 = 0xBD,
MuxNset2 = 0xBE,
MuxPset2 = 0xBF,
MuxNset3 = 0xCC,
MuxPset3 = 0xCD,
MuxNset4 = 0xCE,
MuxPset4 = 0xCF,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct CurrentSenseVoltage {
raw: i32,
}
impl CurrentSenseVoltage {
pub const LSB_VOLTS: f32 = 950e-9;
pub const THRESHOLD_LSB_VOLTS: f32 = 4.0 * Self::LSB_VOLTS;
pub const fn from_raw(raw: i32) -> Self {
Self { raw }
}
pub fn raw(self) -> i32 {
self.raw
}
pub fn decode(self) -> f32 {
self.raw as f32 * Self::LSB_VOLTS
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct AveragedCurrentSenseVoltage {
raw: i32,
}
impl AveragedCurrentSenseVoltage {
pub const LSB_VOLTS: f32 = 237.5e-9;
pub const fn from_raw(raw: i32) -> Self {
Self { raw }
}
pub fn raw(self) -> i32 {
self.raw
}
pub fn decode(self) -> f32 {
self.raw as f32 * Self::LSB_VOLTS
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct PowerOrVoltage {
raw: i32,
}
impl PowerOrVoltage {
pub const POWER_LSB_VOLT_SQUARED: f32 = 5.8368e-12;
pub const VOLTAGE_LSB_VOLTS: f32 = 46.875e-6;
pub const POWER_THRESHOLD_LSB_VOLT_SQUARED: f32 = 4.0 * Self::POWER_LSB_VOLT_SQUARED;
pub const VOLTAGE_THRESHOLD_LSB_VOLTS: f32 = 4.0 * Self::VOLTAGE_LSB_VOLTS;
pub const fn from_raw(raw: i32) -> Self {
Self { raw }
}
pub fn raw(self) -> i32 {
self.raw
}
pub fn decode_power(self, shunt_ohms: f32) -> f32 {
self.raw as f32 * Self::POWER_LSB_VOLT_SQUARED / shunt_ohms
}
pub fn decode_voltage(self) -> f32 {
self.raw as f32 * Self::VOLTAGE_LSB_VOLTS
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct BatteryVoltage {
raw: i16,
}
impl BatteryVoltage {
pub const LSB_VOLTS: f32 = 375e-6;
pub const fn from_raw(raw: i16) -> Self {
Self { raw }
}
pub fn raw(self) -> i16 {
self.raw
}
pub fn decode(self) -> f32 {
self.raw as f32 * Self::LSB_VOLTS
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct DieTemperature {
raw: i16,
}
impl DieTemperature {
pub const LSB_KELVIN: f32 = 0.2;
pub const ZERO_CELSIUS_KELVIN: f32 = 273.15;
pub const fn from_raw(raw: i16) -> Self {
Self { raw }
}
pub fn raw(self) -> i16 {
self.raw
}
pub fn decode_kelvin(self) -> f32 {
self.raw as f32 * Self::LSB_KELVIN
}
pub fn decode_celsius(self) -> f32 {
self.decode_kelvin() - Self::ZERO_CELSIUS_KELVIN
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct SupplyVoltage {
raw: i16,
}
impl SupplyVoltage {
pub const LSB_VOLTS: f32 = 2.26e-3;
pub const fn from_raw(raw: i16) -> Self {
Self { raw }
}
pub fn raw(self) -> i16 {
self.raw
}
pub fn decode(self) -> f32 {
self.raw as f32 * Self::LSB_VOLTS
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct SlotValue {
raw: i16,
}
impl SlotValue {
pub const LSB_VOLTS: f32 = 375e-6;
pub const LSB_DEGREES_CELSIUS: f32 = 0.2;
pub const fn from_raw(raw: i16) -> Self {
Self { raw }
}
pub fn raw(self) -> i16 {
self.raw
}
pub fn decode_voltage(self) -> f32 {
self.raw as f32 * Self::LSB_VOLTS
}
pub fn decode_temperature(self) -> f32 {
self.raw as f32 * Self::LSB_DEGREES_CELSIUS
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct AccumulatedCharge {
raw: i64,
}
impl AccumulatedCharge {
pub const LSB_VOLT_SECONDS: f64 = 377.887e-12;
pub const fn from_raw(raw: i64) -> Self {
Self { raw }
}
pub fn raw(self) -> i64 {
self.raw
}
pub fn decode(self) -> f64 {
self.raw as f64 * Self::LSB_VOLT_SECONDS
}
pub fn decode_coulombs(self, shunt_ohms: f64) -> f64 {
self.decode() / shunt_ohms
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct AccumulatedEnergy {
raw: i64,
}
impl AccumulatedEnergy {
pub const LSB_VOLT_SQUARED_SECONDS: f64 = 2.32175e-9;
pub const fn from_raw(raw: i64) -> Self {
Self { raw }
}
pub fn raw(self) -> i64 {
self.raw
}
pub fn decode(self) -> f64 {
self.raw as f64 * Self::LSB_VOLT_SQUARED_SECONDS
}
pub fn decode_joules(self, shunt_ohms: f64) -> f64 {
self.decode() / shunt_ohms
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct AccumulatedTime {
raw: u32,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum ChargeAccumulator {
Charge1,
Charge2,
Charge3,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum EnergyAccumulator {
Energy1,
Energy2,
Energy4,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum TimeBase {
Time1,
Time2,
Time3,
Time4,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct Threshold<T> {
pub value: T,
}
impl<T> Threshold<T> {
pub const fn new(value: T) -> Self {
Self { value }
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct ThresholdPair<T> {
pub low: T,
pub high: T,
}
impl<T> ThresholdPair<T> {
pub const fn new(low: T, high: T) -> Self {
Self { low, high }
}
}
impl ThresholdPair<f64> {
fn quantize_signed_code(value: f64, lsb: f64, minimum: f64, maximum: f64) -> Result<i64, ThresholdConversionError> {
if !value.is_finite() {
return Err(ThresholdConversionError::NonFiniteValue);
}
if !lsb.is_finite() || lsb <= 0.0 {
return Err(ThresholdConversionError::InvalidScale);
}
let scaled = value / lsb;
if scaled <= minimum - 0.5 || scaled >= maximum + 0.5 {
return Err(ThresholdConversionError::OutOfRange);
}
Ok(if scaled >= 0.0 {
(scaled + 0.5) as i64
} else {
(scaled - 0.5) as i64
})
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum ThresholdConversionError {
NonFiniteValue,
InvalidScale,
LowAboveHigh,
OutOfRange,
}
pub trait Quantize<Output> {
fn quantize(self, lsb: f64) -> Result<Output, ThresholdConversionError>;
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct Signed16Thresholds {
high: i16,
low: i16,
}
impl Signed16Thresholds {
pub const fn high(self) -> i16 {
self.high
}
pub const fn low(self) -> i16 {
self.low
}
pub fn to_be_bytes(self) -> [u8; 4] {
let mut bytes = [0u8; 4];
bytes[..2].copy_from_slice(&self.high.to_be_bytes());
bytes[2..].copy_from_slice(&self.low.to_be_bytes());
bytes
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct Signed48Thresholds {
high: i64,
low: i64,
}
impl Signed48Thresholds {
pub const fn high(self) -> i64 {
self.high
}
pub const fn low(self) -> i64 {
self.low
}
pub fn to_be_bytes(self) -> [u8; 12] {
let high = self.high.to_be_bytes();
let low = self.low.to_be_bytes();
let mut bytes = [0u8; 12];
bytes[..6].copy_from_slice(&high[2..]);
bytes[6..].copy_from_slice(&low[2..]);
bytes
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct Signed64Thresholds {
high: i64,
low: i64,
}
impl Signed64Thresholds {
pub const fn high(self) -> i64 {
self.high
}
pub const fn low(self) -> i64 {
self.low
}
pub const fn high_to_be_bytes(self) -> [u8; 8] {
self.high.to_be_bytes()
}
pub const fn low_to_be_bytes(self) -> [u8; 8] {
self.low.to_be_bytes()
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct Unsigned32Threshold {
raw: u32,
}
impl Unsigned32Threshold {
pub const fn raw(self) -> u32 {
self.raw
}
pub const fn to_be_bytes(self) -> [u8; 4] {
self.raw.to_be_bytes()
}
}
impl Quantize<Signed16Thresholds> for ThresholdPair<f64> {
fn quantize(self, lsb: f64) -> Result<Signed16Thresholds, ThresholdConversionError> {
if self.low > self.high {
return Err(ThresholdConversionError::LowAboveHigh);
}
Ok(Signed16Thresholds {
high: Self::quantize_signed_code(self.high, lsb, f64::from(i16::MIN), f64::from(i16::MAX))? as i16,
low: Self::quantize_signed_code(self.low, lsb, f64::from(i16::MIN), f64::from(i16::MAX))? as i16,
})
}
}
impl Quantize<Signed16Thresholds> for ThresholdPair<f32> {
fn quantize(self, lsb: f64) -> Result<Signed16Thresholds, ThresholdConversionError> {
ThresholdPair::new(f64::from(self.low), f64::from(self.high)).quantize(lsb)
}
}
impl Quantize<Signed48Thresholds> for ThresholdPair<f64> {
fn quantize(self, lsb: f64) -> Result<Signed48Thresholds, ThresholdConversionError> {
const MIN: f64 = -((1u64 << 47) as f64);
const MAX: f64 = ((1u64 << 47) - 1) as f64;
if self.low > self.high {
return Err(ThresholdConversionError::LowAboveHigh);
}
Ok(Signed48Thresholds {
high: Self::quantize_signed_code(self.high, lsb, MIN, MAX)?,
low: Self::quantize_signed_code(self.low, lsb, MIN, MAX)?,
})
}
}
impl Quantize<Signed64Thresholds> for ThresholdPair<f64> {
fn quantize(self, lsb: f64) -> Result<Signed64Thresholds, ThresholdConversionError> {
if self.low > self.high {
return Err(ThresholdConversionError::LowAboveHigh);
}
if !lsb.is_finite() || lsb <= 0.0 {
return Err(ThresholdConversionError::InvalidScale);
}
if !self.low.is_finite() || !self.high.is_finite() {
return Err(ThresholdConversionError::NonFiniteValue);
}
fn quantize(value: f64, lsb: f64) -> Result<i64, ThresholdConversionError> {
let scaled = value / lsb;
if !(-9_223_372_036_854_775_808.0..9_223_372_036_854_775_808.0).contains(&scaled) {
return Err(ThresholdConversionError::OutOfRange);
}
Ok(if scaled >= 0.0 {
(scaled + 0.5) as i64
} else {
(scaled - 0.5) as i64
})
}
Ok(Signed64Thresholds {
high: quantize(self.high, lsb)?,
low: quantize(self.low, lsb)?,
})
}
}
impl Quantize<Unsigned32Threshold> for Threshold<f64> {
fn quantize(self, lsb: f64) -> Result<Unsigned32Threshold, ThresholdConversionError> {
if !self.value.is_finite() {
return Err(ThresholdConversionError::NonFiniteValue);
}
if !lsb.is_finite() || lsb <= 0.0 {
return Err(ThresholdConversionError::InvalidScale);
}
let scaled = self.value / lsb;
if self.value < 0.0 || scaled >= f64::from(u32::MAX) + 0.5 {
return Err(ThresholdConversionError::OutOfRange);
}
Ok(Unsigned32Threshold {
raw: (scaled + 0.5) as u32,
})
}
}
#[derive(Specifier, Copy, Clone, Eq, PartialEq, Debug)]
#[bits = 2]
pub enum GpioCtrl {
Tristate = 0b00,
Low = 0b01,
Toggle400kHz = 0b10,
High = 0b11,
}
#[derive(Copy, Clone, PartialEq, Debug, Default)]
pub enum AccumulatorClock {
#[default]
Internal,
External {
frequency_hz: f64,
pre: u8,
div: u8,
},
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum AccumulatorClockError {
InvalidConfiguration,
}
impl AccumulatorClock {
pub fn lsbs(self) -> Result<(f64, f64, f64), AccumulatorClockError> {
match self {
AccumulatorClock::Internal => Ok((
AccumulatedCharge::LSB_VOLT_SECONDS,
AccumulatedEnergy::LSB_VOLT_SQUARED_SECONDS,
AccumulatedTime::LSB_SECONDS,
)),
AccumulatorClock::External { frequency_hz, pre, div } => {
if !frequency_hz.is_finite() || frequency_hz <= 0.0 || pre > 7 || div > 31 {
return Err(AccumulatorClockError::InvalidConfiguration);
}
let clock_factor = f64::from(1u16 << pre) * (f64::from(div) + 1.0) / frequency_hz;
Ok((
1.21899e-5 * clock_factor,
7.4895e-5 * clock_factor,
12.8315 * clock_factor,
))
}
}
}
}
impl AccumulatedTime {
pub const LSB_SECONDS: f64 = 397.777e-6;
pub const fn from_raw(raw: u32) -> Self {
Self { raw }
}
pub fn raw(self) -> u32 {
self.raw
}
pub fn decode(self) -> f64 {
self.raw as f64 * Self::LSB_SECONDS
}
}
trait Register: Copy {
const PAGE: Page;
fn addr(self) -> u8;
}
impl Register for RegAddressP0 {
const PAGE: Page = Page::Page0;
fn addr(self) -> u8 {
self as u8
}
}
impl Register for RegAddressP1 {
const PAGE: Page = Page::Page1;
fn addr(self) -> u8 {
self as u8
}
}
#[bitfield(bits = 8)]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[repr(u8)]
pub struct Gpio4HeartbeatControlRegister {
pub gpio4_hb_enable: bool,
#[skip]
__: B7,
}
#[bitfield(bits = 8)]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[repr(u8)]
pub struct CurGpioControlRegister {
#[bits = 2]
pub gpio5_ctrl: GpioCtrl,
#[skip]
__: B2,
pub mux_p_cur_pol: bool,
pub mux_p_cur_en: bool,
pub mux_n_cur_pol: bool,
pub mux_n_cur_en: bool,
}
#[bitfield(bits = 8)]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[repr(u8)]
pub struct GpioControlRegister {
#[bits = 2]
pub gpio1_ctrl: GpioCtrl,
#[bits = 2]
pub gpio2_ctrl: GpioCtrl,
#[bits = 2]
pub gpio3_ctrl: GpioCtrl,
#[bits = 2]
pub gpio4_ctrl: GpioCtrl,
}
#[bitfield(bits = 8)]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[repr(u8)]
pub struct OpsControlRegister {
pub sleep: bool,
pub clr: bool,
pub sshot: bool,
pub cont: bool,
#[skip]
__: B1,
pub adjupd: bool,
#[skip]
__: B1,
pub rst: bool,
}
#[bitfield(bits = 8)]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[repr(u8)]
pub struct FastControlRegister {
pub faconv: bool,
pub facha: bool,
pub fach1: bool,
pub fach2: bool,
#[skip]
__: B4,
}
#[bitfield(bits = 8)]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[repr(u8)]
pub struct AdcConfiguration {
pub p1asv: bool,
pub p2asv: bool,
#[skip]
__: B1,
pub ntc1: bool,
pub ntc2: bool,
#[skip]
__: B1,
pub ntcslot1: bool,
#[skip]
__: B1,
}
#[bitfield(bits = 8)]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[repr(u8)]
pub struct RegControlRegister {
pub page: bool,
#[skip]
__: B1,
pub bcren: bool,
#[skip]
__: B1,
pub mlk: B2,
#[skip]
__: B1,
pub rdcvconf: bool,
}
impl Default for OpsControlRegister {
fn default() -> Self {
Self::new()
}
}
impl Default for Gpio4HeartbeatControlRegister {
fn default() -> Self {
Self::new()
}
}
impl Default for CurGpioControlRegister {
fn default() -> Self {
Self::new()
}
}
impl Default for GpioControlRegister {
fn default() -> Self {
Self::new()
}
}
impl Default for FastControlRegister {
fn default() -> Self {
Self::new()
}
}
impl Default for AdcConfiguration {
fn default() -> Self {
Self::new()
}
}
impl Default for RegControlRegister {
fn default() -> Self {
Self::new()
}
}
#[bitfield(bits = 8)]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[repr(u8)]
pub struct StatusRegister {
pub uvloa: bool,
pub pora: bool,
pub uvlostby: bool,
pub uvlod: bool,
pub update: bool,
pub adcerr: bool,
pub tberr: bool,
#[skip]
__: B1,
}
#[bitfield(bits = 8)]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[repr(u8)]
pub struct VTAlerts {
pub bath: bool,
pub batl: bool,
pub temph: bool,
pub templ: bool,
pub slot1h: bool,
pub slot1l: bool,
pub slot2h: bool,
pub slot2l: bool,
}
#[bitfield(bits = 8)]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[repr(u8)]
pub struct IPAlerts {
pub i1h: bool,
pub i1l: bool,
pub p1h: bool,
pub p1l: bool,
pub i2h: bool,
pub i2l: bool,
pub p2h: bool,
pub p2l: bool,
}
#[bitfield(bits = 8)]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[repr(u8)]
pub struct CAlerts {
pub c1h: bool,
pub c1l: bool,
pub c2h: bool,
pub c2l: bool,
pub c3h: bool,
pub c3l: bool,
#[skip]
__: B2,
}
#[bitfield(bits = 8)]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[repr(u8)]
pub struct EAlerts {
pub e1h: bool,
pub e1l: bool,
pub e2h: bool,
pub e2l: bool,
#[skip]
__: B2,
pub e4h: bool,
pub e4l: bool,
}
#[bitfield(bits = 8)]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[repr(u8)]
pub struct CEOFAlerts {
pub c1ovf: bool,
pub c2ovf: bool,
pub c3ovf: bool,
#[skip]
__: B1,
pub e1ovf: bool,
pub e2ovf: bool,
#[skip]
__: B1,
pub e4ovf: bool,
}
#[bitfield(bits = 8)]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[repr(u8)]
pub struct TBAlerts {
pub t1th: bool,
pub t2th: bool,
pub t3th: bool,
pub t4th: bool,
pub t1ovf: bool,
pub t2ovf: bool,
pub t3ovf: bool,
pub t4ovf: bool,
}
#[bitfield(bits = 8)]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[repr(u8)]
pub struct VCCAlerts {
pub vcch: bool,
pub vccl: bool,
pub occ1h: bool,
pub occ2h: bool,
#[skip]
__: B4,
}
#[bitfield(bits = 8)]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[repr(u8)]
pub struct FaultsRegister {
pub promerr: bool,
pub tsd: bool,
pub intcommerr: bool,
pub extcommerr: bool,
pub faerr: bool,
pub hwbist: bool,
pub crccfg: bool,
pub crcmem: bool,
}
#[bitfield(bits = 8)]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[repr(u8)]
pub struct ExtFaultsRegister {
pub hd1biterr: bool,
pub romerr: bool,
pub memerr: bool,
pub fcaerr: bool,
pub xramerr: bool,
pub iramerr: bool,
#[skip]
__: B1,
pub hwmbistexec: bool,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum FifoTag {
Ok,
ReadOverrun,
WriteOverrun,
Unknown(u8),
}
impl FifoTag {
fn from_byte(b: u8) -> Self {
match b {
0x00 => FifoTag::Ok,
0x55 => FifoTag::ReadOverrun,
0xAA => FifoTag::WriteOverrun,
other => FifoTag::Unknown(other),
}
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct FifoSample {
pub raw: i16,
pub tag: FifoTag,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct Accumulators {
pub charge: AccumulatedCharge,
pub energy: AccumulatedEnergy,
pub time: AccumulatedTime,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct OverCurrentConfig {
pub enable: bool,
pub threshold: u8,
pub deglitch_time: u8,
pub polarity: u8,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum Channel {
One,
Two,
}
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct NtcConfig {
pub r_ref: f32,
pub a: f32,
pub b: f32,
pub c: f32,
}
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct ShuntTcConfig {
pub tc: f32,
pub t_ref: f32,
pub tc2: f32,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[repr(u8)]
pub enum MuxInput {
Agnd = 0,
V1 = 1,
V2 = 2,
V3 = 3,
V4 = 4,
V5 = 5,
V6 = 6,
V7 = 7,
V8 = 8,
V9 = 9,
V10 = 10,
V11 = 11,
V12 = 12,
Imt = 13,
Ipt = 14,
VbatM = 15,
VbatP = 16,
Cf2M = 17,
Cf2P = 18,
Cf1M = 19,
Cf1P = 20,
Vref2 = 22,
Vref2Via250k = 23,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum MuxGainSlot {
One,
Two,
Three,
Four,
}
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum ShuntGainCorrection {
CorrectionFactor(f32),
Resistances { nominal_ohms: f32, actual_ohms: f32 },
}
impl ShuntGainCorrection {
pub const fn from_correction_factor(correction_factor: f32) -> Self {
Self::CorrectionFactor(correction_factor)
}
pub const fn from_resistances(nominal_ohms: f32, actual_ohms: f32) -> Self {
Self::Resistances {
nominal_ohms,
actual_ohms,
}
}
pub fn correction_factor(self) -> f32 {
match self {
Self::CorrectionFactor(correction_factor) => correction_factor,
Self::Resistances {
nominal_ohms,
actual_ohms,
} => nominal_ohms / actual_ohms,
}
}
}
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct PositiveRatio(f32);
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum PositiveRatioError {
NonPositiveOrNonFinite,
}
impl PositiveRatio {
pub fn try_from_ratio(ratio: f32) -> Result<Self, PositiveRatioError> {
if !ratio.is_finite() || ratio <= 0.0 {
return Err(PositiveRatioError::NonPositiveOrNonFinite);
}
Ok(Self(ratio))
}
pub fn try_from_parts(numerator: f32, denominator: f32) -> Result<Self, PositiveRatioError> {
if !numerator.is_finite() || numerator <= 0.0 || !denominator.is_finite() || denominator <= 0.0 {
return Err(PositiveRatioError::NonPositiveOrNonFinite);
}
Self::try_from_ratio(numerator / denominator)
}
pub const fn value(self) -> f32 {
self.0
}
}
impl From<PositiveRatio> for f32 {
fn from(ratio: PositiveRatio) -> Self {
ratio.value()
}
}
pub enum Error<B: SpiDevice<u8>> {
BusError(B::Error),
ChecksumMismatch,
InvalidThreshold,
InvalidGainCorrection,
}
impl<B: SpiDevice<u8>> core::fmt::Debug for Error<B> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Error::BusError(_) => f.debug_struct("BusError").finish(),
Error::ChecksumMismatch => f.debug_struct("ChecksumMismatch").finish(),
Error::InvalidThreshold => f.debug_struct("InvalidThreshold").finish(),
Error::InvalidGainCorrection => f.debug_struct("InvalidGainCorrection").finish(),
}
}
}
impl<B: SpiDevice<u8>> From<ThresholdConversionError> for Error<B> {
fn from(_: ThresholdConversionError) -> Self {
Self::InvalidThreshold
}
}
pub trait Client {
type Error;
fn start_wake_up(&mut self) -> Result<u32, Self::Error>;
fn confirm_wake_up(&mut self) -> Result<(), Self::Error>;
fn wake_isospi(&mut self) -> Result<u32, Self::Error>;
fn write_opctrl(&mut self, value: OpsControlRegister) -> Result<(), Self::Error>;
fn read_opctrl(&mut self) -> Result<OpsControlRegister, Self::Error>;
fn write_factrl(&mut self, value: FastControlRegister) -> Result<(), Self::Error>;
fn write_adcconf(&mut self, value: AdcConfiguration) -> Result<(), Self::Error>;
fn write_shunt_gain_correction(
&mut self,
channel: Channel,
correction: ShuntGainCorrection,
) -> Result<(), Self::Error>;
fn write_shunt_ratio(&mut self, rs1_ohms: f32, rs2_ohms: f32) -> Result<(), Self::Error>;
fn write_battery_gain_correction(&mut self, correction_factor: f32) -> Result<(), Self::Error>;
fn write_mux_gain_correction(
&mut self,
slot: MuxGainSlot,
correction_factor: f32,
negative: MuxInput,
positive: MuxInput,
) -> Result<(), Self::Error>;
fn write_charge_thresholds(
&mut self,
accumulator: ChargeAccumulator,
thresholds: ThresholdPair<f64>,
shunt_ohms: f64,
clock: AccumulatorClock,
) -> Result<(), Self::Error>;
fn write_energy_thresholds(
&mut self,
accumulator: EnergyAccumulator,
thresholds: ThresholdPair<f64>,
shunt_ohms: f64,
clock: AccumulatorClock,
) -> Result<(), Self::Error>;
fn write_time_threshold(
&mut self,
time_base: TimeBase,
threshold: Threshold<f64>,
clock: AccumulatorClock,
) -> Result<(), Self::Error>;
fn write_current_thresholds(
&mut self,
channel: Channel,
thresholds: ThresholdPair<f32>,
shunt_ohms: f32,
) -> Result<(), Self::Error>;
fn write_power_thresholds(
&mut self,
channel: Channel,
thresholds: ThresholdPair<f32>,
shunt_ohms: f32,
) -> Result<(), Self::Error>;
fn write_power_as_voltage_thresholds(
&mut self,
channel: Channel,
thresholds: ThresholdPair<f32>,
) -> Result<(), Self::Error>;
fn write_battery_thresholds(&mut self, thresholds: ThresholdPair<f32>) -> Result<(), Self::Error>;
fn write_temperature_thresholds(&mut self, thresholds: ThresholdPair<f32>) -> Result<(), Self::Error>;
fn write_vcc_thresholds(&mut self, thresholds: ThresholdPair<f32>) -> Result<(), Self::Error>;
fn write_slot_voltage_thresholds(
&mut self,
slot: Channel,
thresholds: ThresholdPair<f32>,
) -> Result<(), Self::Error>;
fn write_slot_temperature_thresholds(
&mut self,
slot: Channel,
thresholds: ThresholdPair<f32>,
) -> Result<(), Self::Error>;
fn write_fast_aux_mux(&mut self, mux_n: u8, mux_p: u8) -> Result<(), Self::Error>;
fn write_ntc_coefficients(&mut self, channel: Channel, params: &NtcConfig) -> Result<(), Self::Error>;
fn write_shunt_tc(&mut self, channel: Channel, config: &ShuntTcConfig) -> Result<(), Self::Error>;
fn write_slot_mux(&mut self, slot: Channel, negative: MuxInput, positive: MuxInput) -> Result<(), Self::Error>;
fn write_gpio_ctrl(&mut self, gpio: GpioControlRegister) -> Result<(), Self::Error>;
fn write_gpio5_config(&mut self, config: CurGpioControlRegister) -> Result<(), Self::Error>;
fn write_gpio_controls(
&mut self,
gpio5_and_current: CurGpioControlRegister,
gpio1_to_4: GpioControlRegister,
) -> Result<(), Self::Error>;
fn write_gpio4_hb(&mut self, hb: bool) -> Result<(), Self::Error>;
fn write_occ_config(&mut self, config1: OverCurrentConfig, config2: OverCurrentConfig) -> Result<(), Self::Error>;
fn read_status(&mut self) -> Result<StatusRegister, Self::Error>;
fn read_vt_alerts(&mut self) -> Result<VTAlerts, Self::Error>;
fn read_ip_alerts(&mut self) -> Result<IPAlerts, Self::Error>;
fn read_c_alerts(&mut self) -> Result<CAlerts, Self::Error>;
fn read_e_alerts(&mut self) -> Result<EAlerts, Self::Error>;
fn read_ceof_alerts(&mut self) -> Result<CEOFAlerts, Self::Error>;
fn read_tb_alerts(&mut self) -> Result<TBAlerts, Self::Error>;
fn read_vcc_alerts(&mut self) -> Result<VCCAlerts, Self::Error>;
fn read_faults(&mut self) -> Result<FaultsRegister, Self::Error>;
fn read_extfaults(&mut self) -> Result<ExtFaultsRegister, Self::Error>;
fn request_memory_lock(&mut self) -> Result<u32, Self::Error>;
fn unlock_memory(&mut self) -> Result<(), Self::Error>;
fn read_current1(&mut self) -> Result<CurrentSenseVoltage, Self::Error>;
fn read_current2(&mut self) -> Result<CurrentSenseVoltage, Self::Error>;
fn read_current1_avg(&mut self) -> Result<AveragedCurrentSenseVoltage, Self::Error>;
fn read_current2_avg(&mut self) -> Result<AveragedCurrentSenseVoltage, Self::Error>;
fn read_power1(&mut self) -> Result<PowerOrVoltage, Self::Error>;
fn read_power2(&mut self) -> Result<PowerOrVoltage, Self::Error>;
fn read_bat(&mut self) -> Result<BatteryVoltage, Self::Error>;
fn read_temp(&mut self) -> Result<DieTemperature, Self::Error>;
fn read_vcc(&mut self) -> Result<SupplyVoltage, Self::Error>;
fn read_slot1(&mut self) -> Result<SlotValue, Self::Error>;
fn read_slot2(&mut self) -> Result<SlotValue, Self::Error>;
fn read_charge1(&mut self) -> Result<AccumulatedCharge, Self::Error>;
fn read_charge2(&mut self) -> Result<AccumulatedCharge, Self::Error>;
fn read_charge3(&mut self) -> Result<AccumulatedCharge, Self::Error>;
fn read_energy1(&mut self) -> Result<AccumulatedEnergy, Self::Error>;
fn read_energy2(&mut self) -> Result<AccumulatedEnergy, Self::Error>;
fn read_energy4(&mut self) -> Result<AccumulatedEnergy, Self::Error>;
fn read_time1(&mut self) -> Result<AccumulatedTime, Self::Error>;
fn read_time2(&mut self) -> Result<AccumulatedTime, Self::Error>;
fn read_time3(&mut self) -> Result<AccumulatedTime, Self::Error>;
fn read_time4(&mut self) -> Result<AccumulatedTime, Self::Error>;
fn read_accumulators1(&mut self) -> Result<Accumulators, Self::Error>;
fn read_accumulators2(&mut self) -> Result<Accumulators, Self::Error>;
fn trigger_adcv_broadcast(&mut self) -> Result<(), Self::Error>;
fn trigger_adax(&mut self) -> Result<(), Self::Error>;
}
pub struct LTC2949<B, P>
where
B: SpiDevice<u8>,
P: PollMethod<B>,
{
bus: B,
poll_method: P,
current_page: Option<Page>,
}
impl<B> LTC2949<B, NoPolling>
where
B: SpiDevice<u8>,
{
pub fn new(bus: B) -> Self {
Self {
bus,
poll_method: NoPolling {},
current_page: None,
}
}
}
impl<B, P> Client for LTC2949<B, P>
where
B: SpiDevice<u8>,
P: PollMethod<B>,
{
type Error = Error<B>;
fn start_wake_up(&mut self) -> Result<u32, Error<B>> {
self.current_page = None;
self.bus.write(&[0x00]).map_err(Error::BusError)?;
self.bus.write(&[0x00]).map_err(Error::BusError)?;
Ok(T_BOOT_US)
}
fn confirm_wake_up(&mut self) -> Result<(), Error<B>> {
self.write_bytes(RegAddressP0::WkupAck, &[0x00])
}
fn wake_isospi(&mut self) -> Result<u32, Error<B>> {
self.bus.write(&[0x00]).map_err(Error::BusError)?;
Ok(T_READY_US)
}
fn write_opctrl(&mut self, value: OpsControlRegister) -> Result<(), Error<B>> {
self.write_bytes(RegAddressP0::OpCtrl, &value.into_bytes())
}
fn read_opctrl(&mut self) -> Result<OpsControlRegister, Error<B>> {
let mut buf = [0u8; 1];
self.read_bytes(RegAddressP0::OpCtrl, &mut buf)?;
Ok(OpsControlRegister::from_bytes(buf))
}
fn write_factrl(&mut self, value: FastControlRegister) -> Result<(), Error<B>> {
self.write_bytes(RegAddressP0::FaCtrl, &value.into_bytes())
}
fn write_adcconf(&mut self, value: AdcConfiguration) -> Result<(), Error<B>> {
self.write_bytes(RegAddressP1::AdcConf, &value.into_bytes())
}
fn write_shunt_gain_correction(
&mut self,
channel: Channel,
correction: ShuntGainCorrection,
) -> Result<(), Error<B>> {
let address = match channel {
Channel::One => RegAddressP1::Rs1Gc,
Channel::Two => RegAddressP1::Rs2Gc,
};
let correction_factor = match correction {
ShuntGainCorrection::CorrectionFactor(correction_factor) => correction_factor,
ShuntGainCorrection::Resistances {
nominal_ohms,
actual_ohms,
} => PositiveRatio::try_from_parts(nominal_ohms, actual_ohms)
.map_err(|_| Error::InvalidGainCorrection)?
.value(),
};
self.write_gain_factor(address, correction_factor)
}
fn write_shunt_ratio(&mut self, rs1_ohms: f32, rs2_ohms: f32) -> Result<(), Error<B>> {
let ratio = PositiveRatio::try_from_parts(rs1_ohms, rs2_ohms)
.map_err(|_| Error::InvalidGainCorrection)?
.value();
self.write_gain_factor(RegAddressP1::RsRatio, ratio)
}
fn write_battery_gain_correction(&mut self, correction_factor: f32) -> Result<(), Error<B>> {
self.write_gain_factor(RegAddressP1::BatGc, correction_factor)
}
fn write_mux_gain_correction(
&mut self,
slot: MuxGainSlot,
correction_factor: f32,
negative: MuxInput,
positive: MuxInput,
) -> Result<(), Error<B>> {
let (gain_address, mux_set_address) = match slot {
MuxGainSlot::One => (RegAddressP1::Mux1Gc, RegAddressP1::MuxNset1),
MuxGainSlot::Two => (RegAddressP1::Mux2Gc, RegAddressP1::MuxNset2),
MuxGainSlot::Three => (RegAddressP1::Mux3Gc, RegAddressP1::MuxNset3),
MuxGainSlot::Four => (RegAddressP1::Mux4Gc, RegAddressP1::MuxNset4),
};
let encoded = Self::encode_gain_factor(correction_factor)?;
self.write_bytes(gain_address, &encoded)?;
self.write_bytes(mux_set_address, &[negative as u8, positive as u8])
}
fn write_charge_thresholds(
&mut self,
accumulator: ChargeAccumulator,
thresholds: ThresholdPair<f64>,
shunt_ohms: f64,
clock: AccumulatorClock,
) -> Result<(), Error<B>> {
let (charge_lsb, _, _) = clock.lsbs().map_err(|_| Error::InvalidThreshold)?;
let lsb_coulombs = Self::divide_lsb_by_shunt(charge_lsb, shunt_ohms)?;
match accumulator {
ChargeAccumulator::Charge1 | ChargeAccumulator::Charge2 => {
let address = match accumulator {
ChargeAccumulator::Charge1 => RegAddressP1::C1Th,
ChargeAccumulator::Charge2 => RegAddressP1::C2Th,
ChargeAccumulator::Charge3 => unreachable!(),
};
let encoded: Signed48Thresholds = thresholds.quantize(lsb_coulombs)?;
self.write_bytes(address, &encoded.to_be_bytes())
}
ChargeAccumulator::Charge3 => {
let encoded: Signed64Thresholds = thresholds.quantize(lsb_coulombs)?;
self.write_bytes(RegAddressP1::C3Th, &encoded.high_to_be_bytes())?;
self.write_bytes(RegAddressP1::C3Tl, &encoded.low_to_be_bytes())
}
}
}
fn write_energy_thresholds(
&mut self,
accumulator: EnergyAccumulator,
thresholds: ThresholdPair<f64>,
shunt_ohms: f64,
clock: AccumulatorClock,
) -> Result<(), Error<B>> {
let (_, energy_lsb, _) = clock.lsbs().map_err(|_| Error::InvalidThreshold)?;
let lsb_joules = Self::divide_lsb_by_shunt(energy_lsb, shunt_ohms)?;
match accumulator {
EnergyAccumulator::Energy1 | EnergyAccumulator::Energy2 => {
let address = match accumulator {
EnergyAccumulator::Energy1 => RegAddressP1::E1Th,
EnergyAccumulator::Energy2 => RegAddressP1::E2Th,
EnergyAccumulator::Energy4 => unreachable!(),
};
let encoded: Signed48Thresholds = thresholds.quantize(lsb_joules)?;
self.write_bytes(address, &encoded.to_be_bytes())
}
EnergyAccumulator::Energy4 => {
let encoded: Signed64Thresholds = thresholds.quantize(lsb_joules)?;
self.write_bytes(RegAddressP1::E4Th, &encoded.high_to_be_bytes())?;
self.write_bytes(RegAddressP1::E4Tl, &encoded.low_to_be_bytes())
}
}
}
fn write_time_threshold(
&mut self,
time_base: TimeBase,
threshold: Threshold<f64>,
clock: AccumulatorClock,
) -> Result<(), Error<B>> {
let (_, _, time_lsb) = clock.lsbs().map_err(|_| Error::InvalidThreshold)?;
let encoded: Unsigned32Threshold = threshold.quantize(time_lsb)?;
let address = match time_base {
TimeBase::Time1 => RegAddressP1::Tb1Th,
TimeBase::Time2 => RegAddressP1::Tb2Th,
TimeBase::Time3 => RegAddressP1::Tb3Th,
TimeBase::Time4 => RegAddressP1::Tb4Th,
};
self.write_bytes(address, &encoded.to_be_bytes())
}
fn write_current_thresholds(
&mut self,
channel: Channel,
thresholds: ThresholdPair<f32>,
shunt_ohms: f32,
) -> Result<(), Error<B>> {
let lsb_amperes =
Self::divide_lsb_by_shunt(CurrentSenseVoltage::THRESHOLD_LSB_VOLTS as f64, shunt_ohms as f64)?;
let address = match channel {
Channel::One => RegAddressP1::I1Th,
Channel::Two => RegAddressP1::I2Th,
};
let encoded: Signed16Thresholds = thresholds.quantize(lsb_amperes)?;
self.write_bytes(address, &encoded.to_be_bytes())
}
fn write_power_thresholds(
&mut self,
channel: Channel,
thresholds: ThresholdPair<f32>,
shunt_ohms: f32,
) -> Result<(), Error<B>> {
let lsb_watts = Self::divide_lsb_by_shunt(
PowerOrVoltage::POWER_THRESHOLD_LSB_VOLT_SQUARED as f64,
shunt_ohms as f64,
)?;
let address = match channel {
Channel::One => RegAddressP1::P1Th,
Channel::Two => RegAddressP1::P2Th,
};
let encoded: Signed16Thresholds = thresholds.quantize(lsb_watts)?;
self.write_bytes(address, &encoded.to_be_bytes())
}
fn write_power_as_voltage_thresholds(
&mut self,
channel: Channel,
thresholds: ThresholdPair<f32>,
) -> Result<(), Error<B>> {
let address = match channel {
Channel::One => RegAddressP1::P1Th,
Channel::Two => RegAddressP1::P2Th,
};
let encoded: Signed16Thresholds = thresholds.quantize(PowerOrVoltage::VOLTAGE_THRESHOLD_LSB_VOLTS as f64)?;
self.write_bytes(address, &encoded.to_be_bytes())
}
fn write_battery_thresholds(&mut self, thresholds: ThresholdPair<f32>) -> Result<(), Error<B>> {
let encoded: Signed16Thresholds = thresholds.quantize(BatteryVoltage::LSB_VOLTS as f64)?;
self.write_bytes(RegAddressP1::BatTh, &encoded.to_be_bytes())
}
fn write_temperature_thresholds(&mut self, thresholds: ThresholdPair<f32>) -> Result<(), Error<B>> {
let kelvin = ThresholdPair::new(
thresholds.low + DieTemperature::ZERO_CELSIUS_KELVIN,
thresholds.high + DieTemperature::ZERO_CELSIUS_KELVIN,
);
let encoded: Signed16Thresholds = kelvin.quantize(DieTemperature::LSB_KELVIN as f64)?;
self.write_bytes(RegAddressP1::TempTh, &encoded.to_be_bytes())
}
fn write_vcc_thresholds(&mut self, thresholds: ThresholdPair<f32>) -> Result<(), Error<B>> {
let encoded: Signed16Thresholds = thresholds.quantize(SupplyVoltage::LSB_VOLTS as f64)?;
self.write_bytes(RegAddressP1::VccTh, &encoded.to_be_bytes())
}
fn write_slot_voltage_thresholds(&mut self, slot: Channel, thresholds: ThresholdPair<f32>) -> Result<(), Error<B>> {
let address = match slot {
Channel::One => RegAddressP1::Slot1Th,
Channel::Two => RegAddressP1::Slot2Th,
};
let encoded: Signed16Thresholds = thresholds.quantize(SlotValue::LSB_VOLTS as f64)?;
self.write_bytes(address, &encoded.to_be_bytes())
}
fn write_slot_temperature_thresholds(
&mut self,
slot: Channel,
thresholds: ThresholdPair<f32>,
) -> Result<(), Error<B>> {
let address = match slot {
Channel::One => RegAddressP1::Slot1Th,
Channel::Two => RegAddressP1::Slot2Th,
};
let encoded: Signed16Thresholds = thresholds.quantize(SlotValue::LSB_DEGREES_CELSIUS as f64)?;
self.write_bytes(address, &encoded.to_be_bytes())
}
fn write_fast_aux_mux(&mut self, mux_n: u8, mux_p: u8) -> Result<(), Error<B>> {
self.write_bytes(RegAddressP0::FaMuxN, &[mux_n, mux_p])
}
fn write_ntc_coefficients(&mut self, channel: Channel, params: &NtcConfig) -> Result<(), Error<B>> {
let (rref_addr, abc_addr) = match channel {
Channel::One => (RegAddressP1::Rref1, RegAddressP1::Ntc1A),
Channel::Two => (RegAddressP1::Rref2, RegAddressP1::Ntc2A),
};
let rref = Float24::new(params.r_ref).encode();
self.write_bytes(rref_addr, &rref)?;
let mut abc = [0u8; 9];
abc[0..3].copy_from_slice(&Float24::new(params.a).encode());
abc[3..6].copy_from_slice(&Float24::new(params.b).encode());
abc[6..9].copy_from_slice(&Float24::new(params.c).encode());
self.write_bytes(abc_addr, &abc)?;
Ok(())
}
fn write_shunt_tc(&mut self, channel: Channel, config: &ShuntTcConfig) -> Result<(), Error<B>> {
let (tc_addr, tc2_addr) = match channel {
Channel::One => (RegAddressP1::Rs1Tc, RegAddressP1::Rs1Tc2),
Channel::Two => (RegAddressP1::Rs2Tc, RegAddressP1::Rs2Tc2),
};
let mut tc_burst = [0u8; 5];
tc_burst[0..3].copy_from_slice(&Float24::new(config.tc).encode());
tc_burst[3..5].copy_from_slice(&Float24::new(config.t_ref).encode_high());
self.write_bytes(tc_addr, &tc_burst)?;
let tc2 = Float24::new(config.tc2).encode();
self.write_bytes(tc2_addr, &tc2)?;
Ok(())
}
fn write_slot_mux(&mut self, slot: Channel, negative: MuxInput, positive: MuxInput) -> Result<(), Error<B>> {
let addr_n = match slot {
Channel::One => RegAddressP0::Slot1MuxN,
Channel::Two => RegAddressP0::Slot2MuxN,
};
self.write_bytes(addr_n, &[negative as u8, positive as u8])
}
fn write_gpio_ctrl(&mut self, gpio: GpioControlRegister) -> Result<(), Self::Error> {
self.write_bytes(RegAddressP0::FGpioCtrl, &gpio.into_bytes())
}
fn write_gpio5_config(&mut self, config: CurGpioControlRegister) -> Result<(), Self::Error> {
self.write_bytes(RegAddressP0::FCurGpioCtrl, &config.into_bytes())
}
fn write_gpio_controls(
&mut self,
gpio5_and_current: CurGpioControlRegister,
gpio1_to_4: GpioControlRegister,
) -> Result<(), Self::Error> {
let bytes = [gpio5_and_current.into_bytes()[0], gpio1_to_4.into_bytes()[0]];
self.write_bytes(RegAddressP0::FCurGpioCtrl, &bytes)
}
fn write_gpio4_hb(&mut self, hb: bool) -> Result<(), Self::Error> {
let config = Gpio4HeartbeatControlRegister::new().with_gpio4_hb_enable(hb);
self.write_bytes(RegAddressP0::Gpio4HbCtrl, &config.into_bytes())
}
fn write_occ_config(&mut self, config1: OverCurrentConfig, config2: OverCurrentConfig) -> Result<(), Self::Error> {
let b =
(config1.enable as u8) | (config1.threshold << 1) | (config1.deglitch_time << 4) | (config1.polarity << 6);
self.write_bytes(RegAddressP0::Occ1Ctrl, &[b])?;
let b2 =
(config2.enable as u8) | (config2.threshold << 1) | (config2.deglitch_time << 4) | (config2.polarity << 6);
self.write_bytes(RegAddressP0::Occ2Ctrl, &[b2])
}
fn read_status(&mut self) -> Result<StatusRegister, Error<B>> {
let mut buf = [0u8; 1];
self.read_bytes(RegAddressP0::Status, &mut buf)?;
Ok(StatusRegister::from_bytes(buf))
}
fn read_vt_alerts(&mut self) -> Result<VTAlerts, Self::Error> {
let mut buf = [0u8; 1];
self.read_bytes(RegAddressP0::StatVT, &mut buf)?;
Ok(VTAlerts::from_bytes(buf))
}
fn read_ip_alerts(&mut self) -> Result<IPAlerts, Self::Error> {
let mut buf = [0u8; 1];
self.read_bytes(RegAddressP0::StatIP, &mut buf)?;
Ok(IPAlerts::from_bytes(buf))
}
fn read_c_alerts(&mut self) -> Result<CAlerts, Self::Error> {
let mut buf = [0u8; 1];
self.read_bytes(RegAddressP0::StatC, &mut buf)?;
Ok(CAlerts::from_bytes(buf))
}
fn read_e_alerts(&mut self) -> Result<EAlerts, Self::Error> {
let mut buf = [0u8; 1];
self.read_bytes(RegAddressP0::StatE, &mut buf)?;
Ok(EAlerts::from_bytes(buf))
}
fn read_ceof_alerts(&mut self) -> Result<CEOFAlerts, Self::Error> {
let mut buf = [0u8; 1];
self.read_bytes(RegAddressP0::StatCEOF, &mut buf)?;
Ok(CEOFAlerts::from_bytes(buf))
}
fn read_tb_alerts(&mut self) -> Result<TBAlerts, Self::Error> {
let mut buf = [0u8; 1];
self.read_bytes(RegAddressP0::StatTB, &mut buf)?;
Ok(TBAlerts::from_bytes(buf))
}
fn read_vcc_alerts(&mut self) -> Result<VCCAlerts, Self::Error> {
let mut buf = [0u8; 1];
self.read_bytes(RegAddressP0::StatVCC, &mut buf)?;
Ok(VCCAlerts::from_bytes(buf))
}
fn read_faults(&mut self) -> Result<FaultsRegister, Error<B>> {
let mut buf = [0u8; 1];
self.read_bytes(RegAddressP0::Faults, &mut buf)?;
Ok(FaultsRegister::from_bytes(buf))
}
fn read_extfaults(&mut self) -> Result<ExtFaultsRegister, Error<B>> {
let mut buf = [0u8; 1];
self.read_bytes(RegAddressP0::ExtFaults, &mut buf)?;
Ok(ExtFaultsRegister::from_bytes(buf))
}
fn request_memory_lock(&mut self) -> Result<u32, Error<B>> {
let page = self.current_page.unwrap_or(Page::Page0);
let value = self.regsctrl_base().with_mlk(0b01);
self.dcmd_write(RegAddressP0::RegsCtrl.addr(), &value.into_bytes())?;
self.current_page = Some(page);
Ok(T_MLCK_US)
}
fn unlock_memory(&mut self) -> Result<(), Error<B>> {
let value = self.regsctrl_base();
self.dcmd_write(RegAddressP0::RegsCtrl.addr(), &value.into_bytes())
}
fn read_current1(&mut self) -> Result<CurrentSenseVoltage, Error<B>> {
self.read_signed_24(RegAddressP0::Current1).map(CurrentSenseVoltage::from_raw)
}
fn read_current2(&mut self) -> Result<CurrentSenseVoltage, Error<B>> {
self.read_signed_24(RegAddressP0::Current2).map(CurrentSenseVoltage::from_raw)
}
fn read_current1_avg(&mut self) -> Result<AveragedCurrentSenseVoltage, Error<B>> {
self.read_signed_24(RegAddressP0::Current1Avg)
.map(AveragedCurrentSenseVoltage::from_raw)
}
fn read_current2_avg(&mut self) -> Result<AveragedCurrentSenseVoltage, Error<B>> {
self.read_signed_24(RegAddressP0::Current2Avg)
.map(AveragedCurrentSenseVoltage::from_raw)
}
fn read_power1(&mut self) -> Result<PowerOrVoltage, Error<B>> {
self.read_signed_24(RegAddressP0::Power1).map(PowerOrVoltage::from_raw)
}
fn read_power2(&mut self) -> Result<PowerOrVoltage, Error<B>> {
self.read_signed_24(RegAddressP0::Power2).map(PowerOrVoltage::from_raw)
}
fn read_bat(&mut self) -> Result<BatteryVoltage, Error<B>> {
self.read_signed_16(RegAddressP0::Bat).map(BatteryVoltage::from_raw)
}
fn read_temp(&mut self) -> Result<DieTemperature, Error<B>> {
self.read_signed_16(RegAddressP0::Temp).map(DieTemperature::from_raw)
}
fn read_vcc(&mut self) -> Result<SupplyVoltage, Error<B>> {
self.read_signed_16(RegAddressP0::Vcc).map(SupplyVoltage::from_raw)
}
fn read_slot1(&mut self) -> Result<SlotValue, Error<B>> {
self.read_signed_16(RegAddressP0::Slot1).map(SlotValue::from_raw)
}
fn read_slot2(&mut self) -> Result<SlotValue, Error<B>> {
self.read_signed_16(RegAddressP0::Slot2).map(SlotValue::from_raw)
}
fn read_charge1(&mut self) -> Result<AccumulatedCharge, Error<B>> {
self.read_signed_48(RegAddressP0::Charge1).map(AccumulatedCharge::from_raw)
}
fn read_charge2(&mut self) -> Result<AccumulatedCharge, Error<B>> {
self.read_signed_48(RegAddressP0::Charge2).map(AccumulatedCharge::from_raw)
}
fn read_charge3(&mut self) -> Result<AccumulatedCharge, Error<B>> {
self.read_signed_64(RegAddressP0::Charge3).map(AccumulatedCharge::from_raw)
}
fn read_energy1(&mut self) -> Result<AccumulatedEnergy, Error<B>> {
self.read_signed_48(RegAddressP0::Energy1).map(AccumulatedEnergy::from_raw)
}
fn read_energy2(&mut self) -> Result<AccumulatedEnergy, Error<B>> {
self.read_signed_48(RegAddressP0::Energy2).map(AccumulatedEnergy::from_raw)
}
fn read_energy4(&mut self) -> Result<AccumulatedEnergy, Error<B>> {
self.read_signed_64(RegAddressP0::Energy4).map(AccumulatedEnergy::from_raw)
}
fn read_time1(&mut self) -> Result<AccumulatedTime, Error<B>> {
self.read_unsigned_32(RegAddressP0::Time1).map(AccumulatedTime::from_raw)
}
fn read_time2(&mut self) -> Result<AccumulatedTime, Error<B>> {
self.read_unsigned_32(RegAddressP0::Time2).map(AccumulatedTime::from_raw)
}
fn read_time3(&mut self) -> Result<AccumulatedTime, Error<B>> {
self.read_unsigned_32(RegAddressP0::Time3).map(AccumulatedTime::from_raw)
}
fn read_time4(&mut self) -> Result<AccumulatedTime, Error<B>> {
self.read_unsigned_32(RegAddressP0::Time4).map(AccumulatedTime::from_raw)
}
fn read_accumulators1(&mut self) -> Result<Accumulators, Error<B>> {
self.read_accumulator_row(RegAddressP0::Charge1)
}
fn read_accumulators2(&mut self) -> Result<Accumulators, Error<B>> {
self.read_accumulator_row(RegAddressP0::Charge2)
}
fn trigger_adcv_broadcast(&mut self) -> Result<(), Error<B>> {
self.send_cmd16(0x0260)
}
fn trigger_adax(&mut self) -> Result<(), Error<B>> {
self.send_cmd16(0x0460)
}
}
impl<B, P> LTC2949<B, P>
where
B: SpiDevice<u8>,
P: PollMethod<B>,
{
fn encode_gain_factor(correction_factor: f32) -> Result<[u8; 3], Error<B>> {
if !correction_factor.is_finite() || correction_factor <= 0.0 {
return Err(Error::InvalidGainCorrection);
}
Ok(Float24::new(correction_factor).encode())
}
fn write_gain_factor(&mut self, address: RegAddressP1, correction_factor: f32) -> Result<(), Error<B>> {
let encoded = Self::encode_gain_factor(correction_factor)?;
self.write_bytes(address, &encoded)
}
fn divide_lsb_by_shunt(lsb: f64, shunt_ohms: f64) -> Result<f64, Error<B>> {
if !shunt_ohms.is_finite() || shunt_ohms <= 0.0 {
return Err(Error::InvalidThreshold);
}
Ok(lsb / shunt_ohms)
}
pub fn read_fifo_i1<const N: usize>(&mut self) -> Result<Vec<FifoSample, N>, Error<B>> {
self.read_fifo::<N>(RegAddressP0::FifoI1)
}
pub fn read_fifo_i2<const N: usize>(&mut self) -> Result<Vec<FifoSample, N>, Error<B>> {
self.read_fifo::<N>(RegAddressP0::FifoI2)
}
pub fn read_fifo_bat<const N: usize>(&mut self) -> Result<Vec<FifoSample, N>, Error<B>> {
self.read_fifo::<N>(RegAddressP0::FifoBat)
}
pub fn read_fifo_aux<const N: usize>(&mut self) -> Result<Vec<FifoSample, N>, Error<B>> {
self.read_fifo::<N>(RegAddressP0::FifoAux)
}
fn read_fifo<const N: usize>(&mut self, reg: RegAddressP0) -> Result<Vec<FifoSample, N>, Error<B>> {
let mut samples: Vec<FifoSample, N> = Vec::new();
let mut buf = [0u8; FIFO_SAMPLES_PER_BURST * 3];
let mut remaining = N;
while remaining > 0 {
let batch = remaining.min(FIFO_SAMPLES_PER_BURST);
let bytes = &mut buf[..batch * 3];
self.read_bytes(reg, bytes)?;
for sample in bytes.as_chunks::<3>().0 {
let raw = ((sample[0] as u16) << 8 | sample[1] as u16) as i16;
let tag = FifoTag::from_byte(sample[2]);
let stop = !matches!(tag, FifoTag::Ok);
let _ = samples.push(FifoSample { raw, tag });
if stop {
return Ok(samples);
}
}
remaining -= batch;
}
Ok(samples)
}
fn read_signed_16(&mut self, reg: RegAddressP0) -> Result<i16, Error<B>> {
let mut buf = [0u8; 2];
self.read_bytes(reg, &mut buf)?;
Ok(i16::from_be_bytes(buf))
}
fn read_signed_24(&mut self, reg: RegAddressP0) -> Result<i32, Error<B>> {
let mut buf = [0u8; 3];
self.read_bytes(reg, &mut buf)?;
let raw = (u32::from(buf[0]) << 16) | (u32::from(buf[1]) << 8) | u32::from(buf[2]);
let extended = if raw & 0x0080_0000 != 0 { raw | 0xFF00_0000 } else { raw };
Ok(extended as i32)
}
fn read_unsigned_32(&mut self, reg: RegAddressP0) -> Result<u32, Error<B>> {
let mut buf = [0u8; 4];
self.read_bytes(reg, &mut buf)?;
Ok(u32::from_be_bytes(buf))
}
fn read_signed_48(&mut self, reg: RegAddressP0) -> Result<i64, Error<B>> {
let mut buf = [0u8; 6];
self.read_bytes(reg, &mut buf)?;
Ok(Self::sign_extend_48(&buf))
}
fn read_accumulator_row(&mut self, reg: RegAddressP0) -> Result<Accumulators, Error<B>> {
let mut buf = [0u8; 16];
self.read_bytes(reg, &mut buf)?;
Ok(Accumulators {
charge: AccumulatedCharge::from_raw(Self::sign_extend_48(&buf[0..6])),
energy: AccumulatedEnergy::from_raw(Self::sign_extend_48(&buf[6..12])),
time: AccumulatedTime::from_raw(u32::from_be_bytes([buf[12], buf[13], buf[14], buf[15]])),
})
}
fn read_signed_64(&mut self, reg: RegAddressP0) -> Result<i64, Error<B>> {
let mut buf = [0u8; 8];
self.read_bytes(reg, &mut buf)?;
Ok(i64::from_be_bytes(buf))
}
fn regsctrl_base(&self) -> RegControlRegister {
let page1 = matches!(self.current_page.unwrap_or(Page::Page0), Page::Page1);
RegControlRegister::default().with_rdcvconf(true).with_page(page1)
}
fn select_page(&mut self, page: Page) -> Result<(), Error<B>> {
if self.current_page == Some(page) {
return Ok(());
}
let value = RegControlRegister::default()
.with_rdcvconf(true)
.with_page(matches!(page, Page::Page1));
self.dcmd_write(RegAddressP0::RegsCtrl.addr(), &value.into_bytes())?;
self.current_page = Some(page);
Ok(())
}
fn read_bytes<R: Register>(&mut self, reg: R, buf: &mut [u8]) -> Result<(), Error<B>> {
self.select_page(R::PAGE)?;
self.dcmd_read(reg.addr(), buf)
}
fn write_bytes<R: Register>(&mut self, reg: R, data: &[u8]) -> Result<(), Error<B>> {
if reg.addr() != RegAddressP0::RegsCtrl.addr() {
self.select_page(R::PAGE)?;
}
self.dcmd_write(reg.addr(), data)
}
fn dcmd_write(&mut self, addr: u8, data: &[u8]) -> Result<(), Error<B>> {
assert!(
(1..=N_PER_PEC).contains(&data.len()),
"DCMD write requires 1 to 16 data bytes"
);
let mut frame = [0u8; 23];
frame[0] = 0xFE;
frame[1] = addr;
let header_pec = PEC15::calc(&frame[0..2]);
frame[2] = header_pec[0];
frame[3] = header_pec[1];
let n = data.len();
frame[4] = DcmdId::write((n - 1) as u8).into();
frame[5..5 + n].copy_from_slice(data);
let data_pec = PEC15::calc(&frame[5..5 + n]);
frame[5 + n] = data_pec[0];
frame[6 + n] = data_pec[1];
let total = 5 + n + 2;
self.bus.write(&frame[..total]).map_err(Error::BusError)?;
self.poll_method.end_sync_command(&mut self.bus).map_err(Error::BusError)?;
Ok(())
}
fn dcmd_read(&mut self, addr: u8, buf: &mut [u8]) -> Result<(), Error<B>> {
assert!(
(1..=N_PER_PEC).contains(&buf.len()),
"DCMD read requires 1 to 16 data bytes"
);
let n = buf.len();
let mut mosi = [0xFFu8; 23];
let mut miso = [0x00u8; 23];
mosi[0] = 0xFE;
mosi[1] = addr;
let header_pec = PEC15::calc(&mosi[0..2]);
mosi[2] = header_pec[0];
mosi[3] = header_pec[1];
mosi[4] = DcmdId::read((n - 1) as u8).into();
let total = 5 + n + 2;
self.bus
.transaction(&mut [Operation::Transfer(&mut miso[..total], &mosi[..total])])
.map_err(Error::BusError)?;
buf.copy_from_slice(&miso[5..5 + n]);
let pec = PEC15::calc(&miso[5..5 + n]);
if pec[0] != miso[5 + n] || pec[1] != miso[6 + n] {
self.current_page = None;
return Err(Error::ChecksumMismatch);
}
self.poll_method.end_sync_command(&mut self.bus).map_err(Error::BusError)?;
Ok(())
}
fn send_cmd16(&mut self, cmd: u16) -> Result<(), Error<B>> {
let frame = Self::build_cmd16(cmd);
self.bus.write(&frame).map_err(Error::BusError)?;
self.poll_method.end_sync_command(&mut self.bus).map_err(Error::BusError)?;
Ok(())
}
fn sign_extend_48(bytes: &[u8]) -> i64 {
let mut raw: u64 = 0;
for &b in &bytes[..6] {
raw = (raw << 8) | u64::from(b);
}
if raw & 0x0000_8000_0000_0000 != 0 {
raw |= 0xFFFF_0000_0000_0000;
}
raw as i64
}
fn build_cmd16(cmd: u16) -> [u8; 4] {
let mut frame = [(cmd >> 8) as u8, cmd as u8, 0, 0];
let pec = PEC15::calc(&frame[..2]);
frame[2] = pec[0];
frame[3] = pec[1];
frame
}
}