fix: Refactor command polling and dashboard refresh logic in main loop

This commit is contained in:
MayaTheShy
2026-02-16 01:25:51 -05:00
parent cc7c90799e
commit 000d1bd625

View File

@@ -282,12 +282,46 @@ end
addLog("Listening on channels " .. STATUS_CHANNEL .. " and " .. CHANNEL_RECEIVE, colors.lightBlue)
-- Start polling timer
local POLL_INTERVAL = 1 -- Poll every 1 second
os.startTimer(POLL_INTERVAL)
-- Main loop
local lastRefresh = os.epoch("utc")
while true do
local event, side, channel, replyChannel, message, distance = os.pullEvent()
if event == "modem_message" then
if event == "timer" then
-- Poll for commands for all known turtles
for turtleID, turtleData in pairs(turtles) do
local commands = pollCommands(turtleID)
-- Forward commands back to turtle
for _, cmd in ipairs(commands) do
stats.commandsSent = stats.commandsSent + 1
addLog("CMD: " .. cmd.command .. " -> Turtle #" .. turtleID, colors.yellow)
modem.transmit(COMMAND_CHANNEL, CHANNEL_RECEIVE, {
command = cmd.command,
param = cmd.param,
target = turtleID
})
end
end
-- Restart timer
os.startTimer(POLL_INTERVAL)
-- Refresh display if we have a monitor
if hasMonitor then
local now = os.epoch("utc")
if now - lastRefresh > 2000 then
drawDashboard()
lastRefresh = now
end
end
elseif event == "modem_message" then
-- Only process messages on our channels
if channel == STATUS_CHANNEL or channel == CHANNEL_RECEIVE then
stats.messagesReceived = stats.messagesReceived + 1
@@ -307,21 +341,6 @@ while true do
if success then
stats.serverUpdates = stats.serverUpdates + 1
addLog(" -> Forwarded to server", colors.lime)
-- Check for commands from server
local commands = pollCommands(turtleID)
-- Forward commands back to turtle
for _, cmd in ipairs(commands) do
stats.commandsSent = stats.commandsSent + 1
addLog(" -> CMD: " .. cmd.command .. " to Turtle #" .. turtleID, colors.yellow)
modem.transmit(COMMAND_CHANNEL, CHANNEL_RECEIVE, {
command = cmd.command,
param = cmd.param,
target = turtleID
})
end
else
stats.errors = stats.errors + 1
addLog(" -> Server error", colors.red)
@@ -330,13 +349,4 @@ while true do
end
end
end
-- Refresh display every 2 seconds if we have a monitor
if hasMonitor then
local now = os.epoch("utc")
if now - lastRefresh > 2000 then
drawDashboard()
lastRefresh = now
end
end
end