1use crate::bus::{Bus, I2cBus};
2use crate::calibration::{
3 calibrate_pressure, get_twos_complement, process_calibration_coefficients, CalibrationCoeffs,
4};
5use crate::config::{Config, Oversampling};
6use crate::device_internal::{
7 calc_busy_time_units, calc_total_wait_ms, cfg_reg_value, prs_cfg_value, scale_factor,
8 tmp_cfg_value, MAX_BUSYTIME_UNITS, PRODUCT_ID,
9};
10use crate::register::Register;
11use core::marker::PhantomData;
12use embedded_hal::delay::DelayNs;
13use embedded_hal::i2c::I2c;
14
15#[cfg_attr(feature = "defmt", derive(defmt::Format))]
16#[derive(Clone, Copy, Debug, Eq, PartialEq)]
17pub struct Uninit;
18
19#[cfg_attr(feature = "defmt", derive(defmt::Format))]
20#[derive(Clone, Copy, Debug, Eq, PartialEq)]
21pub struct Ready;
22
23#[cfg_attr(feature = "defmt", derive(defmt::Format))]
24#[derive(Clone, Copy, Debug, Eq, PartialEq)]
25pub enum I2cAddress {
26 Primary,
27 Secondary,
28 Custom(u8),
29}
30
31impl I2cAddress {
32 const fn addr(self) -> u8 {
33 match self {
34 Self::Primary => 0x76,
35 Self::Secondary => 0x77,
36 Self::Custom(v) => v,
37 }
38 }
39}
40
41#[cfg_attr(feature = "defmt", derive(defmt::Format))]
42#[derive(Clone, Copy, Debug, Eq, PartialEq)]
43pub enum Poll<T> {
44 Pending { wait_ms: u32 },
45 Ready(T),
46}
47
48#[cfg_attr(feature = "defmt", derive(defmt::Format))]
49#[derive(Clone, Copy, Debug, Eq, PartialEq)]
50pub enum InitStage {
51 SensorReady,
52 TemperatureReady,
53 CoefficientsReady,
54}
55
56#[cfg_attr(feature = "defmt", derive(defmt::Format))]
57#[derive(Clone, Copy, Debug, Eq, PartialEq)]
58pub enum ConfigError {
59 MeasurementBusyTimeExceeded,
60}
61
62#[cfg_attr(feature = "defmt", derive(defmt::Format))]
63#[derive(Debug)]
64pub enum Error<I2cError> {
65 Bus(I2cError),
66 InvalidDevice { id: u8 },
67 InvalidConfig { reason: ConfigError },
68 Timeout { stage: InitStage },
69 NoSampleReady,
70 InitConsumed,
71}
72
73impl<I2cError> From<I2cError> for Error<I2cError> {
74 fn from(value: I2cError) -> Self {
75 Self::Bus(value)
76 }
77}
78
79pub struct TransitionError<I2C, I2cError, State> {
80 error: Error<I2cError>,
81 state: Dps3xx<I2C, State>,
82}
83
84impl<I2C, I2cError, State> TransitionError<I2C, I2cError, State> {
85 pub fn error(&self) -> &Error<I2cError> {
86 &self.error
87 }
88
89 pub fn into_error(self) -> Error<I2cError> {
90 self.error
91 }
92
93 pub fn into_state(self) -> Dps3xx<I2C, State> {
94 self.state
95 }
96
97 pub fn into_parts(self) -> (Error<I2cError>, Dps3xx<I2C, State>) {
98 (self.error, self.state)
99 }
100
101 pub fn release(self) -> I2C {
102 self.state.release()
103 }
104
105 fn with_state(error: Error<I2cError>, state: Dps3xx<I2C, State>) -> Self {
106 Self { error, state }
107 }
108}
109
110impl<I2C, I2cError, State> core::fmt::Debug for TransitionError<I2C, I2cError, State>
111where
112 Error<I2cError>: core::fmt::Debug,
113{
114 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
115 f.debug_struct("TransitionError")
116 .field("error", &self.error)
117 .field("state", &"<Dps3xx>")
118 .finish()
119 }
120}
121
122#[cfg_attr(feature = "defmt", derive(defmt::Format))]
123#[derive(Clone, Copy, Debug, PartialEq)]
124pub struct Sample {
125 pub pressure_pa: f32,
126 pub temperature_c: f32,
127}
128
129#[cfg_attr(feature = "defmt", derive(defmt::Format))]
130#[derive(Clone, Copy, Debug, Eq, PartialEq)]
131pub struct RawSample {
132 pub pressure: i32,
133 pub temperature: i32,
134}
135
136#[cfg_attr(feature = "defmt", derive(defmt::Format))]
137#[derive(Clone, Copy, Debug, PartialEq, Eq)]
138pub struct Status {
139 pub coefficients_ready: bool,
140 pub sensor_ready: bool,
141 pub temperature_ready: bool,
142 pub pressure_ready: bool,
143}
144
145impl Status {
146 fn from_bits(status: u8) -> Self {
147 Self {
148 coefficients_ready: (status & (1 << 7)) != 0,
149 sensor_ready: (status & (1 << 6)) != 0,
150 temperature_ready: (status & (1 << 5)) != 0,
151 pressure_ready: (status & (1 << 4)) != 0,
152 }
153 }
154}
155
156pub struct Dps3xx<I2C, State = Uninit> {
157 bus: I2cBus<I2C>,
158 coeffs: CalibrationCoeffs,
159 config: Config,
160 pressure_scale: f32,
161 temperature_scale: f32,
162 _state: PhantomData<State>,
163}
164
165pub struct Init<I2C> {
166 state: InitState,
167 dps: Option<Dps3xx<I2C, Uninit>>,
168}
169
170enum InitState {
171 Sensor,
172 Temperature,
173 Coefficients,
174}
175
176impl<I2C, S> Dps3xx<I2C, S> {
177 fn map_state<T>(self) -> Dps3xx<I2C, T> {
178 Dps3xx {
179 bus: self.bus,
180 coeffs: self.coeffs,
181 config: self.config,
182 pressure_scale: self.pressure_scale,
183 temperature_scale: self.temperature_scale,
184 _state: PhantomData,
185 }
186 }
187
188 pub fn release(self) -> I2C {
189 self.bus.release()
190 }
191
192 pub fn config(&self) -> Config {
193 self.config
194 }
195}
196
197impl<I2C, I2cError, S> Dps3xx<I2C, S>
198where
199 I2C: I2c<Error = I2cError>,
200{
201 pub fn status(&mut self) -> Result<Status, Error<I2cError>> {
202 Ok(Status::from_bits(self.read_status()?))
203 }
204
205 pub fn product_id(&mut self) -> Result<u8, Error<I2cError>> {
206 self.read_reg(Register::PROD_ID)
207 }
208
209 pub fn reset(mut self) -> Result<Dps3xx<I2C, Uninit>, TransitionError<I2C, I2cError, S>> {
210 if let Err(err) = self.write_reg(Register::RESET, 0b1000_1001) {
211 return Err(TransitionError::with_state(err, self));
212 }
213 Ok(self.map_state())
214 }
215
216 fn read_status(&mut self) -> Result<u8, Error<I2cError>> {
217 Ok(self.read_reg(Register::MEAS_CFG)? & 0xF0)
218 }
219
220 fn write_reg(&mut self, reg: Register, value: u8) -> Result<(), Error<I2cError>> {
221 self.bus.write_reg(reg, value)?;
222 Ok(())
223 }
224
225 fn write_addr(&mut self, addr: u8, value: u8) -> Result<(), Error<I2cError>> {
226 self.bus.write_addr(addr, value)?;
227 Ok(())
228 }
229
230 fn read_reg(&mut self, reg: Register) -> Result<u8, Error<I2cError>> {
231 Ok(self.bus.read_reg(reg)?)
232 }
233
234 fn read_i24(&mut self, reg: Register) -> Result<i32, Error<I2cError>> {
235 let mut bytes = [0_u8; 3];
236 self.bus.read_many(reg, &mut bytes)?;
237 let value = (u32::from(bytes[0]) << 16) | (u32::from(bytes[1]) << 8) | u32::from(bytes[2]);
238 Ok(get_twos_complement(value, 24))
239 }
240
241 fn apply_temp_workaround_registers(&mut self) -> Result<(), Error<I2cError>> {
242 self.write_addr(0x0E, 0xA5)?;
243 self.write_addr(0x0F, 0x96)?;
244 self.write_addr(0x62, 0x02)?;
245 self.write_addr(0x0E, 0x00)?;
246 self.write_addr(0x0F, 0x00)?;
247 Ok(())
248 }
249
250 fn apply_config(&mut self) -> Result<(), Error<I2cError>> {
251 let prs_cfg = self.read_reg(Register::PRS_CFG)?;
252 self.write_reg(Register::PRS_CFG, prs_cfg_value(prs_cfg, &self.config))?;
253
254 let temp_cfg = self.read_reg(Register::TEMP_CFG)?;
255 let coef_source_ext = (self.read_reg(Register::TMP_COEF_SRCE)? & 0x80) != 0;
256 let new_temp_cfg = tmp_cfg_value(temp_cfg, &self.config, coef_source_ext);
257 self.write_reg(Register::TEMP_CFG, new_temp_cfg)?;
258
259 let temp_shift = self.config.temperature.oversampling.reg() > Oversampling::X8.reg();
260 let pres_shift = self.config.pressure.oversampling.reg() > Oversampling::X8.reg();
261 self.write_reg(
262 Register::CFG_REG,
263 cfg_reg_value(&self.config, temp_shift, pres_shift),
264 )?;
265
266 Ok(())
267 }
268
269 fn standby_internal(&mut self) -> Result<(), Error<I2cError>> {
270 self.write_reg(Register::MEAS_CFG, 0)
271 }
272
273 fn read_coefficients(&mut self) -> Result<(), Error<I2cError>> {
274 let mut bytes = [0_u8; 18];
275 self.bus.read_many(Register::COEFF_REG_1, &mut bytes)?;
276 process_calibration_coefficients(&mut self.coeffs, &mut bytes);
277 Ok(())
278 }
279
280 fn validate_config(config: &Config) -> Result<(), Error<I2cError>> {
281 let prs = calc_busy_time_units(
282 config.pressure.rate.reg(),
283 config.pressure.oversampling.reg(),
284 );
285 let tmp = calc_busy_time_units(
286 config.temperature.rate.reg(),
287 config.temperature.oversampling.reg(),
288 );
289 if prs >= MAX_BUSYTIME_UNITS || tmp >= MAX_BUSYTIME_UNITS || prs + tmp >= MAX_BUSYTIME_UNITS
290 {
291 return Err(Error::InvalidConfig {
292 reason: ConfigError::MeasurementBusyTimeExceeded,
293 });
294 }
295 Ok(())
296 }
297
298 fn init_wait_ms(&self) -> u32 {
299 calc_total_wait_ms(
300 self.config.temperature.rate.reg(),
301 self.config.temperature.oversampling.reg(),
302 )
303 }
304}
305
306impl<I2C, I2cError> Dps3xx<I2C, Uninit>
307where
308 I2C: I2c<Error = I2cError>,
309{
310 pub fn new_i2c(i2c: I2C, address: I2cAddress, config: Config) -> Result<Self, Error<I2cError>> {
311 Self::validate_config(&config)?;
312 Ok(Self {
313 bus: I2cBus::new(i2c, address.addr()),
314 coeffs: CalibrationCoeffs::default(),
315 config,
316 pressure_scale: scale_factor(config.pressure.oversampling),
317 temperature_scale: scale_factor(config.temperature.oversampling),
318 _state: PhantomData,
319 })
320 }
321
322 pub fn init(self) -> Result<Init<I2C>, TransitionError<I2C, I2cError, Uninit>> {
323 Ok(Init {
324 state: InitState::Sensor,
325 dps: Some(self),
326 })
327 }
328
329 pub fn init_blocking<D>(
330 self,
331 delay: &mut D,
332 ) -> Result<Dps3xx<I2C, Ready>, TransitionError<I2C, I2cError, Uninit>>
333 where
334 D: DelayNs,
335 {
336 let mut init = self.init()?;
337 let mut remaining = init.config().init_timeout_ms;
338 loop {
339 match init.poll() {
340 Ok(Poll::Pending { wait_ms }) => {
341 if wait_ms > remaining {
342 let stage = init.stage();
343 let state = init.into_uninit();
344 return Err(TransitionError::with_state(Error::Timeout { stage }, state));
345 }
346 delay.delay_ms(wait_ms);
347 remaining -= wait_ms;
348 }
349 Ok(Poll::Ready(sensor)) => return Ok(sensor),
350 Err(err) => return Err(TransitionError::with_state(err, init.into_uninit())),
351 }
352 }
353 }
354}
355
356impl<I2C> Init<I2C> {
357 pub fn cancel(mut self) -> Option<Dps3xx<I2C, Uninit>> {
358 self.dps.take()
359 }
360
361 fn into_uninit(mut self) -> Dps3xx<I2C, Uninit> {
362 self.dps.take().unwrap_or_else(|| unreachable!())
363 }
364
365 pub fn config(&self) -> Config {
366 self.dps.as_ref().map(|dps| dps.config).unwrap_or_default()
367 }
368
369 pub fn stage(&self) -> InitStage {
370 match self.state {
371 InitState::Sensor => InitStage::SensorReady,
372 InitState::Temperature => InitStage::TemperatureReady,
373 InitState::Coefficients => InitStage::CoefficientsReady,
374 }
375 }
376}
377
378impl<I2C, I2cError> Init<I2C>
379where
380 I2C: I2c<Error = I2cError>,
381{
382 pub fn poll(&mut self) -> Result<Poll<Dps3xx<I2C, Ready>>, Error<I2cError>> {
383 let dps = match self.dps.as_mut() {
384 Some(dps) => dps,
385 None => return Err(Error::InitConsumed),
386 };
387
388 match self.state {
389 InitState::Sensor => {
390 let id = dps.product_id()?;
391 if (id & 0xF0) != (PRODUCT_ID & 0xF0) {
392 return Err(Error::InvalidDevice { id });
393 }
394 dps.apply_config()?;
395 dps.standby_internal()?;
396 dps.apply_temp_workaround_registers()?;
397 let status = dps.status()?;
398 if !status.sensor_ready {
399 return Ok(Poll::Pending {
400 wait_ms: dps.init_wait_ms(),
401 });
402 }
403 dps.write_reg(Register::MEAS_CFG, 0b010)?;
404 self.state = InitState::Temperature;
405 Ok(Poll::Pending {
406 wait_ms: dps.init_wait_ms(),
407 })
408 }
409 InitState::Temperature => {
410 if !dps.status()?.temperature_ready {
411 return Ok(Poll::Pending {
412 wait_ms: dps.init_wait_ms(),
413 });
414 }
415 let _ = dps.read_i24(Register::TMP_B2)?;
416 dps.standby_internal()?;
417 self.state = InitState::Coefficients;
418 Ok(Poll::Pending { wait_ms: 10 })
419 }
420 InitState::Coefficients => {
421 if !dps.status()?.coefficients_ready {
422 return Ok(Poll::Pending { wait_ms: 10 });
423 }
424 dps.read_coefficients()?;
425 let ready = self
426 .dps
427 .take()
428 .unwrap_or_else(|| unreachable!())
429 .map_state();
430 Ok(Poll::Ready(ready))
431 }
432 }
433 }
434}
435
436impl<I2C, I2cError> Dps3xx<I2C, Ready>
437where
438 I2C: I2c<Error = I2cError>,
439{
440 pub fn start_background(&mut self) -> Result<(), Error<I2cError>> {
441 self.start_measurement(0b111)
442 }
443
444 pub fn standby(&mut self) -> Result<(), Error<I2cError>> {
445 self.write_reg(Register::MEAS_CFG, 0)
446 }
447
448 pub fn try_read_sample(&mut self) -> Result<Option<Sample>, Error<I2cError>> {
449 let status = self.status()?;
450 if !(status.pressure_ready && status.temperature_ready) {
451 return Ok(None);
452 }
453
454 let raw = self.read_raw_sample()?;
455 let pressure_scaled = raw.pressure as f32 / self.pressure_scale;
456 let temperature_scaled = raw.temperature as f32 / self.temperature_scale;
457
458 Ok(Some(Sample {
459 pressure_pa: calibrate_pressure(&self.coeffs, pressure_scaled, temperature_scaled),
460 temperature_c: (self.coeffs.C0 as f32 * 0.5)
461 + (self.coeffs.C1 as f32 * temperature_scaled),
462 }))
463 }
464
465 pub fn read_sample(&mut self) -> Result<Sample, Error<I2cError>> {
466 self.try_read_sample()?.ok_or(Error::NoSampleReady)
467 }
468
469 pub fn read_raw_sample(&mut self) -> Result<RawSample, Error<I2cError>> {
470 let mut bytes = [0_u8; 6];
471 self.bus.read_many(Register::PSR_B2, &mut bytes)?;
472 let pressure_bits =
473 (u32::from(bytes[0]) << 16) | (u32::from(bytes[1]) << 8) | u32::from(bytes[2]);
474 let temperature_bits =
475 (u32::from(bytes[3]) << 16) | (u32::from(bytes[4]) << 8) | u32::from(bytes[5]);
476
477 Ok(RawSample {
478 pressure: get_twos_complement(pressure_bits, 24),
479 temperature: get_twos_complement(temperature_bits, 24),
480 })
481 }
482
483 fn start_measurement(&mut self, mode_bits: u8) -> Result<(), Error<I2cError>> {
484 let mut meas_cfg = self.read_reg(Register::MEAS_CFG)?;
485 meas_cfg = (meas_cfg & 0xF8) | mode_bits;
486 self.write_reg(Register::MEAS_CFG, meas_cfg)
487 }
488}