Advertisement
montur

turtle client

Sep 18th, 2023 (edited)
598
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.53 KB | None | 0 0
  1. local serverUrl = "ws://84.86.255.191:8765"
  2.  
  3. os.loadAPI("json")
  4.  
  5. -- State
  6. state = {}
  7. state["pos"] = {}
  8.  
  9. state["name"] = os.getComputerLabel()
  10. state["loggedIn"] = false
  11. state["pos"]["x"] = 0
  12. state["pos"]["y"] = 0
  13. state["pos"]["z"] = 0
  14. state["pos"]["facing"] = "north"
  15.  
  16. -- Connect to the WebSocket server
  17. header = {["device"] = "turtle"}
  18. local ws, err = assert(http.websocket(serverUrl, header))
  19.  
  20. -- Communication functions
  21. local function sendData(data)
  22.   ws.send(json.encode(data))
  23. end
  24.  
  25. -- Check WebSocket server
  26. if not ws then
  27.   print("Failed to connect to WebSocket server:", err)
  28.   return
  29. end
  30. print("Connected to Server. trying to login...")
  31. sendData(state)
  32. -- Receive and handle messages from the WebSocket server
  33. while true do
  34.   local messageStr, err = ws.receive()
  35.   if messageStr then
  36.     message = json.decode(messageStr)
  37.  
  38.     if not state.loggedIn then
  39.       state.loggedIn = message.loggedIn
  40.       print(message.message) -- print welcome message from server
  41.       state["message"] = "ready"
  42.       sendData(state)
  43.     else
  44.       -- Load the function from the string
  45.       local loadedFunction = load(message.func)
  46.       -- Check if the loaded object is a function
  47.       if type(loadedFunction) == "function" then
  48.           -- Call the loaded function
  49.           loadedFunction()
  50.       else
  51.           print("Failed to load the function from the string.")
  52.       end
  53.     end
  54.   else
  55.     print("Failed to receive message:", err)
  56.     break
  57.   end
  58. end
  59.  
  60. -- Close the WebSocket connection when done
  61. ws.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement