2024-10-21 09:24:20 +02:00
|
|
|
package websocket
|
2024-10-19 11:47:56 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"github.com/gorilla/websocket"
|
2024-10-21 08:16:26 +02:00
|
|
|
"time"
|
2024-10-28 09:33:05 +01:00
|
|
|
|
2024-11-04 20:33:25 +01:00
|
|
|
"git.smsvc.net/pomodoro/GoTomato/internal/helper"
|
2024-10-28 09:33:05 +01:00
|
|
|
"git.smsvc.net/pomodoro/GoTomato/internal/shared"
|
2024-10-19 11:47:56 +02:00
|
|
|
)
|
|
|
|
|
2024-10-30 07:37:14 +01:00
|
|
|
// Sends continous messages to all connected WebSocket clients
|
2024-10-21 08:16:26 +02:00
|
|
|
func SendPermanentBroadCastMessage() {
|
2024-11-21 18:54:08 +01:00
|
|
|
ticker := time.NewTicker(BROADCAST_INTERVAL * time.Second)
|
2024-11-21 18:49:10 +01:00
|
|
|
defer ticker.Stop()
|
2024-11-20 14:07:00 +01:00
|
|
|
|
2024-11-21 18:49:10 +01:00
|
|
|
for range ticker.C {
|
2024-10-21 08:16:26 +02:00
|
|
|
// Marshal the message into JSON format
|
2024-10-29 18:46:00 +01:00
|
|
|
jsonMessage, err := json.Marshal(shared.State)
|
2024-10-19 11:47:56 +02:00
|
|
|
if err != nil {
|
2024-11-04 20:33:25 +01:00
|
|
|
helper.Logger.Error("Error marshalling message:", "msg", err)
|
2024-10-21 08:16:26 +02:00
|
|
|
return
|
|
|
|
}
|
2024-11-20 14:07:00 +01:00
|
|
|
|
2024-10-21 08:16:26 +02:00
|
|
|
// Iterate over all connected clients and broadcast the message
|
2024-11-20 21:51:12 +01:00
|
|
|
mu.Lock()
|
2024-10-21 09:24:20 +02:00
|
|
|
for _, client := range Clients {
|
2024-11-20 14:07:00 +01:00
|
|
|
// Send message to client
|
2024-11-21 08:43:02 +01:00
|
|
|
client.Conn.SetWriteDeadline(time.Now().Add(SEND_TIMEOUT * time.Second))
|
|
|
|
err := client.Conn.WriteMessage(websocket.TextMessage, jsonMessage)
|
2024-10-21 08:16:26 +02:00
|
|
|
if err != nil {
|
2024-11-20 14:07:00 +01:00
|
|
|
helper.Logger.Error("Error broadcasting to client:", "msg", err, "host", client.RealIP, "clients", len(Clients))
|
2024-10-21 08:16:26 +02:00
|
|
|
}
|
2024-10-19 11:47:56 +02:00
|
|
|
}
|
2024-11-20 21:51:12 +01:00
|
|
|
mu.Unlock()
|
2024-10-19 11:47:56 +02:00
|
|
|
}
|
|
|
|
}
|