forked from OpenDevicePartnership/tmp108
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasynchronous.rs
More file actions
361 lines (307 loc) · 11.9 KB
/
Copy pathasynchronous.rs
File metadata and controls
361 lines (307 loc) · 11.9 KB
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
//! Tmp108 Async API
use core::future::Future;
#[cfg(feature = "embedded-sensors-hal-async")]
use embedded_sensors_hal_async::sensor;
#[cfg(feature = "embedded-sensors-hal-async")]
use embedded_sensors_hal_async::temperature::{DegreesCelsius, TemperatureSensor};
use super::{Configuration, ConversionMode, ConversionRate, Register, A0};
/// TMP108 asynchronous device driver
pub struct Tmp108<I2C: embedded_hal_async::i2c::I2c, DELAY: embedded_hal_async::delay::DelayNs> {
/// The concrete I2C bus implementation
i2c: I2C,
/// The concrete [`embedded_hal::delay::DelayNs`] implementation
delay: DELAY,
/// The I2C address.
pub(crate) addr: u8,
}
impl<I2C: embedded_hal_async::i2c::I2c, DELAY: embedded_hal_async::delay::DelayNs> Tmp108<I2C, DELAY> {
const CELSIUS_PER_BIT: f32 = 0.0625;
const CONVERSION_TIME_TYPICAL_MS: u32 = 27;
/// Create a new TMP108 instance.
pub async fn new_async(i2c: I2C, mut delay: DELAY, a0: A0) -> Self {
delay.delay_ms(Self::CONVERSION_TIME_TYPICAL_MS).await;
Self {
i2c,
delay,
addr: a0.into(),
}
}
/// Create a new TMP108 instance with A0 tied to GND, resulting in an
/// instance responding to address `0x48`.
pub async fn new_async_with_a0_gnd(i2c: I2C, delay: DELAY) -> Self {
Self::new_async(i2c, delay, A0::Gnd).await
}
/// Create a new TMP108 instance with A0 tied to V+, resulting in an
/// instance responding to address `0x49`.
pub async fn new_async_with_a0_vplus(i2c: I2C, delay: DELAY) -> Self {
Self::new_async(i2c, delay, A0::Vplus).await
}
/// Create a new TMP108 instance with A0 tied to SDA, resulting in an
/// instance responding to address `0x4a`.
pub async fn new_async_with_a0_sda(i2c: I2C, delay: DELAY) -> Self {
Self::new_async(i2c, delay, A0::Sda).await
}
/// Create a new TMP108 instance with A0 tied to SCL, resulting in an
/// instance responding to address `0x4b`.
pub async fn new_async_with_a0_scl(i2c: I2C, delay: DELAY) -> Self {
Self::new_async(i2c, delay, A0::Scl).await
}
/// Destroy the driver instance, return the I2C bus instance.
pub fn destroy(self) -> I2C {
self.i2c
}
/// Read configuration register
///
/// # Errors
///
/// `I2C::Error` when the I2C transaction fails
pub async fn configuration(&mut self) -> Result<Configuration, I2C::Error> {
let data = self.read(Register::Configuration).await?;
Ok(Configuration::from(u16::from_be_bytes(data)))
}
/// Set configuration register
///
/// # Errors
///
/// `I2C::Error` when the I2C transaction fails
pub async fn set_configuration(&mut self, config: Configuration) -> Result<(), I2C::Error> {
let value: u16 = config.into();
self.write(Register::Configuration, value.to_be_bytes()).await
}
/// Read temperature register
///
/// # Errors
///
/// `I2C::Error` when the I2C transaction fails
pub async fn temperature(&mut self) -> Result<f32, I2C::Error> {
self.delay.delay_ms(Self::CONVERSION_TIME_TYPICAL_MS).await;
let raw = self.read(Register::Temperature).await?;
Ok(Self::to_celsius(i16::from_be_bytes(raw)))
}
/// Configure device for One-shot conversion
///
/// # Errors
///
/// `I2C::Error` when the I2C transaction fails
pub async fn one_shot(&mut self) -> Result<(), I2C::Error> {
self.set_mode(ConversionMode::Continuous).await
}
/// Place device in Shutdown mode
///
/// # Errors
///
/// `I2C::Error` when the I2C transaction fails
pub async fn shutdown(&mut self) -> Result<(), I2C::Error> {
self.set_mode(ConversionMode::Shutdown).await
}
/// Initiate continuous conversions
///
/// # Errors
///
/// `I2C::Error` when the I2C transaction fails
pub async fn continuous<F, Fut>(&mut self, mut config: Configuration, f: F) -> Result<(), I2C::Error>
where
F: FnOnce(&mut Self) -> Fut,
Fut: Future<Output = Result<(), I2C::Error>> + Send,
{
config.set_cm(ConversionMode::Continuous);
self.set_configuration(config).await?;
f(self).await?;
self.shutdown().await
}
/// Wait for conversion to complete. This method will block for the amount
/// of time dictated by the CR bits in the [`Configuration`]
/// register. Caller is required to call this method from within their
/// continuous conversion closure.
///
/// # Errors
///
/// `I2C::Error` when the I2C transaction fails
pub async fn wait_for_temperature(&mut self) -> Result<f32, I2C::Error> {
let config = self.configuration().await?;
let delay = match config.cr() {
ConversionRate::Hertz025 => 4_000_000,
ConversionRate::Hertz1 => 1_000_000,
ConversionRate::Hertz4 => 250_000,
ConversionRate::Hertz16 => 62_500,
};
self.delay.delay_us(delay).await;
self.temperature().await
}
/// Read temperature low limit register
///
/// # Errors
///
/// `I2C::Error` when the I2C transaction fails
pub async fn low_limit(&mut self) -> Result<f32, I2C::Error> {
let raw = self.read(Register::LowLimit).await?;
Ok(Self::to_celsius(i16::from_be_bytes(raw)))
}
/// Set temperature low limit register
///
/// # Errors
///
/// `I2C::Error` when the I2C transaction fails
pub async fn set_low_limit(&mut self, limit: f32) -> Result<(), I2C::Error> {
let raw = Self::to_raw(limit);
self.write(Register::LowLimit, raw.to_be_bytes()).await
}
/// Read temperature high limit register
///
/// # Errors
///
/// `I2C::Error` when the I2C transaction fails
pub async fn high_limit(&mut self) -> Result<f32, I2C::Error> {
let raw = self.read(Register::HighLimit).await?;
Ok(Self::to_celsius(i16::from_be_bytes(raw)))
}
/// Set temperature low limit register
///
/// # Errors
///
/// `I2C::Error` when the I2C transaction fails
pub async fn set_high_limit(&mut self, limit: f32) -> Result<(), I2C::Error> {
let raw = Self::to_raw(limit);
self.write(Register::HighLimit, raw.to_be_bytes()).await
}
async fn set_mode(&mut self, mode: ConversionMode) -> Result<(), I2C::Error> {
let mut config = self.configuration().await?;
config.set_cm(mode);
self.set_configuration(config).await
}
async fn read(&mut self, reg: Register) -> Result<[u8; 2], I2C::Error> {
let mut bytes = [0; 2];
self.i2c.write_read(self.addr, &[reg.into()], &mut bytes).await?;
Ok(bytes)
}
async fn write(&mut self, reg: Register, value: [u8; 2]) -> Result<(), I2C::Error> {
let mut data = [0; 3];
data[0] = reg.into();
data[1..].copy_from_slice(&value);
self.i2c.write(self.addr, &data).await
}
fn to_celsius(t: i16) -> f32 {
f32::from(t / 16) * Self::CELSIUS_PER_BIT
}
#[allow(clippy::cast_possible_truncation)]
fn to_raw(t: f32) -> i16 {
(t * 16.0 / Self::CELSIUS_PER_BIT) as i16
}
}
/// Tmp108 Errors
#[derive(Debug)]
pub enum Error<E: embedded_hal_async::i2c::Error> {
/// I2C Bus Error
Bus(E),
}
#[cfg(feature = "embedded-sensors-hal-async")]
impl<E: embedded_hal_async::i2c::Error> sensor::Error for Error<E> {
fn kind(&self) -> sensor::ErrorKind {
sensor::ErrorKind::Other
}
}
#[cfg(feature = "embedded-sensors-hal-async")]
impl<I2C: embedded_hal_async::i2c::I2c, DELAY: embedded_hal_async::delay::DelayNs> sensor::ErrorType
for Tmp108<I2C, DELAY>
{
type Error = Error<I2C::Error>;
}
#[cfg(feature = "embedded-sensors-hal-async")]
impl<I2C: embedded_hal_async::i2c::I2c, DELAY: embedded_hal_async::delay::DelayNs> TemperatureSensor
for Tmp108<I2C, DELAY>
{
async fn temperature(&mut self) -> Result<DegreesCelsius, Self::Error> {
self.temperature().await.map_err(Error::Bus)
}
}
#[cfg(test)]
mod tests {
use assert_approx_eq::assert_approx_eq;
use embedded_hal_mock::eh1::delay::NoopDelay;
use embedded_hal_mock::eh1::i2c::{Mock, Transaction};
use super::*;
use crate::{Hysteresis, Polarity, ThermostatMode};
#[tokio::test]
async fn handle_a0_pin_accordingly() {
let expectations = vec![];
let mock = Mock::new(&expectations);
let delay = NoopDelay::new();
let tmp = Tmp108::new_async_with_a0_gnd(mock, delay).await;
assert_eq!(tmp.addr, 0x48);
let mut mock = tmp.destroy();
mock.done();
let mock = Mock::new(&expectations);
let delay = NoopDelay::new();
let tmp = Tmp108::new_async_with_a0_vplus(mock, delay).await;
assert_eq!(tmp.addr, 0x49);
let mut mock = tmp.destroy();
mock.done();
let mock = Mock::new(&expectations);
let delay = NoopDelay::new();
let tmp = Tmp108::new_async_with_a0_sda(mock, delay).await;
assert_eq!(tmp.addr, 0x4a);
let mut mock = tmp.destroy();
mock.done();
let mock = Mock::new(&expectations);
let delay = NoopDelay::new();
let tmp = Tmp108::new_async_with_a0_scl(mock, delay).await;
assert_eq!(tmp.addr, 0x4b);
let mut mock = tmp.destroy();
mock.done();
}
#[tokio::test]
async fn read_temperature_default_address() {
let expectations = vec![
vec![Transaction::write_read(0x48, vec![0x00], vec![0x7f, 0xf0])],
vec![Transaction::write_read(0x48, vec![0x00], vec![0x64, 0x00])],
vec![Transaction::write_read(0x48, vec![0x00], vec![0x50, 0x00])],
vec![Transaction::write_read(0x48, vec![0x00], vec![0x4b, 0x00])],
vec![Transaction::write_read(0x48, vec![0x00], vec![0x32, 0x00])],
vec![Transaction::write_read(0x48, vec![0x00], vec![0x19, 0x00])],
vec![Transaction::write_read(0x48, vec![0x00], vec![0x00, 0x40])],
vec![Transaction::write_read(0x48, vec![0x00], vec![0x00, 0x00])],
vec![Transaction::write_read(0x48, vec![0x00], vec![0xff, 0xc0])],
vec![Transaction::write_read(0x48, vec![0x00], vec![0xe7, 0x00])],
vec![Transaction::write_read(0x48, vec![0x00], vec![0xc9, 0x00])],
];
let temps = vec![127.9375, 100.0, 80.0, 75.0, 50.0, 25.0, 0.25, 0.0, -0.25, -25.0, -55.0];
for (e, t) in expectations.iter().zip(temps.iter()) {
let mock = Mock::new(e);
let delay = NoopDelay::new();
let mut tmp = Tmp108::new_async_with_a0_gnd(mock, delay).await;
let result = tmp.temperature().await;
assert!(result.is_ok());
let temp = result.unwrap();
assert_approx_eq!(temp, *t, 1e-4);
let mut mock = tmp.destroy();
mock.done();
}
}
#[tokio::test]
async fn read_write_configuration_register() {
let expectations = vec![
Transaction::write_read(0x48, vec![0x01], vec![0x10, 0x22]),
Transaction::write(0x48, vec![0x01, 0xb0, 0xfe]),
];
let mock = Mock::new(&expectations);
let delay = NoopDelay::new();
let mut tmp = Tmp108::new_async_with_a0_gnd(mock, delay).await;
let result = tmp.configuration().await;
assert!(result.is_ok());
let cfg = result.unwrap();
assert_eq!(cfg, Default::default());
let cfg = cfg
.with_cm(ConversionMode::Continuous)
.with_tm(ThermostatMode::Interrupt)
.with_fl(true)
.with_fh(true)
.with_cr(ConversionRate::Hertz16)
.with_id(true)
.with_hysteresis(Hysteresis::FourCelsius)
.with_polarity(Polarity::ActiveHigh);
let result = tmp.set_configuration(cfg).await;
assert!(result.is_ok());
let mut mock = tmp.destroy();
mock.done();
}
}