Files
universal-data-ingest/src/udi/handlers/pv/pv.go
2023-12-01 22:36:21 +01:00

86 lines
2.2 KiB
Go

package pv
import (
"log"
"reflect"
"time"
"encoding/json"
"udi/handlers/handler"
"udi/database"
)
var idSeq int = 0
type PvHandler struct {
id int
dbh *database.DatabaseHandle
}
type PvValue struct {
ImportEnergyActive float32 `unit:"Wh" json:"importEnergyActive"`
ImportEnergyReactive float32 `unit:"VAh" json:"importEnergyReactive"`
ExportEnergyActive float32 `unit:"Wh" json:"exportEnergyActive"`
ExportEnergyReactive float32 `unit:"VAh" json:"exportEnergyiReactive"`
PowerApparent float32 `unit:"VA" json:"powerApparent"`
PowerActive float32 `unit:"W" json:"powerActive"`
PowerReactive float32 `unit:"VA" json:"powerReactive"`
PowerDemandPositive float32 `unit:"W" json:"powerDemandPositive"`
PowerDemandReverse float32 `unit:"W" json:"powerDemandReverse"`
Factor float32 `unit:"" json:"factor"`
Angle float32 `unit:"degree" json:"angle"`
Voltage float32 `unit:"V" json:"voltage"`
Current float32 `unit:"A" json:"current"`
State int `unit:"" json:"state"`
Status string `unit:"" json:"status"`
Timestamp string `unit:"" json:"timestamp"`
Cnt int `unit:"" json:"cnt"`
}
func NewPvHandler() *PvHandler {
t := &PvHandler {
id: idSeq,
}
idSeq += 1
t.dbh = database.NewDatabaseHandle("")
return t
}
func (self *PvHandler) Handle(message handler.MessageT) {
log.Printf("Handler PV %d processing %s -> %s", self.id, message.Topic, message.Payload)
var pvValue PvValue
err := json.Unmarshal([]byte(message.Payload), &pvValue)
if err != nil {
log.Printf("Unable to parse payload into pvValue struct, values are lost: ", err)
return
}
variables := make(map[string]database.VariableType)
pvValueStructValue := reflect.ValueOf(pvValue)
for i := 0; i < pvValueStructValue.NumField(); i++ {
field := pvValueStructValue.Type().Field(i)
fieldValue := pvValueStructValue.Field(i)
v := database.VariableType {
Label: "",
Variable: field.Name,
Unit: field.Tag.Get("unit"),
Value: fieldValue.Interface(),
}
variables[field.Name] = v
}
measurement := database.Measurement {
Time: time.Now(),
Application: "PV",
Device: "Powermeter",
Values: variables,
}
self.dbh.StoreMeasurement(&measurement)
}