MomoFloFlo

djjsshjqshjqksjwjsj

Nov 8th, 2025
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 14.95 KB | None | 0 0
  1.  
  2. -- nanomachine_server.lua
  3. local component = require("component")
  4. local event = require("event")
  5. local serialization = require("serialization")
  6. local filesystem = require("filesystem")
  7.  
  8. -- Config
  9. local PORT = 2000
  10. local UPDATE_INTERVAL = 1
  11. local SAVE_FILE = "/home/nanomachine_data.cfg"
  12.  
  13. -- Components
  14. local modem = component.modem
  15. local nano = component.nanomachines
  16.  
  17. -- State Management
  18. local state = {
  19.   power = 0,
  20.   maxPower = 0,
  21.   health = 0,
  22.   maxHealth = 20,
  23.   hunger = 0,
  24.   activeInputs = 0,
  25.   totalInputs = 0,
  26.   activeEffects = 0,
  27.   currentProfile = nil,
  28.   autoProtect = false,
  29.   healthThreshold = 10,
  30.   hungerThreshold = 6,
  31.   discoveryActive = false,
  32.   discoveryProgress = 0,
  33.   discoveryTested = 0,
  34.   discoveryFound = 0,
  35.   lastUpdate = 0
  36. }
  37.  
  38. -- Data Storage
  39. local profiles = {}
  40. local inputStates = {}
  41. local discoveredEffects = {}
  42. local discoveryQueue = {}
  43. local discoveryIndex = 1
  44.  
  45. -- Initialize
  46. local function initialize()
  47.   print("=== NANOMACHINE SERVER INITIALIZING ===")
  48.   print("")
  49.  
  50.   modem.open(PORT)
  51.   print("✓ Modem listening on port " .. PORT)
  52.   print("✓ Server Address: " .. modem.address)
  53.   print("")
  54.  
  55.   -- Check for nanomachines
  56.   if not nano then
  57.     print("⚠ WARNING: No nanomachines component found!")
  58.     print("Make sure nanomachines are installed and connected.")
  59.     return false
  60.   end
  61.  
  62.   print("✓ Nanomachines detected")
  63.  
  64.   -- Get total inputs
  65.   state.totalInputs = nano.getInputCount()
  66.   print("✓ Total inputs: " .. state.totalInputs)
  67.  
  68.   -- Initialize input states
  69.   for i = 1, state.totalInputs do
  70.     inputStates[i] = {
  71.       id = i,
  72.       active = false,
  73.       lastToggled = 0
  74.     }
  75.   end
  76.  
  77.   -- Load saved data
  78.   loadData()
  79.  
  80.   print("")
  81.   print("=== SERVER READY ===")
  82.   print("")
  83.  
  84.   return true
  85. end
  86.  
  87. -- Save/Load Functions
  88. local function saveData()
  89.   local data = {
  90.     profiles = profiles,
  91.     discoveredEffects = discoveredEffects,
  92.     autoProtect = state.autoProtect,
  93.     healthThreshold = state.healthThreshold,
  94.     hungerThreshold = state.hungerThreshold
  95.   }
  96.  
  97.   local file = io.open(SAVE_FILE, "w")
  98.   if file then
  99.     file:write(serialization.serialize(data))
  100.     file:close()
  101.     print("[SAVE] Data saved successfully")
  102.     return true
  103.   else
  104.     print("[ERROR] Failed to save data")
  105.     return false
  106.   end
  107. end
  108.  
  109. local function loadData()
  110.   if not filesystem.exists(SAVE_FILE) then
  111.     print("[LOAD] No saved data found, starting fresh")
  112.    
  113.     -- Create default profiles
  114.     profiles = {
  115.       {
  116.         name = "Combat",
  117.         description = "Speed + Strength + Resistance",
  118.         inputs = {}
  119.       },
  120.       {
  121.         name = "Mining",
  122.         description = "Haste + Night Vision",
  123.         inputs = {}
  124.       },
  125.       {
  126.         name = "Safe",
  127.         description = "Regeneration only",
  128.         inputs = {}
  129.       }
  130.     }
  131.    
  132.     return
  133.   end
  134.  
  135.   local file = io.open(SAVE_FILE, "r")
  136.   if file then
  137.     local content = file:read("*a")
  138.     file:close()
  139.    
  140.     local success, data = pcall(serialization.unserialize, content)
  141.     if success and data then
  142.       profiles = data.profiles or {}
  143.       discoveredEffects = data.discoveredEffects or {}
  144.       state.autoProtect = data.autoProtect or false
  145.       state.healthThreshold = data.healthThreshold or 10
  146.       state.hungerThreshold = data.hungerThreshold or 6
  147.      
  148.       print("[LOAD] Data loaded successfully")
  149.       print("       Profiles: " .. #profiles)
  150.       print("       Discovered Effects: " .. #discoveredEffects)
  151.     else
  152.       print("[ERROR] Failed to parse saved data")
  153.     end
  154.   end
  155. end
  156.  
  157. -- Nanomachine Control Functions
  158. local function updateNanoStatus()
  159.   if not nano then return end
  160.  
  161.   -- Get power
  162.   state.power = nano.getPowerState()
  163.   state.maxPower = nano.getMaxPower()
  164.  
  165.   -- Count active inputs
  166.   state.activeInputs = 0
  167.   for i = 1, state.totalInputs do
  168.     if nano.getInput(i) then
  169.       inputStates[i].active = true
  170.       state.activeInputs = state.activeInputs + 1
  171.     else
  172.       inputStates[i].active = false
  173.     end
  174.   end
  175.  
  176.   -- Get active effects
  177.   local effects = nano.getActiveEffects()
  178.   state.activeEffects = effects and #effects or 0
  179.  
  180.   state.lastUpdate = os.time()
  181. end
  182.  
  183. local function setInput(inputId, active)
  184.   if not nano or inputId < 1 or inputId > state.totalInputs then
  185.     return false
  186.   end
  187.  
  188.   nano.setInput(inputId, active)
  189.   inputStates[inputId].active = active
  190.   inputStates[inputId].lastToggled = os.time()
  191.  
  192.   print("[INPUT] Input " .. inputId .. " set to " .. (active and "ON" or "OFF"))
  193.   return true
  194. end
  195.  
  196. local function toggleInput(inputId)
  197.   if not nano or inputId < 1 or inputId > state.totalInputs then
  198.     return false
  199.   end
  200.  
  201.   local currentState = nano.getInput(inputId)
  202.   return setInput(inputId, not currentState)
  203. end
  204.  
  205. local function disableAllInputs()
  206.   print("[ACTION] Disabling all inputs...")
  207.  
  208.   for i = 1, state.totalInputs do
  209.     setInput(i, false)
  210.   end
  211.  
  212.   state.currentProfile = nil
  213.   print("[ACTION] All inputs disabled")
  214. end
  215.  
  216. -- Profile Management
  217. local function activateProfile(profileName)
  218.   print("[PROFILE] Activating profile: " .. profileName)
  219.  
  220.   -- Find profile
  221.   local profile = nil
  222.   for _, p in ipairs(profiles) do
  223.     if p.name == profileName then
  224.       profile = p
  225.       break
  226.     end
  227.   end
  228.  
  229.   if not profile then
  230.     print("[ERROR] Profile not found: " .. profileName)
  231.     return false
  232.   end
  233.  
  234.   -- Disable all first
  235.   disableAllInputs()
  236.  
  237.   -- Activate profile inputs
  238.   if profile.inputs and #profile.inputs > 0 then
  239.     for _, inputId in ipairs(profile.inputs) do
  240.       setInput(inputId, true)
  241.     end
  242.   end
  243.  
  244.   state.currentProfile = profileName
  245.   print("[PROFILE] Profile activated: " .. profileName)
  246.  
  247.   return true
  248. end
  249.  
  250. local function createProfile(profileName)
  251.   print("[PROFILE] Creating profile: " .. profileName)
  252.  
  253.   -- Get current active inputs
  254.   local activeInputs = {}
  255.   for i = 1, state.totalInputs do
  256.     if inputStates[i].active then
  257.       table.insert(activeInputs, i)
  258.     end
  259.   end
  260.  
  261.   -- Create profile
  262.   local profile = {
  263.     name = profileName,
  264.     description = "Custom profile",
  265.     inputs = activeInputs,
  266.     created = os.time()
  267.   }
  268.  
  269.   table.insert(profiles, profile)
  270.   saveData()
  271.  
  272.   print("[PROFILE] Profile created with " .. #activeInputs .. " inputs")
  273.   return true
  274. end
  275.  
  276. local function deleteProfile(profileName)
  277.   for i, profile in ipairs(profiles) do
  278.     if profile.name == profileName then
  279.       table.remove(profiles, i)
  280.       saveData()
  281.       print("[PROFILE] Deleted profile: " .. profileName)
  282.       return true
  283.     end
  284.   end
  285.  
  286.   print("[ERROR] Profile not found: " .. profileName)
  287.   return false
  288. end
  289.  
  290. -- Auto-Protection System
  291. local function checkAutoProtection()
  292.   if not state.autoProtect or not nano then
  293.     return
  294.   end
  295.  
  296.   -- Check health (would need player component or other method to get real health)
  297.   -- This is a placeholder - you'd need to implement actual health checking
  298.  
  299.   -- For now, we'll use a simple low power protection
  300.   if state.power < (state.maxPower * 0.2) then
  301.     print("[AUTO-PROTECT] Low power detected, activating emergency profile")
  302.     -- Could activate a specific safe profile here
  303.   end
  304. end
  305.  
  306. -- Discovery System
  307. local function initializeDiscovery()
  308.   print("[DISCOVERY] Initializing discovery system...")
  309.  
  310.   discoveryQueue = {}
  311.  
  312.   -- Generate all possible single input combinations
  313.   for i = 1, state.totalInputs do
  314.     table.insert(discoveryQueue, {i})
  315.   end
  316.  
  317.   -- Generate all possible double input combinations
  318.   for i = 1, state.totalInputs do
  319.     for j = i + 1, state.totalInputs do
  320.       table.insert(discoveryQueue, {i, j})
  321.     end
  322.   end
  323.  
  324.   -- Could add triple combinations but that's a lot
  325.   -- For 32 inputs: 32 + 496 + 4960 = 5488 combinations
  326.  
  327.   print("[DISCOVERY] Queue size: " .. #discoveryQueue .. " combinations")
  328.   discoveryIndex = 1
  329.   state.discoveryTested = 0
  330.   state.discoveryFound = 0
  331. end
  332.  
  333. local function runDiscoveryStep()
  334.   if not state.discoveryActive or discoveryIndex > #discoveryQueue then
  335.     state.discoveryActive = false
  336.     print("[DISCOVERY] Discovery complete!")
  337.     saveData()
  338.     return
  339.   end
  340.  
  341.   local combination = discoveryQueue[discoveryIndex]
  342.  
  343.   -- Disable all inputs
  344.   for i = 1, state.totalInputs do
  345.     setInput(i, false)
  346.   end
  347.  
  348.   -- Wait a bit for effects to clear
  349.   os.sleep(0.5)
  350.  
  351.   -- Enable combination
  352.   for _, inputId in ipairs(combination) do
  353.     setInput(inputId, true)
  354.   end
  355.  
  356.   -- Wait for effects to activate
  357.   os.sleep(1)
  358.  
  359.   -- Check for effects
  360.   local effects = nano.getActiveEffects()
  361.  
  362.   if effects and #effects > 0 then
  363.     local effectData = {
  364.       combination = combination,
  365.       effects = effects,
  366.       discovered = os.time()
  367.     }
  368.    
  369.     table.insert(discoveredEffects, effectData)
  370.     state.discoveryFound = state.discoveryFound + 1
  371.    
  372.     print("[DISCOVERY] Found effects: " .. table.concat(effects, ", "))
  373.     print("            Inputs: " .. table.concat(combination, ", "))
  374.   end
  375.  
  376.   state.discoveryTested = state.discoveryTested + 1
  377.   state.discoveryProgress = math.floor((discoveryIndex / #discoveryQueue) * 100)
  378.  
  379.   discoveryIndex = discoveryIndex + 1
  380. end
  381.  
  382. -- Message Handler
  383. local function handleMessage(sender, port, distance, command, data)
  384.   print("[REQUEST] " .. command .. " from " .. sender:sub(1, 8))
  385.  
  386.   if command == "GET_STATUS" then
  387.     local serialized = serialization.serialize(state)
  388.     modem.send(sender, PORT, "GET_STATUS_RESPONSE", serialized)
  389.    
  390.   elseif command == "GET_PROFILES" then
  391.     local serialized = serialization.serialize(profiles)
  392.     modem.send(sender, PORT, "GET_PROFILES_RESPONSE", serialized)
  393.    
  394.   elseif command == "GET_INPUTS" then
  395.     local serialized = serialization.serialize(inputStates)
  396.     modem.send(sender, PORT, "GET_INPUTS_RESPONSE", serialized)
  397.    
  398.   elseif command == "ACTIVATE_PROFILE" then
  399.     activateProfile(data)
  400.     modem.send(sender, PORT, "ACK")
  401.    
  402.   elseif command == "CREATE_PROFILE" then
  403.     createProfile(data)
  404.     modem.send(sender, PORT, "ACK")
  405.    
  406.   elseif command == "DELETE_PROFILE" then
  407.     deleteProfile(data)
  408.     modem.send(sender, PORT, "ACK")
  409.    
  410.   elseif command == "TOGGLE_INPUT" then
  411.     toggleInput(data)
  412.     modem.send(sender, PORT, "ACK")
  413.    
  414.   elseif command == "DISABLE_ALL" then
  415.     disableAllInputs()
  416.     modem.send(sender, PORT, "ACK")
  417.    
  418.   elseif command == "EMERGENCY_STOP" then
  419.     disableAllInputs()
  420.     state.autoProtect = false
  421.     state.discoveryActive = false
  422.     print("[EMERGENCY] Emergency stop activated!")
  423.     modem.send(sender, PORT, "ACK")
  424.    
  425.   elseif command == "TOGGLE_AUTO" then
  426.     state.autoProtect = not state.autoProtect
  427.     saveData()
  428.     print("[AUTO-PROTECT] " .. (state.autoProtect and "ENABLED" or "DISABLED"))
  429.     modem.send(sender, PORT, "ACK")
  430.    
  431.   elseif command == "SET_HEALTH_THRESHOLD" then
  432.     state.healthThreshold = data
  433.     saveData()
  434.     print("[SETTING] Health threshold set to " .. data)
  435.     modem.send(sender, PORT, "ACK")
  436.    
  437.   elseif command == "SET_HUNGER_THRESHOLD" then
  438.     state.hungerThreshold = data
  439.     saveData()
  440.     print("[SETTING] Hunger threshold set to " .. data)
  441.     modem.send(sender, PORT, "ACK")
  442.    
  443.   elseif command == "START_DISCOVERY" then
  444.     initializeDiscovery()
  445.     state.discoveryActive = true
  446.     print("[DISCOVERY] Discovery started")
  447.     modem.send(sender, PORT, "ACK")
  448.    
  449.   elseif command == "PAUSE_DISCOVERY" then
  450.     state.discoveryActive = false
  451.     print("[DISCOVERY] Discovery paused")
  452.     modem.send(sender, PORT, "ACK")
  453.    
  454.   elseif command == "RESET_DISCOVERY" then
  455.     initializeDiscovery()
  456.     state.discoveryActive = true
  457.     print("[DISCOVERY] Discovery reset and restarted")
  458.     modem.send(sender, PORT, "ACK")
  459.    
  460.   elseif command == "PING" then
  461.     modem.send(sender, PORT, "PONG")
  462.    
  463.   else
  464.     modem.send(sender, PORT, "ERROR")
  465.   end
  466. end
  467.  
  468. -- Status Display
  469. local function displayStatus()
  470.   print("╔═══════════════════════════════════════════════╗")
  471.   print("║     NANOMACHINE SERVER STATUS                 ║")
  472.   print("╚═══════════════════════════════════════════════╝")
  473.   print("")
  474.   print("Server: " .. modem.address:sub(1, 8) .. "...")
  475.   print("Port: " .. PORT)
  476.   print("")
  477.   print("Power: " .. state.power .. "/" .. state.maxPower)
  478.   print("Active Inputs: " .. state.activeInputs .. "/" .. state.totalInputs)
  479.   print("Active Effects: " .. state.activeEffects)
  480.   print("")
  481.   print("Current Profile: " .. (state.currentProfile or "None"))
  482.   print("Auto-Protect: " .. (state.autoProtect and "ENABLED" or "DISABLED"))
  483.   print("")
  484.  
  485.   if state.discoveryActive then
  486.     print("Discovery: ACTIVE")
  487.     print("  Progress: " .. state.discoveryProgress .. "%")
  488.     print("  Tested: " .. state.discoveryTested)
  489.     print("  Found: " .. state.discoveryFound .. " effects")
  490.   else
  491.     print("Discovery: IDLE")
  492.     print("  Total Discovered: " .. #discoveredEffects .. " effects")
  493.   end
  494.  
  495.   print("")
  496.   print("Profiles: " .. #profiles)
  497.   print("")
  498.   print("Press Ctrl+C to stop server")
  499.   print("───────────────────────────────────────────────")
  500. end
  501.  
  502. -- Main Loop
  503. local function main()
  504.   if not initialize() then
  505.     print("Failed to initialize server")
  506.     return
  507.   end
  508.  
  509.   local lastStatusDisplay = 0
  510.   local lastDataUpdate = 0
  511.   local lastAutoCheck = 0
  512.   local lastDiscoveryStep = 0
  513.  
  514.   while true do
  515.     local currentTime = os.time()
  516.    
  517.     -- Update nanomachine status
  518.     if currentTime - lastDataUpdate >= UPDATE_INTERVAL then
  519.       updateNanoStatus()
  520.       lastDataUpdate = currentTime
  521.     end
  522.    
  523.     -- Check auto-protection
  524.     if currentTime - lastAutoCheck >= 2 then
  525.       checkAutoProtection()
  526.       lastAutoCheck = currentTime
  527.     end
  528.    
  529.     -- Run discovery step
  530.     if state.discoveryActive and currentTime - lastDiscoveryStep >= 2 then
  531.       runDiscoveryStep()
  532.       lastDiscoveryStep = currentTime
  533.     end
  534.    
  535.     -- Display status
  536.     if currentTime - lastStatusDisplay >= 5 then
  537.       displayStatus()
  538.       lastStatusDisplay = currentTime
  539.     end
  540.    
  541.     -- Handle messages
  542.     local _, _, sender, port, distance, command, data = event.pull(0.1, "modem_message")
  543.    
  544.     if command then
  545.       handleMessage(sender, port, distance, command, data)
  546.     end
  547.   end
  548. end
  549.  
  550. -- Cleanup
  551. local function cleanup()
  552.   print("")
  553.   print("=== SERVER SHUTTING DOWN ===")
  554.  
  555.   -- Save data
  556.   saveData()
  557.  
  558.   -- Close modem
  559.   modem.close(PORT)
  560.  
  561.   print("✓ Server stopped")
  562. end
  563.  
  564. -- Error handling
  565. local success, err = xpcall(main, debug.traceback)
  566.  
  567. if not success then
  568.   print("")
  569.   print("ERROR: " .. tostring(err))
  570. end
  571.  
  572. cleanup()
  573.  
Advertisement
Add Comment
Please, Sign In to add comment