turtle/behavior.lua
2025-06-27 15:29:05 +01:00

68 lines
1.6 KiB
Lua

local M = {}
local logger = require("libs.logger")
local tutil = require("libs.turtleutils")
local currentStatus = "idle"
local statusCallback = nil
function M.getStatus()
return currentStatus
end
function M.setStatus(value)
currentStatus = value
end
function M.setStatusCallback(fn)
statusCallback = fn
end
-- Position and status reporting coroutine
local function reportStatusLoop()
while true do
local x, y, z, gpsActive = tutil.getPosition()
local posText = gpsActive and
string.format("GPS (%d,%d,%d)", x, y, z) or
string.format("Manual (%d,%d,%d)", x, y, z)
if statusCallback then
statusCallback(currentStatus .. " @ " .. posText)
end
logger.log("Status: " .. currentStatus .. " | " .. posText)
sleep(5)
end
end
function M.run()
-- Register the status setter so turtleutils can call M.setStatus
tutil.setStatusCallback(M.setStatus)
-- Start reporting coroutine
local reporter = coroutine.create(reportStatusLoop)
coroutine.resume(reporter)
while true do
currentStatus = "moving backward"
logger.log("Started moving backward")
for i = 1, 10 do
tutil.back()
sleep(0.5)
end
currentStatus = "moving forward"
logger.log("Started moving forward")
for i = 1, 10 do
tutil.forward()
sleep(0.5)
end
-- Allow reporter coroutine to yield and resume
if coroutine.status(reporter) == "suspended" then
coroutine.resume(reporter)
end
end
end
return M