90 lines
2.4 KiB
Go
90 lines
2.4 KiB
Go
package draginoLdds75
|
|
|
|
import (
|
|
"fmt"
|
|
// "log"
|
|
"strings"
|
|
"strconv"
|
|
"encoding/json"
|
|
"udi/database"
|
|
)
|
|
|
|
/*
|
|
"decoded_payload": {
|
|
"Bat": 3.299,
|
|
"Distance": "352 mm",
|
|
"Interrupt_flag": 0,
|
|
"Sensor_flag": 1,
|
|
"TempC_DS18B20": "0.00"
|
|
},
|
|
*/
|
|
type message struct {
|
|
Bat float32 `json:"Bat"`
|
|
Distance string `json:"Distance"`
|
|
Interrupt_flag int `json:"Interrupt_flag"`
|
|
Sensor_flag int `json:"Sensor_flag"`
|
|
TempC_DS18B20 string `json:"TempC_DS18B20"`
|
|
}
|
|
|
|
func Parse(fPort int, decodedPayload []byte, _ string, variables *map[string]database.VariableType, attributes *map[string]interface{}, device *database.Device) error {
|
|
if fPort != 2 {
|
|
return fmt.Errorf("Unexpected fPort %d", fPort)
|
|
}
|
|
var message message
|
|
err := json.Unmarshal(decodedPayload, &message)
|
|
if err != nil {
|
|
return fmt.Errorf("Unable to parse payload, fPort %d, error %s", fPort, err)
|
|
}
|
|
distanceParts := strings.Split(message.Distance, " ")
|
|
if len(distanceParts) != 2 && distanceParts[1] != "mm" {
|
|
return fmt.Errorf("Invalid format for distance value: %s", message.Distance)
|
|
}
|
|
distance, err2 := strconv.Atoi(distanceParts[0])
|
|
if err2 != nil {
|
|
return fmt.Errorf("Distance value is no number: %s -> %s", message.Distance, err2)
|
|
}
|
|
(*variables)["Battery"] = database.VariableType {
|
|
Label: "Battery",
|
|
Variable: "Voltage",
|
|
Unit: "V",
|
|
Value: message.Bat,
|
|
}
|
|
(*variables)["Distance"] = database.VariableType {
|
|
Label: "Distance",
|
|
Variable: "Level",
|
|
Unit: "mm",
|
|
Value: distance,
|
|
}
|
|
|
|
if distance == 20 {
|
|
(*attributes)["Status"] = "invalid value"
|
|
} else if distance == 0 {
|
|
(*attributes)["Status"] = "no sensor detected"
|
|
} else {
|
|
(*attributes)["Status"] = "Ok"
|
|
}
|
|
|
|
groundLevelI, exists := device.Attributes["GroundLevel"]
|
|
groundLevelS, ok := groundLevelI.(string)
|
|
groundLevel, err3 := strconv.Atoi(groundLevelS)
|
|
if exists && err3 == nil && ok {
|
|
//log.Println("add corrected distance")
|
|
correctedDistance := groundLevel - distance
|
|
(*variables)["CorrectedDistance"] = database.VariableType {
|
|
Label: "CorrectedDistance",
|
|
Variable: "Level",
|
|
Unit: "mm",
|
|
Value: correctedDistance,
|
|
}
|
|
} /* else {
|
|
log.Printf("no ground level: %s %s %s", exists, err3, ok)
|
|
log.Printf("Device: %s", device)
|
|
log.Printf("Attributes: %s", device.Attributes)
|
|
} */
|
|
|
|
return nil
|
|
}
|
|
|
|
|
|
|