-
Notifications
You must be signed in to change notification settings - Fork 325
Expand file tree
/
Copy pathmqtt.go
More file actions
450 lines (377 loc) · 12.1 KB
/
mqtt.go
File metadata and controls
450 lines (377 loc) · 12.1 KB
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
package kvm
import (
"crypto/tls"
"encoding/json"
"fmt"
"strings"
"sync/atomic"
"time"
"github.com/gwatts/rootcerts"
"github.com/jetkvm/kvm/internal/logging"
"github.com/jetkvm/kvm/internal/sync"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
var mqttLogger = logging.GetSubsystemLogger("mqtt")
// publishTimeout is the maximum time to wait for a single MQTT publish to complete.
const publishTimeout = 5 * time.Second
type MQTTConfig struct {
Enabled bool `json:"enabled"`
Broker string `json:"broker"`
Port int `json:"port"`
Username string `json:"username"`
Password string `json:"password"`
BaseTopic string `json:"base_topic"`
UseTLS bool `json:"use_tls"`
TLSInsecure bool `json:"tls_insecure"`
EnableHADiscovery bool `json:"enable_ha_discovery"`
EnableActions bool `json:"enable_actions"`
DebounceMs int `json:"debounce_ms"`
}
var mqttManager *MQTTManager
type MQTTManager struct {
client mqtt.Client
deviceID string
baseTopic string
connected atomic.Bool
lastError atomic.Value // stores string; cleared on successful connect
updateRequested atomic.Bool // set when an update is triggered via MQTT, cleared when OTA finishes
debounceMs int
done chan struct{} // closed on Close() to stop background goroutines
// Debounce state for ATX HDD LED OFF transitions.
// When the HDD LED turns off, publishing is delayed by debounceMs.
// If it turns back on within that window, the OFF is suppressed,
// keeping the published state as ON during rapid flickering.
atxDebounceMu sync.Mutex
atxDebounceTimer *time.Timer
atxLastPublished *ATXState
// Cached virtual media options to avoid redundant discovery republishes.
lastVMOptions []string
// Cached update state to avoid calling getUpdateStatus on every tick.
lastUpdateCheck time.Time
lastUpdatePayload *mqttUpdateState
}
type mqttStatusPayload struct {
Online bool `json:"online"`
}
// topic returns a fully qualified topic string using baseTopic.
func (m *MQTTManager) topic(parts ...string) string {
return m.baseTopic + "/" + strings.Join(parts, "/")
}
// validateBaseTopic checks that the base topic does not contain MQTT wildcards or invalid characters.
func validateBaseTopic(topic string) error {
if strings.ContainsAny(topic, "+#") {
return fmt.Errorf("base topic must not contain MQTT wildcards (+ or #)")
}
if strings.Contains(topic, " ") {
return fmt.Errorf("base topic must not contain spaces")
}
if topic == "" {
return fmt.Errorf("base topic must not be empty")
}
return nil
}
func NewMQTTManager(cfg *MQTTConfig, deviceID string) (*MQTTManager, error) {
if cfg == nil || !cfg.Enabled {
return nil, fmt.Errorf("MQTT is not enabled")
}
baseTopic := cfg.BaseTopic
if baseTopic == "" {
baseTopic = "jetkvm"
}
if err := validateBaseTopic(baseTopic); err != nil {
return nil, err
}
// Ensure baseTopic includes deviceID
if !strings.Contains(baseTopic, deviceID) {
baseTopic = baseTopic + "/" + deviceID
}
m := &MQTTManager{
deviceID: deviceID,
baseTopic: baseTopic,
debounceMs: cfg.DebounceMs,
done: make(chan struct{}),
}
scheme := "tcp"
port := cfg.Port
if port == 0 {
port = 1883
}
if cfg.UseTLS {
scheme = "ssl"
}
brokerURL := fmt.Sprintf("%s://%s:%d", scheme, cfg.Broker, port)
opts := mqtt.NewClientOptions()
opts.AddBroker(brokerURL)
opts.SetClientID(fmt.Sprintf("jetkvm-%s", deviceID))
opts.SetUsername(cfg.Username)
opts.SetPassword(cfg.Password)
opts.SetAutoReconnect(true)
opts.SetConnectRetry(true)
opts.SetCleanSession(false)
opts.SetConnectRetryInterval(10 * time.Second)
opts.SetConnectTimeout(10 * time.Second)
if cfg.UseTLS {
tlsConfig := &tls.Config{
InsecureSkipVerify: cfg.TLSInsecure, //nolint:gosec
}
if !cfg.TLSInsecure {
tlsConfig.RootCAs = rootcerts.ServerCertPool()
}
opts.SetTLSConfig(tlsConfig)
}
// Will message: offline status
willPayload, _ := json.Marshal(mqttStatusPayload{Online: false})
opts.SetWill(m.topic("status"), string(willPayload), 1, true)
opts.OnConnect = m.onConnect
opts.OnConnectionLost = m.onConnectionLost
m.client = mqtt.NewClient(opts)
// Connect in the background — with ConnectRetry(true) this will keep
// retrying automatically without blocking the caller (startup).
token := m.client.Connect()
go func() {
token.Wait()
if token.Error() != nil {
m.setLastError(token.Error())
mqttLogger.Warn().Err(token.Error()).Str("broker", brokerURL).Msg("initial MQTT connection attempt failed, will retry")
}
}()
return m, nil
}
func (m *MQTTManager) setLastError(err error) {
if err != nil {
m.lastError.Store(err.Error())
}
}
func (m *MQTTManager) clearLastError() {
m.lastError.Store("")
}
// LastError returns the last connection error, or empty string if none.
func (m *MQTTManager) LastError() string {
v := m.lastError.Load()
if v == nil {
return ""
}
return v.(string)
}
func (m *MQTTManager) onConnect(client mqtt.Client) {
mqttLogger.Info().Str("deviceID", m.deviceID).Msg("connected to MQTT broker")
m.connected.Store(true)
m.clearLastError()
// Publish online status
m.publish(m.topic("status"), mqttStatusPayload{Online: true}, true)
// Publish Home Assistant discovery configs if enabled
if config.MqttConfig != nil && config.MqttConfig.EnableHADiscovery {
m.publishHADiscovery()
}
// Subscribe to command topics
m.subscribeCommands()
// Immediately publish all current states so Home Assistant knows
// the current state of all switches and sensors right away.
if config.ActiveExtension == "atx-power" {
m.publishATXState(ATXState{
Power: ledPWRState.Load(),
HDD: ledHDDState.Load(),
})
}
if config.ActiveExtension == "dc-power" {
m.publishDCState(getDCState())
}
m.publishExtendedStates()
}
func (m *MQTTManager) onConnectionLost(client mqtt.Client, err error) {
mqttLogger.Warn().Err(err).Msg("MQTT connection lost")
m.connected.Store(false)
m.setLastError(err)
}
// IsConnected returns the current connection state.
func (m *MQTTManager) IsConnected() bool {
return m.connected.Load() && m.client.IsConnected()
}
// Close disconnects from the MQTT broker gracefully and stops background goroutines.
func (m *MQTTManager) Close() {
// Signal all background goroutines to stop.
close(m.done)
m.atxDebounceMu.Lock()
m.cancelATXDebounceTimerLocked()
m.atxDebounceMu.Unlock()
if m.client != nil && m.client.IsConnected() {
m.publish(m.topic("status"), mqttStatusPayload{Online: false}, true)
m.client.Disconnect(500)
}
m.connected.Store(false)
}
// publish marshals the payload to JSON and publishes to the topic.
func (m *MQTTManager) publish(topic string, payload interface{}, retained bool) {
data, err := json.Marshal(payload)
if err != nil {
mqttLogger.Error().Err(err).Str("topic", topic).Msg("failed to marshal MQTT payload")
return
}
token := m.client.Publish(topic, 1, retained, data)
if !token.WaitTimeout(publishTimeout) {
mqttLogger.Warn().Str("topic", topic).Msg("MQTT publish timed out")
return
}
if token.Error() != nil {
mqttLogger.Error().Err(token.Error()).Str("topic", topic).Msg("failed to publish MQTT message")
}
}
// publishString publishes a raw string payload.
func (m *MQTTManager) publishString(topic string, payload string, retained bool) {
token := m.client.Publish(topic, 1, retained, payload)
if !token.WaitTimeout(publishTimeout) {
mqttLogger.Warn().Str("topic", topic).Msg("MQTT publish timed out")
return
}
if token.Error() != nil {
mqttLogger.Error().Err(token.Error()).Str("topic", topic).Msg("failed to publish MQTT message")
}
}
// actionsAllowed checks if MQTT actions are enabled in the config.
func (m *MQTTManager) actionsAllowed() bool {
return config.MqttConfig != nil && config.MqttConfig.EnableActions
}
// --- JSON-RPC Handlers ---
type MQTTStatusResponse struct {
Connected bool `json:"connected"`
Error string `json:"error,omitempty"`
}
const mqttPasswordMask = "********"
func rpcGetMqttSettings() (*MQTTConfig, error) {
cfg := config.MqttConfig
if cfg == nil {
return &MQTTConfig{}, nil
}
// Return a copy with the password masked to avoid leaking credentials.
masked := *cfg
if masked.Password != "" {
masked.Password = mqttPasswordMask
}
return &masked, nil
}
func rpcSetMqttSettings(settings MQTTConfig) error {
if settings.Enabled && settings.Broker == "" {
return fmt.Errorf("broker address is required when MQTT is enabled")
}
if settings.Port < 1 || settings.Port > 65535 {
return fmt.Errorf("port must be between 1 and 65535")
}
if settings.BaseTopic == "" {
settings.BaseTopic = "jetkvm"
}
if err := validateBaseTopic(settings.BaseTopic); err != nil {
return err
}
oldConfig := config.MqttConfig
// If the password is the mask placeholder, preserve the existing password.
if settings.Password == mqttPasswordMask && oldConfig != nil {
settings.Password = oldConfig.Password
}
// Cleanup before applying new settings
if mqttManager != nil && mqttManager.IsConnected() {
wasEnabled := oldConfig != nil && oldConfig.Enabled
wasHADiscovery := oldConfig != nil && oldConfig.EnableHADiscovery
// If MQTT is being disabled, clean up all topics and discovery entries
if wasEnabled && !settings.Enabled {
mqttManager.cleanupAllTopics()
} else if wasHADiscovery && !settings.EnableHADiscovery {
// If only HA Discovery is being disabled, remove discovery entries
mqttManager.removeAllDiscovery()
}
}
if settings.DebounceMs < 0 {
settings.DebounceMs = 0
}
cfg := settings
config.MqttConfig = &cfg
if err := SaveConfig(); err != nil {
return fmt.Errorf("failed to save config: %w", err)
}
// Reconnect MQTT
restartMQTT()
return nil
}
func rpcGetMqttStatus() (MQTTStatusResponse, error) {
connected := false
lastError := ""
if mqttManager != nil {
connected = mqttManager.IsConnected()
lastError = mqttManager.LastError()
}
return MQTTStatusResponse{Connected: connected, Error: lastError}, nil
}
// testMqttConnectionTimeout is the maximum time to wait for a test connection attempt.
const testMqttConnectionTimeout = 5 * time.Second
type MQTTTestResult struct {
Success bool `json:"success"`
Error string `json:"error,omitempty"`
}
func rpcTestMqttConnection(settings MQTTConfig) (MQTTTestResult, error) {
if settings.Broker == "" {
return MQTTTestResult{Error: "broker address is required"}, nil
}
// If the password is the mask placeholder, use the existing password.
if settings.Password == mqttPasswordMask && config.MqttConfig != nil {
settings.Password = config.MqttConfig.Password
}
scheme := "tcp"
port := settings.Port
if port == 0 {
port = 1883
}
if settings.UseTLS {
scheme = "ssl"
}
brokerURL := fmt.Sprintf("%s://%s:%d", scheme, settings.Broker, port)
opts := mqtt.NewClientOptions()
opts.AddBroker(brokerURL)
opts.SetClientID(fmt.Sprintf("jetkvm-%s-test", GetDeviceID()))
opts.SetUsername(settings.Username)
opts.SetPassword(settings.Password)
opts.SetAutoReconnect(false)
opts.SetConnectRetry(false)
opts.SetConnectTimeout(testMqttConnectionTimeout)
if settings.UseTLS {
tlsConfig := &tls.Config{
InsecureSkipVerify: settings.TLSInsecure, //nolint:gosec
}
if !settings.TLSInsecure {
tlsConfig.RootCAs = rootcerts.ServerCertPool()
}
opts.SetTLSConfig(tlsConfig)
}
client := mqtt.NewClient(opts)
token := client.Connect()
token.Wait()
if err := token.Error(); err != nil {
return MQTTTestResult{Error: err.Error()}, nil
}
client.Disconnect(250)
return MQTTTestResult{Success: true}, nil
}
// restartMQTT stops the existing MQTT connection and starts a new one if enabled.
func restartMQTT() {
if mqttManager != nil {
mqttManager.Close()
mqttManager = nil
}
startMQTT()
}
func startMQTT() {
if config.MqttConfig == nil || !config.MqttConfig.Enabled {
mqttLogger.Info().Msg("MQTT is disabled")
return
}
var err error
mqttManager, err = NewMQTTManager(config.MqttConfig, GetDeviceID())
if err != nil {
mqttLogger.Warn().Err(err).Msg("failed to start MQTT")
return
}
mqttManager.startPeriodicStatusUpdates(15 * time.Second)
mqttLogger.Info().Msg("MQTT started")
}
// initMQTT initializes MQTT if enabled in config. Called from main.go.
func initMQTT() {
startMQTT()
}