Update board.go and board_mqtt.go
This commit is contained in:
parent
bcfbbaba80
commit
5e2a7c46bc
@ -13,7 +13,6 @@ type Channel interface {
|
||||
Off() error
|
||||
ToString() string
|
||||
UpdateMQTT()
|
||||
OnChange()
|
||||
Status() bool
|
||||
Parent() Board
|
||||
Dump()
|
||||
|
@ -7,6 +7,7 @@ import (
|
||||
"time"
|
||||
|
||||
MQTT "github.com/eclipse/paho.mqtt.golang"
|
||||
mqtt "github.com/eclipse/paho.mqtt.golang"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
@ -115,19 +116,25 @@ func newMQTTBoard(v *viper.Viper, id string) *MQTTBoard {
|
||||
|
||||
func (c *MQTTChannel) Toggle() (bool, error) {
|
||||
c.Value = !c.Value
|
||||
c.OnChange()
|
||||
c.SaveLastState()
|
||||
c.UpdateMQTT()
|
||||
c.UpdateRemoteMQTT()
|
||||
return c.Value, nil
|
||||
}
|
||||
|
||||
func (c *MQTTChannel) On() error {
|
||||
c.Value = true
|
||||
c.OnChange()
|
||||
c.SaveLastState()
|
||||
c.UpdateMQTT()
|
||||
c.UpdateRemoteMQTT()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *MQTTChannel) Off() error {
|
||||
c.Value = true
|
||||
c.OnChange()
|
||||
c.SaveLastState()
|
||||
c.UpdateMQTT()
|
||||
c.UpdateRemoteMQTT()
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -140,18 +147,20 @@ func (c *MQTTChannel) ToString() string {
|
||||
|
||||
func (c *MQTTChannel) UpdateMQTT() {
|
||||
MQTTpublish(c.MQTTTopic, c.ToString())
|
||||
if c.parent.MQTTClient.IsConnected() {
|
||||
c.parent.MQTTClient.Publish(c.MQTTRemoteTopic, 0, false, c.ToString())
|
||||
}
|
||||
}
|
||||
|
||||
func (c *MQTTChannel) OnChange() {
|
||||
func (c *MQTTChannel) SaveLastState() {
|
||||
if c.onboot == "last" {
|
||||
s := fmt.Sprintf("boards.%s.channels.%s.lastvalue", c.parent.ID, c.ID)
|
||||
viper.Set(s, c.Value)
|
||||
viper.WriteConfig()
|
||||
}
|
||||
c.UpdateMQTT()
|
||||
}
|
||||
|
||||
func (c *MQTTChannel) UpdateRemoteMQTT() {
|
||||
if c.parent.MQTTClient.IsConnected() {
|
||||
c.parent.MQTTClient.Publish(c.MQTTRemoteTopic, 0, false, c.ToString())
|
||||
}
|
||||
}
|
||||
|
||||
func (c *MQTTChannel) Status() bool {
|
||||
@ -212,6 +221,31 @@ func (b *MQTTBoard) Init() {
|
||||
}
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
|
||||
for i := range b.Channels {
|
||||
topic := b.Channels[i].MQTTRemoteTopic
|
||||
if topic == "" {
|
||||
continue
|
||||
}
|
||||
b.MQTTClient.Subscribe(topic, 1, b.Channels[i].MQTTSubHandler)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *MQTTChannel) MQTTSubHandler(client mqtt.Client, msg mqtt.Message) {
|
||||
switch string(msg.Payload()) {
|
||||
case "on":
|
||||
if !c.Value {
|
||||
c.Value = true
|
||||
c.SaveLastState()
|
||||
c.UpdateMQTT()
|
||||
}
|
||||
case "off":
|
||||
if c.Value {
|
||||
c.Value = false
|
||||
c.SaveLastState()
|
||||
c.UpdateMQTT()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (b *MQTTBoard) Channel(num uint64) Channel {
|
||||
|
Loading…
Reference in New Issue
Block a user