Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local COMMAND_PROTOCOL = "controller.command"
- local REQUEST_PROTOCOL = "controller.request"
- local RESPONSE_PROTOCOL = "controller.response"
- local ERR_PROCESS_COMMAND = "\nError running command '%s';\n%s"
- local DIRECTION_FUNCTIONS = {
- move = {
- turtle.up,
- turtle.forward,
- turtle.down,
- turtle.back,
- turtle.turnLeft,
- turtle.turnRight,
- },
- dig = {
- turtle.digUp,
- turtle.dig,
- turtle.digDown,
- },
- place = {
- turtle.placeUp,
- turtle.place,
- turtle.placeDown,
- },
- drop = {
- turtle.dropUp,
- turtle.drop,
- turtle.dropDown,
- },
- suck = {
- turtle.suckUp,
- turtle.suck,
- turtle.suckDown,
- },
- attack = {
- turtle.attackUp,
- turtle.attack,
- turtle.attackDown,
- },
- }
- ---@type table<string, fun(...: rednet.transmittable): nil>
- local COMMANDS = {
- -- run lua code
- loadstring = function(code)
- local func = loadstring(code)
- if func then
- func()
- end
- end,
- -- run a program
- program = function(name, args)
- shell.execute(name, args)
- end,
- -- move the turtle
- move = function(direction)
- DIRECTION_FUNCTIONS.move[tonumber(direction)]()
- end,
- -- dig a block
- dig = function(direction)
- DIRECTION_FUNCTIONS.dig[tonumber(direction)]()
- end,
- -- place a block
- place = function(direction, text)
- DIRECTION_FUNCTIONS.place[tonumber(direction)](text)
- end,
- -- select a slot
- select = function(slot)
- turtle.select(tonumber(slot))
- end,
- -- drop an item
- drop = function(direction, amount)
- DIRECTION_FUNCTIONS.drop[tonumber(direction)](amount)
- end,
- -- suck an item
- suck = function(direction, amount)
- DIRECTION_FUNCTIONS.suck[tonumber(direction)](amount)
- end,
- attack = function(direction, side)
- DIRECTION_FUNCTIONS.attack[tonumber(direction)](side)
- end,
- shutdown = os.shutdown,
- reboot = os.reboot,
- }
- local function awaitController()
- rednet.broadcast("connect", REQUEST_PROTOCOL)
- local id = rednet.receive(RESPONSE_PROTOCOL, 5)
- if not id then
- return awaitController()
- end
- return id
- end
- ---@param command command|rednet.transmittable
- local function processCommand(command)
- local key = command.key
- local func = COMMANDS[key]
- local success, err = pcall(func, unpack(command.arguments))
- if not success then
- printError(ERR_PROCESS_COMMAND:format(key, err))
- end
- end
- local function receiver()
- term.clear()
- term.setCursorPos(1, 1)
- peripheral.find("modem", rednet.open)
- print("Awaiting controller...")
- local activeControllerId = awaitController()
- print("Got controller.", activeControllerId)
- while true do
- local id, command = rednet.receive(COMMAND_PROTOCOL)
- if id == activeControllerId then
- processCommand(command)
- end
- end
- end
- receiver()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement