feat: MQTT integration
This commit is contained in:
@@ -648,6 +648,53 @@ func (wss *WebSocketServer) BroadcastClusterEvent(topic string, data interface{}
|
||||
}
|
||||
}
|
||||
|
||||
// BroadcastMQTTMessage broadcasts an MQTT message to all connected WebSocket clients
|
||||
func (wss *WebSocketServer) BroadcastMQTTMessage(topic string, data []byte) {
|
||||
wss.mutex.RLock()
|
||||
clients := make([]*websocket.Conn, 0, len(wss.clients))
|
||||
for client := range wss.clients {
|
||||
clients = append(clients, client)
|
||||
}
|
||||
wss.mutex.RUnlock()
|
||||
|
||||
if len(clients) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
message := struct {
|
||||
Topic string `json:"topic"`
|
||||
Data string `json:"data"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
}{
|
||||
Topic: topic,
|
||||
Data: string(data),
|
||||
Timestamp: time.Now().Format(time.RFC3339),
|
||||
}
|
||||
|
||||
messageData, err := json.Marshal(message)
|
||||
if err != nil {
|
||||
wss.logger.WithError(err).Error("Failed to marshal MQTT message")
|
||||
return
|
||||
}
|
||||
|
||||
wss.logger.WithFields(log.Fields{
|
||||
"topic": topic,
|
||||
"clients": len(clients),
|
||||
"length": len(data),
|
||||
}).Debug("Broadcasting MQTT message to WebSocket clients")
|
||||
|
||||
// Send to all clients with write synchronization
|
||||
wss.writeMutex.Lock()
|
||||
defer wss.writeMutex.Unlock()
|
||||
|
||||
for _, client := range clients {
|
||||
client.SetWriteDeadline(time.Now().Add(5 * time.Second))
|
||||
if err := client.WriteMessage(websocket.TextMessage, messageData); err != nil {
|
||||
wss.logger.WithError(err).Error("Failed to send MQTT message to client")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Shutdown gracefully shuts down the WebSocket server
|
||||
func (wss *WebSocketServer) Shutdown(ctx context.Context) error {
|
||||
wss.logger.Info("Shutting down WebSocket server")
|
||||
|
||||
Reference in New Issue
Block a user