]> git.basschouten.com Git - openhab-addons.git/blob
8243b6ea7ec0565938ba6e3692680c2129c89c6a
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.novafinedust.internal.sds011protocol.messages;
14
15 import org.eclipse.jdt.annotation.NonNullByDefault;
16 import org.openhab.core.util.HexUtils;
17
18 /**
19  * Class containing the actual measured values from the sensor
20  *
21  * @author Stefan Triller - Initial contribution
22  *
23  */
24 @NonNullByDefault
25 public class SensorMeasuredDataReply extends SensorReply {
26     private final byte pm25lowByte;
27     private final byte pm25highByte;
28     private final byte pm10lowByte;
29     private final byte pm10highByte;
30
31     /**
32      * Create a new instance by parsing the given 10 bytes.
33      *
34      */
35     public SensorMeasuredDataReply(byte[] bytes) {
36         super(bytes);
37         pm25lowByte = bytes[2];
38         pm25highByte = bytes[3];
39         pm10lowByte = bytes[4];
40         pm10highByte = bytes[5];
41     }
42
43     /**
44      * Check if data is valid by checking header, commanderNo, messageTail and checksum.
45      */
46     public boolean isValidData() {
47         return header == Constants.MESSAGE_START && commandID == (byte) 0xC0 && messageTail == Constants.MESSAGE_END
48                 && checksum == calculateChecksum();
49     }
50
51     /**
52      * Get the measured PM2.5 value
53      *
54      * @return the measured PM2.5 value
55      */
56     public float getPm25() {
57         int shiftedValue = ((pm25highByte & 0xFF) << 8) | pm25lowByte & 0xFF;
58         return ((float) shiftedValue) / 10;
59     }
60
61     /**
62      * Get the measured PM10 value
63      *
64      * @return the measured PM10 value
65      */
66     public float getPm10() {
67         int shiftedValue = ((pm10highByte & 0xFF) << 8) | pm10lowByte & 0xFF;
68         return ((float) shiftedValue) / 10;
69     }
70
71     @Override
72     public String toString() {
73         return String.format(
74                 "SensorMeasuredDataReply: [valid=%s, PM 2.5=%.1f, PM 10=%.1f, sourceDevice=%s, pm25lowHigh=(%s) pm10lowHigh=(%s)]",
75                 isValidData(), getPm25(), getPm10(), HexUtils.bytesToHex(new byte[] { deviceID[0], deviceID[1] }),
76                 HexUtils.bytesToHex(new byte[] { pm25lowByte, pm25highByte }),
77                 HexUtils.bytesToHex(new byte[] { pm10lowByte, pm10highByte }));
78     }
79 }