Advertisement
Calenria

BigReactor

Dec 11th, 2014
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 93.99 KB | None | 0 0
  1. --[[
  2. Program name: Lolmer's EZ-NUKE reactor control system
  3. Version: v0.3.14
  4. Programmer: Lolmer
  5. Great assistance by Mechaet
  6. Last update: 2014-09-30
  7. Pastebin: http://pastebin.com/fguScPBQ
  8.  
  9. Description:
  10. This program controls a Big Reactors nuclear reactor in Minecraft with a Computercraft computer, using Computercraft's own wired modem connected to the reactors computer control port.
  11.  
  12. This program was designed to work with the mods and versions installed on Never Stop Toasting (NST) Diet http://www.technicpack.net/modpack/details/never-stop-toasting-diet.254882 Endeavour: Never Stop Toasting: Diet official Minecraft server http://forums.somethingawful.com/showthread.php?threadid=3603757
  13.  
  14. To simplify the code and guesswork, I assume the following monitor layout, where each "monitor" listed below is a collection of 3 wide by two high Advanced Monitors:
  15. 1) One Advanced Monitor for overall status display plus
  16.     one or more Reactors plus
  17.     none or more Turbines.
  18. 2) One Advanced Monitor for overall status display plus (furthest monitor from computer by cable length)
  19.     one Advanced Monitor for each connected Reactor plus (subsequent found monitors)
  20.     one Advanced Monitor for each connected Turbine (last group of monitors found).
  21. If you enable debug mode, add one additional Advanced Monitor for #1 or #2.
  22.  
  23. Notes:
  24.     Only one reactor and one, two, and three turbines have been tested with the above, but IN THEORY any number is supported.
  25.     Devices are found in the reverse order they are plugged in, so monitor_10 will be found before monitor_9.
  26.     Two 15x15x14 Turbines can output 260K RF/t by just one 7^3 (four rods) reactor putting out 4k mB steam.
  27.  
  28. When using actively cooled reactors with turbines, keep the following in mind:
  29.     - 1 mB steam carries up to 10RF of potential energy to extract in a turbine.
  30.     - Actively cooled reactors produce steam, not power.
  31.     - You will need about 10 mB of water for each 1 mB of steam that you want to create in a 7^3 reactor.
  32.  
  33. Features:
  34.     Configurable min/max energy buffer and min/max temperature via ReactorOptions file.
  35.     ReactorOptions is read on start and then current values are saved every program cycle.
  36.     Rod Control value in ReactorOptions is only useful for initial start, after that the program saves the current Rod Control average over all Fuel Rods for next boot.
  37.     Auto-adjusts control rods per reactor to maintain temperature.
  38.     Will display reactor data to all attached monitors of correct dimensions.
  39.         For multiple monitors, the first monitor (often last plugged in) is the overall status monitor.
  40.     For multiple monitors, the first monitor (often last plugged in) is the overall status monitor.
  41.     A new cruise mode from mechaet, ONLINE will be "blue" when active, to keep your actively cooled reactors running smoothly.
  42.  
  43. GUI Usage:
  44.     The "<" and ">" buttons, when right-clicked with the mouse, will decrease and increase, respectively, the values assigned to the monitor:
  45.         "Rod (%)" will lower/raise the Reactor Control Rods for that Reactor
  46.         "mB/t" will lower/raise the Turbine Flow Rate maximum for that Turbine
  47.         "RPM" will lower/raise the target Turbine RPM for that Turbine
  48.     Right-clicking between the "<" and ">" (not on them) will disable auto-adjust of that value for attached device.
  49.         Right-clicking on the "Enabled" or "Disabled" text for auto-adjust will do the same.
  50.     Right-clicking on "ONLINE" or "OFFLINE" at the top-right will toggle the state of attached device.
  51.  
  52. Default values:
  53.     Rod Control: 90% (Let's start off safe and then power up as we can)
  54.     Minimum Energy Buffer: 15% (will power on below this value)
  55.     Maximum Energy Buffer: 85% (will power off above this value)
  56.     Minimum Passive Cooling Temperature: 950^C (will raise control rods below this value)
  57.     Maximum Passive Cooling Temperature: 1,400^C (will lower control rods above this value)
  58.     Minimum Active Cooling Temperature: 300^C (will raise the control rods below this value)
  59.     Maximum Active Cooling Temperature: 420^C (will lower control rods above this value)
  60.     Optimal Turbine RPM:  900, 1,800, or 2,700 (divisible by 900)
  61.     New user-controlled option for target speed of turbines, defaults to 2726RPM, which is high-optimal.
  62.  
  63. Requirements:
  64.     Advanced Monitor size is X: 29, Y: 12 with a 3x2 size
  65.     Computer or Advanced Computer
  66.     Modems (not wireless) connecting each of the Computer to both the Advanced Monitor and Reactor Computer Port.
  67.     Big Reactors (http://www.big-reactors.com/) 0.3.2A+
  68.     Computercraft (http://computercraft.info/) 1.63+
  69.     Reset the computer any time number of connected devices change.
  70.  
  71. Resources:
  72. This script is available from:
  73.     http://pastebin.com/fguScPBQ
  74.     https://github.com/sandalle/minecraft_bigreactor_control
  75. Start-up script is available from:
  76.     http://pastebin.com/ZTMzRLez
  77.     https://github.com/sandalle/minecraft_bigreactor_control
  78. Other reactor control program which I based my program on:
  79.     http://pastebin.com/aMAu4X5J (ScatmanJohn)
  80.     http://pastebin.com/HjUVNDau (version ScatmanJohn based his on)
  81. A simpler Big Reactor control program is available from:
  82.     http://pastebin.com/7S5xCvgL (IronClaymore only for passively cooled reactors)
  83.  
  84.     Reactor Computer Port API: http://wiki.technicpack.net/Reactor_Computer_Port
  85.     Computercraft API: http://computercraft.info/wiki/Category:APIs
  86.     Big Reactors Efficiency, Speculation and Questions! http://www.reddit.com/r/feedthebeast/comments/1vzds0/big_reactors_efficiency_speculation_and_questions/
  87.     Big Reactors API code: https://github.com/erogenousbeef/BigReactors/blob/master/erogenousbeef/bigreactors/common/multiblock/tileentity/TileEntityReactorComputerPort.java
  88.     Big Reactors API: http://big-reactors.com/cc_api.html
  89.  
  90. ChangeLog:
  91. - 0.3.14
  92.     - Fix Issue #5. EZ-Nuke should now work with ComputerCraft 1.58 or 1.63.
  93.  
  94. - 0.3.13
  95.     - Fix one reactor and one monitor incorrectly using status display instead of control display (Issue #35)
  96.     - Fix concatenating a string and boolean, see http://stackoverflow.com/questions/6615572/how-to-format-a-lua-string-with-a-boolean-variable
  97.     - Hopefully fix concatenating string and nul in printLog (Issue #3)
  98.  
  99. - 0.3.12
  100.     - Mechaet's changes:
  101.     - Redid some typing to correct a bug where the reactors always started with rod control disabled.
  102.  
  103. - 0.3.11
  104.     - Mechaet's changes:
  105.     - Cleaned up global variables list
  106.     - Added in per-device naming (displays a friendly name on the bottom of the monitor if configured in the device options file)
  107.     - Bigger bypasses of control routines when the control has been overridden
  108.     - Individual config files for turbines and reactors. Persistent between reboots, remembers your last saved settings.
  109.     - Cruise mode override bypass
  110.     - Changing flow rate no longer toggles flow rate override on and off. Changing the flow rate clearly indicates intent, so we put the override flag on and leave it there.
  111.     - Changed the rate at which the regular algorithm adjusts reactor rod control rates. Instead of being 1:1 we now move at 1:5 speed because there is a wide loophole where big adjustments can cause a swinging pendulum effect continually missing the target.
  112.  
  113. - 0.3.10
  114.     - Turbine algorithm pass by Mechaet.
  115.     - Updated turbine GUI.
  116.     - Fix single monitor (again) for Issue #22.
  117.  
  118. - 0.3.9
  119.     - Reactor algorithm pass by Mechaet.
  120.     - Additional user config options by Mechaet.
  121.     - Fix multiple reactors and none or more turbines with only one status monitor.
  122.     - Fix monitor scaling after one was used as debug (or in case of other modifications).
  123.     - Cruise mode implemented, defaults off but is saved between boots.
  124.     - Fix energy/% displays to match Big Reactors' GUI (Issue #9).
  125.     - Always write out found devices on computer terminal.
  126.     - Much improved round() function from mechaet (Issue #14).
  127.     - Refactoring pass/algorithm change on the reactor temperature control. Should now adjust in increments to achieve the desired temperature range quicker and more accurately.
  128.     - Optimal passive-cooled reactor temperature range changed from 850-900 to 950-1400.
  129.     - Fix display Issue #15.
  130.  
  131. - 0.3.8
  132.     - Update to ComputerCraft 1.6 API (only term.restore() -> term.native() required :)).
  133.  
  134. - 0.3.7
  135.     - Fix typo when initializing TurbineNames array.
  136.     - Fix Issue #1, turbine display is using the Reactor buffer size (10M RF) instead of the Turbine buffer size (1M RF).
  137.  
  138. - 0.3.6
  139.     - Fix multi-reactors displaying on the correct monitors (thanks HybridFusion).
  140.     - Fix rod auto-adjust text position.
  141.     - Reactors store 10M RF and Turbines store 1M RF in their buffer.
  142.     - Add more colour to displayAllStatus().
  143.     - Sleep for only two seconds instead of five.
  144.     - Fix getDeviceStoredEnergyBufferPercent() for Reactors storing 10M RF in buffer.
  145.     - Keep actively cooled reactors between 0-300^C (non-configurable for now).
  146.  
  147. - 0.3.5
  148.     - Do not discover connected devices every loop - nicer on servers. Reset computer anytime number of connected devices change.
  149.     - Fix multi-reactor setups to display the additional reactors on monitors, rather than the last one found.
  150.     - Fix passive reactor display having auto-adjust and energy buffer overwrite each other (removes rod count).
  151.  
  152. - 0.3.4
  153.     - Fix arithmetic for checking if we have enough monitors for the number of reactors.
  154.     - Turbines are optimal at 900, 1800, *and* 2700 RPM
  155.     - Increase loop timer from 1 to 5 to be nicer to servers
  156.  
  157. - 0.3.3
  158.     - Add Big Reactors Turbine support.
  159.     - First found monitor (appears to be last connected monitor) is used to display status of all found devices (if more than one valid monitor is found)
  160.     - Display monitor number on top left of each monitor as "M#" to help find which monitor is which.
  161.     - Enabling debug will use the last monitor found, if more than one, to print out debug info (also written to file)
  162.     - Only clear monitors when we're about to use them (e.g. turbine monitors no longer clear, then wait for all reactors to update)
  163.     - Fix getDeviceStoredEnergyBufferPercent(), was off by a decimal place
  164.     - Just use first Control Rod level for entire reactor, they are no longer treated individually in BR 0.3
  165.     - Allow for one monitor for n number of reactors and m number of turbines
  166.     - Auto-adjust turbine flow rate by 25 mB to keep rotor speed at 900 or 1,800 RPM.
  167.     - Clicks on monitors relate to what the monitor is showing (e.g. clicking on reactor 1's display won't modify turbine 1's nor reactor 2's values)
  168.     - Print monitor name and device (reactor|turbine) name in blue to monitor associated for easier design by users.
  169.     - Remove version number from monitors to free up space for monitor names.
  170.     - Add option of right-clicking on "Enabled"/"Disabled" of auto-adjust to toggle it.
  171.  
  172. - 0.3.2
  173.     - Allow for rod control to override (disable) auto-adjust via UI (Rhonyn)
  174.  
  175. - 0.3.1
  176.     - Add fuel consumption per tick to display
  177.  
  178. - 0.3.0
  179.     - Add multi-monitor support! Sends one reactor's data to all monitors.
  180.     - print function now takes table to support optional specified monitor
  181.     - Set "numRods" every cycle for some people (mechaet)
  182.     - Don't redirect terminal output with multiple monitor support
  183.     - Log troubleshooting data to reactorcontrol.log
  184.     - FC_API no longer used (copied and modified what I needed)
  185.     - Multi-reactor support is theoretically implemented, but it is UNTESTED!
  186.     - Updated for Big Reactor 0.3 (no longer works with 0.2)
  187.     - BR getFuelTemperature() now returns many significant digits, just use math.ceil()
  188.     - BR 0.3 removed individual rod temperatures, now it's only reactor-level temperature
  189.  
  190. - 0.2.4
  191.     - Simplify math, don't divide by a simple large number and then multiply by 100 (#/10000000*100)
  192.     - Fix direct-connected (no modem) devices. getDeviceSide -> FC_API.getDeviceSide (simple as that :))
  193.  
  194. - 0.2.3
  195.     - Check bounds on reactor.setRodControlLevel(#,#), Big Reactor doesn't check for us.
  196.  
  197. - 0.2.2
  198.     - Do not auto-start the reactor if it was manually powered off (autoStart=false)
  199.  
  200. - 0.2.1
  201.     - Lower/raise only the hottest/coldest Control Rod while trying to control the reactor temperature.
  202.     - "<" Rod Control buttons was off by one (to the left)
  203.  
  204. - 0.2.0 - Lolmer Edition :)
  205.     - Add min/max stored energy percentage (default is 15%/85%), configurable via ReactorOptions file.
  206.     - No reason to keep burning fuel if our power output is going nowhere. :)
  207.     - Use variables variable for the title and version.
  208.     - Try to keep the temperature between configured values (default is 850^C-950^C)
  209.     - Add Waste and number of Control/Fuel Rods to displayBards()
  210.  
  211. TODO:
  212. - Save parameters per reactor instead of one global set for all reactors.
  213. - Add min/max RF/t output and have it override temperature concerns (maybe?).
  214. - Add support for wireless modems, see http://computercraft.info/wiki/Modem_%28API%29, will not be secure (anyone can send/listen to your channels)!
  215. - Add support for any sized monitor (minimum 3x3), dynamic allocation/alignment.
  216. - Lookup using pcall for better error handling http://www.computercraft.info/forums2/index.php?/topic/10992-using-pcall/ .
  217. - Update cruise mode to work independently for each actively-cooled reactor.
  218.  
  219. ]]--
  220.  
  221.  
  222. -- Some global variables
  223. local progVer = ""
  224. local progName = "Energyroom"
  225. local sideClick, xClick, yClick = nil, 0, 0
  226. local loopTime = 2
  227. local controlRodAdjustAmount = 1 -- Default Reactor Rod Control % adjustment amount
  228. local flowRateAdjustAmount = 25 -- Default Turbine Flow Rate in mB adjustment amount
  229. local debugMode = false
  230. -- End multi-reactor cleanup section
  231. local minStoredEnergyPercent = nil -- Max energy % to store before activate
  232. local maxStoredEnergyPercent = nil -- Max energy % to store before shutdown
  233. local monitorList = {} -- Empty monitor array
  234. local monitorNames = {} -- Empty array of monitor names
  235. local reactorList = {} -- Empty reactor array
  236. local reactorNames = {} -- Empty array of reactor names
  237. local turbineList = {} -- Empty turbine array
  238. local turbineNames = {} -- Empty array of turbine names
  239. local turbineMonitorOffset = 0 -- Turbines are assigned monitors after reactors
  240.  
  241.  
  242. term.clear()
  243. term.setCursorPos(2,1)
  244. write("Initializing program...\n")
  245.  
  246.  
  247. -- File needs to exist for append "a" later and zero it out if it already exists
  248. -- Always initalize this file to avoid confusion with old files and the latest run
  249. local logFile = fs.open("reactorcontrol.log", "w")
  250. if logFile then
  251.     logFile.writeLine("Minecraft time: Day "..os.day().." at "..textutils.formatTime(os.time(),true))
  252.     logFile.close()
  253. else
  254.     error("Could not open file reactorcontrol.log for writing.")
  255. end
  256.  
  257.  
  258. -- Helper functions
  259.  
  260. local function termRestore()
  261.   local ccVersion = nil
  262.   ccVersion = os.version()
  263.  
  264.     if ccVersion == "CraftOS 1.6" then
  265.         term.native()
  266.     elseif ccVersion == "CraftOS 1.5" then
  267.         term.restore()
  268.     else -- Default to older term.restore
  269.         printLog("Unsupported CraftOS found. Reported version is \""..ccVersion.."\".")
  270.         term.restore()
  271.     end -- if ccVersion
  272. end -- function termRestore()
  273.  
  274. local function printLog(printStr)
  275.     if debugMode then
  276.         -- If multiple monitors, use the last monitor for debugging if debug is enabled
  277.         if #monitorList > 1 then
  278.             term.redirect(monitorList[#monitorList]) -- Redirect to last monitor for debugging
  279.             monitorList[#monitorList].setTextScale(0.5) -- Fit more logs on screen
  280.             write(printStr.."\n")   -- May need to use term.scroll(x) if we output too much, not sure
  281.             termRestore()
  282.         end -- if #monitorList > 1 then
  283.  
  284.         local logFile = fs.open("reactorcontrol.log", "a") -- See http://computercraft.info/wiki/Fs.open
  285.         if logFile then
  286.             logFile.writeLine(printStr)
  287.             logFile.close()
  288.         else
  289.             error("Cannot open file reactorcontrol.log for appending!")
  290.         end -- if logFile then
  291.     end -- if debugMode then
  292. end -- function printLog(printStr)
  293.  
  294. -- Trim a string
  295. function stringTrim(s)
  296.     assert(s ~= nil, "String can't be nil")
  297.     return(string.gsub(s, "^%s*(.-)%s*$", "%1"))
  298. end
  299.  
  300. config = {}
  301.  
  302. -- Save a table into a config file
  303. -- path: path of the file to write
  304. -- tab: table to save
  305. config.save = function(path, tab)
  306.     printLog("Save function called for config for "..path.." EOL")
  307.     assert(path ~= nil, "Path can't be nil")
  308.     assert(type(tab) == "table", "Second parameter must be a table")
  309.     local f = io.open(path, "w")
  310.     local i = 0
  311.     for key, value in pairs(tab) do
  312.         if i ~= 0 then
  313.             f:write("\n")
  314.         end
  315.         f:write("["..key.."]".."\n")
  316.         for key2, value2 in pairs(tab[key]) do
  317.             key2 = stringTrim(key2)
  318.             --doesn't like boolean values
  319.             if (type(value2) ~= "boolean") then
  320.             value2 = stringTrim(value2)
  321.             else
  322.             value2 = tostring(value2)
  323.             end
  324.             key2 = key2:gsub(";", "\\;")
  325.             key2 = key2:gsub("=", "\\=")
  326.             value2 = value2:gsub(";", "\\;")
  327.             value2 = value2:gsub("=", "\\=")   
  328.             f:write(key2.."="..value2.."\n")
  329.         end
  330.         i = i + 1
  331.     end
  332.     f:close()
  333. end --config.save = function(path, tab)
  334.  
  335. -- Load a config file
  336. -- path: path of the file to read
  337. config.load = function(path)
  338.     printLog("Load function called for config for "..path.." EOL")
  339.     assert(path ~= nil, "Path can't be nil")
  340.     local f = fs.open(path, "r")
  341.     if f ~= nil then
  342.         local tab = {}
  343.         local line = ""
  344.         local newLine
  345.         local i
  346.         local currentTag = nil
  347.         local found = false
  348.         local pos = 0
  349.         while line ~= nil do
  350.             found = false      
  351.             line = line:gsub("\\;", "#_!36!_#") -- to keep \;
  352.             line = line:gsub("\\=", "#_!71!_#") -- to keep \=
  353.             if line ~= "" then
  354.                 -- Delete comments
  355.                 newLine = line
  356.                 line = ""
  357.                 for i=1, string.len(newLine) do            
  358.                     if string.sub(newLine, i, i) ~= ";" then
  359.                         line = line..newLine:sub(i, i)                     
  360.                     else               
  361.                         break
  362.                     end
  363.                 end
  364.                 line = stringTrim(line)
  365.                 -- Find tag        
  366.                 if line:sub(1, 1) == "[" and line:sub(line:len(), line:len()) == "]" then
  367.                     currentTag = stringTrim(line:sub(2, line:len()-1))
  368.                     tab[currentTag] = {}
  369.                     found = true                           
  370.                 end
  371.                 -- Find key and values
  372.                 if not found and line ~= "" then               
  373.                     pos = line:find("=")               
  374.                     if pos == nil then
  375.                         error("Bad INI file structure")
  376.                     end
  377.                     line = line:gsub("#_!36!_#", ";")
  378.                     line = line:gsub("#_!71!_#", "=")
  379.                     tab[currentTag][stringTrim(line:sub(1, pos-1))] = stringTrim(line:sub(pos+1, line:len()))
  380.                     found = true           
  381.                 end        
  382.             end
  383.             line = f.readLine()
  384.         end
  385.        
  386.         f:close()
  387.        
  388.         return tab
  389.     else
  390.         return nil
  391.     end
  392. end --config.load = function(path)
  393.  
  394.  
  395.  
  396. -- round() function from mechaet
  397. local function round(num, places)
  398.     local mult = 10^places
  399.     local addon = nil
  400.     if ((num * mult) < 0) then
  401.         addon = -.5
  402.     else
  403.         addon = .5
  404.     end
  405.  
  406.     local integer, decimal = math.modf(num*mult+addon)
  407.     newNum = integer/mult
  408.     printLog("Called round(num="..num..",places="..places..") returns \""..newNum.."\".")
  409.     return newNum
  410. end -- function round(num, places)
  411.  
  412.  
  413. local function print(printParams)
  414.     -- Default to xPos=1, yPos=1, and first monitor
  415.     setmetatable(printParams,{__index={xPos=1, yPos=1, monitorIndex=1}})
  416.     local printString, xPos, yPos, monitorIndex =
  417.         printParams[1], -- Required parameter
  418.         printParams[2] or printParams.xPos,
  419.         printParams[3] or printParams.yPos,
  420.         printParams[4] or printParams.monitorIndex
  421.  
  422.     local monitor = nil
  423.     monitor = monitorList[monitorIndex]
  424.  
  425.     if not monitor then
  426.         printLog("monitor["..monitorIndex.."] in print() is NOT a valid monitor.")
  427.         return -- Invalid monitorIndex
  428.     end
  429.  
  430.     monitor.setCursorPos(xPos, yPos)
  431.     monitor.write(printString)
  432. end -- function print(printParams)
  433.  
  434.  
  435. -- Replaces the one from FC_API (http://pastebin.com/A9hcbZWe) and adding multi-monitor support
  436. local function printCentered(printString, yPos, monitorIndex)
  437.     local monitor = nil
  438.     monitor = monitorList[monitorIndex]
  439.  
  440.     if not monitor then
  441.         printLog("monitor["..monitorIndex.."] in printCentered() is NOT a valid monitor.")
  442.         return -- Invalid monitorIndex
  443.     end
  444.  
  445.     local width, height = monitor.getSize()
  446.     local monitorNameLength = 0
  447.  
  448.     -- Special changes for title bar
  449.     if yPos == 1 then
  450.         -- Add monitor name to first line
  451.         monitorNameLength = 0
  452.  
  453.         -- Leave room for "offline" and "online" on the right except for overall status display
  454.         if (#monitorList ~= 1) and (monitorIndex ~= 1) then
  455.             width = width - 7
  456.         end
  457.     end
  458.  
  459.     monitor.setCursorPos(math.floor(width/2) - math.ceil(printString:len()/2) +  monitorNameLength/2, yPos)
  460.     monitor.clearLine()
  461.     monitor.write(printString)
  462.  
  463.     monitor.setTextColor(colors.blue)
  464.     --print{monitorNames[monitorIndex], 1, 1, monitorIndex}
  465.     monitor.setTextColor(colors.white)
  466. end -- function printCentered(printString, yPos, monitorIndex)
  467.  
  468.  
  469. -- Print text padded from the left side
  470. -- Clear the left side of the screen
  471. local function printLeft(printString, yPos, monitorIndex)
  472.     local monitor = nil
  473.     monitor = monitorList[monitorIndex]
  474.  
  475.     if not monitor then
  476.         printLog("monitor["..monitorIndex.."] in printLeft() is NOT a valid monitor.")
  477.         return -- Invalid monitorIndex
  478.     end
  479.  
  480.     local gap = 1
  481.     local width = monitor.getSize()
  482.  
  483.     -- Clear left-half of the monitor
  484.  
  485.     for curXPos = 1, (width / 2) do
  486.         monitor.setCursorPos(curXPos, yPos)
  487.         monitor.write(" ")
  488.     end
  489.  
  490.     -- Write our string left-aligned
  491.     monitor.setCursorPos(1+gap, yPos)
  492.     monitor.write(printString)
  493. end
  494.  
  495.  
  496. -- Print text padded from the right side
  497. -- Clear the right side of the screen
  498. local function printRight(printString, yPos, monitorIndex)
  499.     local monitor = nil
  500.     monitor = monitorList[monitorIndex]
  501.  
  502.     if not monitor then
  503.         printLog("monitor["..monitorIndex.."] in printRight() is NOT a valid monitor.")
  504.         return -- Invalid monitorIndex
  505.     end
  506.  
  507.     -- Make sure printString is a string
  508.     printString = tostring(printString)
  509.  
  510.     local gap = 1
  511.     local width = monitor.getSize()
  512.  
  513.     -- Clear right-half of the monitor
  514.     for curXPos = (width/2), width do
  515.         monitor.setCursorPos(curXPos, yPos)
  516.         monitor.write(" ")
  517.     end
  518.  
  519.     -- Write our string right-aligned
  520.     monitor.setCursorPos(math.floor(width) - math.ceil(printString:len()+gap), yPos)
  521.     monitor.write(printString)
  522. end
  523.  
  524.  
  525. -- Replaces the one from FC_API (http://pastebin.com/A9hcbZWe) and adding multi-monitor support
  526. local function clearMonitor(printString, monitorIndex)
  527.     local monitor = nil
  528.     monitor = monitorList[monitorIndex]
  529.  
  530.     printLog("Called as clearMonitor(printString="..printString..",monitorIndex="..monitorIndex..").")
  531.  
  532.     if not monitor then
  533.         printLog("monitor["..monitorIndex.."] in clearMonitor(printString="..printString..",monitorIndex="..monitorIndex..") is NOT a valid monitor.")
  534.         return -- Invalid monitorIndex
  535.     end
  536.  
  537.     local gap = 2
  538.     monitor.clear()
  539.     local width, height = monitor.getSize()
  540.     monitor.setTextScale(1.0) -- Make sure scale is correct
  541.  
  542.     printCentered(printString, 1, monitorIndex)
  543.     monitor.setTextColor(colors.blue)
  544.     print{monitorNames[monitorIndex], 1, 1, monitorIndex}
  545.     monitor.setTextColor(colors.white)
  546.  
  547.     for i=1, width do
  548.         monitor.setCursorPos(i, gap)
  549.         monitor.write("-")
  550.     end
  551.  
  552.     monitor.setCursorPos(1, gap+1)
  553. end -- function clearMonitor(printString, monitorIndex)
  554.  
  555.  
  556. -- Return a list of all connected (including via wired modems) devices of "deviceType"
  557. local function getDevices(deviceType)
  558.     printLog("Called as getDevices(deviceType="..deviceType..")")
  559.  
  560.     local deviceName = nil
  561.     local deviceIndex = 1
  562.     local deviceList, deviceNames = {}, {} -- Empty array, which grows as we need
  563.     local peripheralList = peripheral.getNames() -- Get table of connected peripherals
  564.  
  565.     deviceType = deviceType:lower() -- Make sure we're matching case here
  566.  
  567.     for peripheralIndex = 1, #peripheralList do
  568.         -- Log every device found
  569.         -- printLog("Found "..peripheral.getType(peripheralList[peripheralIndex]).."["..peripheralIndex.."] attached as \""..peripheralList[peripheralIndex].."\".")
  570.         if (string.lower(peripheral.getType(peripheralList[peripheralIndex])) == deviceType) then
  571.             -- Log devices found which match deviceType and which device index we give them
  572.             printLog("Found "..peripheral.getType(peripheralList[peripheralIndex]).."["..peripheralIndex.."] as index \"["..deviceIndex.."]\" attached as \""..peripheralList[peripheralIndex].."\".")
  573.             write("Found "..peripheral.getType(peripheralList[peripheralIndex]).."["..peripheralIndex.."] as index \"["..deviceIndex.."]\" attached as \""..peripheralList[peripheralIndex].."\".\n")
  574.             deviceNames[deviceIndex] = peripheralList[peripheralIndex]
  575.             deviceList[deviceIndex] = peripheral.wrap(peripheralList[peripheralIndex])
  576.             deviceIndex = deviceIndex + 1
  577.         end
  578.     end -- for peripheralIndex = 1, #peripheralList do
  579.  
  580.     return deviceList, deviceNames
  581. end -- function getDevices(deviceType)
  582.  
  583. -- Draw a line across the entire x-axis
  584. local function drawLine(yPos, monitorIndex)
  585.     local monitor = nil
  586.     monitor = monitorList[monitorIndex]
  587.  
  588.     if not monitor then
  589.         printLog("monitor["..monitorIndex.."] in drawLine() is NOT a valid monitor.")
  590.         return -- Invalid monitorIndex
  591.     end
  592.  
  593.     local width, height = monitor.getSize()
  594.  
  595.     for i=1, width do
  596.         monitor.setCursorPos(i, yPos)
  597.         monitor.write("-")
  598.     end
  599. end -- function drawLine(yPos,monitorIndex)
  600.  
  601.  
  602. -- Display a solid bar of specified color
  603. local function drawBar(startXPos, startYPos, endXPos, endYPos, color, monitorIndex)
  604.     local monitor = nil
  605.     monitor = monitorList[monitorIndex]
  606.  
  607.     if not monitor then
  608.         printLog("monitor["..monitorIndex.."] in drawBar() is NOT a valid monitor.")
  609.         return -- Invalid monitorIndex
  610.     end
  611.  
  612.     -- PaintUtils only outputs to term., not monitor.
  613.     -- See http://www.computercraft.info/forums2/index.php?/topic/15540-paintutils-on-a-monitor/
  614.     term.redirect(monitor)
  615.     paintutils.drawLine(startXPos, startYPos, endXPos, endYPos, color)
  616.     monitor.setBackgroundColor(colors.black) -- PaintUtils doesn't restore the color
  617.     termRestore()
  618. end -- function drawBar(startXPos, startYPos,endXPos,endYPos,color,monitorIndex)
  619.  
  620.  
  621. -- Display single pixel color
  622. local function drawPixel(xPos, yPos, color, monitorIndex)
  623.     local monitor = nil
  624.     monitor = monitorList[monitorIndex]
  625.  
  626.     if not monitor then
  627.         printLog("monitor["..monitorIndex.."] in drawPixel() is NOT a valid monitor.")
  628.         return -- Invalid monitorIndex
  629.     end
  630.  
  631.     -- PaintUtils only outputs to term., not monitor.
  632.     -- See http://www.computercraft.info/forums2/index.php?/topic/15540-paintutils-on-a-monitor/
  633.     term.redirect(monitor)
  634.     paintutils.drawPixel(xPos, yPos, color)
  635.     monitor.setBackgroundColor(colors.black) -- PaintUtils doesn't restore the color
  636.     termRestore()
  637. end -- function drawPixel(xPos, yPos, color, monitorIndex)
  638.  
  639.  
  640. -- End helper functions
  641.  
  642.  
  643. -- Then initialize the monitors
  644. local function findMonitors()
  645.     -- Empty out old list of monitors
  646.     monitorList = {}
  647.  
  648.     printLog("Finding monitors...")
  649.     monitorList, monitorNames = getDevices("monitor")
  650.  
  651.     if #monitorList == 0 then
  652.         printLog("No monitors found!")
  653.         error("Can't find any monitors!")
  654.     else
  655.         for monitorIndex = 1, #monitorList do
  656.             local monitor, monitorX, monitorY = nil, nil, nil
  657.             monitor = monitorList[monitorIndex]
  658.  
  659.             if not monitor then
  660.                 printLog("monitorList["..monitorIndex.."] in findMonitors() is NOT a valid monitor.")
  661.  
  662.                 table.remove(monitorList, monitorIndex) -- Remove invalid monitor from list
  663.                 if monitorIndex ~= #monitorList then    -- If we're not at the end, clean up
  664.                     monitorIndex = monitorIndex - 1 -- We just removed an element
  665.                 end -- if monitorIndex == #monitorList then
  666.                 break -- Invalid monitorIndex
  667.             else -- valid monitor
  668.                 monitorX, monitorY = monitor.getSize()
  669.                 if (monitorX == nil) or (monitorY == nil) then -- somehow a valid monitor, but non-existent sizes? Maybe fixes Issue #3
  670.                     printLog("monitorList["..monitorIndex.."] in findMonitors() is NOT a valid sized monitor.")
  671.  
  672.                     table.remove(monitorList, monitorIndex) -- Remove invalid monitor from list
  673.                     if monitorIndex ~= #monitorList then    -- If we're not at the end, clean up
  674.                         monitorIndex = monitorIndex - 1 -- We just removed an element
  675.                     end -- if monitorIndex == #monitorList then
  676.                     break -- Invalid monitorIndex
  677.  
  678.                 -- Check for minimum size to allow for monitor.setTextScale(0.5) to work for 3x2 debugging monitor, changes getSize()
  679.                 elseif monitorX < 29 or monitorY < 12 then
  680.                     term.redirect(monitor)
  681.                     monitor.clear()
  682.                     printLog("Removing monitor "..monitorIndex.." for being too small.")
  683.                     monitor.setCursorPos(1,2)
  684.                     write("Monitor is the wrong size!\n")
  685.                     write("Needs to be at least 3x2.")
  686.                     termRestore()
  687.  
  688.                     table.remove(monitorList, monitorIndex) -- Remove invalid monitor from list
  689.                     if monitorIndex == #monitorList then    -- If we're at the end already, break from loop
  690.                         break
  691.                     else
  692.                         monitorIndex = monitorIndex - 1 -- We just removed an element
  693.                     end -- if monitorIndex == #monitorList then
  694.  
  695.                 end -- if monitorX < 29 or monitorY < 12 then
  696.             end -- if not monitor then
  697.  
  698.             printLog("Monitor["..monitorIndex.."] named \""..monitorNames[monitorIndex].."\" is a valid monitor of size x:"..monitorX.." by y:"..monitorY..".")
  699.         end -- for monitorIndex = 1, #monitorList do
  700.     end -- if #monitorList == 0 then
  701.  
  702.     printLog("Found "..#monitorList.." monitor(s) in findMonitors().")
  703. end -- local function findMonitors()
  704.  
  705.  
  706. -- Initialize all Big Reactors - Reactors
  707. local function findReactors()
  708.     -- Empty out old list of reactors
  709.     newReactorList = {}
  710.     printLog("Finding reactors...")
  711.     newReactorList, reactorNames = getDevices("BigReactors-Reactor")
  712.  
  713.     if #newReactorList == 0 then
  714.         printLog("No reactors found!")
  715.         error("Can't find any reactors!")
  716.     else  -- Placeholder
  717.         for reactorIndex = 1, #newReactorList do
  718.             local reactor = nil
  719.             reactor = newReactorList[reactorIndex]
  720.  
  721.             if not reactor then
  722.                 printLog("reactorList["..reactorIndex.."] in findReactors() is NOT a valid Big Reactor.")
  723.  
  724.                 table.remove(newReactorList, reactorIndex) -- Remove invalid reactor from list
  725.                 if reactorIndex ~= #newReactorList then    -- If we're not at the end, clean up
  726.                     reactorIndex = reactorIndex - 1 -- We just removed an element
  727.                 end -- reactorIndex ~= #newReactorList then
  728.                 return -- Invalid reactorIndex
  729.             else
  730.                 printLog("reactor["..reactorIndex.."] in findReactors() is a valid Big Reactor.")
  731.                 --initialize the default table
  732.                 _G[reactorNames[reactorIndex]] = {}
  733.                 _G[reactorNames[reactorIndex]]["ReactorOptions"] = {}
  734.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["baseControlRodLevel"] = 80
  735.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["lastTempPoll"] = 0
  736.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["autoStart"] = true
  737.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["activeCooled"] = true
  738.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorMaxTemp"] = 1400 --set for passive-cooled, the active-cooled subroutine will correct it
  739.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorMinTemp"] = 1000
  740.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["rodOverride"] = false
  741.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorName"] = reactorNames[reactorIndex]
  742.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorCruising"] = false
  743.                 if reactor.getConnected() then
  744.                     printLog("reactor["..reactorIndex.."] in findReactors() is connected.")
  745.                 else
  746.                     printLog("reactor["..reactorIndex.."] in findReactors() is NOT connected.")
  747.                     return -- Disconnected reactor
  748.                 end
  749.             end
  750.            
  751.             --failsafe
  752.             local tempTable = _G[reactorNames[reactorIndex]]
  753.            
  754.             --check to make sure we get a valid config
  755.             if (config.load(reactorNames[reactorIndex]..".options")) ~= nil then
  756.                 tempTable = config.load(reactorNames[reactorIndex]..".options")
  757.             else
  758.                 --if we don't have a valid config from disk, make a valid config
  759.                 config.save(reactorNames[reactorIndex]..".options", _G[reactorNames[reactorIndex]])
  760.             end
  761.            
  762.             --load values from tempTable, checking for nil values along the way
  763.             if tempTable["ReactorOptions"]["baseControlRodLevel"] ~= nil then
  764.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["baseControlRodLevel"] = tempTable["ReactorOptions"]["baseControlRodLevel"]
  765.             end
  766.            
  767.             if tempTable["ReactorOptions"]["lastTempPoll"] ~= nil then
  768.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["lastTempPoll"] = tempTable["ReactorOptions"]["lastTempPoll"]
  769.             end
  770.            
  771.             if tempTable["ReactorOptions"]["autoStart"] ~= nil then
  772.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["autoStart"] = tempTable["ReactorOptions"]["autoStart"]
  773.             end
  774.            
  775.             if tempTable["ReactorOptions"]["activeCooled"] ~= nil then
  776.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["activeCooled"] = tempTable["ReactorOptions"]["activeCooled"]
  777.             end
  778.            
  779.             if tempTable["ReactorOptions"]["reactorMaxTemp"] ~= nil then
  780.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorMaxTemp"] = tempTable["ReactorOptions"]["reactorMaxTemp"]
  781.             end
  782.            
  783.             if tempTable["ReactorOptions"]["reactorMinTemp"] ~= nil then
  784.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorMinTemp"] = tempTable["ReactorOptions"]["reactorMinTemp"]
  785.             end
  786.            
  787.             if tempTable["ReactorOptions"]["rodOverride"] ~= nil then
  788.                 printLog("Got value from config file for Rod Override, the value is: "..tostring(tempTable["ReactorOptions"]["rodOverride"]).." EOL")
  789.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["rodOverride"] = tempTable["ReactorOptions"]["rodOverride"]
  790.             end
  791.            
  792.             if tempTable["ReactorOptions"]["reactorName"] ~= nil then
  793.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorName"] = tempTable["ReactorOptions"]["reactorName"]
  794.             end
  795.            
  796.             if tempTable["ReactorOptions"]["reactorCruising"] ~= nil then
  797.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorCruising"] = tempTable["ReactorOptions"]["reactorCruising"]
  798.             end
  799.            
  800.             --stricter typing, let's set these puppies up with the right type of value.
  801.             _G[reactorNames[reactorIndex]]["ReactorOptions"]["baseControlRodLevel"] = tonumber(_G[reactorNames[reactorIndex]]["ReactorOptions"]["baseControlRodLevel"])
  802.            
  803.             _G[reactorNames[reactorIndex]]["ReactorOptions"]["lastTempPoll"] = tonumber(_G[reactorNames[reactorIndex]]["ReactorOptions"]["lastTempPoll"])
  804.            
  805.             if (tostring(_G[reactorNames[reactorIndex]]["ReactorOptions"]["autoStart"]) == "true") then
  806.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["autoStart"] = true
  807.             else
  808.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["autoStart"] = false
  809.             end
  810.            
  811.             if (tostring(_G[reactorNames[reactorIndex]]["ReactorOptions"]["activeCooled"]) == "true") then
  812.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["activeCooled"] = true
  813.             else
  814.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["activeCooled"] = false
  815.             end
  816.            
  817.             _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorMaxTemp"] = tonumber(_G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorMaxTemp"])
  818.            
  819.             _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorMinTemp"] = tonumber(_G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorMinTemp"])
  820.            
  821.             if (tostring(_G[reactorNames[reactorIndex]]["ReactorOptions"]["rodOverride"]) == "true") then
  822.                 printLog("Setting Rod Override for  "..reactorNames[reactorIndex].." to true because value was "..tostring(_G[reactorNames[reactorIndex]]["ReactorOptions"]["rodOverride"]).." EOL")
  823.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["rodOverride"] = true
  824.             else
  825.                 printLog("Setting Rod Override for  "..reactorNames[reactorIndex].." to false because value was "..tostring(_G[reactorNames[reactorIndex]]["ReactorOptions"]["rodOverride"]).." EOL")
  826.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["rodOverride"] = false
  827.             end
  828.            
  829.             if (tostring(_G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorCruising"]) == "true") then
  830.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorCruising"] = true
  831.             else
  832.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorCruising"] = false
  833.             end
  834.                        
  835.             --save one more time, in case we didn't have a complete config file before
  836.             config.save(reactorNames[reactorIndex]..".options", _G[reactorNames[reactorIndex]])
  837.         end -- for reactorIndex = 1, #newReactorList do
  838.     end -- if #newReactorList == 0 then
  839.  
  840.     -- Overwrite old reactor list with the now updated list
  841.     reactorList = newReactorList
  842.  
  843.     -- Start turbine monitor offset after reactors get monitors
  844.     -- This assumes that there is a monitor for each turbine and reactor, plus the overall monitor display
  845.     turbineMonitorOffset = #reactorList + 1 -- #turbineList will start at "1" if turbines found and move us just beyond #reactorList and status monitor range
  846.  
  847.     printLog("Found "..#reactorList.." reactor(s) in findReactors().")
  848.     printLog("Set turbineMonitorOffset to "..turbineMonitorOffset.." in findReactors().")
  849. end -- function findReactors()
  850.  
  851.  
  852. -- Initialize all Big Reactors - Turbines
  853. local function findTurbines()
  854.     -- Empty out old list of turbines
  855.     newTurbineList = {}
  856.  
  857.     printLog("Finding turbines...")
  858.     newTurbineList, turbineNames = getDevices("BigReactors-Turbine")
  859.  
  860.     if #newTurbineList == 0 then
  861.         printLog("No turbines found") -- Not an error
  862.     else
  863.         for turbineIndex = 1, #newTurbineList do
  864.             local turbine = nil
  865.             turbine = newTurbineList[turbineIndex]
  866.  
  867.             if not turbine then
  868.                 printLog("turbineList["..turbineIndex.."] in findTurbines() is NOT a valid Big Reactors Turbine.")
  869.  
  870.                 table.remove(newTurbineList, turbineIndex) -- Remove invalid turbine from list
  871.                 if turbineIndex ~= #newTurbineList then    -- If we're not at the end, clean up
  872.                     turbineIndex = turbineIndex - 1 -- We just removed an element
  873.                 end -- turbineIndex ~= #newTurbineList then
  874.  
  875.                 return -- Invalid turbineIndex
  876.             else
  877.            
  878.                 _G[turbineNames[turbineIndex]] = {}
  879.                 _G[turbineNames[turbineIndex]]["TurbineOptions"] = {}
  880.                 _G[turbineNames[turbineIndex]]["TurbineOptions"]["LastSpeed"] = 0
  881.                 _G[turbineNames[turbineIndex]]["TurbineOptions"]["BaseSpeed"] = 2726
  882.                 _G[turbineNames[turbineIndex]]["TurbineOptions"]["autoStart"] = true
  883.                 _G[turbineNames[turbineIndex]]["TurbineOptions"]["LastFlow"] = 2000 --open up with all the steam wide open
  884.                 _G[turbineNames[turbineIndex]]["TurbineOptions"]["flowOverride"] = false
  885.                 _G[turbineNames[turbineIndex]]["TurbineOptions"]["turbineName"] = turbineNames[turbineIndex]
  886.                 printLog("turbineList["..turbineIndex.."] in findTurbines() is a valid Big Reactors Turbine.")
  887.                 if turbine.getConnected() then
  888.                     printLog("turbine["..turbineIndex.."] in findTurbines() is connected.")
  889.                 else
  890.                     printLog("turbine["..turbineIndex.."] in findTurbines() is NOT connected.")
  891.                     return -- Disconnected turbine
  892.                 end
  893.             end
  894.            
  895.             --failsafe
  896.             local tempTable = _G[turbineNames[turbineIndex]]
  897.            
  898.             --check to make sure we get a valid config
  899.             if (config.load(turbineNames[turbineIndex]..".options")) ~= nil then
  900.                 tempTable = config.load(turbineNames[turbineIndex]..".options")
  901.             else
  902.                 --if we don't have a valid config from disk, make a valid config
  903.                 config.save(turbineNames[turbineIndex]..".options", _G[turbineNames[turbineIndex]])
  904.             end
  905.            
  906.             --load values from tempTable, checking for nil values along the way
  907.             if tempTable["TurbineOptions"]["LastSpeed"] ~= nil then
  908.                 _G[turbineNames[turbineIndex]]["TurbineOptions"]["LastSpeed"] = tempTable["TurbineOptions"]["LastSpeed"]
  909.             end
  910.            
  911.             if tempTable["TurbineOptions"]["BaseSpeed"] ~= nil then
  912.                 _G[turbineNames[turbineIndex]]["TurbineOptions"]["BaseSpeed"] = tempTable["TurbineOptions"]["BaseSpeed"]
  913.             end
  914.            
  915.             if tempTable["TurbineOptions"]["autoStart"] ~= nil then
  916.                 _G[turbineNames[turbineIndex]]["TurbineOptions"]["autoStart"] = tempTable["TurbineOptions"]["autoStart"]
  917.             end
  918.            
  919.             if tempTable["TurbineOptions"]["LastFlow"] ~= nil then
  920.                 _G[turbineNames[turbineIndex]]["TurbineOptions"]["LastFlow"] = tempTable["TurbineOptions"]["LastFlow"]
  921.             end
  922.            
  923.             if tempTable["TurbineOptions"]["flowOverride"] ~= nil then
  924.                 _G[turbineNames[turbineIndex]]["TurbineOptions"]["flowOverride"] = tempTable["TurbineOptions"]["flowOverride"]
  925.             end
  926.            
  927.             if tempTable["TurbineOptions"]["turbineName"] ~= nil then
  928.                 _G[turbineNames[turbineIndex]]["TurbineOptions"]["turbineName"] = tempTable["TurbineOptions"]["turbineName"]
  929.             end
  930.            
  931.             --save once more just to make sure we got it
  932.             config.save(turbineNames[turbineIndex]..".options", _G[turbineNames[turbineIndex]])
  933.         end -- for turbineIndex = 1, #newTurbineList do
  934.  
  935.         -- Overwrite old turbine list with the now updated list
  936.         turbineList = newTurbineList
  937.     end -- if #newTurbineList == 0 then
  938.  
  939.     printLog("Found "..#turbineList.." turbine(s) in findTurbines().")
  940. end -- function findTurbines()
  941.  
  942.  
  943. -- Return current energy buffer in a specific reactor by %
  944. local function getReactorStoredEnergyBufferPercent(reactor)
  945.     printLog("Called as getReactorStoredEnergyBufferPercent(reactor).")
  946.  
  947.     if not reactor then
  948.         printLog("getReactorStoredEnergyBufferPercent() did NOT receive a valid Big Reactor Reactor.")
  949.         return -- Invalid reactorIndex
  950.     else
  951.         printLog("getReactorStoredEnergyBufferPercent() did receive a valid Big Reactor Reactor.")
  952.     end
  953.  
  954.     local energyBufferStorage = reactor.getEnergyStored()
  955.     return round(energyBufferStorage/100000, 1) -- (buffer/10000000 RF)*100%
  956. end -- function getReactorStoredEnergyBufferPercent(reactor)
  957.  
  958.  
  959. -- Return current energy buffer in a specific Turbine by %
  960. local function getTurbineStoredEnergyBufferPercent(turbine)
  961.     printLog("Called as getTurbineStoredEnergyBufferPercent(turbine)")
  962.  
  963.     if not turbine then
  964.         printLog("getTurbineStoredEnergyBufferPercent() did NOT receive a valid Big Reactor Turbine.")
  965.         return -- Invalid reactorIndex
  966.     else
  967.         printLog("getTurbineStoredEnergyBufferPercent() did receive a valid Big Reactor Turbine.")
  968.     end
  969.  
  970.     local energyBufferStorage = turbine.getEnergyStored()
  971.     return round(energyBufferStorage/10000, 1) -- (buffer/1000000 RF)*100%
  972. end -- function getTurbineStoredEnergyBufferPercent(turbine)
  973.  
  974. local function reactorCruise(cruiseMaxTemp, cruiseMinTemp, reactorIndex)
  975.     printLog("Called as reactorCruise(cruiseMaxTemp="..cruiseMaxTemp..",cruiseMinTemp="..cruiseMinTemp..",lastPolledTemp=".._G[reactorNames[reactorIndex]]["ReactorOptions"]["lastTempPoll"]..",reactorIndex="..reactorIndex..").")
  976.    
  977.     --sanitization
  978.     local lastPolledTemp = tonumber(_G[reactorNames[reactorIndex]]["ReactorOptions"]["lastTempPoll"])
  979.     cruiseMaxTemp = tonumber(cruiseMaxTemp)
  980.     cruiseMinTemp = tonumber(cruiseMinTemp)
  981.    
  982.     if ((lastPolledTemp < cruiseMaxTemp) and (lastPolledTemp > cruiseMinTemp)) then
  983.         local reactor = nil
  984.         reactor = reactorList[reactorIndex]
  985.         if not reactor then
  986.             printLog("reactor["..reactorIndex.."] in reactorCruise(cruiseMaxTemp="..cruiseMaxTemp..",cruiseMinTemp="..cruiseMinTemp..",lastPolledTemp="..lastPolledTemp..",reactorIndex="..reactorIndex..") is NOT a valid Big Reactor.")
  987.             return -- Invalid reactorIndex
  988.         else
  989.             printLog("reactor["..reactorIndex.."] in reactorCruise(cruiseMaxTemp="..cruiseMaxTemp..",cruiseMinTemp="..cruiseMinTemp..",lastPolledTemp="..lastPolledTemp..",reactorIndex="..reactorIndex..") is a valid Big Reactor.")
  990.             if reactor.getConnected() then
  991.                 printLog("reactor["..reactorIndex.."] in reactorCruise(cruiseMaxTemp="..cruiseMaxTemp..",cruiseMinTemp="..cruiseMinTemp..",lastPolledTemp="..lastPolledTemp..",reactorIndex="..reactorIndex..") is connected.")
  992.             else
  993.                 printLog("reactor["..reactorIndex.."] in reactorCruise(cruiseMaxTemp="..cruiseMaxTemp..",cruiseMinTemp="..cruiseMinTemp..",lastPolledTemp="..lastPolledTemp..",reactorIndex="..reactorIndex..") is NOT connected.")
  994.                 return -- Disconnected reactor
  995.             end -- if reactor.getConnected() then
  996.         end -- if not reactor then
  997.  
  998.         local rodPercentage = math.ceil(reactor.getControlRodLevel(0))
  999.         local reactorTemp = math.ceil(reactor.getFuelTemperature())
  1000.         _G[reactorNames[reactorIndex]]["ReactorOptions"]["baseControlRodLevel"] = rodPercentage
  1001.        
  1002.         if ((reactorTemp < cruiseMaxTemp) and (reactorTemp > cruiseMinTemp)) then
  1003.             if (reactorTemp < lastPolledTemp) then
  1004.                 rodPercentage = (rodPercentage - 1)
  1005.                 --Boundary check
  1006.                 if rodPercentage < 0 then
  1007.                     reactor.setAllControlRodLevels(0)
  1008.                 else
  1009.                     reactor.setAllControlRodLevels(rodPercentage)
  1010.                 end
  1011.             else
  1012.                 rodPercentage = (rodPercentage + 1)
  1013.                 --Boundary check
  1014.                 if rodPercentage > 99 then
  1015.                     reactor.setAllControlRodLevels(99)
  1016.                 else
  1017.                     reactor.setAllControlRodLevels(rodPercentage)
  1018.                 end
  1019.             end -- if (reactorTemp > lastPolledTemp) then
  1020.         else
  1021.             --disengage cruise, we've fallen out of the ideal temperature range
  1022.             _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorCruising"] = false
  1023.         end -- if ((reactorTemp < cruiseMaxTemp) and (reactorTemp > cruiseMinTemp)) then
  1024.     else
  1025.         --I don't know how we'd get here, but let's turn the cruise mode off
  1026.         _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorCruising"] = false
  1027.     end -- if ((lastPolledTemp < cruiseMaxTemp) and (lastPolledTemp > cruiseMinTemp)) then
  1028.     _G[reactorNames[reactorIndex]]["ReactorOptions"]["lastTempPoll"] = reactorTemp
  1029.     _G[reactorNames[reactorIndex]]["ReactorOptions"]["activeCooled"] = true
  1030.     _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorMaxTemp"] = cruiseMaxTemp
  1031.     _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorMinTemp"] = cruiseMinTemp
  1032.     config.save(reactorNames[reactorIndex]..".options", _G[reactorNames[reactorIndex]])
  1033. end -- function reactorCruise(cruiseMaxTemp, cruiseMinTemp, lastPolledTemp, reactorIndex)
  1034.  
  1035. -- Modify reactor control rod levels to keep temperature with defined parameters, but
  1036. -- wait an in-game half-hour for the temperature to stabalize before modifying again
  1037. local function temperatureControl(reactorIndex)
  1038.     printLog("Called as temperatureControl(reactorIndex="..reactorIndex..")")
  1039.  
  1040.     local reactor = nil
  1041.     reactor = reactorList[reactorIndex]
  1042.     if not reactor then
  1043.         printLog("reactor["..reactorIndex.."] in temperatureControl(reactorIndex="..reactorIndex..") is NOT a valid Big Reactor.")
  1044.         return -- Invalid reactorIndex
  1045.     else
  1046.         printLog("reactor["..reactorIndex.."] in temperatureControl(reactorIndex="..reactorIndex..") is a valid Big Reactor.")
  1047.  
  1048.         if reactor.getConnected() then
  1049.             printLog("reactor["..reactorIndex.."] in temperatureControl(reactorIndex="..reactorIndex..") is connected.")
  1050.         else
  1051.             printLog("reactor["..reactorIndex.."] in temperatureControl(reactorIndex="..reactorIndex..") is NOT connected.")
  1052.             return -- Disconnected reactor
  1053.         end -- if reactor.getConnected() then
  1054.     end
  1055.  
  1056.     local reactorNum = reactorIndex
  1057.     local rodPercentage = math.ceil(reactor.getControlRodLevel(0))
  1058.     local reactorTemp = math.ceil(reactor.getFuelTemperature())
  1059.     local localMinReactorTemp, localMaxReactorTemp = _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorMinTemp"], _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorMaxTemp"]
  1060.  
  1061.     --bypass if the reactor itself is set to not be auto-controlled
  1062.     if ((not _G[reactorNames[reactorIndex]]["ReactorOptions"]["rodOverride"]) or (_G[reactorNames[reactorIndex]]["ReactorOptions"]["rodOverride"] == "false")) then
  1063.         -- No point modifying control rod levels for temperature if the reactor is offline
  1064.         if reactor.getActive() then
  1065.             -- Actively cooled reactors should range between 0^C-300^C
  1066.             -- Actually, active-cooled reactors should range between 300 and 420C (Mechaet)
  1067.             -- Accordingly I changed the below lines
  1068.             if reactor.isActivelyCooled() then
  1069.                 -- below was 0
  1070.                 localMinReactorTemp = 800
  1071.                 -- below was 300
  1072.                 localMaxReactorTemp = 900
  1073.             else
  1074.                 localMinReactorTemp = _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorMinTemp"]
  1075.                 localMaxReactorTemp = _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorMaxTemp"]
  1076.             end
  1077.             local lastTempPoll = _G[reactorNames[reactorIndex]]["ReactorOptions"]["lastTempPoll"]
  1078.             if _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorCruising"] then
  1079.                 --let's bypass all this math and hit the much-more-subtle cruise feature
  1080.                 --printLog("min: "..localMinReactorTemp..", max: "..localMaxReactorTemp..", lasttemp: "..lastTempPoll..", ri: "..reactorIndex.."  EOL")
  1081.                 reactorCruise(localMaxReactorTemp, localMinReactorTemp, reactorIndex)
  1082.             else
  1083.                 -- Don't bring us to 100, that's effectively a shutdown
  1084.                 if (reactorTemp > localMaxReactorTemp) and (rodPercentage ~= 99) then
  1085.                     --increase the rods, but by how much?
  1086.                     if (reactorTemp > lastTempPoll) then
  1087.                         --we're climbing, we need to get this to decrease
  1088.                         if ((reactorTemp - lastTempPoll) > 100) then
  1089.                             --we're climbing really fast, arrest it
  1090.                             if (rodPercentage + (10 * controlRodAdjustAmount)) > 99 then
  1091.                                 reactor.setAllControlRodLevels(99)
  1092.                             else
  1093.                                 reactor.setAllControlRodLevels(rodPercentage + (10 * controlRodAdjustAmount))
  1094.                             end
  1095.                         else
  1096.                             --we're not climbing by leaps and bounds, let's give it a rod adjustment based on temperature increase
  1097.                             local diffAmount = reactorTemp - lastTempPoll
  1098.                             diffAmount = (round(diffAmount/10, 0))/5
  1099.                             controlRodAdjustAmount = diffAmount
  1100.                             if (rodPercentage + controlRodAdjustAmount) > 99 then
  1101.                                 reactor.setAllControlRodLevels(99)
  1102.                             else
  1103.                                 reactor.setAllControlRodLevels(rodPercentage + controlRodAdjustAmount)
  1104.                             end
  1105.                         end --if ((reactorTemp - lastTempPoll) > 100) then
  1106.                     elseif (reactorTemp == lastTempPoll) then
  1107.                         --temperature has stagnated, kick it very lightly
  1108.                         local controlRodAdjustment = 1
  1109.                         if (rodPercentage + controlRodAdjustment) > 99 then
  1110.                             reactor.setAllControlRodLevels(99)
  1111.                         else
  1112.                             reactor.setAllControlRodLevels(rodPercentage + controlRodAdjustment)
  1113.                         end
  1114.                     end --if (reactorTemp > lastTempPoll) then
  1115.                         --worth noting that if we're above temp but decreasing, we do nothing. let it continue decreasing.
  1116.  
  1117.                 elseif (reactorTemp < localMinReactorTemp) and (rodPercentage ~=0) then
  1118.                     --we're too cold. time to warm up, but by how much?
  1119.                     if (reactorTemp < lastTempPoll) then
  1120.                         --we're descending, let's stop that.
  1121.                         if ((lastTempPoll - reactorTemp) > 100) then
  1122.                             --we're headed for a new ice age, bring the heat
  1123.                             if (rodPercentage - (10 * controlRodAdjustAmount)) < 0 then
  1124.                                 reactor.setAllControlRodLevels(0)
  1125.                             else
  1126.                                 reactor.setAllControlRodLevels(rodPercentage - (10 * controlRodAdjustAmount))
  1127.                             end
  1128.                         else
  1129.                             --we're not descending quickly, let's bump it based on descent rate
  1130.                             local diffAmount = lastTempPoll - reactorTemp
  1131.                             diffAmount = (round(diffAmount/10, 0))/5
  1132.                             controlRodAdjustAmount = diffAmount
  1133.                             if (rodPercentage - controlRodAdjustAmount) < 0 then
  1134.                                 reactor.setAllControlRodLevels(0)
  1135.                             else
  1136.                                 reactor.setAllControlRodLevels(rodPercentage - controlRodAdjustAmount)
  1137.                             end
  1138.                         end --if ((lastTempPoll - reactorTemp) > 100) then
  1139.                     elseif (reactorTemp == lastTempPoll) then
  1140.                         --temperature has stagnated, kick it very lightly
  1141.                         local controlRodAdjustment = 1
  1142.                         if (rodPercentage - controlRodAdjustment) < 0 then
  1143.                             reactor.setAllControlRodLevels(0)
  1144.                         else
  1145.                             reactor.setAllControlRodLevels(rodPercentage - controlRodAdjustment)
  1146.                         end --if (rodPercentage - controlRodAdjustment) < 0 then
  1147.  
  1148.                     end --if (reactorTemp < lastTempPoll) then
  1149.                     --if we're below temp but increasing, do nothing and let it continue to rise.
  1150.                 end --if (reactorTemp > localMaxReactorTemp) and (rodPercentage ~= 99) then
  1151.  
  1152.                 if ((reactorTemp > localMinReactorTemp) and (reactorTemp < localMaxReactorTemp)) then
  1153.                     --engage cruise mode
  1154.                     _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorCruising"] = true
  1155.                 end -- if ((reactorTemp > localMinReactorTemp) and (reactorTemp < localMaxReactorTemp)) then
  1156.             end -- if reactorCruising then
  1157.             --always set this number
  1158.             _G[reactorNames[reactorIndex]]["ReactorOptions"]["lastTempPoll"] = reactorTemp
  1159.             config.save(reactorNames[reactorIndex]..".options", _G[reactorNames[reactorIndex]])
  1160.         end -- if reactor.getActive() then
  1161.     else
  1162.         printLog("Bypassed temperature control due to rodOverride being "..tostring(_G[reactorNames[reactorIndex]]["ReactorOptions"]["rodOverride"]).." EOL")
  1163.     end -- if not _G[reactorNames[reactorIndex]]["ReactorOptions"]["rodOverride"] then
  1164. end -- function temperatureControl(reactorIndex)
  1165.  
  1166. -- Load saved reactor parameters if ReactorOptions file exists
  1167. local function loadReactorOptions()
  1168.     local reactorOptions = fs.open("ReactorOptions", "r") -- See http://computercraft.info/wiki/Fs.open
  1169.  
  1170.     if reactorOptions then
  1171.         -- The following values were added by Lolmer
  1172.         minStoredEnergyPercent = reactorOptions.readLine()
  1173.         maxStoredEnergyPercent = reactorOptions.readLine()
  1174.         --added by Mechaet
  1175.         -- If we succeeded in reading a string, convert it to a number
  1176.  
  1177.         if minStoredEnergyPercent ~= nil then
  1178.             minStoredEnergyPercent = tonumber(minStoredEnergyPercent)
  1179.         end
  1180.  
  1181.         if maxStoredEnergyPercent ~= nil then
  1182.             maxStoredEnergyPercent = tonumber(maxStoredEnergyPercent)
  1183.         end
  1184.  
  1185.         reactorOptions.close()
  1186.     end -- if reactorOptions then
  1187.  
  1188.     -- Set default values if we failed to read any of the above
  1189.     if minStoredEnergyPercent == nil then
  1190.         minStoredEnergyPercent = 15
  1191.     end
  1192.  
  1193.     if maxStoredEnergyPercent == nil then
  1194.         maxStoredEnergyPercent = 85
  1195.     end
  1196.  
  1197. end -- function loadReactorOptions()
  1198.  
  1199.  
  1200. -- Save our reactor parameters
  1201. local function saveReactorOptions()
  1202.     local reactorOptions = fs.open("ReactorOptions", "w") -- See http://computercraft.info/wiki/Fs.open
  1203.  
  1204.     -- If we can save the files, save them
  1205.     if reactorOptions then
  1206.         local reactorIndex = 1
  1207.         -- The following values were added by Lolmer
  1208.         reactorOptions.writeLine(minStoredEnergyPercent)
  1209.         reactorOptions.writeLine(maxStoredEnergyPercent)
  1210.         reactorOptions.close()
  1211.     else
  1212.         printLog("Failed to open file ReactorOptions for writing!")
  1213.     end -- if reactorOptions then
  1214. end -- function saveReactorOptions()
  1215.  
  1216.  
  1217. local function displayReactorBars(barParams)
  1218.     -- Default to first reactor and first monitor
  1219.     setmetatable(barParams,{__index={reactorIndex=1, monitorIndex=1}})
  1220.     local reactorIndex, monitorIndex =
  1221.         barParams[1] or barParams.reactorIndex,
  1222.         barParams[2] or barParams.monitorIndex
  1223.  
  1224.     printLog("Called as displayReactorBars(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..").")
  1225.  
  1226.     -- Grab current monitor
  1227.     local monitor = nil
  1228.     monitor = monitorList[monitorIndex]
  1229.     if not monitor then
  1230.         printLog("monitor["..monitorIndex.."] in displayReactorBars(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..") is NOT a valid monitor.")
  1231.         return -- Invalid monitorIndex
  1232.     end
  1233.  
  1234.     -- Grab current reactor
  1235.     local reactor = nil
  1236.     reactor = reactorList[reactorIndex]
  1237.     if not reactor then
  1238.         printLog("reactor["..reactorIndex.."] in displayReactorBars(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..") is NOT a valid Big Reactor.")
  1239.         return -- Invalid reactorIndex
  1240.     else
  1241.         printLog("reactor["..reactorIndex.."] in displayReactorBars(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..") is a valid Big Reactor.")
  1242.         if reactor.getConnected() then
  1243.             printLog("reactor["..reactorIndex.."] in displayReactorBars(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..") is connected.")
  1244.         else
  1245.             printLog("reactor["..reactorIndex.."] in displayReactorBars(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..") is NOT connected.")
  1246.             return -- Disconnected reactor
  1247.         end -- if reactor.getConnected() then
  1248.     end -- if not reactor then
  1249.  
  1250.     -- Draw border lines
  1251.     local width, height = monitor.getSize()
  1252.     printLog("Size of monitor is "..width.."w x"..height.."h in displayReactorBars(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..")")
  1253.  
  1254.     for i=3, 5 do
  1255.         monitor.setCursorPos(22, i)
  1256.         monitor.write("|")
  1257.     end
  1258.  
  1259.     drawLine(2, monitorIndex)
  1260.     drawLine(6, monitorIndex)
  1261.  
  1262.     -- Draw some text
  1263.     local fuelString = "Fuel: "
  1264.     local tempString = "Temp: "
  1265.     local energyBufferString = ""
  1266.  
  1267.     if reactor.isActivelyCooled() then
  1268.         energyBufferString = "Steam: "
  1269.     else
  1270.         energyBufferString = "Energy: "
  1271.     end
  1272.  
  1273.     local padding = math.max(string.len(fuelString), string.len(tempString), string.len(energyBufferString))
  1274.  
  1275.     local fuelPercentage = round(reactor.getFuelAmount()/reactor.getFuelAmountMax()*100,1)
  1276.     print{fuelString,2,3,monitorIndex}
  1277.     print{fuelPercentage.." %",padding+2,3,monitorIndex}
  1278.  
  1279.     local reactorTemp = math.ceil(reactor.getFuelTemperature())
  1280.     print{tempString,2,5,monitorIndex}
  1281.     print{reactorTemp.." C",padding+2,5,monitorIndex}
  1282.  
  1283.     local rodPercentage = math.ceil(reactor.getControlRodLevel(0))
  1284.     printLog("Current Rod Percentage for reactor["..reactorIndex.."] is "..rodPercentage.."% in displayReactorBars(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..").")
  1285.     -- Allow controlling Reactor Control Rod Level from GUI
  1286.     -- Decrease rod button: 23X, 4Y
  1287.     -- Increase rod button: 28X, 4Y
  1288.     if (xClick == 23) and (yClick == 4) and (sideClick == monitorNames[monitorIndex]) then
  1289.         printLog("Decreasing Rod Levels in displayReactorBars(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..").")
  1290.         --Decrease rod level by amount
  1291.         newRodPercentage = rodPercentage - (5 * controlRodAdjustAmount)
  1292.         if newRodPercentage < 0 then
  1293.             newRodPercentage = 0
  1294.         end
  1295.         sideClick, xClick, yClick = 0, 0, 0
  1296.  
  1297.         printLog("Setting reactor["..reactorIndex.."] Rod Levels to "..newRodPercentage.."% in displayReactorBars(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..").")
  1298.         reactor.setAllControlRodLevels(newRodPercentage)
  1299.         _G[reactorNames[reactorIndex]]["ReactorOptions"]["baseControlRodLevel"] = newRodPercentage
  1300.  
  1301.         -- Save updated rod percentage
  1302.         config.save(reactorNames[reactorIndex]..".options", _G[reactorNames[reactorIndex]])
  1303.         rodPercentage = newRodPercentage
  1304.     elseif (xClick == 29) and (yClick == 4) and (sideClick == monitorNames[monitorIndex]) then
  1305.         printLog("Increasing Rod Levels in displayReactorBars(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..").")
  1306.         --Increase rod level by amount
  1307.         newRodPercentage = rodPercentage + (5 * controlRodAdjustAmount)
  1308.         if newRodPercentage > 100 then
  1309.             newRodPercentage = 100
  1310.         end
  1311.         sideClick, xClick, yClick = 0, 0, 0
  1312.  
  1313.         printLog("Setting reactor["..reactorIndex.."] Rod Levels to "..newRodPercentage.."% in displayReactorBars(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..").")
  1314.         reactor.setAllControlRodLevels(newRodPercentage)
  1315.         _G[reactorNames[reactorIndex]]["ReactorOptions"]["baseControlRodLevel"] = newRodPercentage
  1316.        
  1317.         -- Save updated rod percentage
  1318.         config.save(reactorNames[reactorIndex]..".options", _G[reactorNames[reactorIndex]])
  1319.         rodPercentage = round(newRodPercentage,0)
  1320.     else
  1321.         printLog("No change to Rod Levels requested by "..progName.." GUI in displayReactorBars(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..").")
  1322.     end -- if (xClick == 29) and (yClick == 4) and (sideClick == monitorNames[monitorIndex]) then
  1323.  
  1324.     print{"Rod (%)",23,3,monitorIndex}
  1325.     print{"<     >",23,4,monitorIndex}
  1326.     print{stringTrim(rodPercentage),25,4,monitorIndex}
  1327.  
  1328.  
  1329.     -- getEnergyProducedLastTick() is used for both RF/t (passively cooled) and mB/t (actively cooled)
  1330.     local energyBuffer = reactor.getEnergyProducedLastTick()
  1331.     if reactor.isActivelyCooled() then
  1332.         printLog("reactor["..reactorIndex.."] produced "..energyBuffer.." mB last tick in displayReactorBars(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..").")
  1333.     else
  1334.         printLog("reactor["..reactorIndex.."] produced "..energyBuffer.." RF last tick in displayReactorBars(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..").")
  1335.     end
  1336.  
  1337.     print{energyBufferString,2,4,monitorIndex}
  1338.  
  1339.     -- Actively cooled reactors do not produce energy, only hot fluid mB/t to be used in a turbine
  1340.     -- still uses getEnergyProducedLastTick for mB/t of hot fluid generated
  1341.     if not reactor.isActivelyCooled() then
  1342.         printLog("reactor["..reactorIndex.."] in displayReactorBars(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..") is NOT an actively cooled reactor.")
  1343.  
  1344.         -- Draw stored energy buffer bar
  1345.         drawBar(2,8,28,8,colors.gray,monitorIndex)
  1346.  
  1347.         local curStoredEnergyPercent = getReactorStoredEnergyBufferPercent(reactor)
  1348.         if curStoredEnergyPercent > 4 then
  1349.             drawBar(2, 8, math.floor(26*curStoredEnergyPercent/100)+2, 8, colors.yellow, monitorIndex)
  1350.         elseif curStoredEnergyPercent > 0 then
  1351.             drawPixel(2, 8, colors.yellow, monitorIndex)
  1352.         end -- if curStoredEnergyPercent > 4 then
  1353.  
  1354.         print{"Energy Buffer",2,7,monitorIndex}
  1355.         print{curStoredEnergyPercent, width-(string.len(curStoredEnergyPercent)+2),7,monitorIndex}
  1356.         print{"%",28,7,monitorIndex}
  1357.  
  1358.         print{math.ceil(energyBuffer).." RF/t",padding+2,4,monitorIndex}
  1359.     else
  1360.         printLog("reactor["..reactorIndex.."] in displayReactorBars(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..") is an actively cooled reactor.")
  1361.         print{math.ceil(energyBuffer).." mB/t",padding+2,4,monitorIndex}
  1362.     end -- if not reactor.isActivelyCooled() then
  1363.  
  1364.     -- Print rod override status
  1365.     local reactorRodOverrideStatus = ""
  1366.  
  1367.     print{"Rod Auto-adjust:",2,9,monitorIndex}
  1368.  
  1369.     if not _G[reactorNames[reactorIndex]]["ReactorOptions"]["rodOverride"] then
  1370.         printLog("Reactor Rod Override status is: "..tostring(_G[reactorNames[reactorIndex]]["ReactorOptions"]["rodOverride"]).." EOL")
  1371.         reactorRodOverrideStatus = "Enabled"
  1372.         monitor.setTextColor(colors.green)
  1373.     else
  1374.         printLog("Reactor Rod Override status is: "..tostring(_G[reactorNames[reactorIndex]]["ReactorOptions"]["rodOverride"]).." EOL")
  1375.         reactorRodOverrideStatus = "Disabled"
  1376.         monitor.setTextColor(colors.red)
  1377.     end -- if not reactorRodOverride then
  1378.     printLog("reactorRodOverrideStatus is \""..reactorRodOverrideStatus.."\" in displayReactorBars(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..").")
  1379.  
  1380.     print{reactorRodOverrideStatus, width - string.len(reactorRodOverrideStatus) - 1, 9, monitorIndex}
  1381.     monitor.setTextColor(colors.white)
  1382.  
  1383.     print{"Reactivity: "..math.ceil(reactor.getFuelReactivity()).." %", 2, 10, monitorIndex}
  1384.     print{"Fuel: "..round(reactor.getFuelConsumedLastTick(),3).." mB/t", 2, 11, monitorIndex}
  1385.     print{"Waste: "..reactor.getWasteAmount().." mB", width-(string.len(reactor.getWasteAmount())+10), 11, monitorIndex}
  1386.  
  1387.     monitor.setTextColor(colors.blue)
  1388.     --printCentered(_G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorName"],12,monitorIndex)
  1389.     monitor.setTextColor(colors.white)
  1390. end -- function displayReactorBars(barParams)
  1391.  
  1392.  
  1393. local function reactorStatus(statusParams)
  1394.     -- Default to first reactor and first monitor
  1395.     setmetatable(statusParams,{__index={reactorIndex=1, monitorIndex=1}})
  1396.     local reactorIndex, monitorIndex =
  1397.         statusParams[1] or statusParams.reactorIndex,
  1398.         statusParams[2] or statusParams.monitorIndex
  1399.     printLog("Called as reactorStatus(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..")")
  1400.  
  1401.     -- Grab current monitor
  1402.     local monitor = nil
  1403.     monitor = monitorList[monitorIndex]
  1404.     if not monitor then
  1405.         printLog("monitor["..monitorIndex.."] in reactorStatus(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..") is NOT a valid monitor.")
  1406.         return -- Invalid monitorIndex
  1407.     end
  1408.  
  1409.     -- Grab current reactor
  1410.     local reactor = nil
  1411.     reactor = reactorList[reactorIndex]
  1412.     if not reactor then
  1413.         printLog("reactor["..reactorIndex.."] in reactorStatus(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..") is NOT a valid Big Reactor.")
  1414.         return -- Invalid reactorIndex
  1415.     else
  1416.         printLog("reactor["..reactorIndex.."] in reactorStatus(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..") is a valid Big Reactor.")
  1417.     end
  1418.  
  1419.     local width, height = monitor.getSize()
  1420.     local reactorStatus = ""
  1421.  
  1422.     if reactor.getConnected() then
  1423.         printLog("reactor["..reactorIndex.."] in reactorStatus(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..") is connected.")
  1424.  
  1425.         if reactor.getActive() then
  1426.             reactorStatus = "ONLINE"
  1427.  
  1428.             -- Set "ONLINE" to blue if the actively cooled reactor is both in cruise mode and online
  1429.             if _G[reactorNames[reactorIndex]]["ReactorOptions"]["reactorCruising"] and reactor.isActivelyCooled() then
  1430.                 monitor.setTextColor(colors.blue)
  1431.             else
  1432.                 monitor.setTextColor(colors.green)
  1433.             end -- if reactorCruising and reactor.isActivelyCooled() then
  1434.         else
  1435.             reactorStatus = "OFFLINE"
  1436.             monitor.setTextColor(colors.red)
  1437.         end -- if reactor.getActive() then
  1438.  
  1439.         if xClick >= (width - string.len(reactorStatus) - 1) and xClick <= (width-1) and (sideClick == monitorNames[monitorIndex]) then
  1440.             if yClick == 1 then
  1441.                 reactor.setActive(not reactor.getActive()) -- Toggle reactor status
  1442.                 _G[reactorNames[reactorIndex]]["ReactorOptions"]["autoStart"] = reactor.getActive()
  1443.                 config.save(reactorNames[reactorIndex]..".options", _G[reactorNames[reactorIndex]])
  1444.                 sideClick, xClick, yClick = 0, 0, 0 -- Reset click after we register it
  1445.  
  1446.                 -- If someone offlines the reactor (offline after a status click was detected), then disable autoStart
  1447.                 if not reactor.getActive() then
  1448.                     _G[reactorNames[reactorIndex]]["ReactorOptions"]["autoStart"] = false
  1449.                 end
  1450.             end -- if yClick == 1 then
  1451.         end -- if (xClick >= (width - string.len(reactorStatus) - 1) and xClick <= (width-1)) and (sideClick == monitorNames[monitorIndex]) then
  1452.  
  1453.         -- Allow disabling rod level auto-adjust and only manual rod level control
  1454.         if ((xClick > 23 and xClick < 28 and yClick == 4)
  1455.                 or (xClick > 20 and xClick < 27 and yClick == 9))
  1456.                 and (sideClick == monitorNames[monitorIndex]) then
  1457.             _G[reactorNames[reactorIndex]]["ReactorOptions"]["rodOverride"] = not _G[reactorNames[reactorIndex]]["ReactorOptions"]["rodOverride"]
  1458.             config.save(reactorNames[reactorIndex]..".options", _G[reactorNames[reactorIndex]])
  1459.             sideClick, xClick, yClick = 0, 0, 0 -- Reset click after we register it
  1460.         end -- if (xClick > 23) and (xClick < 28) and (yClick == 4) and (sideClick == monitorNames[monitorIndex]) then
  1461.  
  1462.     else
  1463.         printLog("reactor["..reactorIndex.."] in reactorStatus(reactorIndex="..reactorIndex..",monitorIndex="..monitorIndex..") is NOT connected.")
  1464.         reactorStatus = "DISCONNECTED"
  1465.         monitor.setTextColor(colors.red)
  1466.     end -- if reactor.getConnected() then
  1467.  
  1468.     print{reactorStatus, width - string.len(reactorStatus) - 1, 1, monitorIndex}
  1469.     monitor.setTextColor(colors.white)
  1470. end -- function reactorStatus(statusParams)
  1471.  
  1472.  
  1473. -- Display all found reactors' status to monitor 1
  1474. -- This is only called if multiple reactors and/or a reactor plus at least one turbine are found
  1475. local function displayAllStatus()
  1476.     local reactor, turbine = nil, nil
  1477.     local onlineReactor, onlineTurbine = 0, 0
  1478.     local totalReactorRF, totalReactorSteam, totalTurbineRF = 0, 0, 0
  1479.     local totalReactorFuelConsumed = 0
  1480.     local totalCoolantStored, totalSteamStored, totalEnergy, totalMaxEnergyStored = 0, 0, 0, 0 -- Total turbine and reactor energy buffer and overall capacity
  1481.     local maxSteamStored = (2000*#turbineList)+(5000*#reactorList)
  1482.     local maxCoolantStored = (2000*#turbineList)+(5000*#reactorList)
  1483.  
  1484.     local monitor, monitorIndex = nil, 1
  1485.     monitor = monitorList[monitorIndex]
  1486.     if not monitor then
  1487.         printLog("monitor["..monitorIndex.."] in displayAllStatus() is NOT a valid monitor.")
  1488.         return -- Invalid monitorIndex
  1489.     end
  1490.  
  1491.     for reactorIndex = 1, #reactorList do
  1492.         reactor = reactorList[reactorIndex]
  1493.         if not reactor then
  1494.             printLog("reactor["..reactorIndex.."] in displayAllStatus() is NOT a valid Big Reactor.")
  1495.             break -- Invalid reactorIndex
  1496.         else
  1497.             printLog("reactor["..reactorIndex.."] in displayAllStatus() is a valid Big Reactor.")
  1498.         end -- if not reactor then
  1499.  
  1500.         if reactor.getConnected() then
  1501.             printLog("reactor["..reactorIndex.."] in displayAllStatus() is connected.")
  1502.             if reactor.getActive() then
  1503.                 onlineReactor = onlineReactor + 1
  1504.                 totalReactorFuelConsumed = totalReactorFuelConsumed + reactor.getFuelConsumedLastTick()
  1505.             end -- reactor.getActive() then
  1506.  
  1507.             -- Actively cooled reactors do not produce or store energy
  1508.             if not reactor.isActivelyCooled() then
  1509.                 totalMaxEnergyStored = totalMaxEnergyStored + 10000000 -- Reactors store 10M RF
  1510.                 totalEnergy = totalEnergy + reactor.getEnergyStored()
  1511.                 totalReactorRF = totalReactorRF + reactor.getEnergyProducedLastTick()
  1512.             else
  1513.                 totalReactorSteam = totalReactorSteam + reactor.getEnergyProducedLastTick()
  1514.                 totalSteamStored = totalSteamStored + reactor.getHotFluidAmount()
  1515.                 totalCoolantStored = totalCoolantStored + reactor.getCoolantAmount()
  1516.             end -- if not reactor.isActivelyCooled() then
  1517.         else
  1518.             printLog("reactor["..reactorIndex.."] in displayAllStatus() is NOT connected.")
  1519.         end -- if reactor.getConnected() then
  1520.     end -- for reactorIndex = 1, #reactorList do
  1521.  
  1522.     for turbineIndex = 1, #turbineList do
  1523.         turbine = turbineList[turbineIndex]
  1524.         if not turbine then
  1525.             printLog("turbine["..turbineIndex.."] in displayAllStatus() is NOT a valid Turbine.")
  1526.             break -- Invalid turbineIndex
  1527.         else
  1528.             printLog("turbine["..turbineIndex.."] in displayAllStatus() is a valid Turbine.")
  1529.         end -- if not turbine then
  1530.  
  1531.         if turbine.getConnected() then
  1532.             printLog("turbine["..turbineIndex.."] in displayAllStatus() is connected.")
  1533.             if turbine.getActive() then
  1534.                 onlineTurbine = onlineTurbine + 1
  1535.             end
  1536.  
  1537.             totalMaxEnergyStored = totalMaxEnergyStored + 1000000 -- Turbines store 1M RF
  1538.             totalEnergy = totalEnergy + turbine.getEnergyStored()
  1539.             totalTurbineRF = totalTurbineRF + turbine.getEnergyProducedLastTick()
  1540.             totalSteamStored = totalSteamStored + turbine.getInputAmount()
  1541.             totalCoolantStored = totalCoolantStored + turbine.getOutputAmount()
  1542.         else
  1543.             printLog("turbine["..turbineIndex.."] in displayAllStatus() is NOT connected.")
  1544.         end -- if turbine.getConnected() then
  1545.     end -- for turbineIndex = 1, #turbineList do
  1546.  
  1547.     print{"Reactors online/found: "..onlineReactor.."/"..#reactorList, 2, 3, monitorIndex}
  1548.     print{"Turbines online/found: "..onlineTurbine.."/"..#turbineList, 2, 4, monitorIndex}
  1549.  
  1550.     if totalReactorRF ~= 0 then
  1551.         monitor.setTextColor(colors.blue)
  1552.         printRight("Reactor", 9, monitorIndex)
  1553.         monitor.setTextColor(colors.white)
  1554.         printRight(math.ceil(totalReactorRF).." (RF/t)", 10, monitorIndex)
  1555.     end
  1556.  
  1557.     if #turbineList then
  1558.         -- Display liquids
  1559.         monitor.setTextColor(colors.blue)
  1560.         printLeft("Steam (mB)", 6, monitorIndex)
  1561.         monitor.setTextColor(colors.white)
  1562.         printLeft(math.ceil(totalSteamStored).."/"..maxSteamStored, 7, monitorIndex)
  1563.         printLeft(math.ceil(totalReactorSteam).." mB/t", 8, monitorIndex)
  1564.         monitor.setTextColor(colors.blue)
  1565.         printRight("Coolant (mB)", 6, monitorIndex)
  1566.         monitor.setTextColor(colors.white)
  1567.         printRight(math.ceil(totalCoolantStored).."/"..maxCoolantStored, 7, monitorIndex)
  1568.  
  1569.         monitor.setTextColor(colors.blue)
  1570.         printLeft("Turbine", 9, monitorIndex)
  1571.         monitor.setTextColor(colors.white)
  1572.         printLeft(math.ceil(totalTurbineRF).." RF/t", 10, monitorIndex)
  1573.     end -- if #turbineList then
  1574.  
  1575.     printCentered("Fuel: "..round(totalReactorFuelConsumed,3).." mB/t", 11, monitorIndex)
  1576.     print{"Buffer: "..math.ceil(totalEnergy,3).."/"..totalMaxEnergyStored.." RF", 2, 12, monitorIndex}
  1577. end -- function displayAllStatus()
  1578.  
  1579.  
  1580. -- Get turbine status
  1581. local function displayTurbineBars(turbineIndex, monitorIndex)
  1582.     printLog("Called as displayTurbineBars(turbineIndex="..turbineIndex..",monitorIndex="..monitorIndex..").")
  1583.  
  1584.     -- Grab current monitor
  1585.     local monitor = nil
  1586.     monitor = monitorList[monitorIndex]
  1587.     if not monitor then
  1588.         printLog("monitor["..monitorIndex.."] in displayTurbineBars(turbineIndex="..turbineIndex..",monitorIndex="..monitorIndex..") is NOT a valid monitor.")
  1589.         return -- Invalid monitorIndex
  1590.     end
  1591.  
  1592.     -- Grab current turbine
  1593.     local turbine = nil
  1594.     turbine = turbineList[turbineIndex]
  1595.     if not turbine then
  1596.         printLog("turbine["..turbineIndex.."] in displayTurbineBars(turbineIndex="..turbineIndex..",monitorIndex="..monitorIndex..") is NOT a valid Big Turbine.")
  1597.         return -- Invalid turbineIndex
  1598.     else
  1599.         printLog("turbine["..turbineIndex.."] in displayTurbineBars(turbineIndex="..turbineIndex..",monitorIndex="..monitorIndex..") is a valid Big Turbine.")
  1600.         if turbine.getConnected() then
  1601.             printLog("turbine["..turbineIndex.."] in displayTurbineBars(turbineIndex="..turbineIndex..",monitorIndex="..monitorIndex..") is connected.")
  1602.         else
  1603.             printLog("turbine["..turbineIndex.."] in displayTurbineBars(turbineIndex="..turbineIndex..",monitorIndex="..monitorIndex..") is NOT connected.")
  1604.             return -- Disconnected turbine
  1605.         end -- if turbine.getConnected() then
  1606.     end -- if not turbine then
  1607.  
  1608.     --local variable to match the view on the monitor
  1609.     local turbineBaseSpeed = tonumber(_G[turbineNames[turbineIndex]]["TurbineOptions"]["BaseSpeed"])
  1610.  
  1611.     -- Draw border lines
  1612.     local width, height = monitor.getSize()
  1613.  
  1614.     for i=3, 6 do
  1615.         monitor.setCursorPos(21, i)
  1616.         monitor.write("|")
  1617.     end
  1618.  
  1619.     drawLine(2,monitorIndex)
  1620.     drawLine(7,monitorIndex)
  1621.  
  1622.     -- Allow controlling Turbine Flow Rate from GUI
  1623.     -- Decrease flow rate button: 22X, 4Y
  1624.     -- Increase flow rate button: 28X, 4Y
  1625.     local turbineFlowRate = tonumber(_G[turbineNames[turbineIndex]]["TurbineOptions"]["LastFlow"])
  1626.     if (xClick == 22) and (yClick == 4) and (sideClick == monitorNames[monitorIndex]) then
  1627.         printLog("Decrease to Flow Rate requested by "..progName.." GUI in displayTurbineBars(turbineIndex="..turbineIndex..",monitorIndex="..monitorIndex..").")
  1628.         --Decrease rod level by amount
  1629.         newTurbineFlowRate = turbineFlowRate - flowRateAdjustAmount
  1630.         if newTurbineFlowRate < 0 then
  1631.             newTurbineFlowRate = 0
  1632.         end
  1633.         sideClick, xClick, yClick = 0, 0, 0
  1634.  
  1635.         -- Check bounds [0,2000]
  1636.         if newTurbineFlowRate > 2000 then
  1637.             newTurbineFlowRate = 2000
  1638.         elseif newTurbineFlowRate < 0 then
  1639.             newTurbineFlowRate = 25 -- Don't go to zero, might as well power off
  1640.         end
  1641.  
  1642.         turbine.setFluidFlowRateMax(newTurbineFlowRate)
  1643.         _G[turbineNames[turbineIndex]]["TurbineOptions"]["LastFlow"] = newTurbineFlowRate
  1644.         -- Save updated Turbine Flow Rate
  1645.         turbineFlowRate = newTurbineFlowRate
  1646.         config.save(turbineNames[turbineIndex]..".options", _G[turbineNames[turbineIndex]])
  1647.     elseif (xClick == 29) and (yClick == 4) and (sideClick == monitorNames[monitorIndex]) then
  1648.         printLog("Increase to Flow Rate requested by "..progName.." GUI in displayTurbineBars(turbineIndex="..turbineIndex..",monitorIndex="..monitorIndex..").")
  1649.         --Increase rod level by amount
  1650.         newTurbineFlowRate = turbineFlowRate + flowRateAdjustAmount
  1651.         if newTurbineFlowRate > 2000 then
  1652.             newTurbineFlowRate = 2000
  1653.         end
  1654.         sideClick, xClick, yClick = 0, 0, 0
  1655.  
  1656.         -- Check bounds [0,2000]
  1657.         if newTurbineFlowRate > 2000 then
  1658.             newTurbineFlowRate = 2000
  1659.         elseif newTurbineFlowRate < 0 then
  1660.             newTurbineFlowRate = 25 -- Don't go to zero, might as well power off
  1661.         end
  1662.  
  1663.         turbine.setFluidFlowRateMax(newTurbineFlowRate)
  1664.        
  1665.         -- Save updated Turbine Flow Rate
  1666.         turbineFlowRate = math.ceil(newTurbineFlowRate)
  1667.         _G[turbineNames[turbineIndex]]["TurbineOptions"]["LastFlow"] = turbineFlowRate
  1668.         config.save(turbineNames[turbineIndex]..".options", _G[turbineNames[turbineIndex]])
  1669.     else
  1670.         printLog("No change to Flow Rate requested by "..progName.." GUI in displayTurbineBars(turbineIndex="..turbineIndex..",monitorIndex="..monitorIndex..").")
  1671.     end -- if (xClick == 29) and (yClick == 4) and (sideClick == monitorNames[monitorIndex]) then
  1672.  
  1673.     if (xClick == 22) and (yClick == 6) and (sideClick == monitorNames[monitorIndex]) then
  1674.         printLog("Decrease to Turbine RPM requested by "..progName.." GUI in displayTurbineBars(turbineIndex="..turbineIndex..",monitorIndex="..monitorIndex..").")
  1675.         rpmRateAdjustment = 909
  1676.         newTurbineBaseSpeed = turbineBaseSpeed - rpmRateAdjustment
  1677.         if newTurbineBaseSpeed < 908 then
  1678.             newTurbineBaseSpeed = 908
  1679.         end
  1680.         sideClick, xClick, yClick = 0, 0, 0
  1681.         _G[turbineNames[turbineIndex]]["TurbineOptions"]["BaseSpeed"] = newTurbineBaseSpeed
  1682.         config.save(turbineNames[turbineIndex]..".options", _G[turbineNames[turbineIndex]])
  1683.     elseif (xClick == 29) and (yClick == 6) and (sideClick == monitorNames[monitorIndex]) then
  1684.         printLog("Increase to Turbine RPM requested by "..progName.." GUI in displayTurbineBars(turbineIndex="..turbineIndex..",monitorIndex="..monitorIndex..").")
  1685.         rpmRateAdjustment = 909
  1686.         newTurbineBaseSpeed = turbineBaseSpeed + rpmRateAdjustment
  1687.         if newTurbineBaseSpeed > 2726 then
  1688.             newTurbineBaseSpeed = 2726
  1689.         end
  1690.         sideClick, xClick, yClick = 0, 0, 0
  1691.         _G[turbineNames[turbineIndex]]["TurbineOptions"]["BaseSpeed"] = newTurbineBaseSpeed
  1692.         config.save(turbineNames[turbineIndex]..".options", _G[turbineNames[turbineIndex]])
  1693.     else
  1694.         printLog("No change to Turbine RPM requested by "..progName.." GUI in displayTurbineBars(turbineIndex="..turbineIndex..",monitorIndex="..monitorIndex..").")
  1695.     end -- if (xClick == 29) and (yClick == 4) and (sideClick == monitorNames[monitorIndex]) then
  1696.     print{"  mB/t",22,3,monitorIndex}
  1697.     print{"<      >",22,4,monitorIndex}
  1698.     print{stringTrim(turbineFlowRate),24,4,monitorIndex}
  1699.     print{"  RPM",22,5,monitorIndex}
  1700.     print{"<      >",22,6,monitorIndex}
  1701.     print{stringTrim(tonumber(_G[turbineNames[turbineIndex]]["TurbineOptions"]["BaseSpeed"])),24,6,monitorIndex}
  1702.     local rotorSpeedString = "Speed: "
  1703.     local energyBufferString = "Energy: "
  1704.     local padding = math.max(string.len(rotorSpeedString), string.len(energyBufferString))
  1705.  
  1706.     local energyBuffer = turbine.getEnergyProducedLastTick()
  1707.     print{energyBufferString,1,4,monitorIndex}
  1708.     print{math.ceil(energyBuffer).." RF/t",padding+1,4,monitorIndex}
  1709.  
  1710.     local rotorSpeed = math.ceil(turbine.getRotorSpeed())
  1711.     print{rotorSpeedString,1,5,monitorIndex}
  1712.     print{rotorSpeed.." RPM",padding+1,5,monitorIndex}
  1713.  
  1714.     -- PaintUtils only outputs to term., not monitor.
  1715.     -- See http://www.computercraft.info/forums2/index.php?/topic/15540-paintutils-on-a-monitor/
  1716.  
  1717.     -- Draw stored energy buffer bar
  1718.     drawBar(1,9,28,9,colors.gray,monitorIndex)
  1719.  
  1720.     local curStoredEnergyPercent = getTurbineStoredEnergyBufferPercent(turbine)
  1721.     if curStoredEnergyPercent > 4 then
  1722.         drawBar(1, 9, math.floor(26*curStoredEnergyPercent/100)+2, 9, colors.yellow,monitorIndex)
  1723.     elseif curStoredEnergyPercent > 0 then
  1724.         drawPixel(1, 9, colors.yellow, monitorIndex)
  1725.     end -- if curStoredEnergyPercent > 4 then
  1726.  
  1727.     print{"Energy Buffer",1,8,monitorIndex}
  1728.     print{curStoredEnergyPercent, width-(string.len(curStoredEnergyPercent)+2),8,monitorIndex}
  1729.     print{"%",28,8,monitorIndex}
  1730.  
  1731.     -- Print rod override status
  1732.     local turbineFlowRateOverrideStatus = ""
  1733.  
  1734.     print{"Flow Auto-adjust:",2,10,monitorIndex}
  1735.  
  1736.     if ((not _G[turbineNames[turbineIndex]]["TurbineOptions"]["flowOverride"]) or (_G[turbineNames[turbineIndex]]["TurbineOptions"]["flowOverride"] == "false")) then
  1737.         turbineFlowRateOverrideStatus = "Enabled"
  1738.         monitor.setTextColor(colors.green)
  1739.     else
  1740.         turbineFlowRateOverrideStatus = "Disabled"
  1741.         monitor.setTextColor(colors.red)
  1742.     end -- if not reactorRodOverride then
  1743.  
  1744.     print{turbineFlowRateOverrideStatus, width - string.len(turbineFlowRateOverrideStatus) - 1, 10, monitorIndex}
  1745.     monitor.setTextColor(colors.white)
  1746.  
  1747.     monitor.setTextColor(colors.blue)
  1748.     printCentered(_G[turbineNames[turbineIndex]]["TurbineOptions"]["turbineName"],12,monitorIndex)
  1749.     monitor.setTextColor(colors.white)
  1750.  
  1751.     -- Need equation to figure out rotor efficiency and display
  1752. end -- function displayTurbineBars(statusParams)
  1753.  
  1754.  
  1755. -- Display turbine status
  1756. local function turbineStatus(turbineIndex, monitorIndex)
  1757.     -- Grab current monitor
  1758.     local monitor = nil
  1759.  
  1760.     printLog("Called as turbineStatus(turbineIndex="..turbineIndex..",monitorIndex="..monitorIndex..").")
  1761.  
  1762.     monitor = monitorList[monitorIndex]
  1763.     if not monitor then
  1764.         printLog("monitor["..monitorIndex.."] in turbineStatus(turbineIndex="..turbineIndex..",monitorIndex="..monitorIndex..") is NOT a valid monitor.")
  1765.         return -- Invalid monitorIndex
  1766.     end
  1767.  
  1768.     -- Grab current turbine
  1769.     local turbine = nil
  1770.     turbine = turbineList[turbineIndex]
  1771.     if not turbine then
  1772.         printLog("turbine["..turbineIndex.."] in turbineStatus(turbineIndex="..turbineIndex..",monitorIndex="..monitorIndex..") is NOT a valid Big Turbine.")
  1773.         return -- Invalid turbineIndex
  1774.     else
  1775.         printLog("turbine["..turbineIndex.."] in turbineStatus(turbineIndex="..turbineIndex..",monitorIndex="..monitorIndex..") is a valid Big Turbine.")
  1776.     end
  1777.  
  1778.     local width, height = monitor.getSize()
  1779.     local turbineStatus = ""
  1780.  
  1781.     if turbine.getConnected() then
  1782.         printLog("turbine["..turbineIndex.."] in turbineStatus(turbineIndex="..turbineIndex..",monitorIndex="..monitorIndex..") is connected.")
  1783.         if turbine.getActive() then
  1784.             turbineStatus = "ONLINE"
  1785.             monitor.setTextColor(colors.green)
  1786.         else
  1787.             turbineStatus = "OFFLINE"
  1788.             monitor.setTextColor(colors.red)
  1789.         end -- if turbine.getActive() then
  1790.  
  1791.         if (xClick >= (width - string.len(turbineStatus) - 1)) and (xClick <= (width-1)) and (sideClick == monitorNames[monitorIndex]) then
  1792.             if yClick == 1 then
  1793.                 turbine.setActive(not turbine.getActive()) -- Toggle turbine status
  1794.                 _G[turbineNames[turbineIndex]]["TurbineOptions"]["autoStart"] = turbine.getActive()
  1795.                 config.save(turbineNames[turbineIndex]..".options", _G[turbineNames[turbineIndex]])
  1796.                 sideClick, xClick, yClick = 0, 0, 0 -- Reset click after we register it
  1797.             end -- if yClick == 1 then
  1798.         end -- if (xClick >= (width - string.len(turbineStatus) - 1)) and (xClick <= (width-1)) and (sideClick == monitorNames[monitorIndex]) then
  1799.  
  1800.         -- Allow disabling/enabling flow rate auto-adjust
  1801.         if (xClick > 23 and xClick < 28 and yClick == 4) and (sideClick == monitorNames[monitorIndex]) then
  1802.             _G[turbineNames[turbineIndex]]["TurbineOptions"]["flowOverride"] = true
  1803.             sideClick, xClick, yClick = 0, 0, 0 -- Reset click after we register it
  1804.         elseif (xClick > 20 and xClick < 27 and yClick == 10) and (sideClick == monitorNames[monitorIndex]) then
  1805.            
  1806.             if ((_G[turbineNames[turbineIndex]]["TurbineOptions"]["flowOverride"]) or (_G[turbineNames[turbineIndex]]["TurbineOptions"]["flowOverride"] == "true")) then
  1807.                 _G[turbineNames[turbineIndex]]["TurbineOptions"]["flowOverride"] = false
  1808.             else
  1809.                 _G[turbineNames[turbineIndex]]["TurbineOptions"]["flowOverride"] = true
  1810.             end
  1811.             sideClick, xClick, yClick = 0, 0, 0 -- Reset click after we register it
  1812.         end
  1813.         config.save(turbineNames[turbineIndex]..".options", _G[turbineNames[turbineIndex]])
  1814.  
  1815.     else
  1816.         printLog("turbine["..turbineIndex.."] in turbineStatus(turbineIndex="..turbineIndex..",monitorIndex="..monitorIndex..") is NOT connected.")
  1817.         turbineStatus = "DISCONNECTED"
  1818.         monitor.setTextColor(colors.red)
  1819.     end -- if turbine.getConnected() then
  1820.  
  1821.     print{turbineStatus, width - string.len(turbineStatus) - 1, 1, monitorIndex}
  1822.     monitor.setTextColor(colors.white)
  1823. end -- function function turbineStatus(turbineIndex, monitorIndex)
  1824.  
  1825.  
  1826. -- Maintain Turbine flow rate at 900 or 1,800 RPM
  1827. local function flowRateControl(turbineIndex)
  1828.     if ((not _G[turbineNames[turbineIndex]]["TurbineOptions"]["flowOverride"]) or (_G[turbineNames[turbineIndex]]["TurbineOptions"]["flowOverride"] == "false")) then
  1829.        
  1830.         printLog("Called as flowRateControl(turbineIndex="..turbineIndex..").")
  1831.  
  1832.         -- Grab current turbine
  1833.         local turbine = nil
  1834.         turbine = turbineList[turbineIndex]
  1835.  
  1836.         -- assign for the duration of this run
  1837.         local lastTurbineSpeed = tonumber(_G[turbineNames[turbineIndex]]["TurbineOptions"]["LastSpeed"])
  1838.         local turbineBaseSpeed = tonumber(_G[turbineNames[turbineIndex]]["TurbineOptions"]["BaseSpeed"])
  1839.  
  1840.         if not turbine then
  1841.             printLog("turbine["..turbineIndex.."] in flowRateControl(turbineIndex="..turbineIndex..") is NOT a valid Big Turbine.")
  1842.             return -- Invalid turbineIndex
  1843.         else
  1844.             printLog("turbine["..turbineIndex.."] in flowRateControl(turbineIndex="..turbineIndex..") is a valid Big Turbine.")
  1845.  
  1846.             if turbine.getConnected() then
  1847.                 printLog("turbine["..turbineIndex.."] in flowRateControl(turbineIndex="..turbineIndex..") is connected.")
  1848.             else
  1849.                 printLog("turbine["..turbineIndex.."] in flowRateControl(turbineIndex="..turbineIndex..") is NOT connected.")
  1850.             end -- if turbine.getConnected() then
  1851.         end -- if not turbine then
  1852.  
  1853.         -- No point modifying control rod levels for temperature if the turbine is offline
  1854.         if turbine.getActive() then
  1855.             printLog("turbine["..turbineIndex.."] in flowRateControl(turbineIndex="..turbineIndex..") is active.")
  1856.  
  1857.             local flowRate = tonumber(_G[turbineNames[turbineIndex]]["TurbineOptions"]["LastFlow"])
  1858.             local flowRateUserMax = math.ceil(turbine.getFluidFlowRateMax())
  1859.             local rotorSpeed = math.ceil(turbine.getRotorSpeed())
  1860.             local newFlowRate = 0
  1861.  
  1862.             -- Going to control the turbine based on target RPM since changing the target flow rate bypasses this function
  1863.             if (rotorSpeed < turbineBaseSpeed) then
  1864.                 printLog("BELOW COMMANDED SPEED")
  1865.                 if (rotorSpeed > lastTurbineSpeed) then
  1866.                     --we're still increasing, let's let it level off
  1867.                     --also lets the first control pass go by on startup
  1868.                 elseif (rotorSpeed < lastTurbineSpeed) then
  1869.                     --we're decreasing where we should be increasing, do something
  1870.                     if ((lastTurbineSpeed - rotorSpeed) > 100) then
  1871.                         --kick it harder
  1872.                         newFlowRate = 2000
  1873.                         printLog("HARD KICK")
  1874.                     else
  1875.                         --let's adjust based on proximity
  1876.                         flowAdjustment = (turbineBaseSpeed - rotorSpeed)/5
  1877.                         newFlowRate = flowRate + flowAdjustment
  1878.                         printLog("Light Kick: new flow rate is "..newFlowRate.." mB/t and flowAdjustment was "..flowAdjustment.." EOL")
  1879.                     end
  1880.                 else
  1881.                     --we've stagnated, kick it.
  1882.                     flowAdjustment = (turbineBaseSpeed - lastTurbineSpeed)
  1883.                     newFlowRate = flowRate + flowAdjustment
  1884.                     printLog("Stagnated: new flow rate is "..newFlowRate.." mB/t and flowAdjustment was "..flowAdjustment.." EOL")
  1885.                 end --if (rotorSpeed > lastTurbineSpeed) then
  1886.             else
  1887.                 --we're above commanded turbine speed
  1888.                 printLog("ABOVE COMMANDED SPEED")
  1889.                 if (rotorSpeed < lastTurbineSpeed) then
  1890.                 --we're decreasing, let it level off
  1891.                 --also bypasses first control pass on startup
  1892.                 elseif (rotorSpeed > lastTurbineSpeed) then
  1893.                     --we're above and ascending.
  1894.                     if ((rotorSpeed - lastTurbineSpeed) > 100) then
  1895.                         --halt
  1896.                         newFlowRate = 25
  1897.                     else
  1898.                         --let's adjust based on proximity
  1899.                         flowAdjustment = (rotorSpeed - turbineBaseSpeed)/5
  1900.                         newFlowRate = flowRate - flowAdjustment
  1901.                         printLog("Light Kick: new flow rate is "..newFlowRate.." mB/t and flowAdjustment was "..flowAdjustment.." EOL")
  1902.                     end
  1903.                 else
  1904.                     --we've stagnated, kick it.
  1905.                     flowAdjustment = (lastTurbineSpeed - turbineBaseSpeed)
  1906.                     newFlowRate = flowRate - flowAdjustment
  1907.                     printLog("Stagnated: new flow rate is "..newFlowRate.." mB/t and flowAdjustment was "..flowAdjustment.." EOL")
  1908.                 end --if (rotorSpeed < lastTurbineSpeed) then
  1909.             end --if (rotorSpeed < turbineBaseSpeed)
  1910.  
  1911.             --check to make sure an adjustment was made
  1912.             if (newFlowRate == 0) then
  1913.                 --do nothing, we didn't ask for anything this pass
  1914.             else
  1915.                 --boundary check
  1916.                 if newFlowRate > 2000 then
  1917.                     newFlowRate = 2000
  1918.                 elseif newFlowRate < 25 then
  1919.                     newFlowRate = 25 -- Don't go to zero, might as well power off
  1920.                 end -- if newFlowRate > 2000 then
  1921.                 --no sense running an adjustment if it's not necessary
  1922.                 if ((newFlowRate < flowRate) or (newFlowRate > flowRate)) then
  1923.                     printLog("turbine["..turbineIndex.."] in flowRateControl(turbineIndex="..turbineIndex..") is being commanded to "..newFlowRate.." mB/t flow")
  1924.                     newFlowRate = round(newFlowRate, 0)
  1925.                     turbine.setFluidFlowRateMax(newFlowRate)
  1926.                     _G[turbineNames[turbineIndex]]["TurbineOptions"]["LastFlow"] = newFlowRate
  1927.                     config.save(turbineNames[turbineIndex]..".options", _G[turbineNames[turbineIndex]])
  1928.                 end
  1929.             end
  1930.             --always set this
  1931.             _G[turbineNames[turbineIndex]]["TurbineOptions"]["LastSpeed"] = rotorSpeed
  1932.             config.save(turbineNames[turbineIndex]..".options", _G[turbineNames[turbineIndex]])
  1933.         else
  1934.             printLog("turbine["..turbineIndex.."] in flowRateControl(turbineIndex="..turbineIndex..") is NOT active.")
  1935.         end -- if turbine.getActive() then
  1936.     else
  1937.         printLog("turbine["..turbineIndex.."] has flow override set to "..tostring(_G[turbineNames[turbineIndex]]["TurbineOptions"]["flowOverride"])..", bypassing flow control.")
  1938.     end -- if not _G[turbineNames[turbineIndex]]["TurbineOptions"]["flowOverride"] then
  1939. end -- function flowRateControl(turbineIndex)
  1940.  
  1941.  
  1942. function main()
  1943.     -- Load reactor parameters and initialize systems
  1944.     loadReactorOptions()
  1945.  
  1946.     -- Get our initial list of connected monitors and reactors
  1947.     -- and initialize every cycle in case the connected devices change
  1948.     findMonitors()
  1949.     findReactors()
  1950.     findTurbines()
  1951.  
  1952.     while not finished do
  1953.         local reactor = nil
  1954.         local monitorIndex = 1
  1955.  
  1956.         -- For multiple reactors/monitors, monitor #1 is reserved for overall status
  1957.         -- or for multiple reactors/turbines and only one monitor
  1958.         if ( ( ((#reactorList + #turbineList) > 1) and (#monitorList >= 1) )   or
  1959.              ( ((#reactorList + #turbineList) >=1) and (#monitorList >  1) ) ) then
  1960.             local monitor = nil
  1961.             monitor = monitorList[monitorIndex]
  1962.             if not monitor then
  1963.                 printLog("monitor["..monitorIndex.."] in main() is NOT a valid monitor.")
  1964.                 return -- Invalid monitorIndex
  1965.             end
  1966.  
  1967.             clearMonitor(progName.." "..progVer, monitorIndex) -- Clear monitor and draw borders
  1968.             printCentered(progName.." "..progVer, 1, monitorIndex)
  1969.             displayAllStatus()
  1970.             monitorIndex = 2 -- Next monitor, #1 is reserved for overall status
  1971.         end
  1972.  
  1973.         -- Iterate through reactors, continue to run even if not enough monitors are connected
  1974.         for reactorIndex = 1, #reactorList do
  1975.             local monitor = nil
  1976.             local reactorMonitorIndex = monitorIndex + reactorIndex - 1 -- reactorIndex starts at 1
  1977.  
  1978.             printLog("Attempting to display reactor["..reactorIndex.."] on monitor["..reactorMonitorIndex.."]...")
  1979.  
  1980.             reactor = reactorList[reactorIndex]
  1981.             if not reactor then
  1982.                 printLog("reactor["..reactorIndex.."] in main() is NOT a valid Big Reactor.")
  1983.                 break -- Invalid reactorIndex
  1984.             else
  1985.                 printLog("reactor["..reactorIndex.."] in main() is a valid Big Reactor.")
  1986.             end --  if not reactor then
  1987.  
  1988.             -- Only attempt to assign a monitor if we have a monitor for this reactor
  1989.             if (reactorMonitorIndex <= #monitorList) then
  1990.                 printLog("Displaying reactor["..reactorIndex.."] on monitor["..reactorMonitorIndex.."].")
  1991.                 monitor = monitorList[reactorMonitorIndex]
  1992.  
  1993.                 if not monitor then
  1994.                     printLog("monitor["..reactorMonitorIndex.."] in main() is NOT a valid monitor.")
  1995.                 else
  1996.                     clearMonitor(progName, reactorMonitorIndex) -- Clear monitor and draw borders
  1997.                     printCentered(progName, 1, reactorMonitorIndex)
  1998.  
  1999.                     -- Display reactor status, includes "Disconnected" but found reactors
  2000.                     reactorStatus{reactorIndex, reactorMonitorIndex}
  2001.  
  2002.                     -- Draw the borders and bars for the current reactor on the current monitor
  2003.                     displayReactorBars{reactorIndex, reactorMonitorIndex}
  2004.                 end -- if not monitor
  2005.             else
  2006.                 printLog("You may want "..(#reactorList + #turbineList + 1).." monitors for your "..#reactorList.." connected reactors and "..#turbineList.." connected turbines.")
  2007.             end -- if (#monitorList ~= 1) and (reactorMonitorIndex < #monitorList) then
  2008.  
  2009.             if reactor.getConnected() then
  2010.                 printLog("reactor["..reactorIndex.."] is connected.")
  2011.                 local curStoredEnergyPercent = getReactorStoredEnergyBufferPercent(reactor)
  2012.  
  2013.                 -- Shutdown reactor if current stored energy % is >= desired level, otherwise activate
  2014.                 -- First pass will have curStoredEnergyPercent=0 until displayBars() is run once
  2015.                 if curStoredEnergyPercent >= maxStoredEnergyPercent then
  2016.                     reactor.setActive(false)
  2017.                 -- Do not auto-start the reactor if it was manually powered off (autoStart=false)
  2018.                 elseif (curStoredEnergyPercent <= minStoredEnergyPercent) and (_G[reactorNames[reactorIndex]]["ReactorOptions"]["autoStart"] == true) then
  2019.                     reactor.setActive(true)
  2020.                 end -- if curStoredEnergyPercent >= maxStoredEnergyPercent then
  2021.  
  2022.                 -- Don't try to auto-adjust control rods if manual control is requested
  2023.                 if not _G[reactorNames[reactorIndex]]["ReactorOptions"]["rodOverride"] then
  2024.                     temperatureControl(reactorIndex)
  2025.                 end -- if not reactorRodOverride then
  2026.             else
  2027.                 printLog("reactor["..reactorIndex.."] is NOT connected.")
  2028.             end -- if reactor.getConnected() then
  2029.         end -- for reactorIndex = 1, #reactorList do
  2030.  
  2031.         -- Monitors for turbines start after turbineMonitorOffset
  2032.         for turbineIndex = 1, #turbineList do
  2033.             local monitor = nil
  2034.             local turbineMonitorIndex = turbineIndex + turbineMonitorOffset
  2035.  
  2036.             printLog("Attempting to display turbine["..turbineIndex.."] on monitor["..turbineMonitorIndex.."]...")
  2037.  
  2038.             -- Only attempt to assign a monitor if we found a monitor for this turbine
  2039.             if (turbineMonitorIndex <= #monitorList) then
  2040.                 printLog("Displaying turbine["..turbineIndex.."] on monitor["..turbineMonitorIndex.."].")
  2041.                 monitor = monitorList[turbineMonitorIndex]
  2042.                 if not monitor then
  2043.                     printLog("monitor["..turbineMonitorIndex.."] in main() is NOT a valid monitor.")
  2044.                 else
  2045.                     clearMonitor(progName, turbineMonitorIndex) -- Clear monitor and draw borders
  2046.                     printCentered(progName, 1, turbineMonitorIndex)
  2047.  
  2048.                     -- Display turbine status, includes "Disconnected" but found turbines
  2049.                     turbineStatus(turbineIndex, turbineMonitorIndex)
  2050.  
  2051.                     -- Draw the borders and bars for the current turbine on the current monitor
  2052.                     displayTurbineBars(turbineIndex, turbineMonitorIndex)
  2053.                 end -- if not monitor
  2054.             else
  2055.                 printLog("You may want "..(#reactorList + #turbineList + 1).." monitors for your "..#reactorList.." connected reactors and "..#turbineList.." connected turbines.")
  2056.             end -- if (#monitorList ~= 1) and (turbineMonitorIndex < #monitorList) then
  2057.  
  2058.             turbine = turbineList[turbineIndex]
  2059.             if not turbine then
  2060.                 printLog("turbine["..turbineIndex.."] in main() is NOT a valid Big Turbine.")
  2061.                 break -- Invalid turbineIndex
  2062.             else
  2063.                 printLog("turbine["..turbineIndex.."] in main() is a valid Big Turbine.")
  2064.             end -- if not turbine then
  2065.  
  2066.             if turbine.getConnected() then
  2067.                 printLog("turbine["..turbineIndex.."] is connected.")
  2068.  
  2069.                 if not _G[turbineNames[turbineIndex]]["TurbineOptions"]["flowOverride"] then
  2070.                     flowRateControl(turbineIndex)
  2071.                 end -- if not turbineFlowRateOverride[turbineIndex] then
  2072.             else
  2073.                 printLog("turbine["..turbineIndex.."] is NOT connected.")
  2074.             end -- if turbine.getConnected() then
  2075.         end -- for reactorIndex = 1, #reactorList do
  2076.  
  2077.         sleep(loopTime) -- Sleep
  2078.         saveReactorOptions()
  2079.     end -- while not finished do
  2080. end -- main()
  2081.  
  2082.  
  2083. local function eventHandler()
  2084.     while not finished do
  2085.         -- http://computercraft.info/wiki/Os.pullEvent
  2086.         -- http://www.computercraft.info/forums2/index.php?/topic/1516-ospullevent-what-is-it-and-how-is-it-useful/
  2087.         event, arg1, arg2, arg3 = os.pullEvent()
  2088.  
  2089.         if event == "monitor_touch" then
  2090.             sideClick, xClick, yClick = arg1, math.floor(arg2), math.floor(arg3)
  2091.             printLog("Side: "..arg1.." Monitor touch X: "..xClick.." Y: "..yClick)
  2092.         elseif event == "char" and not inManualMode then
  2093.             local ch = string.lower(arg1)
  2094.             if ch == "q" then
  2095.                 finished = true
  2096.             elseif ch == "r" then
  2097.                 finished = true
  2098.                 os.reboot()
  2099.             end -- if ch == "q" then
  2100.         end -- if event == "monitor_touch" then
  2101.     end -- while not finished do
  2102. end -- function eventHandler()
  2103.  
  2104.  
  2105. while not finished do
  2106.     parallel.waitForAny(eventHandler, main)
  2107.     sleep(loopTime)
  2108. end -- while not finished do
  2109.  
  2110.  
  2111. -- Clear up after an exit
  2112. term.clear()
  2113. term.setCursorPos(1,1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement