diff --git a/behavior.lua b/behavior.lua index 5c3b017..54b77a7 100644 --- a/behavior.lua +++ b/behavior.lua @@ -4,6 +4,7 @@ local logger = require("libs.logger") local tutil = require("libs.turtleutils") local currentStatus = "idle" +local statusCallback = nil function M.getStatus() return currentStatus @@ -13,10 +14,35 @@ 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 for turtleutils to call + -- 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") @@ -31,6 +57,11 @@ function M.run() 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 diff --git a/libs/turtleutils.lua b/libs/turtleutils.lua index 5cba0b0..316b5b4 100644 --- a/libs/turtleutils.lua +++ b/libs/turtleutils.lua @@ -99,12 +99,12 @@ local function refuelIfNeeded() local x, y, z, gpsActive = M.getPosition() local posText = gpsActive and string.format("GPS (%d,%d,%d)", x, y, z) or - string.format("Manual (%d,%d,%d)", x, y, z) + string.format("Travelled: (%d,%d,%d)", x, y, z) if statusCallback then statusCallback("out_of_fuel " .. posText) end - + logger.log("No fuel. Waiting for fuel... Location: " .. posText) sleep(5)