Calame

Godot_Control.lua

Feb 6th, 2021 (edited)
891
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.90 KB | None | 0 0
  1. os.loadAPI( "connection.lua" )
  2. shell.run( "TurtleFleet/Turtle/advanced_turtle.lua" )
  3. json = dofile( "TurtleFleet/Utils/json.lua" )
  4.  
  5. local ws, err = http.websocket( connection.get_string() )
  6.  
  7. function string.tohex( str )
  8.     return ( str:gsub( '.', function ( c )
  9.         return string.format( '%02X', string.byte( c ) )
  10.     end ) )
  11. end
  12.  
  13. function string.fromhex( str )
  14.     return ( str:gsub( '..', function ( cc )
  15.         return string.char( tonumber( cc , 16 ) )
  16.     end ) )
  17. end
  18.  
  19. function decode( msg )
  20.     local type = string.byte( string.sub( msg, 1, 1) )
  21.     -- Bool
  22.     if     type == 0x01 then return msg:sub( 5, 5 ):byte() == 0x01
  23.     -- Int
  24.     elseif type == 0x02 then return tonumber( "0x" .. msg:sub( 5, 8 ):reverse():tohex() )
  25.     -- String
  26.     elseif type == 0x04 then return msg:sub( 9, 8 + tonumber( "0x" .. msg:sub( 5, 8 ):reverse():tohex() ) )
  27.     -- 0x00 or unknown
  28.     else return nil
  29.     end
  30. end
  31.  
  32. function connected()
  33.     ws.send( "turtle" )
  34.     ws.send( "001" .. json.encode( turtle.getInventory() ) )
  35. end
  36.  
  37. local command = {}
  38. command[ "moveForward" ] = function() turtle.forward() end
  39. command[ "turnLeft" ] = function() turtle.turnLeft() end
  40. command[ "turnRight" ] = function() turtle.turnRight() end
  41. command[ "moveBack" ] = function() turtle.back() end
  42. command[ "moveDown" ] = function() turtle.down() end
  43. command[ "moveUp" ] = function() turtle.up() end
  44. command[ "digUp" ] = function() turtle.digUp() end
  45. command[ "digForward" ] = function() turtle.dig() end
  46. command[ "digDown" ] = function() turtle.digDown() end
  47. command[ "Connected" ] = connected
  48.  
  49. while true do
  50.     local event, url, message = os.pullEvent( "websocket_message" )
  51.     print( message )
  52.     print( string.tohex( message ) )
  53.  
  54.     local data = decode( message )
  55.     print( "Received = " .. tostring( data ) )
  56.     if command[ tostring( data ) ] then
  57.         command[ tostring( data ) ]()
  58.     end
  59. end
Add Comment
Please, Sign In to add comment