feat: add new lib net.lua
This commit is contained in:
parent
6294b38806
commit
3f92309ac6
@ -8,6 +8,7 @@ local LIST_FILES = {
|
||||
};
|
||||
|
||||
local LIST_LIBS_FILES = {
|
||||
'libs/net.lua',
|
||||
'libs/utils.lua',
|
||||
'libs/turtle-utils.lua',
|
||||
'libs/robot.lua'
|
||||
|
||||
53
libs/net.lua
Normal file
53
libs/net.lua
Normal file
@ -0,0 +1,53 @@
|
||||
local DEFAULT_TIMEOUT = 2
|
||||
local QUERY_PROTO = 'trap/query'
|
||||
local QUERY_RESPONSE_PROTO = 'trap/query:response'
|
||||
|
||||
local net = {}
|
||||
|
||||
local function assertRednetIsOpened()
|
||||
if not rednet.isOpen() then
|
||||
error('rednet should be enabled with rednet.open(modemName)')
|
||||
end
|
||||
end
|
||||
|
||||
net.listenQuery = function(hostname, processQueryMessage)
|
||||
assertRednetIsOpened()
|
||||
|
||||
rednet.host(QUERY_PROTO, hostname)
|
||||
|
||||
while true do
|
||||
local computerId, message = rednet.receive(QUERY_PROTO)
|
||||
local responseMessage = processQueryMessage(textutils.unserialize(message), computerId)
|
||||
rednet.send(computerId, textutils.serialize(responseMessage), QUERY_RESPONSE_PROTO)
|
||||
end
|
||||
|
||||
-- in case we decide to exit the loop in the future
|
||||
rednet.unhost(QUERY_PROTO)
|
||||
end
|
||||
|
||||
net.sendQuery = function(hostname, message, timeout)
|
||||
timeout = timeout or DEFAULT_TIMEOUT
|
||||
assertRednetIsOpened()
|
||||
|
||||
local serverId = rednet.lookup(QUERY_PROTO, hostname)
|
||||
|
||||
if not serverId then
|
||||
return false, 'hostname lookup error'
|
||||
end
|
||||
|
||||
local sendOk = rednet.send(serverId, textutils.serialize(message))
|
||||
|
||||
if not sendOk then
|
||||
return false, 'rednet error'
|
||||
end
|
||||
|
||||
local responseServerId, responseMessage = rednet.receive(QUERY_RESPONSE_PROTO, timeout)
|
||||
|
||||
if not responseServerId then
|
||||
return false, 'timeout'
|
||||
end
|
||||
|
||||
return textutils.unserialize(responseMessage)
|
||||
end
|
||||
|
||||
return net
|
||||
Loading…
Reference in New Issue
Block a user