feat: MQTT integration
This commit is contained in:
25
main.go
25
main.go
@@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
"spore-gateway/internal/discovery"
|
||||
"spore-gateway/internal/mqtt"
|
||||
"spore-gateway/internal/server"
|
||||
"spore-gateway/pkg/config"
|
||||
|
||||
@@ -21,6 +22,7 @@ func main() {
|
||||
configFile := flag.String("config", "", "Path to configuration file")
|
||||
port := flag.String("port", "3001", "HTTP server port")
|
||||
udpPort := flag.String("udp-port", "4210", "UDP discovery port")
|
||||
mqttServer := flag.String("mqtt", "", "Enable MQTT integration with server URL (e.g., tcp://localhost:1883)")
|
||||
logLevel := flag.String("log-level", "info", "Log level (debug, info, warn, error)")
|
||||
flag.Parse()
|
||||
|
||||
@@ -61,6 +63,22 @@ func main() {
|
||||
// Initialize HTTP server
|
||||
httpServer := server.NewHTTPServer(cfg.HTTPPort, nodeDiscovery)
|
||||
|
||||
// Initialize MQTT client if enabled
|
||||
var mqttClient *mqtt.MQTTClient
|
||||
if *mqttServer != "" {
|
||||
log.WithField("server", *mqttServer).Info("Initializing MQTT client")
|
||||
mqttClient = mqtt.NewMQTTClientFromEnv(*mqttServer)
|
||||
|
||||
// Set callback to forward MQTT messages to WebSocket
|
||||
mqttClient.SetMessageCallback(func(topic string, data []byte) {
|
||||
httpServer.BroadcastMQTTMessage(topic, data)
|
||||
})
|
||||
|
||||
if err := mqttClient.Connect(); err != nil {
|
||||
log.WithError(err).Fatal("Failed to connect to MQTT broker")
|
||||
}
|
||||
}
|
||||
|
||||
// Setup graceful shutdown
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
@@ -90,6 +108,13 @@ func main() {
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Shutdown MQTT client
|
||||
if mqttClient != nil {
|
||||
if err := mqttClient.Shutdown(shutdownCtx); err != nil {
|
||||
log.WithError(err).Error("MQTT client shutdown error")
|
||||
}
|
||||
}
|
||||
|
||||
// Shutdown HTTP server
|
||||
if err := httpServer.Shutdown(shutdownCtx); err != nil {
|
||||
log.WithError(err).Error("HTTP server shutdown error")
|
||||
|
||||
Reference in New Issue
Block a user