This commit is contained in:
parent
fbcafef67c
commit
cad01edab8
3 changed files with 38 additions and 3 deletions
|
|
@ -40,6 +40,8 @@ fn parse_mqtt_update(
|
|||
case topic {
|
||||
"homeassistant/sensor/bws/node1/state1" ->
|
||||
Ok(sensors.parse_topic_1(payload_str))
|
||||
"homeassistant/sensor/bws/node1/state2" ->
|
||||
Ok(sensors.parse_topic_2(payload_str))
|
||||
_ -> Error(Nil)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,8 +27,6 @@ pub fn sensor_name(sensor: Sensor) -> String {
|
|||
}
|
||||
}
|
||||
|
||||
pub const topic_1: String = "homeassistant/sensor/bws/node1/state1"
|
||||
|
||||
type Topic1Value {
|
||||
Topic1Value(temp: Float, humidity: Float, pressure: Float)
|
||||
}
|
||||
|
|
@ -50,6 +48,27 @@ pub fn parse_topic_1(json_string: String) -> List(SensorReading) {
|
|||
]
|
||||
}
|
||||
|
||||
type Topic2Value {
|
||||
Topic2Value(pm1: Float, pm2: Float, pm10: Float)
|
||||
}
|
||||
|
||||
/// Parses a JSON string into a list of `SensorReading` values from topic 2.
|
||||
/// example input string: {"pm1":16.83,"pm2_5":10.68,"pm10":16.619719}
|
||||
pub fn parse_topic_2(json_string: String) -> List(SensorReading) {
|
||||
let decoder = {
|
||||
use pm1 <- decode.field("pm1", decode.float)
|
||||
use pm2 <- decode.field("pm2_5", decode.float)
|
||||
use pm10 <- decode.field("pm10", decode.float)
|
||||
decode.success(Topic2Value(pm1:, pm2:, pm10:))
|
||||
}
|
||||
let assert Ok(decoded_val) = json.parse(from: json_string, using: decoder)
|
||||
[
|
||||
SensorReading(sensor: ParticalMatterOne, value: decoded_val.pm1),
|
||||
SensorReading(sensor: ParticalMatterTwoPointFive, value: decoded_val.pm2),
|
||||
SensorReading(sensor: ParticalMatterTen, value: decoded_val.pm10),
|
||||
]
|
||||
}
|
||||
|
||||
pub fn print_sensor_reading(reading: SensorReading) -> Nil {
|
||||
let sensor_name = sensor_name(reading.sensor)
|
||||
io.println(sensor_name <> ": " <> float.to_string(reading.value))
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ pub fn main() -> Nil {
|
|||
gleeunit.main()
|
||||
}
|
||||
|
||||
pub fn file_read_test() {
|
||||
pub fn sensor_name_and_unit_test() {
|
||||
let reading =
|
||||
sensors.sensor_name(sensors.Temperature)
|
||||
<> " "
|
||||
|
|
@ -28,3 +28,17 @@ pub fn parse_topic_1_test() {
|
|||
sensors.SensorReading(sensor: sensors.Pressure, value: 944.67),
|
||||
])
|
||||
}
|
||||
|
||||
pub fn parse_topic_2_test() {
|
||||
let json_string = "{\"pm1\":16.83,\"pm2_5\":10.68,\"pm10\":16.619719}"
|
||||
let readings = sensors.parse_topic_2(json_string)
|
||||
readings
|
||||
|> should.equal([
|
||||
sensors.SensorReading(sensor: sensors.ParticalMatterOne, value: 16.83),
|
||||
sensors.SensorReading(
|
||||
sensor: sensors.ParticalMatterTwoPointFive,
|
||||
value: 10.68,
|
||||
),
|
||||
sensors.SensorReading(sensor: sensors.ParticalMatterTen, value: 16.619719),
|
||||
])
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue