feat: add getting computer data route
This commit is contained in:
parent
840e584082
commit
58adca9cd0
4 changed files with 34 additions and 0 deletions
|
|
@ -2,6 +2,7 @@ package handler
|
|||
|
||||
import (
|
||||
"backend/internal/model"
|
||||
"backend/internal/service"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
|
@ -25,12 +26,14 @@ func HandleComputerWebSocket(w http.ResponseWriter, r *http.Request) {
|
|||
defer conn.Close()
|
||||
|
||||
slog.Info("Websocket connection established!")
|
||||
online := true
|
||||
|
||||
// Read messages
|
||||
for {
|
||||
_, message, err := conn.ReadMessage()
|
||||
if err != nil {
|
||||
slog.Error("WebSocket connection closed by client", slog.Any("error", err))
|
||||
online = false
|
||||
break
|
||||
}
|
||||
|
||||
|
|
@ -40,6 +43,12 @@ func HandleComputerWebSocket(w http.ResponseWriter, r *http.Request) {
|
|||
continue
|
||||
}
|
||||
|
||||
service.AddComputerData(online, clientMessage)
|
||||
slog.Info("Recieved message", slog.Any("message", clientMessage))
|
||||
}
|
||||
}
|
||||
|
||||
func HandleComputerGraphData(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(service.ComputerData)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,3 +4,9 @@ type ComputerWebSocketMessage struct {
|
|||
Cpu uint8 `json:"cpu"`
|
||||
Ram uint8 `json:"ram"`
|
||||
}
|
||||
|
||||
type ComputerGraphData struct {
|
||||
Online bool `json:"online"`
|
||||
Cpu []int `json:"cpu"`
|
||||
Ram []int `json:"ram"`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,6 +42,7 @@ func NewRouter() {
|
|||
r.Get("/currently-playing", handler.HandleGetCurrentlyPlaying)
|
||||
r.Get("/status", handler.HandleGetStatus)
|
||||
|
||||
r.Get("/computer", handler.HandleComputerGraphData)
|
||||
r.Get("/ws/computer", handler.HandleComputerWebSocket)
|
||||
|
||||
port := os.Getenv("PORT")
|
||||
|
|
|
|||
18
internal/service/computer.go
Normal file
18
internal/service/computer.go
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"backend/internal/model"
|
||||
)
|
||||
|
||||
var ComputerData model.ComputerGraphData
|
||||
|
||||
func AddComputerData(online bool, clientMessage model.ComputerWebSocketMessage) {
|
||||
ComputerData.Online = online
|
||||
ComputerData.Cpu = append(ComputerData.Cpu, int(clientMessage.Cpu))
|
||||
ComputerData.Ram = append(ComputerData.Ram, int(clientMessage.Ram))
|
||||
|
||||
if len(ComputerData.Cpu) > 20 {
|
||||
ComputerData.Cpu = ComputerData.Cpu[1:]
|
||||
ComputerData.Ram = ComputerData.Ram[1:]
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue