robocar-led/part/part.go

105 lines
2.3 KiB
Go
Raw Normal View History

2019-12-14 10:56:22 +00:00
package part
import (
"fmt"
"github.com/cyrilix/robocar-base/mqttdevice"
2019-12-27 15:51:39 +00:00
"github.com/cyrilix/robocar-base/service"
"github.com/cyrilix/robocar-base/types"
2019-12-14 10:56:22 +00:00
"github.com/cyrilix/robocar-led/led"
mqtt "github.com/eclipse/paho.mqtt.golang"
"log"
"sync"
"time"
)
func NewPart(client mqtt.Client, driveModeTopic, recordTopic string) *LedPart {
return &LedPart{
led: led.New(),
client: client,
onDriveModeTopic: driveModeTopic,
onRecordTopic: recordTopic,
muDriveMode: sync.Mutex{},
2019-12-27 15:51:39 +00:00
m: types.DriveModeInvalid,
2019-12-14 10:56:22 +00:00
muRecord: sync.Mutex{},
recordEnabled: false,
}
}
type LedPart struct {
led led.ColoredLed
client mqtt.Client
onDriveModeTopic string
onRecordTopic string
muDriveMode sync.Mutex
2019-12-27 15:51:39 +00:00
m types.DriveMode
2019-12-14 10:56:22 +00:00
muRecord sync.Mutex
recordEnabled bool
}
func (p *LedPart) Start() error {
if err := p.registerCallbacks(); err != nil {
return fmt.Errorf("unable to start service: %v", err)
}
for {
time.Sleep(1 * time.Hour)
}
}
func (p *LedPart) Stop() {
2019-12-17 23:28:15 +00:00
defer p.led.SetBlink(0)
defer p.led.SetGreen(0)
defer p.led.SetBlue(0)
defer p.led.SetRed(0)
2019-12-27 15:51:39 +00:00
service.StopService("led", p.client, p.onDriveModeTopic, p.onRecordTopic)
2019-12-14 10:56:22 +00:00
}
func (p *LedPart) onDriveMode(_ mqtt.Client, message mqtt.Message) {
2019-12-18 20:22:09 +00:00
payload := message.Payload()
value := mqttdevice.NewMqttValue(payload)
m, err := value.DriveModeValue()
2019-12-14 10:56:22 +00:00
if err != nil {
2019-12-18 20:22:09 +00:00
log.Printf("invalid drive mode: %v", err)
2019-12-14 10:56:22 +00:00
return
}
switch m {
2019-12-27 15:51:39 +00:00
case types.DriveModeUser:
2019-12-14 10:56:22 +00:00
p.led.SetRed(0)
p.led.SetGreen(255)
p.led.SetBlue(0)
2019-12-27 15:51:39 +00:00
case types.DriveModePilot:
2019-12-14 10:56:22 +00:00
p.led.SetRed(0)
p.led.SetGreen(0)
p.led.SetBlue(255)
}
}
func (p *LedPart) onRecord(client mqtt.Client, message mqtt.Message) {
mqttValue := mqttdevice.NewMqttValue(message.Payload())
rec, err := mqttValue.BoolValue()
if err != nil {
log.Printf("unable to convert message payload '%v' to bool: %v", message.Payload(), err)
return
}
if rec {
p.led.SetBlink(2)
} else {
p.led.SetBlink(0)
}
}
func (p *LedPart) registerCallbacks() error {
2019-12-27 15:51:39 +00:00
err := service.RegisterCallback(p.client, p.onDriveModeTopic, p.onDriveMode)
2019-12-14 10:56:22 +00:00
if err != nil {
return err
}
2019-12-27 15:51:39 +00:00
err = service.RegisterCallback(p.client, p.onRecordTopic, p.onRecord)
2019-12-14 10:56:22 +00:00
if err != nil {
return err
}
return nil
}