scd30_i2c 1.0.0

Rust Trait for SCD30 device I2C interface related operations.
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
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
// Copyright 2024, F. Stan
//
// Licensed under the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// This file may not be copied, modified, or distributed
// except according to those terms.

use i2cdev::core::*;
use i2cdev::linux::{LinuxI2CDevice, LinuxI2CError};
use std::error::Error;
use std::fmt;
use std::io;
use std::{thread, time};

///
///SCD30 error enum, including Io error from
///i2cdev library. ChecksumError when a crc 8
///checksum does not correspond with the calculated
///one. CommunicationError when read or write operations
///fails
///
#[derive(Debug)]
pub enum Scd30Error {
    /// Input/output error
    Io(io::Error),
    /// ChecksumError when the checksum does not correspond to calculated checksum using crc
    /// algorithm
    ChecksumError,
    /// Communication error when the trait tries to read or write to scd30 device
    ComunicationError,
}
///Implementation for Io error to Scd30Error
impl From<io::Error> for Scd30Error {
    fn from(e: io::Error) -> Self {
        Scd30Error::Io(e)
    }
}
///Implementation of display for SCD30Error
impl fmt::Display for Scd30Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Scd30Error::ChecksumError => fmt::Display::fmt("Checksum Error found", f),
            Scd30Error::Io(ref e) => fmt::Display::fmt(e, f),
            Scd30Error::ComunicationError => fmt::Display::fmt("Comunication error with device", f),
        }
    }
}
///Implementation for Error to SCD30
impl Error for Scd30Error {}

/// SCD30 Struct, wraps a LinuxI2CDevice structs
/// and has implemented related SCD30 operations
///
pub struct Scd30 {
    pub i2cdev: LinuxI2CDevice,
}

/// Implementation of SCD30 related
/// operations
///
///
impl Scd30 {
    /// Create a new SCD30 Struct
    ///
    /// Tries to create the device on standard address 0x61.
    /// If fails, return an LinuxI2CError from i2cdev
    ///
    pub fn new() -> Result<Scd30, LinuxI2CError> {
        let device = LinuxI2CDevice::new("/dev/i2c-1", 0x61)?;
        Ok(Scd30 { i2cdev: device })
    }

    /// Checksum checker function
    /// Thanks to [RequestForCoffee](https://github.com/RequestForCoffee)
    /// for the python version of scd30 communication.
    /// This code is an adaptation of the python version.
    /// More info regarding the [algorithm](https://en.wikipedia.org/wiki/Computation_of_cyclic_redundancy_checks)
    ///
    pub fn crc8(message: &Vec<u8>) -> u8 {
        let mut rem = 0xFF;
        let polynomial = 0x31;
        for byte in message {
            rem ^= byte;
            for _ in 0..8 {
                if (rem & 0x80) != 0 {
                    rem = (rem << 1) ^ polynomial;
                } else {
                    rem = rem << 1
                }
                rem &= 0xFF;
            }
        }
        rem
    }

    /// Checks on 4 bytes data if the checksum is correct
    ///
    /// The parameter is a 6 byte array, the first two and the checksum
    /// and the other two with the ckecksum
    ///
    fn check_crc_in_bytes(co2: &[u8]) -> bool {
        //Splited in two two bytes with checksum
        let first_crc = Scd30::crc8(&vec![co2[0], co2[1]]);
        let second_crc = Scd30::crc8(&vec![co2[3], co2[4]]);

        first_crc == co2[2] && second_crc == co2[5]
    }

    /// Checks the firmware version of the SCD30 device.
    /// If fails, return SCD30Error.
    /// Else returns the firmware version.
    ///
    pub fn check_firmware(&mut self) -> Result<u16, Scd30Error> {
        let buffer: [u8; 2] = [0xd1, 0x00];
        match self.i2cdev.write(&buffer) {
            Ok(_) => {
                let ten_millis = time::Duration::from_millis(30);
                thread::sleep(ten_millis);
                // Read data from the selected register
                let mut data_buffer: [u8; 3] = [0; 3];
                match self.i2cdev.read(&mut data_buffer) {
                    Ok(_) => {
                        if data_buffer[2] == Scd30::crc8(&vec![data_buffer[0], data_buffer[1]]) {
                            Ok(u16::from_be_bytes([data_buffer[0], data_buffer[1]]))
                        } else {
                            Err(Scd30Error::ChecksumError)
                        }
                    }
                    Err(_) => Err(Scd30Error::ComunicationError),
                }
            }

            Err(_) => Err(Scd30Error::ComunicationError),
        }
    }

    /// Trigger the continous measurements for SCD30 device.
    /// If fails return a communication error.
    /// If succeds, does not return anything.
    ///
    pub fn trigger_cont_measurements(&mut self) -> Result<(), Scd30Error> {
        let buffer: [u8; 5] = [0x00, 0x10, 0x00, 0x00, 0x81];
        match self.i2cdev.write(&buffer) {
            Ok(_) => {
                let ten_millis = time::Duration::from_millis(30);
                thread::sleep(ten_millis);
                Ok(())
            }
            Err(_) => Err(Scd30Error::ComunicationError),
        }
    }

    /// Stops the continous measurements for SCD30 device.
    /// If fails return a communication error.
    /// If succeds, does not return anything.
    ///
    pub fn stop_cont_measurements(&mut self) -> Result<(), Scd30Error> {
        let buffer: [u8; 2] = [0x01, 0x01];
        match self.i2cdev.write(&buffer) {
            Ok(_) => {
                let ten_millis = time::Duration::from_millis(30);
                thread::sleep(ten_millis);
                Ok(())
            }
            Err(_) => Err(Scd30Error::ComunicationError),
        }
    }

    /// Sets the measurements interval for the device,
    /// the default is 2 seconds. You can change it using the second parameter
    ///
    pub fn set_measurements_interval(&mut self, seconds: u16) -> Result<(), Scd30Error> {
        let time_in_bytes: [u8; 2] = seconds.to_be_bytes();
        let checksum = Scd30::crc8(&vec![time_in_bytes[0], time_in_bytes[1]]);
        let buffer: [u8; 5] = [0x46, 0x00, time_in_bytes[0], time_in_bytes[1], checksum];
        match self.i2cdev.write(&buffer) {
            Ok(_) => {
                let ten_millis = time::Duration::from_millis(30);
                thread::sleep(ten_millis);
                Ok(())
            }
            Err(_) => Err(Scd30Error::ComunicationError),
        }
    }

    /// Gets if the device is ready for reading
    /// a measurement. If not, returns false.
    /// If error, returns the error.
    pub fn get_data_ready(&mut self) -> Result<bool, Scd30Error> {
        let buffer: [u8; 2] = [0x02, 0x02];
        match self.i2cdev.write(&buffer) {
            Ok(_) => {
                let thirty_millis = time::Duration::from_millis(30);
                thread::sleep(thirty_millis);
                let mut data_buffer: [u8; 3] = [0; 3];
                match self.i2cdev.read(&mut data_buffer) {
                    Ok(_) => {
                        if Scd30::crc8(&vec![data_buffer[0], data_buffer[1]]) == data_buffer[2] {
                            if data_buffer[1] == 0x01 {
                                Ok(true)
                            } else {
                                Ok(false)
                            }
                        } else {
                            Err(Scd30Error::ChecksumError)
                        }
                    }
                    Err(_) => Err(Scd30Error::ComunicationError),
                }
            }
            Err(_) => Err(Scd30Error::ComunicationError),
        }
    }

    /// Get CO2, Temperature and Humidity for the device as a f32 tuple.
    /// Checks the checksum for each pair of bytes, if everything ok returns the tuple.
    /// In case of any problem, returns the error.
    pub fn get_measurements(&mut self) -> Result<(f32, f32, f32), Scd30Error> {
        let buffer: [u8; 2] = [0x03, 0x00];
        match self.i2cdev.write(&buffer) {
            Ok(_) => {
                let ten_millis = time::Duration::from_millis(30);
                thread::sleep(ten_millis);
                let mut data_buffer: [u8; 18] = [0; 18];
                match self.i2cdev.read(&mut data_buffer) {
                    Ok(_) => {
                        let co2_measurement = &data_buffer[0..6];
                        let temp_measurement = &data_buffer[6..12];
                        let rh_measurement = &data_buffer[12..=17];

                        if Scd30::check_crc_in_bytes(co2_measurement)
                            && Scd30::check_crc_in_bytes(temp_measurement)
                            && Scd30::check_crc_in_bytes(rh_measurement)
                        {
                            Ok((
                                f32::from_be_bytes([
                                    co2_measurement[0],
                                    co2_measurement[1],
                                    co2_measurement[3],
                                    co2_measurement[4],
                                ]),
                                f32::from_be_bytes([
                                    temp_measurement[0],
                                    temp_measurement[1],
                                    temp_measurement[3],
                                    temp_measurement[4],
                                ]),
                                f32::from_be_bytes([
                                    rh_measurement[0],
                                    rh_measurement[1],
                                    rh_measurement[3],
                                    rh_measurement[4],
                                ]),
                            ))
                        } else {
                            Err(Scd30Error::ChecksumError)
                        }
                    }
                    Err(_) => Err(Scd30Error::ComunicationError),
                }
            }
            Err(_) => Err(Scd30Error::ComunicationError),
        }
    }
    /// Gets if the devive is in self calibration procedure or not. In case it fails,
    /// returns and SCD30 error
    pub fn get_self_calibration_status(&mut self) -> Result<bool, Scd30Error> {
        let buffer: [u8; 2] = [0x53, 0x06];
        match self.i2cdev.write(&buffer) {
            Ok(_) => {
                let thirty_millis = time::Duration::from_millis(30);
                thread::sleep(thirty_millis);
                let mut data_buffer: [u8; 3] = [0; 3];
                match self.i2cdev.read(&mut data_buffer) {
                    Ok(_) => {
                        if Scd30::crc8(&vec![data_buffer[0], data_buffer[1]]) == data_buffer[2] {
                            if data_buffer[1] == 0x01 {
                                Ok(true)
                            } else {
                                Ok(false)
                            }
                        } else {
                            Err(Scd30Error::ChecksumError)
                        }
                    }
                    Err(_) => Err(Scd30Error::ComunicationError),
                }
            }
            Err(_) => Err(Scd30Error::ComunicationError),
        }
    }

    ///Set self calibration configuration. In this configuration, the device
    /// will start the process of self calibration, will take 7 days and requires at least
    /// 1 hour of fresh air per day, after that, the found value will be setted in non
    /// volatile memory.
    /// If fails returns communication errors, else returns nothing
    pub fn set_self_calibration(&mut self, active: bool) -> Result<(), Scd30Error> {
        let activate_function = if active { 0x01 } else { 0x00 };
        let checksum = Scd30::crc8(&vec![0x00, activate_function]);
        let buffer: [u8; 5] = [0x53, 0x06, 0x00, activate_function, checksum];
        match self.i2cdev.write(&buffer) {
            Ok(_) => {
                let ten_millis = time::Duration::from_millis(30);
                thread::sleep(ten_millis);
                Ok(())
            }
            Err(_) => Err(Scd30Error::ComunicationError),
        }
    }

    /// Soft reset the sensor device.
    /// If fails, return SCD30Error.
    ///
    pub fn soft_reset(&mut self) -> Result<(), Scd30Error> {
        let buffer: [u8; 2] = [0xd3, 0x04];
        match self.i2cdev.write(&buffer) {
            Ok(_) => {
                let ten_millis = time::Duration::from_millis(30);
                thread::sleep(ten_millis);
                Ok(())
            }

            Err(_) => Err(Scd30Error::ComunicationError),
        }
    }

    /// Gets the set altitude of the device.
    /// If fails, return SCD30Error.
    /// Else returns the altitue in meters from sea level (0 meters).
    ///
    pub fn get_altitude(&mut self) -> Result<u16, Scd30Error> {
        let buffer: [u8; 2] = [0x51, 0x02];
        match self.i2cdev.write(&buffer) {
            Ok(_) => {
                let ten_millis = time::Duration::from_millis(30);
                thread::sleep(ten_millis);
                // Read data from the selected register
                let mut data_buffer: [u8; 3] = [0; 3];
                match self.i2cdev.read(&mut data_buffer) {
                    Ok(_) => {
                        if data_buffer[2] == Scd30::crc8(&vec![data_buffer[0], data_buffer[1]]) {
                            Ok(u16::from_be_bytes([data_buffer[0], data_buffer[1]]))
                        } else {
                            Err(Scd30Error::ChecksumError)
                        }
                    }
                    Err(_) => Err(Scd30Error::ComunicationError),
                }
            }

            Err(_) => Err(Scd30Error::ComunicationError),
        }
    }

    /// Sets the altitude for the device.
    /// Altitude is a u16 in meters starting from sea level (0 meters)
    /// If fails returns SCD30Error,
    /// else return nothing.
    /// After the set you can check the saved value to be the same as expected
    pub fn set_altitude(&mut self, altitude: u16) -> Result<(), Scd30Error> {
        let altitude_in_bytes: [u8; 2] = altitude.to_be_bytes();
        let checksum = Scd30::crc8(&vec![altitude_in_bytes[0], altitude_in_bytes[1]]);
        let buffer: [u8; 5] = [
            0x51,
            0x02,
            altitude_in_bytes[0],
            altitude_in_bytes[1],
            checksum,
        ];
        match self.i2cdev.write(&buffer) {
            Ok(_) => {
                let ten_millis = time::Duration::from_millis(30);
                thread::sleep(ten_millis);
                Ok(())
            }
            Err(_) => Err(Scd30Error::ComunicationError),
        }
    }

    /// Gets the temperature offset of the device.
    /// If fails, return SCD30Error.
    /// Else returns the temperature offset in shif ticks, each tick 0.01 Celsius.
    ///
    pub fn get_temperature_offset(&mut self) -> Result<u16, Scd30Error> {
        let buffer: [u8; 2] = [0x54, 0x03];
        match self.i2cdev.write(&buffer) {
            Ok(_) => {
                let ten_millis = time::Duration::from_millis(30);
                thread::sleep(ten_millis);
                // Read data from the selected register
                let mut data_buffer: [u8; 3] = [0; 3];
                match self.i2cdev.read(&mut data_buffer) {
                    Ok(_) => {
                        if data_buffer[2] == Scd30::crc8(&vec![data_buffer[0], data_buffer[1]]) {
                            Ok(u16::from_be_bytes([data_buffer[0], data_buffer[1]]))
                        } else {
                            Err(Scd30Error::ChecksumError)
                        }
                    }
                    Err(_) => Err(Scd30Error::ComunicationError),
                }
            }

            Err(_) => Err(Scd30Error::ComunicationError),
        }
    }

    /// Sets the temperature offset of the device.
    /// Offset is a u16 correspoding to one tick, each tick is 0.01 Celsius of offset
    /// If fails returns SCD30Error,
    /// else return nothing.
    pub fn set_temperature_offset(&mut self, offset: u16) -> Result<(), Scd30Error> {
        let offset_in_bytes: [u8; 2] = offset.to_be_bytes();
        let checksum = Scd30::crc8(&vec![offset_in_bytes[0], offset_in_bytes[1]]);
        let buffer: [u8; 5] = [0x54, 0x03, offset_in_bytes[0], offset_in_bytes[1], checksum];
        match self.i2cdev.write(&buffer) {
            Ok(_) => {
                let ten_millis = time::Duration::from_millis(30);
                thread::sleep(ten_millis);
                Ok(())
            }
            Err(_) => Err(Scd30Error::ComunicationError),
        }
    }

    /// Checks the forced calibration value of the device.
    /// If fails, return SCD30Error.
    /// Else returns the forced value in ppm units.
    ///
    pub fn get_forced_value(&mut self) -> Result<u16, Scd30Error> {
        let buffer: [u8; 2] = [0x52, 0x04];
        match self.i2cdev.write(&buffer) {
            Ok(_) => {
                let ten_millis = time::Duration::from_millis(30);
                thread::sleep(ten_millis);
                // Read data from the selected register
                let mut data_buffer: [u8; 3] = [0; 3];
                match self.i2cdev.read(&mut data_buffer) {
                    Ok(_) => {
                        if data_buffer[2] == Scd30::crc8(&vec![data_buffer[0], data_buffer[1]]) {
                            Ok(u16::from_be_bytes([data_buffer[0], data_buffer[1]]))
                        } else {
                            Err(Scd30Error::ChecksumError)
                        }
                    }
                    Err(_) => Err(Scd30Error::ComunicationError),
                }
            }

            Err(_) => Err(Scd30Error::ComunicationError),
        }
    }

    /// Sets a force recalibration value to the device.
    /// Usually this is use when no time for automatic self calibration is posible.
    /// If fails returns SCD30Error,
    /// else return nothing.
    pub fn set_force_recalibration_value(&mut self, forced_value: u16) -> Result<(), Scd30Error> {
        let forced_value_in_bytes: [u8; 2] = forced_value.to_be_bytes();
        let checksum = Scd30::crc8(&vec![forced_value_in_bytes[0], forced_value_in_bytes[1]]);
        let buffer: [u8; 5] = [
            0x52,
            0x04,
            forced_value_in_bytes[0],
            forced_value_in_bytes[1],
            checksum,
        ];
        match self.i2cdev.write(&buffer) {
            Ok(_) => {
                let ten_millis = time::Duration::from_millis(30);
                thread::sleep(ten_millis);
                Ok(())
            }
            Err(_) => Err(Scd30Error::ComunicationError),
        }
    }
}