-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
183 lines (149 loc) · 4.57 KB
/
main.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
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/go-mqtt/mqtt"
"github.com/leonlatsch/pc2mqtt/internal/appconfig"
"github.com/leonlatsch/pc2mqtt/internal/entities"
"log"
"time"
)
func main() {
log.Println("Starting application")
if err := appconfig.LoadConfig(); err != nil {
log.Fatalln(err)
}
client := createClient()
for {
// Main context. Cancel to stop all goroutines and retry connection
ctx, cancel := context.WithCancel(context.Background())
entityList := entities.GetEntities()
entitiesWithCommands := entities.FilterEntitiesWithCommands(entityList)
go logWhenClientOnline(client)
go func() {
// Wait with availability until config was sent
publishAutoDiscoveryConfigs(ctx, cancel, client, entityList)
publishAvailability(ctx, cancel, client, entityList)
}()
go publishSensorStates(ctx, cancel, client, entityList)
go subscribeToCommandTopics(ctx, cancel, client, entitiesWithCommands)
go readMessages(cancel, client, entitiesWithCommands)
<-ctx.Done()
log.Println("Connection lost. Reconnecting in 5 seconds...")
time.Sleep(5 * time.Second)
cancel()
}
}
func logWhenClientOnline(client *mqtt.Client) {
appConf := appconfig.RequireConfig()
<-client.Online()
log.Printf("Conencted to %q:%d", appConf.Mqtt.Host, appConf.Mqtt.Port)
}
func publishAutoDiscoveryConfigs(ctx context.Context, cancel func(), client *mqtt.Client, entityList []entities.Entity) {
for _, ety := range entityList {
configJson, err := json.Marshal(ety.GetDiscoveryConfig())
if err != nil {
log.Println(err)
continue
}
if err := client.PublishRetained(ctx.Done(), configJson, ety.GetDiscoveryTopic()); err != nil {
log.Println(err)
cancel()
return
}
}
debugLog("Published auto discovery messages successfully")
}
func publishAvailability(ctx context.Context, cancel func(), client *mqtt.Client, entityList []entities.Entity) {
for _, ety := range entityList {
availability := ety.GetDiscoveryConfig().Availability
payload := []byte(availability.PayloadAvailable)
if err := client.PublishRetained(ctx.Done(), payload, availability.Topic); err != nil {
log.Println(err)
cancel()
}
}
debugLog("Published availability messages successfully")
}
func publishSensorStates(ctx context.Context, cancel func(), client *mqtt.Client, entityList []entities.Entity) {
var sensors []entities.BinarySensor
for _, entity := range entityList {
switch v := entity.(type) {
case entities.BinarySensor:
sensors = append(sensors, v)
}
}
for _, sensor := range sensors {
topic := sensor.GetDiscoveryConfig().StateTopic
payload := []byte(sensor.DiscoveryConfig.PayloadOn)
if err := client.PublishRetained(ctx.Done(), payload, topic); err != nil {
log.Println(err)
cancel()
return
}
}
debugLog("Published sensor state successfully")
}
func subscribeToCommandTopics(ctx context.Context, cancel func(), client *mqtt.Client, entitiesWithCommands []entities.EntityWithCommand) {
cmdTopics := make([]string, 0, len(entitiesWithCommands))
for _, ety := range entitiesWithCommands {
cmdTopics = append(cmdTopics, ety.GetDiscoveryConfig().CommandTopic)
}
if err := client.Subscribe(ctx.Done(), cmdTopics...); err != nil {
log.Println(err)
cancel()
}
log.Println("Ready to receive commands")
debugLog("Subscribed to command topic")
}
func readMessages(cancel func(), client *mqtt.Client, entitiesWithCommands []entities.EntityWithCommand) {
for {
message, topic, err := client.ReadSlices()
switch {
case err == nil:
top := string(topic)
mes := string(message)
debugLog("DEBUG: REC: " + top + " : " + mes)
for _, ety := range entitiesWithCommands {
if ety.GetDiscoveryConfig().CommandTopic == top {
ety.QueueAction()
}
}
default:
cancel()
return
}
}
}
func createClient() *mqtt.Client {
appConf := appconfig.RequireConfig()
clientId := "pc2mqtt-" + appConf.DeviceName
uri := fmt.Sprintf("%v:%v", appConf.Mqtt.Host, appConf.Mqtt.Port)
client, err := mqtt.VolatileSession(clientId, &mqtt.Config{
Dialer: mqtt.NewDialer("tcp", uri),
PauseTimeout: 4 * time.Second,
UserName: appConf.Mqtt.Username,
Password: []byte(appConf.Mqtt.Password),
Will: struct {
Topic string
Message []byte
Retain bool
AtLeastOnce bool
ExactlyOnce bool
}{
Topic: entities.GetDeviceAvailability().Topic,
Message: []byte(entities.GetDeviceAvailability().PayloadNotAvailable),
Retain: true,
},
})
if err != nil {
panic(err)
}
return client
}
func debugLog(message string) {
if appconfig.RequireConfig().DebugMode {
log.Println(message)
}
}