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") 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) rednet.open(modemSide)
--get message, no timeout rednet.broadcast("", "fileRX") --notify transmitter that we're ready to receive
id, msg, dist = rednet.receive()
print("Data received!")
--get filename --get message, no timeout
term.write("Output filename: ") id, msg, sth = rednet.receive("fileTX")
name = tostring(read())
--decompress string --decompress string
content = textutils.unserialize(msg) data = textutils.unserialize(msg)
filename = data.filename
content = data.content
--write to file --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) file.write(content)
print("Received '" .. filename .. "' !")
--finish up --finish up
file.close() file.close()

View File

@ -1,36 +1,48 @@
--import module
dofile("utils") dofile("utils")
--init rednet local function printUsage()
modemSide = utils.getSideOf("modem") print("Usage:")
rednet.open(modemSide) print("send_file <filename> <receiver ID>")
end
local args = { ... }
if #args < 2 then
printUsage()
return
end
--get file content into right format local filename = args[1]
term.write("Path: ")
path = tostring(read())
local file = fs.open(path, "r") local file = fs.open(path, "r")
if file == nil then if file == nil then
print("File does not exist!") print("Error: File not found")
return return
end end
content = file.readAll() 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 --init rednet
term.write("Receiver id: ") modemSide = utils.getSideOf("modem")
id = tonumber(read()) if modemSide == nil then
print("Error: No modem detected!")
print("Initialize receiver please!") return
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.")
end 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 --finish up
rednet.close(modemSide) rednet.close(modemSide)