Improved file transfer

This commit is contained in:
Hadinos Sanosam 2021-01-09 04:27:27 +01:00
parent d643f4c77c
commit 4185f1fcc7
2 changed files with 52 additions and 32 deletions

View File

@ -1,22 +1,30 @@
dofile("/git-scripts/utils")
modemSide = utils.getSideOf("modem") --get side the modem is on
modemSide = utils.getSideOf("modem") --get side the modem is on
if modemSide == nil then
print("Error: No modem detected!")
return
end
rednet.open(modemSide)
--get message, no timeout
id, msg, dist = rednet.receive()
print("Data received!")
rednet.broadcast("", "fileRX") --notify transmitter that we're ready to receive
--get filename
term.write("Output filename: ")
name = tostring(read())
--get message, no timeout
id, msg, sth = rednet.receive("fileTX")
--decompress string
content = textutils.unserialize(msg)
data = textutils.unserialize(msg)
filename = data.filename
content = data.content
--write to file
local file = fs.open(name, "w")
local file = fs.open(filename, "w")
if file == nil then
print("Error: failed to write file " .. filename)
return
end
file.write(content)
print("Received '" .. filename .. "' !")
--finish up
file.close()

View File

@ -1,36 +1,48 @@
--import module
dofile("utils")
--init rednet
modemSide = utils.getSideOf("modem")
rednet.open(modemSide)
local function printUsage()
print("Usage:")
print("send_file <filename> <receiver ID>")
end
--get file content into right format
term.write("Path: ")
path = tostring(read())
local args = { ... }
if #args < 2 then
printUsage()
return
end
local filename = args[1]
local file = fs.open(path, "r")
if file == nil then
print("File does not exist!")
print("Error: File not found")
return
end
content = file.readAll()
data = textutils.serialize(content)
local data = {} --pack filename, content
data.filename = filename
data.content = content
data = textutils.serialize(data) --convert to string
file.close()
local receiver = args[2]
--get receiver
term.write("Receiver id: ")
id = tonumber(read())
print("Initialize receiver please!")
print("Press 's' to send")
--wait for button press
local event, c = os.pullEvent("char")
if c == "s" then
print("Sending...")
print(id)
rednet.send(id, data)
else
print("Aborted.")
--init rednet
modemSide = utils.getSideOf("modem")
if modemSide == nil then
print("Error: No modem detected!")
return
end
rednet.open(modemSide)
print("Waiting for receiver...")
id, msg, sth = rednet.receive("fileXfer")
while id != receiver do
id, msg, sth = rednet.receive("fileRX") --keep waiting
end
--receiver is online!
rednet.send(id, data, "fileTX")
print("Sent!")
--finish up
rednet.close(modemSide)