Advertisement
opencomputerstest2

IE Diesel Generator Control

Mar 25th, 2023
608
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.18 KB | Gaming | 0 0
  1. --Tame your naughty diesel generator with this script! No more wasted power!
  2. print("Starting Diesel Control v3.5\n")
  3. --End config
  4.  
  5. --Constants
  6. local component = require("component")
  7. local event = require("event")
  8. local diesel = component.ie_diesel_generator
  9. local gpu = component.gpu
  10.  
  11.  --Variables
  12. local run = true
  13.  
  14.  
  15. --Enable computer control of the generator.
  16. diesel.enableComputerControl(true)
  17. os.sleep(1)
  18. diesel.setEnabled(false)
  19.  
  20.  
  21. local function display(str)
  22.     local x = gpu.getViewport() - (string.len(str) - 1)
  23.     gpu.set(x, 1, str)
  24. end
  25.  
  26. local function getCaps()
  27.     --Reset on every read
  28.     local totalMax = 0
  29.     local total = 0
  30.     --Read every capacitor's max charge, and it's charge
  31.     for addr, typ in component.list("v_capacitor") do
  32.         totalMax = totalMax + component.invoke(addr, "getMaxEnergyStored")
  33.         total = total + component.invoke(addr, "getEnergyStored")
  34.     end
  35.     if totalMax == 0 then error("no capacitors :(") end
  36.     --Return the charge level in percent form.
  37.     return math.ceil((total / totalMax) * 100)
  38. end
  39.  
  40.  
  41.  
  42. local function getTank()
  43.     local raw = diesel.getTankInfo()
  44.     local out = {}
  45.     out["percent"] = math.ceil((raw["amount"] / raw["capacity"]) * 100)
  46.     out["type"] = raw["label"]
  47.     return out
  48. end
  49.  
  50. local function run()
  51.     --Read the charge level in percent
  52.     charge = getCaps()
  53.     --Read the fuel level and type
  54.     if charge ~= lastMeas then
  55.         if charge > 90 then
  56.             status = "Off "
  57.             diesel.setEnabled(false)
  58.         elseif charge < 80 then
  59.             status = " On "
  60.             diesel.setEnabled(true)
  61.         end
  62.         display(status .. charge .. "%")
  63.     end
  64.     --Set the last measurement so we can tell if it has
  65.     --changed while we were away.
  66.     lastMeas = charge
  67. end
  68.  
  69. local timer = event.timer(1, run, math.huge)
  70.  
  71.  
  72. local function stop()
  73.     print("Caught interrupt, stopping.")
  74.     --Stop main control loop
  75.     event.cancel(timer)
  76.     --Shutdown generator
  77.     diesel.setEnabled(false)
  78.     diesel.enableComputerControl(false)
  79.     --Stop script
  80.     event.ignore("interrupted", stop)
  81.     print("Stopped")
  82. end
  83. event.listen("interrupted", stop)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement