-- TurtleDeck installer local f = fs.open("/turtledeck.lua", "w") f.write([=[ -- TurtleDeck client for CC:Tweaked turtles. -- -- turtledeck connect (asks for the link key the first time) -- turtledeck [world] connect with / replace the saved link key (and name the world) -- turtledeck setpos x y z f set position by hand (f = north|east|south|west) -- turtledeck world name the world/dimension this turtle maps into -- turtledeck autoupdate on|off check the website for a newer version on start (default on) -- turtledeck startup on|off start TurtleDeck when the turtle boots (default on) -- turtledeck reset forget the saved key and position -- -- Every movement made through the `turtle` API while this runs (from the -- website or from your own programs started by it) is tracked, and the blocks -- around the turtle are reported to your TurtleDeck account. local RELAY_URL = "wss://lionfish-app-i8kz6.ondigitalocean.app" local SITE_URL = "https://turtledeck.thultz.dev" local VERSION = "1.21.0" -- Top-level helper functions live in this table instead of being locals: CC:Tweaked's Lua counts every local in scope -- (enclosing functions included) towards a limit of 200, and this file has more helpers than that leaves room for. local F = {} local CONFIG_PATH = "/.turtledeck" local SITES_PATH = "/.turtledeck_sites" -- how far each mine / hole has been dug, so a repeat run continues instead of redoing it if not turtle then error("TurtleDeck must run on a turtle", 0) end if not http or not http.websocket then error("The HTTP/WebSocket API is disabled in the CC:Tweaked server config", 0) end ---------------------------------------------------------------- config local cfg = {} if fs.exists(CONFIG_PATH) then local f = fs.open(CONFIG_PATH, "r") cfg = textutils.unserialize(f.readAll() or "") or {} f.close() end function F.saveConfig() local f = fs.open(CONFIG_PATH, "w") f.write(textutils.serialize(cfg)) f.close() end local FACINGS = { north = 0, east = 1, south = 2, west = 3 } local FACING_NAMES = { [0] = "north", "east", "south", "west" } -- facing -> dx, dz (Minecraft: north is -z, east is +x) local DX = { [0] = 0, 1, 0, -1 } local DZ = { [0] = -1, 0, 1, 0 } local args = { ... } if args[1] == "reset" then fs.delete(CONFIG_PATH) print("TurtleDeck config cleared.") return elseif args[1] == "setpos" then local x, y, z = tonumber(args[2]), tonumber(args[3]), tonumber(args[4]) local f = FACINGS[args[5] or ""] if not (x and y and z and f) then error("usage: turtledeck setpos ", 0) end cfg.x, cfg.y, cfg.z, cfg.facing, cfg.located = x, y, z, f, "manual" F.saveConfig() print("Position saved.") return elseif args[1] == "world" then if not args[2] then error("usage: turtledeck world ", 0) end cfg.world = args[2] F.saveConfig() print("World set to " .. args[2]) return elseif args[1] == "startup" then if args[2] ~= "on" and args[2] ~= "off" then error("usage: turtledeck startup on|off", 0) end local ok, err = F.setStartup(args[2] == "on") if not ok then error("Could not change startup: " .. tostring(err), 0) end cfg.startup = args[2] == "on" F.saveConfig() print("Start on boot " .. args[2]) return elseif args[1] == "autoupdate" then if args[2] ~= "on" and args[2] ~= "off" then error("usage: turtledeck autoupdate on|off", 0) end cfg.autoupdate = args[2] == "on" F.saveConfig() print("Auto-update " .. args[2]) return elseif args[1] then cfg.key = args[1] if args[2] then cfg.world, cfg.worldManual = args[2], true end F.saveConfig() end -- World name: set by hand, else read from an Advanced Peripherals environment detector if one is attached. function F.cleanWorld(name) name = tostring(name or ""):gsub("[^%w_:%-%.]", ""):sub(1, 64) return name ~= "" and name or nil end if not cfg.worldManual and peripheral and peripheral.find then local det = peripheral.find("environmentDetector") if det and det.getDimension then local ok, dim = pcall(det.getDimension) if ok and F.cleanWorld(dim) and cfg.world ~= F.cleanWorld(dim) then cfg.world = F.cleanWorld(dim) F.saveConfig() end end end local STARTUP_PATH = "/startup/99_turtledeck.lua" --- CC runs every file in /startup on boot, alongside any startup.lua the owner already has. function F.setStartup(on) if not (shell and fs.makeDir and fs.isDir) then return false, "not available" end if not on then if fs.exists(STARTUP_PATH) then fs.delete(STARTUP_PATH) end return true end if fs.exists("/startup") and not fs.isDir("/startup") then return false, "/startup is a file; rename it to /startup.lua first" end fs.makeDir("/startup") local f = fs.open(STARTUP_PATH, "w") f.write(('shell.run(%q)\n'):format("/" .. shell.getRunningProgram())) f.close() return true end --- Fetch the website's current version and write it over this file. Returns "updated", "current", or nil + why. function F.installLatest() if SITE_URL:sub(1, 2) == "__" or not shell then return nil, "this copy was not installed from a website" end local res = http.get(SITE_URL .. "/install.lua?raw=1") if not res then return nil, "could not reach " .. SITE_URL end local latest = res.readAll() res.close() -- Only accept something that is plausibly this program and actually compiles. if not latest or #latest < 1000 or not latest:find("TurtleDeck client", 1, true) or not load(latest, "=update") then return nil, "the website did not return a valid program" end local path = shell.getRunningProgram() local f = fs.open(path, "r") local current = f.readAll() f.close() if current == latest then return "current" end f = fs.open(path, "w") f.write(latest) f.close() _G.__turtledeck_updated = true -- never loop, even if the comparison is off by a byte return "updated" end --- Replace this file with the website's current version if it differs, then restart once. function F.autoUpdate() if cfg.autoupdate == false or _G.__turtledeck_updated then return false end if F.installLatest() ~= "updated" then return false end local path = shell.getRunningProgram() print("TurtleDeck updated, restarting...") shell.run(path, table.unpack(args)) return true end if F.autoUpdate() then return end -- A turtle that stays offline after every server restart is no use to a swarm: start on boot unless told not to. if cfg.startup == nil then cfg.startup = F.setStartup(true) and true or false F.saveConfig() if cfg.startup then print("TurtleDeck will start when this turtle boots.") print("(turtledeck startup off to disable)") end end if cfg.relay then RELAY_URL = cfg.relay end -- optional override in /.turtledeck if not cfg.key then print("Enter your TurtleDeck link key") print("(website > Link key; Ctrl+V pastes):") write("> ") cfg.key = read() F.saveConfig() end ---------------------------------------------------------------- tracked state -- Keep the untracked originals exactly once, even if we are restarted. local native = _G.__turtledeck_native if not native then native = {} for k, v in pairs(turtle) do native[k] = v end _G.__turtledeck_native = native end local pos = { x = cfg.x or 0, y = cfg.y or 0, z = cfg.z or 0 } local facing = cfg.facing or 0 local located = cfg.located or "relative" local ws = nil local relayRoutes = false -- the relay plans routes over the account's map (it said so in its welcome, 1.19.1+) local routeWaiting, routeAnswer = nil, nil -- the route request td.goTo waits for, and its answer -- Shared chest queues (1.19.3+, the welcome says `depotQueue`): the relay decides who uses a shared chest when, so turtles -- never crowd one. depotState.ticket: the turn this turtle asked for ({ id, kind, solo, held }), said again after a reconnect; -- depotState.answers: the relay's latest word per ticket (go, wait here, out of the queue). local depotState = { queue = false, ticket = nil, answers = {} } -- queue: the relay runs depot queues -- Reports the link wants sent (after a reconnect, when the inventory changes). The chores coroutine sends them, so the -- reader never makes a turtle call: CC hands the events that arrive while one waits for its answer to no one. local chores = { look = false, state = false, force = false } function F.chore(look, force) if look then chores.look = true end if force then chores.force = true end chores.state = true os.queueEvent("turtledeck_chore") end local pendingBlocks = {} local lastInvSig = nil local busyNative = false -- true while a native turtle call is in flight function F.savePosition() cfg.x, cfg.y, cfg.z, cfg.facing, cfg.located = pos.x, pos.y, pos.z, facing, located F.saveConfig() end -- While the relay is away (a restart, a deploy, a network blip) the turtle keeps working and keeps what it has to say -- in an outbox, sent when it is back. Reports that matter (a program's end, command results, progress) are numbered -- (`seq`) and kept until the relay acknowledges them, so a relay restart neither loses nor repeats them. Map reports -- are merged; dig events, monitor frames and progress queries are only worth anything live and are dropped. local RELIABLE = { run = true, result = true, progress = true, site = true, need = true, build_wait = true, depot_leave = true } local LIVE_ONLY = { dig = true, monitor = true, site_get = true, route = true, depot_enter = true } local OUTBOX_MAX, STATE_BLOCKS_MAX, FRAME_MAX = 300, 800, 60000 local outbox, unacked, seq = {}, {}, 0 local relayAcks = false -- this relay acknowledges numbered reports (it said so in its welcome) local SESSION = ("%d-%.0f-%d"):format(os.getComputerID and os.getComputerID() or 0, os.epoch and os.epoch("utc") or 0, math.random(1, 999999)) function F.encode(msg) local ok, data = pcall(textutils.serializeJSON, msg) if ok then return data end end function F.rawSend(data) if not ws or not data then return false end return pcall(ws.send, data) end --- Keep a message for later. State reports merge into the newest waiting one (newest position, every block seen). local function keep(msg) if msg.t == "state" then for i = #outbox, 1, -1 do local m = outbox[i] if m.t == "state" then if #(m.blocks or {}) + #(msg.blocks or {}) > STATE_BLOCKS_MAX then break end if msg.blocks then m.blocks = m.blocks or {} for _, b in ipairs(msg.blocks) do m.blocks[#m.blocks + 1] = b end end m.state, m.label, m.world = msg.state, msg.label, msg.world if msg.inventory then m.inventory, m.upgrades = msg.inventory, msg.upgrades end return end end end outbox[#outbox + 1] = msg while #outbox > OUTBOX_MAX do -- Full: log lines and map reports go first, the oldest first; numbered reports only when nothing else is left. local drop = 1 for i, m in ipairs(outbox) do if not RELIABLE[m.t] then drop = i break end end table.remove(outbox, drop) end end function F.sendMsg(msg) if RELIABLE[msg.t] and not msg.seq then seq = seq + 1 msg.seq = seq end local data = F.encode(msg) if not data then return false end -- cannot be sent at all (a value JSON cannot hold) if ws and #outbox == 0 and F.rawSend(data) then if msg.seq and relayAcks then unacked[#unacked + 1] = msg if #unacked > OUTBOX_MAX then table.remove(unacked, 1) end end return true end if not LIVE_ONLY[msg.t] then keep(msg) end return false end --- After a reconnect: everything kept (and everything sent but never acknowledged) goes out, in order, in batches. --- The relay says in its welcome which numbered reports it already has (it handled them before a restart). function F.flushOutbox(relaySeq) for i = #unacked, 1, -1 do table.insert(outbox, 1, unacked[i]) end unacked = {} local list = {} for _, m in ipairs(outbox) do if not (m.seq and relaySeq and m.seq <= relaySeq) then list[#list + 1] = m end end outbox = {} if not relayAcks then -- An older relay: no batches, no acks; it allows bursts of about 120 messages. for i = 1, math.min(#list, 100) do F.rawSend(F.encode(list[i])) end return end local i = 1 while i <= #list do local parts, size, from = {}, 0, i while i <= #list and #parts < 50 do local data = F.encode(list[i]) or "{}" if #parts > 0 and size + #data > FRAME_MAX then break end parts[#parts + 1], size, i = data, size + #data + 1, i + 1 end if not F.rawSend('{"t":"batch","list":[' .. table.concat(parts, ",") .. "]}") then for j = from, #list do outbox[#outbox + 1] = list[j] end -- gone again: keep the rest for next time return end for j = from, i - 1 do if list[j].seq then unacked[#unacked + 1] = list[j] end end end end function F.acked(n) n = tonumber(n) if not n then return end while unacked[1] and unacked[1].seq <= n do table.remove(unacked, 1) end end -- Advanced (gold) turtles have a colour terminal; normal ones do not. Read once: it never changes. local ADVANCED = false do local t = term.native and term.native() or term if t and t.isColor then ADVANCED = t.isColor() == true end end function F.nowMs() if os.epoch then return os.epoch("utc") end return math.floor(os.clock() * 1000) end -- Dig (and attack) events for the website's swing animation. At most one message per DIG_EVERY ms: a -- dig inside that window waits (replacing any older waiting one, `n` counts them) and goes out with the -- next state report, or is dropped once it is DIG_STALE ms old. Sending never waits on the network. local DIG_EVERY, DIG_STALE = 100, 1000 local lastDigSent, pendingDig = -DIG_EVERY, nil function F.flushDig() if not pendingDig then return end local now = F.nowMs() if now - pendingDig.at > DIG_STALE then pendingDig = nil return end if now - lastDigSent < DIG_EVERY then return end local ev = pendingDig pendingDig = nil ev.at = nil if ev.n == 1 then ev.n = nil end lastDigSent = now F.sendMsg(ev) end function F.noteDig(ev) ev.t, ev.at = "dig", F.nowMs() ev.n = (pendingDig and pendingDig.n or 0) + 1 pendingDig = ev F.flushDig() end -- Never dug, whatever a program asks for. local PROTECTED = { "chest", "barrel", "shulker", "hopper", "furnace", "computercraft:", "spawner", "bedrock", "barrier", "portal", "command_block" } -- A plan's constraints (1.20.0), set by its program with td.protect / td.fence and cleared when the program ends: -- more blocks never dug, and boxes no move, dig or place may enter (outside `within`, inside any of `avoid`). -- Kept in F (not locals): see the note at the top about CC:Tweaked's limit of 200 locals. F.planProtect = {} F.planFence = nil -- { within = box | nil, avoid = { box... } }, box = { x1, y1, z1, x2, y2, z2 } with x1 <= x2... F.FENCED = "outside the area this plan may use" function F.isProtected(name) for _, p in ipairs(PROTECTED) do if name:find(p, 1, true) then return true end end for _, p in ipairs(F.planProtect) do if name:find(p, 1, true) then return true end end return false end function F.inBox(b, x, y, z) return x >= b[1] and x <= b[4] and y >= b[2] and y <= b[5] and z >= b[3] and z <= b[6] end --- A cell the plan keeps turtles out of. A turtle that already stands in such a cell may move (to get out). function F.planFenced(x, y, z) local f = F.planFence if not f then return false end local function out(cx, cy, cz) if f.within and not F.inBox(f.within, cx, cy, cz) then return true end for _, b in ipairs(f.avoid) do if F.inBox(b, cx, cy, cz) then return true end end return false end return out(x, y, z) and not out(pos.x, pos.y, pos.z) end -- What the turtle has seen, for route planning: true = passable, false = solid, "p" = solid and protected. local known, knownCount = {}, 0 function F.kkey(x, y, z) return x .. "," .. y .. "," .. z end function F.isTurtle(name) return name:find("computercraft:turtle", 1, true) ~= nil end function F.remember(x, y, z, name) local k = F.kkey(x, y, z) if known[k] == nil then knownCount = knownCount + 1 end if not name or name:find("water", 1, true) or name:find("lava", 1, true) then known[k] = true elseif F.isProtected(name) then known[k] = "p" else known[k] = false end if knownCount > 40000 then known, knownCount = {}, 0 end end -- Where the owner's other turtles are, as told by the relay: id -> { x, y, z }. Refreshed in full -- whenever a program starts and kept current while it runs, so routes can bend around them. local peers = {} function F.peerCells() local cells = {} for _, p in pairs(peers) do cells[F.kkey(p.x, p.y, p.z)] = true end return cells end -- Shared spots set on the website: depots.fuel / depots.unload = { x, y, z, facing }, where a turtle -- stands to use the chest touching that spot. local depots = type(cfg.depots) == "table" and cfg.depots or {} --- The shared chests this turtle knows, as one short string ("fuel=x,y,z,facing;supply=...;unload=..."), reported in --- every state report: the relay compares it with the account's and sends them again when they differ (1.19.1+). function F.depotSig() local parts = {} for _, kind in ipairs({ "fuel", "supply", "unload" }) do local d = depots[kind] if d then parts[#parts + 1] = ("%s=%d,%d,%d,%d"):format(kind, math.floor(d.x), math.floor(d.y), math.floor(d.z), math.floor(d.facing or 0) % 4) end end return table.concat(parts, ";") end --- Take the shared chests the relay sent (in its welcome, or a config message) and keep them on disk. function F.applyDepots(list) depots = {} for _, kind in ipairs({ "fuel", "unload", "supply" }) do local d = list[kind] if type(d) == "table" and tonumber(d.x) and tonumber(d.y) and tonumber(d.z) then depots[kind] = { x = tonumber(d.x), y = tonumber(d.y), z = tonumber(d.z), facing = (tonumber(d.facing) or 0) % 4 } end end cfg.depots = depots F.saveConfig() end -- Changes the relay asks of a running job (keyed by program id), e.g. "narrow your hole, a helper takes the rest". local jobLimits = {} local currentProgramId, currentProgramName = nil, nil local buildWaiting = nil -- { layer, of } while td.build waits for modems to be connected: told to a relay after a restart -- Programs the website paused (1.19.2+, keyed by program id): a paused program finishes the move or dig it is on and -- waits in place at its next one until resumed. Kept in memory across relay restarts (the relay also says it again). local pausedIds = {} local logLine -- defined with the program runner below -- Block state, so the website can draw blocks the right way round: "key=value,..." with booleans as 1/0, at most -- STATE_MAX characters (the relay's limit), nothing when the block has none of the keys. It costs nothing extra: -- inspect already returned it, and every look sends it again, so old maps fill in. -- CC:Tweaked blocks: the facing of computers, monitors and drives, a monitor's orientation, a cable's arms and modem. local CC_STATE_KEYS = { "facing", "orientation", "cable", "modem", "peripheral", "north", "south", "east", "west", "up", "down", "state", "on", "top", "bottom", "type" } -- Every other block (1.18.1+): the properties the website's block set uses for shape and orientation, most telling -- first (stairs, slabs, logs, doors, chests, fences, panes, walls, rails, buttons, beds, signs, crops, water level...). -- Anything else a block reports (leaf distance, note block pitch...) does not change its look and is left out. local STATE_KEYS = { "facing", "half", "type", "axis", "shape", "hinge", "open", "face", "attachment", "rotation", "part", "north", "south", "east", "west", "up", "down", "in_wall", "hanging", "attached", "lit", "powered", "power", "snowy", "layers", "level", "age", "candles", "pickles", "eggs", "bites", "extended", "short", "thickness", "vertical_direction", "tilt", "orientation", "mode", "delay", "locked", "waterlogged", } local STATE_MAX = 160 function F.stateOf(data) if type(data) ~= "table" or type(data.name) ~= "string" or type(data.state) ~= "table" then return nil end if F.isTurtle(data.name) then return nil end local keys = data.name:sub(1, 14) == "computercraft:" and CC_STATE_KEYS or STATE_KEYS local out, len = {}, -1 for _, k in ipairs(keys) do local v = data.state[k] if v == true then v = "1" elseif v == false then v = k ~= "waterlogged" and "0" or nil -- waterlogged only changes the look when true (sea pickles) elseif type(v) == "number" then v = v == math.floor(v) and string.format("%d", v) or nil elseif type(v) == "string" and v:match("^[%w_]+$") then v = v:lower() else v = nil end if v and len + #k + #v + 2 <= STATE_MAX then out[#out + 1] = k .. "=" .. v len = len + #k + #v + 2 end end return #out > 0 and table.concat(out, ",") or nil end function F.noteBlock(x, y, z, name, state) -- Another turtle is not part of the world: the website draws turtles live from their own reports. -- Whatever terrain the map had at that spot is gone, though, or the turtle could not be standing there. if name and F.isTurtle(name) then name = false end pendingBlocks[#pendingBlocks + 1] = { x, y, z, name or false, name and state or nil } F.remember(x, y, z, name) end -- The last thing seen in each direction and where: the block name a dig removes, without another inspect. local lastLook = {} function F.inspectDir(dir) local ok, data, x, y, z if dir == "up" then ok, data = native.inspectUp(); x, y, z = pos.x, pos.y + 1, pos.z elseif dir == "down" then ok, data = native.inspectDown(); x, y, z = pos.x, pos.y - 1, pos.z else ok, data = native.inspect(); x, y, z = pos.x + DX[facing], pos.y, pos.z + DZ[facing] end F.noteBlock(x, y, z, ok and data.name or false, ok and F.stateOf(data) or nil) lastLook[dir] = { x = x, y = y, z = z, name = ok and data.name or nil } return ok, data end function F.lookAround() F.inspectDir("front"); F.inspectDir("up"); F.inspectDir("down") end function F.getInventory() local inv, sig = {}, {} for slot = 1, 16 do local d = native.getItemDetail(slot) if d then inv[#inv + 1] = { slot = slot, name = d.name, count = d.count } sig[#sig + 1] = slot .. d.name .. d.count end end return inv, table.concat(sig, ";") end function F.getUpgrades() local function side(s) local getter = s == "left" and native.getEquippedLeft or native.getEquippedRight if getter then local d = getter() return d and d.name or nil end return peripheral.getType(s) end return { left = side("left"), right = side("right") } end function F.getState() return { x = pos.x, y = pos.y, z = pos.z, facing = facing, located = located, fuel = native.getFuelLevel(), fuelLimit = native.getFuelLimit and native.getFuelLimit() or nil, selected = native.getSelectedSlot(), advanced = ADVANCED, digEvents = true, home = cfg.home or nil, homeChest = cfg.home and cfg.homeChest or nil, depots = F.depotSig(), } end -- Mirrored monitors (td.mirrorMonitor): the program draws on a window over the monitor; about once a second the -- rows that changed go to the website, which paints them on that monitor in the 3D map. Never waits on anything. local mirrors, lastMirrorAt = {}, 0 local SIDE_NAMES = { top = true, bottom = true, left = true, right = true, front = true, back = true } function F.paletteOf(t) if not (t.getPaletteColour and term.nativePaletteColour) then return nil end local out, custom = {}, false for i = 0, 15 do local c = 2 ^ i local r, g, b = t.getPaletteColour(c) local nr, ng, nb = term.nativePaletteColour(c) if r ~= nr or g ~= ng or b ~= nb then custom = true end out[i + 1] = math.floor(r * 255 + 0.5) * 65536 + math.floor(g * 255 + 0.5) * 256 + math.floor(b * 255 + 0.5) end return custom and out or nil end function F.flushMirrors(force) if not next(mirrors) or not ws then return end local now = F.nowMs() if not force and now - lastMirrorAt < 1000 then return end lastMirrorAt = now for name, m in pairs(mirrors) do local ok, err = pcall(function() local w, h = m.mon.getSize() local ww, wh = m.win.getSize() if ww ~= w or wh ~= h then m.win.reposition(1, 1, w, h) m.full, m.rows = true, {} end local rows = {} for y = 1, h do local t, f, b = m.win.getLine(y) local key = t .. f .. b if m.full or m.rows[y] ~= key then m.rows[y] = key rows[#rows + 1] = { y, t, f, b } end end if #rows == 0 then return end local msg = { t = "monitor", name = name, w = w, h = h, rows = rows, full = m.full or nil, advanced = m.mon.isColor and m.mon.isColor() or false, palette = F.paletteOf(m.win) } if located ~= "relative" then msg.pos = { x = pos.x, y = pos.y, z = pos.z } msg.facing = facing end if SIDE_NAMES[name] then msg.side = name end if F.sendMsg(msg) then m.full = false end end) if not ok then mirrors[name] = nil logLine("mirrorMonitor " .. name .. ": " .. tostring(err), "error") end end end --- Push position, newly seen blocks and (if changed) inventory to the relay. function F.sendState(forceAll) F.flushDig() F.flushMirrors() local msg = { t = "state", state = F.getState(), label = os.getComputerLabel() or false, world = cfg.world or "default" } if #pendingBlocks > 0 then msg.blocks = pendingBlocks pendingBlocks = {} end local inv, sig = F.getInventory() if forceAll or sig ~= lastInvSig then lastInvSig = sig msg.inventory = #inv > 0 and inv or textutils.empty_json_array msg.upgrades = F.getUpgrades() end F.sendMsg(msg) end ---------------------------------------------------------------- tracked turtle API function F.guarded(fn, ...) busyNative = true local r = table.pack(pcall(fn, ...)) busyNative = false if not r[1] then error(r[2], 3) end return table.unpack(r, 2, r.n) end --- A paused program (see pausedIds) waits here, before its next move, dig or place. function F.waitIfPaused() if currentProgramId == nil or not pausedIds[currentProgramId] then return end logLine(("Paused at %d, %d, %d: waiting here until the job is resumed"):format(pos.x, pos.y, pos.z)) while currentProgramId ~= nil and pausedIds[currentProgramId] do os.pullEvent("turtledeck_pause") end logLine("Resumed") end function F.trackedMove(name, dx, dy, dz) return function() F.waitIfPaused() local mx, mz = dx, dz if dx == "f" then mx, mz = DX[facing], DZ[facing] elseif dx == "b" then mx, mz = -DX[facing], -DZ[facing] end if F.planFenced(pos.x + mx, pos.y + dy, pos.z + mz) then return false, F.FENCED end local ok, err = F.guarded(native[name]) if ok then pos.x, pos.y, pos.z = pos.x + mx, pos.y + dy, pos.z + mz F.savePosition() F.noteBlock(pos.x, pos.y, pos.z, false) -- we are standing here, so it is not a block F.lookAround() else F.lookAround() -- whatever stopped us is worth drawing end F.sendState() return ok, err end end function F.trackedTurn(name, delta) return function() local ok, err = F.guarded(native[name]) if ok then facing = (facing + delta) % 4 F.savePosition() F.inspectDir("front") end F.sendState() return ok, err end end function F.cellIn(dir) if dir == "up" then return pos.x, pos.y + 1, pos.z end if dir == "down" then return pos.x, pos.y - 1, pos.z end return pos.x + DX[facing], pos.y, pos.z + DZ[facing] end --- Actions that change the block in one direction (dig, place, attack...). function F.trackedAction(name, dir) local swings = name:sub(1, 3) == "dig" and "dig" or name:sub(1, 6) == "attack" and "attack" or nil return function(...) F.waitIfPaused() local side = ... local ev local base = name:gsub("Up$", ""):gsub("Down$", "") if base == "dig" or base == "place" then local cx, cy, cz = F.cellIn(dir) if F.planFenced(cx, cy, cz) then return false, F.FENCED end if base == "dig" and #F.planProtect > 0 then local has, data = native[dir == "up" and "inspectUp" or dir == "down" and "inspectDown" or "inspect"]() if has and F.isProtected(data.name) then return false, "protected block (" .. data.name .. ")" end end end if swings then local x, y, z = F.cellIn(dir) ev = { dir = dir, x = x, y = y, z = z, side = (side == "left" or side == "right") and side or nil } local seen = lastLook[dir] if swings == "dig" and seen and seen.x == x and seen.y == y and seen.z == z then ev.block = seen.name end if swings == "attack" then ev.attack = true end end local r = table.pack(F.guarded(native[name], ...)) if ev and r[1] == true then F.noteDig(ev) end F.inspectDir(dir) F.sendState() return table.unpack(r, 1, r.n) end end --- Actions that only change inventory / fuel / equipment. function F.trackedInventory(name) return function(...) local r = table.pack(F.guarded(native[name], ...)) F.sendState(name == "equipLeft" or name == "equipRight") return table.unpack(r, 1, r.n) end end local tracked = { forward = F.trackedMove("forward", "f", 0), back = F.trackedMove("back", "b", 0), up = F.trackedMove("up", 0, 1, 0), down = F.trackedMove("down", 0, -1, 0), turnLeft = F.trackedTurn("turnLeft", -1), turnRight = F.trackedTurn("turnRight", 1), } for _, base in ipairs({ "dig", "place", "attack", "suck", "drop" }) do tracked[base] = F.trackedAction(base, "front") tracked[base .. "Up"] = F.trackedAction(base .. "Up", "up") tracked[base .. "Down"] = F.trackedAction(base .. "Down", "down") end for _, name in ipairs({ "select", "refuel", "equipLeft", "equipRight", "transferTo", "craft" }) do if native[name] then tracked[name] = F.trackedInventory(name) end end function F.installTracking() for k, v in pairs(tracked) do turtle[k] = v end end function F.removeTracking() for k in pairs(tracked) do turtle[k] = native[k] end end ---------------------------------------------------------------- locating --- GPS position, plus facing worked out by stepping one block and comparing. function F.locateWithGps() if not gps then return false end local x, y, z = gps.locate(2) if not x then return false end pos.x, pos.y, pos.z = math.floor(x + 0.5), math.floor(y + 0.5), math.floor(z + 0.5) located = "gps" for turns = 0, 3 do if native.forward() then local x2, _, z2 = gps.locate(2) native.back() if x2 then local dx, dz = math.floor(x2 + 0.5) - pos.x, math.floor(z2 + 0.5) - pos.z for f = 0, 3 do if DX[f] == dx and DZ[f] == dz then facing = f end end end for _ = 1, turns do native.turnLeft() end facing = (facing - turns) % 4 return true end native.turnRight() end -- Boxed in (or no fuel): position is right, facing is whatever we last knew. return true end function F.locate() if F.locateWithGps() then print(("GPS: %d %d %d facing %s"):format(pos.x, pos.y, pos.z, FACING_NAMES[facing])) elseif cfg.x then if located == "gps" then located = "saved" end print(("Saved position: %d %d %d facing %s"):format(pos.x, pos.y, pos.z, FACING_NAMES[facing])) else print("No GPS. Enter position as: x y z facing") print("(F3 shows both. Blank = start at 0 0 0 north)") write("> ") local x, y, z, f = (read() or ""):match("^%s*(-?%d+)%s+(-?%d+)%s+(-?%d+)%s+(%a+)") if x and FACINGS[f:lower()] then pos.x, pos.y, pos.z, facing, located = tonumber(x), tonumber(y), tonumber(z), FACINGS[f:lower()], "manual" else located = "relative" end end F.savePosition() end ---------------------------------------------------------------- td: navigation, home, mining -- Available to programs run from the website as the global `td`. local td = { mine = {} } --- Draw on the returned window instead of the monitor and the website shows the screen on the map. mon: a wrapped --- monitor or its peripheral name. The frames are keyed by this turtle and the monitor's peripheral name. function td.mirrorMonitor(mon) if type(mon) == "string" then mon = peripheral.wrap(mon) end if type(mon) ~= "table" or not mon.getSize or not mon.blit then error("td.mirrorMonitor: pass a monitor (peripheral.find(\"monitor\"))", 2) end local name = peripheral.getName and peripheral.getName(mon) or "monitor" local w, h = mon.getSize() local win = window.create(mon, 1, 1, w, h, true) mirrors[name] = { win = win, mon = mon, rows = {}, full = true } return win end local DIRS = { forward = { move = "forward", dig = "dig", attack = "attack", look = "front" }, up = { move = "up", dig = "digUp", attack = "attackUp", look = "up" }, down = { move = "down", dig = "digDown", attack = "attackDown", look = "down" }, } function td.pos() return { x = pos.x, y = pos.y, z = pos.z, facing = facing } end function td.home() return cfg.home end function F.boxOf(b) if type(b) ~= "table" then return nil end local x1, y1, z1 = tonumber(b.x1 or b[1]), tonumber(b.y1 or b[2]), tonumber(b.z1 or b[3]) local x2, y2, z2 = tonumber(b.x2 or b[4]), tonumber(b.y2 or b[5]), tonumber(b.z2 or b[6]) if not (x1 and y1 and z1 and x2 and y2 and z2) then return nil end return { math.min(x1, x2), math.min(y1, y2), math.min(z1, z2), math.max(x1, x2), math.max(y1, y2), math.max(z1, z2) } end --- A plan's area rules for this program (1.20.0): opts.within = a box every move, dig and place stays inside; --- opts.avoid = boxes none may enter. Boxes are { x1, y1, z1, x2, y2, z2 } (or with those keys). nil clears them. --- Routes (here and from the relay) go round fenced cells; a turtle already inside one may move out. function td.fence(opts) if opts == nil then F.planFence = nil return true end local f = { within = F.boxOf(opts.within), avoid = {} } for _, b in ipairs(opts.avoid or {}) do local box = F.boxOf(b) if box and #f.avoid < 8 then f.avoid[#f.avoid + 1] = box end end F.planFence = (f.within or #f.avoid > 0) and f or nil return true end --- Blocks this program never breaks, beyond chests, machines and computers (1.20.0): ids or parts of ids --- ("farmland", "minecraft:glass"). nil clears the list. Returns how many are protected. function td.protect(list) F.planProtect = {} for _, p in ipairs(list or {}) do p = tostring(p):lower():gsub("[^%w_:%./-]", "") if #p >= 2 and #F.planProtect < 16 then F.planProtect[#F.planProtect + 1] = p end end return #F.planProtect end function td.face(f) local diff = (f - facing) % 4 if diff == 1 then tracked.turnRight() elseif diff == 2 then tracked.turnRight(); tracked.turnRight() elseif diff == 3 then tracked.turnLeft() end return facing == f end --- Move one block, digging / attacking whatever is in the way. Falling gravel is handled by retrying. function td.digMove(dir) local d = DIRS[dir or "forward"] if native.getFuelLevel() == 0 then return false, "Out of fuel" end local waited = 0 for _ = 1, 40 do if tracked[d.move]() then return true end local has, data = F.inspectDir(d.look) if has then if F.isTurtle(data.name) then waited = waited + 1 if waited > 12 then return false, "turtle in the way" end sleep(0.4 + math.random() * 1.2) -- random, so two turtles facing each other do not retry in lockstep elseif F.isProtected(data.name) then return false, "protected block (" .. data.name .. ")" else local ok, err = tracked[d.dig]() if not ok then -- The server said no (a land claim, spawn protection) or the block is unbreakable. Works the same everywhere: -- no plugin needs to be known about, the refusal itself is the signal. Remember it so routes go around. local tx = pos.x + (dir == "up" and 0 or dir == "down" and 0 or DX[facing]) local ty = pos.y + (dir == "up" and 1 or dir == "down" and -1 or 0) local tz = pos.z + (dir == "up" and 0 or dir == "down" and 0 or DZ[facing]) known[F.kkey(tx, ty, tz)] = "p" return false, err or "cannot dig" end end else tracked[d.attack]() sleep(0.3) end end return false, "blocked" end --- Straight-line travel that digs its way: y first, then x, then z. function td.digTo(x, y, z) for _ = 1, 4000 do if pos.x == x and pos.y == y and pos.z == z then return true end local moved, err = false, nil if pos.y ~= y then moved, err = td.digMove(pos.y < y and "up" or "down") end if not moved and pos.x ~= x then td.face(pos.x < x and 1 or 3); moved, err = td.digMove("forward") end if not moved and pos.z ~= z then td.face(pos.z < z and 2 or 0); moved, err = td.digMove("forward") end if not moved then return false, err or "blocked" end end return false, "gave up" end -- A* over what the turtle has seen. Seen-clear cells are cheapest, unseen ones are worth a try, -- solid ones are only considered when digging is allowed, protected ones never. function F.heapPush(h, item) local i = #h + 1 h[i] = item while i > 1 do local p = math.floor(i / 2) if h[p][1] <= h[i][1] then break end h[p], h[i] = h[i], h[p] i = p end end function F.heapPop(h) local top, n = h[1], #h h[1] = h[n] h[n] = nil n = n - 1 local i = 1 while true do local l, r, m = i * 2, i * 2 + 1, i if l <= n and h[l][1] < h[m][1] then m = l end if r <= n and h[r][1] < h[m][1] then m = r end if m == i then break end h[m], h[i] = h[i], h[m] i = m end return top end local NEIGHBOURS = { { 1, 0, 0 }, { -1, 0, 0 }, { 0, 1, 0 }, { 0, -1, 0 }, { 0, 0, 1 }, { 0, 0, -1 } } -- weight: how much the distance left counts (1.5; 2 plans long trips through unknown cells, which cost 2 each, in far -- fewer steps). Returns the path, or nil and true when it gave up for size rather than for want of a way. function F.findPath(tx, ty, tz, allowDig, maxNodes, knownOnly, weight) local startK, goalK = F.kkey(pos.x, pos.y, pos.z), F.kkey(tx, ty, tz) local occupied = F.peerCells() local best, came, open = { [startK] = 0 }, {}, {} weight = weight or 1.5 local function h(x, y, z) return (math.abs(x - tx) + math.abs(y - ty) + math.abs(z - tz)) * weight end F.heapPush(open, { h(pos.x, pos.y, pos.z), 0, pos.x, pos.y, pos.z, startK }) local expanded = 0 while #open > 0 do local cur = F.heapPop(open) local g, x, y, z, k = cur[2], cur[3], cur[4], cur[5], cur[6] if k == goalK then local path = {} while k ~= startK do local c = came[k] table.insert(path, 1, { c[1], c[2], c[3] }) k = c[4] end return path end if g <= best[k] then expanded = expanded + 1 if expanded > maxNodes then return nil, true end if expanded % 400 == 0 then os.queueEvent("turtledeck_yield"); os.pullEvent("turtledeck_yield") end for _, n in ipairs(NEIGHBOURS) do local nx, ny, nz = x + n[1], y + n[2], z + n[3] local nk = F.kkey(nx, ny, nz) local seen, cost = known[nk], nil if nk == goalK or seen == true then cost = 1 elseif seen == nil then cost = 2 elseif seen == false and allowDig then cost = 8 end if knownOnly and seen ~= true and nk ~= goalK then cost = nil end -- stay inside corridors that are known to be open if cost and F.planFence and F.planFenced(nx, ny, nz) then cost = nil end -- the plan keeps turtles out of there if cost and occupied[nk] then cost = cost + 20 end -- another turtle is there: go around if there is any way to if cost and (best[nk] == nil or g + cost < best[nk]) then best[nk] = g + cost came[nk] = { nx, ny, nz, k } F.heapPush(open, { g + cost + h(nx, ny, nz), g + cost, nx, ny, nz, nk }) end end end end return nil end -- Set by td.survey for its own program: routes it takes never attack whatever stands in the way (it waits instead). local peaceful = nil -- { id = the program id } while a survey runs function F.stepTo(nx, ny, nz, allowDig) local dir = "forward" if ny > pos.y then dir = "up" elseif ny < pos.y then dir = "down" else td.face(nx > pos.x and 1 or nx < pos.x and 3 or nz > pos.z and 2 or 0) end if allowDig then return td.digMove(dir) end local d = DIRS[dir] if native.getFuelLevel() == 0 then return false, "Out of fuel" end local sawTurtle = false for _ = 1, 8 do if tracked[d.move]() then return true end local has, data = F.inspectDir(d.look) if has and F.isTurtle(data.name) then sawTurtle = true sleep(0.4 + math.random() * 1.2) elseif has then return false, "blocked" elseif peaceful and peaceful.id == currentProgramId then sleep(0.5) -- something alive is in the way, and a survey leaves it alone else tracked[d.attack]() -- something alive is in the way sleep(0.3) end end return false, sawTurtle and "turtle in the way" or "blocked" end -- Routes from the relay (1.19.1+): it plans over the account's whole map (everything any of the owner's turtles has -- seen, and cells known to be open), around the other turtles and their routes. The answer is a list of waypoints, each -- a straight line from the one before. Trips shorter than ROUTE_MIN, trips through known corridors only and anything -- while the relay is away are planned here, as before. local ROUTE_MIN, ROUTE_WAIT = 6, 3 -- blocks; seconds to wait for an answer local routeSeq = 0 --- Ask the relay for a route to x, y, z. Returns the cells to walk and the answer, or nil (then plan here). function F.askRoute(tx, ty, tz, mode, avoid) if not (ws and relayRoutes) or located == "relative" then return nil end routeSeq = routeSeq + 1 local id = "r" .. routeSeq local msg = { t = "route", id = id, from = { pos.x, pos.y, pos.z }, to = { tx, ty, tz }, dig = mode } if F.planFence then msg.fence = { within = F.planFence.within, avoid = F.planFence.avoid } end if #avoid > 0 then msg.avoid = avoid end routeWaiting, routeAnswer = id, nil if not F.sendMsg(msg) then routeWaiting = nil return nil end local timer = os.startTimer(ROUTE_WAIT) while not routeAnswer do local ev, a = os.pullEvent() if ev == "timer" and a == timer then break end end local m = routeAnswer routeWaiting, routeAnswer = nil, nil if os.cancelTimer then os.cancelTimer(timer) end if not (m and m.ok and type(m.path) == "table") then return nil, m and m.why or "no answer" end local cells, x, y, z = {}, pos.x, pos.y, pos.z for _, w in ipairs(m.path) do local wx, wy, wz = tonumber(w[1]), tonumber(w[2]), tonumber(w[3]) if not (wx and wy and wz) then return nil end if (wx ~= x and 1 or 0) + (wy ~= y and 1 or 0) + (wz ~= z and 1 or 0) > 1 then return nil end -- not a straight leg while x ~= wx or y ~= wy or z ~= wz do if x ~= wx then x = x + (wx > x and 1 or -1) elseif y ~= wy then y = y + (wy > y and 1 or -1) else z = z + (wz > z and 1 or -1) end cells[#cells + 1] = { x, y, z } if #cells > 8000 then return nil end end end return cells, m end --- Smart travel. opts.dig: false = never dig, true = dig freely, "fallback" (default) = only if no clear route exists. --- opts.known = true: only move through cells known to be open (seen, or taught with td.learn). Never digs. --- Routes of 6 blocks or more come from the relay (the account's map) when it is there; something in the way that the --- map did not know is gone around here, then the relay plans the rest again from there. function td.goTo(x, y, z, opts) if F.planFenced(x, y, z) then return false, F.FENCED end local mode = opts and opts.dig local knownOnly = opts and opts.known == true if knownOnly then mode = false end if mode == nil then mode = "fallback" end local allowDig = mode == true local detour = {} -- cells blocked by another turtle: avoided on this trip, forgotten afterwards local yielded = {} local avoid = {} -- cells found blocked on this trip that the map cannot show (a turtle, a mob, a refused dig): told to the relay local function done(...) for _, d in ipairs(detour) do known[d[1]] = d[2] end return ... end local function digOn() allowDig = true logLine("No clear route found, digging where needed") end local bumps = 0 -- clear-route attempts that hit something unseen; after a few, start digging (fallback mode) local relayMisses = 0 -- the relay did not answer or had no route: after a few, plan here for the rest of the trip for _ = 1, 80 do if pos.x == x and pos.y == y and pos.z == z then return done(true) end if mode == "fallback" and not allowDig and bumps >= 6 then digOn() end local path, fromRelay = nil, false if not knownOnly and relayMisses < 3 and math.abs(x - pos.x) + math.abs(y - pos.y) + math.abs(z - pos.z) >= ROUTE_MIN then local cells, m = F.askRoute(x, y, z, allowDig and true or mode, avoid) if cells and #cells > 0 then path, fromRelay = cells, true if m.dig and not allowDig then digOn() end else relayMisses = relayMisses + 1 end end if not path then local capped path, capped = F.findPath(x, y, z, allowDig, 8000, knownOnly) -- A long trip through cells nobody has seen: the search gave up for size, not for want of a way. Again, leaning -- harder towards the goal (before 1.19.1 this ended in "no route", or in digging through open air). if not path and capped then path = F.findPath(x, y, z, allowDig, 8000, knownOnly, 2.001) end end if not path then if mode == "fallback" and not allowDig then digOn() else return done(false, "no route") end else local i = 1 while i <= #path do local c = path[i] local ck = F.kkey(c[1], c[2], c[3]) if not yielded[ck] and F.peerCells()[ck] then yielded[ck] = true -- a turtle moved into the way since this route was planned: plan again, once break end local ok, err = F.stepTo(c[1], c[2], c[3], allowDig) if not ok then if err == "Out of fuel" then return done(false, err) end -- The goal itself cannot be entered (a refused dig, or another turtle standing on it): no point re-planning. if c[1] == x and c[2] == y and c[3] == z and (allowDig or err == "turtle in the way") then return done(false, err) end local k = F.kkey(c[1], c[2], c[3]) if not allowDig then bumps = bumps + 1 end -- A block there is on the map already (the look that found it was reported); a turtle, a mob or a refused dig -- is not, so the relay is told about it when it plans again. local sawBlock = known[k] == false or known[k] == "p" if (err == "turtle in the way" or allowDig or not sawBlock) and #avoid < 32 then avoid[#avoid + 1] = { c[1], c[2], c[3] } end -- Remember why we could not pass so the next plan avoids it. if err == "turtle in the way" then detour[#detour + 1] = { k, known[k] } known[k] = "p" elseif allowDig then known[k] = "p" elseif known[k] == nil or known[k] == true then known[k] = false end if fromRelay then -- The map was out of date here: get round it with what this turtle sees, back onto the route a few cells on, -- then have the relay plan the rest from there (it knows about the obstacle now). local rejoin = path[math.min(i + 3, #path)] local around = F.findPath(rejoin[1], rejoin[2], rejoin[3], allowDig, 400, false) if around and #around <= 12 then for _, a in ipairs(around) do if not F.stepTo(a[1], a[2], a[3], allowDig) then break end end end end break end i = i + 1 end end end return done(false, "gave up") end --- If the turtle is on its home spot, read the chest touching it so the website can show the contents. function F.scanHomeChest() local h = cfg.home if not h or pos.x ~= h.x or pos.y ~= h.y or pos.z ~= h.z or not peripheral.wrap then return end local spots = { { "bottom", 0, -1, 0 }, { "top", 0, 1, 0 }, { "front", DX[facing], 0, DZ[facing] }, { "back", -DX[facing], 0, -DZ[facing] }, } local found for _, sp in ipairs(spots) do local inv = peripheral.wrap(sp[1]) if inv and inv.list and inv.size then local ok, list = pcall(inv.list) if ok and type(list) == "table" then local totals, used = {}, 0 for _, item in pairs(list) do used = used + 1 totals[item.name] = (totals[item.name] or 0) + item.count end local items = {} for name, count in pairs(totals) do items[#items + 1] = { name = name, count = count } end table.sort(items, function(a, b) return a.count > b.count end) while #items > 40 do table.remove(items) end found = { x = pos.x + sp[2], y = pos.y + sp[3], z = pos.z + sp[4], slots = inv.size(), used = used, at = os.epoch and os.epoch("utc") or 0, items = #items > 0 and items or textutils.empty_json_array, } break end end end cfg.homeChest = found F.saveConfig() end --- Teach the route planner corridors somebody else dug: a list of boxes { x0, y0, z0, x1, y1, z1 } of open cells. function td.learn(boxes) local taught = 0 for _, b in ipairs(boxes) do for x = math.min(b[1], b[4]), math.max(b[1], b[4]) do for y = math.min(b[2], b[5]), math.max(b[2], b[5]) do for z = math.min(b[3], b[6]), math.max(b[3], b[6]) do if taught < 6000 then local k = F.kkey(x, y, z) if known[k] == nil then knownCount = knownCount + 1 end known[k] = true taught = taught + 1 end end end end end return taught end function td.setHome() cfg.home = { x = pos.x, y = pos.y, z = pos.z, facing = facing } F.scanHomeChest() F.saveConfig() F.sendState() return true end function td.goHome(opts) local h = cfg.home if not h then return false, "No home set" end local ok, err = td.goTo(h.x, h.y, h.z, opts) if ok then td.face(h.facing) F.scanHomeChest() F.sendState() end return ok, err end ---------------------------------------------------------------- td: inventory local JUNK = { "cobblestone", "cobbled_deepslate", "dirt", "gravel", "netherrack", "tuff", "granite", "diorite", "andesite", "minecraft:stone", "minecraft:deepslate", "flint" } local CONTAINERS = { "chest", "barrel", "shulker", "hopper", "drawer", "crate" } function F.matchesAny(name, list) for _, p in ipairs(list) do if name:find(p, 1, true) then return true end end return false end function td.emptySlots() local n = 0 for slot = 1, 16 do if native.getItemCount(slot) == 0 then n = n + 1 end end return n end function td.dropJunk() local selected = native.getSelectedSlot() for slot = 1, 16 do local d = native.getItemDetail(slot) if d and F.matchesAny(d.name, JUNK) then native.select(slot) native.dropDown() end end native.select(selected) F.sendState() end -- Fuel per item: the furnace burn time / 20 (as in relay/fleet.mjs). Anything else is measured by burning one. local FUEL_VALUES = { ["minecraft:coal"] = 80, ["minecraft:charcoal"] = 80, ["minecraft:coal_block"] = 800, ["minecraft:lava_bucket"] = 1000, ["minecraft:blaze_rod"] = 120, ["minecraft:dried_kelp_block"] = 200, } --- Burn what the selected slot holds, just enough for `target`: one refuel call with the count (a fuel the table does not --- know is measured by burning one first). Returns the number of items burned. function F.burnSelected(target) local d = native.getItemDetail(native.getSelectedSlot()) local level = native.getFuelLevel() if not d or level >= target or not native.refuel(0) then return 0 end local per, burned = FUEL_VALUES[d.name], 0 if not per then if not native.refuel(1) then return 0 end burned, per = 1, native.getFuelLevel() - level if per <= 0 then return burned end level = native.getFuelLevel() if level >= target or d.count <= 1 then return burned end end local n = math.min(d.count - burned, math.ceil((target - level) / per)) if n > 0 and native.refuel(n) then burned = burned + n end return burned end --- Burn fuel items from the inventory until the level reaches `target` (one refuel call per stack, the exact count). function td.refuel(target) if native.getFuelLevel() == "unlimited" then return true end local limit = native.getFuelLimit and native.getFuelLimit() if type(limit) == "number" then target = math.min(target, limit) end local selected = native.getSelectedSlot() for slot = 1, 16 do if native.getFuelLevel() >= target then break end if native.getItemCount(slot) > 0 then native.select(slot) F.burnSelected(target) end end native.select(selected) F.sendState() return native.getFuelLevel() >= target end --- Could the block on this side (left, right, back) be a chest, as far as the peripherals tell without turning? Every --- chest and barrel is a peripheral; the turtle's own modem or other upgrade on the left or right hides the block --- there, so that side has to be looked at. function F.sideMayHold(side) if not (peripheral and peripheral.getType) then return true end local ok, t = pcall(peripheral.getType, side) if not ok then return true end if t == nil then return false end if peripheral.hasType then local ok2, inv = pcall(peripheral.hasType, side, "inventory") if ok2 and inv then return true end end return F.matchesAny(tostring(t), CONTAINERS) or side ~= "back" end --- The chest / barrel touching the turtle, as { drop = fn, suck = fn }: below, above, in front, else on a side the --- peripherals say may hold one (turning to it). Nil when there is none, without spinning round looking for it. function F.findContainer() local function isContainer(dir) local has, data = F.inspectDir(dir) return has and F.matchesAny(data.name, CONTAINERS) end if isContainer("down") then return { drop = native.dropDown, suck = native.suckDown } end if isContainer("up") then return { drop = native.dropUp, suck = native.suckUp } end if isContainer("front") then return { drop = native.drop, suck = native.suck } end for _, side in ipairs({ "right", "left", "back" }) do if F.sideMayHold(side) then local was = facing if side == "right" then tracked.turnRight() elseif side == "left" then tracked.turnLeft() else tracked.turnRight() tracked.turnRight() end if isContainer("front") then return { drop = native.drop, suck = native.suck } end td.face(was) end end end --- Empty the inventory into a chest / barrel touching the turtle. Keeps one stack of fuel if asked. function td.unload(keepFuel) local container = F.findContainer() if not container then return false, "no chest next to the turtle" end local drop = container.drop local selected, keptFuel = native.getSelectedSlot(), false for slot = 1, 16 do if native.getItemCount(slot) > 0 then native.select(slot) if keepFuel and not keptFuel and native.refuel(0) then keptFuel = true else drop() end end end native.select(selected) F.scanHomeChest() F.sendState() return true end ---------------------------------------------------------------- td: shared depots local NO_CHEST = "no chest at the fuel spot" function F.inventoryEmpty() for slot = 1, 16 do if native.getItemCount(slot) > 0 then return false end end return true end --- The shared chests this turtle knows (set on the website, sent by the relay): a copy of --- { fuel = { x, y, z, facing }, unload = ..., supply = ... } for the kinds that are set. function td.depots() local out = {} for kind, d in pairs(depots) do out[kind] = { x = d.x, y = d.y, z = d.z, facing = d.facing } end return out end --- A shared chest spot with no chest at it: said once, plainly, instead of looking round for it. function F.noChestAt(kind, d) local why = ("no chest at the %s chest spot %d, %d, %d: was it moved or broken? Set it again on the website (Jobs, Shared chests)"):format(kind, d.x, d.y, d.z) logLine(why:sub(1, 1):upper() .. why:sub(2), "error") return why end -- Shared chests without crowding and without digging (1.19.3). With a relay that coordinates them (its welcome says -- `depotQueue`), a turtle asks for its turn first: the relay gives it a spot to stand next to the chest when one is free -- (usually there is one), or a queue spot a few blocks away to wait at, and tells it when to move up. Trips to the chest, -- to the queue spot and away never dig: a turtle that finds no way waits, says so, and tries again. With an older relay, -- or no relay at all, it goes straight there without digging and waits politely when another turtle is in the way. -- Grouped in a block so its helpers do not count as top-level locals: CC:Tweaked's Lua counts every local in -- scope (enclosing functions included) towards a limit of 200, and the top level of this file is close to it. local depotEnter, depotLeave, visitDepot do local DEPOT_WAIT_MAX = 15 * 60 -- seconds in line before it gives up local DEPOT_REMIND = 20 -- seconds between reminders while waiting (the relay forgets a waiting turtle that goes quiet) local depotSeq = 0 --- The relay's next word about ticket `id`, or nil after `seconds`. local function depotWait(id, seconds) local timer = os.startTimer(seconds) while true do local a = depotState.answers[id] if a and a.fresh then a.fresh = nil if os.cancelTimer then os.cancelTimer(timer) end return a end local ev, p = os.pullEvent() if ev == "timer" and p == timer then return nil end end end function depotEnter() local t = depotState.ticket if not t then return end F.sendMsg({ t = "depot_enter", id = t.id, kind = t.kind, solo = t.solo or nil, held = t.held or nil, at = { pos.x, pos.y, pos.z } }) end --- Out of the queue (done, given up, or the program ended). failed: why it could not use the chest. function depotLeave(failed) local t = depotState.ticket if not t then return end depotState.ticket = nil F.sendMsg({ t = "depot_leave", id = t.id, kind = t.kind, failed = failed }) end --- Wait for this turtle's turn at a shared chest. Returns the spot to stand at ({ x, y, z, facing, side }), or nil and --- why ("no queue": the relay does not coordinate, go without it). The queue spot it was sent to comes back third. local function takeTurn(kind, label, solo, startedAt) for _ = 1, 30 do -- the relay is away (a restart): give it a moment before going without it if ws then break end sleep(1) end if not (ws and depotState.queue and located ~= "relative") then return nil, "no queue" end depotSeq = depotSeq + 1 local id = ("q%d-%s"):format(depotSeq, SESSION) depotState.ticket = { id = id, kind = kind, solo = solo and true or nil, held = false } depotState.answers = {} depotEnter() local answered, place, queueAt, gones = false, nil, nil, 0 while true do if os.clock() - startedAt > DEPOT_WAIT_MAX then depotLeave("waited too long") return nil, ("waited %d minutes for the %s"):format(math.floor(DEPOT_WAIT_MAX / 60), label) end local a = depotWait(id, answered and DEPOT_REMIND or 5) if not a then if not answered then depotLeave("no answer") return nil, "no queue" end -- this relay does not answer: go without it depotEnter() -- still waiting (a relay that restarted meanwhile learns about this turtle again) elseif a.go then depotState.ticket.held = true return type(a.spot) == "table" and a.spot or depots[kind], nil, queueAt elseif a.gone then gones = gones + 1 logLine(("Out of the queue for the %s (%s)%s"):format(label, tostring(a.why or "the relay said so"), gones < 3 and "; asking again" or "")) if gones >= 3 then depotLeave("left out") return nil, "no queue" end answered = true depotEnter() else answered = true if a.place and a.place ~= place then place = a.place logLine(("Waiting for the %s: %s"):format(label, place == 1 and "next in line" or ("number " .. place .. " in line"))) end local cell = type(a.wait) == "table" and a.wait or nil if cell and tonumber(cell[1]) and tonumber(cell[2]) and tonumber(cell[3]) then local k = F.kkey(cell[1], cell[2], cell[3]) if queueAt ~= k and not (pos.x == cell[1] and pos.y == cell[2] and pos.z == cell[3]) then queueAt = k local ok, why = td.goTo(tonumber(cell[1]), tonumber(cell[2]), tonumber(cell[3]), { dig = false }) if not ok then logLine(("Could not get to the queue spot (%s): waiting here"):format(tostring(why))) end end end end end end --- Look at all six sides again (turning round once), so the route planners know what is there now. local function lookAgain() F.inspectDir("up") F.inspectDir("down") for _ = 1, 4 do tracked.turnRight() end -- each turn looks ahead and reports it F.sendState() end --- Step off the chest's spot so the next turtle can use it: to where it waited in line, else a couple of blocks back. local function stepAside(queueAt) if queueAt then local x, y, z = queueAt:match("^(-?%d+),(-?%d+),(-?%d+)$") if x and td.goTo(tonumber(x), tonumber(y), tonumber(z), { dig = false }) then return true end end local here = td.pos() for _, d in ipairs({ { -DX[facing], 0, -DZ[facing] }, { 0, 1, 0 }, { DX[(facing + 1) % 4], 0, DZ[(facing + 1) % 4] } }) do if td.goTo(here.x + 2 * d[1], here.y + 2 * d[2], here.z + 2 * d[3], { dig = false }) then return true end end return false end --- Use a shared chest: kind "fuel", "unload" or "supply"; action() runs there, facing the chest, and returns ok, why. --- opts.solo: nobody else at the chest meanwhile (one at a time). opts.after: "back" (default: back to where it started, --- or opts.back), "home", "park" (step aside and stay near the chest) or "leave" (the caller moves on at once). --- Never digs on the way there, near the chest or while stepping aside, and never stands in another turtle's way at the --- chest. opts.dig ("fallback"): the trip home or back, once away from the chest, may dig where there is no clear way. function td.useDepot(kind, action, opts) opts = opts or {} local d = depots[kind] if not d then return false, "no " .. kind .. " chest has been set" end local label = kind .. " chest" local back = opts.back or td.pos() local startedAt = os.clock() local ok, err, queueAt -- Blocked on the way (no route without digging): wait longer each time, up to DEPOT_WAIT_MAX in all, never digging. for attempt = 1, 60 do local spot, why spot, why, queueAt = takeTurn(kind, label, opts.solo, startedAt) local arrived, reason = false, nil if spot then arrived, reason = td.goTo(tonumber(spot.x), tonumber(spot.y), tonumber(spot.z), { dig = false }) elseif why == "no queue" then spot = d for n = 1, 8 do -- no coordination: straight there, waiting while another turtle uses it arrived, reason = td.goTo(d.x, d.y, d.z, { dig = false }) if arrived or reason == "Out of fuel" then break end if n == 1 then logLine(("The %s is busy or out of reach (%s): waiting"):format(label, tostring(reason))) end sleep(3 + math.random() * 5) end else return false, why end if arrived then if spot.side ~= "down" and spot.side ~= "up" then td.face(tonumber(spot.facing) or d.facing) end local fine, a1, a2 = pcall(action) depotLeave() if not fine then error(a1, 0) end -- an abort (or a bug) in the action: the spot is free again, then it goes on up ok, err = a1, a2 if not ok and tostring(err):find("no chest", 1, true) then err = F.noChestAt(kind, d) end break end depotLeave(tostring(reason)) if reason == "Out of fuel" then return false, "Out of fuel on the way to the " .. label end local pause = math.min(60, 15 + 10 * (attempt - 1)) if os.clock() - startedAt + pause > DEPOT_WAIT_MAX then return false, ("could not reach the %s without digging (%s)"):format(label, tostring(reason)) end logLine(("Cannot reach the %s without digging (%s): waiting %d s, then trying again"):format(label, tostring(reason), pause), "error") sleep(pause + math.random() * 5) lookAgain() -- the way may have been cleared meanwhile: what is around is looked at again (and reported to the map) end local after = opts.after or "back" if after == "leave" then return ok, err end if after == "park" then stepAside(queueAt) return ok, err end -- Home or back to the work: never digging unless allowed (opts.dig). Blocked: wait and try again, then say so. stepAside(queueAt) local digBack = opts.dig == "fallback" and "fallback" or false for n = 1, 3 do local there, why if after == "home" then if not cfg.home then return ok, err end there, why = td.goHome({ dig = digBack }) else there, why = td.goTo(back.x, back.y, back.z, { dig = digBack }) if there then td.face(back.facing) end end if there then return ok, err end if why == "Out of fuel" or n == 3 then local where = after == "home" and "home" or "back to the work site" if ok then return false, ("could not get %s without digging (%s)"):format(where, tostring(why)) end return ok, err end logLine(("Cannot get %s without digging (%s): waiting, then trying again"):format(after == "home" and "home" or "back", tostring(why)), "error") sleep(10 + math.random() * 10) lookAgain() end return ok, err end --- Travel to a shared spot, do something there, and come back to where the work was (through the queue, never digging). function visitDepot(kind, action, opts) return td.useDepot(kind, action, opts) end end --- Take fuel from the chest touching the turtle and burn it up to `target`, in as few pulls as possible: up to a stack a --- pull, more pulls when the target needs them and there is room, one refuel call per stack with the exact count. What --- is left over goes back into the chest; opts.keep items of it stay on board as a reserve. Returns ok, why. function td.takeFuel(target, opts) opts = opts or {} local level = native.getFuelLevel() if level == "unlimited" then return true end local limit = native.getFuelLimit and native.getFuelLimit() if type(limit) == "number" then target = math.min(target, limit) end local container = F.findContainer() -- first: a chest that is gone is said, even when no fuel is needed if not container then return false, NO_CHEST end if level >= target then return true end local selected = native.getSelectedSlot() local taken, values, order, burned = {}, {}, {}, {} -- taken from the chest this visit; fuel per item; kinds in pull order; burned local function counts() local t = {} for s = 1, 16 do local it = native.getItemDetail(s) t[s] = it and { name = it.name, count = it.count } or false end return t end local function freeSlot() for s = 1, 16 do if native.getItemCount(s) == 0 then return s end end end --- Drop up to n of an item back into the chest (from the last slots first). Returns how many went. local function giveBack(name, n) local gone = 0 for s = 16, 1, -1 do if gone >= n then break end local it = native.getItemDetail(s) if it and it.name == name then native.select(s) container.drop(math.min(it.count, n - gone)) gone = gone + (it.count - native.getItemCount(s)) end end return gone end --- One pull of up to n items into a free slot. Returns the item name and how many came, or nil and why. local function pull(n) local s = freeSlot() if not s then return nil, "no room" end native.select(s) local before = counts() if not container.suck(math.max(1, math.min(64, n))) then return nil, "empty" end local after, name, got = counts(), nil, 0 for slot = 1, 16 do local a, b = before[slot], after[slot] local more = (b and b.count or 0) - ((a and b and a.name == b.name) and a.count or 0) if b and more > 0 then name, got = b.name, got + more end end if not name then return nil, "empty" end for slot = 1, 16 do local it = native.getItemDetail(slot) if it and it.name == name then native.select(slot) break end end if not native.refuel(0) then giveBack(name, got) return nil, "not fuel", name end if not taken[name] then order[#order + 1] = name end taken[name] = (taken[name] or 0) + got return name, got end --- Fuel in what was taken and not burned yet. local function onHand() local w = 0 for item, n in pairs(taken) do w = w + (n - (burned[item] or 0)) * (values[item] or 80) end return w end -- The first pull is sized for coal, the usual fuel; a richer fuel needs fewer, and the rest goes back. local why = nil local name, got, other = pull(math.ceil((target - level) / 80)) if not name then native.select(selected) if got == "not fuel" then return false, "the fuel chest holds something that is not fuel (" .. tostring(other) .. ")" end return false, got == "no room" and "no empty slot to take fuel into" or "the fuel chest is empty" end if not FUEL_VALUES[name] then -- not in the table: burn one and see for slot = 1, 16 do local it = native.getItemDetail(slot) if it and it.name == name then native.select(slot) break end end local was = native.getFuelLevel() if native.refuel(1) then values[name] = math.max(1, native.getFuelLevel() - was) burned[name] = 1 level = native.getFuelLevel() end end values[name] = values[name] or FUEL_VALUES[name] or 80 -- More pulls while the target needs more and there is room. for _ = 1, 15 do level = native.getFuelLevel() if level + onHand() >= target then break end local last = order[#order] local more, n2, bad = pull(math.ceil((target - level - onHand()) / (values[last] or 80))) if not more then if n2 == "empty" then why = "the fuel chest ran out" elseif n2 == "not fuel" then why = "the fuel chest also holds something that is not fuel (" .. tostring(bad) .. ")" end break end values[more] = values[more] or FUEL_VALUES[more] if not values[more] then -- a new kind nobody knows: measure it too for slot = 1, 16 do local it = native.getItemDetail(slot) if it and it.name == more then native.select(slot) break end end local was = native.getFuelLevel() if native.refuel(1) then values[more] = math.max(1, native.getFuelLevel() - was) burned[more] = (burned[more] or 0) + 1 level = native.getFuelLevel() else values[more] = 80 end end end -- Burn: one refuel call per stack, the exact count. for _, item in ipairs(order) do for slot = 1, 16 do if native.getFuelLevel() >= target then break end local it = native.getItemDetail(slot) if it and it.name == item and (taken[item] - (burned[item] or 0)) > 0 then native.select(slot) local n = math.min(it.count, taken[item] - (burned[item] or 0), math.ceil((target - native.getFuelLevel()) / values[item])) if n > 0 and native.refuel(n) then burned[item] = (burned[item] or 0) + n end end end end -- Leftovers back into the chest, less the reserve asked for. local keep = math.max(0, math.floor(tonumber(opts.keep) or 0)) for _, item in ipairs(order) do local extra = taken[item] - (burned[item] or 0) local stay = math.min(extra, keep) keep = keep - stay if extra - stay > 0 then giveBack(item, extra - stay) end end native.select(selected) F.sendState() if native.getFuelLevel() >= target then return true end return false, why or "not enough fuel in the chest" end --- Fill up at the shared fuel chest (through the queue). opts as td.useDepot, plus keep (items kept as a reserve). function td.refuelAtDepot(target, opts) opts = opts or {} return visitDepot("fuel", function() return td.takeFuel(target, { keep = opts.keep }) end, opts) end --- Count of each item on board. function F.stock() local have = {} for slot = 1, 16 do local d = native.getItemDetail(slot) if d then have[d.name] = (have[d.name] or 0) + d.count end end return have end function F.selectItem(name) for slot = 1, 16 do local d = native.getItemDetail(slot) if d and d.name == name then native.select(slot) return true end end return false end local ENDER_ID = type(cfg.enderId) == "string" and cfg.enderId or "sc-goodies:ender_storage" function td.setEnderId(id) ENDER_ID = tostring(id) end --- Items that stay on board when unloading: the ender chest, one fuel stack, and anything in `keep`. function F.keepable(d, keep) return d.name == ENDER_ID or (keep and keep[d.name]) end --- Empty the inventory through a carried ender chest (its other end is the deposit chest, which the storage --- station drains). Placed above, or in front if there is no room above. Returns true, or false and why. function td.dumpViaEnder(keep) if not F.selectItem(ENDER_ID) then return false, "no ender chest on board" end local dir if not F.inspectDir("up") and tracked.placeUp() then dir = "up" elseif not F.inspectDir("front") and tracked.place() then dir = "front" else return false, "no room to place the ender chest" end local drop, take = (dir == "up" and native.dropUp or native.drop), (dir == "up" and tracked.digUp or tracked.dig) local selected, keptFuel, stuck = native.getSelectedSlot(), false, false for slot = 1, 16 do local d = native.getItemDetail(slot) if d and not F.keepable(d, keep) then native.select(slot) if not keptFuel and native.refuel(0) then keptFuel = true else for _ = 1, 3 do if native.getItemCount(slot) == 0 or not drop() then break end sleep(0.2) end if native.getItemCount(slot) > 0 then stuck = true end end end end native.select(selected) take() -- back into the inventory, link intact F.sendState(true) if stuck then return false, "the ender chest is full: is the storage station draining the deposit chest?" end return true end function F.hasEnder() for slot = 1, 16 do local d = native.getItemDetail(slot) if d and d.name == ENDER_ID then return true end end return false end --- Unload: through a carried ender chest if there is one, else at the shared unload chest. Home is a parking --- spot, not a store (Tim's choice), so a chest at home is only used when nothing else exists. function F.unloadSomewhere(keep) if F.hasEnder() then local ok, why = td.dumpViaEnder(keep) if ok then return true end logLine("Ender chest: " .. tostring(why) .. ", falling back to the unload chest", "error") end if depots.unload then return visitDepot("unload", function() return td.unload(true) end) end if td.unload(true) then return true end return false, "no ender chest on board and no shared unload chest set" end ---------------------------------------------------------------- td: mining -- Best Y level per ore (Minecraft 1.18+ world generation). td.ORE_LEVELS = { coal = 96, copper = 48, iron = 16, gold = -16, lapis = 0, redstone = -59, diamond = -59, emerald = 236, ancient_debris = 15, quartz = 15, } function F.abort(reason) error({ turtledeckAbort = reason }, 0) end -- Work sites, keyed by where and which way the job started. local sites function F.loadSites() if not sites then sites = {} if fs.exists(SITES_PATH) then local f = fs.open(SITES_PATH, "r") sites = textutils.unserialize(f.readAll() or "") or {} f.close() end end return sites end function F.saveSite(key, done, restart) -- The server keeps the shared copy: a lane is often finished by a different turtle than the one that began it. F.sendMsg({ t = "site", key = key, done = done, restart = restart or nil }) local all = F.loadSites() all[key] = { done = done, t = os.epoch and os.epoch("utc") or 0 } local n, oldestKey, oldest = 0, nil, math.huge for k, v in pairs(all) do n = n + 1 if v.t < oldest then oldestKey, oldest = k, v.t end end if n > 200 and oldestKey ~= key then all[oldestKey] = nil end local f = fs.open(SITES_PATH, "w") f.write(textutils.serialize(all)) f.close() end function F.siteKey(kind, extra) return ("%s:%d,%d,%d:%d%s"):format(kind, pos.x, pos.y, pos.z, facing, extra or "") end --- What the account's other turtles recorded for this site. Waits briefly for the relay; 0 if it does not answer. function F.sharedSiteDone(key) if not F.sendMsg({ t = "site_get", key = key }) then return 0 end local timer = os.startTimer(3) while true do local ev, a, b = os.pullEvent() if ev == "turtledeck_site" and a == key then return tonumber(b) or 0 end if ev == "timer" and a == timer then return 0 end end end function F.siteDone(key, opts) if opts.resume == false then return 0 end local site = F.loadSites()[key] return math.max(site and site.done or 0, F.sharedSiteDone(key)) end function td.forgetSites() sites = {} if fs.exists(SITES_PATH) then fs.delete(SITES_PATH) end end function F.distanceTo(p) return math.abs(pos.x - p.x) + math.abs(pos.y - p.y) + math.abs(pos.z - p.z) end --- Called before every block mined: keeps enough fuel to get back, and empties a full inventory at home. function F.checkpoint(job) local fuel = native.getFuelLevel() if fuel ~= "unlimited" then local need = F.distanceTo(job.ret) + 30 if fuel < need and not td.refuel(need + 200) then -- Nothing to burn on board: fall back to the shared fuel chest, if it can still be reached. local d = depots.fuel if not d or native.getFuelLevel() < F.distanceTo(d) + 5 then F.abort("low fuel") end logLine("Low on fuel, going to the fuel chest") local limit = native.getFuelLimit and native.getFuelLimit() or 20000 local ok, err = td.refuelAtDepot(math.min(limit, math.max(need * 3, 2000))) if native.getFuelLevel() < F.distanceTo(job.ret) + 30 then F.abort("low fuel (" .. tostring(err or "fuel chest did not help") .. ")") end end end if td.emptySlots() == 0 then if job.opts.dropJunk then td.dropJunk() end if td.emptySlots() == 0 then logLine(F.hasEnder() and "Inventory full, emptying through the ender chest" or "Inventory full, going to the unload chest") local unloaded, why = F.unloadSomewhere(job.keep) if not unloaded then F.abort("inventory full: " .. tostring(why)) end end end end function F.isOre(name) return name:find("_ore", 1, true) ~= nil or name:find("ancient_debris", 1, true) ~= nil end local veinFrom function F.tryOre(job, dir) local has, data = F.inspectDir(DIRS[dir].look) if not (has and F.isOre(data.name)) or job.veinBudget <= 0 then return end F.checkpoint(job) if not td.digMove(dir) then return end job.ores = job.ores + 1 job.veinBudget = job.veinBudget - 1 veinFrom(job) if dir == "up" then td.digMove("down") elseif dir == "down" then td.digMove("up") elseif not tracked.back() then local f = facing td.face((f + 2) % 4) td.digMove("forward") td.face(f) end end --- Dig out the whole ore vein touching the turtle, then come back to where it started. function veinFrom(job) F.tryOre(job, "up") F.tryOre(job, "down") for _ = 1, 4 do F.tryOre(job, "forward") tracked.turnRight() end end local PLUGS = { "cobblestone", "cobbled_deepslate", "dirt", "netherrack", "tuff", "granite", "diorite", "andesite", "minecraft:stone", "minecraft:deepslate" } function F.slotOf(list) for slot = 1, 16 do local d = native.getItemDetail(slot) if d and F.matchesAny(d.name, list) then return slot end end end --- Lava or water next to the tunnel: wall it off with a junk block so it cannot flow in. function F.plug(job, dir) if job.opts.plug == false then return end local has, data = F.inspectDir(DIRS[dir].look) if not (has and (data.name:find("lava", 1, true) or data.name:find("water", 1, true))) then return end local slot = F.slotOf(PLUGS) if not slot then return end local selected = native.getSelectedSlot() native.select(slot) tracked[dir == "up" and "placeUp" or dir == "down" and "placeDown" or "place"]() native.select(selected) end --- A torch in a one-block niche in the left wall, so it lights the tunnel without standing in the way. function F.placeTorch() local slot = F.slotOf({ "torch" }) if not slot then return false end tracked.turnLeft() local has, data = F.inspectDir("front") local clear = not has or (not F.isProtected(data.name) and tracked.dig()) if clear then local selected = native.getSelectedSlot() native.select(slot) tracked.place() native.select(selected) end tracked.turnRight() return clear end local function scan(job, sides) local veins = job.opts.veins ~= false job.veinBudget = 64 for _, dir in ipairs({ "up", "down" }) do if veins then F.tryOre(job, dir) end F.plug(job, dir) end if sides then tracked.turnLeft() if veins then F.tryOre(job, "forward") end F.plug(job, "forward") tracked.turnRight(); tracked.turnRight() if veins then F.tryOre(job, "forward") end F.plug(job, "forward") tracked.turnLeft() end end local function clear(dir) local d = DIRS[dir] for _ = 1, 20 do local has, data = F.inspectDir(d.look) if not has or F.isProtected(data.name) or not tracked[d.dig]() then return end sleep(0.2) -- let gravel settle end end td.clear = clear -- td.clear("up" | "down" | "forward"): dig until nothing falls back in --- One block of tunnel. height 1-3; at height 3 the turtle is expected to travel in the middle row. function F.tunnelStep(job, height, sides) F.checkpoint(job) local ok, err = td.digMove("forward") if not ok then return false, err end if height >= 2 then clear("up") end if height >= 3 then clear("down") end scan(job, sides) return true end function F.runJob(name, opts, body) opts = opts or {} local h = cfg.home local job = { opts = opts, ores = 0, veinBudget = 64, ret = h and { x = h.x, y = h.y, z = h.z, facing = h.facing } or td.pos() } logLine(name .. " started") local ok, err = pcall(body, job) local reason if not ok then if type(err) == "table" and err.turtledeckAbort then reason = err.turtledeckAbort logLine(name .. " stopped early: " .. reason, "error") else error(err, 0) end end if opts.returnHome ~= false then if td.goTo(job.ret.x, job.ret.y, job.ret.z) then td.face(job.ret.facing) if not F.inventoryEmpty() then F.unloadSomewhere(job.keep) end else logLine("Could not get back to the start", "error") end end logLine(("%s finished. Ore blocks mined: %d. Fuel left: %s"):format(name, job.ores, tostring(native.getFuelLevel()))) return ok, reason end --- Run custom work as a job: same start/finish logging, return home and unload as the built-in jobs. --- body receives check(), to call before each block: it keeps the fuel reserve and empties a full inventory. function td.run(name, opts, body) return F.runJob(name, opts, function(job) body(function() F.checkpoint(job) end) end) end function F.stripBody(job, opts) local length, spacing, branch = opts.length or 32, math.max(opts.spacing or 3, 1), opts.branch or 8 local height, sides = math.min(opts.height or 1, 3), opts.sides ~= false local torches = tonumber(opts.torches) or 0 local heading = facing local key = F.siteKey("strip") local before = F.siteDone(key, opts) if height == 3 and not td.digMove("up") then F.abort("cannot start the tunnel") end if before > 0 then -- Mined here before: walk to the end of the old tunnel and carry on from there. logLine(("The first %d blocks were mined on an earlier run, continuing from there"):format(before)) for _ = 1, before do F.checkpoint(job) if not td.digMove("forward") then F.abort("the old tunnel is blocked") end end end for i = before + 1, before + length do local ok, err = F.tunnelStep(job, height, sides) if not ok then if err == "Out of fuel" or err == "turtle in the way" then F.abort("main tunnel blocked: " .. tostring(err)) end -- Bedrock, a protected claim, spawn protection: nobody can dig this, so the mine simply ends here. logLine(("The tunnel cannot go past block %d (%s). Ending this mine here."):format(i - 1, tostring(err)), "error") break end if branch > 0 and i % spacing == 0 then for _, turn in ipairs({ -1, 1 }) do td.face((heading + turn) % 4) local dug = 0 for _ = 1, branch do if not F.tunnelStep(job, 1, sides) then break end dug = dug + 1 end td.face((heading - turn) % 4) for _ = 1, dug do td.digMove("forward") end end td.face(heading) end if torches > 0 and i % torches == 0 then F.placeTorch() end F.saveSite(key, i, opts.resume == false and i == before + 1) end end --- Main tunnel with side branches. opts: length, spacing, branch, height (1-3), sides, veins, dropJunk, returnHome function td.mine.strip(opts) opts = opts or {} return F.runJob("Strip mine", opts, function(job) F.stripBody(job, opts) end) end --- A plain tunnel. opts: length, height (1-3), sides, veins function td.mine.tunnel(opts) opts = opts or {} local o = setmetatable({ branch = 0 }, { __index = opts }) return F.runJob("Tunnel", opts, function(job) F.stripBody(job, o) end) end --- Go to the best level for an ore, then strip mine there. opts: ore (or y), plus the strip options. function td.mine.ore(opts) opts = opts or {} local y = tonumber(opts.y) or td.ORE_LEVELS[opts.ore or ""] if not y then error("unknown ore: " .. tostring(opts.ore), 0) end if located == "relative" then error("Ore levels need real coordinates: set up GPS or run `turtledeck setpos`", 0) end return F.runJob("Mining for " .. tostring(opts.ore or ("y=" .. y)), opts, function(job) for _ = 1, 2 do -- keep the shaft clear of the home spot if not td.digMove("forward") then F.abort("cannot leave the start") end end local heading = facing local ok, err = td.digTo(pos.x, y, pos.z) if not ok then F.abort("cannot reach y=" .. y .. ": " .. tostring(err)) end td.face(heading) F.stripBody(job, opts) end) end --- A walkable staircase. opts: direction ("down"/"up"), steps or toY, headroom (2-3) function td.mine.stairs(opts) opts = opts or {} local up = opts.direction == "up" local steps = opts.steps or (opts.toY and math.abs(pos.y - opts.toY)) or 16 local headroom = opts.headroom or 3 local torches = tonumber(opts.torches) or 0 return F.runJob("Staircase", opts, function(job) for step = 1, steps do F.checkpoint(job) local ok, err if up then ok, err = td.digMove("up") if ok then ok, err = td.digMove("forward") end else ok, err = td.digMove("forward") end if not ok then F.abort(tostring(err)) end clear("up") if headroom >= 3 and td.digMove("up") then clear("up") td.digMove("down") end if not up then ok, err = td.digMove("down") if not ok then F.abort(tostring(err)) end end scan(job, false) if torches > 0 and step % torches == 0 then F.placeTorch() end end end) end --- Dig a box downwards. The turtle sits on the near-left corner: width runs to its right, length ahead, depth below. function td.mine.hole(opts) opts = opts or {} local width, length, depth = math.max(opts.width or 3, 1), math.max(opts.length or 3, 1), math.max(opts.depth or 3, 1) return F.runJob("Dig hole", opts, function(job) local ox, oy, oz, f = pos.x, pos.y, pos.z, facing local r = (f + 1) % 4 local cells local function layOut() cells = {} for j = 0, width - 1 do for n = 0, length - 1 do local i = (j % 2 == 0) and n or (length - 1 - n) cells[#cells + 1] = { ox + DX[f] * i + DX[r] * j, oz + DZ[f] * i + DZ[r] * j } end end end layOut() local key = F.siteKey("hole", (":%dx%d"):format(width, length)) -- opts.skip: layers someone else already dug here (a helper taking over part of a running hole) local before = math.min(math.max(F.siteDone(key, opts), tonumber(opts.skip) or 0), depth) if before >= depth then logLine(("This hole is already %d deep. Ask for more depth to go further."):format(before)) elseif before > 0 then logLine(("The top %d layers were dug on an earlier run, continuing below them"):format(before)) end local skipped = 0 local top, remaining, reverse = oy - 1 - before, depth - before, false while remaining > 0 do -- Between passes is the one safe moment to hand columns to a helper: the relay asks, we narrow and say from which layer. local limit = currentProgramId and jobLimits[currentProgramId] if limit and tonumber(limit.width) and limit.width >= 1 and limit.width < width then width = math.floor(limit.width) layOut() reverse = false logLine(("Handing the far columns to a helper, keeping %d"):format(width)) end F.sendMsg({ t = "progress", id = currentProgramId, layers = depth - remaining, width = width }) local slab = math.min(3, remaining) -- three layers per pass: the one we travel in, plus above and below local travel = slab == 1 and top or top - 1 for n = 1, #cells do local c = cells[reverse and (#cells + 1 - n) or n] F.checkpoint(job) local ok, err = td.digTo(c[1], travel, c[2]) if not ok and err ~= "Out of fuel" then ok, err = td.goTo(c[1], travel, c[2], { dig = true }) end -- around whatever refused if ok then if slab >= 2 then clear("up") end if slab == 3 then clear("down") end elseif err == "Out of fuel" then F.abort(tostring(err)) else skipped = skipped + 1 -- claimed land, bedrock: leave it and carry on end end top, remaining, reverse = top - slab, remaining - slab, not reverse F.saveSite(key, depth - remaining, opts.resume == false and remaining + slab == depth - before) end if skipped > 0 then logLine(("%d spots could not be dug (protected or unbreakable) and were left alone"):format(skipped), "error") end end) end ---------------------------------------------------------------- td: building --- Go to the supply spot (or home), ask the storage station to put the missing items in the supply chest, take them, come back. --- Go to the supply spot (or home), ask the storage station for the missing items, take them, come back. --- need: item -> how many the job cannot do without; ask (optional): item -> how many to request (need plus spare). function F.restock(job, need, ask) local spot = depots.supply or cfg.home if not spot then F.abort("no supply spot and no home: a build needs somewhere to restock") end logLine("Out of materials, going to restock") --- At the chest: make room, ask storage for what is missing, take it. Returns ok, why. local function fetch() local container = F.findContainer() if not container then return false, "no chest at the supply spot to take materials from" end -- Make room: junk goes into the chest, but fuel and materials stay on board. local selected = native.getSelectedSlot() for slot = 1, 16 do local d = native.getItemDetail(slot) if d and F.matchesAny(d.name, JUNK) and not need[d.name] then native.select(slot) container.drop() end end native.select(selected) local items = {} for name, n in pairs(ask or need) do items[#items + 1] = { name = name, count = n } end F.sendMsg({ t = "need", items = items }) local deadline = os.clock() + 120 local told = false while true do for _ = 1, 16 do if not container.suck() then break end end local have, short = F.stock(), {} for name, n in pairs(need) do if (have[name] or 0) < n then short[#short + 1] = ("%d %s"):format(n - (have[name] or 0), name) end end if #short == 0 then return true end if os.clock() > deadline then return false, "still missing " .. table.concat(short, ", ") .. " (is a storage station with a supply chest online, and does storage have them?)" end if not told then told = true logLine("Waiting at the supply chest for " .. table.concat(short, ", ")) end sleep(3) end end if depots.supply then -- The shared supply chest: through the queue like every shared chest, never digging on the way. local ok, why = td.useDepot("supply", fetch, { back = td.pos() }) if not ok then F.abort(why) end return end -- The chest beside home (no shared supply spot set). local back = td.pos() local arrived = false for attempt = 1, 20 do -- another builder may be at the spot: give it time, then look again local ok, err = td.goTo(spot.x, spot.y, spot.z, { dig = false }) if ok then arrived = true break end if err == "turtle in the way" then if attempt == 1 then logLine("Waiting for another turtle to finish at the supply chest") end sleep(8 + math.random() * 7) else sleep(3) end end if not arrived then F.abort("could not reach the supply chest without digging") end td.face(spot.facing) local ok, why = fetch() if not ok then F.abort(why) end if not td.goTo(back.x, back.y, back.z, { dig = true }) then F.abort("could not get back to the build") end td.face(back.facing) end --- Build a blueprint: bp.palette = { ["B"] = "mod:block" }, bp.layers[y] = { "row strings" } with rows along z --- (forward from the turtle) and characters along x (to the turtle's right). "." or " " = leave alone. --- bp.faces = { ["S"] = 0..3 } (optional): the way to face when placing that kind, relative to the build's forward --- (0 forward, 1 right, 2 back, 3 left), so stairs, furnaces and the like come out turned as captured. --- The turtle starts on the bottom-front-left cell of the build and works up, standing above each layer. --- opts.fromLayer resumes at a layer (1-based); opts.skipExisting leaves blocks already present. function td.build(bp, opts) opts = opts or {} if type(bp) ~= "table" or type(bp.layers) ~= "table" or type(bp.palette) ~= "table" then error("bad blueprint", 0) end return F.runJob(opts.name or "Build", opts, function(job) job.keep = {} for _, id in pairs(bp.palette) do job.keep[id] = true end local ox, oy, oz, f = pos.x, pos.y, pos.z, facing local r = (f + 1) % 4 local placed, skipped = 0, 0 for y = tonumber(opts.fromLayer) or 1, #bp.layers do local rows = bp.layers[y] -- what this layer needs, minus what is on board local need, have = {}, F.stock() for _, row in ipairs(rows) do for i = 1, #row do local id = bp.palette[row:sub(i, i)] if id then need[id] = (need[id] or 0) + 1 end end end local short, ask = {}, {} for id, n in pairs(need) do if (have[id] or 0) < n then short[id] = n - (have[id] or 0) ask[id] = math.min(short[id] + 8, 64 * 4) end -- a little spare, best effort end if next(short) then F.restock(job, short, ask) end logLine(("Layer %d of %d"):format(y, #bp.layers)) local reverse = false for zi = 1, #rows do local row = rows[zi] for step = 1, #row do local xi = reverse and (#row + 1 - step) or step local ch = row:sub(xi, xi) local id = bp.palette[ch] if id then local wx = ox + DX[f] * (zi - 1) + DX[r] * (xi - 1) local wz = oz + DZ[f] * (zi - 1) + DZ[r] * (xi - 1) local wy = oy + (y - 1) F.checkpoint(job) if not td.goTo(wx, wy + 1, wz, { dig = true }) then F.abort(("cannot reach (%d,%d,%d)"):format(wx, wy + 1, wz)) end local has, data = F.inspectDir("down") if has and data.name == id then skipped = skipped + 1 else if has then if F.isProtected(data.name) then F.abort("a protected block is in the way at " .. wx .. "," .. wy .. "," .. wz) end if opts.skipExisting then skipped = skipped + 1 goto continue end tracked.digDown() end if not F.selectItem(id) then F.restock(job, { [id] = need[id] or 1 }) if not F.selectItem(id) then F.abort("no " .. id .. " to place") end end local turn = type(bp.faces) == "table" and tonumber(bp.faces[ch]) or nil if turn then td.face((f + turn) % 4) end if not tracked.placeDown() then F.abort("could not place " .. id .. " at " .. wx .. "," .. wy .. "," .. wz) end placed = placed + 1 if placed % 25 == 0 then logLine(("Layer %d: %d placed"):format(y, placed)) end end end ::continue:: end reverse = not reverse end F.sendMsg({ t = "site", key = ("build:%d,%d,%d:%d:%s"):format(ox, oy, oz, f, tostring(opts.name or "")), done = y }) if opts.pauseEachLayer and y < #bp.layers then -- Give the owner time to right-click the modems of this layer; the relay says "continue" when the new -- barrels show up on the storage network, or when Continue is pressed. buildWaiting = { layer = y, of = #bp.layers } F.sendMsg({ t = "build_wait", layer = y, of = #bp.layers }) logLine(("Layer %d built. Waiting for the modems to be connected (Continue on the website skips the wait)"):format(y)) continueRequested = false while not continueRequested do os.startTimer(2) local ev = os.pullEvent() if ev == "turtledeck_continue" then break end if stopRequested then buildWaiting = nil F.abort("stopped") end end buildWaiting = nil end end logLine(("Build finished: %d placed, %d already there"):format(placed, skipped)) end) end ---------------------------------------------------------------- td: upgrading barrels --- Empty the inventory below into an ender chest placed above (the deposit end of which the storage --- station drains), then swap the block below for `toId`. The turtle stands in an open cell above the barrel. function F.swapBelow(job, fromId, toId, enderId) local function slotsFree() local n = 0 for slot = 1, 16 do if native.getItemCount(slot) == 0 then n = n + 1 end end return n end local function dump() td.setEnderId(enderId) local ok, why = td.dumpViaEnder({ [toId] = true }) if not ok then F.abort(tostring(why)) end end local has, data = F.inspectDir("down") if not has or data.name ~= fromId then return false end -- take everything out, stack by stack for _ = 1, 400 do if slotsFree() < 2 then dump() end if not native.suckDown() then break end end if slotsFree() < 2 then dump() end F.checkpoint(job) if not tracked.digDown() then F.abort("could not break the old barrel") end if not F.selectItem(toId) then F.restock(job, { [toId] = 8 }) if not F.selectItem(toId) then F.abort("no " .. toId .. " to place") end end if not tracked.placeDown() then F.abort("could not place the new barrel") end return true end --- Walk a width x length area (rows away from the turtle, columns to its right) one block above a barrel layer, --- replacing every `from` barrel below with `to`. opts: from, to, ender, width, length. function td.upgradeBarrels(opts) opts = opts or {} local fromId, toId, enderId = opts.from or "sc-goodies:iron_barrel", opts.to or "sc-goodies:diamond_barrel", opts.ender or "sc-goodies:ender_storage" local width, length = math.max(1, opts.width or 10), math.max(1, opts.length or 10) return F.runJob("Upgrade barrels", opts, function(job) if not F.selectItem(enderId) then F.abort("carry an " .. enderId .. " linked to the deposit chest") end local ox, oy, oz, f = pos.x, pos.y, pos.z, facing local r = (f + 1) % 4 local swapped = 0 for j = 0, width - 1 do for n = 0, length - 1 do local i = (j % 2 == 0) and n or (length - 1 - n) local wx, wz = ox + DX[f] * i + DX[r] * j, oz + DZ[f] * i + DZ[r] * j if not td.goTo(wx, oy, wz) then F.abort(("cannot reach %d,%d,%d"):format(wx, oy, wz)) end if F.swapBelow(job, fromId, toId, enderId) then swapped = swapped + 1 end end end logLine(("Upgraded %d barrels"):format(swapped)) -- empty barrels and leftovers ride home in the inventory; runJob unloads them there end) end ---------------------------------------------------------------- fleet: fuel rescue and survey (1.19.0) -- td.fuelRescue: a turtle with fuel fetches some from the shared fuel chest and hands it to a stranded one (the relay -- decides who helps whom). td.survey: fly over an area just above the ground and look at everything, never digging, -- placing or attacking. Everything here is local to this block. do td.FUEL_VALUES = FUEL_VALUES -- fuel per item (defined with td.refuel) local function distTo(p) return math.abs(pos.x - p.x) + math.abs(pos.y - p.y) + math.abs(pos.z - p.z) end --- How far a rescue has got, for the website (the relay reads progress reports of its rescue programs). local function stage(text, extra) if currentProgramId == nil then return end local msg = { t = "progress", id = currentProgramId, stage = text } for k, v in pairs(extra or {}) do msg[k] = v end F.sendMsg(msg) end -- Where to stand next to a turtle to hand it something: offset, and the facing (or up/down) to drop in. local SPOTS = { { 0, 1, 0, "down" }, { 1, 0, 0, 3 }, { -1, 0, 0, 1 }, { 0, 0, 1, 0 }, { 0, 0, -1, 2 }, { 0, -1, 0, "up" } } --- Fetch fuel from the shared fuel chest and hand it to the turtle at x, y, z. opts: x, y, z, need (fuel units it must --- get), name (for messages), dig (false, or "fallback" when it is inside a mine it dug), learn (boxes of that mine's --- corridors, for the route planner), reserve (fuel to top up to for the trip there and home). --- Returns true, count, item; or false and why. function td.fuelRescue(opts) opts = opts or {} local d = depots.fuel if not d then return false, "no fuel chest has been set" end local tx, ty, tz = tonumber(opts.x), tonumber(opts.y), tonumber(opts.z) if not (tx and ty and tz) then return false, "td.fuelRescue: x, y, z of the turtle to help are missing" end local name = tostring(opts.name or "the turtle") local need = math.max(1, math.floor(tonumber(opts.need) or 1)) local dig = opts.dig == "fallback" and "fallback" or false stage("to the fuel chest") local selected = native.getSelectedSlot() local function freeSlot() for s = 1, 16 do if native.getItemCount(s) == 0 then return s end end end local function selectOf(name) for s = 16, 1, -1 do local d = native.getItemDetail(s) if d and d.name == name then native.select(s) return s end end end local function snapshot() local t = {} for s = 1, 16 do local d = native.getItemDetail(s) t[s] = d and { name = d.name, count = d.count } or false end return t end --- Drop up to n of an item (from the fullest-numbered slots first); returns how many went. local function dropItems(name, n, dropFn) local gone = 0 for s = 16, 1, -1 do if gone >= n then break end local d = native.getItemDetail(s) if d and d.name == name then native.select(s) dropFn(math.min(d.count, n - gone)) gone = gone + (d.count - native.getItemCount(s)) end end native.select(selected) return gone end local item, per, count = nil, nil, 0 --- At the fuel chest (its turn in the queue): top itself up for the trip, then take the stranded turtle's share. local function atChest() local chest = F.findContainer() if not chest then return false, F.noChestAt("fuel", d) end local reserve = math.floor(tonumber(opts.reserve) or 0) if reserve > 0 and native.getFuelLevel() ~= "unlimited" and native.getFuelLevel() < reserve then td.takeFuel(reserve) -- enough to get there and home again; the rest of what it took goes back chest = F.findContainer() or chest end -- Its share: one kind of fuel, as few pulls as it takes (a stack a pull, the exact count), into free slots. What -- arrived is worked out from the inventory before and after, since a stack may merge into one already on board. local taken = 0 for _ = 1, 8 do local want = per and math.ceil(need / per) - taken or math.ceil(need / 80) if want <= 0 then break end local s = freeSlot() if not s then break end native.select(s) local before = snapshot() if not chest.suck(math.max(1, math.min(64, want))) then break end local after, name, got = snapshot(), nil, 0 for slot = 1, 16 do local a, b = before[slot], after[slot] local more = (b and b.count or 0) - ((a and b and a.name == b.name) and a.count or 0) if b and more > 0 then name, got = b.name, got + more end end if not name then break end selectOf(name) if not native.refuel(0) then dropItems(name, got, chest.drop) if item then dropItems(item, taken, chest.drop) end return false, "the fuel chest holds something that is not fuel (" .. name .. ")" end if item and name ~= item then dropItems(name, got, chest.drop) break end -- one kind only item, taken = name, taken + got if not per then per = FUEL_VALUES[item] if not per then -- not in the table: burn one and see (the helper keeps that fuel) local was = native.getFuelLevel() selectOf(item) if type(was) == "number" and native.refuel(1) then per = native.getFuelLevel() - was taken = taken - 1 end if not per or per <= 0 then per = 80 end end end end native.select(selected) if not item then return false, "the fuel chest is empty" end count = math.ceil(need / per) if taken < count then dropItems(item, taken, chest.drop) return false, ("the fuel chest has only %d %s; %s needs %d"):format(taken, item, name, count) end if taken > count then dropItems(item, taken - count, chest.drop) end -- the rest goes back F.sendState() return true end -- Through the queue like every trip to a shared chest, never digging; it leaves for the stranded turtle at once. local got, why = td.useDepot("fuel", atChest, { after = "leave" }) if not got then return false, why end stage("on the way", { item = item, count = count }) logLine(("Taking %d %s to %s at %d, %d, %d"):format(count, item, name, tx, ty, tz)) if type(opts.learn) == "table" then td.learn(opts.learn) end -- Stand next to it: cells known to be open first, then unseen ones; solid ones only when digging is allowed. local spots = {} for _, sp in ipairs(SPOTS) do local x, y, z = tx + sp[1], ty + sp[2], tz + sp[3] local seen = known[F.kkey(x, y, z)] if seen == true or seen == nil or (dig and seen == false) then spots[#spots + 1] = { x = x, y = y, z = z, hand = sp[4], rank = (seen == true and 0 or 1000) + distTo({ x = x, y = y, z = z }) } end end table.sort(spots, function(a, b) return a.rank < b.rank end) local at, lastWhy = nil, "walled in" for i = 1, math.min(#spots, 4) do local sp = spots[i] local ok, err = td.goTo(sp.x, sp.y, sp.z, { dig = dig }) if ok then at = sp break end lastWhy = err if err == "Out of fuel" then return false, "Out of fuel on the way to " .. name end end if not at then return false, ("could not reach %s at %d, %d, %d (%s): no open way next to it"):format(name, tx, ty, tz, tostring(lastWhy)) end local look, drop = "front", native.drop if at.hand == "down" then look, drop = "down", native.dropDown elseif at.hand == "up" then look, drop = "up", native.dropUp else td.face(at.hand) end local has, data = F.inspectDir(look) if not (has and F.isTurtle(data.name)) then return false, ("%s is not at %d, %d, %d any more"):format(name, tx, ty, tz) end local given = dropItems(item, count, drop) -- into the other turtle's inventory native.select(selected) F.sendState() if given == 0 then return false, name .. " has no room for fuel: its inventory is full" end stage("delivered", { item = item, count = given }) logLine(("Handed %d %s to %s"):format(given, item, name)) return true, given, item end -- Survey ---------------------------------------------------------------------------------------------------------- local active -- the survey running now: which blocks it has seen local function noteSeen() if not active then return end for _, dir in ipairs({ "front", "up", "down" }) do local l = lastLook[dir] if l and l.name then local k = F.kkey(l.x, l.y, l.z) if not active.seen[k] then active.seen[k] = true active.blocks = active.blocks + 1 end end end end --- One block, only into air. Another turtle or a mob in the way is waited for, never dug or hit. local function flyMove(dir) local d = DIRS[dir] for attempt = 1, 4 do if native.getFuelLevel() == 0 then return false, "Out of fuel" end local has, data = F.inspectDir(d.look) if has then if not (F.isTurtle(data.name) and attempt < 4) then return false, data.name end sleep(0.5 + math.random()) -- another turtle: it moves on elseif tracked[d.move]() then noteSeen() return true else sleep(0.4) -- air, but something alive stands there end end return false, "blocked" end --- Down onto whatever is below (ground, water, a roof), at most maxDrop blocks, then up to `clear` above it. local function settle(sv) local dropped = 0 while dropped < sv.maxDrop and pos.y > sv.floor do if not flyMove("down") then break end dropped = dropped + 1 end for _ = 2, sv.clear do if pos.y >= sv.ceiling or not flyMove("up") then break end end end --- One block ahead: climb over what is in the way (at most maxClimb), then settle. On failure it settles back down. local function flyStep(sv) local climbed = 0 while true do local ok, why = flyMove("forward") if ok then break end if why == "Out of fuel" then return false, why end local up, upWhy = false, "too high to climb" if climbed < sv.maxClimb and pos.y < sv.ceiling then up, upWhy = flyMove("up") end if not up then if upWhy == "Out of fuel" then return false, upWhy end settle(sv) return false, climbed >= sv.maxClimb and "too high to climb" or "boxed in" end climbed = climbed + 1 end settle(sv) return true end --- To the column x, z: the longer axis first, the other when that is blocked, a step aside as a last resort. local function flyTo(sv, x, z) local budget = (math.abs(pos.x - x) + math.abs(pos.z - z)) * 3 + 24 local prev while pos.x ~= x or pos.z ~= z do budget = budget - 1 if budget < 0 then return false, "no way through" end local dx, dz = x - pos.x, z - pos.z local ax, az = dx ~= 0 and (dx > 0 and 1 or 3) or nil, dz ~= 0 and (dz > 0 and 2 or 0) or nil local order = {} local function add(f) if f then order[#order + 1] = f end end if math.abs(dx) >= math.abs(dz) then add(ax) add(az) else add(az) add(ax) end add((order[1] + 1) % 4) add((order[1] + 3) % 4) local moved, why = false, nil for _, f in ipairs(order) do local nx, nz = pos.x + DX[f], pos.z + DZ[f] if not (prev and prev[1] == nx and prev[2] == nz) then -- never straight back where it came from local here = { pos.x, pos.z } td.face(f) local ok, err = flyStep(sv) if ok then moved, prev = true, here break end why = err if err == "Out of fuel" then return false, err end end end if not moved then return false, why or "boxed in" end end return true end --- Before each cell: enough fuel to get back to the fuel chest (or home)? Refuel from the inventory, else fly to the --- fuel chest without digging and come back. A survey that cannot aborts with a fuel error: the relay's fuel rescue --- takes it from there. local function surveyFuel(sv) local fuel = native.getFuelLevel() if fuel == "unlimited" then return end local d = depots.fuel local back = d or cfg.home -- the way back, plus room for a few climbs that come to nothing local need = (back and distTo(back) or 0) + 60 + 4 * sv.maxClimb if fuel >= need then return end if td.refuel(need + 400) then return end if not d then F.abort("low fuel and no fuel chest is set") end if native.getFuelLevel() < distTo(d) + 5 then F.abort("low fuel: cannot reach the fuel chest") end logLine("Survey: low on fuel, flying to the fuel chest") local here = td.pos() local limit = native.getFuelLimit and native.getFuelLimit() or 20000 -- Through the queue, never digging, and back to this cell afterwards. local ok, why = td.refuelAtDepot(math.min(limit, math.max(need * 3, 2000)), { back = here }) if not ok and tostring(why):find("could not get", 1, true) then F.abort("could not get back to the survey after refuelling: " .. tostring(why)) end if not ok and tostring(why):find("could not reach", 1, true) then F.abort("low fuel: " .. tostring(why)) end if native.getFuelLevel() < distTo(here) + 40 then F.abort("low fuel: the fuel chest did not help") end end local function num(v, lo, hi, dflt) v = tonumber(v) if not v then return dflt end return math.min(hi, math.max(lo, math.floor(v))) end --- Fly over an area and look at everything: the ground below, what is ahead, what is above, with block state (the --- same inspect path as every move). Never digs, places or attacks: it climbs over what is in the way (trees, --- walls), moves only into air (never into water or lava) and skips what it cannot get around, saying so. --- opts: x, z (first cell), dir (travel facing), side (facing the columns step towards), length (cells per column), --- width (columns), clearance (blocks above the ground, 1 = right above it), maxClimb, maxDrop, key (progress --- memory), resume, via (x, y, z to pass through when the area cannot be flown to directly), returnHome. --- Columns are flown back and forth. Returns true, { cells, of, blocks, skipped }; or false and why. function td.survey(opts) opts = opts or {} local dir = num(opts.dir, 0, 3, facing) local side = num(opts.side, 0, 3, (dir + 1) % 4) local length, width = num(opts.length, 1, 256, 16), num(opts.width, 1, 256, 1) local sx, sz = num(opts.x, -30000000, 30000000, pos.x), num(opts.z, -30000000, 30000000, pos.z) local sv = { clear = num(opts.clearance, 1, 8, 1), maxClimb = num(opts.maxClimb, 1, 64, 24), maxDrop = num(opts.maxDrop, 1, 64, 32), ceiling = 318, floor = -62, seen = {}, blocks = 0, skipped = 0, cells = 0 } local key = opts.key and tostring(opts.key) or ("survey:%d,%d:%d:%d:%dx%d"):format(sx, sz, dir, side, width, length) local total = length * width local lastReport = -100 local function report(force) if not force and sv.cells + sv.skipped - lastReport < 16 then return end lastReport = sv.cells + sv.skipped if currentProgramId ~= nil then F.sendMsg({ t = "progress", id = currentProgramId, cells = sv.cells, of = total, seen = sv.blocks, skipped = sv.skipped }) end end local wasActive, wasPeaceful = active, peaceful active, peaceful = sv, { id = currentProgramId } local ok, err = pcall(function() local before = math.min(F.siteDone(key, opts), width) sv.cells = before * length if before > 0 then logLine(("Survey: %d of %d columns were flown on an earlier run, continuing"):format(before, width)) end logLine(("Survey: %d x %d cells, %d above the ground"):format(width, length, sv.clear)) report(true) for j = before, width - 1 do local cells = {} for i = 0, length - 1 do local ii = (j % 2 == 0) and i or (length - 1 - i) cells[#cells + 1] = { sx + DX[dir] * ii + DX[side] * j, sz + DZ[dir] * ii + DZ[side] * j } end local travel = (j % 2 == 0) and dir or (dir + 2) % 4 -- The first cell of the column it can get to. local n, why for k = 1, math.min(3, #cells) do surveyFuel(sv) local reached reached, why = flyTo(sv, cells[k][1], cells[k][2]) if not reached and why ~= "Out of fuel" and not sv.triedVia and type(opts.via) == "table" and tonumber(opts.via.x) then sv.triedVia = true -- once: through where the job started (the lead turtle stood there, so it is open) if td.goTo(tonumber(opts.via.x), tonumber(opts.via.y), tonumber(opts.via.z), { dig = false }) then reached, why = flyTo(sv, cells[k][1], cells[k][2]) end end if why == "Out of fuel" then F.abort("Out of fuel") end if reached then n = k break end end if not n then sv.skipped = sv.skipped + #cells logLine(("Survey: could not get to column %d (%s), skipped it"):format(j + 1, tostring(why)), "error") else settle(sv) sv.skipped = sv.skipped + (n - 1) sv.cells = sv.cells + 1 while n < #cells do surveyFuel(sv) td.face(travel) noteSeen() local stepped, stepWhy = flyStep(sv) if stepped then n = n + 1 sv.cells = sv.cells + 1 else if stepWhy == "Out of fuel" then F.abort("Out of fuel") end local blocked, around = cells[n + 1], nil for k = n + 2, math.min(n + 4, #cells) do -- around it, to a cell beyond local got, gotWhy = flyTo(sv, cells[k][1], cells[k][2]) if got then around = k break end if gotWhy == "Out of fuel" then F.abort("Out of fuel") end end if around then logLine(("Survey: went around %s at %d, %d (%d cell%s skipped)"):format(stepWhy, blocked[1], blocked[2], around - n - 1, around - n - 1 == 1 and "" or "s")) sv.skipped = sv.skipped + (around - n - 1) sv.cells = sv.cells + 1 n = around else logLine(("Survey: boxed in near %d, %d, %d (%s): skipped the rest of column %d (%d cells)"):format(pos.x, pos.y, pos.z, stepWhy, j + 1, #cells - n), "error") sv.skipped = sv.skipped + (#cells - n) n = #cells end end report() end end F.saveSite(key, j + 1, opts.resume == false and j == before) report(true) end logLine(("Survey finished: %d of %d cells flown over, %d blocks seen%s"):format(sv.cells, total, sv.blocks, sv.skipped > 0 and (", " .. sv.skipped .. " skipped (boxed in)") or "")) end) active, peaceful = wasActive, wasPeaceful if not ok then if type(err) == "table" and err.turtledeckAbort then report(true) logLine("Survey stopped early: " .. err.turtledeckAbort, "error") return false, err.turtledeckAbort end error(err, 0) end if opts.returnHome == true and cfg.home then local home, homeWhy = td.goHome({ dig = false }) if not home then logLine("Could not get home without digging: " .. tostring(homeWhy), "error") end end return true, { cells = sv.cells, of = total, blocks = sv.blocks, skipped = sv.skipped } end end ---------------------------------------------------------------- commands function F.scanAround() for _ = 1, 4 do tracked.turnRight() end F.inspectDir("up"); F.inspectDir("down") F.sendState() return true end --- Uses an Advanced Peripherals Geo Scanner if one is attached. function F.geoScan(radius) local scanner = peripheral.find("geoScanner") or peripheral.find("geo_scanner") if not scanner then return false, "No geo scanner attached" end local found, err = scanner.scan(math.min(tonumber(radius) or 8, 16)) if not found then return false, err end for _, b in ipairs(found) do if not (b.x == 0 and b.y == 0 and b.z == 0) then F.noteBlock(pos.x + b.x, pos.y + b.y, pos.z + b.z, b.name) end if #pendingBlocks >= 2000 then F.sendState() end end F.sendState() return true, #found end function F.jsonSafe(v) local t = type(v) if t == "nil" or t == "boolean" or t == "number" or t == "string" then return v end local ok, s = pcall(textutils.serialize, v) return ok and s or tostring(v) end --- Home (and its chest) were recorded in the old frame of reference: move them with a position correction. function F.shiftHome(dx, dy, dz) for _, p in ipairs({ cfg.home or false, cfg.homeChest or false }) do if p then p.x, p.y, p.z = p.x + dx, p.y + dy, p.z + dz end end end local continueRequested = false -- set by a "continue" message from the website / relay local restarting = false -- set by the update command: leave the main loop, then run the new version local special = { scan = F.scanAround, geoscan = F.geoScan, refresh = function() F.lookAround(); F.scanHomeChest(); F.sendState(true); return true end, -- Update from the website and restart, without anyone touching the turtle. update = function() local result, why = F.installLatest() if not result then return false, why end if result == "current" then return true, "Already up to date (" .. VERSION .. ")" end restarting = true os.queueEvent("turtledeck_tick") return true, "Updated from " .. VERSION .. ", restarting" end, setWorld = function(name) name = F.cleanWorld(name) if not name then return false, "world names use letters, digits, _ : - ." end cfg.world, cfg.worldManual = name, true F.saveConfig() known, knownCount = {}, 0 -- what was seen belongs to the old world td.forgetSites() F.lookAround(); F.sendState() return true, "World set to " .. name end, craft = function(times) -- a crafty turtle with the grid already staged by the storage station if not native.craft then return false, "not a crafty turtle" end local selected = native.getSelectedSlot() native.select(16) -- results go to the selected slot when it is outside the grid local ok, err = native.craft(math.max(1, math.floor(tonumber(times) or 1))) native.select(selected) F.sendState(true) if not ok then return false, err end return true, { slots = (F.getInventory()) } -- the station pulls these exact slots: a turtle over a wired modem may not offer list() end, setEnderId = function(id) id = tostring(id or ""):gsub("[^%w_:%-%./]", "") if id == "" then return false, "bad item id" end ENDER_ID, cfg.enderId = id, id F.saveConfig() return true, "Ender chest item is " .. id end, setHome = function() return td.setHome() end, forgetMap = function() known, knownCount = {}, 0 F.lookAround(); F.sendState() return true end, relocate = function() local ox, oy, oz = pos.x, pos.y, pos.z if not F.locateWithGps() then return false, "No GPS fix. Is a wireless modem equipped and a GPS constellation in range?" end F.shiftHome(pos.x - ox, pos.y - oy, pos.z - oz) known, knownCount = {}, 0 td.forgetSites() -- they were recorded at the old coordinates F.savePosition(); F.lookAround(); F.sendState() return true, ("%d %d %d facing %s"):format(pos.x, pos.y, pos.z, FACING_NAMES[facing]) end, clearHome = function() cfg.home, cfg.homeChest = nil, nil; F.saveConfig(); F.sendState(); return true end, setPosition = function(x, y, z, f) local ox, oy, oz = pos.x, pos.y, pos.z pos.x, pos.y, pos.z = tonumber(x) or pos.x, tonumber(y) or pos.y, tonumber(z) or pos.z F.shiftHome(pos.x - ox, pos.y - oy, pos.z - oz) known, knownCount = {}, 0 td.forgetSites() facing = (tonumber(f) or facing) % 4 located = "manual" F.savePosition(); F.lookAround(); F.sendState() return true end, writeFile = function(name, content) name = tostring(name or ""):gsub("[^%w%._%-/]", "") if name == "" then return false, "bad file name" end local f = fs.open(name, "w") f.write(tostring(content or "")) f.close() return true, name end, eval = function(code) local env = setmetatable({ td = td }, { __index = _ENV }) local fn = load("return " .. tostring(code), "=eval", "t", env) or load(tostring(code), "=eval", "t", env) if not fn then local _, err = load(tostring(code), "=eval", "t", env) return false, err end local r = table.pack(pcall(fn)) if not r[1] then return false, r[2] end local out = {} for i = 2, r.n do out[#out + 1] = tostring(F.jsonSafe(r[i])) end return true, table.concat(out, ", ") end, } -- Commands a relay marks `once` have ids that are never reused. One that arrives again (a relay that took over after a -- restart repeats what it had no answer for) is not run again: its answer is sent again, or, while it is still queued -- or running, comes when it is done. local answered, answeredOrder = {}, {} -- id -> true (queued / running) or the final message function F.noteAnswer(id, v) if answered[id] == nil then answeredOrder[#answeredOrder + 1] = id end answered[id] = v while #answeredOrder > 64 do local old = table.remove(answeredOrder, 1) if answered[old] == true then answeredOrder[#answeredOrder + 1] = old break end -- still running: keep it answered[old] = nil end end function F.answer(job, msg) if job.once and job.id ~= nil then F.noteAnswer(job.id, msg) end F.sendMsg(msg) end function F.runCommand(job) local fn = special[job.op] or tracked[job.op] or (native[job.op] and turtle[job.op]) if not fn then return F.answer(job, { t = "result", id = job.id, ok = false, error = "unknown op " .. tostring(job.op) }) end local r = table.pack(pcall(fn, table.unpack(job.args or {}))) if not r[1] then F.answer(job, { t = "result", id = job.id, ok = false, error = tostring(r[2]) }) elseif r[2] == false then F.answer(job, { t = "result", id = job.id, ok = false, error = tostring(r[3] or "failed") }) else F.answer(job, { t = "result", id = job.id, ok = true, value = F.jsonSafe(r[3] ~= nil and r[3] or r[2]) }) end end ---------------------------------------------------------------- running programs local queue = {} local stopRequested = false function logLine(text, level) F.sendMsg({ t = "log", text = text, level = level or "info" }) end --- Runs fn as a coroutine we can abandon when the website presses Stop. function F.runAbortable(fn) local co = coroutine.create(fn) local ok, filter = coroutine.resume(co) while ok and coroutine.status(co) ~= "dead" do local ev = table.pack(os.pullEventRaw()) -- Never abandon a move half way: the position would be lost. if stopRequested and not busyNative then return false, "Stopped" end if filter == nil or ev[1] == filter or ev[1] == "terminate" then ok, filter = coroutine.resume(co, table.unpack(ev, 1, ev.n)) end F.flushMirrors() end if not ok then return false, tostring(filter) end return true end function F.runProgram(job) local function out(...) local parts = table.pack(...) for i = 1, parts.n do parts[i] = tostring(parts[i]) end return table.concat(parts, "\t") end local env = setmetatable({ print = function(...) logLine(out(...)); return print(...) end, write = function(s) logLine(tostring(s)); return write(s) end, printError = function(...) logLine(out(...), "error"); return printError(...) end, td = td, }, { __index = _ENV }) env._ENV = env local fn, err = load(job.code, "=" .. (job.name or "program"), "t", env) if not fn then F.answer(job, { t = "run", id = job.id, name = job.name, status = "error", error = tostring(err) }) return end stopRequested = false currentProgramId, currentProgramName = job.id, job.name F.sendMsg({ t = "run", id = job.id, name = job.name, status = "started" }) local ok, runErr = F.runAbortable(fn) F.flushMirrors(true) -- the last picture stays on the map (as it does on the monitor) mirrors = {} if ok then F.answer(job, { t = "run", id = job.id, name = job.name, status = "finished" }) elseif runErr == "Stopped" then F.answer(job, { t = "run", id = job.id, name = job.name, status = "stopped" }) else F.answer(job, { t = "run", id = job.id, name = job.name, status = "error", error = runErr }) end stopRequested = false buildWaiting = nil depotLeave(ok and nil or "the program ended") -- stopped (or failed) while in line or at a chest: out of the queue pausedIds[job.id] = nil currentProgramId, currentProgramName = nil, nil jobLimits = {} F.planFence, F.planProtect = nil, {} -- a plan's area rules and protected blocks last as long as its program F.sendState(true) end ---------------------------------------------------------------- main loops local quit = false local unlinking = false local relayRestarting = false -- the relay said it is restarting: reconnect soon, it is not an error function F.reader(url) while true do local ev = table.pack(os.pullEventRaw()) if unlinking and not busyNative then -- never walk away mid-move: the position would be lost cfg.key = nil F.saveConfig() quit = true return end if restarting and not busyNative then quit = true return end if ev[1] == "websocket_message" and ev[2] == url then local msg = textutils.unserializeJSON(ev[3] or "") if type(msg) == "table" then if msg.t == "continue" then continueRequested = true os.queueEvent("turtledeck_continue") elseif msg.t == "site" and msg.key ~= nil then os.queueEvent("turtledeck_site", msg.key, tonumber(msg.done) or 0) elseif msg.t == "config" and type(msg.depots) == "table" then if type(msg.enderId) == "string" and msg.enderId ~= "" then ENDER_ID = msg.enderId cfg.enderId = ENDER_ID end F.applyDepots(msg.depots) elseif msg.t == "route" and msg.id ~= nil then if routeWaiting == msg.id then routeAnswer = msg os.queueEvent("turtledeck_route", msg.id) end elseif msg.t == "depot" and msg.id ~= nil then -- the relay's word on a turn at a shared chest: kept per ticket, the program waiting for it picks it up if depotState.ticket and depotState.ticket.id == msg.id then msg.fresh = true depotState.answers[msg.id] = msg os.queueEvent("turtledeck_depot", msg.id) end elseif msg.t == "limit" and msg.id ~= nil then jobLimits[msg.id] = { width = tonumber(msg.width) } elseif msg.t == "pause" and msg.id ~= nil then pausedIds[msg.id] = msg.paused ~= false or nil os.queueEvent("turtledeck_pause") elseif msg.t == "peers" and type(msg.list) == "table" then peers = {} for _, p in ipairs(msg.list) do if tonumber(p.id) and tonumber(p.x) and tonumber(p.y) and tonumber(p.z) then peers[p.id] = { x = p.x, y = p.y, z = p.z } end end elseif msg.t == "peer" and msg.id ~= nil then if msg.gone or not (tonumber(msg.x) and tonumber(msg.y) and tonumber(msg.z)) then peers[msg.id] = nil else peers[msg.id] = { x = msg.x, y = msg.y, z = msg.z } end elseif msg.t == "unlink" then -- Deactivated from the website: stop work, forget the key, leave. stopRequested, unlinking, queue = true, true, {} os.queueEvent("turtledeck_tick") elseif msg.t == "stop" then stopRequested = true os.queueEvent("turtledeck_pause") -- a paused program is waiting for an event: this one ends it for _, j in ipairs(queue) do if j.once and answered[j.id] == true then answered[j.id] = nil end end queue = {} elseif msg.t == "cmd" or msg.t == "exec" then local seen = msg.once and msg.id ~= nil and answered[msg.id] if type(seen) == "table" then -- done already: answer again local again = {} for k, v in pairs(seen) do if k ~= "seq" then again[k] = v end end F.sendMsg(again) elseif not seen then if msg.once and msg.id ~= nil then F.noteAnswer(msg.id, true) end queue[#queue + 1] = msg os.queueEvent("turtledeck_job") end elseif msg.t == "ack" then F.acked(msg.seq) elseif msg.t == "restarting" then relayRestarting = true end end elseif ev[1] == "websocket_closed" and ev[2] == url then return elseif ev[1] == "turtle_inventory" then -- Never a turtle call in here: while one waits for its answer, CC hands every other event (a message from the -- relay) to no one. The chores coroutine sends the report. F.chore(false, false) elseif ev[1] == "terminate" then quit = true return end end end function F.worker() while true do while #queue == 0 do os.pullEventRaw("turtledeck_job") end local job = table.remove(queue, 1) if job.t == "exec" then F.runProgram(job) else F.runCommand(job) end end end --- Reports asked for by the link: a look around after a reconnect (only when idle), and a state report. function F.choresLoop() while true do os.pullEventRaw("turtledeck_chore") while chores.state do local look, force = chores.look, chores.force chores.look, chores.state, chores.force = false, false, false if look and not currentProgramId and #queue == 0 and not busyNative then F.lookAround() end if not busyNative then F.sendState(force) end -- a turtle call in progress reports when it is done end end end function F.connect() local url = RELAY_URL .. "/turtle" local sock, err = http.websocket(url) if not sock then return false, err end -- ws stays unset until the relay welcomes us: whatever the program says meanwhile waits in the outbox. The hello says -- which program is still running (the relay picks its job up again) and where the numbered reports got to. pcall(sock.send, textutils.serializeJSON({ t = "hello", key = cfg.key, version = VERSION, computerId = os.getComputerID(), label = os.getComputerLabel() or false, world = cfg.world or "default", state = F.getState(), upgrades = F.getUpgrades(), inventory = (F.getInventory()), session = SESSION, resume = true, job = currentProgramId ~= nil and { id = currentProgramId, name = currentProgramName, buildWait = buildWaiting } or nil, })) local reply = sock.receive(10) local msg = reply and textutils.unserializeJSON(reply) if type(msg) ~= "table" or msg.t ~= "welcome" then pcall(sock.close) if type(msg) == "table" and msg.t == "denied" then return false, msg.reason, true end return false, "no welcome from relay" end ws = sock relayAcks = msg.resume == true relayRoutes = msg.routes == true depotState.queue = msg.depotQueue == true -- The shared chests come with the welcome (1.19.1+ relays): read here, they cannot be missed. if type(msg.depots) == "table" then F.applyDepots(msg.depots) end return url, tonumber(msg.seq) end term.clear() term.setCursorPos(1, 1) print("TurtleDeck " .. VERSION) F.locate() F.installTracking() --- Keeps the link to the relay: connects, reads, and reconnects when it drops. The worker (programs and commands) --- runs beside it and carries on while the relay is away. function F.connection() local backoff, linked = 1, false while not quit do if (restarting or unlinking) and not busyNative then quit = true break end local url, detail, fatal = F.connect() -- detail: the relay's last seq, or why it failed if url then backoff = 1 if linked then print(relayRestarting and "Relay restarted. Back online." or "Reconnected.") else print("Linked. Control me from the website.") print("Hold Ctrl+T to quit.") end linked, relayRestarting = true, false lastInvSig = nil for _, m in pairs(mirrors) do m.full, m.rows = true, {} end -- the relay may have forgotten the frames F.flushOutbox(tonumber(detail)) -- A turn at a shared chest this turtle is waiting for, or using: said again (a new relay knows nothing of it). if depotState.ticket and depotState.queue then depotEnter() end -- Straight to reading: whatever the relay sends right after its welcome (shared chests, a step it repeats, a -- stop) would be lost while a turtle call here waited for its answer. The look and the report come from chores. F.chore(true, true) F.reader(url) pcall(ws.close) ws = nil if unlinking then print("Deactivated from the website. Run turtledeck to link again.") elseif not quit then print(relayRestarting and "Relay restarting, reconnecting..." or "Connection lost. Reconnecting...") if currentProgramId then print("(the program keeps running)") end if relayRestarting then sleep(0.5 + math.random() * 1.5) end -- the new relay is up in a moment; spread the turtles out end elseif fatal and tostring(detail):find("Too many turtles", 1, true) then -- The account is at a turtle limit: the key is fine, so keep it and try again later. printError("Link refused: " .. tostring(detail)) print("Retrying in a minute.") sleep(60) elseif fatal then printError("Link refused: " .. tostring(detail)) print("Run: turtledeck ") cfg.key = nil F.saveConfig() quit = true else printError("Can't reach relay: " .. tostring(detail)) sleep(backoff) backoff = math.min(backoff * 2, relayRestarting and 4 or 30) end end end function F.main() parallel.waitForAny(F.connection, F.worker, F.choresLoop) end local ok, mainErr = pcall(F.main) F.removeTracking() if ws then pcall(ws.close) end if restarting and shell then print("TurtleDeck updated, restarting...") shell.run("/" .. shell.getRunningProgram(), table.unpack(args)) return end if not ok and mainErr ~= "Terminated" then printError(mainErr) end print("TurtleDeck stopped.") ]=]) f.close() print("Installed /turtledeck.lua") shell.run("/turtledeck.lua", ...)