-- station.lua - Drone Delivery station: storages -> outbox -> docking port -> drone -- -- CEE only. Devices on the computer's sides or on CEE Signal Ports (pins), each gets a role: -- STORE storages (any number): what the station sells / where received items go -- OUTBOX the order is put here (as much as fits); a hopper / funnel from it pushes into the port -- (no packager: the drone carries the items as they are - user, 2026-10-20) -- The docking port (facing up, always powered) is moved by blocks only - CC can't read its buffer: -- OUTBOX -> hopper -> port (the 1-slot buffer lets one stack through to the drone at a time) -- a comparator at the port into a Signal Port = dock sensor (15 = a drone is locked on) -- Receiving: a drone docks and drops its items through its funnel; funnels at the station catch -- them into a STORE (no computer work). -- Items move between storages by CC: the target needs a name (side) or the source does (pullItems). -- In the game (user, 2026-10-20) only storages right against the computer work: keep every STORE and -- the OUTBOX on a computer side; the Signal Port pins are for redstone (port power, dock sensor). -- Mode (DEVICES page): STORAGE = the STOREs only; NETWORK = a Create Stock Ticker (role NET, side or -- pin) only: the whole Create logistics network as one storage. Its stock() counts; -- requestFiltered(net_addr, ...) makes Create pack the items and send them to the packager with that -- address at the OUTBOX, which unpacks them there (the drone waits for the count). No OUTBOX: the -- Frogport with that address sits on the docking port and drops the items straight into it. -- Server: wss, token from the order site ("My stations"), sends the stock, gets "load" jobs. -- Lock: the station is its owner's: he sets his own password ([PASS]; the server's drone password is -- not used here). With it the settings and leaving (Ctrl+T, [EXIT]) ask for it; the owner can clear -- it from the order site (station page). Ctrl+T never just stops the program; startup.lua starts it. -- Updates: the server announces a new version; with no job running the station downloads it, checks -- that it compiles, keeps the old one as station_prev.lua and reboots. local CONFIG_FILE = "station.json" local config = { url = "wss://delivery.msiu.eu/ws/station", token = false, roles = {}, -- peripheral name -> "store" / "outbox" / "net" mode = "store", -- "store": sell from the STOREs / "net": from the Create network (NET) net_addr = "", -- NET: the address of the packager at the OUTBOX labels = {}, -- peripheral name -> own name shown on the screen port_side = "none", -- what powers the port: a computer side, "pin3" (CEE Signal Port) or "none" dock_sensor = "none", -- comparator at the port: a computer side or "pin3" (15 = docked) pw_hash = false, -- sha256(salt .. ":" .. password); false = no lock pw_salt = false, pw_own = false, -- the password was set here (older versions took the server's) } local function saveConfig() local f = fs.open(CONFIG_FILE, "w") if f then f.write(textutils.serializeJSON(config)); f.close() end end local function loadConfig() if not fs.exists(CONFIG_FILE) then return end local f = fs.open(CONFIG_FILE, "r") if not f then return end local data = textutils.unserializeJSON(f.readAll()) f.close() if type(data) == "table" then for k, v in pairs(data) do if config[k] ~= nil then config[k] = v end end end if type(config.roles) ~= "table" then config.roles = {} end for id, r in pairs(config.roles) do -- BUFFER / PACKER of the old scheme if r ~= "store" and r ~= "outbox" and r ~= "net" then config.roles[id] = nil end end if config.pw_hash and not config.pw_own then -- the old server password: the owner never knew it config.pw_hash, config.pw_salt = false, false saveConfig() end end loadConfig() -- ---------- lock: password (only its salted SHA-256 is kept) ---------- local lock = { unlocked = false, lastKey = 0 } function lock.sha256(msg) local band, bor, bxor, bnot, rrot, rsh = bit32.band, bit32.bor, bit32.bxor, bit32.bnot, bit32.rrotate, bit32.rshift local k = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 } local h = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 } local len = #msg msg = msg .. "\128" .. string.rep("\0", (55 - len) % 64) local bits = len * 8 for i = 7, 0, -1 do msg = msg .. string.char(math.floor(bits / 2 ^ (8 * i)) % 256) end local M = 4294967296 for chunk = 1, #msg, 64 do local w = {} for i = 0, 15 do local a, b, c, d = msg:byte(chunk + i * 4, chunk + i * 4 + 3) w[i] = ((a * 256 + b) * 256 + c) * 256 + d end for i = 16, 63 do local s0 = bxor(rrot(w[i - 15], 7), rrot(w[i - 15], 18), rsh(w[i - 15], 3)) local s1 = bxor(rrot(w[i - 2], 17), rrot(w[i - 2], 19), rsh(w[i - 2], 10)) w[i] = (w[i - 16] + s0 + w[i - 7] + s1) % M end local a, b, c, d, e, f, g, hh = h[1], h[2], h[3], h[4], h[5], h[6], h[7], h[8] for i = 0, 63 do local S1 = bxor(rrot(e, 6), rrot(e, 11), rrot(e, 25)) local ch = bxor(band(e, f), band(bnot(e), g)) local t1 = (hh + S1 + ch + k[i + 1] + w[i]) % M local S0 = bxor(rrot(a, 2), rrot(a, 13), rrot(a, 22)) local maj = bxor(band(a, b), band(a, c), band(b, c)) local t2 = (S0 + maj) % M hh, g, f, e, d, c, b, a = g, f, e, (d + t1) % M, c, b, a, (t1 + t2) % M end h[1], h[2], h[3], h[4] = (h[1] + a) % M, (h[2] + b) % M, (h[3] + c) % M, (h[4] + d) % M h[5], h[6], h[7], h[8] = (h[5] + e) % M, (h[6] + f) % M, (h[7] + g) % M, (h[8] + hh) % M end local out = {} for i = 1, 8 do out[i] = string.format("%08x", h[i]) end return table.concat(out) end function lock.check(pw) return config.pw_hash and lock.sha256((config.pw_salt or "") .. ":" .. (pw or "")) == config.pw_hash end function lock.isOpen() return not config.pw_hash or lock.unlocked end function lock.set(pw) if pw == "" then config.pw_hash, config.pw_salt = false, false else config.pw_salt = string.format("%08x%08x", math.random(0, 2147483646), math.random(0, 2147483646)) config.pw_hash = lock.sha256(config.pw_salt .. ":" .. pw) end config.pw_own = true saveConfig() end local state = { net = "off", name = nil, kind = nil, docked = false, job = nil, msg = "", inv = {}, log = {} } local running = true local function nowMs() local ok, t = pcall(os.epoch, "utc") return ok and t or os.clock() * 1000 end local function note(text) state.msg, state.msgT = text, os.clock() table.insert(state.log, 1, os.date and (os.date("%H:%M:%S") .. " " .. text) or text) while #state.log > 10 do table.remove(state.log) end end -- ============================================================ -- Devices: a CC name (computer side) or "pin3" / "pin3#2" (CEE Signal Port, maybe no name) -- ============================================================ local function pinId(id) if type(id) ~= "string" then return nil end local p, i = id:match("^pin(%d+)#?(%d*)$") if not p then return nil end return tonumber(p), tonumber(i) or 1 end -- object to call + its CC name (nil = only through the pin) local function getDev(id) local p, i = pinId(id) if p then if type(cee) ~= "table" or type(cee.getPeripherals) ~= "function" then return nil end local ok, l = pcall(cee.getPeripherals, p) return ok and type(l) == "table" and l[i] or nil, nil end if type(id) ~= "string" or not peripheral.isPresent(id) then return nil end return peripheral.wrap(id), id end -- CC moves items only INTO a named device: push to a name, or pull from a named source local function move(fromH, fromName, toH, toName, slot, limit) if not fromH or not toH then return false, "device missing" end if toName then return pcall(fromH.pushItems, toName, slot, limit) end if fromName and type(toH.pullItems) == "function" then return pcall(toH.pullItems, fromName, slot, limit) end return false, "both on pins: put one of them on a computer side" end -- a redstone level 0-15 on a computer side or a pin local function input(src) if type(src) ~= "string" or src == "none" then return nil end local p = tonumber(src:match("^pin(%d+)$") or "") local ok, v if p then if type(cee) ~= "table" or type(cee.getAnalog) ~= "function" then return nil end ok, v = pcall(cee.getAnalog, p) else ok, v = pcall(redstone.getAnalogInput, src) end return ok and type(v) == "number" and v or nil end local function named(role) local list = {} for id, r in pairs(config.roles) do if r == role and getDev(id) then list[#list + 1] = id end end table.sort(list) return list end -- id, object, CC name of the one device with this role local function one(role) local id = named(role)[1] if not id then return nil end local h, nm = getDev(id) return id, h, nm end local function isBox(it) return type(it) == "table" and type(it.name) == "string" and it.name:find("package") ~= nil end local function listOf(p) if not p then return {} end local ok, l = pcall(p.list) return ok and type(l) == "table" and l or {} end local function countIn(p) local n = 0 for _, it in pairs(listOf(p)) do n = n + it.count end return n end -- display names, asked once per item (getItemDetail waits a server tick). CC turns every letter -- outside Latin-1 into "?" (the server runs in Russian), so such a name is made from the id: -- "minecraft:diamond_pickaxe" -> "Diamond Pickaxe" local function nameFromId(id) local path = tostring(id):gsub("^[^:]*:", ""):gsub("[/%-]", "_") local words = {} for w in path:gmatch("[^_]+") do words[#words + 1] = w:sub(1, 1):upper() .. w:sub(2) end return #words > 0 and table.concat(words, " ") or tostring(id) end local labels = {} local stackOf = {} -- item -> stack size (64, 16 for ender pearls, 1 for tools...) -- stock of all storages (without boxes): { name -> {name, label, count} } local function stock() local out = {} for _, id in ipairs(config.mode == "net" and {} or named("store")) do local p = getDev(id) for slot, it in pairs(listOf(p)) do if not isBox(it) then local e = out[it.name] if not e then if not labels[it.name] then local ok, d = pcall(p.getItemDetail, slot) local dn = ok and type(d) == "table" and d.displayName labels[it.name] = (type(dn) == "string" and dn ~= "" and not dn:find("?", 1, true)) and dn or nameFromId(it.name) stackOf[it.name] = ok and type(d) == "table" and tonumber(d.maxCount) or nil end e = { name = it.name, label = labels[it.name], count = 0, max = stackOf[it.name] } out[it.name] = e end e.count = e.count + it.count end end end local t = config.mode == "net" and getDev(named("net")[1]) -- detailed list: the names come with the items (getStockItemDetail(i) reads a fresh list in -- another order -> other items' names) local ok, l = pcall(t and t.stock, true) if t and not ok then if not state.stockErr then note("stock(true): " .. tostring(l)) end state.stockErr = true ok, l = pcall(t.stock) -- names from the ids then end for _, it in pairs(ok and type(l) == "table" and l or {}) do if type(it) == "table" and type(it.name) == "string" and not isBox(it) then if not labels[it.name] then local dn = it.displayName labels[it.name] = (type(dn) == "string" and dn ~= "" and not dn:find("?", 1, true)) and dn or nameFromId(it.name) stackOf[it.name] = tonumber(it.maxCount) end local e = out[it.name] or { name = it.name, label = labels[it.name], count = 0, max = stackOf[it.name] } out[it.name] = e e.count = e.count + (tonumber(it.count) or 0) end end return out end -- move up to n of an item from the storages into the device `toId`; returns how many moved local function fetch(item, n, toId) local moved = 0 local toH, toN = getDev(toId) local err for _, id in ipairs(config.mode == "net" and {} or named("store")) do local p, pn = getDev(id) for slot, it in pairs(listOf(p)) do if it.name == item and moved < n then local ok, k = move(p, pn, toH, toN, slot, n - moved) if ok and type(k) == "number" then moved = moved + k elseif not ok then err = k end end end if moved >= n then break end end local t = config.mode == "net" and getDev(named("net")[1]) if moved < n and t and config.net_addr ~= "" then local ok, k = pcall(t.requestFiltered, config.net_addr, { name = item, _requestCount = n - moved }) -- Create returns whether the request went out (true/false), not a count if ok and k == true then moved = n elseif ok and type(k) == "number" then moved = moved + k elseif ok then if state.refused ~= item then note("network refused " .. item) end state.refused = item else err = k end end if moved == 0 and err then note("move: " .. tostring(err)) end return moved end local function slotsUsed(p) local n = 0 for _ in pairs(listOf(p)) do n = n + 1 end return n end -- ============================================================ -- Load job: the order into the outbox (as much as fits), its hopper feeds the port -- ============================================================ local JOB_TIMEOUT = 90 -- s without any progress -> failed local function jobFail(why) local j = state.job state.job = nil note("order #" .. j.order .. " failed: " .. why) state.outbox = state.outbox or {} state.outbox[#state.outbox + 1] = { t = "load_failed", order = j.order, msg = why } end local function jobStart(m) if state.job then state.outbox = state.outbox or {} state.outbox[#state.outbox + 1] = { t = "load_failed", order = m.order, msg = "station busy with #" .. state.job.order } return end local want = {} for _, it in ipairs(m.items or {}) do if type(it.name) == "string" and tonumber(it.count) then want[#want + 1] = { name = it.name, left = tonumber(it.count), total = tonumber(it.count) } end end state.job = { order = m.order, want = want, put = 0, sent = 0, last = os.clock() } note("order #" .. tostring(m.order) .. ": loading") end -- the order was cancelled: stop, and what still waits in the outbox goes back into a STORE (what -- already went through the port the drone drops back into the funnels) local function jobCancel(order) local j = state.job if not j or j.order ~= order then return end state.job = nil local outName, outb, outN = one("outbox") local back = 0 if outb then for slot, it in pairs(listOf(outb)) do for _, id in ipairs(named("store")) do local sh, sn = getDev(id) local ok, k = move(outb, outN, sh, sn, slot, it.count) if ok and type(k) == "number" then back = back + k; it.count = it.count - k end if it.count <= 0 then break end end end end state.invDirty = true note(string.format("order #%d cancelled: %d back into the storages", order, back)) end local function jobTick() local j = state.job local outName, outb = one("outbox") -- NETWORK: no OUTBOX needed - Create sends the packages straight to the Frogport (net_addr) on the port if not outName and config.mode ~= "net" then return jobFail("set an OUTBOX") end if os.clock() - j.last > JOB_TIMEOUT then return jobFail("no progress for " .. JOB_TIMEOUT .. " s") end if not j.checked then -- enough in stock for the whole order? local s = stock() for _, w in ipairs(j.want) do if not s[w.name] or s[w.name].count < w.left then return jobFail("not enough " .. w.name) end end j.checked = true end -- 1. top the outbox up (it takes what fits; the rest waits for the hopper to empty it) local leftAll = 0 local okS, size = outb and pcall(outb.size) local room = not (okS and type(size) == "number") or slotsUsed(outb) < size for _, w in ipairs(j.want) do if w.left > 0 and room then local k = fetch(w.name, w.left, outName) if k > 0 then w.left, j.put, j.last = w.left - k, j.put + k, os.clock() end end leftAll = leftAll + w.left end -- 2. what left the outbox went into the port (only while a drone is locked on) local inOut = countIn(outb) local sent = j.put - inOut if sent > j.sent then j.sent, j.last = sent, os.clock() end -- 3. all through the port: the drone waits for this many items in its cargo storage if leftAll == 0 and inOut == 0 and j.put > 0 and state.docked then state.outbox = state.outbox or {} -- a packager after the outbox turns this into boxes of up to 9 stacks: how many boxes at most local stacks = 0 for _, w in ipairs(j.want) do stacks = stacks + math.ceil(w.total / (stackOf[w.name] or 64)) end state.outbox[#state.outbox + 1] = { t = "loaded", order = j.order, boxes = j.put, packs = math.max(1, math.ceil(stacks / 9)) } note(string.format("order #%d loaded: %d items", j.order, j.put)) state.job = nil end end local periphs, readHolds -- screen helpers (defined below), the work loop refreshes with them -- ============================================================ -- Work loop: port, received boxes, packing -- ============================================================ local function portPower(out, on) local p = tonumber(tostring(out):match("^pin(%d+)$") or "") if p then if type(cee) == "table" and cee.setOutput then pcall(cee.setOutput, p, on) end elseif out ~= "none" then pcall(redstone.setOutput, out, on) end end local function workTick() portPower(config.port_side, os.clock() >= (state.portOffUntil or 0)) -- [T] on the PORT page: off 3 s -- docked = the comparator at the port shows 15; the port's hoppers move the boxes local v = input(config.dock_sensor) state.dockSignal = v state.docked = v ~= nil and v >= 15 if state.job then jobTick() end end local function workLoop() local lastInv = -100 while running do local ok, err = pcall(workTick) if not ok then note("error: " .. tostring(err)) end if os.clock() - (state.holdsT or -10) > 2 then state.holdsT = os.clock() pcall(readHolds, periphs()) end if os.clock() - lastInv > 5 then lastInv = os.clock() local okS, s = pcall(stock) if okS then local items = {} for _, e in pairs(s) do items[#items + 1] = e end state.inv = items state.invDirty = true end end sleep(0.2) end end -- ============================================================ -- Server link -- ============================================================ local net = { ws = nil, connecting = false, nextTry = 0 } local function send(m) if not net.ws then return end if not pcall(net.ws.send, textutils.serializeJSON(m)) then net.ws, state.net, net.nextTry = nil, "lost", nowMs() + 3000 end end local function handle(raw) local m = textutils.unserializeJSON(raw) if type(m) ~= "table" then return end if m.t == "pwreset" then -- the owner cleared it on the order site lock.set("") note("password cleared from the site") end if m.t == "welcome" or m.t == "version" then if m.t == "welcome" then -- the name as UTF-8: CC's JSON turns every \uXXXX past 255 into "?" local raw8 = raw:match('"name"%s*:%s*"(.-)"') state.name = raw8 and utf8 and raw8:gsub("\\u(%x%x%x%x)", function(h) return utf8.char(tonumber(h, 16)) end) or m.name state.kind = m.kind state.net = "online" state.invDirty = true end local cur = state.ver if type(m.ver) == "string" and m.ver ~= cur and m.ver ~= state.updBad then state.updWanted = m.ver end elseif m.t == "bad_token" then state.net = "token refused: check it on the site" if net.ws then pcall(net.ws.close) end net.ws, net.nextTry = nil, nowMs() + 30000 elseif m.t == "load" then jobStart(m) elseif m.t == "load_cancel" then jobCancel(m.order) end end -- ---------- program update ---------- local function readVer() if not fs.exists("station_ver.txt") then return "unknown" end local f = fs.open("station_ver.txt", "r") local v = f and f.readAll() or "" if f then f.close() end v = v:gsub("%s", "") return v ~= "" and v or "unknown" end state.ver = readVer() local function update() local ver = state.updWanted state.updWanted = nil local url = config.url:gsub("^wss://", "https://"):gsub("^ws://", "http://"):gsub("/ws/station$", "/prog/station") local ok, r = pcall(http.get, url, { ["X-Token"] = config.token or "" }) if not ok or not r then note("update: download failed"); return end local code = r.readAll() r.close() local fn, err = load(code, "=station_new", "t", {}) if not fn then state.updBad = ver note("update refused: " .. tostring(err)) state.outbox = state.outbox or {} state.outbox[#state.outbox + 1] = { t = "upd", ok = false, ver = ver, msg = tostring(err):sub(1, 200) } return end if fs.exists("station_prev.lua") then fs.delete("station_prev.lua") end if fs.exists("station.lua") then fs.copy("station.lua", "station_prev.lua") end local f = fs.open("station.lua", "w"); f.write(code); f.close() f = fs.open("station_ver.txt", "w"); f.write(ver); f.close() send({ t = "upd", ok = true, ver = ver }) note("updated to " .. ver .. " - restarting") sleep(1) os.reboot() end local function netLoop() local tmr = os.startTimer(1) while running do local ev, a, b = os.pullEvent() if ev == "timer" and a == tmr then tmr = os.startTimer(1) -- a newer station.lua put onto the disk directly: restart into it (no job running) if not state.job and readVer() ~= state.ver and readVer() ~= "unknown" then note("new version on the disk - restarting") sleep(1) os.reboot() end if state.updWanted and not state.job and net.ws then pcall(update) end if net.ws then if state.invDirty then -- textutils turns an empty table into {} instead of [] send({ t = "inv", items = #state.inv > 0 and state.inv or textutils.empty_json_array }) state.invDirty = false end send({ t = "st", docked = state.docked, busy = state.job and state.job.order or nil, msg = state.msg, ver = state.ver }) while state.outbox and #state.outbox > 0 do send(table.remove(state.outbox, 1)) end elseif not net.connecting and nowMs() >= net.nextTry then if not config.token then state.net = "no token: [TOKEN]" elseif http and http.websocketAsync then net.connecting, state.net = true, "connecting" if not pcall(http.websocketAsync, config.url) then net.connecting, state.net, net.nextTry = false, "bad url", nowMs() + 10000 end else state.net = "no http API" end end elseif ev == "websocket_success" and a == config.url then net.ws, net.connecting, state.net = b, false, "hello" send({ t = "hello", token = config.token }) elseif ev == "websocket_failure" and a == config.url then net.connecting, state.net, net.nextTry = false, "no server", nowMs() + 5000 elseif ev == "websocket_closed" and a == config.url then net.ws, state.net, net.nextTry = nil, "lost", nowMs() + 3000 elseif ev == "websocket_message" and a == config.url then handle(b) end end end -- ============================================================ -- Screen: 3 pages in the order site's dark theme (palette set on start, put back on exit) -- Status server / port / order cards, setup chips, stock with bars, last event -- Devices every storage: < ROLE >, click the name = rename, what it holds -- Port dock sensor and port redstone: < value >, click the value = type it, Test -- Looking around needs no password, changing something does (10 minutes without asking again). -- The screen only draws what the work loop read (every peripheral call waits a server tick). -- ============================================================ local ROLE_FOR = { "store", "outbox" } -- the roles of a storage, in click order local ROLE_LABEL = { store = "STORE", outbox = "OUTBOX", net = "NET" } local ROLE_COL = { store = "5", outbox = "4", net = "3" } local function outputs() local list = { "none", "bottom", "top", "front", "back", "left", "right" } if type(cee) == "table" and cee.setOutput and cee.getSignalCount then local ok, n = pcall(cee.getSignalCount) for p = 1, (ok and n or 0) do list[#list + 1] = "pin" .. p end end return list end local page = "home" local scroll = 0 local ROWS = 12 -- device rows 5..16 -- by what the device can do (works the same for a side and a pin) local function rolesOf(id) local h = getDev(id) if type(h) ~= "table" then return nil end if type(h.getConnectedName) == "function" then return nil end -- the docking port: not readable if type(h.requestFiltered) == "function" then return { "net" } end -- Stock Ticker (its list() = payments) if type(h.list) == "function" then return ROLE_FOR end return nil end -- "minecraft:chest_3" -> "Chest #3", "create:item_vault_0" -> "Item Vault #0", own names first local SIDE_SET = { top = true, bottom = true, left = true, right = true, front = true, back = true } local typeOf = {} -- id -> peripheral type, read by the work loop local function prettyName(name) local own = type(config.labels) == "table" and config.labels[name] if own and own ~= "" then return own end local base, num = name:gsub("^.*:", ""):match("^(.-)_?(%d*)$") if not base or base == "" then base = name end if SIDE_SET[name] or pinId(name) then base, num = (typeOf[name] or "device"):gsub("^.*:", "") .. " (" .. name .. ")", "" end base = base:gsub("docking_connector", "docking port"):gsub("_", " ") base = base:gsub("(%a)([%w]*)", function(a, b) return a:upper() .. b end) return base .. (num ~= "" and (" #" .. num) or "") end -- the device list and what every device holds, read in the background local holds, devs = {}, {} function readHolds(names) local out = {} for _, n in ipairs(names) do local p = getDev(n) local txt = "" if p and type(p.requestFiltered) == "function" then txt = config.net_addr ~= "" and ("to " .. config.net_addr) or "no address" elseif p and type(p.list) == "function" then local okL, l = pcall(p.list) local okS, size = pcall(p.size) local used, top, topN, by = 0, nil, 0, {} for _, it in pairs(okL and l or {}) do used = used + 1 by[it.name] = (by[it.name] or 0) + it.count if by[it.name] > topN then top, topN = it.name, by[it.name] end end txt = used == 0 and "empty" or string.format("%d/%s %s", used, okS and tostring(size) or "?", ((top or ""):gsub("^.*:", ""):gsub("_", " "))) end out[n] = txt if not typeOf[n] then local ok, t if pinId(n) then ok, t = pcall(cee.getPeripheralType, (pinId(n))) else ok, t = pcall(peripheral.getType, n) end typeOf[n] = ok and type(t) == "string" and t or nil end end holds, devs = out, names end function periphs() local list = {} for _, n in ipairs(peripheral.getNames()) do if rolesOf(n) then list[#list + 1] = n end end -- what hangs on the CEE Signal Ports if type(cee) == "table" and type(cee.getPeripherals) == "function" and type(cee.getSignalCount) == "function" then local okc, cnt = pcall(cee.getSignalCount) for p = 1, okc and cnt or 0 do local ok, l = pcall(cee.getPeripherals, p) if ok and type(l) == "table" then for i = 1, #l do local id = "pin" .. p .. (#l > 1 and ("#" .. i) or "") if rolesOf(id) then list[#list + 1] = id end end end end end table.sort(list) return list end -- ---------- drawing: rows of text + colours, then blit (no clear -> no flicker) ---------- local scr = {} local hits = {} -- clickable spots of the last draw: { y, x1, x2, fn } local overlay = {} -- UTF-8 text written over the frame (the "CC:Tweaked Unicode Support" mod) local function put(x, y, text, fg, bg) local r = scr[y] if not r then return end text = tostring(text) local w = #r.t if x > w then return end text = text:sub(1, w - x + 1) local n = #text r.t = r.t:sub(1, x - 1) .. text .. r.t:sub(x + n) r.f = r.f:sub(1, x - 1) .. string.rep(fg or "0", n) .. r.f:sub(x + n) r.b = r.b:sub(1, x - 1) .. string.rep(bg or "f", n) .. r.b:sub(x + n) return x + n end -- a button: text on a background, fn on click local function btn(x, y, text, fn, fg, bg) local e = put(x, y, text, fg or "0", bg or "7") if e and fn then hits[#hits + 1] = { y, x, e - 1, fn } end return e end -- ---------- typing at the bottom line ---------- local function ask(prompt, hidden) local _, h = term.getSize() term.setCursorPos(1, h) term.setBackgroundColor(colors.gray) term.setTextColor(colors.lightBlue) term.clearLine() term.write(prompt) term.setTextColor(colors.white) local v = read(hidden and "*" or nil) or "" term.setBackgroundColor(colors.black) term.setCursorPos(1, h) term.clearLine() return v end -- the password once (then 10 minutes without asking again) local function unlock() if lock.isOpen() then lock.lastKey = os.clock(); return true end if lock.check(ask("password: ", true)) then lock.unlocked, lock.lastKey = true, os.clock() return true end note("wrong password") return false end -- a change: only after the password local function guarded(fn) return function(...) if unlock() then fn(...) end end end local function askToken() local t = ask("token (site -> My stations): "):gsub("%s", "") if t ~= "" then config.token = t saveConfig() if net.ws then pcall(net.ws.close) end net.ws, net.connecting, net.nextTry = nil, false, 0 note("token saved - connecting") end end local function askPass() local a = ask("new password (empty = no lock): ", true) if a == ask("the same again: ", true) then lock.set(a) note(a == "" and "lock removed" or "password set") else note("the two passwords differ - nothing changed") end end -- next / previous role of a device (after the last one: no role) local function stepRole(n, dir) local opts = rolesOf(n) if not opts then return end local cur, idx = config.roles[n], 0 for i, r in ipairs(opts) do if r == cur then idx = i end end idx = (idx + dir) % (#opts + 1) local nxt = opts[idx] -- idx 0 = no role -- only one outbox / network if nxt == "outbox" or nxt == "net" then for other, r in pairs(config.roles) do if r == nxt and other ~= n then config.roles[other] = nil end end end config.roles[n] = nxt saveConfig() state.invDirty, state.holdsT = true, -10 end local function rename(n) local t = ask("name for " .. n .. ": "):gsub("^%s+", ""):gsub("%s+$", "") if type(config.labels) ~= "table" then config.labels = {} end config.labels[n] = t ~= "" and t:sub(1, 22) or nil saveConfig() end -- dock sensor / port redstone: step through the list or type it ("3" = pin3) local function stepOut(key, dir) local list = outputs() local cur = 1 for i, sd in ipairs(list) do if sd == config[key] then cur = i end end if key == "port_side" then portPower(config.port_side, false) end config[key] = list[(cur - 1 + dir) % #list + 1] saveConfig() end local function typeOut(key) local t = ask("side (left, top...) or pin number: "):gsub("%s", ""):lower() if t == "" then return end if tonumber(t) then t = "pin" .. t end for _, sd in ipairs(outputs()) do if sd == t then if key == "port_side" then portPower(config.port_side, false) end config[key] = t saveConfig() return end end note("no such side or pin: " .. t) end -- what is still missing for orders (red on the STATUS page) local function checks() local have, onPin = {}, false for id, r in pairs(config.roles) do if holds[id] then have[r] = (have[r] or 0) + 1 end if pinId(id) and r ~= "net" then onPin = true end end return { { "NEXT TO PC", not onPin }, { "TOKEN", config.token and true or false }, config.mode == "net" and { "NET", (have.net or 0) > 0 and config.net_addr ~= "" } or { "STORE", (have.store or 0) > 0 }, { "OUTBOX", have.outbox ~= nil or config.mode == "net" }, { "SENSOR", state.dockSignal ~= nil }, } end -- ---------- look: the order site's dark theme (the palette goes back on exit) ---------- -- (web.py :root) f page 7 card 1 card-hi 8 muted 0 text b accent 3 light accent 5 ok d ok chip 4 warn e bad -- splash: 6 sky a wings 2 thrust 9 box c box tape local THEME = { f = 0x000000, ["7"] = 0x181818, ["1"] = 0x2a2a2a, ["8"] = 0xa7a7a7, ["0"] = 0xffffff, b = 0x2f7bff, ["3"] = 0x5a97ff, ["5"] = 0x3ddc84, d = 0x1f9d5c, ["4"] = 0xffb340, e = 0xff6b6b, ["6"] = 0x3d7fd9, a = 0x3c6e93, ["2"] = 0xf7d3da, ["9"] = 0xc8a26a, c = 0x8a6a3a } local paletteOld = {} local function theme(on) for c, rgb in pairs(THEME) do local col = 2 ^ tonumber(c, 16) if on then paletteOld[c] = { term.getPaletteColour(col) } term.setPaletteColour(col, rgb) elseif paletteOld[c] then term.setPaletteColour(col, table.unpack(paletteOld[c])) end end end local RULE = "\140" -- teletext: a thin line through the middle of the cell local ARROW_L, ARROW_R = "\17", "\16" -- the CC font has no Cyrillic: "ั‚ะตัั‚" -> "test" (UTF-8 decoded by hand, other letters -> "?") local CYR = "a b v g d e zh z i y k l m n o p r s t u f h c ch sh sch ' y ' e yu ya" local cyr = {} for l in CYR:gmatch("%S+") do cyr[#cyr + 1] = l end local function latin(t) return (tostring(t):gsub("[\192-\247][\128-\191]*", function(ch) local b1, b2 = ch:byte(1, 2) local cp = b2 and (b1 % 32) * 64 + b2 % 64 or 0 local up = cp >= 0x410 and cp <= 0x42F local l = cyr[(cp - (up and 0x410 or 0x430)) + 1] if cp == 0x401 or cp == 0x451 then l = "e" elseif cp == 0x404 or cp == 0x454 then l = "ye" elseif cp == 0x406 or cp == 0x456 then l = "i" elseif cp == 0x407 or cp == 0x457 then l = "yi" end if not l or #ch ~= 2 then return "?" end return up and l:sub(1, 1):upper() .. l:sub(2) or l end)) end -- a coloured tag: " TEXT " local function chip(x, y, text, bg, fg) return put(x, y, " " .. text .. " ", fg or "f", bg) end -- big letters in teletext pixels: 3x5 font, every row = one octal digit (4 = left pixel) local FONT3 = { A = "25755", B = "65656", C = "34443", D = "65556", E = "74647", F = "74644", G = "34553", H = "55755", I = "72227", J = "11153", K = "55655", L = "44447", M = "57755", N = "65555", O = "25552", P = "65644", Q = "25563", R = "65655", S = "34216", T = "72222", U = "55557", V = "55552", W = "55775", X = "55255", Y = "55222", Z = "71247", ["0"] = "75557", ["1"] = "26227", ["2"] = "61247", ["3"] = "61216", ["4"] = "55711", ["5"] = "74616", ["6"] = "34656", ["7"] = "71122", ["8"] = "75757", ["9"] = "75711", [" "] = "00000", ["-"] = "00700" } -- the text in cells x.. on rows y, y+1 (6 pixel rows: 1 empty on top), as many letters as fit in wd cells local function bigText(x, y, wd, text, fg, bg) local on = {} local px = 0 for ch in text:upper():gmatch(".") do local g = FONT3[ch] or FONT3["-"] if px + 3 > wd * 2 then break end for r = 1, 5 do local bits = tonumber(g:sub(r, r)) for c = 0, 2 do if math.floor(bits / 2 ^ (2 - c)) % 2 == 1 then on[(r) * 100 + px + c] = true end end end px = px + 4 end for cy = 0, 1 do for cx = 0, wd - 1 do local bits = 0 for i = 0, 5 do if on[(cy * 3 + math.floor(i / 2)) * 100 + cx * 2 + i % 2] then bits = bits + 2 ^ i end end if bits >= 32 then put(x + cx, y + cy, string.char(128 + 63 - bits), bg, fg) -- bottom-right lit: swap else put(x + cx, y + cy, string.char(128 + bits), fg, bg) end end end end -- animations: the page slides up / down from the side of its menu item, a clicked button flashes, the -- stock bars grow when the page opens, the port meter moves smoothly; the UI ticks at 20/s while busy local anim = { slide = nil, flash = nil, pageT = 0, meter = 0 } local TAB_ORDER = { home = 0, status = 1, stock = 2, devices = 3, port = 4 } local function ease(u) return 1 - (1 - math.min(1, u)) ^ 3 end function anim.busy() return anim.slide or anim.flash or os.clock() - anim.pageT < 0.6 or state.job or os.clock() - (state.msgT or -9) < 1 or math.abs(anim.meter - (state.dockSignal or 0)) > 0.2 end -- a number counting up from 0 when the page opens local function countUp(n) return math.floor(n * ease((os.clock() - anim.pageT) / 0.5) + 0.5) end -- the newest event types itself out local function typed(text) return text:sub(1, math.floor((os.clock() - (state.msgT or -9)) * 60) + 9) end local SPIN = { "\24", "\26", "\25", "\27" } local function goPage(to) if to ~= page then local old = {} for y, r in pairs(scr) do old[y] = r end anim.slide = { rows = old, dir = TAB_ORDER[to] > TAB_ORDER[page] and 1 or -1, t0 = os.clock() } anim.pageT = os.clock() end page, scroll = to, 0 end -- the station name: real letters with the unicode mod (not while a page slides), else in latin local function nameAt(x, y, fg, bg) local n = state.name or "Station" if type(unicode) == "table" and unicode.len and not anim.slide and n:find("[\128-\255]") then local len = unicode.len(n) overlay[#overlay + 1] = { x, y, n, fg, bg or "f" } return put(x, y, string.rep(" ", len), fg, bg) end return put(x, y, latin(n), fg, bg) end -- ---------- layout: a home screen of tiles; a tile opens its page, the bar on top goes back ---------- local X0 = 2 -- the pages start here local function lockTag() if not config.pw_hash then return "no password", "4" end return lock.isOpen() and "unlocked" or "locked", lock.isOpen() and "5" or "e" end -- rounded corners: teletext cells with one corner pixel in the colour under the box local function round(x, y, wd, ht, col, under) under = under or "f" put(x, y, "\129", under, col); put(x + wd - 1, y, "\130", under, col) put(x, y + ht - 1, "\144", under, col); put(x + wd - 1, y + ht - 1, "\159", col, under) end -- a one-row button with round ends (the ends sit outside x..x2) local function pill(x, y, text, fn, fg, bg) put(x - 1, y, "\149", "f", bg) local x2 = btn(x, y, text, fn, fg, bg) put(x2, y, "\149", bg, "f") if fn then hits[#hits][5] = { x - 1, y, x2, y } end return x2 + 1 end -- a tile: icon + name, a value with a dot, a grey detail; a click anywhere on it runs fn local function tile(x, y, wd, icon, label, value, col, detail, fn) for r = 0, 4 do put(x, y + r, string.rep(" ", wd), "0", "7") hits[#hits + 1] = { y + r, x, x + wd - 1, fn, { x, y, x + wd - 1, y + 4 } } end round(x, y, wd, 5, "7") put(x + 2, y + 1, icon, "3", "7"); put(x + 4, y + 1, label, "0", "7") put(x + 2, y + 2, "\7", col, "7"); put(x + 4, y + 2, value:sub(1, wd - 5), "0", "7") put(x + 2, y + 3, detail:sub(1, wd - 3), "8", "7") end local function drawHome(w, h) put(2, 1, "\4", "3") nameAt(4, 1, "0") local online = state.net == "online" local right = (state.kind or "not linked") .. " " .. (online and "online" or "offline") put(w - #right, 1, right, "8") put(w - #right - 2, 1, "\7", online and (math.floor(os.clock() * 2) % 2 == 0 and "5" or "d") or "e") -- pulse local bad = false for _, c in ipairs(checks()) do bad = bad or not c[2] end local j, sv, sc, sd = state.job, "running", "5", "no order" if bad then sv, sc = "needs setup", "e" elseif not online then sv, sc = state.net, "4" end if j then local total = 0 for _, w in pairs(j.want or {}) do total = total + (w.total or 0) end sd = ("order #%s %d/%d"):format(j.order, j.sent, total) end local kinds, items = 0, 0 for _, e in ipairs(state.inv) do kinds, items = kinds + 1, items + e.count end local nS, nO = 0, 0 for _, n in ipairs(devs) do if config.roles[n] == (config.mode == "net" and "net" or "store") then nS = nS + 1 elseif config.roles[n] == "outbox" then nO = nO + 1 end end local pv, pc = "free", "0" if state.dockSignal == nil then pv, pc = "no sensor", "e" elseif state.docked then pv, pc = "docked", "5" end local lt, lc = lockTag() local W = math.floor((w - 5) / 3) local T = { { "\16", "Status", sv, sc, sd, function() goPage("status") end }, { "\4", "Stock", countUp(kinds) .. " kinds", kinds > 0 and "5" or "8", countUp(items) .. " items", function() goPage("stock") end }, { "\8", "Devices", countUp(#devs) .. " storages", (nS > 0 and (nO == 1 or config.mode == "net")) and "5" or "e", (config.mode == "net" and "network " or (nS .. " store ")) .. nO .. " outbox", function() goPage("devices") end }, { "\9", "Port", pv, pc, "power: " .. config.port_side, function() goPage("port") end }, { "\7", "Password", lt == "no password" and "not set" or lt, lc, "click to set", guarded(askPass) }, { "\7", "Token", config.token and "set" or "not set", config.token and "5" or "e", "click to set", guarded(askToken) }, } for i, t in ipairs(T) do if os.clock() - anim.pageT >= (i - 1) * 0.05 then -- the tiles come in one by one tile(2 + ((i - 1) % 3) * (W + 1), 3 + math.floor((i - 1) / 3) * 6, W, t[1], t[2], t[3], t[4], t[5], t[6]) end end if state.job then -- an order is loading: the status dot spins put(4, 5, SPIN[math.floor(os.clock() * 8) % 4 + 1], "4", "7") end put(2, 15, "Activity", "3") for i = 1, math.min(#state.log, h - 16) do put(2, 15 + i, "\7 ", "3") put(4, 15 + i, (i == 1 and typed(state.log[i]) or state.log[i]):sub(1, w - 4), i == 1 and "0" or "8") end if not state.log[1] then put(2, 16, "no events yet", "8") end pill(w - 6, h, " Exit ", guarded(function() running = false end), "e", "7") end -- the bar on top of a page: back home, the page name, the lock local function navBar(w) pill(3, 1, "\17 Home", function() goPage("home") end, "0", "b") local name = " " .. page:sub(1, 1):upper() .. page:sub(2) .. " " pill(math.floor((w - #name) / 2) + 1, 1, name, nil, "0", "1") -- the page name, centred local lt, lc = lockTag() put(w - #lt - 2, 1, "\7", lc); put(w - #lt, 1, lt, "8") end -- a grey panel with round corners local function panel(x, y, wd, ht) for r = 0, ht - 1 do put(x, y + r, string.rep(" ", wd), "0", "7") end round(x, y, wd, ht, "7") end -- a small card: label, value with a dot, detail, maybe a bar (0..1) local function card(x, y, wd, label, value, col, detail, bar) panel(x, y, wd, 5) put(x + 2, y + 1, label, "8", "7") put(x + 2, y + 2, "\7", col, "7"); put(x + 4, y + 2, value:sub(1, wd - 5), "0", "7") if detail then put(x + 2, y + 3, detail:sub(1, wd - 3), "8", "7") end if bar then local n = math.floor((wd - 4) * math.min(1, bar) + 0.5) put(x + 2, y + 4, string.rep(RULE, n), col, "7") put(x + 2 + n, y + 4, string.rep(RULE, wd - 4 - n), "1", "7") end end local function setupLine(x, y, skip, bg) local bad = false for _, c in ipairs(checks()) do if not (skip and skip[c[1]]) then put(x, y, "\7", c[2] and "5" or "e", bg) x = put(x + 1, y, (c[1] == "NEXT TO PC" and "PC" or c[1]), c[2] and "0" or "e", bg) + 2 if not c[2] then bad = true end end end return x, bad end -- page up / down for a list, on the right of row y local function pager(w, y, n, rows, onPage) if n <= rows then return end local txt = string.format("%d-%d of %d", scroll + 1, math.min(n, scroll + rows), n) put(w - 12 - #txt, y, txt, "8") pill(w - 9, y, " \30 ", function() scroll = math.max(0, scroll - rows) end, "0", "7") pill(w - 4, y, " \31 ", function() scroll = math.min(n - rows, scroll + rows) end, "0", "7") end local function drawStatus(w, h) local online = state.net == "online" local W = math.floor((w - 5) / 3) panel(2, 11, w - 2, 3) put(4, 12, "Setup", "8", "7") local _, bad = setupLine(11, 12, nil, "7") if bad then put(2, 3, "\7", "e"); put(4, 3, "Needs setup: the red ones below", "0") elseif not online then put(2, 3, "\7", "4"); put(4, 3, "Not connected: " .. state.net, "0") else put(2, 3, "\7", "5"); put(4, 3, "Everything is running", "0") end put(nameAt(4, 4, "8"), 4, " v " .. tostring(state.ver):sub(1, 8), "8") card(2, 5, W, "SERVER", online and "online" or "offline", online and "5" or "e", state.kind or "not linked") if online then put(4, 7, "\7", math.floor(os.clock() * 2) % 2 == 0 and "5" or "d", "7") end -- pulse if state.dockSignal == nil then card(3 + W, 5, W, "PORT", "no sensor", "e", "set it: Port") elseif state.docked then card(3 + W, 5, W, "PORT", "docked", "5", "sensor 15") else card(3 + W, 5, W, "PORT", "free", "0", "sensor " .. state.dockSignal) end local j = state.job if j then local total = 0 for _, w in pairs(j.want or {}) do total = total + (w.total or 0) end card(4 + 2 * W, 5, W, "ORDER", "#" .. j.order, "4", j.sent .. " / " .. total, total > 0 and j.sent / total or 0) else card(4 + 2 * W, 5, W, "ORDER", "none", "8", "waiting") end panel(2, 15, w - 2, h - 15) put(4, 15, "Activity", "8", "7") if not config.pw_hash then put(w - 22, 15, "! no password set", "4", "7") end if not state.log[1] then put(4, 16, "no events yet", "8", "7") end for i = 1, math.min(#state.log, h - 17) do put(4, 15 + i, "\7", i == 1 and "3" or "1", "7") put(6, 15 + i, (i == 1 and typed(state.log[i]) or state.log[i]):sub(1, w - 8), i == 1 and "0" or "8", "7") end end -- every kind in the STOREs, the biggest first, a bar by amount local function drawStock(w, h) local inv = {} local total = 0 for _, e in ipairs(state.inv) do inv[#inv + 1] = e; total = total + e.count end table.sort(inv, function(a, b) return a.count > b.count end) put(2, 3, #inv .. " kinds", "0"); put(4 + #tostring(#inv) + 5, 3, total .. " items", "8") local rows = h - 7 scroll = math.max(0, math.min(scroll, #inv - rows)) pager(w, 3, #inv, rows) panel(2, 5, w - 2, h - 5) local top = inv[1] and inv[1].count or 1 if not inv[1] then put(4, 6, "nothing in the STOREs", "8", "7") end local grow = ease((os.clock() - anim.pageT) / 0.5) for i = 1, rows do local e, y = inv[i + scroll], 5 + i if e then put(4, y, tostring(e.label):sub(1, 24), "0", "7") local n = math.max(1, math.floor(e.count / top * 12 * grow + 0.5)) put(29, y, string.rep(RULE, n), "3", "7") put(29 + n, y, string.rep(RULE, 12 - n), "1", "7") local num = tostring(countUp(e.count)) put(w - 2 - #num, y, num, "0", "7") end end end local function drawDevices(w, h) local x = setupLine(2, 3, { TOKEN = true, SENSOR = true }) local net = config.mode == "net" x = pill(x + 1, 3, net and "NETWORK" or "STORAGE", guarded(function() config.mode = net and "store" or "net" saveConfig() state.invDirty = true end), "f", net and "3" or "5") if net then btn(x + 1, 3, (" to: " .. (config.net_addr ~= "" and config.net_addr or "?")):sub(1, w - x - 1) .. " ", guarded(function() local a = ask("address of the packager at the OUTBOX: "):gsub("^%s+", ""):gsub("%s+$", "") if a ~= "" then config.net_addr = a; saveConfig(); state.invDirty = true end end), config.net_addr ~= "" and "0" or "e", "1") end local rows = h - 7 scroll = math.max(0, math.min(scroll, #devs - rows)) put(2, 4, ARROW_L .. ARROW_R .. " role click a name to rename", "8") pager(w, 4, #devs, rows) panel(2, 5, w - 2, h - 5) if #devs == 0 then put(4, 6, "no storages next to the computer", "e", "7") end for i = 1, rows do local n, y = devs[i + scroll], 5 + i if n then local r = config.roles[n] btn(4, y, ARROW_L, guarded(function() stepRole(n, -1) end), "0", "1") btn(5, y, string.format(" %-7s", r and ROLE_LABEL[r] or "-"), guarded(function() stepRole(n, 1) end), r and "f" or "8", r and ROLE_COL[r] or "1") btn(13, y, ARROW_R, guarded(function() stepRole(n, 1) end), "0", "1") btn(15, y, string.format("%-16s", prettyName(n):sub(1, 16)), guarded(function() rename(n) end), "0", "7") if pinId(n) and r ~= "net" then put(32, y, "PIN: move to PC", "e", "7") -- items do not move there else put(32, y, (holds[n] or "..."):sub(1, w - 34), "8", "7") end end end end -- < value >: arrows step, a click on the value = type it local function outLine(x, y, key) btn(x, y, " " .. ARROW_L .. " ", guarded(function() stepOut(key, -1) end), "0", "1") btn(x + 3, y, string.format(" %-8s ", config[key]), guarded(function() typeOut(key) end), "0", "f") btn(x + 13, y, " " .. ARROW_R .. " ", guarded(function() stepOut(key, 1) end), "0", "1") end local function drawPort(w, h) put(2, 3, "click a value to type it (3 = pin3)", "8") panel(2, 5, w - 2, 4) put(4, 6, "Dock sensor", "0", "7"); put(17, 6, "comparator at the port, 15 = docked", "8", "7") outLine(4, 7, "dock_sensor") local v = state.dockSignal if v == nil then put(22, 7, "not set", "e", "7") else anim.meter = anim.meter + (v - anim.meter) * 0.35 local m = math.floor(anim.meter + 0.5) put(22, 7, string.rep(RULE, m), state.docked and "5" or "3", "7") put(22 + m, 7, string.rep(RULE, 15 - m), "1", "7") put(39, 7, state.docked and "DOCKED" or ("now " .. v), state.docked and "5" or "0", "7") end panel(2, 10, w - 2, 4) put(4, 11, "Port power", "0", "7"); put(17, 11, "redstone that keeps the port on", "8", "7") outLine(4, 12, "port_side") local off = os.clock() < (state.portOffUntil or 0) btn(22, 12, off and " off... " or " Test ", config.port_side ~= "none" and guarded(function() state.portOffUntil = os.clock() + 3 end) or nil, "0", off and "e" or "b") put(31, 12, "off for 3 s", "8", "7") panel(2, 15, w - 2, h - 15) local x = put(4, 15, "STORE", "5", "7") x = put(x, 15, " " .. ARROW_R .. " PC " .. ARROW_R .. " ", "8", "7") x = put(x, 15, "OUTBOX", "4", "7") put(x, 15, " " .. ARROW_R .. " hopper " .. ARROW_R .. " port", "8", "7") put(4, 16, "comparator at the port " .. ARROW_R .. " dock sensor", "8", "7") put(4, 17, "received: funnels at the port " .. ARROW_R .. " a STORE", "8", "7") put(4, 18, "storages right against the PC, drone nose WEST", "8", "7") end local PRESS = { ["7"] = "1", ["1"] = "8", f = "1", b = "3" } local function draw() local w, h = term.getSize() for y = 1, h do scr[y] = { t = string.rep(" ", w), f = string.rep("0", w), b = string.rep("f", w) } end hits, overlay = {}, {} if page == "home" then drawHome(w, h) elseif page == "devices" then drawDevices(w, h) elseif page == "port" then drawPort(w, h) elseif page == "stock" then drawStock(w, h) else drawStatus(w, h) end if page ~= "home" then navBar(w) end -- slides with the page if state.msg ~= "" and os.clock() - (state.msgT or 0) < 10 then put(X0 - 1, h, " " .. state.msg .. string.rep(" ", w), "4", "7") end local sl = anim.slide if sl and os.clock() - sl.t0 >= 0.25 then anim.slide, sl = nil, nil end if sl then -- the page part moves up (next item below) or down: the new page pushes the old one out local s = math.floor(h * ease((os.clock() - sl.t0) / 0.25) + 0.5) local new = {} for y = 1, h do new[y] = scr[y] end for y = 1, h do local src = sl.dir > 0 and y + s or y - s local r if src >= 1 and src <= h then r = sl.rows[src] else r = new[src > h and src - h or src + h] end if r then local n = new[y] scr[y] = r end end end local fl = anim.flash if fl and not anim.slide and os.clock() - fl.t0 < 0.2 then -- pressed: one shade lighter local x1, y1, x2, y2 = fl[1], fl[2], fl[3], fl[4] for y = y1, y2 do local r = scr[y] r.f = r.f:sub(1, x1 - 1) .. r.f:sub(x1, x2):gsub("[71b]", PRESS) .. r.f:sub(x2 + 1) r.b = r.b:sub(1, x1 - 1) .. r.b:sub(x1, x2):gsub("[71fb]", PRESS) .. r.b:sub(x2 + 1) end else anim.flash = nil end for y = 1, h do term.setCursorPos(1, y) term.blit(scr[y].t, scr[y].f, scr[y].b) end for _, o in ipairs(overlay) do term.setCursorPos(o[1], o[2]) term.setTextColour(2 ^ tonumber(o[4], 16)); term.setBackgroundColour(2 ^ tonumber(o[5], 16)) term.write(o[3]) end end -- ---------- idle splash: the drone over the station drops a box onto the port ---------- -- drawn in 2x3 teletext pixels (like the drone's lock screen); any click / key hides it local SPL = { IDLE = 30, -- s without a click or key SPRITE = { -- the drone from the front (same as delivery.lua K.SPRITE) ".........WWWWWWWWWWWW.........", ".........WKKWWWWWWKKW.........", ".........WKKWWWWWWKKW.........", "..BBBBBBBWWWWKKKKWWWWBBBBBBB..", "BBBBBBBBBWWWWKKKKWWWWBBBBBBBBB", "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", "BBBBBBBBB............BBBBBBBBB", "..WWWWWW..............WWWWWW..", "....PP..PP..........PP..PP....", ".....P..P............P..P.....", }, COL = { W = "0", K = "f", B = "a", P = "2" }, FONT = { -- 5x7 letters of the title D = { "11110", "10001", "10001", "10001", "10001", "10001", "11110" }, R = { "11110", "10001", "10001", "11110", "10100", "10010", "10001" }, O = { "01110", "10001", "10001", "10001", "10001", "10001", "01110" }, N = { "10001", "11001", "10101", "10011", "10001", "10001", "10001" }, E = { "11111", "10000", "10000", "11110", "10000", "10000", "11111" }, L = { "10000", "10000", "10000", "10000", "10000", "10000", "11111" }, I = { "111", "010", "010", "010", "010", "010", "111" }, V = { "10001", "10001", "10001", "10001", "10001", "01010", "00100" }, Y = { "10001", "10001", "01010", "00100", "00100", "00100", "00100" }, [" "] = { "000", "000", "000", "000", "000", "000", "000" }, }, } local function drawSplash(t) local w, h = term.getSize() local pw, ph = w * 2, h * 3 local px = {} local function rect(x0, y0, wd, ht, c) for y = y0, y0 + ht - 1 do for x = x0, x0 + wd - 1 do if x >= 0 and x < pw and y >= 0 and y < ph then px[y * pw + x] = c end end end end -- title local title, tw = "DRONE DELIVERY", -1 for i = 1, #title do tw = tw + #SPL.FONT[title:sub(i, i)][1] + 1 end local tx = math.floor((pw - tw) / 2) for i = 1, #title do local g = SPL.FONT[title:sub(i, i)] for gy = 1, 7 do for gx = 1, #g[gy] do if g[gy]:sub(gx, gx) == "1" then px[(5 + gy) * pw + tx + gx - 1] = "0" end end end tx = tx + #g[1] + 1 end -- the station: grass, a building with lit windows and a door, crates, an antenna with a blinking -- light, the landing pad on the roof with edge lights and the port (green while the box lands) local p = t % 3.2 local sy, mid = ph - 14, math.floor(pw / 4) * 2 -- even: whole cells, no 3-colour clashes local blink = math.floor(t * 2) % 2 == 0 rect(0, ph - 2, pw, 2, "d") rect(mid - 17, sy + 2, 34, ph - sy - 4, "1") for wx = mid - 14, mid + 11, 5 do if wx < mid - 3 or wx > mid + 1 then rect(wx, sy + 4, 3, 2, (wx + math.floor(t)) % 3 == 0 and "4" or "3") end end rect(mid - 2, ph - 8, 4, 6, "f") rect(mid + 20, ph - 7, 5, 5, "9"); rect(mid + 20, ph - 5, 5, 1, "c") rect(mid + 26, ph - 6, 4, 4, "9"); rect(mid + 26, ph - 4, 4, 1, "c") rect(mid + 22, ph - 11, 4, 4, "9"); rect(mid + 22, ph - 9, 4, 1, "c") rect(mid - 15, sy - 7, 1, 7, "8") rect(mid - 16, sy - 8, 3, 1, blink and "e" or "1") rect(mid - 21, sy, 42, 2, "8") for _, x in ipairs({ mid - 21, mid - 13, mid + 11, mid + 19 }) do rect(x, sy, 2, 1, blink and "4" or "0") end rect(mid - 6, sy - 2, 10, 2, "7") rect(mid - 4, sy - 2, 6, 1, (p > 1.4 and p < 2.2) and "5" or "b") -- the drone, bobbing a little local dy = 18 + math.floor(math.sin(t * 3) + 0.5) for ry, row in ipairs(SPL.SPRITE) do for rx = 1, #row do local c = SPL.COL[row:sub(rx, rx)] if c then px[(dy + ry - 1) * pw + mid - 16 + rx - 1] = c end end end -- the box: under the drone, falls, sits on the port, gone local top, land = dy + 9, sy - 7 local by = nil if p < 0.6 then by = top elseif p < 1.4 then by = top + (land - top) * ((p - 0.6) / 0.8) ^ 2 elseif p < 2.2 then by = land end if by then rect(mid - 4, math.floor(by), 6, 5, "9") end -- pixels -> 2x3 characters: background = the bottom-right pixel, the rest in the most common other colour for cy = 0, h - 1 do local chars, fg, bg = {}, {}, {} for cx = 0, w - 1 do local cell, cnt, best, n = {}, {}, nil, 0 for i = 0, 5 do cell[i] = px[(cy * 3 + math.floor(i / 2)) * pw + cx * 2 + i % 2] or "6" end local b = cell[5] for i = 0, 4 do if cell[i] ~= b then cnt[cell[i]] = (cnt[cell[i]] or 0) + 1 if cnt[cell[i]] > n then best, n = cell[i], cnt[cell[i]] end end end local bits = 0 for i = 0, 4 do if best and cell[i] == best then bits = bits + 2 ^ i end end chars[#chars + 1], fg[#fg + 1], bg[#bg + 1] = string.char(128 + bits), best or b, b end term.setCursorPos(1, cy + 1) term.blit(table.concat(chars), table.concat(fg), table.concat(bg)) end end local function click(x, y) for _, b in ipairs(hits) do if y == b[1] and x >= b[2] and x <= b[3] then anim.flash = b[5] or { b[2], y, b[3], y } anim.flash.t0 = os.clock() draw() -- pressed for a moment, then it acts sleep(0.12) b[4]() return end end end local function uiLoop() draw() local tmr = os.startTimer(0.5) local idle, splash = os.clock(), false while running do local ev, a, b, c = os.pullEventRaw() if ev == "mouse_click" or ev == "monitor_touch" or ev == "key" or ev == "char" or ev == "terminate" then idle = os.clock() if splash then -- the first click / key only hides the splash splash = false draw() ev = nil end end if ev == "terminate" then -- Ctrl+T: only with the password if config.pw_hash and lock.check(ask("password to leave: ", true)) then running = false else note(config.pw_hash and "wrong password" or "Ctrl+T: set a password ([PASS]) to leave") end draw() elseif ev == "mouse_click" or ev == "monitor_touch" then click(b, c) draw() tmr = os.startTimer(0.05) elseif ev == "timer" and a == tmr then splash = os.clock() - idle > SPL.IDLE tmr = os.startTimer((splash and 0.1) or (anim.busy() and 0.05) or 0.5) if config.pw_hash and lock.unlocked and os.clock() - lock.lastKey > 600 then lock.unlocked = false end if splash then drawSplash(os.clock()) else draw() end elseif ev == "peripheral" or ev == "peripheral_detach" then state.holdsT = -10 if not splash then draw() end end end end -- offline test hook (never set in game) if STATION_TEST then return { config = config, state = state, workTick = workTick, handle = handle, jobStart = jobStart, stock = stock, click = click, draw = draw, readHolds = function() readHolds(periphs()) end, lock = lock, update = update, drawSplash = drawSplash } end -- Ctrl+T reaches the loops as an event; no disk startup; after a reboot it starts by itself local pullEvent0 = os.pullEvent os.pullEvent = os.pullEventRaw pcall(settings.set, "shell.allow_disk_startup", false) pcall(settings.save) if not fs.exists("startup.lua") and not fs.exists("startup") then local f = fs.open("startup.lua", "w") if f then f.write([[-- Drone Delivery station: start after a reboot if not shell.run("station") and fs.exists("station_prev.lua") then print("station.lua failed - starting the previous version") shell.run("station_prev") end ]]) f.close() end end theme(true) parallel.waitForAny(uiLoop, workLoop, netLoop) theme(false) os.pullEvent = pullEvent0 if net.ws then pcall(net.ws.close) end term.setBackgroundColor(colors.black) term.setTextColor(colors.white) term.clear() term.setCursorPos(1, 1) print("Station stopped. Settings are in " .. CONFIG_FILE .. ".")