github.com/simpleiot/simpleiot@v0.18.3/node/modbus-io.go (about) 1 package node 2 3 import ( 4 "log" 5 "time" 6 7 "github.com/nats-io/nats.go" 8 "github.com/simpleiot/simpleiot/data" 9 ) 10 11 // ModbusIO represents the state of a managed modbus io 12 type ModbusIO struct { 13 ioNode *ModbusIONode 14 sub *nats.Subscription 15 lastSent time.Time 16 } 17 18 // NewModbusIO creates a new modbus IO 19 func NewModbusIO(nc *nats.Conn, node *ModbusIONode, chPoint chan<- pointWID) (*ModbusIO, error) { 20 io := &ModbusIO{ 21 ioNode: node, 22 } 23 24 var err error 25 io.sub, err = nc.Subscribe("p."+io.ioNode.nodeID, func(msg *nats.Msg) { 26 points, err := data.PbDecodePoints(msg.Data) 27 if err != nil { 28 // FIXME, send over channel 29 log.Println("Error decoding node data:", err) 30 return 31 } 32 33 for _, p := range points { 34 chPoint <- pointWID{io.ioNode.nodeID, p} 35 } 36 }) 37 38 if err != nil { 39 return nil, err 40 } 41 42 return io, nil 43 } 44 45 // Stop io 46 func (io *ModbusIO) Stop() { 47 if io.sub != nil { 48 err := io.sub.Unsubscribe() 49 if err != nil { 50 log.Println("Error unsubscribing from IO:", err) 51 } 52 } 53 }