72 lines
1.8 KiB
Lua
72 lines
1.8 KiB
Lua
local logFileName = "turtle_status.log"
|
|
local turtleStates = {}
|
|
local monitor = peripheral.find("monitor")
|
|
|
|
-- Try to open modem on any side
|
|
local modemOpened = false
|
|
for _, side in ipairs({"top", "bottom", "left", "right", "front", "back"}) do
|
|
if peripheral.getType(side) == "modem" then
|
|
rednet.open(side)
|
|
modemOpened = true
|
|
break
|
|
end
|
|
end
|
|
|
|
if not modemOpened then
|
|
print("No modem found. Cannot continue.")
|
|
return
|
|
end
|
|
|
|
if monitor then
|
|
monitor.setTextScale(0.5)
|
|
monitor.clear()
|
|
end
|
|
|
|
-- Logging function
|
|
local function logToFile(line)
|
|
local file = fs.open(logFileName, "a")
|
|
file.writeLine(("[%s] %s"):format(os.date("%H:%M:%S"), line))
|
|
file.close()
|
|
end
|
|
|
|
-- Draws to monitor or terminal
|
|
local function draw()
|
|
local output = {}
|
|
|
|
table.insert(output, "Turtle Monitor")
|
|
for id, data in pairs(turtleStates) do
|
|
local age = os.clock() - data.time
|
|
local status = (age > 10) and "offline" or data.status
|
|
local line = string.format("%s (ID %d): %s", data.label, id, status)
|
|
table.insert(output, line)
|
|
end
|
|
|
|
-- Output to monitor if present
|
|
if monitor then
|
|
monitor.clear()
|
|
monitor.setCursorPos(1,1)
|
|
for i, line in ipairs(output) do
|
|
monitor.setCursorPos(1, i)
|
|
monitor.write(line)
|
|
end
|
|
else
|
|
term.clear()
|
|
term.setCursorPos(1,1)
|
|
for _, line in ipairs(output) do
|
|
print(line)
|
|
end
|
|
end
|
|
end
|
|
|
|
-- Main loop
|
|
while true do
|
|
local id, message, protocol = rednet.receive("turtle_status", 2)
|
|
if id then
|
|
local ok, data = pcall(textutils.unserialize, message)
|
|
if ok and data and data.id then
|
|
turtleStates[data.id] = data
|
|
logToFile(string.format("Received from %s (ID %d): %s", data.label, data.id, data.status))
|
|
end
|
|
end
|
|
draw()
|
|
end |