etri-smartfarm-poc-controll.../listener.go

115 lines
2.2 KiB
Go
Raw Normal View History

2021-12-10 01:14:34 +00:00
package manager
2021-12-10 06:45:28 +00:00
import (
"encoding/json"
"fmt"
"log"
)
2021-12-10 01:14:34 +00:00
2021-12-10 06:45:28 +00:00
type SyncHandler struct {
devices map[string]*_device
chanForSync map[string]chan map[string]interface{}
}
func compareMap(src map[string]interface{}, dst map[string]interface{}, props []string) bool {
for _, prop := range props {
srcV, ok := src[prop].(int)
if !ok {
srcV = int(src[prop].(float64))
}
dstV, ok := dst[prop].(int)
if !ok {
dstV = int(dst[prop].(float64))
}
if srcV != dstV {
fmt.Println("diff ", prop, "] ", srcV, " vs ", dstV)
return false
}
}
return true
}
func (sh *SyncHandler) Handle(e Event) {
device, ok := sh.devices[e.Key().(string)]
// fmt.Println("sync] ", device.IfaceName)
// fmt.Println(sh.devices)
if !ok {
return
}
2021-12-10 01:14:34 +00:00
2021-12-10 06:45:28 +00:00
params := e.Params()
if params == nil {
return
}
go func() {
encoder := json.NewEncoder(device.Iface)
origin := map[string]interface{}{}
origin["code"] = 200
props := device.propsToSync
// props := []string{"fan", "light", "servo"}
for _, pname := range props {
prop, ok := params[pname]
if !ok {
origin[pname] = device.states[pname]
} else {
origin[pname] = prop
}
}
err := encoder.Encode(origin)
if err != nil {
return
}
sh.chanForSync[device.IfaceName] = make(chan map[string]interface{})
for state := range sh.chanForSync[device.IfaceName] {
if compareMap(origin, state, props) {
log.Println("Same!!")
close(sh.chanForSync[device.IfaceName])
delete(sh.chanForSync, device.IfaceName)
return
}
log.Println("wrong: ", state)
log.Println("resend: ", origin)
err := encoder.Encode(origin)
if err != nil {
return
}
}
}()
2021-12-10 01:14:34 +00:00
}
2021-12-10 06:45:28 +00:00
type RecvHandler struct {
devices map[interface{}]*_device
chanForSync map[string]chan map[string]interface{}
2021-12-10 08:07:20 +00:00
next EventHandler
2021-12-10 06:45:28 +00:00
}
func (rh *RecvHandler) Handle(e Event) {
device, ok := rh.devices[e.Key()]
if !ok {
return
}
param := e.Params()
code, _ := param["code"].(float64)
2021-12-10 08:07:20 +00:00
if int(code) == 100 {
return
2021-12-10 06:45:28 +00:00
}
2021-12-10 01:14:34 +00:00
2021-12-10 08:07:20 +00:00
device.states = param
2021-12-10 06:45:28 +00:00
channel, ok := rh.chanForSync[device.IfaceName]
if ok {
channel <- device.states
}
2021-12-10 01:14:34 +00:00
2021-12-10 08:07:20 +00:00
if rh.next != nil {
rh.next.Handle(e)
}
2021-12-10 06:45:28 +00:00
// fmt.Println("recv] ", device.states)
2021-12-10 01:14:34 +00:00
}