Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- term.clear()
- print("Turtle Swarm Drone")
- os.loadAPI("json")
- os.loadAPI("turtle2")
- local ws_url = "ws://172.16.1.4:8000/ws/main/turtle/"
- local ws, err
- while true do
- ws, err = http.websocket(ws_url)
- if not ws then
- printError(err)
- sleep(5)
- else
- print("Connected to server")
- break
- end
- end
- function move(direction, force)
- if direction == "forward" then
- if not turtle2.forward() and force then
- turtle.dig()
- turtle2.forward()
- end
- elseif direction == "back" then
- turtle2.back()
- elseif direction == "left" then
- turtle2.turnLeft()
- elseif direction == "right" then
- turtle2.turnRight()
- elseif direction == "down" then
- if not turtle2.down() and force then
- turtle.digDown()
- turtle2.down()
- end
- elseif direction == "up" then
- if not turtle2.up() and force then
- turtle.digUp()
- turtle2.up()
- end
- end
- end
- function sendInfo()
- local data = {
- type = "turtleInfo",
- id = os.getComputerID(),
- label = os.getComputerLabel(),
- fuel = turtle.getFuelLevel(),
- maxFuel = turtle.getFuelLimit()
- }
- ws.send(json.encode(data))
- end
- function sendPosition()
- local data = {
- type = "position",
- xPos = turtle2.xpos,
- yPos = turtle2.ypos,
- zPos = turtle2.zPos,
- direction = turtle2.facing,
- }
- ws.send(json.encode(data))
- end
- sendInfo()
- while true do
- local event, url, response, isBinary = os.pullEvent()
- if event == "websocket_message" then
- local message_obj = json.decode(response)
- if message_obj.type == "command" then
- local func, err = loadstring("return " .. message_obj.command)
- if func then
- local result = func()
- ws.send(json.encode({
- type = "command_response",
- command = message_obj.command,
- response = tostring(result)
- }))
- else
- return printError(err)
- end
- elseif message_obj.type == "move" then
- move(message_obj.direction, message_obj.force)
- sendPosition()
- else
- print(response)
- end
- elseif event == "websocket_closed" then
- print("Disconnected")
- while true do
- ws, err = http.websocket(ws_url)
- if not ws then
- printError(err)
- sleep(5)
- else
- print("Connected to server")
- break
- end
- end
- else
- print(event)
- end
- end
- ws.close()
Add Comment
Please, Sign In to add comment