Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --[[
- Network API is built for the transfer of multiple
- parameters without the need to splice sentences
- individually.
- Additionally, it also incorporates a SYN-ACK setup
- to ensure messages are sent and received appropriately.
- ]]
- version = 0.0.1
- function listen(timeOut)
- --Waits to receive a signal, if it gets an init
- --it opens a connection, receives all sending vars
- --and ensures what it got was all that was meant to be
- --sent
- --Returns whats it gets if it gets everything, otherwise, nil
- local computerID, message, distance = rednet.receive(timeOut)
- local connectionID
- local receiveTable = {}
- --Checks to ensure all messages were received
- local receivedMessages = 0
- local toReceiveMessage = 0
- --Looking for if the init-starter is received
- if message == "init" then
- rednet.send(computerID, "ack")
- computerID, message, distance = rednet.receive(.5)
- --Checks for number of args to be sent to finalize the connection
- if tonumber(message) ~= nil then
- rednet.send(computerID, "ack")
- toReceiveMessage = tonumber(message)
- connectionID = computerID
- --Here is where we start pulling all the values which need to be received.
- for i=0, toReceiveMessage do
- computerID, message, distance = nil
- computerID, message, distance = rednet.receive(.5)
- if connectionID == computerID and message ~= nil then
- rednet.send(connectionID, "ack")
- receiveTable[i+1] = message
- receivedMessages = receivedMessages+1
- end
- end
- end
- end
- --Ensures everything was gotten
- if toReceiveMessage == receivedMessages then
- return unpack(receiveTable)
- end
- end
- function send(computerID, ...)
- --Sends any number of parameters as individual strings.
- --Will be received in order
- local isSuccess = false
- local args = {...}
- local packetsSent = 0
- if sendAck(computerID, "init") and sendAck(computerID, #args) then
- --Loop through all outputs and send them, one at a time, counting
- --that they go through
- for i=0, #args do
- if sendAck(computerID, args[i+1]) then
- packetsSent = packetsSent+1
- end
- sleep(.1)
- end
- else
- return false
- end
- --Ensure everything went through
- if packetsSent == #args then
- return true
- else
- return false
- end
- end
- --=========Utility Stuff Down Here==========
- function sendAck(computerID, message)
- --Sends a single message to the computer,
- --waits for a response, if failed, it tries 2
- --more times. Returns true or false.
- local isSuccess = false
- for i=0, 3 do
- rednet.send(computerID, message)
- id, message, distance = rednet.receive(.5)
- if id == computerID and message == "ack" then
- isSuccess = true
- break
- end
- end
- if isSuccess then return true
- else return false end
- end
Advertisement
Add Comment
Please, Sign In to add comment