Exemplo n.º 1
0
        /// <summary>
        /// Reads the data from the sensor.
        /// </summary>
        /// <returns cref="Pms5003Data">The data.</returns>
        /// <exception cref="ReadFailedException">Thrown when the read fails.</exception>
        public Pms5003Data ReadData()
        {
            var       currentTry = 0;
            const int maxRetries = 5;

            while (currentTry < maxRetries)
            {
                try
                {
                    var buffer = new byte[32];
                    _serialPort.Read(buffer, 0, 32);
                    return(Pms5003Data.FromBytes(buffer));
                }
                catch (Exception e)
                {
                    Logger?.LogWarning(e.ToString());
                    Thread.Sleep(1000);
                }
                finally
                {
                    currentTry += 1;
                }
            }

            throw new ReadFailedException();
        }
Exemplo n.º 2
0
        /// <summary>
        /// Instantiates a new instance from the given byte buffer.
        /// </summary>
        /// <param name="buffer">The data buffer</param>
        /// <returns>A new instance.</returns>
        public static Pms5003Data FromBytes(byte[] buffer)
        {
            var pms5003Measurement = new Pms5003Data();

            if (buffer.Length < 4)
            {
                throw new BufferUnderflowException();
            }

            if (buffer[0] != Pms5003Constants.StartByte1 || buffer[1] != Pms5003Constants.StartByte2)
            {
                throw new InvalidStartByteException(buffer[0], buffer[1]);
            }

            var frameLength = Utils.CombineBytes(buffer[2], buffer[3]);

            if (frameLength > 0)
            {
                var currentDataPoint = 0;
                for (var i = 4; i < frameLength + 4; i += 2)
                {
                    pms5003Measurement._data[currentDataPoint] = Utils.CombineBytes(buffer[i], buffer[i + 1]);
                    currentDataPoint += 1;
                }
            }

            var checkSum = 0;

            for (var i = 0; i < frameLength + 2; i++)
            {
                checkSum += buffer[i];
            }

            if (pms5003Measurement.Checksum != checkSum)
            {
                throw new ChecksumMismatchException();
            }

            return(pms5003Measurement);
        }