package robot import ( "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" ) 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) cache.RemoveRobotById(robot.Id) 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) logger.AddSystemLog("Robot %s status changed to %s", robot.Name, utils.GetRobotStatusString(status)) }