Use channel to exit start loop
This commit is contained in:
parent
3b228216fa
commit
6157e27850
17
part/part.go
17
part/part.go
@ -26,6 +26,8 @@ type Pca9685Part struct {
|
||||
|
||||
throttleTopic string
|
||||
steeringTopic string
|
||||
|
||||
cancel chan interface{}
|
||||
}
|
||||
|
||||
func NewPca9685Part(client MQTT.Client, throttleCtrl *actuator.Throttle, steeringCtrl *actuator.Steering, updateFrequency int, throttleTopic, steeringTopic string) *Pca9685Part {
|
||||
@ -36,6 +38,7 @@ func NewPca9685Part(client MQTT.Client, throttleCtrl *actuator.Throttle, steerin
|
||||
updateFrequency: updateFrequency,
|
||||
throttleTopic: throttleTopic,
|
||||
steeringTopic: steeringTopic,
|
||||
cancel: make(chan interface{}),
|
||||
}
|
||||
}
|
||||
|
||||
@ -43,20 +46,26 @@ func (p *Pca9685Part) Start() error {
|
||||
if err := p.registerCallbacks(); err != nil {
|
||||
return fmt.Errorf("unable to start service: %v", err)
|
||||
}
|
||||
defer p.Stop()
|
||||
ticker := time.NewTicker(time.Second / time.Duration(p.updateFrequency))
|
||||
|
||||
for {
|
||||
time.Sleep(time.Second / time.Duration(p.updateFrequency))
|
||||
select {
|
||||
case <-ticker.C:
|
||||
p.updateCtrl()
|
||||
case <-p.cancel:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Pca9685Part) Stop() {
|
||||
close(p.cancel)
|
||||
service.StopService("pca9685", p.client, p.throttleTopic, p.steeringTopic)
|
||||
}
|
||||
|
||||
func (p *Pca9685Part) onThrottleChange(_ MQTT.Client, message MQTT.Message) {
|
||||
var throttle types.Throttle
|
||||
err := json.Unmarshal(message.Payload(), throttle)
|
||||
err := json.Unmarshal(message.Payload(), &throttle)
|
||||
if err != nil {
|
||||
log.Printf("[%v] unable to unmarshall throttle msg: %v", message.Topic(), err)
|
||||
return
|
||||
@ -68,7 +77,7 @@ func (p *Pca9685Part) onThrottleChange(_ MQTT.Client, message MQTT.Message) {
|
||||
|
||||
func (p *Pca9685Part) onSteeringChange(_ MQTT.Client, message MQTT.Message) {
|
||||
var steering types.Steering
|
||||
err := json.Unmarshal(message.Payload(), steering)
|
||||
err := json.Unmarshal(message.Payload(), &steering)
|
||||
if err != nil {
|
||||
log.Printf("[%v] unable to unmarshall steering msg: %v", message.Topic(), err)
|
||||
return
|
||||
|
Loading…
Reference in New Issue
Block a user