first handler writing to database
This commit is contained in:
85
src/udi/handlers/pv/pv.go
Normal file
85
src/udi/handlers/pv/pv.go
Normal file
@ -0,0 +1,85 @@
|
||||
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("Enable 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)
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user