Update board_mqtt.go

This commit is contained in:
Paolo Asperti 2021-01-05 17:15:36 +01:00
parent 5e2a7c46bc
commit 355bb6532b

View File

@ -19,7 +19,10 @@ type MQTTChannel struct {
Value bool
onboot string
parent *MQTTBoard
MQTTRemoteTopic string
MQTTRemoteStateTopic string
MQTTRemoteCommandTopic string
MQTTRemotePayloadOn string
MQTTRemotePayloadOff string
}
type MQTTBoard struct {
@ -40,7 +43,10 @@ func newMQTTChannel(v *viper.Viper, channelID string) MQTTChannel {
v.SetDefault("lastValue", false)
v.SetDefault("onboot", "off")
v.SetDefault("mqtttopic", v.GetString("name"))
v.SetDefault("mqttremote.topic", v.GetString("name"))
v.SetDefault("mqttremote.statetopic", v.GetString("name"))
v.SetDefault("mqttremote.commandtopic", v.GetString("name"))
v.SetDefault("mqttremote.payloadon", "on")
v.SetDefault("mqttremote.payloadoff", "off")
value := false
switch v.GetString("onboot") {
@ -58,7 +64,10 @@ func newMQTTChannel(v *viper.Viper, channelID string) MQTTChannel {
MQTTTopic: v.GetString("mqtttopic"),
Value: value,
onboot: v.GetString("onboot"),
MQTTRemoteTopic: v.GetString("mqttremote.topic"),
MQTTRemoteStateTopic: v.GetString("mqttremote.statetopic"),
MQTTRemoteCommandTopic: v.GetString("mqttremote.commandtopic"),
MQTTRemotePayloadOn: v.GetString("mqttremote.payloadon"),
MQTTRemotePayloadOff: v.GetString("mqttremote.payloadoff"),
}
}
@ -159,7 +168,11 @@ func (c *MQTTChannel) SaveLastState() {
func (c *MQTTChannel) UpdateRemoteMQTT() {
if c.parent.MQTTClient.IsConnected() {
c.parent.MQTTClient.Publish(c.MQTTRemoteTopic, 0, false, c.ToString())
v := c.MQTTRemotePayloadOff
if c.Value {
v = c.MQTTRemotePayloadOn
}
c.parent.MQTTClient.Publish(c.MQTTRemoteCommandTopic, 0, false, v)
}
}
@ -223,7 +236,7 @@ func (b *MQTTBoard) Init() {
}
for i := range b.Channels {
topic := b.Channels[i].MQTTRemoteTopic
topic := b.Channels[i].MQTTRemoteStateTopic
if topic == "" {
continue
}
@ -233,13 +246,13 @@ func (b *MQTTBoard) Init() {
func (c *MQTTChannel) MQTTSubHandler(client mqtt.Client, msg mqtt.Message) {
switch string(msg.Payload()) {
case "on":
case c.MQTTRemotePayloadOn:
if !c.Value {
c.Value = true
c.SaveLastState()
c.UpdateMQTT()
}
case "off":
case c.MQTTRemotePayloadOff:
if c.Value {
c.Value = false
c.SaveLastState()