109 lines
2.5 KiB
Go
109 lines
2.5 KiB
Go
package robot
|
|
|
|
import (
|
|
"encoding/json"
|
|
"jannex/robot-control-manager/modules/cache"
|
|
"jannex/robot-control-manager/modules/database"
|
|
"jannex/robot-control-manager/modules/logger"
|
|
"jannex/robot-control-manager/modules/request"
|
|
"jannex/robot-control-manager/modules/structs"
|
|
"jannex/robot-control-manager/modules/utils"
|
|
"time"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
func RobotPingHandler() {
|
|
ticker := time.NewTicker(utils.RobotPingHandlerInterval * time.Second)
|
|
|
|
for range ticker.C {
|
|
for _, robot := range cache.GetRobots() {
|
|
if robot.Status == utils.RobotStatusOffline {
|
|
continue
|
|
}
|
|
|
|
err := request.Request(fiber.MethodGet, robot.Address+":5000/api/v1/ping", nil)
|
|
|
|
if err != nil {
|
|
logger.AddSystemLog("Robot ping request failed: %v", err)
|
|
|
|
if robot.PingRetries == utils.RobotPingRetries {
|
|
UpdateRobotStatus(robot, utils.RobotStatusOffline)
|
|
|
|
logger.AddSystemLog("Robot %s marked as offline because %v attempts have already been made to reach it", robot.Name, utils.RobotPingRetries)
|
|
continue
|
|
}
|
|
|
|
robot.PingRetries++
|
|
|
|
logger.AddSystemLog("Trying to ping robot %s for %v times failed", robot.Name, robot.PingRetries)
|
|
|
|
if robot.Status != utils.RobotStatusConnecting {
|
|
UpdateRobotStatus(robot, utils.RobotStatusConnecting)
|
|
}
|
|
continue
|
|
}
|
|
|
|
if robot.Status == utils.RobotStatusConnecting {
|
|
UpdateRobotStatus(robot, utils.RobotStatusIdle)
|
|
}
|
|
|
|
if robot.PingRetries != 0 {
|
|
robot.PingRetries = 0
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func LoadRobotsFromDatabase() {
|
|
var robots []structs.Robot
|
|
|
|
database.DB.Find(&robots)
|
|
|
|
cache.AddRobots(robots)
|
|
|
|
for _, robot := range cache.GetRobots() {
|
|
if robot.Status == utils.RobotStatusOffline {
|
|
continue
|
|
}
|
|
|
|
UpdateRobotStatus(robot, utils.RobotStatusConnecting)
|
|
}
|
|
}
|
|
|
|
func UpdateRobotStatus(robot *structs.Robot, status uint8) {
|
|
robot.Status = status
|
|
|
|
database.DB.Model(&structs.Robot{}).
|
|
Where("id = ?", robot.Id).
|
|
Update("status", status)
|
|
|
|
BroadcastSSEMessage(structs.SSEMessage{
|
|
Cmd: utils.SSESentCmdUpdateRobotStatus,
|
|
Body: struct {
|
|
RobotId string
|
|
Status uint8
|
|
}{
|
|
RobotId: robot.Id,
|
|
Status: status,
|
|
},
|
|
})
|
|
}
|
|
|
|
func BroadcastSSEMessage(message structs.SSEMessage) {
|
|
marshaledMessage, err := json.Marshal(message)
|
|
|
|
if err != nil {
|
|
log.Error().Msgf("Error marshaling SSE message: %v", err)
|
|
return
|
|
}
|
|
|
|
for clientId, sseClient := range cache.GetSSEClients() {
|
|
sseClient.MessageChannel <- structs.SSEClientChannelMessage{
|
|
ClientId: clientId,
|
|
Message: marshaledMessage,
|
|
}
|
|
}
|
|
}
|