commit cdc2d3200e566725285ab5e821e4d97f01b4391b Author: Rivulet Date: Mon Apr 6 22:00:40 2026 -0700 Gurt diff --git a/libs/entrypointlib.lua b/libs/entrypointlib.lua new file mode 100644 index 0000000..449df35 --- /dev/null +++ b/libs/entrypointlib.lua @@ -0,0 +1,124 @@ +local pullEvent = os.pullEventRaw +local modem = peripheral.find("modem",function (s) return peripheral.wrap(s).isWireless() end) +term.clear() +term.setCursorPos(1,1) +local network = {} +local message_queue = {} +modem.open(15125) +local canidate = {id = -1, distance = 764, max_distance=0} +parallel.waitForAny(function () repeat sleep(0.1) until canidate.id ~= -1 end, +function () + while true do + local _, _, channel, _, msg, distance = pullEvent("modem_message") + if channel == 15125 then + if msg.protocol == "entrypoint_advertise" then + if distance < canidate.distance and distance < (msg.max_distance or 128) then + canidate.max_distance = (msg.max_distance or 128) + canidate.id = msg.sender + canidate.distance = distance + end + end + end + end +end) +local last_heartbeat = os.epoch("utc") +modem.transmit(15125,15125,{protocol="entrypoint_connect",sender=os.getComputerID(),target=canidate.id}) + +local function receive() + while true do + local _, _, channel, _, msg, distance = pullEvent("modem_message") + if channel == 15125 then + if msg.protocol == "heartbeat" and msg.target == os.getComputerID() and msg.sender == canidate.id then + last_heartbeat = os.epoch("utc") + modem.transmit(15125,15125,{protocol="heartbeat_response",sender=os.getComputerID(),target=canidate.id}) + canidate.distance = distance + canidate.max_distance = msg.max_distance + if distance > (msg.max_distance or 764) then + modem.transmit(15125,15125,{protocol="entrypoint_disconnect",sender=os.getComputerID(),target=canidate.id}) + canidate = {id = -1, distance = 764, max_distance=0} + parallel.waitForAny(function () repeat sleep(0.1) until canidate.id ~= -1 end, + function () + while true do + local _, _, channel, _, msg, distance = pullEvent("modem_message") + if channel == 15125 then + if msg.protocol == "entrypoint_advertise" then + if distance < canidate.distance and distance > (msg.max_distance or 128) then + canidate.max_distance = msg.max_distance + canidate.id = msg.sender + canidate.distance = distance + end + end + end + end + end) + if canidate.id == -1 then + sleep(5) + else + modem.transmit(15125,15125,{protocol="entrypoint_connect",sender=os.getComputerID(),target=canidate.id}) + last_heartbeat = os.epoch("utc") + end + end + elseif msg.protocol == "packet" then + if msg.hops >= 1 and msg.destination == os.computerID() then + os.queueEvent("network_packet",msg.content,msg.sender,msg.hops) + end + end + end + end +end + +function network.send(msg,destination) + if not msg then error("No message provided",2) end + if not destination then error("No destination provided",2) end + message_queue[#message_queue+1] = {protocol="packet",content=msg,destination=destination,sender=os.getComputerID(),hops=0} +end + +local function connect() + while true do + if os.epoch("utc") - last_heartbeat > math.max((300*canidate.distance)/100,300) then + canidate = {id = -1, distance = 764, max_distance=0} + parallel.waitForAny(function () repeat sleep(0.1) until canidate.id ~= -1 end, + function () + while true do + local _, _, channel, _, msg, distance = pullEvent("modem_message") + if channel == 15125 then + if msg.protocol == "entrypoint_advertise" then + if distance > (msg.max_distance or 128) then + modem.transmit(15125,15125,{protocol="out_of_range",sender=os.getComputerID(),target=msg.sender}) + elseif distance < canidate.distance then + canidate.max_distance = msg.max_distance + canidate.id = msg.sender + canidate.distance = distance + end + end + end + end + end) + if canidate.id == -1 then + sleep(5) + else + if canidate.distance > (canidate.max_distance or 128) then + modem.transmit(15125,15125,{protocol="out_of_range",sender=os.getComputerID(),target=canidate.id}) + else + modem.transmit(15125,15125,{protocol="entrypoint_connect",sender=os.getComputerID(),target=canidate.id}) + last_heartbeat = os.epoch("utc") + end + end + else + local msg = table.remove(message_queue,1) + if msg then + modem.transmit(15125,15125,msg) + end + end + sleep() + end +end +function network.getCandidate() + return canidate +end + +function network.loop() + parallel.waitForAny(connect,receive) +end + +return network diff --git a/meshnetBackend.lua b/meshnetBackend.lua new file mode 100644 index 0000000..9bd94c6 --- /dev/null +++ b/meshnetBackend.lua @@ -0,0 +1,36 @@ +local backend = {} +local network = require("libs.entrypointlib") +local loop = coroutine.create(network.loop or function () while true do sleep(100) end end) +local filter = nil + +-- some black magic bs that i pulled from https://gist.github.com/MCJack123/473475f07b980d57dd2bd818026c97e8 +local env = getfenv(rednet.run) +env.os = setmetatable({ + pullEventRaw = function () + local ev = table.pack(coroutine.yield()) + if filter == nil or filter == ev[1] then + _,filter = coroutine.resume(loop,table.unpack(ev, 1, ev.n)) + end + return table.unpack(ev, 1, ev.n) + end +},{__index=env.os}) + +local target = nil +function backend.setTarget(id) + target = id +end + +function backend.sendMessage(msg, id) + if not (id or target) then error("failed to imply or specify target id",2) end + network.send(msg,id or target) +end + +function backend.receiveMessage() + local _,msg,id,hops + repeat + _,msg,id,hops = os.pullEvent("network_packet") + until id == (target or id) + return msg,id +end + +return backend \ No newline at end of file diff --git a/startup.lua b/startup.lua new file mode 100644 index 0000000..fc03984 --- /dev/null +++ b/startup.lua @@ -0,0 +1,54 @@ +-- Source - https://stackoverflow.com/a/1579673 +-- Posted by Faisal Hanif, modified by community. See post 'Timeline' for change history +-- Retrieved 2026-04-05, License - CC BY-SA 3.0 + +---splits a string by a pattern +---@param pString string +---@param pPattern string +---@return string[] +local function split(pString, pPattern) + local Table = {} -- NOTE: use {n = 0} in Lua-5.0 + local fpat = "(.-)" .. pPattern + local last_end = 1 + local s, e, cap = pString:find(fpat, 1) + while s do + if s ~= 1 or cap ~= "" then + table.insert(Table,cap) + end + last_end = e+1 + s, e, cap = pString:find(fpat, last_end) + end + if last_end <= #pString then + cap = pString:sub(last_end) + table.insert(Table, cap) + end + return Table +end + +local printer = peripheral.find("printer") +if not printer then error("no printer found") end +printer.getSize = printer.getPageSize +local stratumDBlib = require("stratumDBlib") +local meshnetBackend = require("meshnetBackend") +meshnetBackend.setTarget(10) +stratumDBlib.setBackend(meshnetBackend) +print("connecting to database...") +local trans = stratumDBlib.loadTransforms("transforms","stratumDBlib") + +while true do + print("Press any key to print the first in queue order") + os.pullEvent("key") + local name,request = trans.removeOrder(1) + if name then + if not printer.newPage() then error("failed to create a page") end + print("Name:",name) + printer.setPageTitle("Order From "..name) + print("Request:",request) + setfenv(write,setmetatable({term = printer},{__index=_ENV}))(request) + setfenv(write,_ENV) + printer.endPage() + print("printed page!") + else + print("no orders in queue") + end +end diff --git a/stratumDBlib.lua b/stratumDBlib.lua new file mode 100644 index 0000000..4bc2965 --- /dev/null +++ b/stratumDBlib.lua @@ -0,0 +1,133 @@ +local stratum = {} + +-- Source - https://stackoverflow.com/a/1579673 +-- Posted by Faisal Hanif, modified by community. See post 'Timeline' for change history +-- Retrieved 2026-04-05, License - CC BY-SA 3.0 + +---splits a string by a pattern +---@param pString string +---@param pPattern string +---@return string[] +local function split(pString, pPattern) + local Table = {} -- NOTE: use {n = 0} in Lua-5.0 + local fpat = "(.-)" .. pPattern + local last_end = 1 + local s, e, cap = pString:find(fpat, 1) + while s do + if s ~= 1 or cap ~= "" then + table.insert(Table,cap) + end + last_end = e+1 + s, e, cap = pString:find(fpat, last_end) + end + if last_end <= #pString then + cap = pString:sub(last_end) + table.insert(Table, cap) + end + return Table +end + + + +---applys macros to code +---@param code string +---@return string +function stratum.applyMacros(code,libpath) + local import_name = "" + local alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"} + for _ = 1,10 do + import_name = import_name..alphabet[math.random(1,#alphabet)] + end + local import_string = "local "..import_name.." = require(\""..libpath.."\")\n" + local splits = split(" "..code,"%-%-#") + for instanceIndex = 2,#splits do + local instance = splits[instanceIndex] + local lines = split(instance:gsub("\n"," \n").." ","\n") + local nonSpacedLines = split(instance,"\n") + local contextDepth = 0 + local finalCodeLines = {} + for lineIndex = 2,#lines do + local line = lines[lineIndex] + local _,dos = line:gsub("do ","") + local _,funcs = line:gsub("function ","") + local _,thens = line:gsub("then ","") + local _,ends = line:gsub("end ","") + contextDepth = contextDepth+dos+funcs+thens-ends + finalCodeLines[#finalCodeLines+1] = nonSpacedLines[lineIndex] + if contextDepth <= 0 then + break + end + end + local replaceSub = table.concat(finalCodeLines,"\n") + local opcount = 0 + ---@type string + local funcdef = table.remove(finalCodeLines,1) + table.remove(finalCodeLines) + local body = table.concat(finalCodeLines,"\n") + local replace = funcdef + + if nonSpacedLines[1] == "data_transform" and string.find(funcdef,"function ") then + funcdef,opcount = funcdef:gsub("function ",""):gsub("local ", "") + local defsplit = split(funcdef, "%(") + defsplit[2] = split(defsplit[2],"%)")[1] or "_" + replace = defsplit[1].." = "..import_name..".createTransform(\""..defsplit[1].."\",\"local data,"..defsplit[2].." = ...\\n"..body:gsub("\n","\\n"):gsub("\"","\\\"").."\")" + if opcount > 0 then + replace = "local "..replace + end + elseif nonSpacedLines[1] == "common_transform" and string.find(funcdef,"function ") then + funcdef = funcdef:gsub("function ",""):gsub("local ", "") + local defsplit = split(funcdef, "%(") + defsplit[2] = split(defsplit[2],"%)")[1] or "_" + replace = replaceSub.."\n"..(import_name..".createTransform(\""..defsplit[1].."\",\"local data,"..defsplit[2].." = ...\\n"..body:gsub("\n","\\n"):gsub("\"","\\\"").."\")") + end + code = code:gsub(replaceSub:gsub("([%(%)%.%%%+%-%*%?%[%]%^%$])", "%%%1"),replace) + end + return import_string..code +end + +function stratum.loadTransforms(modules,libpath) + local file,err = package.searchpath(shell.dir(),modules) + if not file then + file,err = package.searchpath(shell.dir(),modules..".lua") + end + if not file then error("failed to find package: "..err,2) end + local file = fs.open(file,"r") + if not file then error("failed to open file",2) end + local contents = file.readAll() + file.close() + if not contents then error("failed to read file",2) end + contents = stratum.applyMacros(contents,libpath) + local trans, err = load(contents,"transforms","t",_ENV) + if not trans then error(err,2) end + return trans() +end + +function stratum.setBackend(backend) + if backend.sendMessage and backend.receiveMessage then + _G._STRATUMBACKEND = backend + end +end + +function stratum.createTransform(name,func) + local backend = _STRATUMBACKEND + if not backend or not (backend.sendMessage and backend.receiveMessage) then error("stratum backend not defined or defined incorrectly",2) end + backend.sendMessage({protocol="RegisterTransform",name=name,functionBody=func}) + while true do + local message = backend.receiveMessage() + if message.protocol == "TransformRegistered" and message.name == name then + return function (...) + backend.sendMessage({protocol = "CallTransform", name=name,params={...}}) + while true do + local message = backend.receiveMessage() + if message.protocol == "TransformResult" and message.name == name then + return table.unpack(message.result) + elseif message.protocol == "TransformError" and message.name == name then + error(message.error,2) + end + end + end + end + end +end + +return stratum \ No newline at end of file diff --git a/transforms.lua b/transforms.lua new file mode 100644 index 0000000..99c53af --- /dev/null +++ b/transforms.lua @@ -0,0 +1,26 @@ +local trans = {} + +--#data_transform +function trans.addOrder(requestorName,request) + if not data.orders then data.orders = {} end + data.orders[#data.orders+1] = {name=requestorName,request=request} +end + +--#data_transform +function trans.getOrder(index) + local order = (data.orders or {})[index] or {} + return order.name,order.request +end + +--#data_transform +function trans.getOrderCount() + return #(data.orders or {}) +end + +--#data_transform +function trans.removeOrder(index) + local order = table.remove(data.orders or {},index) or {} + return order.name,order.request +end + +return trans \ No newline at end of file