Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- term.clear()
- -- API Initialization
- if api then os.unloadAPI("api.lua") end
- if not os.loadAPI("api.lua") then error("missing Des/warpdrive/api") end
- local w = api.w
- local data
- --THIS PROGRAM HAS BEEN MODIFIED TO SUPPORT MULTIPLE WARPDRIVE CORES.
- --THIS PROGRAM HAS BEEN MODIFIED TO INCLUDE AN AUTOPILOT THAT IS NOT PROPERLY IMPLEMENTED
- --modified by discord@thisismylegacy
- debug = false
- ----------- Ship support
- local ship
- local ship_front = 0
- local ship_right = 0
- local ship_up = 0
- local ship_back = 0
- local ship_left = 0
- local ship_down = 0
- local ship_isInHyper = false
- local ship_x, ship_y, ship_z = 0, 0, 0
- local ship_xTarget, ship_yTarget, ship_zTarget = 0, 0, 0
- local ship_actualDistance = 0
- local ship_energyRequired = 0
- local ship_movement = { 0, 0, 0 }
- local ship_rotationSteps = 0
- local ship_indexPlayer = 0
- local ship_arrayPlayers = { }
- local ship_indexTarget = 0
- local ship_indexCore = 0
- local name = "<@>" -- Discord ID
- local uri = "https://disco" -- Discord Uri
- local lever = "front" -- format: front,back,left,right,top,bottom ONLY
- local failping = 0 -- format: Will ping on Failed node execution 0 = Dont Ping, 1 = Ping
- local navdatafile = ".navdata"
- local navbackup = ".navbackup"
- local navdata={} -- format: {{dx,dy,dz},{dx,dy,dz},...} -- these are ship coords (forward, up, right)
- local cores = {} -- cores table for multicore processing
- local corePositions = {} -- table for handling core positions || *usually for recovery purposes...
- local coreVectors = {} -- table for handling core movement vectors || *usually for recovery purposes...
- local errors = {} -- 10% rule... (table to drop errors into)
- local relativeCoreName = {}
- local savedPositions = {}
- local currentPositions = {}
- local base_url="http://Gateburn.asuscomm.com/api/" local get_command_url=base_url.."coregetCommand" local post_result_url=base_url.."corecommandResult" local core_update_url=base_url.."coreupdate" local cc_id=os.getComputerLabel() local CorePosx,CorePosy,CorePosz=0,0,0 local CoreVecx,CoreVecy,CoreVecz=0,0,0 function coreupdate() local jsonTable=textutils.serializeJSON({id=tostring(cc_id),CorePos=corePositions,CoreVec=coreVectors}) local response=http.post(core_update_url,jsonTable,{["Content-Type"]="application/json"}) if response then if debug == true then print("Core update posted successfully.") end response.close() else if debug == true then print("Failed to post core update.") else end end end
- function ship_read(parData)
- data = parData
- end
- function ship_name(parName)
- if ship == nil or ship.isInterfaced() == nil then
- return ''
- end
- return ship.name(parName)
- end
- local delayedCoreFilename = "delayedCore.txt"
- function saveDelayedCore()
- local file = fs.open(delayedCoreFilename, "w")
- if delayedCore then
- file.write(delayedCore.address)
- else
- file.write("")
- end
- file.close()
- end
- function loadDelayedCore()
- if fs.exists(delayedCoreFilename) then
- local file = fs.open(delayedCoreFilename, "r")
- local address = file.readLine()
- file.close()
- if #address > 0 then
- for _, core in ipairs(cores) do
- if core.address == address then
- delayedCore = core
- break
- end
- end
- end
- end
- end
- function ship_register()
- -- Define a function to register a new core and its device
- local function registerCore(deviceType, address, wrap)
- local core = {
- address = address,
- deviceType = deviceType,
- wrapper = wrap
- }
- table.insert(cores, core)
- numOfCores = #cores
- ConnectedCores = tostring(numOfCores)
- end
- -- Ensure numOfCores is initialized
- if numOfCores == nil then numOfCores = 0 end
- numOfCores = #cores
- ConnectedCores = tostring(numOfCores)
- -- Advanced proxy table to handle calls across all cores
- local shipProxy = {}
- local shipProxyMeta = {
- __index = function(t, key)
- return function(...)
- local args = {...}
- local results = {}
- local threads = {}
- local co
- -- Create coroutines for each core
- for _, core in ipairs(cores) do
- if core.wrapper[key] then
- co = coroutine.create(function()
- -- Apply delay to the selected core
- if delayedCore and core.address == delayedCore.address then
- os.sleep(10) -- 10 second delay
- end
- local result = { pcall(core.wrapper[key], table.unpack(args)) }
- local success = table.remove(result, 1)
- if success then
- if #result > 0 then
- table.insert(results, result)
- end
- else
- print("Error calling method " .. key .. " on core " .. core.address)
- end
- end)
- table.insert(threads, co)
- end
- end
- -- Resume coroutines to run them concurrently
- for _, co in ipairs(threads) do
- coroutine.resume(co)
- end
- -- If we got results, return the first successful result set
- if #results > 0 then
- return table.unpack(results[1])
- end
- end
- end
- }
- setmetatable(shipProxy, shipProxyMeta)
- -- Register warp drive devices
- w.device_register("warpdriveShipController", registerCore, function() end)
- w.device_register("warpdriveShipCore", registerCore, function() end)
- -- Event hooks
- w.event_register("shipCoreCooldownDone", function()
- w.status_showWarning("Ship core cooldown done")
- return false
- end)
- -- Data hooks
- w.data_register("ship", ship_read, nil, ship_name)
- -- Point 'ship' variable to the ship proxy
- ship = shipProxy
- loadDelayedCore()
- end
- function computeCoresCenter()
- local totalX, totalY, totalZ, numOfCores = 0, 0, 0, #cores
- for _, core in ipairs(cores) do
- local x, y, z = core.wrapper.getLocalPosition() -- Get local positions
- if x == nil or y == nil or z == nil then
- x, y, z = 0, 0, 0
- end
- totalX = totalX + x
- totalY = totalY + y
- totalZ = totalZ + z
- end
- local centerX = totalX / numOfCores
- local centerY = totalY / numOfCores
- local centerZ = totalZ / numOfCores
- return centerX, centerY, centerZ
- end
- local function savePositions(positions)
- local file = fs.open("Relpositions.dat", "w")
- if file then
- file.write(textutils.serialize(positions))
- file.close()
- else
- print("Error: Failed to open 'Relpositions.dat' for writing.")
- end
- end
- local function loadPositions()
- if fs.exists("Relpositions.dat") then
- local file = fs.open("Relpositions.dat", "r")
- local content = file.readAll()
- file.close()
- return textutils.unserialize(content)
- else
- return nil
- end
- end
- function printSavedPos()
- local positions = loadPositions()
- if not positions then
- print("No saved positions found.")
- return
- end
- print("Saved core positions:")
- for coreName, pos in pairs(positions) do
- print(string.format(" %s: X=%d Y=%d Z=%d", coreName, pos.relativeCoreX, pos.relativeCoreY, pos.relativeCoreZ))
- end
- end
- --====================================
- -- WarpDrive Core Position System
- --====================================
- local anchor = peripheral.find("warpdriveSiren")
- if not anchor then
- print("Error: No warpdriveSiren anchor found!")
- return
- end
- --============================
- -- INTERNAL HELPERS
- --============================
- -- Get all cores we care about
- local function getrelativeCores()
- local relativeCores = {}
- for _, name in ipairs(peripheral.getNames()) do
- local type = peripheral.getType(name)
- if type == "warpdriveShipCore" or type == "warpdriveShipController" then
- table.insert(relativeCores, {
- name = name,
- relativeCore = peripheral.wrap(name)
- })
- end
- end
- return relativeCores
- end
- -- Get position relative to anchor
- local function getRelativePosition(anchor, core)
- local ax, ay, az = anchor.getLocalPosition()
- local cx, cy, cz = core.getLocalPosition()
- return {
- relativeCoreX = cx - ax,
- relativeCoreY = cy - ay,
- relativeCoreZ = cz - az
- }
- end
- -- Compare two positions
- local function positionsMatch(a, b)
- return a.relativeCoreX == b.relativeCoreX and
- a.relativeCoreY == b.relativeCoreY and
- a.relativeCoreZ == b.relativeCoreZ
- end
- local function comparePositions(savedPositions, currentPositions)
- local errors = {} --Table to store all errors
- for relativeCoreName, savedPos in pairs(savedPositions) do
- if currentPositions[relativeCoreName] then
- local currentPos = currentPositions[relativeCoreName]
- if savedPos.relativeCoreX ~= currentPos.relativeCoreX or
- savedPos.relativeCoreY ~= currentPos.relativeCoreY or
- savedPos.relativeCoreZ ~= currentPos.relativeCoreZ then
- --Add mismatch error to the list
- table.insert(errors, string.format("Position mismatch for core '%s':", relativeCoreName))
- table.insert(errors, string.format(" Saved: x=%d y=%d z=%d", savedPos.relativeCoreX, savedPos.relativeCoreY, savedPos.relativeCoreZ))
- table.insert(errors, string.format(" Current: x=%d y=%d z=%d", currentPos.relativeCoreX, currentPos.relativeCoreY, currentPos.relativeCoreZ))
- end
- else
- --Add missing core error to the list
- table.insert(errors, "Error: No position data for core '" .. relativeCoreName .. "' in current positions!")
- end
- end
- --If there were any errors, print them
- if #errors > 0 then
- print("Errors found:")
- for _, errorMsg in ipairs(errors) do
- print(errorMsg)
- end
- return false
- end
- return true
- end
- --============================
- -- checkCorePos
- --============================
- local function checkCorePos()
- local positions = loadPositions()
- local relativeCores = getrelativeCores()
- if positions then
- print("Loaded saved positions:")
- for relativeCoreName, position in pairs(positions) do
- print(string.format("%s: x=%d y=%d z=%d", relativeCoreName, position.relativeCoreX, position.relativeCoreY, position.relativeCoreZ))
- end
- local currentPositions = {}
- for i, relativeCoreData in ipairs(relativeCores) do
- local relativeCoreName = relativeCoreData.name
- currentPositions[relativeCoreName] = getRelativePosition(anchor, relativeCoreData.relativeCore)
- end
- --Compare the saved positions with the current ones
- if not comparePositions(positions, currentPositions) then
- return
- else
- print("Positions match successfully!")
- end
- else
- positions = {}
- local relativeCores = getrelativeCores()
- if #relativeCores == 0 then
- print("Error: No warpdrive ship cores found!")
- return
- end
- for i, relativeCoreData in ipairs(relativeCores) do
- local relativeCoreName = relativeCoreData.name
- positions[relativeCoreName] = getRelativePosition(anchor, relativeCoreData.relativeCore)
- end
- savePositions(positions)
- print("Positions saved for the first time:")
- for relativeCoreName, position in pairs(positions) do
- print(string.format("%s: X=%d Y=%d Z=%d", relativeCoreName, position.relativeCoreX, position.relativeCoreY, position.relativeCoreZ))
- end
- end
- end
- --============================
- -- processRecall
- --============================
- function processRecall()
- local savedPositions = loadPositions()
- if not savedPositions then
- w.status_showWarning("No saved positions!")
- return
- end
- local relativeCores = getrelativeCores()
- if not relativeCores then
- w.status_showWarning("No cores found.")
- return
- end
- local currentPositions = {}
- for _, coreData in ipairs(relativeCores) do
- currentPositions[coreData.name] = getRelativePosition(anchor, coreData.relativeCore)
- end
- local errors = {}
- local erroredCores = identifyErroredCores(savedPositions, currentPositions, errors)
- if #erroredCores == 0 then
- w.status_showSuccess("No position mismatch detected.")
- else
- recallErroredCores(savedPositions, currentPositions)
- end
- end
- --============================
- -- identifyErroredCores
- --============================
- function identifyErroredCores(savedPositions, currentPositions)
- local errored = {}
- for name, savedPos in pairs(savedPositions) do
- local currentPos = currentPositions[name]
- if not currentPos or not positionsMatch(savedPos, currentPos) then
- table.insert(errored, name)
- end
- end
- return errored
- end
- --============================
- -- recallCore
- --============================
- local function recallCore(coreName, savedPos)
- local core = peripheral.wrap(coreName)
- if not core then
- w.status_showWarning("Core not found: " .. coreName)
- return
- end
- local currentX, currentY, currentZ = core.getLocalPosition()
- local anchorX, anchorY, anchorZ = anchor.getLocalPosition()
- local relX = currentX - anchorX
- local relY = currentY - anchorY
- local relZ = currentZ - anchorZ
- local moveX = savedPos.relativeCoreX - relX
- local moveY = savedPos.relativeCoreY - relY
- local moveZ = savedPos.relativeCoreZ - relZ
- w.status_showWarning(string.format("Moving core '%s' by X=%d Y=%d Z=%d", coreName, moveX, moveY, moveZ))
- sleep(2)
- core.movement(moveX, moveY, moveZ)
- core.command("MANUAL", true)
- w.status_showSuccess("Core '" .. coreName .. "' recalled successfully.")
- end
- --============================
- -- recallErroredCores
- --============================
- function recallErroredCores(savedPositions, currentPositions)
- local errored = identifyErroredCores(savedPositions, currentPositions)
- if #errored == 0 then
- w.status_showSuccess("No errored cores.")
- return
- end
- for _, coreName in ipairs(errored) do
- local savedPos = savedPositions[coreName]
- if savedPos then
- recallCore(coreName, savedPos)
- else
- w.status_showWarning("No saved position for core: " .. coreName)
- end
- end
- end
- function ship_boot()
- if ship == nil or ship.isInterfaced() == nil then
- return
- end
- w.setColorNormal()
- w.writeLn("Booting Ship")
- w.write("- acquiring parameters: ")
- ship_front, ship_right, ship_up = ship.dim_positive()
- ship_back, ship_left, ship_down = ship.dim_negative()
- ship_isInHyper = ship.isInHyperspace()
- ship_movement = { ship.movement() }
- ship_rotationSteps = ship.rotationSteps()
- w.setColorSuccess()
- w.writeLn("ok")
- w.setColorNormal()
- w.write("- checking assembly : ")
- local timeout = 10
- local isValid, message
- repeat
- isValid, message = ship.getAssemblyStatus()
- w.sleep(0.05)
- timeout = timeout - 1
- until isValid == true or timeout < 0
- if timeout < 0 then
- w.setColorWarning()
- w.writeLn("failed")
- w.writeLn(message)
- w.setColorNormal()
- w.sleep(3)
- -- don't reboot as the player might need to set new dimensions to fix it
- else
- w.setColorSuccess()
- w.writeLn("passed")
- end
- w.sleep(0.15)
- w.setColorNormal()
- w.write("- celestial position : ")
- timeout = 10
- local pos
- repeat
- pos = ship.getLocalPosition()
- w.sleep(0.05)
- timeout = timeout - 1
- until pos ~= nil or timeout < 0
- if timeout < 0 then
- w.setColorWarning()
- w.writeLn("failed")
- w.writeLn("")
- w.writeLn("Something is wrong here, rebooting...")
- w.setColorNormal()
- w.sleep(2)
- w.reboot()
- else
- w.setColorSuccess()
- w.writeLn("triangulated")
- end
- ship.command("MANUAL", false)
- ship_updateMovementStats()
- w.sleep(0.2)
- w.setColorNormal()
- w.write("- integrity check : ")
- timeout = 10
- local shipSize
- repeat
- shipSize = ship.getShipSize()
- w.sleep(0.05)
- timeout = timeout - 1
- until (shipSize ~= nil and shipSize ~= 0) or timeout < 0
- if timeout < 0 then
- w.setColorWarning()
- w.writeLn("ongoing...")
- w.setColorNormal()
- w.sleep(2)
- else
- w.setColorSuccess()
- w.writeLn("passed")
- end
- ship.enable(true)
- ship.command("IDLE", true)
- w.sleep(0.3)
- end
- function ship_writeMovement(prefix)
- local message = prefix
- local count = 0
- if ship_movement[1] > 0 then
- message = message .. w.format_integer(ship_movement[1]) .. " front"
- count = count + 1
- elseif ship_movement[1] < 0 then
- message = message .. w.format_integer(- ship_movement[1]) .. " back"
- count = count + 1
- end
- if ship_movement[2] > 0 then
- if count > 0 then message = message .. ", " end
- message = message .. w.format_integer(ship_movement[2]) .. " up"
- count = count + 1
- elseif ship_movement[2] < 0 then
- if count > 0 then message = message .. ", " end
- message = message .. w.format_integer(- ship_movement[2]) .. " down"
- count = count + 1
- end
- if ship_movement[3] > 0 then
- if count > 0 then message = message .. ", " end
- message = message .. w.format_integer(ship_movement[3]) .. " right"
- count = count + 1
- elseif ship_movement[3] < 0 then
- if count > 0 then message = message .. ", " end
- message = message .. w.format_integer(- ship_movement[3]) .. " left"
- count = count + 1
- end
- if ship_rotationSteps == 1 then
- if count > 0 then message = message .. ", " end
- message = message .. "Turn right"
- count = count + 1
- elseif ship_rotationSteps == 2 then
- if count > 0 then message = message .. ", " end
- message = message .. "Turn back"
- count = count + 1
- elseif ship_rotationSteps == 3 then
- if count > 0 then message = message .. ", " end
- message = message .. "Turn left"
- count = count + 1
- end
- if count == 0 then
- message = message .. "(none)"
- end
- w.writeLn(message)
- end
- function ship_writeRotation()
- if ship_rotationSteps == 0 then
- w.writeLn(" Rotation = Front ")
- elseif ship_rotationSteps == 1 then
- w.writeLn(" Rotation = Right +90")
- elseif ship_rotationSteps == 2 then
- w.writeLn(" Rotation = Back 180 ")
- elseif ship_rotationSteps == 3 then
- w.writeLn(" Rotation = Left -90 ")
- end
- end
- function getCoreBoundaries()
- local minValues = { math.huge, math.huge, math.huge }
- local maxValues = { -math.huge, -math.huge, -math.huge }
- for _, core in ipairs(cores) do
- local x, y, z = core.wrapper.getLocalPosition() -- Get local positions
- if x == nil or y == nil or z == nil then
- x, y, z = 0, 0, 0
- end
- local front, right, up = core.wrapper.dim_positive()
- local back, left, down = core.wrapper.dim_negative()
- if front == nil or back == nil or up == nil or back == nil or left == nil or down == nil then
- front, right, up = 0, 0 ,0
- back, left, down = 0, 0 ,0
- end
- minValues[1] = math.min(minValues[1], x - back)
- minValues[2] = math.min(minValues[2], y - down)
- minValues[3] = math.min(minValues[3], z - left)
- maxValues[1] = math.max(maxValues[1], x + front)
- maxValues[2] = math.max(maxValues[2], y + up)
- maxValues[3] = math.max(maxValues[3], z + right)
- end
- return minValues, maxValues
- end
- function getVerticalClearance()
- local minValues, maxValues = getCoreBoundaries()
- local verticalClearance = maxValues[2] - minValues[2]
- return minValues[2], maxValues[2], verticalClearance
- end
- function ship_updateMovementStats()
- -- Ship position and movement calculations
- ship_x, ship_y, ship_z = computeCoresCenter()
- if ship_x == nil then
- ship_x, ship_y, ship_z = 0, 0, 0
- end
- -- Get vertical clearance
- local minY, maxY, verticalClearance = getVerticalClearance()
- print("Vertical Clearance:", verticalClearance)
- if debug == true then
- print("Lowest Y position:", minY)
- print("Highest Y position:", maxY)
- else end
- -- compute movement
- local dx, dy, dz = ship.getOrientation()
- local minValues, maxValues = getCoreBoundaries()
- if dx == nil then
- dx, dy, dz = 0, 0, 0
- end
- local worldMovement = { x = 0, y = 0, z = 0 }
- if ship_movement[2] + maxValues[2] > 256 or ship_movement[2] - minValues[2] < 0
- then ship_movement[2] = 0
- end
- worldMovement.x = dx * ship_movement[1] - dz * ship_movement[3]
- worldMovement.y = ship_movement[2]
- worldMovement.z = dz * ship_movement[1] + dx * ship_movement[3]
- ship_actualDistance = math.ceil(math.sqrt(worldMovement.x * worldMovement.x + worldMovement.y * worldMovement.y + worldMovement.z * worldMovement.z))
- ship_xTarget = ship_x + worldMovement.x
- ship_yTarget = ship_y + worldMovement.y
- ship_zTarget = ship_z + worldMovement.z
- -- update energy requirement
- local success, result = ship.getEnergyRequired()
- if success then
- ship_energyRequired = result
- else
- w.status_showWarning(result)
- end
- end
- --callAllCoresWithDelay("movement", ship_movement[1], ship_movement[2], ship_movement[3])
- function ship_warp()
- cupdate()
- -- rs.setOutput(alarm_side, true)
- if w.input_readConfirmation("Engage jump drive? (Y/n)") then
- -- rs.setOutput(alarm_side, false)
- ship.command("MANUAL", false)
- -- Use callAllCoresWithDelay to set movement and rotationSteps for all cores
- callAllCoresWithDelay("movement", ship_movement[1], ship_movement[2], ship_movement[3])
- callAllCoresWithDelay("rotationSteps", ship_rotationSteps)
- ship.command("MANUAL", true)
- -- ship = nil
- end
- -- rs.setOutput(alarm_side, false)
- end
- function ship_page_setMovement(isByPosition)
- -- force manual jump so we get proper max jump distance
- ship.command("MANUAL", false)
- local success, maxJumpDistance = ship.getMaxJumpDistance()
- if success ~= true then
- w.status_showWarning("" .. maxJumpDistance)
- return
- end
- -- Define the function to iterate the setMovement command across all cores
- local function setAllCoresMovement(x, y, z)
- for _, core in ipairs(cores) do
- local wrap = core.wrapper
- wrap.movement(x, y, z)
- end
- end
- w.page_begin("<==== Set ship movement ====>")
- w.setCursorPos(1, 3)
- w.setColorNormal()
- ship_writeMovement("Current movement is ")
- w.setCursorPos(1, 5)
- --original configuration //// this is simply for coders sake, I need a place holder cuz im bad
- -- local lenFB = math.abs(ship_front + ship_back + 1)
- -- local lenUD = math.abs(ship_up + ship_down + 1)
- -- local lenLR = math.abs(ship_left + ship_right + 1)
- --Modified configuration
- --This calculates the cores as if they are a single continuous mass
- local minValues, maxValues = getCoreBoundaries()
- local lenFB = math.abs(maxValues[1] + minValues[1] + 1)
- local lenUD = math.abs(maxValues[2] + minValues[2] + 1)
- local lenLR = math.abs(maxValues[3] + minValues[3] + 1)
- if (isByPosition) then
- local dx, dy, dz = ship.getOrientation()
- if dx == nil then
- dx, dy, dz = 0, 0, 0
- end
- if dx == 0 then
- ship_movement[3] = -dz * ship_page_setDistanceAxis(4, "X" , "East" , "West" , ship_movement[3], lenLR, maxJumpDistance, ship_x)
- ship_movement[1] = dz * ship_page_setDistanceAxis(6, "Z" , "South" , "North" , ship_movement[1], lenFB, maxJumpDistance, ship_z)
- else
- ship_movement[1] = dx * ship_page_setDistanceAxis(4, "X" , "East" , "West" , ship_movement[1], lenFB, maxJumpDistance, ship_x)
- ship_movement[3] = dx * ship_page_setDistanceAxis(6, "Z" , "South" , "North" , ship_movement[3], lenLR, maxJumpDistance, ship_z)
- end
- ship_movement[2] = ship_page_setDistanceAxis(8, "Y" , "Up" , "Down" , ship_movement[2], lenUD, maxJumpDistance, ship_y)
- if ship_movement[2] + maxValues[2] > 256 or ship_movement[2] - minValues[2] < 0
- then ship_movement[2] = 0
- end
- else
- ship_movement[1] = ship_page_setDistanceAxis(4, "Forward/back", "Forward", "Backward", ship_movement[1], lenFB, maxJumpDistance, 0)
- ship_movement[2] = ship_page_setDistanceAxis(6, "Up/down" , "Up" , "Down" , ship_movement[2], lenUD, maxJumpDistance, 0)
- ship_movement[3] = ship_page_setDistanceAxis(8, "Right/left" , "Right" , "Left" , ship_movement[3], lenLR, maxJumpDistance, 0)
- end
- -- Call setAllCoresMovement at the end of the function to set movement for all cores:
- setAllCoresMovement(ship_movement[1], ship_movement[2], ship_movement[3])
- for _, core in ipairs(cores) do
- ship_updateMovementStats(core.wrapper)
- end
- end
- function ship_page_setDistanceAxis(line, axis, positive, negative, userEntry, shipLength, maxJumpDistance, offset)
- local maximumDistance = math.floor(shipLength + maxJumpDistance)
- w.setCursorPos(1, line + 2)
- w.setColorHelp()
- w.writeFullLine(" Enter between " .. w.format_integer(offset + math.floor( shipLength + 1)) .. " and " .. w.format_integer(offset + maximumDistance) .. " to move " .. positive .. ".")
- w.writeFullLine(" Enter " .. w.format_integer(offset) .. " to keep position on this axis.")
- w.writeFullLine(" Enter between " .. w.format_integer(offset - maximumDistance) .. " and " .. w.format_integer(offset + math.floor(-shipLength - 1)) .. " to move " .. negative .. ".")
- repeat
- w.setCursorPos(1, line)
- w.setColorNormal()
- w.write(axis .. " movement: ")
- userEntry = w.input_readInteger(offset + userEntry)
- if math.abs(userEntry - offset) > maximumDistance then
- w.status_showWarning("Wrong distance. Try again.")
- end
- until math.abs(userEntry - offset) <= maximumDistance
- w.setCursorPos(1, line + 2)
- w.clearLine()
- w.setCursorPos(1, line + 3)
- w.clearLine()
- w.setCursorPos(1, line + 4)
- w.clearLine()
- return userEntry - offset
- end
- function ship_page_setRotation()
- local inputAbort = false
- w.page_begin("<==== Set ship rotation ====>")
- w.setCursorPos(1, 8)
- w.setColorHelp()
- w.writeFullLine(" Select ship rotation (Up, Down, Left, Right).")
- w.writeFullLine(" Select Front to keep current orientation.")
- w.writeFullLine(" Press Enter to save your selection.")
- repeat
- w.setCursorPos(1, 3)
- w.setColorNormal()
- ship_writeRotation()
- local params = { os.pullEventRaw() }
- local eventName = params[1]
- local address = params[2]
- if address == nil then address = "none" end
- if eventName == "key" then
- local keycode = params[2]
- if keycode == 200 then
- ship_rotationSteps = 0
- elseif keycode == 203 then
- ship_rotationSteps = 3
- elseif keycode == 205 then
- ship_rotationSteps = 1
- elseif keycode == 208 then
- ship_rotationSteps = 2
- elseif keycode == 28 then
- inputAbort = true
- else
- w.status_showWarning("Key code " .. w.format_integer(keycode) .. " is invalid")
- end
- elseif eventName == "terminate" then
- inputAbort = true
- elseif not w.event_handler(eventName, params[2]) then
- w.status_showWarning("Event '" .. eventName .. "', " .. address .. " is unsupported")
- end
- until inputAbort
- ship_rotationSteps = ship.rotationSteps(ship_rotationSteps)
- end
- function ship_page_setDimensions()
- w.page_begin("<==== Set ship dimensions ====>")
- w.setCursorPos(1, 14)
- w.setColorHelp()
- w.writeFullLine(" Enter ship size in blocks (0-9).")
- w.writeFullLine(" First block next to Ship counts as 1.")
- w.writeFullLine(" ")
- w.writeFullLine(" Press Enter to save your selection.")
- w.setCursorPos(1, 3)
- w.setColorNormal()
- w.write(" Front (".. w.format_integer(ship_front) ..") : ")
- ship_front = w.input_readInteger(ship_front)
- w.write(" Right (".. w.format_integer(ship_right) ..") : ")
- ship_right = w.input_readInteger(ship_right)
- w.write(" Up (".. w.format_integer(ship_up) ..") : ")
- ship_up = w.input_readInteger(ship_up)
- w.write(" Back (".. w.format_integer(ship_back) ..") : ")
- ship_back = w.input_readInteger(ship_back)
- w.write(" Left (".. w.format_integer(ship_left) ..") : ")
- ship_left = w.input_readInteger(ship_left)
- w.write(" Down (".. w.format_integer(ship_down) ..") : ")
- ship_down = w.input_readInteger(ship_down)
- w.write("Setting dimensions...")
- ship_front, ship_right, ship_up = ship.dim_positive(ship_front, ship_right, ship_up)
- ship_back, ship_left, ship_down = ship.dim_negative(ship_back, ship_left, ship_down)
- end
- function ship_page_autopilot()
- w.page_begin("<==== Set Auto Pilot ====>")
- w.writeLn("")
- w.writeLn("Your ship should be already inside the system.")
- w.setCursorPos(1, 16)
- w.setColorHelp()
- w.writeFullLine(" Enter target coordinates.")
- w.writeFullLine(" Press enter to save.")
- w.setCursorPos(1, 5)
- w.setColorNormal()
- w.write("Target coordinates: ")
- if #navdata <= 0 then
- local targetAutopilot = ""
- targetAutopilot = w.input_readText("")
- local txs,tys,tzs=targetAutopilot:gmatch("(%-?%d+) (%-?%d+) (%-?%d+)")()
- local tx = tonumber(txs)
- local ty = tonumber(tys)
- local tz = tonumber(tzs)
- if tx == nil or ty == nil or tz == "" then
- w.status_showWarning("Please use the proper number format.")
- ship_page_autopilot()
- end
- local ship_len_back,ship_len_left,ship_len_down=ship.dim_negative()
- local ship_len_front,ship_len_right,ship_len_up=ship.dim_positive()
- function dst(x1,y1,z1,x2,y2,z2)
- local dx = x2-x1
- local dy = y2-y1
- local dz = z2-z1
- return math.sqrt(dx*dx+dy*dy+dz*dz)
- end
- if ty-ship_len_down <= 0 or ty+ship_len_up >= 256 then
- w.status_showWarning("Target y position needs to be inside "..minY.." and "..256-maxY..".")
- ship_page_autopilot()
- end
- w.writeLn("----------------------------------")
- w.writeLn("Is this information correct?")
- w.writeLn("Current coords: X: ".. w.format_integer(ship_x) .. " Y: " .. w.format_integer(ship_y) .." Z: " .. w.format_integer(ship_z))
- w.writeLn("Target coords: X: ".. tx .. " Y: " .. ty .." Z: " ..tz)
- w.writeLn("Total distance: "..math.floor(dst(w.format_integer(ship_x),w.format_integer(ship_y),w.format_integer(ship_z),tx,ty,tz)).." blocks")
- w.writeLn("----------------------------------")
- for i=1,0,-1 do
- term.setCursorPos(1,select(2,term.getCursorPos()))
- term.write("Please double check the info..."..i.." ")
- sleep(1)
- end
- if w.input_readConfirmation("Enter 'Y' or press ENTER to calculate.") then
- w.status_showSuccess("Computing navigation steps...")
- local shipdeltafront, shipdeltaright
- local shipdeltaup = ty-w.format_integer(ship_y)
- local orix,_,oriz = ship.getOrientation()
- if orix == 1 then
- shipdeltafront = tx-w.format_integer(ship_x)
- shipdeltaright = tz-w.format_integer(ship_z)
- elseif orix == -1 then
- shipdeltafront = -tx+w.format_integer(ship_x)
- shipdeltaright = -tz+w.format_integer(ship_z)
- elseif oriz == 1 then
- shipdeltafront = tz-w.format_integer(ship_z)
- shipdeltaright = -tx+w.format_integer(ship_x)
- elseif oriz == -1 then
- shipdeltafront = -tz+w.format_integer(ship_z)
- shipdeltaright = tx-w.format_integer(ship_x)
- else
- w.status_showWarning("Unexpected ship orientation!")
- end
- w.page_begin("<==== Computing Course ====>")
- w.writeLn("")
- --w.writeLn("We need to move "..shipdeltafront.." block(s) forward ")
- --w.writeLn(shipdeltaup.." block(s) upward and "..shipdeltaright.." block(s) to the right.")
- local minforward = ship_len_front+ship_len_back
- local minup = ship_len_up+ship_len_down
- local minright = ship_len_right+ship_len_left
- ship.command("MANUAL",false)
- local success, maxdist = ship.getMaxJumpDistance()
- if not success then w.status_showWarning("unable to get the ships max jump distance: "..maxdist) end
- if maxdist <= 0 then w.status_showWarning("max jump distance is zero") end
- --w.writeLn("Max jump length = "..maxdist)
- function computeMove(mindist,remaining,ignoreconstraint) -- returns a move to make along that axis
- if remaining == 0 then return 0 end
- local remsign = (remaining < 0) and -1 or 1
- if math.abs(remaining) < mindist and not ignoreconstraint then -- if the move would be impossible because it is too short, move further away
- return -remsign * mindist
- end
- return remsign * math.min(math.abs(remaining),maxdist)
- end
- repeat
- local move = {}
- move[2] = computeMove(minup+1,shipdeltaup,true) --y
- shipdeltaup = shipdeltaup - move[2]
- move[1] = computeMove(minforward+1,shipdeltafront,math.abs(move[2]) > minup) --x
- if not (math.abs(move[2]) > minup) and shipdeltafront == 0 and shipdeltaright == 0 and shipdeltaup ~= 0 and move[1] == 0 then
- move[1] = minforward+1
- end
- shipdeltafront = shipdeltafront - move[1]
- move[3] = computeMove(minright+1,shipdeltaright, math.abs(move[2]) > minup or math.abs(move[1]) > minforward) --z
- shipdeltaright = shipdeltaright - move[3]
- navdata[#navdata+1] = move
- w.setCursorPos(1, 3)
- w.write("Computed move: #"..#navdata)
- w.setCursorPos(1, 4)
- if string.match(move[1], "-") then
- w.write(move[1].." block(s) back ")
- else
- w.write(move[1].." block(s) forward ")
- end
- w.setCursorPos(1, 5)
- if string.match(move[2], "-") then
- w.write(move[2] .." block(s) down ")
- else
- w.write(move[2] .." block(s) up ")
- end
- w.setCursorPos(1, 6)
- if string.match(move[3], "-") then
- w.write(move[3].." block(s) left ")
- else
- w.write(move[3].." block(s) right ")
- end
- w.setCursorPos(1, 7)
- w.write("Remaining: "..shipdeltafront..":"..shipdeltaup..":"..shipdeltaright.." ")
- sleep(1)
- until shipdeltafront == 0 and shipdeltaup == 0 and shipdeltaright == 0
- w.writeLn("")
- w.writeLn("")
- w.writeLn("Navigational path plotted using "..#navdata.." jump(s).")
- if w.input_readConfirmation("Engage Auto Pilot? (Y/n)") then
- for i=1,#navdata do
- local move = navdata[i]
- w.status_showSuccess("Executing Jump. There are "..#navdata.." Jump(s) left.")
- http.post(uri,"{\"content\":\"```yaml\\nAutopilot: Executing next node There are "..#navdata.." node(s) left to execute.```\"}",{['content-type']="application/json"})
- table.remove(navdata,1)
- if fs.exists(navbackup) then
- fs.delete(navbackup)
- end
- if #navdata > 0 then
- local text = textutils.serialize(navdata)
- local h = fs.open(navdatafile, "w")
- h.write(text)
- h.close()
- fs.copy(navdatafile, navbackup)
- else
- fs.delete(navdatafile)
- end
- ship.command("MANUAL", false)
- ship.movement(move[1],move[2],move[3])
- ship.rotationSteps(0)
- ship.command("MANUAL", true)
- for i=60,0,-1 do
- w.status_showSuccess("Waiting for the ship to jump..."..i.." ")
- sleep(1)
- end
- number = #navdata + 1
- http.post(uri,"{\"content\":\"```yaml\\nAutoPilot: Failed Executing node "..number..".```\"}",{['content-type']="application/json"})
- fs.delete(navdatafile)
- fs.copy(navbackup, navdatafile)
- w.status_showWarning("The ship did not jump.")
- if failping >= 0 then
- http.post(uri,"{\"content\":\""..name.."\"}",{['content-type']="application/json"})
- end
- sleep(3)
- os.reboot()
- end
- end
- targetAutopilot = ""
- ship_page_navigation()
- end
- end
- end
- function ship_page_controls()
- local minValues, maxValues = getCoreBoundaries()
- w.page_begin("Core(s) Detected (" .. ConnectedCores .. ") " .. w.data_getName() .. " - Ship controls")
- if ship == nil or ship.isInterfaced() == nil then
- w.status_showWarning("No ship controller detected")
- else
- local isValid, message = ship.getAssemblyStatus()
- if isValid ~= true then
- w.status_showWarning(message)
- else
- local isEnabled = ship.enable()
- if not isEnabled then
- ship.command("MANUAL", false)
- ship_updateMovementStats()
- end
- end
- w.setCursorPos(1, 2)
- w.writeLn("Ship:")
- w.writeLn(" Current position = " .. w.format_integer(ship_x) .. ", " .. w.format_integer(ship_y) .. ", " .. w.format_integer(ship_z))
- local energyStored, energyMax, energyUnits = ship.getEnergyStatus()
- if energyStored == nil then energyStored = 0 end
- if energyMax == nil or energyMax == 0 then energyMax = 1 end
- w.writeLn(" Energy = " .. math.floor(energyStored / energyMax * 100) .. " % (" .. w.format_integer(energyStored) .. " " .. energyUnits .. ")")
- w.writeLn("")
- w.writeLn("Dimensions:")
- w.writeLn(" Front, Right, Up = " .. w.format_integer(ship_front) .. ", " .. w.format_integer(ship_right) .. ", " .. w.format_integer(maxValues[2]) .. " blocks")
- w.writeLn(" Back, Left, Down = " .. w.format_integer(ship_back) .. ", " .. w.format_integer(ship_left) .. ", " .. w.format_integer(minValues[2]) .. " blocks")
- local shipMass, shipVolume = ship.getShipSize()
- if shipMass == nil then
- shipMass = 0
- shipVolume = 0
- end
- w.write(" Mass, Volume = ")
- if shipMass == 0 then
- w.write("?")
- else
- w.write(w.format_integer(shipMass))
- end
- w.write(" tons, ")
- if shipVolume == 0 then
- w.write("?")
- else
- w.write(w.format_integer(shipVolume))
- end
- w.writeLn(" blocks")
- if isValid == true then
- w.writeLn("")
- w.writeLn("Warp data:")
- ship_writeMovement(" Movement = ")
- w.writeLn(" Distance = " .. w.format_integer(ship_actualDistance) .. " m (" .. w.format_integer(ship_energyRequired) .. " " .. energyUnits .. ", " .. math.floor(energyStored / ship_energyRequired) .. " jumps)")
- w.writeLn(" Target position = " .. w.format_integer(ship_xTarget) .. ", " .. w.format_integer(ship_yTarget) .. ", " .. w.format_integer(ship_zTarget))
- end
- end
- w.setCursorPos(1, 16)
- w.setColorControl()
- w.writeFullLine(" set ship Name (N), Recall Pos (R), Movement (M/P)")
- if ship_isInHyper then
- w.writeFullLine(" Jump to move ship (J), exit Hyperspace (H)")
- else
- w.writeFullLine(" Jump to move ship (J), enter Hyperspace (H)")
- end
- end
- function ship_key_controls(character, keycode)
- if character == 'm' or character == 'M' then
- ship_page_setMovement(false)
- ship_page_setRotation()
- ship_warp()
- return true
- elseif character == 'p' or character == 'P' then
- ship_page_setMovement(true)
- ship_page_setRotation()
- ship_warp()
- return true
- elseif character == 'i' or character == 'I' then
- --ship_page_setDimensions()
- w.input_readConfirmation("This Function is not supported")
- return true
- elseif character == 'r' or character == 'R' then
- processRecall()
- return true
- elseif character == 'j' or character == 'J' then
- ship_warp()
- return true
- elseif character == 'h' or character == 'H' then
- -- rs.setOutput(alarm_side, true)
- local isConfirmed
- if ship_isInHyper then
- isConfirmed = w.input_readConfirmation("Disengage hyperdrive? (Y/n)")
- else
- isConfirmed = w.input_readConfirmation("Engage hyperdrive? (Y/n)")
- end
- if isConfirmed then
- -- rs.setOutput(alarm_side, false)
- -- Use callAllCoresWithDelay to set HYPERDRIVE mode for all cores
- callAllCoresWithDelay("command", "HYPERDRIVE", true)
- ship_updateMovementStats()
- -- ship = nil
- end
- -- rs.setOutput(alarm_side, false)
- return true
- elseif character == 'n' or character == 'N' then
- w.data_setName()
- return true
- end
- return false
- end
- function callAllCoresWithDelay(method, ...)
- local args = {...}
- local results = {}
- local delayedCoreResult = nil
- local function callWrapper(core)
- if core.wrapper[method] then
- local result = { pcall(core.wrapper[method], table.unpack(args)) }
- local success = table.remove(result, 1)
- if success then
- if #result > 0 then
- table.insert(results, result)
- end
- else
- print("Error calling method " .. method .. " on core " .. core.address)
- end
- end
- end
- for _, core in ipairs(cores) do
- if core.wrapper[method] then
- if delayedCore and core.address == delayedCore.address then
- -- Process delayed core result later
- delayedCoreResult = function() callWrapper(core) end
- else
- -- Process non-delayed core
- callWrapper(core)
- end
- end
- end
- if delayedCoreResult then
- os.sleep(10) -- 10 second delay
- delayedCoreResult() -- process delayed core result
- end
- if #results > 0 then
- return table.unpack(results[1])
- end
- end
- function ship_page_coreList()
- loadDelayedCore()
- w.page_begin(w.data_getName() .. " - Core List")
- w.writeLn("Connected Cores:")
- for index, core in ipairs(cores) do
- local coreName = core.wrapper.name() or "Unnamed"
- if index == ship_indexCore + 1 then
- w.setColorSelected() -- Change color for selected core
- w.write(">") -- Add the indicator for the selected core
- else
- w.write(" ")
- end
- w.write(index .. ". " .. core.address .. " (" .. coreName .. ")")
- -- Indicate the delayed core
- if delayedCore and core.address == delayedCore.address then
- w.setColorWarning()
- w.write(" (Delayed)")
- w.setColorNormal()
- end
- w.writeLn("")
- end
- w.setColorNormal()
- w.setCursorPos(1, 16)
- w.setColorControl()
- w.writeFullLine(" Select core (Up, Down) Set delay for core (D)")
- --w.writeFullLine(" Set delay for core (D)")
- end
- function ship_key_coreList(character, keycode)
- if keycode == 200 or keycode == 203 or character == '-' then -- Up or Left or -
- if ship_indexCore == 0 then
- ship_indexCore = #cores - 1
- else
- ship_indexCore = ship_indexCore - 1
- end
- return true
- elseif keycode == 208 or keycode == 205 or character == '+' then -- Down or Right or +
- if ship_indexCore == #cores - 1 then
- ship_indexCore = 0
- else
- ship_indexCore = ship_indexCore + 1
- end
- elseif character == 'd' or character == 'D' then
- delayedCore = cores[ship_indexCore + 1]
- saveDelayedCore() -- Save the delayed core to a file
- ship_page_coreList() -- Redraw the Ship Core Page
- local coreName = delayedCore.wrapper.name() or "Unnamed"
- w.status_showSuccess("Added 10-second delay to core " .. coreName)
- return true
- end
- return false
- end
- function ship_writeArray(arrayValues, indexSelected)
- if indexSelected then
- indexSelected = (indexSelected + #arrayValues) % #arrayValues
- end
- local indexSplit = math.ceil(#arrayValues / 2)
- for i = 1, indexSplit do
- if indexSelected and i == indexSelected + 1 then
- w.setColorSelected()
- w.write(">" .. string.sub(arrayValues[i] .. " ", 1, 24))
- w.setColorNormal()
- else
- w.write(" " .. string.sub(arrayValues[i] .. " ", 1, 24))
- end
- if arrayValues[i + indexSplit] ~= nil then
- if indexSelected and i + indexSplit == indexSelected + 1 then
- w.setColorSelected()
- w.writeLn(">" .. string.sub(arrayValues[i + indexSplit] .. " ", 1, 24))
- w.setColorNormal()
- else
- w.writeLn(" " .. arrayValues[i + indexSplit])
- end
- else
- w.writeLn("")
- end
- end
- return indexSelected
- end
- function ship_page_navigation()
- --w.page_begin(w.data_getName() .. " - Ship navigation //NON-FUNCTIONAL\\")
- w.page_begin("Ship navigation //NON-FUNCTIONAL\\")
- if ship == nil or ship.isInterfaced() == nil then
- w.status_showWarning("No ship controller detected")
- else
- local isValid, message = ship.getAssemblyStatus()
- if isValid ~= true then
- w.status_showWarning(message)
- else
- w.writeLn("Ship:")
- w.writeLn(" Current position = " .. w.format_integer(ship_x) .. ", " .. w.format_integer(ship_y) .. ", " .. w.format_integer(ship_z))
- w.writeLn("Destination:")
- local stringTarget, _ = targetAutopilot, nil -- ship.getTargets()
- if stringTarget == nil or stringTarget == "" then
- stringTarget = "~ None ~"
- end
- local arrayTarget = w.data_splitString(stringTarget, ",")
- ship_indexTarget = ship_writeArray(arrayTarget, ship_indexTarget)
- end
- end
- w.setCursorPos(1, 16)
- w.setColorControl()
- w.writeFullLine(" set Destination (Enter)")
- --w.writeFullLine(" engage Auto Pilot (G)")
- w.writeFullLine("")
- end
- function ship_key_navigation(character, keycode)
- if keycode == 28 then -- Enter
- ship_page_autopilot()
- return true
- elseif character == 'g' or character == 'G' then -- G
- --ship_page_jumpToGate()
- return true
- elseif keycode == 200 or keycode == 203 or character == '-' then -- Up or Left or -
- ship_indexTarget = ship_indexTarget - 1
- return true
- elseif keycode == 208 or keycode == 205 or character == '+' then -- Down or Right or +
- ship_indexTarget = ship_indexTarget + 1
- return true
- end
- return false
- end
- function ship_page_advanced()
- w.page_begin(w.data_getName() .. " - Advanced")
- w.setCursorPos(1, 5)
- local status, isEnabled, state, energy = ship.state()
- if state == nil then state = "-Undetected-" end
- w.writeLn("Ship is in " .. state .. " mode")
- w.setCursorPos(1, 16)
- w.setColorControl()
- w.writeFullLine("OFFLINE/disabled mode |O|I| IDLE/online mode")
- w.writeFullLine(" MAINTENANCE mode |M|R| Reset core info")
- end
- function ship_key_advanced(character, keycode)
- if character == 'o' or character == 'O' then -- O
- ship.command("OFFLINE", false)
- ship.command("OFFLINE", true)
- ship.enable(false)
- return true
- elseif character == 'm' or character == 'M' then -- M
- ship.command("MAINTENANCE", false)
- ship.enable(true)
- ship.command("MAINTENANCE", true)
- return true
- elseif character == 'i' or character == 'I' then -- I
- ship.command("IDLE", false)
- ship.enable(true)
- ship.command("IDLE", true)
- elseif character == 'r' or character == 'R' then -- R
- if w.input_readConfirmation("Are you sure? This cannot be undone. (Y/N)") then
- shell.run("delete Relpositions.dat")
- w.status_showWarning("The Computer will now reboot...")
- sleep(2) os.reboot()
- end
- return true
- end
- return false
- end
- ----------- connections status
- function connections_page(isBooting)
- w.page_begin(w.data_getName() .. " - Connections")
- w.writeLn("")
- local monitors = w.device_getMonitors()
- if #monitors == 0 then
- w.setColorDisabled()
- w.writeLn("No Monitor detected")
- elseif #monitors == 1 then
- w.setColorSuccess()
- w.writeLn("1 monitor detected")
- else
- w.setColorSuccess()
- w.writeLn(#monitors .. " Monitors detected")
- end
- if ship == nil or ship.isInterfaced() == nil then
- w.setColorDisabled()
- w.writeLn("No ship controller detected")
- else
- w.setColorSuccess()
- w.writeLn("Ship controller detected")
- if isBooting then
- ship_boot()
- end
- end
- w.writeLn("")
- w.setColorNormal()
- w.writeLn("This is a keyboard controlled user interface.")
- w.write("Key controls are written like so: ")
- w.setColorControl()
- w.write("Action (key)")
- w.setColorNormal()
- w.writeLn(".")
- w.write("For example, typing ")
- w.setColorControl()
- w.write(" 1 ")
- w.setColorNormal()
- w.writeLn(" will open Ship controls.")
- end
- function cupdate()
- local CID = 0
- for _, core in ipairs(cores) do
- CID = CID + 1
- local CorePosx, CorePosy, CorePosz = core.wrapper.getLocalPosition()
- table.insert(corePositions, {Core = CID, x = CorePosx, y = CorePosy, z = CorePosz})
- core.wrapper.command("MANUAL",false)
- local CoreVecx, CoreVecy, CoreVecz = core.wrapper.movement()
- table.insert(coreVectors, {Core = CID, x = CoreVecx, y = CoreVecy, z = CoreVecz})
- end
- coreupdate(corePositions, coreVectors)
- end
- -- Function to wait for a key press
- local function waitForKeyPress()
- print("Press any key to continue...")
- while true do
- sleep(0.1) -- dont time out
- local event, key = os.pullEvent("key")
- if event == "key" then
- return
- end
- end
- end
- ----------- Boot sequence
- -- Function to simulate typing out message
- local function typeOut(text, delay, color)
- term.setTextColor(color or colors.white) -- Set the text color (default is white if no color is provided)
- for i = 1, #text do
- write(text:sub(i, i)) -- Write one character at a time
- sleep(delay)
- end
- end
- -- First-time setup check
- if fs.exists("Relpositions.dat") then
- term.setCursorBlink(true)
- term.setCursorPos(0,0)
- checkCorePos()
- -- Print all errors, if any
- if #errors > 0 then
- print("Errors found:\n")
- for _, errorMsg in ipairs(errors) do
- print(errorMsg)
- end
- typeOut("\n\nPress 'r' to reboot...\n", 0.05, colors.yellow)
- typeOut("Press 'f' to attempt recall...\n",0.05,colors.orange)
- typeOut("Press 'm' to reset to default settings\n (This erases core info)", 0.05, colors.red)
- --handle keypresses
- local function handleKeyPress(character)
- if character == 'r' or character == 'R' then -- R
- os.reboot()
- elseif character == 'f' or character == 'F' then -- F
- processRecall()
- w.status_showWarning("Attempting to recall core(s)...")
- sleep(2.5)
- --count down to reboot
- local i = 10
- while i do
- w.status_showWarning("Rebooting in ("..i..")")
- i = i - 1
- sleep(1)
- if i <= 0 then os.reboot()
- end
- end
- elseif character == 'm' or character == 'M' then -- M
- if w.input_readConfirmation("Are you sure? This cannot be undone. (Y/N)") then
- shell.run("delete Relpositions.dat")
- w.status_showWarning("The Computer will now reboot...")
- sleep(2)
- os.reboot()
- end
- end
- end
- -- Wait for keypresses indefinitely
- while true do
- local event, character = os.pullEvent("char") -- Wait for a character input event
- handleKeyPress(character)
- sleep(0.1)
- end
- end
- else
- checkCorePos()
- -- Setup initial information display
- term.clear()
- term.setCursorPos(1, 1)
- term.setCursorBlink(true)
- -- Displaying the setup instructions
- typeOut("Initializing first time setup...\n\n", 0.05, colors.cyan)
- typeOut("Once complete, you can't move any ship cores\n", 0.05, colors.red)
- typeOut("Nor can you move the anchor block (Siren)\n\n", 0.05, colors.red)
- typeOut("If these blocks are moved OR have their modems broken for any reason, you MUST reset the First Time Configuration (FTC) \n\nFailure to follow this warning MAY lead to unexpected operational errors\n\n", 0.05, colors.yellow) -- Yellow color for the title
- typeOut("To reset the FTC, follow these simple steps:\n", 0.05, colors.blue)
- typeOut("Step 1: Open page 4 of this program\n", 0.05, colors.green)
- typeOut("Step 2: Press 'r'\n", 0.05, colors.purple)
- term.setTextColor(colors.red)
- waitForKeyPress() -- Wait for the user to acknowledge and press any key
- -- Additional confirmation
- term.clear()
- term.setCursorPos(1, 1)
- printSavedPos()
- typeOut("\nThank you!\n", 0.05, colors.green)
- typeOut("Setup is complete.\n", 0.05, colors.green)
- waitForKeyPress() -- Wait for the user to press any key again
- os.reboot()
- end
- -------- Actually Booting...
- w.page_setEndText(" Home (0), Ctrl (1), Cores (2), Nav (3), Advncd (4) ")
- w.page_register('0', connections_page, nil)
- w.page_register('1', ship_page_controls, ship_key_controls)
- --w.page_register('2', ship_page_crew, ship_key_crew)
- w.page_register('2', ship_page_coreList, ship_key_coreList)
- w.page_register('3', ship_page_navigation, ship_key_navigation)
- w.page_register('4', ship_page_advanced, ship_key_advanced)
- ship_register()
- w.boot()
- cupdate()
- checkCorePos()
- processRecall()
- term.setCursorBlink(false)
- on = redstone.getAnalogInput(lever)
- if on > 6 then
- w.status_showWarning("AutoPilot: Disabled")
- sleep(3)
- elseif on < 5 then
- if fs.exists(navdatafile) then
- local h = fs.open(navdatafile, "r")
- local text = h.readAll()
- navdata = textutils.unserialize(text)
- h.close()
- for _, core in ipairs(cores) do
- local wrap = core.wrapper
- while true do
- local status, isEnabled, state, energy = wrap.state()
- if state ~= "COOLING" then break end
- w.status_showWarning("Waiting Ship is in " .. state .. " mode")
- sleep(5)
- end
- while true do
- local status, isEnabled, state, energy = wrap.state()
- if state ~= "-NotDetected-" then break end
- w.status_showWarning("Waiting to connect to core(s)...")
- sleep(5)
- end
- end
- --------------------------------------AUTO PILOT
- for i=1,#navdata do
- local move = navdata[i]
- w.status_showSuccess("Executing Jump. There are "..#navdata.." Jump(s) left.")
- http.post(uri,"{\"content\":\"```yaml\\nAutopilot: Executing next node There are "..#navdata.." node(s) left to execute.```\"}",{['content-type']="application/json"})
- table.remove(navdata,1)
- if fs.exists(navbackup) then
- fs.delete(navbackup)
- fs.copy(navdatafile, navbackup)
- end
- if #navdata > 0 then
- local text = textutils.serialize(navdata)
- local h = fs.open(navdatafile, "w")
- h.write(text)
- h.close()
- else
- fs.delete(navdatafile)
- end
- ship.command("MANUAL", false)
- ship.movement(move[1],move[2],move[3])
- ship.rotationSteps(0)
- ship.command("MANUAL", true)
- sleep(10)
- for i=50,0,-1 do
- w.status_showWarning("Waiting for the ship to jump..."..i.." ")
- sleep(1)
- end
- number = #navdata + 1
- http.post(uri,"{\"content\":\"```yaml\\nAutoPilot: Failed Executing node "..number..".```\"}",{['content-type']="application/json"})
- fs.delete(navdatafile)
- fs.copy(navbackup, navdatafile)
- w.status_showWarning("AutoPilot: Failed Executing node " .. number)
- if failping >= 0 then
- http.post(uri,"{\"content\":\""..name.."\"}",{['content-type']="application/json"})
- end
- sleep(3)
- os.reboot()
- end
- --------------------------------------AUTO PILOT
- end
- end
- -- while true do
- -- local status, isEnabled, state, energy = ship.state()
- -- if state == "COOLING" then
- -- w.status_showWarning("Waiting Ship is in " .. state .. " mode")
- -- sleep(5)
- -- elseif state == "-NotDetected-" then
- -- w.status_showWarning("Waiting to connect to core(s)...")
- -- sleep(5)
- -- else
- -- break
- -- end
- -- end
- for _, core in ipairs(cores) do
- local wrap = core.wrapper
- while true do
- local status, isEnabled, state, energy = wrap.state()
- if state ~= "COOLING" then break end
- w.status_showWarning("Waiting Ship is in " .. state .. " mode")
- sleep(5)
- end
- while true do
- local status, isEnabled, state, energy = wrap.state()
- if state ~= "-NotDetected-" then break end
- w.status_showWarning("Waiting to connect to core(s)...")
- sleep(5)
- end
- end
- local success, message = pcall(w.run)
- if not success then
- print("failed with message")
- print(message)
- w.sleep(5)
- print("rebooting...")
- w.reboot()
- else
- if ship ~= nil then
- ship.command("OFFLINE", true)
- ship.enable(false)
- end
- w.close()
- end
Add Comment
Please, Sign In to add comment