Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local WS_URL = "ws://127.0.0.1:6969"
- function handleCommand(msg)
- local msg = textutils.unserialiseJSON(msg)
- -- NOT DONE!!! if cant read message or "type" != "command" return
- if not msg or msg.type ~= "command" or msg['function'] == nil then return end
- -- try to execute recieved command
- local success, result = loadstring("return "..msg['function'])()
- print(success)
- print(result)
- if success then
- print("successfully executed: "..msg['function'])
- else
- print("couldnt execute: "..msg['function'])
- end
- return textutils.serializeJSON({
- type = "response",
- id = msg.id,
- success = success,
- result = success and result or "Error: " .. tostring(result)
- })
- end
- function mainLoop()
- local ws, err = assert(http.websocket(WS_URL))
- if not ws then
- error("Connection failed: "..err)
- end
- turtle_id = os.getComputerID()
- term.clear()
- term.setCursorPos(1,1)
- print(" {O}\n")
- print("Connected to Server with ID: "..turtle_id)
- -- Send computer ID first
- ws.send(textutils.serializeJSON({
- type = "identify",
- id = turtle_id
- }))
- while true do
- local msg = ws.receive()
- print('msg recieved: '..msg)
- if msg == nil then
- print("msg nil")
- break
- end
- local Response = handleCommand(msg)
- if Response then
- ws.send(Response)
- end
- end
- ws.close()
- return true --Signal for reconnection
- end
- -- trying to initiate connection/reconnect to ws server
- while true do
- local success, reconnect = pcall(mainLoop)
- if not reconnect then break end
- os.sleep(100)
- term.clear()
- term.setCursorPos(1,1)
- print("reconnecting in 5 seconds.")
- os.sleep(1)
- term.clear()
- term.setCursorPos(1,1)
- print("reconnecting in 5 seconds..")
- os.sleep(1)
- term.clear()
- term.setCursorPos(1,1)
- print("reconnecting in 5 seconds...")
- os.sleep(1)
- end
Advertisement
Add Comment
Please, Sign In to add comment