Make fortoprt handling more robust

This commit is contained in:
Nise Void 2018-09-28 14:05:06 +02:00
parent c83feeb845
commit bd9e9136e6
Signed by: NiseVoid
GPG Key ID: FBA14AC83EA602F3

View File

@ -8,6 +8,7 @@ import (
"git.fuyu.moe/5GPowerQuality/parser/data" "git.fuyu.moe/5GPowerQuality/parser/data"
"git.fuyu.moe/5GPowerQuality/parser/shared" "git.fuyu.moe/5GPowerQuality/parser/shared"
"git.fuyu.moe/Fuyu/flog"
"golang.org/x/net/websocket" "golang.org/x/net/websocket"
) )
@ -43,51 +44,61 @@ func FetchData() {
requestData(conn, 2) requestData(conn, 2)
for { for {
b, n := make([]byte, 16384), 0 readData(conn)
msg := message{}
for {
nn, err := conn.Read(b[n:])
if err != nil {
panic(err)
}
n += nn
err = json.Unmarshal(b[:n], &msg)
if err != nil {
continue
}
break
}
// sets := data.Sets{}
mID := data.GetMeterID(data.SourceFortop, host+`-`+strconv.Itoa(msg.Data["U1"].DeviceID))
sets := data.Sets{}
for k, v := range msg.Data {
key := data.Key{Meter: mID, Time: time.Time(v.Timestamp)}
if _, ok := sets[key]; !ok {
sets[key] = data.Set{}
}
if len(k) == 2 {
n := k[1:]
if n == `4` {
n = `N`
}
k = k[:1] + `Gem` + n
}
sets[key][k] = v.Value
}
data.InsertSets(sets)
} }
} }
func readData(conn *websocket.Conn) {
defer func() {
v := recover()
if v != nil {
flog.Critical(v)
}
}()
b, n := make([]byte, 16384), 0
msg := message{}
for {
nn, err := conn.Read(b[n:])
if err != nil {
panic(err)
}
n += nn
err = json.Unmarshal(b[:n], &msg)
if err != nil {
continue
}
break
}
mID := data.GetMeterID(data.SourceFortop, host+`-`+strconv.Itoa(msg.Data["U1"].DeviceID))
sets := data.Sets{}
for k, v := range msg.Data {
key := data.Key{Meter: mID, Time: time.Time(v.Timestamp)}
if _, ok := sets[key]; !ok {
sets[key] = data.Set{}
}
if len(k) == 2 {
n := k[1:]
if n == `4` {
n = `N`
}
k = k[:1] + `Gem` + n
}
sets[key][k] = v.Value
}
data.InsertSets(sets)
}
func requestData(conn *websocket.Conn, meter int) { func requestData(conn *websocket.Conn, meter int) {
write(conn, `{"MESSAGEINFO":{"VERSION":1,"APPLICATION":"DCEM_ENTERPRISE","MODULE":"LIVEDATA","FUNCTION":"REQUEST_DATASTREAM","REVISION":1},"VARS":{"DEVICEID":`+strconv.Itoa(meter)+`,"VALUES":`+values+`}}`) write(conn, `{"MESSAGEINFO":{"VERSION":1,"APPLICATION":"DCEM_ENTERPRISE","MODULE":"LIVEDATA","FUNCTION":"REQUEST_DATASTREAM","REVISION":1},"VARS":{"DEVICEID":`+strconv.Itoa(meter)+`,"VALUES":`+values+`}}`)
} }