-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmqtt.go
227 lines (198 loc) · 5.75 KB
/
mqtt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"time"
MQTT "github.com/eclipse/paho.mqtt.golang"
"github.com/rs/zerolog/log"
)
const (
TIMEOUT time.Duration = time.Second * 10
SUBSCRIBE = APPNAME + "/set"
)
type SetTimer struct {
Id string `json:"id"`
Description string `json:"description"`
Start string `json:"start"`
Interval string `json:"interval"`
Until string `json:"until"`
Topic string `json:"topic"`
Message interface{} `json:"message"`
Enable *bool `json:"enable,omitempty"`
}
var mqttClient MQTT.Client
func sendToMtt(topic string, message string) {
mqttClient.Publish(topic, byte(config.Mqtt.Qos), config.Mqtt.Retain, message)
}
func sendToMttRetain(topic string, message string) {
mqttClient.Publish(topic, byte(config.Mqtt.Qos), true, message)
}
func receive(client MQTT.Client, msg MQTT.Message) {
message := string(msg.Payload()[:])
var setTimer SetTimer
err := json.Unmarshal([]byte(message), &setTimer)
if err != nil {
log.Error().Msgf("JSON Error: %s", err.Error())
return
}
err = validateMessage(setTimer)
if err != nil {
log.Warn().Msgf("MQTT message error: %s", err.Error())
return
}
if timerInConfig(setTimer) {
return
}
if setTimer.Enable != nil && *setTimer.Enable {
log.Error().Msgf("MQTT message error: programmable timers can only be disabled")
return
}
removed := scheduler.RemoveByTag(setTimer.Id)
if setTimer.Enable != nil {
if removed == nil {
if !*setTimer.Enable {
log.Debug().Msgf("Reset '%s'", setTimer.Id)
}
} else {
log.Warn().Msgf("Warning: timer '%s' not found", setTimer.Id)
}
return
}
var messages []string
if setTimer.Topic == "" {
setTimer.Topic = TIMERS_TOPIC + setTimer.Id + "/event"
}
if setTimer.Message != nil {
switch setTimer.Message.(type) {
case string:
messages = append(messages, setTimer.Message.(string))
case []interface{}:
msgArray := setTimer.Message.([]interface{})
for _, message := range msgArray {
messages = append(messages, message.(string))
}
default:
log.Error().Msgf("Error: incorrect message type: %s", fmt.Sprint(setTimer.Message))
}
} else {
messages = append(messages, setTimer.Id)
}
startTime, err := parseStart(setTimer.Start)
if err != nil {
log.Error().Err(err)
return
}
offset, err := parseInterval(setTimer.Interval, messages)
if err != nil {
log.Error().Err(err)
return
}
until, untilTime := parseUntil(setTimer.Until, startTime)
isEnd := true
for isEnd {
for _, message := range messages {
timer := Timer{}
timer.Active = true
timer.Id = setTimer.Id
timer.Description = strings.TrimPrefix(fmt.Sprintf("%s [%s]", setTimer.Description, message), " ")
timer.Time = startTime.Format("15:04:05")
timer.Topic = setTimer.Topic
timer.Message = message
job, err := scheduler.Every(1).Day().At(startTime).Tag(timer.Id).Do(handleEvent, &timer)
if err != nil {
log.Error().Msgf("Scheduler Error: %s", err.Error())
return
}
job.LimitRunsTo(1)
startTime = startTime.Add(offset)
}
if until > 0 {
until--
isEnd = until > 0
} else if until < 0 {
t1 := startTime.Hour()*60*60 + startTime.Minute()*60 + startTime.Second()
t2 := untilTime.Hour()*60*60 + untilTime.Minute()*60 + untilTime.Second()
isEnd = t1 < t2
} else {
isEnd = false
}
}
}
func GetClientId() string {
hostname, _ := os.Hostname()
return APPNAME + "_" + hostname
}
func validateMessage(msg SetTimer) error {
if msg.Id == "" {
return errors.New("id is mandatory")
}
if msg.Enable == nil {
if msg.Start == "" && msg.Interval == "" {
return errors.New("start or interval must be specified")
}
if msg.Until != "" && msg.Interval == "" {
return errors.New("interval must have a value if until is specified")
}
} else {
if msg.Start != "" || msg.Interval != "" || msg.Until != "" || msg.Topic != "" || msg.Message != nil {
return errors.New("enable cannot be combined with other fields")
}
}
return nil
}
func timerInConfig(setTimer SetTimer) bool {
inConfig := false
id, wildcard := strings.CutSuffix(setTimer.Id, "*")
// check config
for i := 0; i < len(config.Timers); i++ {
if config.Timers[i].Id == id || wildcard && strings.HasPrefix(config.Timers[i].Id, id) {
if setTimer.Enable != nil {
config.Timers[i].Active = *setTimer.Enable
if config.Timers[i].Active {
log.Info().Msgf("Enabled '%s'", config.Timers[i].Id)
} else {
log.Info().Msgf("Disabled '%s'", config.Timers[i].Id)
}
inConfig = true
}
if !inConfig {
log.Error().Msgf("Error: timer '%s' defined in config", setTimer.Id)
inConfig = true
}
}
}
return inConfig
}
func startMqttClient() {
opts := MQTT.NewClientOptions().AddBroker(config.Mqtt.Url)
if config.Mqtt.Username != "" && config.Mqtt.Password != "" {
opts.SetUsername(config.Mqtt.Username)
opts.SetPassword(config.Mqtt.Password)
}
opts.SetClientID(GetClientId())
opts.SetCleanSession(true)
opts.SetBinaryWill(APPNAME+"/status", []byte("Offline"), 0, true)
opts.SetAutoReconnect(true)
opts.SetConnectionLostHandler(connLostHandler)
opts.SetOnConnectHandler(onConnectHandler)
mqttClient = MQTT.NewClient(opts)
token := mqttClient.Connect()
if token.WaitTimeout(TIMEOUT) && token.Error() != nil {
log.Fatal().Err(token.Error()).Msg("MQTT connection")
}
token = mqttClient.Publish(APPNAME+"/status", 2, true, "Online")
token.Wait()
}
func connLostHandler(c MQTT.Client, err error) {
log.Fatal().Err(err).Msg("MQTT connection lost")
}
func onConnectHandler(c MQTT.Client) {
log.Debug().Msg("MQTT Client connected")
token := mqttClient.Subscribe(SUBSCRIBE, 0, receive)
if token.Wait() && token.Error() != nil {
log.Fatal().Err(token.Error()).Msgf("Could not subscribe to %s", SUBSCRIBE)
}
}