From 120831d75063a84c51d17e7e1455fe8ef7d8657b Mon Sep 17 00:00:00 2001 From: MayaTheShy Date: Sun, 15 Feb 2026 23:49:13 -0500 Subject: [PATCH] Add web bridge script for forwarding turtle status updates to server --- webbridge.lua | 93 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 webbridge.lua diff --git a/webbridge.lua b/webbridge.lua new file mode 100644 index 0000000..66446fd --- /dev/null +++ b/webbridge.lua @@ -0,0 +1,93 @@ +-- 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 = "http://localhost:3001" -- 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") + + if channel == STATUS_CHANNEL and type(message) == "table" then + -- Status update from turtle + print("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