You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
1.4 KiB
Go

package reactor
import (
pb "FRMS/internal/pkg/grpc"
"FRMS/internal/pkg/sensor"
"sync"
)
type DeviceManager interface {
GetInfo() (*pb.Device, error)
SetStatus(int) error
}
func NewDeviceManager(addr int, status int) (DeviceManager, error) {
dev := &pb.Device{Addr: int32(addr), Status: pb.Status(int32(status))}
return sensor.NewDeviceManager(dev)
}
type DeviceCoordinator struct {
Managers map[int]DeviceManager
sync.RWMutex
}
func NewDeviceCoordinator() *DeviceCoordinator {
dm := &DeviceCoordinator{}
dm.Managers = make(map[int]DeviceManager)
return dm
}
func (c *DeviceCoordinator) UpdateDevices(active map[int]bool) error {
// update dev status, add new ones
c.Lock()
defer c.Unlock()
var err error
for addr, _ := range active {
// loop over devs
if _, ok := c.Managers[addr]; !ok {
// no device
if c.Managers[addr], err = NewDeviceManager(addr, 1); err != nil {
return err
}
}
}
// all devs accounted for
for addr, dm := range c.Managers {
if active[addr] {
err = dm.SetStatus(1)
} else {
err = dm.SetStatus(0)
}
if err != nil {
return err
}
}
return err
}
func (c *DeviceCoordinator) GetDevices() ([]*pb.Device, error) {
// TODO
c.RLock()
defer c.RUnlock()
var err error
var devices []*pb.Device
var dev *pb.Device
for _, dm := range c.Managers {
dev, err = dm.GetInfo()
devices = append(devices, dev)
}
return devices, err
}