mrjoecool

ws

Feb 12th, 2025 (edited)
287
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.02 KB | None | 0 0
  1. local WS_URL = "ws://127.0.0.1:6969"
  2.  
  3. function handleCommand(msg)
  4.     local msg = textutils.unserialiseJSON(msg)
  5.     -- NOT DONE!!! if cant read message or "type" != "command" return
  6.     if not msg or msg.type ~= "command" or msg['function'] == nil then return end
  7.  
  8.     -- try to execute recieved command
  9.     local success, result = loadstring("return "..msg['function'])()
  10.     print(success)
  11.     print(result)
  12.     if success then
  13.         print("successfully executed: "..msg['function'])
  14.     else
  15.         print("couldnt execute: "..msg['function'])
  16.     end
  17.     return textutils.serializeJSON({
  18.         type = "response",
  19.         id = msg.id,
  20.         success = success,
  21.         result = success and result or "Error: " .. tostring(result)
  22.     })
  23. end
  24.  
  25.  
  26. function mainLoop()
  27.     local ws, err = assert(http.websocket(WS_URL))
  28.     if not ws then
  29.         error("Connection failed: "..err)
  30.     end
  31.     turtle_id = os.getComputerID()
  32.     term.clear()
  33.     term.setCursorPos(1,1)
  34.     print("      {O}\n")
  35.     print("Connected to Server with ID: "..turtle_id)
  36.  
  37.     -- Send computer ID first
  38.     ws.send(textutils.serializeJSON({
  39.         type = "identify",
  40.         id = turtle_id
  41.     }))
  42.  
  43.     while true do
  44.         local msg = ws.receive()
  45.         print('msg recieved: '..msg)
  46.         if msg == nil then
  47.             print("msg nil")
  48.             break
  49.         end
  50.  
  51.         local Response = handleCommand(msg)
  52.         if Response then
  53.             ws.send(Response)
  54.         end
  55.     end
  56.  
  57.     ws.close()
  58.     return true --Signal for reconnection
  59. end
  60.  
  61. -- trying to initiate connection/reconnect to ws server
  62. while true do
  63.     local success, reconnect = pcall(mainLoop)
  64.     if not reconnect then break end
  65.  
  66.     os.sleep(100)
  67.     term.clear()
  68.     term.setCursorPos(1,1)
  69.     print("reconnecting in 5 seconds.")
  70.     os.sleep(1)
  71.     term.clear()
  72.     term.setCursorPos(1,1)
  73.     print("reconnecting in 5 seconds..")
  74.     os.sleep(1)
  75.     term.clear()
  76.     term.setCursorPos(1,1)
  77.     print("reconnecting in 5 seconds...")
  78.     os.sleep(1)
  79. end
Advertisement
Add Comment
Please, Sign In to add comment