Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local component = require("component")
- local event = require("event")
- local term = require("term")
- local thread = require("thread")
- local modem = component.modem
- -- Constants
- local PORT = 1
- local PING = "ping"
- local PONG = "pong"
- local devices = {}
- -- Open port if needed
- if modem.isOpen(PORT) == false then
- modem.open(PORT)
- print("PORT '" .. PORT .. "' opened successfully!")
- end
- -- Read whole file
- local function readAll(file)
- local f = assert(io.open(file, "r"))
- local content = f:read("*all")
- f:close()
- return content
- end
- -- Quit our program
- local function quit()
- os.exit(1)
- end
- -- Remove the first element of a table
- local function reorderParameters(parameters)
- local reordered = {}
- for k, param in pairs(parameters) do
- if k > 1 then
- reordered[k-1] = param
- end
- end
- return reordered
- end
- -- Send network message to all registered devices
- local function sendToDevices(...)
- for _, device in pairs(devices) do
- modem.broadcast(PORT, ...)
- end
- end
- -- Commands
- local commands = {
- -- Find all IoT devices
- discover = function()
- devices = {}
- local collectThread = thread.create(function()
- print("Discover Internet of Things...")
- modem.broadcast(PORT, PING)
- while true do
- local _, _, remoteAddress, _, _, payload = event.pull("modem_message")
- if payload == PONG then
- table.insert(devices, remoteAddress)
- end
- end
- end)
- -- Wait some seconds and kill the thread
- collectThread:join(2)
- collectThread:kill()
- print(#devices .. " devices found!")
- end,
- -- Load program from filesystem and execute on all devices
- executefile = function(filename)
- if not filename then
- print("Usage:")
- print("executeFile <filename>")
- return false
- end
- local program = readAll(filename)
- if program == nil then
- print("File not found!")
- return false
- end
- print("Execute '" .. filename .. "' on " .. #devices .. " devices...")
- sendToDevices(tostring(program))
- end,
- clear = function()
- term.clear()
- end
- }
- -- Find devices on startup
- commands.discover()
- -- Terminal history for up and down navigation
- local history = {}
- -- Main loop
- while term.isAvailable() do
- -- Prefix input field
- io.write("\27[33mcommand> \27[37m")
- -- Read input
- local input = term.read(history)
- if not input then quit() end
- -- Push input to history
- table.insert(history, input)
- -- Get command parameters
- local parameters = {}
- for param in input:gmatch("%S+") do
- table.insert(parameters, param)
- end
- -- Define our command
- local command = parameters[1]
- -- Remove command from parameters
- parameters = reorderParameters(parameters)
- -- Check whether the command does not exist or should be called
- if commands[command] == nil then
- print("Command not found!")
- else
- pcall(commands[command], table.unpack(parameters))
- end
- end
Add Comment
Please, Sign In to add comment