|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Device.Model; |
| 6 | +using System.IO; |
| 7 | +using System.IO.Ports; |
| 8 | +using System.Threading; |
| 9 | +using UnitsNet; |
| 10 | + |
| 11 | +namespace Iot.Device.Mhz19b |
| 12 | +{ |
| 13 | + /// <summary> |
| 14 | + /// MH-Z19B CO2 concentration sensor binding |
| 15 | + /// </summary> |
| 16 | + [Interface("MH-Z19B CO2 concentration sensor binding")] |
| 17 | + public sealed class Mhz19b : IDisposable |
| 18 | + { |
| 19 | + private const int MessageBytes = 9; |
| 20 | + private bool _shouldDispose = false; |
| 21 | + private SerialPort? _serialPort; |
| 22 | + private Stream _serialPortStream; |
| 23 | + |
| 24 | + /// <summary> |
| 25 | + /// Initializes a new instance of the <see cref="Mhz19b"/> class using an existing (serial port) stream. |
| 26 | + /// </summary> |
| 27 | + /// <param name="stream">Existing stream</param> |
| 28 | + /// <param name="shouldDispose">If true, the stream gets disposed when disposing the binding</param> |
| 29 | + public Mhz19b(Stream stream, bool shouldDispose) |
| 30 | + { |
| 31 | + _serialPortStream = stream ?? throw new ArgumentNullException(nameof(stream)); |
| 32 | + _shouldDispose = shouldDispose; |
| 33 | + } |
| 34 | + |
| 35 | + /// <summary> |
| 36 | + /// Initializes a new instance of the <see cref="Mhz19b"/> class and creates a new serial port stream. |
| 37 | + /// </summary> |
| 38 | + /// <param name="uartDevice">Path to the UART device / serial port, e.g. /dev/serial0</param> |
| 39 | + /// <exception cref="System.ArgumentException">uartDevice is null or empty</exception> |
| 40 | + public Mhz19b(string uartDevice) |
| 41 | + { |
| 42 | + if (uartDevice is not { Length: > 0 }) |
| 43 | + { |
| 44 | + throw new ArgumentException(nameof(uartDevice)); |
| 45 | + } |
| 46 | + |
| 47 | + // create serial port using the setting acc. to datasheet, pg. 7, sec. general settings |
| 48 | + _serialPort = new SerialPort(uartDevice, 9600, Parity.None, 8, StopBits.One) |
| 49 | + { |
| 50 | + ReadTimeout = 1000, |
| 51 | + WriteTimeout = 1000 |
| 52 | + }; |
| 53 | + |
| 54 | + _serialPort.Open(); |
| 55 | + _serialPortStream = _serialPort.BaseStream; |
| 56 | + _shouldDispose = true; |
| 57 | + } |
| 58 | + |
| 59 | + /// <summary> |
| 60 | + /// Gets the current CO2 concentration from the sensor. |
| 61 | + /// </summary> |
| 62 | + /// <returns>CO2 volume concentration</returns> |
| 63 | + /// <exception cref="IOException">Communication with sensor failed</exception> |
| 64 | + /// <exception cref="TimeoutException">A timeout occurred while communicating with the sensor</exception> |
| 65 | + [Telemetry("Co2Concentration")] |
| 66 | + public VolumeConcentration GetCo2Reading() |
| 67 | + { |
| 68 | + // send read command request |
| 69 | + byte[] request = CreateRequest(Command.ReadCo2Concentration); |
| 70 | + request[(int)MessageFormat.Checksum] = Checksum(request); |
| 71 | + _serialPortStream.Write(request, 0, request.Length); |
| 72 | + |
| 73 | + // read complete response (9 bytes expected) |
| 74 | + byte[] response = new byte[MessageBytes]; |
| 75 | + |
| 76 | + long endTicks = DateTime.UtcNow.AddMilliseconds(250).Ticks; |
| 77 | + int bytesRead = 0; |
| 78 | + while (DateTime.UtcNow.Ticks < endTicks && bytesRead < MessageBytes) |
| 79 | + { |
| 80 | + bytesRead += _serialPortStream.Read(response, bytesRead, response.Length - bytesRead); |
| 81 | + Thread.Sleep(1); |
| 82 | + } |
| 83 | + |
| 84 | + if (bytesRead < MessageBytes) |
| 85 | + { |
| 86 | + throw new TimeoutException($"Communication with sensor failed."); |
| 87 | + } |
| 88 | + |
| 89 | + // check response and return calculated concentration if valid |
| 90 | + if (response[(int)MessageFormat.Checksum] == Checksum(response)) |
| 91 | + { |
| 92 | + return VolumeConcentration.FromPartsPerMillion((int)response[(int)MessageFormat.DataHighResponse] * 256 + (int)response[(int)MessageFormat.DataLowResponse]); |
| 93 | + } |
| 94 | + else |
| 95 | + { |
| 96 | + throw new IOException("Invalid response message received from sensor"); |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + /// <summary> |
| 101 | + /// Initiates a zero point calibration. |
| 102 | + /// </summary> |
| 103 | + /// <exception cref="System.IO.IOException">Communication with sensor failed</exception> |
| 104 | + [Command] |
| 105 | + public void PerformZeroPointCalibration() => SendRequest(CreateRequest(Command.CalibrateZeroPoint)); |
| 106 | + |
| 107 | + /// <summary> |
| 108 | + /// Initiate a span point calibration. |
| 109 | + /// </summary> |
| 110 | + /// <param name="span">span value, between 1000[ppm] and 5000[ppm]. The typical value is 2000[ppm].</param> |
| 111 | + /// <exception cref="System.ArgumentException">Thrown when span value is out of range</exception> |
| 112 | + /// <exception cref="System.IO.IOException">Communication with sensor failed</exception> |
| 113 | + [Command] |
| 114 | + public void PerformSpanPointCalibration(VolumeConcentration span) |
| 115 | + { |
| 116 | + if ((span.PartsPerMillion < 1000) || (span.PartsPerMillion > 5000)) |
| 117 | + { |
| 118 | + throw new ArgumentException("Span value out of range (1000-5000[ppm])", nameof(span)); |
| 119 | + } |
| 120 | + |
| 121 | + byte[] request = CreateRequest(Command.CalibrateSpanPoint); |
| 122 | + // set span in request, c. f. datasheet rev. 1.0, pg. 8 for details |
| 123 | + request[(int)MessageFormat.DataHighRequest] = (byte)(span.PartsPerMillion / 256); |
| 124 | + request[(int)MessageFormat.DataLowRequest] = (byte)(span.PartsPerMillion % 256); |
| 125 | + |
| 126 | + SendRequest(request); |
| 127 | + } |
| 128 | + |
| 129 | + /// <summary> |
| 130 | + /// Switches the autmatic baseline correction on and off. |
| 131 | + /// </summary> |
| 132 | + /// <param name="state">State of automatic correction</param> |
| 133 | + /// <exception cref="System.IO.IOException">Communication with sensor failed</exception> |
| 134 | + [Command] |
| 135 | + public void SetAutomaticBaselineCorrection(AbmState state) |
| 136 | + { |
| 137 | + byte[] request = CreateRequest(Command.AutoCalibrationSwitch); |
| 138 | + // set on/off state in request, c. f. datasheet rev. 1.0, pg. 8 for details |
| 139 | + request[(int)MessageFormat.DataHighRequest] = (byte)state; |
| 140 | + |
| 141 | + SendRequest(request); |
| 142 | + } |
| 143 | + |
| 144 | + /// <summary> |
| 145 | + /// Set the sensor detection range. |
| 146 | + /// </summary> |
| 147 | + /// <param name="detectionRange">Detection range of the sensor</param> |
| 148 | + /// <exception cref="System.IO.IOException">Communication with sensor failed</exception> |
| 149 | + [Property("DetectionRange")] |
| 150 | + public void SetSensorDetectionRange(DetectionRange detectionRange) |
| 151 | + { |
| 152 | + byte[] request = CreateRequest(Command.DetectionRangeSetting); |
| 153 | + // set detection range in request, c. f. datasheet rev. 1.0, pg. 8 for details |
| 154 | + request[(int)MessageFormat.DataHighRequest] = (byte)((int)detectionRange / 256); |
| 155 | + request[(int)MessageFormat.DataLowRequest] = (byte)((int)detectionRange % 256); |
| 156 | + |
| 157 | + SendRequest(request); |
| 158 | + } |
| 159 | + |
| 160 | + private void SendRequest(byte[] request) |
| 161 | + { |
| 162 | + request[(int)MessageFormat.Checksum] = Checksum(request); |
| 163 | + |
| 164 | + try |
| 165 | + { |
| 166 | + _serialPortStream.Write(request, 0, request.Length); |
| 167 | + } |
| 168 | + catch (Exception e) |
| 169 | + { |
| 170 | + throw new IOException("Sensor communication failed", e); |
| 171 | + } |
| 172 | + } |
| 173 | + |
| 174 | + private byte[] CreateRequest(Command command) => new byte[] |
| 175 | + { |
| 176 | + 0xff, // start byte, |
| 177 | + 0x01, // sensor number, always 0x1 |
| 178 | + (byte)command, |
| 179 | + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // empty bytes |
| 180 | + }; |
| 181 | + |
| 182 | + /// <summary> |
| 183 | + /// Calculate checksum for requests and responses. |
| 184 | + /// For details refer to datasheet rev. 1.0, pg. 8. |
| 185 | + /// </summary> |
| 186 | + /// <param name="packet">Packet the checksum is calculated for</param> |
| 187 | + /// <returns>Cheksum</returns> |
| 188 | + private byte Checksum(byte[] packet) |
| 189 | + { |
| 190 | + byte checksum = 0; |
| 191 | + for (int i = 1; i < 8; i++) |
| 192 | + { |
| 193 | + checksum += packet[i]; |
| 194 | + } |
| 195 | + |
| 196 | + checksum = (byte)(0xff - checksum); |
| 197 | + checksum += 1; |
| 198 | + return checksum; |
| 199 | + } |
| 200 | + |
| 201 | + /// <inheritdoc cref="IDisposable" /> |
| 202 | + public void Dispose() |
| 203 | + { |
| 204 | + if (_shouldDispose) |
| 205 | + { |
| 206 | + _serialPortStream?.Dispose(); |
| 207 | + _serialPortStream = null!; |
| 208 | + } |
| 209 | + |
| 210 | + if (_serialPort is not null) |
| 211 | + { |
| 212 | + if (_serialPort.IsOpen) |
| 213 | + { |
| 214 | + _serialPort.Close(); |
| 215 | + } |
| 216 | + } |
| 217 | + |
| 218 | + _serialPort?.Dispose(); |
| 219 | + _serialPort = null; |
| 220 | + } |
| 221 | + |
| 222 | + private enum Command : byte |
| 223 | + { |
| 224 | + ReadCo2Concentration = 0x86, |
| 225 | + CalibrateZeroPoint = 0x87, |
| 226 | + CalibrateSpanPoint = 0x88, |
| 227 | + AutoCalibrationSwitch = 0x79, |
| 228 | + DetectionRangeSetting = 0x99 |
| 229 | + } |
| 230 | + |
| 231 | + private enum MessageFormat |
| 232 | + { |
| 233 | + Start = 0x00, |
| 234 | + SensorNum = 0x01, |
| 235 | + Command = 0x02, |
| 236 | + DataHighRequest = 0x03, |
| 237 | + DataLowRequest = 0x04, |
| 238 | + DataHighResponse = 0x02, |
| 239 | + DataLowResponse = 0x03, |
| 240 | + Checksum = 0x08 |
| 241 | + } |
| 242 | + } |
| 243 | +} |
0 commit comments