firex20

regulate_turbine_energy

Nov 10th, 2025 (edited)
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 4.59 KB | Gaming | 0 0
  1. -- energy_redstone_control.lua
  2. -- Enciende redstone por <redstoneSide> cuando la energía >= highThreshold (porcentaje)
  3. -- y apaga cuando la energía <= lowThreshold.
  4. -- Uso:
  5. --   shell.run("energy_redstone_control", <energySide>, <redstoneSide>, <highPct>, <lowPct>, <pollInterval>)
  6. -- Ejemplo:
  7. --   shell.run("energy_redstone_control", "back", "left", "0.9", "0.5", "1")
  8.  
  9. local args = {...}
  10. local energySide  = args[1] or "back"   -- lado donde está el bloque que almacena energía
  11. local redstoneSide = args[2] or "left" -- lado por donde emitir la señal de redstone
  12. local highPct     = tonumber(args[3]) or 0.90  -- umbral ON (90% por defecto)
  13. local lowPct      = tonumber(args[4]) or 0.50  -- umbral OFF (50% por defecto)
  14. local pollInterval = tonumber(args[5]) or 1    -- segundos entre comprobaciones
  15.  
  16. -- función segura para llamar a métodos del periférico
  17. local function tryCall(side, method, ...)
  18.   local ok, res = pcall(peripheral.call, side, method, ...)
  19.   if not ok then return nil, res end
  20.   return res
  21. end
  22.  
  23. -- intenta obtener energía y capacidad usando varios nombres comunes
  24. local function getEnergy(side)
  25.   local tries = {
  26.     {"getEnergyStored", "getMaxEnergyStored"},
  27.     {"getEnergyStored", "getEnergyCapacity"},
  28.     {"getEnergy", "getMaxEnergy"},
  29.     {"getEnergy", "getEnergyCapacity"},
  30.     {"getEnergyStats"} -- puede devolver tabla {energy=.., capacity=..} o {energy, capacity}
  31.   }
  32.  
  33.   for _, pair in ipairs(tries) do
  34.     local curMeth, capMeth = pair[1], pair[2]
  35.     if capMeth then
  36.       local ok1, cur = pcall(peripheral.call, side, curMeth)
  37.       local ok2, cap = pcall(peripheral.call, side, capMeth)
  38.       if ok1 and ok2 and type(cur) == "number" and type(cap) == "number" then
  39.         return cur, cap
  40.       end
  41.       -- algunos mods devuelven tabla en una llamada
  42.       if ok1 and type(cur) == "table" and (cur.energy or cur.energyStored or cur.capacity or cur.maxEnergy) then
  43.         local c = cur.energy or cur.energyStored or cur.energy or cur.amount
  44.         local capv = cur.capacity or cur.maxEnergy or cur.max or cur.energyCapacity
  45.         if type(c) == "number" and type(capv) == "number" then
  46.           return c, capv
  47.         end
  48.       end
  49.     else
  50.       -- caso de getEnergyStats()
  51.       local ok, res = pcall(peripheral.call, side, curMeth)
  52.       if ok and type(res) == "table" then
  53.         -- intentar distintos formatos
  54.         if type(res.energy) == "number" and type(res.capacity) == "number" then
  55.           return res.energy, res.capacity
  56.         elseif type(res[1]) == "number" and type(res[2]) == "number" then
  57.           return res[1], res[2]
  58.         end
  59.       end
  60.     end
  61.   end
  62.  
  63.   return nil, nil
  64. end
  65.  
  66. -- set redstone safely (no pcall necesario; setOutput no falla si lado inválido, pero por seguridad usamos pcall)
  67. local function setRedstone(side, state)
  68.   pcall(redstone.setOutput, side, state)
  69. end
  70.  
  71. -- Helper visual
  72. local function fmt(n)
  73.   if not n then return "nil" end
  74.   return tostring(math.floor(n + 0.5))
  75. end
  76.  
  77. -- Comprobaciones iniciales
  78. print(("Control de energía -> energySide=%s, redstoneSide=%s, ON>=%.0f%%, OFF<=%.0f%%, poll=%.1fs")
  79.       :format(energySide, redstoneSide, highPct*100, lowPct*100, pollInterval))
  80.  
  81. local outputOn = false
  82.  
  83. while true do
  84.   if not peripheral.isPresent(energySide) then
  85.     print("No hay periférico detectado en: " .. tostring(energySide))
  86.     -- no bloque; dejar salida en off y esperar
  87.     if outputOn then
  88.       setRedstone(redstoneSide, false)
  89.       outputOn = false
  90.       print("Salida redstone DESACTIVADA (no hay periférico).")
  91.     end
  92.     sleep(pollInterval)
  93.   else
  94.     local energy, capacity = getEnergy(energySide)
  95.     if not energy or not capacity or capacity == 0 then
  96.       print("No se pudo leer energía desde " .. tostring(energySide))
  97.       sleep(pollInterval)
  98.     else
  99.       local pct = energy / capacity
  100.       local pctDisplay = pct * 100
  101.       -- imprimir estado
  102.       term.clear()
  103.       term.setCursorPos(1,1)
  104.       print(("Energía: %s / %s FE (%.1f%%)"):format(fmt(energy), fmt(capacity), pctDisplay))
  105.       print(("Salida actual: %s"):format(outputOn and "ON" or "OFF"))
  106.  
  107.       -- lógica con histéresis
  108.       if not outputOn and pct >= highPct then
  109.         outputOn = true
  110.         setRedstone(redstoneSide, true)
  111.         print(("== Umbral alcanzado (>= %.0f%%). Salida ACTIVADA"):format(highPct*100))
  112.       elseif outputOn and pct <= lowPct then
  113.         outputOn = false
  114.         setRedstone(redstoneSide, false)
  115.         print(("== Energía baja (<= %.0f%%). Salida DESACTIVADA"):format(lowPct*100))
  116.       end
  117.  
  118.       sleep(pollInterval)
  119.     end
  120.   end
  121. end
  122.  
Advertisement
Add Comment
Please, Sign In to add comment