This commit is contained in:
2026-04-06 14:13:46 -07:00
commit eb4659817e
11 changed files with 857 additions and 0 deletions

12
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,12 @@
{
"Lua.workspace.library": [
"/home/ruffles/.vscode/extensions/pawz.polytoria-lua-1.1.1/api",
"${addons}/cc-tweaked/module/library"
],
"Lua.runtime.version": "Lua 5.3",
"Lua.runtime.builtin": {
"io": "disable",
"os": "disable"
},
"Lua.workspace.checkThirdParty": false
}

8
data.db Normal file
View File

@@ -0,0 +1,8 @@
{
materials = {
Steel = 0.0625,
Iron = 0.03125,
Gold = 0.021739130434783,
},
currency_unit = "diamonds",
}

124
entrypointlib.lua Normal file
View File

@@ -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

91
localdb.lua Normal file
View File

@@ -0,0 +1,91 @@
local db = {}
if not fs.exists("data.db") then
local file = fs.open("data.db", "w")
file.write("{}")
fs.close()
end
local file = fs.open("data.db","r+")
if not file then error("failed to open db file") end
local function readTable()
file.seek("set")
return textutils.unserialise(file.readAll() or "{}") or {}
end
local function writeTable(t)
file.seek("set")
file.write(textutils.serialise(t))
file.flush()
end
---returns a list of all materials
---@return string[]
function db.getMaterials()
local table = readTable()
local materials = {}
for k,_ in pairs(table.materials or {}) do
materials[#materials+1] = k
end
return materials
end
---gets the price of a material
---@param mat string
---@return number
function db.getPrice(mat)
return (readTable().materials or {})[mat]
end
---returns a list of all currencies
---@return string[]
function db.getCurrencies()
local table = readTable()
local currencies = {}
for k,_ in pairs(table.currencies or {}) do
currencies[#currencies+1] = k
end
return currencies
end
---gets the worth of a currency
---@param cur string
---@return number
function db.getCurrencyWorth(cur)
return (readTable().currencies or {})[cur]
end
---sets the price of a material
---@param mat string
---@param price number
function db.setPrice(mat,price)
local table = readTable()
if not table.materials then table.materials = {} end
table.materials[mat] = price
writeTable(table)
end
---sets the worth of a currency
---@param cur string
---@param worth number
function db.setWorth(cur,worth)
local table = readTable()
if not table.currencies then table.currencies = {} end
table.currencies[cur] = worth
writeTable(table)
end
---gets the currency unit string
---@return string
function db.getCurrencyUnit()
return readTable().currency_unit or "cr"
end
---sets the currency unit string
---@param unit string
function db.setCurrencyUnit(unit)
local table = readTable()
table.currency_unit = unit
writeTable(table)
end
return db

101
remotedb.lua Normal file
View File

@@ -0,0 +1,101 @@
local dbid = 7
local eplib = require("entrypointlib")
local db = {}
db.loop = eplib.loop
local tableCache = nil
local function readTable()
if not tableCache then
eplib.send({proto = "getTable"}, dbid)
local event = {}
repeat
event = {os.pullEvent("network_packet")}
until event[3] == dbid and event[2].proto == "resp"
tableCache = event[2].table
end
return tableCache
end
local function writeTable(t)
local event = {}
repeat
eplib.send({proto = "setTable", table = t}, dbid)
parallel.waitForAny(function () event = {os.pullEvent("network_packet")} end, function () sleep(0.5) end)
until event[3] == dbid and event[2].proto == "OK"
tableCache = t
end
---returns a list of all materials
---@return string[]
function db.getMaterials()
local table = readTable()
local materials = {}
for k,_ in pairs(table.materials or {}) do
materials[#materials+1] = k
end
return materials
end
---gets the price of a material
---@param mat string
---@return number
function db.getPrice(mat)
return (readTable().materials or {})[mat]
end
---returns a list of all currencies
---@return string[]
function db.getCurrencies()
local table = readTable()
local currencies = {}
for k,_ in pairs(table.currencies or {}) do
currencies[#currencies+1] = k
end
return currencies
end
---gets the worth of a currency
---@param cur string
---@return number
function db.getCurrencyWorth(cur)
return (readTable().currencies or {})[cur]
end
---sets the price of a material
---@param mat string
---@param price number
function db.setPrice(mat,price)
local table = readTable()
if not table.materials then table.materials = {} end
table.materials[mat] = price
writeTable(table)
end
---sets the worth of a currency
---@param cur string
---@param worth number
function db.setWorth(cur,worth)
local table = readTable()
if not table.currencies then table.currencies = {} end
table.currencies[cur] = worth
writeTable(table)
end
---gets the currency unit string
---@return string
function db.getCurrencyUnit()
return readTable().currency_unit or "cr"
end
---sets the currency unit string
---@param unit string
function db.setCurrencyUnit(unit)
local table = readTable()
table.currency_unit = unit
writeTable(table)
end
return db

31
remotedbserver.lua Normal file
View File

@@ -0,0 +1,31 @@
local eplib = require("entrypointlib")
local function readTable()
local file = fs.open("data.db","r")
if not file then error("failed to open db file") end
return textutils.unserialise(file.readAll() or "{}") or {}
end
local function writeTable(t)
local file = fs.open("data.db", "w")
if not file then error("failed to open db file") end
file.write(textutils.serialise(t))
file.close()
end
local function receive()
while true do
sleep(0)
local _,msg,id = os.pullEvent("network_packet")
if msg.proto == "getTable" then
eplib.send({proto = "resp", table = readTable()}, id)
print("sent table to "..tostring(id))
elseif msg.proto == "setTable" then
writeTable(msg.table)
print("updated table from "..tostring(id))
eplib.send({proto="OK"},id)
end
end
end
parallel.waitForAny(eplib.loop,receive)

253
startup.lua Normal file
View File

@@ -0,0 +1,253 @@
local db = require("stratumBackend")
print("setup backend")
local completion = require("cc.completion")
local total_items = {}
local monitor = peripheral.find("monitor")
local price_map = {}
local unit_name = nil
local full_item_qoute
term.clear()
local x,y = term.getSize()
term.setCursorPos(1,y)
local function tallyUpItems(price)
local items = {}
local currencies = db.getCurrencies()
local worthmap = {}
local worths = {}
local minimum = 999
for k,v in ipairs(currencies) do
worthmap[db.getCurrencyWorth(v)] = v
worths[#worths+1] = db.getCurrencyWorth(v)
minimum = math.min(db.getCurrencyWorth(v),minimum)
end
table.sort(worths, function (a, b)
return a > b
end)
price = math.ceil(price/minimum)*minimum
repeat
local ran = false
for _,i in ipairs(worths) do
if i <= price then
items[worthmap[i]] = (items[worthmap[i]] or 0)+1
price = price - i
ran = true
end
end
if not ran then
break
end
until price <= 0
return items
end
local function input()
while true do
local event = {os.pullEvent()}
if event[1] == "key" then
if event[2] == keys.a then
sleep(0)
local added_item_name = nil
local added_item_count = nil
local x,y = term.getSize()
term.setCursorPos(1,y)
term.write("item name > ")
local materials = db.getMaterials()
added_item_name = read(nil,nil, function(text) return completion.choice(text, materials) end)
if added_item_name == "" then
added_item_name = nil
else
repeat
term.write("item count > ")
added_item_count = tonumber(read())
until added_item_count ~= nil
if added_item_count <= 0 then
added_item_name = nil
added_item_count = nil
else
if not db.getPrice(added_item_name) then
print("item not found... define a price?")
print("price in items per 1 "..unit_name)
local new_price = nil
repeat
term.write("item price > ")
new_price = 1/tonumber(read())
until new_price ~= nil
---@cast new_price number
if new_price > 0 then
db.setPrice(added_item_name,new_price)
end
end
total_items[added_item_name] = (total_items[added_item_name] or 0 ) + added_item_count
price_map[added_item_name] = db.getPrice(added_item_name)
end
end
elseif event[2] == keys.l then
for k,v in pairs(total_items) do
print(tostring(k).." x"..tostring(v))
end
elseif event[2] == keys.t then
local total = 0
for k,v in pairs(total_items) do
total = total + (( db.getPrice(k) or 0)*v)
end
print("total: "..tostring(total).." "..tostring(db.getCurrencyUnit()))
elseif event[2] == keys.f then
sleep(0)
local total = 0
for k,v in pairs(total_items) do
print(tostring(k).." x"..tostring(v))
total = total + (( db.getPrice(k) or 0)*v)
end
print("total: "..tostring(total).." "..tostring(db.getCurrencyUnit()))
full_item_qoute = tallyUpItems(total)
for k,v in pairs(full_item_qoute) do
print(tostring(k).." x"..tostring(v))
total = total + (( db.getPrice(k) or 0)*v)
end
term.write("finish order? (Y/n)")
local resp = read()
if string.find("n", string.lower(resp)) == nil or resp == "" then
total_items = {}
print("finished order..")
end
full_item_qoute = nil
elseif event[2] == keys.d then
sleep(0)
local removed_item_name = nil
local x,y = term.getSize()
term.setCursorPos(1,y)
term.write("item name > ")
local materials = db.getMaterials()
removed_item_name = read(nil,nil, function(text) return completion.choice(text, materials) end)
if removed_item_name == "" then
removed_item_name = nil
else
if total_items[removed_item_name] then
total_items[removed_item_name] = nil
print("removed item")
end
end
elseif event[2] == keys.n then
sleep(0)
term.setCursorPos(1,y)
term.write("unit name > ")
local unit_namel = read()
if unit_namel ~= "" then
db.setCurrencyUnit(unit_namel)
unit_name = unit_namel
print("set currency unit")
end
elseif event[2] == keys.c then
sleep(0)
local added_currency_name = nil
local added_currency_worth = nil
local x,y = term.getSize()
term.setCursorPos(1,y)
term.write("currency name > ")
added_currency_name = read()
if added_currency_name == "" then
added_currency_name = nil
else
repeat
term.write("currency worth > ")
added_currency_worth = tonumber(read())
until added_currency_worth ~= nil
if added_currency_worth <= 0 then
added_currency_name = nil
added_currency_worth = nil
else
---@cast added_currency_worth number
db.setWorth(added_currency_name,added_currency_worth)
end
end
elseif event[2] == keys.i then
sleep(0)
local added_item_name = nil
local added_item_price = nil
local x,y = term.getSize()
term.setCursorPos(1,y)
term.write("item name > ")
local materials = db.getMaterials()
added_item_name = read(nil,nil, function(text) return completion.choice(text, materials) end)
if added_item_name == "" then
added_item_name = nil
else
repeat
print("price in items per 1 "..unit_name)
term.write("item price > ")
added_item_price = 1/tonumber(read())
until added_item_price ~= nil
if added_item_price <= 0 then
added_item_name = nil
added_item_price = nil
else
---@cast added_item_price number
db.setPrice(added_item_name,added_item_price)
price_map[added_item_name] = db.getPrice(added_item_name)
end
end
end
end
end
end
local function render_monitor()
while true do
sleep(0)
if monitor then
if not full_item_qoute then
if not unit_name then
unit_name = db.getCurrencyUnit()
end
monitor.clear()
local x,y = monitor.getSize()
local total = 0
for k,v in pairs(total_items) do
monitor.setCursorPos(1,y)
monitor.write(tostring(k).." x"..tostring(v).."")
monitor.scroll(1)
total = total + (( price_map[k] or 0)*v)
end
monitor.setCursorPos(1,y)
monitor.write("total: "..tostring(total).." "..tostring(db.getCurrencyUnit()))
else
if not unit_name then
unit_name = db.getCurrencyUnit()
end
monitor.clear()
local x,y = monitor.getSize()
local total = 0
for k,v in pairs(total_items) do
total = total + (( price_map[k] or 0)*v)
end
for k,v in pairs(full_item_qoute) do
monitor.setCursorPos(1,y)
monitor.write(tostring(k).." x"..tostring(v).."")
monitor.scroll(1)
end
monitor.setCursorPos(1,1)
monitor.write("Full Item Quote:")
monitor.setCursorPos(1,y)
monitor.write("total: "..tostring(total).." "..tostring(db.getCurrencyUnit()))
end
end
end
end
local loops = {input,render_monitor}
if db.loop then loops[#loops+1] = db.loop end
for k,v in ipairs(loops) do
---@cast loops thread[]
loops[k] = coroutine.create(v)
coroutine.resume(loops[k])
end
print("starting update loop")
while true do
local event = {os.pullEvent()}
for _,v in ipairs(loops) do
if coroutine.status(v) ~= "dead" then
local succ, err = coroutine.resume(v, table.unpack(event))
if not succ then
print(err)
end
end
end
end

10
stratumBackend/init.lua Normal file
View File

@@ -0,0 +1,10 @@
local sdb = require("stratumBackend.stratumDBlib")
local meshnetBackend = require("stratumBackend.meshnetBackend")
print("loaded meshent backend")
meshnetBackend.setTarget(10)
print("set target")
sdb.setBackend(meshnetBackend)
print("set backend")
local trans = sdb.loadTransforms("stratumBackend/transforms","stratumBackend.stratumDBlib")
print("finished preparing transforms")
return trans

View File

@@ -0,0 +1,36 @@
local backend = {}
local network = require("entrypointlib")
local loop = coroutine.create(network.loop)
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

View File

@@ -0,0 +1,137 @@
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
print("applying macros")
contents = stratum.applyMacros(contents,libpath)
print("loading contents")
local trans, err = load(contents,"transforms","t",_ENV)
if not trans then error(err,2) end
print("running contents")
return trans()
end
function stratum.setBackend(backend)
if backend.sendMessage and backend.receiveMessage then
_G._STRATUMBACKEND = backend
end
end
function stratum.createTransform(name,func)
print("registering "..name)
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

View File

@@ -0,0 +1,54 @@
local db = {}
--#data_transform
function db.getMaterials()
local materials = {}
for k,_ in pairs(data.materials or {}) do
materials[#materials+1] = k
end
return materials
end
--#data_transform
function db.getPrice(mat)
return (data.materials or {})[mat]
end
--#data_transform
function db.getCurrencies()
local currencies = {}
for k,_ in pairs(data.currencies or {}) do
currencies[#currencies+1] = k
end
return currencies
end
--#data_transform
function db.getCurrencyWorth(cur)
return (data.currencies or {})[cur]
end
--#data_transform
function db.setPrice(mat,price)
if not data.materials then data.materials = {} end
data.materials[mat] = price
end
--#data_transform
function db.setWorth(cur,worth)
if not data.currencies then data.currencies = {} end
data.currencies[cur] = worth
end
--#data_transform
function db.getCurrencyUnit()
return data.currency_unit or "cr"
end
--#data_transform
function db.setCurrencyUnit(unit)
data.currency_unit = unit
end
return db