Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Logistics Robot Update
- -- Program to be run first on a wireless-capable computer with an updated "/home/LRobot.lua" file, then on a wireless-capable robot within range to receive that file.
- local component = require("component")
- local event = require("event")
- local m = component.modem -- get primary modem component
- local fs = require("filesystem")
- local term = require("term")
- local PORT = 10
- local argv = {...}
- local mode = "receive" -- "send" or "receive"
- if argv[1] == "send" then
- mode = "send"
- end
- local signal_strength = tonumber(argv[2])
- local function writeFile(path, data_string)
- local f_h = fs.open(path, "w")
- f_h:write(data_string)
- f_h:close()
- end
- local function getMessage()
- local _, _, from, port, _, message = event.pull("modem_message")
- return message
- end
- m.open(PORT)
- m.setStrength(signal_strength)
- if mode == "send" then
- print("Preparing to send file...")
- local max_send_length = 250
- if not fs.exists("/home/LRobot.lua") then
- print("ERROR: No such file '/home/LRobot.lua!'")
- os.exit()
- end
- local send_h = fs.open("/home/LRobot.lua", "r")
- local send_total_length = fs.size("/home/LRobot.lua")
- local total_sent = 0
- local next_send_length = 0
- local next_send_string = ""
- local function getNextSendString()
- next_send_length = math.min(max_send_length, send_total_length - total_sent)
- next_send_string = send_h:read(next_send_length)
- end
- getNextSendString()
- while total_sent < send_total_length do
- term.clear()
- local broadcast_status = m.broadcast(PORT, next_send_string)
- if not broadcast_status then
- print("ERROR: Couldn't broadcast!")
- os.exit()
- end
- local msg = getMessage()
- if msg == "next" then
- total_sent = total_sent + next_send_length
- getNextSendString()
- end
- if total_sent == 0 then
- print("Waiting for receiver to accept data...")
- else
- print("Sending File. (" .. tostring(math.floor(((total_sent / send_total_length) * 100) * 100) / 100) .. "%)")
- end
- os.sleep(1)
- end
- term.clear()
- m.broadcast(PORT, "DOWNLOAD_END")
- print("File sent successfully!")
- send_h:close()
- elseif mode == "receive" then
- local received_data = ""
- local data_end = false
- while not data_end do
- term.clear()
- print("Listening...")
- local msg = getMessage()
- if msg then
- if msg == "DOWNLOAD_END" then
- data_end = true
- else
- received_data = received_data .. msg
- print("Packet Received!")
- m.broadcast(PORT, "next")
- end
- else
- print("Waiting for next packet...")
- end
- os.sleep(1)
- end
- writeFile("/home/LRobot.lua", received_data)
- print("Download Complete!")
- end
- m.close(PORT)
Add Comment
Please, Sign In to add comment