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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
// Copyright Claudio Mattera 2022-2024.
//
// Distributed under the MIT License or the Apache 2.0 License at your option.
// See the accompanying files License-MIT.txt and License-Apache-2.0.txt, or
// online at
// https://opensource.org/licenses/MIT
// https://opensource.org/licenses/Apache-2.0

//! Data types and functions for BME280 sensor interface

use log::{debug, warn};

use embedded_hal::delay::DelayNs;
use embedded_hal::i2c::I2c;

use crate::calibration;
use crate::constants::{
    BME280_COMMAND_SOFTRESET, BME280_REGISTER_CHIPID, BME280_REGISTER_CONFIG,
    BME280_REGISTER_CONTROL, BME280_REGISTER_CONTROLHUMID, BME280_REGISTER_HUMIDDATA,
    BME280_REGISTER_PRESSUREDATA, BME280_REGISTER_SOFTRESET, BME280_REGISTER_STATUS,
    BME280_REGISTER_TEMPDATA, DEFAULT_ADDRESS, MODE_SLEEP, SKIPPED_HUMIDITY_OUTPUT,
    SKIPPED_PRESSURE_OUTPUT, SKIPPED_TEMPERATURE_OUTPUT,
};
use crate::sample::{
    humidity_from_number, pressure_from_pascal, temperature_from_celsius, Humidity, Pressure,
    RawSample, Sample, Temperature,
};
use crate::{CalibrationData, Configuration, Status};

/// Interface to BME280 sensor over I²C
///
/// ```no_run
/// # use embedded_hal_mock::eh1::delay::NoopDelay as DelayMock;
/// # use embedded_hal_mock::eh1::i2c::Mock as I2cMock;
/// # use embedded_hal::i2c::ErrorKind;
/// use bme280_rs::{Bme280, Configuration, Oversampling, SensorMode};
/// # let i2c = I2cMock::new(&[]);
/// # let delay = DelayMock;
///
/// let mut bme280 = Bme280::new(i2c, delay);
///
/// bme280.init()?;
///
/// let configuration = Configuration::default()
///     .with_temperature_oversampling(Oversampling::Oversample1)
///     .with_pressure_oversampling(Oversampling::Oversample1)
///     .with_humidity_oversampling(Oversampling::Oversample1)
///     .with_sensor_mode(SensorMode::Normal);
/// bme280.set_sampling_configuration(configuration)?;
///
/// if let Some(temperature) = bme280.read_temperature()? {
///     println!("Temperature: {:?}", temperature);
/// } else {
///     println!("Temperature reading was disabled");
/// }
/// # Ok::<(), ErrorKind>(())
/// ```
pub struct Bme280<I2c, Delay> {
    /// I²C device
    i2c: I2c,

    /// I²C address
    address: u8,

    /// Delay function
    delay: Delay,

    /// Calibration coefficients
    coefficients: CalibrationData,

    /// Sensor configuration
    configuration: Configuration,
}

impl<I2C, D> Bme280<I2C, D>
where
    I2C: I2c,
    D: DelayNs,
{
    /// Create a new sensor using an I²C interface and a delay function using
    /// the sensor's default address [`DEFAULT_ADDRESS`])
    pub fn new(i2c: I2C, delay: D) -> Self {
        Self::new_with_address(i2c, DEFAULT_ADDRESS, delay)
    }

    /// Release the I²C interface
    pub fn release(self) -> I2C {
        self.i2c
    }

    /// Create a new sensor using an I²C interface and a delay function
    pub fn new_with_address(i2c: I2C, address: u8, delay: D) -> Self {
        Self::new_with_coefficients(i2c, address, delay, CalibrationData::default())
    }

    /// Create a new sensor with specific calibration coefficients
    fn new_with_coefficients(
        i2c: I2C,
        address: u8,
        delay: D,
        coefficients: CalibrationData,
    ) -> Self {
        debug!("Creating new BME280 device at address 0x{:x}", address);
        Self {
            i2c,
            address,
            delay,
            coefficients,
            configuration: Configuration::default(),
        }
    }

    /// Initialize the sensor
    ///
    /// Send a soft-reset signal, obtain the calibration coefficients, and set
    /// default sampling configuration.
    ///
    /// Note that the default sampling configuration disables measurement of
    /// temperature, pressure and humidity.
    ///
    /// # Errors
    ///
    /// Return an error if it cannot communicate with the sensor.
    pub fn init(&mut self) -> Result<(), I2C::Error> {
        debug!("Sending soft-reset signal");
        self.write_u8(BME280_REGISTER_SOFTRESET, BME280_COMMAND_SOFTRESET)?;

        debug!("Waiting 10 ms");
        self.delay.delay_ms(10);

        while self.status()?.is_calibrating() {
            debug!("Calibration not complete, waiting 10 ms");
            self.delay.delay_ms(10);
        }

        debug!("Reading coefficients");
        self.read_calibration_coefficients()?;

        debug!("Set sampling");
        let configuration = Configuration::default();
        self.set_sampling_configuration(configuration)?;

        debug!("Waiting 100 ms");
        self.delay.delay_ms(100);

        Ok(())
    }

    /// Obtain the chip id
    ///
    /// The chip id is always [`crate::constants::CHIP_ID`], so this function
    /// can be used to validate that communication with the chip works fine.
    ///
    /// # Errors
    ///
    /// Return an error if it cannot communicate with the sensor.
    pub fn chip_id(&mut self) -> Result<u8, I2C::Error> {
        debug!("Read chip id");
        let chip_id = self.read_u8(BME280_REGISTER_CHIPID)?;

        Ok(chip_id)
    }

    /// Obtain the chip status
    ///
    /// # Errors
    ///
    /// Return an error if it cannot communicate with the sensor.
    pub fn status(&mut self) -> Result<Status, I2C::Error> {
        debug!("Read chip status");
        let status = self.read_u8(BME280_REGISTER_STATUS)?.into();

        Ok(status)
    }

    /// Set the sampling configuration
    ///
    /// # Errors
    ///
    /// Return an error if it cannot communicate with the sensor.
    pub fn set_sampling_configuration(
        &mut self,
        configuration: Configuration,
    ) -> Result<(), I2C::Error> {
        self.configuration = configuration;

        let (config, ctrl_meas, ctrl_hum) = self.configuration.to_lowlevel_configuration();

        // making sure sensor is in sleep mode before setting configuration
        // as it otherwise may be ignored
        self.write_u8(BME280_REGISTER_CONTROL, MODE_SLEEP)?;

        // you must make sure to also set REGISTER_CONTROL after setting the
        // CONTROLHUMID register, otherwise the values won't be applied (see
        // DS 5.4.3)
        self.write_u8(BME280_REGISTER_CONTROLHUMID, ctrl_hum.into())?;
        self.write_u8(BME280_REGISTER_CONFIG, config.into())?;
        self.write_u8(BME280_REGISTER_CONTROL, ctrl_meas.into())?;

        Ok(())
    }

    /// Take a forced measurement
    ///
    /// When the chip is set to work in forced mode, it goes back to sleep
    /// after every measurement.
    /// It must be set again to forced mode in order to force a new
    /// measurement.
    ///
    /// # Errors
    ///
    /// Return an error if it cannot communicate with the sensor.
    pub fn take_forced_measurement(&mut self) -> Result<bool, I2C::Error> {
        if self.configuration.is_forced() {
            debug!("Forcing taking a measurement");

            let (_config, ctrl_meas, _ctrl_hum) = self.configuration.to_lowlevel_configuration();
            self.write_u8(BME280_REGISTER_CONTROL, ctrl_meas.into())?;

            for _ in 0..10 {
                if !self.status()?.is_measuring() {
                    break;
                }

                debug!("Measuring not complete, waiting 10 ms");
                self.delay.delay_ms(10);
            }

            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Read a raw sample from sensor
    ///
    /// Raw sample must be converted to human-readable quantities using
    /// compensation formulas from the data sheet.
    fn read_raw_sample(&mut self) -> Result<RawSample, I2C::Error> {
        let buffer: [u8; 1] = [BME280_REGISTER_PRESSUREDATA];
        let mut buf: [u8; 8] = [0; 8];
        self.i2c.write_read(self.address, &buffer, &mut buf)?;

        // msb [7:0] = p[19:12]
        // lsb [7:0] = p[11:4]
        // xlsb[7:4] = p[3:0]
        let adc_p: u32 =
            (u32::from(buf[0]) << 12) | (u32::from(buf[1]) << 4) | (u32::from(buf[2]) >> 4);
        // msb [7:0] = t[19:12]
        // lsb [7:0] = t[11:4]
        // xlsb[7:4] = t[3:0]
        let adc_t: u32 =
            (u32::from(buf[3]) << 12) | (u32::from(buf[4]) << 4) | (u32::from(buf[5]) >> 4);
        // msb [7:0] = h[15:8]
        // lsb [7:0] = h[7:0]
        let adc_h: u16 = (u16::from(buf[6]) << 8) | u16::from(buf[7]);

        Ok(RawSample {
            adc_t: if adc_t == SKIPPED_TEMPERATURE_OUTPUT {
                None
            } else {
                Some(adc_t)
            },
            adc_p: if adc_p == SKIPPED_PRESSURE_OUTPUT {
                None
            } else {
                Some(adc_p)
            },
            adc_h: if adc_h == SKIPPED_HUMIDITY_OUTPUT {
                None
            } else {
                Some(adc_h)
            },
        })
    }

    /// Read a sample of temperature, pressure and humidity
    ///
    /// Measures that are disabled in the sampling configuration have value
    /// `None`.
    ///
    /// # Errors
    ///
    /// Return an error if it cannot communicate with the sensor.
    pub fn read_sample(&mut self) -> Result<Sample, I2C::Error> {
        let RawSample {
            adc_t,
            adc_p,
            adc_h,
        } = self.read_raw_sample()?;

        if let Some(adc_t) = adc_t {
            let t_fine = self.coefficients.compensate_temperature(adc_t);
            let t = Some(Self::temperature_fine_to_temperature(t_fine));
            let p = adc_p.map(|adc_p| self.coefficients.compensate_pressure(adc_p, t_fine));
            let h = adc_h.map(|adc_h| self.coefficients.compensate_humidity(adc_h, t_fine));

            let temperature = t;

            #[allow(clippy::cast_precision_loss)] // Acceptable precision loss
            let pressure = p.map(|p| p as f32 / 256.0);
            let pressure = pressure.map(pressure_from_pascal);
            #[allow(clippy::cast_precision_loss)] // Acceptable precision loss
            let humidity = h.map(|h| h as f32 / 1024.0);
            let humidity = humidity.map(humidity_from_number);

            Ok(Sample {
                temperature,
                pressure,
                humidity,
            })
        } else {
            warn!("Temperature measurement is disabled");

            Ok(Sample::default())
        }
    }

    /// Compute raw temperature from human-readable temperature
    fn temperature_fine_to_temperature(t_fine: i32) -> Temperature {
        let t = (t_fine * 5 + 128) >> 8;

        #[allow(clippy::cast_precision_loss)] // Acceptable precision loss
        let t = t as f32;

        temperature_from_celsius(t / 100.0)
    }

    /// Read a sample of temperature
    ///
    /// If temperature is disabled in the sampling configuration, return `None`.
    ///
    /// # Errors
    ///
    /// Return an error if it cannot communicate with the sensor.
    pub fn read_temperature(&mut self) -> Result<Option<Temperature>, I2C::Error> {
        if let Some(t_fine) = self.read_temperature_fine()? {
            Ok(Some(Self::temperature_fine_to_temperature(t_fine)))
        } else {
            Ok(None)
        }
    }

    /// Read temperature from sensor
    fn read_temperature_fine(&mut self) -> Result<Option<i32>, I2C::Error> {
        let adc_t = self.read_raw_temperature()?;
        let t_fine = adc_t.map(|adc_t| self.coefficients.compensate_temperature(adc_t));
        Ok(t_fine)
    }

    /// Read raw temperature from sensor
    ///
    /// Raw temperature must be converted to human-readable temperature using
    /// compensation formulas from the data sheet.
    fn read_raw_temperature(&mut self) -> Result<Option<u32>, I2C::Error> {
        let adc_t = self.read_u24(BME280_REGISTER_TEMPDATA)?;

        if adc_t == SKIPPED_TEMPERATURE_OUTPUT {
            Ok(None)
        } else {
            Ok(Some(adc_t))
        }
    }

    /// Read a sample of pressure
    ///
    /// The temperature value, necessary to compute the compensated pressure
    /// value, is also read from the sensor.
    ///
    /// If pressure is disabled in the sampling configuration, return `None`.
    ///
    /// # Errors
    ///
    /// Return an error if it cannot communicate with the sensor.
    pub fn read_pressure(&mut self) -> Result<Option<Pressure>, I2C::Error> {
        if let Some(t_fine) = self.read_temperature_fine()? {
            self.read_pressure_with_temperature_fine(t_fine)
        } else {
            warn!("Pressure measurement is disabled");
            Ok(None)
        }
    }

    /// Read a sample of pressure with a user-specified temperature value
    ///
    /// Unlike in [`Self::read_pressure()`], this function does not take the
    /// temperature from the sensor, so it can be used if the temperature
    /// is already known.
    ///
    /// If pressure is disabled in the sampling configuration, return `None`.
    ///
    /// # Errors
    ///
    /// Return an error if it cannot communicate with the sensor.
    pub fn read_pressure_with_temperature(
        &mut self,
        temperature: f32,
    ) -> Result<Option<Pressure>, I2C::Error> {
        #[allow(clippy::cast_possible_truncation)] // Acceptable truncation
        let t = (temperature * 100.0) as i32;
        let t_fine = ((t << 8) - 128) / 5;
        self.read_pressure_with_temperature_fine(t_fine)
    }

    /// Read pressure from sensor usings pecific temperature reference
    fn read_pressure_with_temperature_fine(
        &mut self,
        t_fine: i32,
    ) -> Result<Option<Pressure>, I2C::Error> {
        let adc_p = self.read_raw_pressure()?;
        let p = adc_p.map(|adc_p| {
            let p = self.coefficients.compensate_pressure(adc_p, t_fine);

            #[allow(clippy::cast_precision_loss)] // Acceptable precision loss
            let p = p as f32;

            pressure_from_pascal(p / 256.0)
        });
        Ok(p)
    }

    /// Read raw pressure from sensor
    ///
    /// Raw pressure must be converted to human-readable pressure using
    /// compensation formulas from the data sheet.
    fn read_raw_pressure(&mut self) -> Result<Option<u32>, I2C::Error> {
        let adc_p = self.read_u24(BME280_REGISTER_PRESSUREDATA)?;

        if adc_p == SKIPPED_PRESSURE_OUTPUT {
            Ok(None)
        } else {
            Ok(Some(adc_p))
        }
    }

    /// Read a sample of humidity
    ///
    /// The temperature value, necessary to compute the compensated pressure
    /// value, is also read from the sensor.
    ///
    /// If humidity is disabled in the sampling configuration, return `None`.
    ///
    /// # Errors
    ///
    /// Return an error if it cannot communicate with the sensor.
    pub fn read_humidity(&mut self) -> Result<Option<Humidity>, I2C::Error> {
        if let Some(t_fine) = self.read_temperature_fine()? {
            self.read_humidity_with_temperature_fine(t_fine)
        } else {
            warn!("Humidity measurement is disabled");
            Ok(None)
        }
    }

    /// Read a sample of humidity with a user-specified temperature value
    ///
    /// Unlike in [`Self::read_humidity()`], this function does not take the
    /// temperature from the sensor, so it can be used if the temperature
    /// is already known.
    ///
    /// If humidity is disabled in the sampling configuration, return `None`.
    ///
    /// # Errors
    ///
    /// Return an error if it cannot communicate with the sensor.
    pub fn read_humidity_with_temperature(
        &mut self,
        temperature: f32,
    ) -> Result<Option<Humidity>, I2C::Error> {
        #[allow(clippy::cast_possible_truncation)] // Acceptable truncation
        let t = (temperature * 100.0) as i32;
        let t_fine = ((t << 8) - 128) / 5;
        self.read_humidity_with_temperature_fine(t_fine)
    }

    /// Read humidity from sensor using specific reference temperature
    fn read_humidity_with_temperature_fine(
        &mut self,
        t_fine: i32,
    ) -> Result<Option<Humidity>, I2C::Error> {
        let adc_h = self.read_raw_humidity()?;
        let h = adc_h.map(|adc_h| {
            let h = self.coefficients.compensate_humidity(adc_h, t_fine);

            #[allow(clippy::cast_precision_loss)] // Acceptable precision loss
            let h = h as f32;

            humidity_from_number(h / 1024.0)
        });
        Ok(h)
    }

    /// Read raw humidity from sensor
    ///
    /// Raw humidity must be converted to human-readable humidity using
    /// compensation formulas from the data sheet.
    fn read_raw_humidity(&mut self) -> Result<Option<u16>, I2C::Error> {
        let adc_h = self.read_u16(BME280_REGISTER_HUMIDDATA)?;

        if adc_h == SKIPPED_HUMIDITY_OUTPUT {
            Ok(None)
        } else {
            Ok(Some(adc_h))
        }
    }

    /// Read calibration coefficients from sensor
    fn read_calibration_coefficients(&mut self) -> Result<(), I2C::Error> {
        let buffer: [u8; 1] = [calibration::FIRST_REGISTER];

        let mut out: [u8; calibration::TOTAL_LENGTH] = [0; calibration::TOTAL_LENGTH];
        self.i2c.write_read(
            self.address,
            &buffer,
            &mut out[0..calibration::FIRST_LENGTH],
        )?;

        let buffer: [u8; 1] = [calibration::SECOND_REGISTER];
        self.i2c.write_read(
            self.address,
            &buffer,
            &mut out[calibration::FIRST_LENGTH..calibration::TOTAL_LENGTH],
        )?;

        self.coefficients = (&out).into();

        Ok(())
    }

    /// Write an unsigned byte to an I²C register
    fn write_u8(&mut self, register: u8, value: u8) -> Result<(), I2C::Error> {
        let buffer: [u8; 2] = [register, value];
        self.i2c.write(self.address, &buffer)?;
        Ok(())
    }

    /// Write an unsigned byte from an I²C register
    fn read_u8(&mut self, register: u8) -> Result<u8, I2C::Error> {
        let buffer: [u8; 1] = [register];
        let mut output_buffer: [u8; 1] = [0];
        self.i2c
            .write_read(self.address, &buffer, &mut output_buffer)?;
        Ok(output_buffer[0])
    }

    /// Write two unsigned bytes to an I²C register
    fn read_u16(&mut self, register: u8) -> Result<u16, I2C::Error> {
        let buffer: [u8; 1] = [register];
        let mut output_buffer: [u8; 2] = [0, 0];
        self.i2c
            .write_read(self.address, &buffer, &mut output_buffer)?;
        Ok(u16::from(output_buffer[0]) << 8 | u16::from(output_buffer[1]))
    }

    /// Write three unsigned bytes to an I²C register
    fn read_u24(&mut self, register: u8) -> Result<u32, I2C::Error> {
        let buffer: [u8; 1] = [register];
        let mut output_buffer: [u8; 3] = [0, 0, 0];
        self.i2c
            .write_read(self.address, &buffer, &mut output_buffer)?;
        Ok(u32::from(output_buffer[0]) << 12
            | u32::from(output_buffer[1]) << 4
            | u32::from(output_buffer[2]) >> 4)
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::panic_in_result_fn)]

    use super::*;

    use embedded_hal::i2c::ErrorKind;

    use embedded_hal_mock::eh1::delay::NoopDelay as DelayMock;
    use embedded_hal_mock::eh1::i2c::{Mock as I2cMock, Transaction as I2cTransaction};

    use crate::calibration::TEST_CALIBRATION_DATA;
    use crate::constants::CHIP_ID;

    #[test]
    fn test_chip_id() -> Result<(), ErrorKind> {
        let expectations = [I2cTransaction::write_read(
            DEFAULT_ADDRESS,
            vec![BME280_REGISTER_CHIPID],
            vec![CHIP_ID],
        )];
        let i2c = I2cMock::new(&expectations);

        let mut bme280 = Bme280::new(i2c, DelayMock);

        let chip_id = bme280.chip_id()?;

        assert_eq!(chip_id, CHIP_ID);

        bme280.release().done();
        Ok(())
    }

    #[test]
    fn test_chip_status() -> Result<(), ErrorKind> {
        let expectations = [I2cTransaction::write_read(
            DEFAULT_ADDRESS,
            vec![BME280_REGISTER_STATUS],
            vec![0x00],
        )];
        let i2c = I2cMock::new(&expectations);

        let mut bme280 = Bme280::new(i2c, DelayMock);

        let status = bme280.status()?;

        assert!(!status.is_measuring());
        assert!(!status.is_calibrating());

        bme280.release().done();
        Ok(())
    }

    #[test]
    fn test_chip_status_measuring() -> Result<(), ErrorKind> {
        let expectations = [I2cTransaction::write_read(
            DEFAULT_ADDRESS,
            vec![BME280_REGISTER_STATUS],
            vec![0b0000_0100],
        )];
        let i2c = I2cMock::new(&expectations);

        let mut bme280 = Bme280::new(i2c, DelayMock);

        let status = bme280.status()?;

        assert!(status.is_measuring());
        assert!(!status.is_calibrating());

        bme280.release().done();
        Ok(())
    }

    #[test]
    fn test_read_temperature_disabled() -> Result<(), ErrorKind> {
        let expectations = [I2cTransaction::write_read(
            DEFAULT_ADDRESS,
            vec![BME280_REGISTER_TEMPDATA],
            vec![0x80, 0x00, 0x00],
        )];
        let i2c = I2cMock::new(&expectations);

        let mut bme280 = Bme280::new_with_coefficients(
            i2c,
            DEFAULT_ADDRESS,
            DelayMock,
            TEST_CALIBRATION_DATA.clone(),
        );

        let expected = None;

        let temperature = bme280.read_temperature()?;

        assert_eq!(temperature, expected);

        bme280.release().done();
        Ok(())
    }

    #[test]
    fn test_read_temperature() -> Result<(), ErrorKind> {
        let expectations = [I2cTransaction::write_read(
            DEFAULT_ADDRESS,
            vec![BME280_REGISTER_TEMPDATA],
            vec![0x84, 0x47, 0x00],
        )];
        let i2c = I2cMock::new(&expectations);

        let mut bme280 = Bme280::new_with_coefficients(
            i2c,
            DEFAULT_ADDRESS,
            DelayMock,
            TEST_CALIBRATION_DATA.clone(),
        );

        let expected = Some(temperature_from_celsius(27.33));

        let temperature = bme280.read_temperature()?;

        assert_eq!(temperature, expected);

        bme280.release().done();
        Ok(())
    }

    #[test]
    fn test_read_pressure_disabled() -> Result<(), ErrorKind> {
        let expectations = [
            I2cTransaction::write_read(
                DEFAULT_ADDRESS,
                vec![BME280_REGISTER_TEMPDATA],
                vec![0x84, 0x47, 0x00],
            ),
            I2cTransaction::write_read(
                DEFAULT_ADDRESS,
                vec![BME280_REGISTER_PRESSUREDATA],
                vec![0x80, 0x00, 0x00],
            ),
        ];
        let i2c = I2cMock::new(&expectations);

        let mut bme280 = Bme280::new_with_coefficients(
            i2c,
            DEFAULT_ADDRESS,
            DelayMock,
            TEST_CALIBRATION_DATA.clone(),
        );

        let expected = None;

        let pressure = bme280.read_pressure()?;

        assert_eq!(pressure, expected);

        bme280.release().done();
        Ok(())
    }

    #[test]
    fn test_read_pressure() -> Result<(), ErrorKind> {
        let expectations = [
            I2cTransaction::write_read(
                DEFAULT_ADDRESS,
                vec![BME280_REGISTER_TEMPDATA],
                vec![0x84, 0x47, 0x00],
            ),
            I2cTransaction::write_read(
                DEFAULT_ADDRESS,
                vec![BME280_REGISTER_PRESSUREDATA],
                vec![0x4f, 0x50, 0x00],
            ),
        ];
        let i2c = I2cMock::new(&expectations);

        let mut bme280 = Bme280::new_with_coefficients(
            i2c,
            DEFAULT_ADDRESS,
            DelayMock,
            TEST_CALIBRATION_DATA.clone(),
        );

        let expected = Some(pressure_from_pascal(101_233.016));

        let pressure = bme280.read_pressure()?;

        assert_eq!(pressure, expected);

        bme280.release().done();
        Ok(())
    }

    #[test]
    fn test_read_humidity_disabled() -> Result<(), ErrorKind> {
        let expectations = [
            I2cTransaction::write_read(
                DEFAULT_ADDRESS,
                vec![BME280_REGISTER_TEMPDATA],
                vec![0x84, 0x47, 0x00],
            ),
            I2cTransaction::write_read(
                DEFAULT_ADDRESS,
                vec![BME280_REGISTER_HUMIDDATA],
                vec![0x80, 0x00],
            ),
        ];
        let i2c = I2cMock::new(&expectations);

        let mut bme280 = Bme280::new_with_coefficients(
            i2c,
            DEFAULT_ADDRESS,
            DelayMock,
            TEST_CALIBRATION_DATA.clone(),
        );

        let expected = None;

        let humidity = bme280.read_humidity()?;

        assert_eq!(humidity, expected);

        bme280.release().done();
        Ok(())
    }

    #[test]
    fn test_read_humidity() -> Result<(), ErrorKind> {
        let expectations = [
            I2cTransaction::write_read(
                DEFAULT_ADDRESS,
                vec![BME280_REGISTER_TEMPDATA],
                vec![0x84, 0x47, 0x00],
            ),
            I2cTransaction::write_read(
                DEFAULT_ADDRESS,
                vec![BME280_REGISTER_HUMIDDATA],
                vec![0x60, 0x02],
            ),
        ];
        let i2c = I2cMock::new(&expectations);

        let mut bme280 = Bme280::new_with_coefficients(
            i2c,
            DEFAULT_ADDRESS,
            DelayMock,
            TEST_CALIBRATION_DATA.clone(),
        );

        let expected = Some(humidity_from_number(34.854_492));

        let humidity = bme280.read_humidity()?;

        assert_eq!(humidity, expected);

        bme280.release().done();
        Ok(())
    }
}