lc709203 0.3.0

Platform-agnostic Rust driver for the LC709302 battery gauge sensor.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
#![no_std]

//! A platform agnostic Rust driver for the LC709302 battery gauge sensor.
//!
//! # Example usage
//!
//! ```rust
//! // some concrete type implementing I2C access, i.e. the embedded_hal::blocking::i2c::WriteRead
//! // and embedded_hal::blocking::i2c::Write traits
//! let i2c = I2C::new();
//!
//! // create a builder
//! let lc709203 = lc709203::Builder::default()
//!     .with_battery_capacity(2500) // battery capacity (specified in mAh) must be set!
//!     .build(&mut i2c)?; // initialize the lc709203 chip
//! let battery_voltage = lc709203.cell_voltage_v(&mut i2c)?; // query current battery voltage
//! ```

use core::{marker::PhantomData, time::Duration};

use device::Device;
use embedded_hal::i2c::I2c;

pub use device::ChipError;

pub mod device;

/// Higher level access to the LC709203 chip. Provides interpreted/converted data.
pub struct LC709203<I2C> {
    address: u8,
    _c: PhantomData<I2C>,
}

impl<I2C, E> LC709203<I2C>
where
    I2C: I2c<Error = E>,
{
    /// Raw device access.
    pub fn device<'a>(&self, i2c: &'a mut I2C) -> Device<'a, I2C> {
        Device::new(self.address, i2c)
    }

    /// Put chip to sleep. No data will be updated while the chip is asleep.
    pub fn sleep(&self, i2c: &mut I2C) -> Result<(), ChipError<E>> {
        self.device(i2c)
            .write_power_mode(device::constants::IC_POWER_MODE_SLEEP)
    }

    /// Wake IC up from sleep mode.
    pub fn wake_up(&self, i2c: &mut I2C) -> Result<(), ChipError<E>> {
        self.device(i2c)
            .write_power_mode(device::constants::IC_POWER_MODE_OPERATION)
    }

    pub fn is_discharging(&self, i2c: &mut I2C) -> Result<bool, ChipError<E>> {
        let status = self.device(i2c).battery_status()?;
        Ok((status & device::constants::BATTERY_STATUS_DISCHARGING) != 0)
    }

    pub fn is_charging(&self, i2c: &mut I2C) -> Result<bool, ChipError<E>> {
        self.is_discharging(i2c).map(|discharging| !discharging)
    }

    /// Gets current relative state of charge in %.
    pub fn rsoc(&self, i2c: &mut I2C) -> Result<u8, ChipError<E>> {
        self.device(i2c).rsoc().map(|r| r as u8)
    }

    /// Gets current cell charge in %.
    pub fn cell_percentage(&self, i2c: &mut I2C) -> Result<f32, ChipError<E>> {
        self.device(i2c).ite().map(|r| (r as f32) * 0.1)
    }

    /// Gets estimated battery health in %.
    pub fn battery_health(&self, i2c: &mut I2C) -> Result<u8, ChipError<E>> {
        self.device(i2c).battery_health().map(|h| h as u8)
    }

    /// Gets current cell voltage in mV.
    pub fn cell_voltage_mv(&self, i2c: &mut I2C) -> Result<u16, ChipError<E>> {
        self.device(i2c).cell_voltage()
    }

    /// Gets current cell voltage in V.
    pub fn cell_voltage_v(&self, i2c: &mut I2C) -> Result<f32, ChipError<E>> {
        self.cell_voltage_mv(i2c).map(|mv| (mv as f32) / 1000.)
    }

    /// Gets IC version number.
    pub fn ic_version(&self, i2c: &mut I2C) -> Result<u16, ChipError<E>> {
        self.device(i2c).ic_version()
    }

    /// Gets estimated time until battery is empty with a precision of 1 minute.
    pub fn time_to_empty(&self, i2c: &mut I2C) -> Result<Duration, ChipError<E>> {
        self.device(i2c)
            .time_to_empty()
            .map(|t| Duration::from_secs((t as u64) * 60))
    }

    /// Gets current temperature mode for the cell temperature (TSENSE1).
    pub fn cell_temperature_mode(&self, i2c: &mut I2C) -> Result<TemperatureMode, ChipError<E>> {
        let status = self.device(i2c).status_bit()?;
        if (status & device::constants::STATUS_BIT_TSENSE1) == 0 {
            Ok(TemperatureMode::Measure)
        } else {
            Ok(TemperatureMode::I2C)
        }
    }

    /// Sets temperature mode for the cell temperature (TSENSE1).
    pub fn set_cell_temperature_mode(
        &self,
        i2c: &mut I2C,
        mode: TemperatureMode,
    ) -> Result<(), ChipError<E>> {
        let mut dev = self.device(i2c);
        let mut status = dev.status_bit()?;
        status &= !device::constants::STATUS_BIT_TSENSE1;
        if mode == TemperatureMode::I2C {
            status |= device::constants::STATUS_BIT_TSENSE1;
        }
        dev.write_status_bit(status)
    }

    /// Gets B-constant for measuring the cell temperature (TSENSE1).
    pub fn cell_temperature_thermistor_b(&self, i2c: &mut I2C) -> Result<u16, ChipError<E>> {
        self.device(i2c).tsense1_thermistor_b()
    }

    /// Sets B-constant for measuring the cell temperature (TSENSE1).
    pub fn set_cell_temperature_thermistor_b(
        &self,
        i2c: &mut I2C,
        value: u16,
    ) -> Result<(), ChipError<E>> {
        self.device(i2c).write_tsense1_thermistor_b(value)
    }

    /// Gets current cell temperature in °C.
    pub fn cell_temperature(&self, i2c: &mut I2C) -> Result<f32, ChipError<E>> {
        // cell temperature is specified in units of 0.1K
        self.device(i2c)
            .cell_temperature()
            .map(|t| (t as f32) * 0.1 - 273.2)
    }

    /// Sets cell temperature in °C. Only useful when the temperature mode is set to I2C.
    pub fn set_cell_temperature(
        &self,
        i2c: &mut I2C,
        temperature: f32,
    ) -> Result<(), ChipError<E>> {
        let temp = ((temperature + 273.2) * 10.) as u16;
        self.device(i2c).write_cell_temperature(temp)
    }

    /// Gets current temperature mode for the ambient temperature (TSENSE2).
    pub fn ambient_temperature_mode(&self, i2c: &mut I2C) -> Result<TemperatureMode, ChipError<E>> {
        let status = self.device(i2c).status_bit()?;
        if (status & device::constants::STATUS_BIT_TSENSE2) == 0 {
            Ok(TemperatureMode::Measure)
        } else {
            Ok(TemperatureMode::I2C)
        }
    }

    /// Sets temperature mode for the ambient temperature (TSENSE2).
    pub fn set_ambient_temperature_mode(
        &self,
        i2c: &mut I2C,
        mode: TemperatureMode,
    ) -> Result<(), ChipError<E>> {
        let mut dev = self.device(i2c);
        let mut status = dev.status_bit()?;
        status &= !device::constants::STATUS_BIT_TSENSE2;
        if mode == TemperatureMode::I2C {
            status |= device::constants::STATUS_BIT_TSENSE2;
        }
        dev.write_status_bit(status)
    }

    /// Gets B-constant for measuring the ambient temperature (TSENSE2).
    pub fn ambient_temperature_thermistor_b(&self, i2c: &mut I2C) -> Result<u16, ChipError<E>> {
        self.device(i2c).tsense2_thermistor_b()
    }

    /// Sets B-constant for measuring the ambient temperature (TSENSE2).
    pub fn set_ambient_temperature_thermistor_b(
        &self,
        i2c: &mut I2C,
        value: u16,
    ) -> Result<(), ChipError<E>> {
        self.device(i2c).write_tsense2_thermistor_b(value)
    }

    /// Gets current ambient temperature in °C.
    pub fn ambient_temperature(&self, i2c: &mut I2C) -> Result<f32, ChipError<E>> {
        // ambient temperature is specified in units of 0.1K
        self.device(i2c)
            .ambient_temperature()
            .map(|t| (t as f32) * 0.1 - 273.2)
    }
}

/// Mode for the temperature registers (cell temperature and ambient temperature).
#[derive(Debug, PartialEq, Eq)]
pub enum TemperatureMode {
    /// Temperature is measured from a connected thermistor.
    Measure,
    /// Temperature must be provided via I2C.
    I2C,
}

/// Error during initialization.
#[derive(Debug)]
pub enum BuildError<E> {
    /// I2C Error
    I2CError(E),
    /// No battery capacity was specified.
    MissingBatteryCapacity,
    /// Battery capacity out of range for the given battery type.
    BatteryCapacityOutOfRange,
}

impl<E> From<E> for BuildError<E> {
    fn from(e: E) -> Self {
        Self::I2CError(e)
    }
}

impl<E> From<ChipError<E>> for BuildError<E> {
    fn from(e: ChipError<E>) -> Self {
        match e {
            ChipError::I2CError(e) => Self::I2CError(e),
            ChipError::CrcMismatch(_) => {
                // no read happens during build -> cannot happen
                unreachable!("");
            }
        }
    }
}

/// Determines which battery voltage should be used to initializes RSOC measurements.
#[derive(Debug, Clone, Copy)]
pub enum InitTime {
    /// Use voltage measured 10ms after power on reset.
    PowerOn10ms,
    /// Use voltage measured 20ms after power on reset.
    PowerOn20ms,
    /// Use voltage measured 30ms after power on reset.
    PowerOn30ms,
    /// Use voltage measured 40ms after power on reset.
    PowerOn40ms,
    /// Use voltage measured now.
    Now,
}

/// Battery type to use.
#[derive(Debug, Clone, Copy)]
pub enum BatteryType {
    /// Battery with a nominal voltage of 3.7V and a charging voltage of 4.2V. Capacity must be between 50 and 6000mAh.
    Type01,
    /// Panasonic UR18650ZY battery. Capacity must be exactly 2600mAh.
    Type04,
    /// Samsung ICR18650-26H battery. Capacity must be exactly 2600mAh.
    Type05,
    /// Battery with a nominal voltage of 3.8V and a charging voltage of 4.35V. Capacity must be between 50 and 6000mAh.
    Type06,
    /// Battery with a nominal voltage of 3.85V and a charging voltage of 4.4V. Capacity must be between 50 and 3000mAh.
    Type07,
}

/// Builder to configure a LC709203 instance.
pub struct Builder {
    address: u8,
    init_time: InitTime,
    battery_type: BatteryType,
    battery_capacity: Option<u16>,
}

impl Default for Builder {
    fn default() -> Self {
        Self {
            address: device::DEFAULT_I2C_ADDRESS,
            init_time: InitTime::Now,
            battery_type: BatteryType::Type01,
            battery_capacity: None,
        }
    }
}

impl Builder {
    /// Initialize the chip according to configuration.
    pub fn build<I2C, E>(self, i2c: &mut I2C) -> Result<LC709203<I2C>, BuildError<E>>
    where
        I2C: I2c<Error = E>,
    {
        if self.battery_capacity.is_none() {
            return Err(BuildError::MissingBatteryCapacity);
        }

        #[cfg(feature = "log")]
        log::debug!("Initializing device");

        let result = LC709203 {
            address: self.address,
            _c: PhantomData,
        };
        let mut device = result.device(i2c);

        #[cfg(feature = "log")]
        log::debug!("Waking up chip");
        device.write_power_mode(device::constants::IC_POWER_MODE_OPERATION)?;

        #[cfg(feature = "log")]
        log::debug!("Writing battery configuration");
        let apa = Self::calc_apa(self.battery_type, self.battery_capacity.unwrap())? as u16;
        let apa = (apa << 8) | apa;
        #[cfg(feature = "log")]
        log::trace!("calculated battery APA: {:x}", apa);
        device.write_apa(apa)?;
        let type_value = match self.battery_type {
            BatteryType::Type01 => device::constants::BATTERY_TYPE01,
            BatteryType::Type04 => device::constants::BATTERY_TYPE04,
            BatteryType::Type05 => device::constants::BATTERY_TYPE05,
            BatteryType::Type06 => device::constants::BATTERY_TYPE06,
            BatteryType::Type07 => device::constants::BATTERY_TYPE07,
        };
        device.write_battery_type(type_value)?;

        // clear status bits
        device.write_battery_status(0)?;
        match self.init_time {
            InitTime::Now => device.write_init_rsoc(device::constants::INIT_RSOC)?,
            InitTime::PowerOn10ms => {
                device.write_before_rsoc(device::constants::BEFORE_RSOC_1ST_SAMPLE)?
            }
            InitTime::PowerOn20ms => {
                device.write_before_rsoc(device::constants::BEFORE_RSOC_2ND_SAMPLE)?
            }
            InitTime::PowerOn30ms => {
                device.write_before_rsoc(device::constants::BEFORE_RSOC_3RD_SAMPLE)?
            }
            InitTime::PowerOn40ms => {
                device.write_before_rsoc(device::constants::BEFORE_RSOC_4TH_SAMPLE)?
            }
        }
        #[cfg(feature = "log")]
        log::info!("Device initialized");

        Ok(result)
    }

    fn calc_apa<E>(battery_type: BatteryType, battery_capacity: u16) -> Result<u8, BuildError<E>> {
        let apa_table = match (battery_type, battery_capacity) {
            (BatteryType::Type04, 2600) => return Ok(0x10),
            (BatteryType::Type05, 2600) => return Ok(0x06),
            (BatteryType::Type01, cap) if cap >= 50 && cap < 6000 => {
                [0x13, 0x15, 0x18, 0x21, 0x2d, 0x3a, 0x3f, 0x42, 0x44, 0x45]
            }
            (BatteryType::Type01, 6000) => return Ok(0x45),
            (BatteryType::Type06, cap) if cap >= 50 && cap < 6000 => {
                [0x0c, 0x0e, 0x11, 0x17, 0x1e, 0x28, 0x30, 0x34, 0x36, 0x37]
            }
            (BatteryType::Type06, 6000) => return Ok(0x37),
            (BatteryType::Type07, cap) if cap >= 50 && cap < 3000 => {
                [0x03, 0x05, 0x07, 0x02, 0x13, 0x19, 0x1c, 0x00, 0x00, 0x00]
            }
            (BatteryType::Type07, 3000) => return Ok(0x1c),
            _ => return Err(BuildError::BatteryCapacityOutOfRange),
        };
        const CAP_TABLE: [u16; 10] = [50, 100, 200, 500, 1000, 2000, 3000, 4000, 5000, 6000];

        for i in 0..apa_table.len() - 1 {
            if CAP_TABLE[i] == battery_capacity {
                return Ok(apa_table[i]);
            }
            if CAP_TABLE[i] < battery_capacity && CAP_TABLE[i + 1] > battery_capacity {
                let apa0 = apa_table[i];
                let apa1 = apa_table[i + 1];
                let cap0 = CAP_TABLE[i];
                let cap1 = CAP_TABLE[i + 1];
                let apa = apa0 + (apa1 - apa0) * ((battery_capacity - cap0) / (cap1 - cap0)) as u8;
                return Ok(apa);
            }
        }

        unreachable!();
    }

    /// Set I2C address to a non-default address.
    pub fn with_address(mut self, address: u8) -> Self {
        self.address = address;
        self
    }

    /// Change which voltage measurement should be used for RSOC initialization.
    pub fn with_init_time(mut self, init_time: InitTime) -> Self {
        self.init_time = init_time;
        self
    }

    /// Change the battery type to use.
    pub fn with_battery_type(mut self, battery_type: BatteryType) -> Self {
        self.battery_type = battery_type;
        self
    }

    /// Set the design capacity of the used battery in mAh. Must be changed!
    pub fn with_battery_capacity(mut self, battery_capacity: u16) -> Self {
        self.battery_capacity = Some(battery_capacity);
        self
    }
}