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
// 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 configuration

/// Chip configuration
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Configuration {
    /// Standby time settings
    standby_time: StandbyTime,

    /// Filter settings
    filter: Filter,

    /// SPI3w option
    spi3w: bool,

    /// Temperature oversampling settings
    temperature_oversampling: Oversampling,

    /// Pressure oversampling settings
    pressure_oversampling: Oversampling,

    /// Humidity oversampling settings
    humidity_oversampling: Oversampling,

    /// Sensor mode
    sensor_mode: SensorMode,
}

impl From<&Configuration> for (Config, ControlMeasurement, ControlHumidity) {
    fn from(configuration: &Configuration) -> Self {
        let config = (
            configuration.standby_time,
            configuration.filter,
            configuration.spi3w,
        )
            .into();
        let control_measurement = (
            configuration.temperature_oversampling,
            configuration.pressure_oversampling,
            configuration.sensor_mode,
        )
            .into();
        let control_humidity = configuration.humidity_oversampling.into();
        (config, control_measurement, control_humidity)
    }
}

impl Configuration {
    /// Convert to low-level configuration items
    #[doc(hidden)]
    #[must_use]
    pub(crate) fn to_lowlevel_configuration(
        &self,
    ) -> (Config, ControlMeasurement, ControlHumidity) {
        self.into()
    }

    /// Set the standby time
    #[must_use]
    pub fn with_standby_time(mut self, standby_time: StandbyTime) -> Self {
        self.standby_time = standby_time;
        self
    }

    /// Set the filter
    #[must_use]
    pub fn with_filter(mut self, filter: Filter) -> Self {
        self.filter = filter;
        self
    }

    /// Set the SPI3w option
    #[doc(hidden)]
    #[allow(unused)]
    pub(crate) fn with_spi3w(mut self, spi3w: bool) -> Self {
        self.spi3w = spi3w;
        self
    }

    /// Set the oversampling factor for temperature
    #[must_use]
    pub fn with_temperature_oversampling(mut self, temperature_oversampling: Oversampling) -> Self {
        self.temperature_oversampling = temperature_oversampling;
        self
    }

    /// Set the oversampling factor for pressure
    #[must_use]
    pub fn with_pressure_oversampling(mut self, pressure_oversampling: Oversampling) -> Self {
        self.pressure_oversampling = pressure_oversampling;
        self
    }

    /// Set the oversampling factor for humidity
    #[must_use]
    pub fn with_humidity_oversampling(mut self, humidity_oversampling: Oversampling) -> Self {
        self.humidity_oversampling = humidity_oversampling;
        self
    }

    /// Set the sensor mode
    #[must_use]
    pub fn with_sensor_mode(mut self, sensor_mode: SensorMode) -> Self {
        self.sensor_mode = sensor_mode;
        self
    }

    /// Check if chip is in forced mode
    #[doc(hidden)]
    pub(crate) fn is_forced(&self) -> bool {
        self.sensor_mode == SensorMode::Forced
    }
}

/// Chip status
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub struct Status {
    /// True if the sensor is performing a measurement
    measuring: bool,

    /// True if the sensor is performing calibration
    calibrating: bool,
}

impl Status {
    /// Return `true` if the chip is measuring data
    #[must_use]
    pub fn is_measuring(&self) -> bool {
        self.measuring
    }

    /// Return `true` if the chip is computing calibration data
    #[must_use]
    pub fn is_calibrating(&self) -> bool {
        self.calibrating
    }
}

impl core::fmt::Display for Status {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        if self.calibrating && self.measuring {
            write!(f, "calibrating and measuring")?;
        } else if self.calibrating {
            write!(f, "calibrating")?;
        } else if self.measuring {
            write!(f, "measuring")?;
        } else {
            write!(f, "ready")?;
        }
        Ok(())
    }
}

impl From<u8> for Status {
    fn from(arg: u8) -> Self {
        Self {
            measuring: (arg & 0b0000_0100) != 0,
            calibrating: (arg & 0b0000_0001) != 0,
        }
    }
}

/// Oversampling setting
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Oversampling {
    /// Skip the measurement altogether
    Skip,

    /// Take a single sample
    Oversample1,

    /// Take two samples
    Oversample2,

    /// Take four samples
    Oversample4,

    /// Take eight samples
    Oversample8,

    /// Take sixteen samples
    Oversample16,
}

impl Oversampling {
    /// Convert to binary value
    #[doc(hidden)]
    pub(crate) fn to_value(self) -> u8 {
        match self {
            Self::Skip => 0b000,
            Self::Oversample1 => 0b001,
            Self::Oversample2 => 0b010,
            Self::Oversample4 => 0b011,
            Self::Oversample8 => 0b100,
            Self::Oversample16 => 0b101,
        }
    }
}

impl Default for Oversampling {
    fn default() -> Self {
        Self::Skip
    }
}

/// Sensor working mode
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum SensorMode {
    /// Sleep mode
    ///
    /// The sensor is not active.
    Sleep,

    /// Forced mode
    ///
    /// The sensor takes a single sample and then enters sleep mode.
    Forced,

    /// Normal mode
    ///
    /// The sensor takes samples at regular times, and returns the latest one
    /// when queried.
    /// The time between measurements can be specified as [`StandbyTime`]
    Normal,
}

impl SensorMode {
    /// Convert to binary value
    #[doc(hidden)]
    pub(crate) fn to_value(self) -> u8 {
        match self {
            Self::Sleep => 0b00,
            Self::Forced => 0b01,
            Self::Normal => 0b11,
        }
    }
}

impl Default for SensorMode {
    fn default() -> Self {
        Self::Sleep
    }
}

/// Standby time between readings in normal mode
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum StandbyTime {
    /// 0.5 ms
    Millis0_5,

    /// 10 ms
    Millis10,

    /// 20 ms
    Millis20,

    /// 62.5 ms
    Millis62_5,

    /// 125 ms
    Millis125,

    /// 250 ms
    Millis250,

    /// 500 ms
    Millis500,

    /// 1000 ms
    Millis1000,
}

impl StandbyTime {
    /// Convert to binary value
    #[doc(hidden)]
    pub(crate) fn to_value(self) -> u8 {
        match self {
            Self::Millis0_5 => 0b000,
            Self::Millis10 => 0b110,
            Self::Millis20 => 0b111,
            Self::Millis62_5 => 0b001,
            Self::Millis125 => 0b010,
            Self::Millis250 => 0b011,
            Self::Millis500 => 0b100,
            Self::Millis1000 => 0b101,
        }
    }
}

impl Default for StandbyTime {
    fn default() -> Self {
        Self::Millis0_5
    }
}

/// Filter coefficient
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Filter {
    /// No filtering
    Off,

    /// Filter ×2
    Filter2,

    /// Filter ×4
    Filter4,

    /// Filter ×8
    Filter8,

    /// Filter ×16
    Filter16,
}

impl Filter {
    /// Convert to binary value
    #[doc(hidden)]
    pub(crate) fn to_value(self) -> u8 {
        match self {
            Self::Off => 0b000,
            Self::Filter2 => 0b001,
            Self::Filter4 => 0b010,
            Self::Filter8 => 0b011,
            Self::Filter16 => 0b100,
        }
    }
}

impl Default for Filter {
    fn default() -> Self {
        Self::Off
    }
}

/// Low-level config item
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub(crate) struct Config(u8);

impl From<(StandbyTime, Filter, bool)> for Config {
    fn from((standby_time, filter, spi3w): (StandbyTime, Filter, bool)) -> Self {
        let standby_time = standby_time.to_value() & 0b111;
        let filter = filter.to_value() & 0b111;
        let spi3w = u8::from(spi3w) & 0b1;
        Self(standby_time << 5 | filter << 2 | spi3w)
    }
}

impl From<Config> for u8 {
    fn from(config: Config) -> Self {
        config.0
    }
}

/// Low-level control humidity item
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub(crate) struct ControlHumidity(u8);

impl From<Oversampling> for ControlHumidity {
    fn from(humidity_oversampling: Oversampling) -> Self {
        Self(humidity_oversampling.to_value() & 0b111)
    }
}

impl From<ControlHumidity> for u8 {
    fn from(ctrl_hum: ControlHumidity) -> Self {
        ctrl_hum.0
    }
}

/// Low-level control measurement item
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub(crate) struct ControlMeasurement(u8);

impl From<(Oversampling, Oversampling, SensorMode)> for ControlMeasurement {
    fn from(
        (oversampling_temperature, oversampling_pressure, sensor_mode): (
            Oversampling,
            Oversampling,
            SensorMode,
        ),
    ) -> Self {
        let oversampling_temperature = oversampling_temperature.to_value() & 0b111;
        let oversampling_pressure = oversampling_pressure.to_value() & 0b111;
        let sensor_mode = sensor_mode.to_value() & 0b11;
        Self(oversampling_temperature << 5 | oversampling_pressure << 2 | sensor_mode)
    }
}

impl From<ControlMeasurement> for u8 {
    fn from(ctrl_meas: ControlMeasurement) -> Self {
        ctrl_meas.0
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_status() {
        let raw_status = 0b0000_0000;
        let status: Status = raw_status.into();

        let expected = Status {
            measuring: false,
            calibrating: false,
        };

        assert_eq!(status, expected);
    }

    #[test]
    fn test_status_calibrating() {
        let raw_status = 0b0000_0001;
        let status: Status = raw_status.into();

        let expected = Status {
            measuring: false,
            calibrating: true,
        };

        assert_eq!(status, expected);
    }

    #[test]
    fn test_standby() {
        let standby = StandbyTime::Millis125;

        let expected = 0b010;
        let actual = standby.to_value();

        assert_eq!(actual, expected, "0b{actual:03b} == 0b{expected:03b}");
    }

    #[test]
    fn test_config() {
        let configuration = Configuration::default()
            .with_standby_time(StandbyTime::Millis125)
            .with_filter(Filter::Filter2)
            .with_spi3w(true);
        let (config, _ctrl_meas, _ctrl_hum) = configuration.to_lowlevel_configuration();
        let actual: u8 = config.into();

        let expected = 0b0100_0101;

        assert_eq!(actual, expected, "0b{actual:08b} == 0b{expected:08b}");
    }

    #[test]
    fn test_control_measurement() {
        let configuration = Configuration::default()
            .with_temperature_oversampling(Oversampling::Oversample8)
            .with_pressure_oversampling(Oversampling::Oversample4)
            .with_sensor_mode(SensorMode::Normal);
        let (_config, ctrl_meas, _ctrl_hum) = configuration.to_lowlevel_configuration();
        let actual: u8 = ctrl_meas.into();

        let expected = 0b1000_1111;

        assert_eq!(actual, expected, "0b{actual:08b} == 0b{expected:08b}");
    }

    #[test]
    fn test_control_humidity() {
        let configuration =
            Configuration::default().with_humidity_oversampling(Oversampling::Oversample8);
        let (_config, _ctrl_meas, ctrl_hum) = configuration.to_lowlevel_configuration();
        let actual: u8 = ctrl_hum.into();

        let expected = 0b100;

        assert_eq!(actual, expected, "0b{actual:03b} == 0b{expected:03b}");
    }
}