Files
remoteturtle/webbridge.lua

103 lines
2.9 KiB
Lua

-- Web Bridge for Turtle System
-- This script forwards turtle status updates to the web server
-- Place this on a computer connected to the wireless network
local SERVER_URL = "https://turtles.spatulaa.com" -- Change to your server address
local CHANNEL_RECEIVE = 101
local STATUS_CHANNEL = 102
local modem = peripheral.find("modem")
if not modem then
error("No wireless modem found!")
end
modem.open(CHANNEL_RECEIVE)
modem.open(STATUS_CHANNEL)
print("Web Bridge Started")
print("Listening for turtle updates...")
print("Server: " .. SERVER_URL)
-- Track turtles to forward updates
local turtles = {}
-- Function to send data to web server
local function sendToServer(data)
local jsonData = textutils.serializeJSON(data)
local response = http.post(
SERVER_URL .. "/api/turtle/update",
jsonData,
{["Content-Type"] = "application/json"}
)
if response then
response.close()
return true
else
return false
end
end
-- Function to poll for commands from server
local function pollCommands(turtleID)
local response = http.get(SERVER_URL .. "/api/turtle/" .. turtleID .. "/commands")
if response then
local content = response.readAll()
response.close()
local data = textutils.unserializeJSON(content)
if data and data.commands then
return data.commands
end
end
return {}
end
-- Main loop
while true do
local event, side, channel, replyChannel, message, distance = os.pullEvent("modem_message")
print("Received modem message on channel " .. channel)
if type(message) == "table" then
print(" Message type: " .. (message.type or "no type"))
print(" Turtle ID: " .. tostring(message.turtleID))
else
print(" Message is not a table, it's: " .. type(message))
end
if channel == STATUS_CHANNEL and type(message) == "table" and message.type == "status" then
-- Status update from turtle
print("✓ Valid status from Turtle " .. (message.turtleID or "?"))
-- Update local cache
turtles[message.turtleID] = message
-- Forward to web server
local success = sendToServer(message)
if success then
print(" -> Sent to server")
-- Check for commands from server
local commands = pollCommands(message.turtleID)
-- Forward commands back to turtle
for _, cmd in ipairs(commands) do
print(" -> Command for Turtle " .. message.turtleID .. ": " .. cmd.command)
modem.transmit(100, 101, {
command = cmd.command,
param = cmd.param,
target = message.turtleID
})
end
else
print(" -> Failed to send to server")
end
end
sleep(0.1) -- Small delay to prevent overwhelming the system
end