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

96 lines
2.0 KiB
Go
Raw Permalink Normal View History

2021-12-10 01:14:34 +00:00
package manager
import (
"context"
2021-12-10 06:45:28 +00:00
"errors"
2021-12-10 01:14:34 +00:00
"log"
"git.godopu.net/lab/etri-smartfarm-poc-controller-serial/puserial"
"github.com/rjeczalik/notify"
)
var ctx context.Context
var cancel context.CancelFunc
var ch_discover chan notify.EventInfo
var _managerObj *_manager
2021-12-10 08:07:20 +00:00
var registerHandleFunc func(uuid string)
var removeHandleFunc func(uuid string)
2021-12-10 01:14:34 +00:00
func init() {
ctx, cancel = context.WithCancel(context.Background())
ch_discover = make(chan notify.EventInfo)
2021-12-10 06:45:28 +00:00
devWithUUID := map[string]*_device{}
devWithIface := map[interface{}]*_device{}
chanForSync := map[string]chan map[string]interface{}{}
2021-12-10 01:14:34 +00:00
_managerObj = &_manager{
2021-12-10 06:45:28 +00:00
devicesWithUUID: devWithUUID,
devicesWithIface: devWithIface,
2021-12-10 08:07:20 +00:00
chanForSync: chanForSync,
2021-12-10 06:45:28 +00:00
SyncListener: &SyncHandler{devices: devWithUUID, chanForSync: chanForSync},
RecvListener: &RecvHandler{devices: devWithIface, chanForSync: chanForSync},
2021-12-10 01:14:34 +00:00
}
2021-12-10 06:45:28 +00:00
2021-12-10 08:07:20 +00:00
registerHandleFunc = nil
removeHandleFunc = nil
}
func AddRegisterHandleFunc(h func(uuid string)) {
registerHandleFunc = h
}
func AddRemoveHandleFunc(h func(uuid string)) {
removeHandleFunc = h
2021-12-10 01:14:34 +00:00
}
func Close() {
cancel()
}
2021-12-10 06:45:28 +00:00
func Sync(key string, param map[string]interface{}) {
_managerObj.onSync(key, param)
}
2021-12-10 01:14:34 +00:00
2021-12-10 08:07:20 +00:00
func AddRecvListener(h EventHandler) {
_managerObj.addRecvListener(h)
}
2021-12-10 06:45:28 +00:00
func SetDevicePropsToSync(uuid string, propsToSync []string) error {
device, ok := _managerObj.devicesWithUUID[uuid]
if !ok {
return errors.New("device not found")
2021-12-10 01:14:34 +00:00
}
2021-12-10 06:45:28 +00:00
device.propsToSync = propsToSync
return nil
2021-12-10 01:14:34 +00:00
}
func Run() error {
iface, err := puserial.InitDevice()
if err != nil {
if err.Error() != "USB Not found" {
return err
}
} else {
// _managerObj.onAdd(iface)
2021-12-10 06:45:28 +00:00
_managerObj.onAdded(iface)
2021-12-10 01:14:34 +00:00
}
go puserial.WatchNewDevice(ctx, ch_discover)
for {
e, ok := <-ch_discover
if !ok {
log.Println("manager exit")
return nil
}
2021-12-10 08:07:20 +00:00
switch e.Event() {
case notify.Create:
_managerObj.onAdded(e.Path())
// case notify.Remove:
// log.Println("USB Disconnected!!")
// _managerObj.onAdded(e.Path())
}
2021-12-10 01:14:34 +00:00
}
}