Advertisement
April_The_Sergal

node script

Nov 23rd, 2024 (edited)
390
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 10.56 KB | Gaming | 0 0
  1. -- Node Script
  2.  
  3. -- Variables
  4. local PROTOCOL = "mobFarm"
  5. local LOCAL_ID = "MOB_" .. os.getComputerID()
  6. local status = "STOPPED"
  7. local cID = nil -- Controller ID
  8. local startDelay = 3
  9. local stopDelay = 0
  10. local delay = 0
  11. local monitor = peripheral.wrap("front")
  12. local REDSTONE_BACK = "back" -- Lights
  13. local REDSTONE_RIGHT = "left" -- Fans and grinder
  14. local version = "1.0.4" -- Version of the startup.lua
  15.  
  16. -- Ensure update.lua exists with version and Pastebin checks
  17.  
  18. local pastebinID = "8DnZvWtP" -- Pastebin ID for update.lua
  19. local pastebinURL = "https://pastebin.com/raw/" .. pastebinID
  20. local updateScriptName = "update.lua"
  21. local localVersionFile = "update_version.txt" -- File to store the local version
  22.  
  23. -- Function to check if the Pastebin file exists
  24. local function checkPastebinFileExists()
  25.     print("Checking if Pastebin file exists...")
  26.     local response = http.get(pastebinURL)
  27.     if response then
  28.         response.close()
  29.         print("Pastebin file exists.")
  30.         return true
  31.     else
  32.         print("Pastebin file does not exist or cannot be accessed.")
  33.         return false
  34.     end
  35. end
  36.  
  37. -- Function to read the local version of update.lua
  38. local function readLocalVersion()
  39.     if fs.exists(localVersionFile) then
  40.         local file = fs.open(localVersionFile, "r")
  41.         local version = file.readLine()
  42.         file.close()
  43.         return version
  44.     else
  45.         return nil -- No local version exists
  46.     end
  47. end
  48.  
  49. -- Function to write the local version of update.lua
  50. local function writeLocalVersion(version)
  51.     local file = fs.open(localVersionFile, "w")
  52.     file.writeLine(version)
  53.     file.close()
  54. end
  55.  
  56. -- Function to fetch the remote version from Pastebin
  57. local function fetchRemoteVersion()
  58.     print("Fetching remote version from Pastebin...")
  59.     local response = http.get(pastebinURL)
  60.     if response then
  61.         local content = response.readAll()
  62.         response.close()
  63.  
  64.         -- Extract the version from the script content
  65.         local remoteVersion = content:match('local version%s*=%s*"(.-)"')
  66.         if remoteVersion then
  67.             print("Remote version found: " .. remoteVersion)
  68.             return remoteVersion
  69.         else
  70.             print("Failed to extract version from remote script.")
  71.             return nil
  72.         end
  73.     else
  74.         print("Failed to fetch remote script. Check network or Pastebin ID.")
  75.         return nil
  76.     end
  77. end
  78.  
  79. -- Function to compare versions
  80. local function isUpdateRequired(localVersion, remoteVersion)
  81.     if not localVersion then
  82.         print("No local version found. Update required.")
  83.         return true
  84.     end
  85.  
  86.     if localVersion ~= remoteVersion then
  87.         print("Version mismatch: Local (" .. localVersion .. ") vs Remote (" .. remoteVersion .. "). Update required.")
  88.         return true
  89.     else
  90.         print("Local version (" .. localVersion .. ") is up-to-date.")
  91.         return false
  92.     end
  93. end
  94.  
  95. -- Main logic to ensure update.lua exists and is up-to-date
  96. print("Checking update.lua...")
  97.  
  98. -- Check if the Pastebin file exists
  99. if not checkPastebinFileExists() then
  100.     print("Pastebin file does not exist. Aborting check.")
  101. end
  102.  
  103. -- Read local version
  104. local localVersion = readLocalVersion()
  105.  
  106. -- Fetch remote version
  107. local remoteVersion = fetchRemoteVersion()
  108.  
  109. -- Check if an update is required
  110. if remoteVersion and isUpdateRequired(localVersion, remoteVersion) then
  111.     -- Remove outdated update.lua
  112.     if fs.exists(updateScriptName) then
  113.         print("Removing outdated " .. updateScriptName)
  114.         fs.delete(updateScriptName)
  115.     end
  116.  
  117.     -- Download the new update.lua
  118.     print("Downloading updated " .. updateScriptName .. " from Pastebin...")
  119.     local success = shell.run("pastebin get " .. pastebinID .. " " .. updateScriptName)
  120.     if success then
  121.         print(updateScriptName .. " downloaded successfully.")
  122.         -- Write the new version to the local version file
  123.         writeLocalVersion(remoteVersion)
  124.     else
  125.         print("Failed to download " .. updateScriptName .. ". Please check the Pastebin ID or your connection.")
  126.     end
  127. else
  128.     print(updateScriptName .. " is up-to-date. No action required.")
  129. end
  130.  
  131.  
  132. -- Peripherals
  133. peripheral.find("modem", rednet.open)
  134. rednet.host(PROTOCOL, LOCAL_ID)
  135.  
  136. -- Helper Functions
  137. local function setRedstoneOutput(side, state)
  138.     redstone.setOutput(side, state)
  139. end
  140.  
  141. local function toggleLights(state)
  142.     setRedstoneOutput(REDSTONE_BACK, state)
  143. end
  144.  
  145. local function toggleFans(state)
  146.     sleep(delay) -- Delay for fans
  147.     setRedstoneOutput(REDSTONE_RIGHT, state)
  148. end
  149.  
  150. local function updateMonitor(farmStatus)
  151.     if not monitor then
  152.         print("No monitor detected.")
  153.         return
  154.     end
  155.  
  156.     monitor.setTextScale(2)
  157.     monitor.clear()
  158.     monitor.setTextColor(colors.white)
  159.     local bgColor = (farmStatus == "RUNNING") and colors.red or colors.green
  160.     monitor.setBackgroundColor(bgColor)
  161.     monitor.clear()
  162.  
  163.     local screenWidth, screenHeight = monitor.getSize()
  164.     local centeredX = math.floor(screenWidth / 2)
  165.     local centeredY = math.floor(screenHeight / 2)
  166.  
  167.     monitor.setCursorPos(centeredX - math.floor(#LOCAL_ID / 2), centeredY)
  168.     monitor.write(LOCAL_ID)
  169.     monitor.setCursorPos(centeredX - math.floor(#farmStatus / 2), centeredY+1)
  170.     monitor.write(farmStatus)
  171.     monitor.setBackgroundColor(colors.black)
  172. end
  173.  
  174. local function toggleFarm()
  175.     if status == "RUNNING" then
  176.         print("Stopping farm...")
  177.         delay = startDelay
  178.         toggleLights(true)
  179.         toggleFans(false)
  180.         status = "STOPPED"
  181.     else
  182.         print("Starting farm...")
  183.         delay = stopDelay
  184.         toggleLights(false)
  185.         toggleFans(true)
  186.         status = "RUNNING"
  187.     end
  188.     updateMonitor(status)
  189. end
  190.  
  191. local function validateStatus()
  192.     local lightsState = redstone.getOutput(REDSTONE_BACK)
  193.     local fansState = redstone.getOutput(REDSTONE_RIGHT)
  194.  
  195.     if lightsState == fansState then
  196.         print("Error: Lights and fans in the same state. Resetting...")
  197.         toggleLights(true)
  198.         toggleFans(false)
  199.         status = "STOPPED"
  200.     else
  201.         status = fansState and "RUNNING" or "STOPPED"
  202.     end
  203. end
  204.  
  205. local function sendStatus()
  206.     validateStatus()
  207.     local packet = {
  208.         type = "status",
  209.         hostName = LOCAL_ID,
  210.         status = status
  211.     }
  212.     rednet.send(cID, packet, PROTOCOL)
  213.     print("Sent status update:", textutils.serialize(packet))
  214.     updateMonitor(status)
  215. end
  216.  
  217. -- Restore redstone state explicitly based on the saved status
  218. local function restoreRedstoneState()
  219.     if status == "RUNNING" then
  220.         toggleLights(false)
  221.         toggleFans(true)
  222.     else
  223.         toggleLights(true)
  224.         toggleFans(false)
  225.     end
  226.     print("Redstone state restored to:", status)
  227. end
  228.  
  229. -- Send immediate status update with handshake
  230. local function connectToController()
  231.     while not cID do
  232.         cID = rednet.lookup(PROTOCOL, "controller")
  233.         if cID then
  234.             print("Connected to controller (ID: " .. cID .. ")")
  235.             rednet.send(cID, {
  236.                 type = "handshake",
  237.                 hostName = LOCAL_ID,
  238.                 status = status -- Include current status in the handshake
  239.             }, PROTOCOL)
  240.             restoreRedstoneState()
  241.         else
  242.             print("Controller not found. Retrying in 3 seconds...")
  243.             sleep(3)
  244.         end
  245.     end
  246. end
  247.  
  248. local function maintainConnection()
  249.     while true do
  250.         if cID then
  251.             rednet.send(cID, {
  252.                 type = "handshake",
  253.                 hostName = LOCAL_ID,
  254.                 status = status -- Include current status in the handshake
  255.             }, PROTOCOL)
  256.         else
  257.             connectToController()
  258.         end
  259.         sleep(5) -- Send handshakes every 5 seconds
  260.     end
  261. end
  262.  
  263. -- Storage Monitoring
  264. local function monitorStorage()
  265.     local chest = peripheral.wrap("top") -- Ensure this matches your setup
  266.     if not chest or not chest.list then
  267.         print("No chest detected above. Skipping storage monitoring.")
  268.         return
  269.     end
  270.  
  271.     while true do
  272.         local items = chest.list()
  273.         local totalSlots = chest.size()
  274.         local usedSlots = 0
  275.  
  276.         for _, item in pairs(items) do
  277.             if item.count > 0 then
  278.                 usedSlots = usedSlots + 1
  279.             end
  280.         end
  281.  
  282.         local storagePercent = math.floor((usedSlots / totalSlots) * 100)
  283.         print("Calculated storage: " .. storagePercent .. "%")
  284.  
  285.         -- Send storage update to controller
  286.         if cID then
  287.             rednet.send(cID, {
  288.                 type = "storageUpdate",
  289.                 hostName = LOCAL_ID,
  290.                 storagePercent = storagePercent
  291.             }, PROTOCOL)
  292.             print("Sent storage update to controller: " .. storagePercent .. "%")
  293.         else
  294.             print("No controller connected. Skipping storage update.")
  295.         end
  296.  
  297.         -- Stop the farm if storage exceeds 95%
  298.         if storagePercent > 95 and status == "RUNNING" then
  299.             print("Storage exceeds 95%. Stopping farm...")
  300.             toggleFarm()
  301.         end
  302.  
  303.         sleep(5) -- Update storage every 5 seconds
  304.     end
  305. end
  306.  
  307.  
  308. -- Message Handling with Debug Logs
  309. local function handleMessages()
  310.     while true do
  311.         local senderId, message = rednet.receive(PROTOCOL)
  312.         if senderId then
  313.             print("Message received from:", senderId, "Type:", message and message.type or "nil")
  314.             if message and message.type == "requestId" then
  315.                 -- Respond to requestId with CLIENT_ID
  316.                 rednet.send(senderId, { type = "responseId", CLIENT_ID = LOCAL_ID }, PROTOCOL)
  317.                 print("Responded to requestId with CLIENT_ID:", LOCAL_ID)
  318.             elseif message and message.type == "toggle" then
  319.                 toggleFarm()
  320.                 sendStatus()
  321.             elseif message and message.type == "requestStatus" then
  322.                 sendStatus()
  323.             elseif message and message.type == "update" then
  324.                 print("Update command received. Updating...")
  325.                 shell.run("update.lua")
  326.                 return
  327.             end
  328.         else
  329.             print("No message received.")
  330.         end
  331.     end
  332. end
  333.  
  334. -- Startup Logic
  335. connectToController() -- Ensure connection on startup
  336. updateMonitor(status)
  337.  
  338. -- Parallel Tasks
  339. parallel.waitForAll(
  340.         handleMessages,       -- Listen and process incoming messages
  341.         maintainConnection,   -- Maintain connection with the controller
  342.         monitorStorage        -- Periodically monitor chest storage
  343. )
  344.  
Advertisement
Comments
  • April_The_Sergal
    217 days
    # text 0.31 KB | 0 0
    1. This is a lua script used to create nodes for a mob farm. Each node will self assign a UID and communicate with a singular controller. The node will send status comms through a rednet protocol to the controller such as the current status (Running, or Stopped), the amount of storage used in the farm, among others.
Add Comment
Please, Sign In to add comment
Advertisement