Advertisement
Blackhome

Main Storage Management

May 2nd, 2025 (edited)
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 14.03 KB | Gaming | 0 0
  1. -- Storage System Manager
  2. -- By ChatGPT, structured for modular expansion
  3.  
  4. -- === CONFIG ===
  5. local DISK_NAMES = {
  6.     incoming = "Incoming Task",
  7.     user = "User Task",
  8.     outgoing = "Outgoing Task",
  9.     finished = "Finished Task",
  10.     settings = "Settings",
  11.     storage = "Data Storage",
  12.     init = "Turtle Initializing"
  13. }
  14.  
  15. local TASK_DATA = {
  16.     currentTasks = {},
  17.     emptyChests = {},
  18.     storedItems = {},
  19.     completedTasks = {},
  20.     totalChestCount = 0,
  21.     outgoingTask = nil
  22. }
  23.  
  24. local SYSTEM_STATE = {
  25.     chestInitialized = false,
  26.     waitingForChestPlacement = false,
  27.     orientation = nil,
  28.     orientationDirection = 1,
  29.     startCoords = nil,
  30.     endCoords = nil,
  31.     modulo = nil
  32. }
  33.  
  34. local TASK_TYPES = {
  35.     createChests = "create_chests",
  36.     storeItems = "store_items",
  37.     getItems = "get_items",
  38.     checkInventory = "check_inventory",
  39.     initializeChests = "initialize_chests"
  40. }
  41.  
  42. local taskIdCounter = 1
  43. local currentTaskSourceIndex = 1
  44. local TASK_SOURCES = {"incoming", "user", "settings"}  -- disk name keys
  45.  
  46. -- === UTILITIES ===
  47. function getDiskByLabel(label)
  48.     for _, side in ipairs(peripheral.getNames()) do
  49.         if peripheral.getType(side) == "drive" then
  50.             local disk = peripheral.wrap(side)
  51.             if disk.getDiskLabel() == label then
  52.                 return disk, disk.getMountPath()
  53.             end
  54.         end
  55.     end
  56.     return nil, nil
  57. end
  58.  
  59. function saveTableToDisk(tableData, filename)
  60.     local disk, path = getDiskByLabel(DISK_NAMES.storage)
  61.     if not path then error("Data Storage disk not found") end
  62.     local fullPath = fs.combine(path, filename)
  63.     local file = fs.open(fullPath, "w")
  64.     file.write(textutils.serialize(tableData))
  65.     file.close()
  66. end
  67.  
  68. function loadTableFromDisk(filename)
  69.     local disk, path = getDiskByLabel(DISK_NAMES.storage)
  70.     if not path then return {} end
  71.     local fullPath = fs.combine(path, filename)
  72.     if not fs.exists(fullPath) then return {} end
  73.     local file = fs.open(fullPath, "r")
  74.     local data = textutils.unserialize(file.readAll())
  75.     file.close()
  76.     return data or {}
  77. end
  78.  
  79. function loadTaskIdCounter()
  80.     local disk, path = getDiskByLabel(DISK_NAMES.storage)
  81.     if not path then return 1 end
  82.     local fullPath = fs.combine(path, "taskIdCounter.txt")
  83.     if fs.exists(fullPath) then
  84.         local file = fs.open(fullPath, "r")
  85.         local id = tonumber(file.readLine())
  86.         file.close()
  87.         return id or 1
  88.     end
  89.     return 1
  90. end
  91.  
  92. function saveTaskIdCounter()
  93.     local disk, path = getDiskByLabel(DISK_NAMES.storage)
  94.     if not path then error("Data Storage disk not found for saving taskIdCounter") end
  95.     local fullPath = fs.combine(path, "taskIdCounter.txt")
  96.     local file = fs.open(fullPath, "w")
  97.     file.writeLine(tostring(taskIdCounter))
  98.     file.close()
  99. end
  100.  
  101. function getTaskList(path)
  102.     if not fs.exists(path) then return {} end
  103.     local file = fs.open(path, "r")
  104.     local data = textutils.unserialize(file.readAll())
  105.     file.close()
  106.     return data or {}
  107. end
  108.  
  109. function saveTaskList(path, taskList)
  110.     local file = fs.open(path, "w")
  111.     file.write(textutils.serialize(taskList))
  112.     file.close()
  113. end
  114.  
  115. function addTaskToList(path, task)
  116.     local tasks = getTaskList(path)
  117.     table.insert(tasks, task)
  118.     saveTaskList(path, tasks)
  119. end
  120.  
  121. function saveTaskToDisk(contentTable)
  122.     contentTable.taskId = taskIdCounter
  123.     taskIdCounter = taskIdCounter + 1
  124.     saveTaskIdCounter()
  125.  
  126.     if contentTable.taskType == TASK_TYPES.initializeChests then
  127.         local finishedDisk, finishedPath = getDiskByLabel(DISK_NAMES.finished)
  128.         if not finishedPath then error("Finished disk not found") end
  129.         local fullFinishedPath = fs.combine(finishedPath, "task_list.txt")
  130.  
  131.         addTaskToList(fullFinishedPath, contentTable)
  132.     else
  133.         local outgoingDisk, outgoingPath = getDiskByLabel(DISK_NAMES.outgoing)
  134.         if not outgoingPath then error("Outgoing Task disk not found") end
  135.         local fullOutgoingPath = fs.combine(outgoingPath, "task_list.txt")
  136.  
  137.         addTaskToList(fullOutgoingPath, contentTable)
  138.     end
  139.  
  140.     local storageDisk, storagePath = getDiskByLabel(DISK_NAMES.storage)
  141.     if not storagePath then error("Data Storage disk not found") end
  142.     local fullStoragePath = fs.combine(storagePath, "currentTasks.txt")
  143.  
  144.     addTaskToList(fullStoragePath, contentTable)
  145.     table.insert(TASK_DATA.currentTasks, contentTable)
  146. end
  147.  
  148. function hasOutgoingTasks()
  149.     local _, path = getDiskByLabel(DISK_NAMES.outgoing)
  150.     if not path then return false end
  151.  
  152.     local tasks = getTaskList(fs.combine(path, "task_list.txt"))
  153.     return #tasks > 0
  154. end
  155.  
  156.  
  157. -- === INITIALIZATION ===
  158. function waitForInitialSettings()
  159.     print("Waiting for settings...")
  160.     local _, path = getDiskByLabel(DISK_NAMES.settings)
  161.     while not path do sleep(1) path = select(2, getDiskByLabel(DISK_NAMES.settings)) end
  162.  
  163.  
  164.     local settingsPath = fs.combine(path, "initial_coords.txt")
  165.     while not fs.exists(settingsPath) do sleep(1) end
  166.  
  167.     local file = fs.open(settingsPath, "r")
  168.     local x1, y1, z1 = file.readLine():match("(-?%d+),(-?%d+),(-?%d+)")
  169.     local x2, y2, z2 = file.readLine():match("(-?%d+),(-?%d+),(-?%d+)")
  170.     file.close()
  171.  
  172.     SYSTEM_STATE.startCoords = {x=tonumber(x1), y=tonumber(y1), z=tonumber(z1)}
  173.     SYSTEM_STATE.endCoords = {x=tonumber(x2), y=tonumber(y2), z=tonumber(z2)}
  174.  
  175.     determineOrientation(SYSTEM_STATE.startCoords, SYSTEM_STATE.endCoords)
  176. end
  177.  
  178. function determineOrientation(startPos, endPos)
  179.     if startPos.x ~= endPos.x then
  180.         SYSTEM_STATE.orientation = "x"
  181.         SYSTEM_STATE.orientationDirection = (endPos.x - startPos.x > 0) and 1 or -1
  182.         SYSTEM_STATE.modulo = (startPos.z + 2 * SYSTEM_STATE.orientationDirection) % 8
  183.     elseif startPos.z ~= endPos.z then
  184.         SYSTEM_STATE.orientation = "z"
  185.         SYSTEM_STATE.orientationDirection = (endPos.z - startPos.z > 0) and 1 or -1
  186.         SYSTEM_STATE.modulo = (startPos.x + 2 * SYSTEM_STATE.orientationDirection) % 8
  187.     else
  188.         SYSTEM_STATE.orientation = "unknown"
  189.         SYSTEM_STATE.orientationDirection = 1
  190.         SYSTEM_STATE.modulo = 0
  191.     end
  192.  
  193.     local disk, path = getDiskByLabel(DISK_NAMES.init)
  194.     if path then
  195.         local file = fs.open(fs.combine(path, "init.txt"), "w")
  196.         file.writeLine("orientation=" .. SYSTEM_STATE.orientation)
  197.         file.writeLine("direction=" .. tostring(SYSTEM_STATE.orientationDirection))
  198.         file.writeLine("modulo=" .. tostring(SYSTEM_STATE.modulo))
  199.         file.close()
  200.     end
  201. end
  202.  
  203. function initializeChestList(coords)
  204.     print("Initializing chest list...")
  205.     for row = 0, 4 do
  206.         for col = 0, 9 do
  207.             local offsetX = SYSTEM_STATE.orientation == "x" and col * SYSTEM_STATE.orientationDirection or 0
  208.             local offsetZ = SYSTEM_STATE.orientation == "z" and col * SYSTEM_STATE.orientationDirection or 0
  209.             local chestPos = {
  210.                 x = coords.x + offsetX,
  211.                 y = coords.y + row,
  212.                 z = coords.z + offsetZ
  213.             }
  214.             TASK_DATA.totalChestCount = TASK_DATA.totalChestCount + 1
  215.             table.insert(TASK_DATA.emptyChests, {id = TASK_DATA.totalChestCount, pos = chestPos})
  216.         end
  217.     end
  218.     SYSTEM_STATE.chestInitialized = true
  219.     SYSTEM_STATE.waitingForChestPlacement = false
  220.     saveTableToDisk(TASK_DATA.emptyChests, "emptyChests.txt")
  221.     saveTableToDisk({count = TASK_DATA.totalChestCount}, "totalChestCount.txt")
  222. end
  223.  
  224. function checkForCompletedTasks()
  225.     local _, finishedPath = getDiskByLabel(DISK_NAMES.finished)
  226.     if not finishedPath then error("Finished disk not found") end
  227.     local finishedTasks = getTaskList(fs.combine(finishedPath, "task_list.txt"))
  228.  
  229.     for _, task in ipairs(finishedTasks) do
  230.         if task.taskId then
  231.             local handled = false
  232.  
  233.             if task.taskType == TASK_TYPES.createChests then
  234.                 print("Abgeschlossener Task: " .. tostring(task.taskType) .." --- Initialisiere Kistenliste")
  235.                 initializeChestList({x = task.x, y = task.y, z = task.z})
  236.                 handled = true
  237.  
  238.             elseif task.taskType == TASK_TYPES.storeItems then
  239.                 print("Abgeschlossener Task: " .. tostring(task.taskType))
  240.  
  241.                 handled = true
  242.  
  243.             elseif task.taskType == TASK_TYPES.getItems then
  244.                 print("Abgeschlossener Task: " .. tostring(task.taskType))
  245.  
  246.                 handled = true
  247.            
  248.             elseif task.taskType == TASK_TYPES.checkInventory then
  249.                 print("Abgeschlossener Task: " .. tostring(task.taskType))
  250.  
  251.                 handled = true
  252.            
  253.             elseif task.taskType == TASK_TYPES.initializeChests then
  254.                 print("Abgeschlossener Task: " .. tostring(task.taskType) .." --- Initialisiere Kistenliste")
  255.                 initializeChestList({x = task.x, y = task.y, z = task.z})
  256.                 handled = true
  257.            
  258.             else
  259.                 print("Unbekannter Task-Typ: " .. tostring(task.taskType))
  260.             end
  261.  
  262.             if handled then
  263.                 -- Suche Task in den aktuellen Tasks
  264.                 local matchedIndex = nil
  265.                 for index, current in ipairs(TASK_DATA.currentTasks) do
  266.                     if current.taskId == task.taskId then
  267.                         matchedIndex = index
  268.                         break
  269.                     end
  270.                 end
  271.  
  272.                 if matchedIndex then
  273.                     local matchedTask = TASK_DATA.currentTasks[matchedIndex]
  274.                     table.insert(TASK_DATA.completedTasks, matchedTask)
  275.                     table.remove(TASK_DATA.currentTasks, matchedIndex)
  276.  
  277.                     local disk, storagePath = getDiskByLabel(DISK_NAMES.storage)
  278.                     if not storagePath then error("Data Storage disk not found") end
  279.  
  280.                     -- Aktuelle Tasks speichern
  281.                     local currentPath = fs.combine(storagePath, "currentTasks.txt")
  282.                     saveTaskList(currentPath, TASK_DATA.currentTasks)
  283.  
  284.                     -- Abgeschlossene Tasks speichern
  285.                     local completedPath = fs.combine(storagePath, "completedTasks.txt")
  286.                     addTaskToList(completedPath, matchedTask)
  287.                 else
  288.                     print("Warnung: Task nicht in den aktuellen Tasks gefunden: " .. tostring(task.id))
  289.                 end
  290.             end
  291.         else
  292.             print("Warnung: Task ohne ID gefunden, wird übersprungen")
  293.             print(task.taskType)
  294.         end
  295.     end
  296.     saveTaskList(fs.combine(finishedPath, "task_list.txt"), {})
  297.  
  298. end
  299.  
  300.  
  301. function processNextTaskFromDisk(diskLabelKey)
  302.     local disk, path = getDiskByLabel(DISK_NAMES[diskLabelKey])
  303.     if not path then return end
  304.  
  305.     local tasks = getTaskList(fs.combine(path, "task_list.txt"))
  306.     if #tasks == 0 then return end
  307.  
  308.     local task = table.remove(tasks, 1)
  309.  
  310.     -- Save remaining tasks back
  311.     local fullPath = fs.combine(path, "task_list.txt")
  312.     local file = fs.open(fullPath, "w")
  313.     file.write(textutils.serialize(tasks))
  314.     file.close()
  315.  
  316.     -- Save to outgoing
  317.     saveTaskToDisk(task)
  318.  
  319.     -- Do something with the task (expand as needed)
  320.     print("Processed " .. diskLabelKey .. " task ID: " .. tostring(taskIdCounter - 1))
  321. end
  322.  
  323.  
  324. function handleIncomingTask()
  325.     processNextTaskFromDisk("incoming")
  326. end
  327.  
  328. function handleUserTask()
  329.     processNextTaskFromDisk("user")
  330. end
  331.  
  332. function handleSettingsTask()
  333.     processNextTaskFromDisk("settings")
  334. end
  335.  
  336. function handleChestCreationTask() end
  337.  
  338. local handlerMap = {
  339.     incoming = handleIncomingTask,
  340.     user = handleUserTask,
  341.     settings = handleSettingsTask
  342. }
  343.  
  344. -- === START ===
  345. TASK_DATA.currentTasks = loadTableFromDisk("currentTasks.txt")
  346. TASK_DATA.emptyChests = loadTableFromDisk("emptyChests.txt")
  347. TASK_DATA.storedItems = loadTableFromDisk("storedItems.txt")
  348. TASK_DATA.completedTasks = loadTableFromDisk("completedTasks.txt")
  349. local chestCountData = loadTableFromDisk("totalChestCount.txt")
  350. TASK_DATA.totalChestCount = chestCountData.count or 0
  351. taskIdCounter = loadTaskIdCounter()
  352.  
  353. if #TASK_DATA.emptyChests == 0 and not SYSTEM_STATE.chestInitialized then
  354.     waitForInitialSettings()
  355.     local _, settingsPath = getDiskByLabel(DISK_NAMES.settings)
  356.     if not settingsPath then error("Settings disk not found") end
  357.     local taskList = getTaskList(fs.combine(settingsPath, "task_list.txt"))
  358.     local hasCreateTask = false
  359.     local createTaskIndex = nil
  360.     local createTask = nil
  361.  
  362.     for index, task in ipairs(taskList) do
  363.         if task.taskType == TASK_TYPES.createChests then
  364.             hasCreateTask = true
  365.             createTaskIndex = index
  366.             createTask = task
  367.             break
  368.         end
  369.     end
  370.  
  371.     if hasCreateTask then
  372.         -- Task abspeichern auf Daten-Disk (als wäre er gerade ausgeführt worden)
  373.         local disk, path = getDiskByLabel(DISK_NAMES.storage)
  374.         if not path then error("Data Storage disk not found") end
  375.         local currentPath = fs.combine(path, "currentTasks.txt")
  376.        
  377.         addTaskToList(currentPath, createTask)
  378.         saveTaskToDisk(createTask)
  379.  
  380.         -- Task aus taskList entfernen und aktualisieren
  381.         table.remove(taskList, createTaskIndex)
  382.         saveTaskList(fs.combine(settingsPath, "task_list.txt"), taskList)
  383.     else
  384.         initializeChestList(SYSTEM_STATE.startCoords)
  385.     end
  386. end
  387.  
  388.  
  389.  
  390. -- === MAIN LOOP ===
  391. while true do
  392.     checkForCompletedTasks()
  393.  
  394.     if not hasOutgoingTasks() then
  395.         if SYSTEM_STATE.waitingForChestPlacement then
  396.             handlerMap.settings()
  397.         elseif #TASK_DATA.emptyChests == 0 then
  398.             SYSTEM_STATE.waitingForChestPlacement = true
  399.         else
  400.             local sourceKey = TASK_SOURCES[currentTaskSourceIndex]
  401.             handlerMap[sourceKey]()
  402.  
  403.             currentTaskSourceIndex = currentTaskSourceIndex + 1
  404.             if currentTaskSourceIndex > #TASK_SOURCES then
  405.                 currentTaskSourceIndex = 1
  406.             end
  407.         end
  408.     end
  409.  
  410.     sleep(1)
  411. end
  412.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement