parse topic 2
All checks were successful
Unit Tests / Run Tests (push) Successful in 11s

This commit is contained in:
Travis Shears 2026-03-25 11:21:04 +01:00
parent fbcafef67c
commit cad01edab8
Signed by: travisshears
GPG key ID: CB9BF1910F3F7469
3 changed files with 38 additions and 3 deletions

View file

@ -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)
}
}

View file

@ -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))