From 3f92309ac6e1717255da73e4f1c3487add4180c1 Mon Sep 17 00:00:00 2001 From: Guillaume ARM Date: Tue, 21 May 2024 21:51:02 +0200 Subject: [PATCH] feat: add new lib net.lua --- install.lua | 1 + libs/net.lua | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 libs/net.lua diff --git a/install.lua b/install.lua index ec0d551..b176025 100644 --- a/install.lua +++ b/install.lua @@ -8,6 +8,7 @@ local LIST_FILES = { }; local LIST_LIBS_FILES = { + 'libs/net.lua', 'libs/utils.lua', 'libs/turtle-utils.lua', 'libs/robot.lua' diff --git a/libs/net.lua b/libs/net.lua new file mode 100644 index 0000000..7ca8c62 --- /dev/null +++ b/libs/net.lua @@ -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