co2mon 2.1.1

Driver for the Holtek ZyTemp CO₂ USB HID sensors
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
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
#![doc(html_root_url = "https://docs.rs/co2mon/2.0.3")]
#![deny(missing_docs)]

//! A driver for the Holtek ([ZyAura ZG][ZG]) CO₂ USB monitors.
//!
//! The implementation was tested using a
//! [TFA-Dostmann AIRCO2NTROL MINI][AIRCO2NTROL MINI] sensor.
//!
//! [AIRCO2NTROL MINI]: https://www.tfa-dostmann.de/en/produkt/co2-monitor-airco2ntrol-mini/
//! [ZG]: http://www.zyaura.com/products/ZG_module.asp
//!
//! # Example usage
//!
//! ```no_run
//! # use co2mon::{Result, Sensor};
//! # fn main() -> Result<()> {
//! #
//! let sensor = Sensor::open_default()?;
//! let reading = sensor.read_one()?;
//! println!("{:?}", reading);
//! #
//! # Ok(())
//! # }
//! ```
//!
//! # Permissions
//!
//! On Linux, you need to be able to access the USB HID device. For that, you
//! can save the following `udev` rule to `/etc/udev/rules.d/60-co2mon.rules`:
//!
//! ```text
//! ACTION=="add|change", SUBSYSTEMS=="usb", ATTRS{idVendor}=="04d9", ATTRS{idProduct}=="a052", MODE:="0666"
//! ```
//!
//! Then reload the rules and trigger them:
//!
//! ```text
//! ## udevadm control --reload
//! ## udevadm trigger
//! ```
//!
//! Note that the `udev` rule above makes the device accessible to every local user.
//!
//! # References
//!
//! The USB HID protocol is not documented, but was [reverse-engineered][had] [before][revspace].
//!
//! [had]: https://hackaday.io/project/5301/
//! [revspace]: https://revspace.nl/CO2MeterHacking

use hidapi::{HidApi, HidDevice};
use std::convert::TryFrom;
use std::ffi::CString;
use std::result;
use std::time::{Duration, Instant};

pub use error::Error;
pub use zg_co2::SingleReading;

mod error;

/// A specialized [`Result`][std::result::Result] type for the fallible functions.
pub type Result<T> = result::Result<T, Error>;

/// A reading consisting of temperature (in °C) and CO₂ concentration (in ppm) values.
///
/// # Example
///
/// ```no_run
/// # use co2mon::{Result, Sensor};
/// # fn main() -> Result<()> {
/// #
/// let sensor = Sensor::open_default()?;
/// let reading = sensor.read()?;
/// println!("{} °C, {} ppm CO₂", reading.temperature(), reading.co2());
/// #
/// # Ok(())
/// # }
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct Reading {
    temperature: f32,
    co2: u16,
}

impl Reading {
    /// Returns the measured temperature in °C.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use co2mon::{Result, Sensor};
    /// # fn main() -> Result<()> {
    /// #
    /// let sensor = Sensor::open_default()?;
    /// let reading = sensor.read()?;
    /// println!("{} °C", reading.temperature());
    /// #
    /// # Ok(())
    /// # }
    pub fn temperature(&self) -> f32 {
        self.temperature
    }

    /// Returns the CO₂ concentration in ppm (parts per million).
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use co2mon::{Result, Sensor};
    /// # fn main() -> Result<()> {
    /// #
    /// let sensor = Sensor::open_default()?;
    /// let reading = sensor.read()?;
    /// println!("{} ppm CO₂", reading.co2());
    /// #
    /// # Ok(())
    /// # }
    pub fn co2(&self) -> u16 {
        self.co2
    }
}

/// Sensor driver struct.
///
/// # Example
///
/// ```no_run
/// # use co2mon::{Result, Sensor};
/// # fn main() -> Result<()> {
/// #
/// let sensor = Sensor::open_default()?;
/// let reading = sensor.read_one()?;
/// println!("{:?}", reading);
/// #
/// # Ok(())
/// # }
/// ```
pub struct Sensor {
    device: HidDevice,
    key: [u8; 8],
    timeout: i32,
}

impl Sensor {
    /// Opens the sensor device using the default USB Vendor ID (`0x04d9`) and Product ID (`0xa052`) values.
    ///
    /// When multiple devices are connected, the first one will be used.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use co2mon::{Result, Sensor};
    /// # fn main() -> Result<()> {
    /// #
    /// let sensor = Sensor::open_default()?;
    /// let reading = sensor.read_one()?;
    /// println!("{:?}", reading);
    /// #
    /// # Ok(())
    /// # }
    pub fn open_default() -> Result<Self> {
        OpenOptions::new().open()
    }

    fn open(options: &OpenOptions) -> Result<Self> {
        let hidapi = HidApi::new()?;

        const VID: u16 = 0x04d9;
        const PID: u16 = 0xa052;

        let device = match options.path_type {
            DevicePathType::Id => hidapi.open(VID, PID),
            DevicePathType::SerialNumber(ref sn) => hidapi.open_serial(VID, PID, sn),
            DevicePathType::Path(ref path) => hidapi.open_path(path),
        }?;

        let key = options.key;

        // fill in the Report Id
        let frame = {
            let mut frame = [0; 9];
            frame[1..9].copy_from_slice(&key);
            frame
        };
        device.send_feature_report(&frame)?;

        let timeout = options
            .timeout
            .map(|timeout| timeout.as_millis())
            .map_or(Ok(-1), i32::try_from)
            .map_err(|_| Error::InvalidTimeout)?;

        let air_control = Self {
            device,
            key,
            timeout,
        };
        Ok(air_control)
    }

    /// Takes a single reading from the sensor.
    ///
    /// # Errors
    ///
    /// An error will be returned on an I/O error or if a message could not be
    /// read or decoded.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use co2mon::{Result, Sensor};
    /// # fn main() -> Result<()> {
    /// #
    /// let sensor = Sensor::open_default()?;
    /// let reading = sensor.read_one()?;
    /// println!("{:?}", reading);
    /// #
    /// # Ok(())
    /// # }
    pub fn read_one(&self) -> Result<SingleReading> {
        let mut data = [0; 8];
        if self.device.read_timeout(&mut data, self.timeout)? != 8 {
            return Err(Error::InvalidMessage);
        }

        // if the "magic byte" is present no decryption is necessary. This is the case for AIRCO2NTROL COACH
        // and newer AIRCO2NTROL MINIs in general
        let data = if data[4] == 0x0d {
            data
        } else {
            decrypt(data, self.key)
        };
        let reading = zg_co2::decode([data[0], data[1], data[2], data[3], data[4]])?;
        Ok(reading)
    }

    /// Takes a multiple readings from the sensor until the temperature and
    /// CO₂ concentration are available, and returns both.
    ///
    /// # Errors
    ///
    /// An error will be returned on an I/O error or if a message could not be
    /// read or decoded.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use co2mon::{Result, Sensor};
    /// # fn main() -> Result<()> {
    /// #
    /// let sensor = Sensor::open_default()?;
    /// let reading = sensor.read()?;
    /// println!("{} °C, {} ppm CO₂", reading.temperature(), reading.co2());
    /// #
    /// # Ok(())
    /// # }
    pub fn read(&self) -> Result<Reading> {
        let start = Instant::now();
        let mut temperature = None;
        let mut co2 = None;
        loop {
            let reading = self.read_one()?;
            match reading {
                SingleReading::Temperature(val) => temperature = Some(val),
                SingleReading::CO2(val) => co2 = Some(val),
                _ => {}
            }
            if let (Some(temperature), Some(co2)) = (temperature, co2) {
                let reading = Reading { temperature, co2 };
                return Ok(reading);
            }

            if self.timeout != -1 {
                let duration = Instant::now() - start;
                if duration.as_millis() > self.timeout as u128 {
                    return Err(Error::Timeout);
                }
            }
        }
    }
}

fn decrypt(mut data: [u8; 8], key: [u8; 8]) -> [u8; 8] {
    data.swap(0, 2);
    data.swap(1, 4);
    data.swap(3, 7);
    data.swap(5, 6);

    for (r, k) in data.iter_mut().zip(key.iter()) {
        *r ^= k;
    }

    let tmp = data[7] << 5;
    data[7] = data[6] << 5 | data[7] >> 3;
    data[6] = data[5] << 5 | data[6] >> 3;
    data[5] = data[4] << 5 | data[5] >> 3;
    data[4] = data[3] << 5 | data[4] >> 3;
    data[3] = data[2] << 5 | data[3] >> 3;
    data[2] = data[1] << 5 | data[2] >> 3;
    data[1] = data[0] << 5 | data[1] >> 3;
    data[0] = tmp | data[0] >> 3;

    for (r, m) in data.iter_mut().zip(b"Htemp99e".iter()) {
        *r = r.wrapping_sub(m << 4 | m >> 4);
    }

    data
}

#[derive(Debug, Clone)]
enum DevicePathType {
    Id,
    SerialNumber(String),
    Path(CString),
}

/// Sensor open options.
///
/// Opens the first available device with the USB Vendor ID `0x04d9`
/// and Product ID `0xa052`, a `0` encryption key and a 5 seconds timeout.
///
/// Normally there's no need to change the encryption key.
///
/// # Example
///
/// ```no_run
/// # use co2mon::{OpenOptions, Result};
/// # use std::time::Duration;
/// # fn main() -> Result<()> {
/// #
/// let sensor = OpenOptions::new()
///     .timeout(Some(Duration::from_secs(10)))
///     .open()?;
/// #
/// # Ok(())
/// # }
#[derive(Debug, Clone)]
pub struct OpenOptions {
    path_type: DevicePathType,
    key: [u8; 8],
    timeout: Option<Duration>,
}

impl Default for OpenOptions {
    fn default() -> Self {
        Self::new()
    }
}

impl OpenOptions {
    /// Creates a new set of options to be configured.
    ///
    /// The defaults are opening the first connected sensor and a timeout of
    /// 5 seconds.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use co2mon::{OpenOptions, Result};
    /// # use std::time::Duration;
    /// # fn main() -> Result<()> {
    /// #
    /// let sensor = OpenOptions::new()
    ///     .timeout(Some(Duration::from_secs(10)))
    ///     .open()?;
    /// #
    /// # Ok(())
    /// # }
    pub fn new() -> Self {
        Self {
            path_type: DevicePathType::Id,
            key: [0; 8],
            timeout: Some(Duration::from_secs(5)),
        }
    }

    /// Sets the serial number of the sensor device to open.
    ///
    /// The serial number appears to be the firmware version.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use co2mon::OpenOptions;
    /// # use std::error::Error;
    /// # use std::ffi::CString;
    /// # use std::result::Result;
    /// # fn main() -> Result<(), Box<Error>> {
    /// #
    /// let sensor = OpenOptions::new()
    ///     .with_serial_number("1.40")
    ///     .open()?;
    /// #
    /// # Ok(())
    /// # }
    pub fn with_serial_number<S: Into<String>>(&mut self, sn: S) -> &mut Self {
        self.path_type = DevicePathType::SerialNumber(sn.into());
        self
    }

    /// Sets the path to the sensor device to open.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use co2mon::OpenOptions;
    /// # use std::error::Error;
    /// # use std::ffi::CString;
    /// # use std::result::Result;
    /// # fn main() -> Result<(), Box<Error>> {
    /// #
    /// let sensor = OpenOptions::new()
    ///     .with_path(CString::new("/dev/bus/usb/001/004")?)
    ///     .open()?;
    /// #
    /// # Ok(())
    /// # }
    pub fn with_path(&mut self, path: CString) -> &mut Self {
        self.path_type = DevicePathType::Path(path);
        self
    }

    /// Sets the encryption key.
    ///
    /// The key is used to encrypt the communication with the sensor, but
    /// changing it is probably not very useful.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use co2mon::{OpenOptions, Result};
    /// # use std::ffi::CString;
    /// # fn main() -> Result<()> {
    /// #
    /// let sensor = OpenOptions::new()
    ///     .with_key([0x62, 0xea, 0x1d, 0x4f, 0x14, 0xfa, 0xe5, 0x6c])
    ///     .open()?;
    /// #
    /// # Ok(())
    /// # }
    pub fn with_key(&mut self, key: [u8; 8]) -> &mut Self {
        self.key = key;
        self
    }

    /// Sets the read timeout.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use co2mon::{OpenOptions, Result};
    /// # use std::time::Duration;
    /// # fn main() -> Result<()> {
    /// #
    /// let sensor = OpenOptions::new()
    ///     .timeout(Some(Duration::from_secs(10)))
    ///     .open()?;
    /// #
    /// # Ok(())
    /// # }
    pub fn timeout(&mut self, timeout: Option<Duration>) -> &mut Self {
        self.timeout = timeout;
        self
    }

    /// Opens the sensor.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use co2mon::{OpenOptions, Result};
    /// # use std::time::Duration;
    /// # fn main() -> Result<()> {
    /// #
    /// let sensor = OpenOptions::new()
    ///     .timeout(Some(Duration::from_secs(10)))
    ///     .open()?;
    /// #
    /// # Ok(())
    /// # }
    pub fn open(&self) -> Result<Sensor> {
        Sensor::open(self)
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_decrypt() {
        let data = [0x6c, 0xa4, 0xa2, 0xb6, 0x5d, 0x9a, 0x9c, 0x08];
        let key = [0; 8];

        let data = super::decrypt(data, key);
        assert_eq!(data, [0x50, 0x04, 0x57, 0xab, 0x0d, 0x00, 0x00, 0x00]);
    }

    #[test]
    fn test_open_options_send() {
        fn assert_send<T: Send>() {}
        assert_send::<super::Sensor>();
        assert_send::<super::OpenOptions>();
    }

    #[test]
    fn test_open_options_sync() {
        fn assert_sync<T: Sync>() {}
        assert_sync::<super::OpenOptions>();
    }
}