Advertisement
rhn

lolmer bigreactor term.restore

rhn
May 25th, 2014
6,705
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 56.96 KB | None | 0 0
  1. --[[
  2. Program name: Lolmer's EZ-NUKE reactor control system
  3. Version: v0.3.8
  4. Programmer: Lolmer
  5. Last update: 2014-04-18
  6. Pastebin: http://pastebin.com/fguScPBQ
  7.  
  8. Description:
  9. 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.
  10.  
  11. 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
  12.  
  13. To simplify the code and guesswork, I assume the following monitor layout:
  14. 1) One Advanced Monitor for overall status display plus
  15.     one or more Reactors plus
  16.     none or more Turbines.
  17. 2) One Advanced Monitor for overall status display plus (first found monitor)
  18.     one Advanced Monitor for each connected Reactor plus (subsequent found monitors)
  19.     one Advanced Monitor for each connected Turbine (last group of monitors found).
  20. If you enable debug mode, add one additional Advanced Monitor for #1 or #2.
  21.  
  22. Notes:
  23.     Only one reactor and one, two, and three turbines have been tested with the above, but IN THEORY any number is supported.
  24.     Devices are found in the reverse order they are plugged in, so monitor_10 will be found before monitor_9.
  25.     Two 15x15x14 Turbines can output 260K RF/t by just one 7^3 (four rods) reactor putting out 4k mB steam
  26.  
  27. When using actively cooled reactors with turbines, keep the following in mind:
  28.     - 1 mB steam carries up to 10RF of potential energy to extract in a turbine.
  29.     - Actively cooled reactors produce steam, not power.
  30.     - You will need about 10 mB of water for each 1 mB of steam that you want to create in a 7^3 reactor.
  31.  
  32. Features:
  33.     Configurable min/max energy buffer and min/max temperature via ReactorOptions file.
  34.     ReactorOptions is read on start and then current values are saved every program cycle.
  35.     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.
  36.     Auto-adjusts control rods per reactor to maintain temperature.
  37.     Will display reactor data to all attached monitors of correct dimensions.
  38.         For multiple monitors, the first monitor (often last plugged in) is the overall status monitor.
  39.     For multiple monitors, the first monitor (often last plugged in) is the overall status monitor.
  40.  
  41. GUI Usage:
  42.     The "<" and ">" buttons, when right-clicked with the mouse, will decrease and increase, respectively, the values assigned to the monitor:
  43.         "Rod (%)" will lower/raise the Reactor Control Rods for that Reactor
  44.         "Flow mB/t" will lower/raise the Turbine Flow Rate maximum for that Turbine
  45.     Right-clicking between the "<" and ">" (not on them) will disable auto-adjust of that value for attached device.
  46.         Right-clicking on the "Enabled" or "Disabled" text for auto-adjust will do the same.
  47.     Right-clicking on "ONLINE" or "OFFLINE" at the top-right will toggle the state of attached device.
  48.  
  49. Default values:
  50.     Rod Control: 90% (Let's start off safe and then power up as we can)
  51.     Minimum Energy Buffer: 15% (will power on below this value)
  52.     Maximum Energy Buffer: 85% (will power off above this value)
  53.     Minimum Passive Cooling Temperature: 850^C (will raise control rods below this value)
  54.     Maximum Passive Temperature: 950^C (will lower control rods above this value)
  55.     Optimal Turbine RPM: 900 or 1,800
  56.  
  57. Requirements:
  58.     Advanced Monitor size is X: 29, Y: 12 with a 3x2 size
  59.     Computer or Advanced Computer
  60.     Modems (not wireless) connecting each of the Computer to both the Advanced Monitor and Reactor Computer Port.
  61.     Big Reactors (http://www.big-reactors.com/) 0.3.2A+
  62.     Computercraft (http://computercraft.info/) 1.63+
  63.     Reset the computer any time number of connected devices change.
  64.  
  65. Resources:
  66. This script is available from:
  67.     http://pastebin.com/fguScPBQ
  68.     https://github.com/sandalle/minecraft_bigreactor_control
  69. Start-up script is available from:
  70.     http://pastebin.com/ZTMzRLez
  71.     https://github.com/sandalle/minecraft_bigreactor_control
  72. Other reactor control program which I based my program on:
  73.     http://pastebin.com/aMAu4X5J (ScatmanJohn)
  74.     http://pastebin.com/HjUVNDau (version ScatmanJohn based his on)
  75. A simpler Big Reactor control program is available from:
  76.     http://pastebin.com/7S5xCvgL (IronClaymore only for passively cooled reactors)
  77.  
  78. Reactor Computer Port API: http://wiki.technicpack.net/Reactor_Computer_Port
  79. Computercraft API: http://computercraft.info/wiki/Category:APIs
  80. Big Reactors Efficiency, Speculation and Questions! http://www.reddit.com/r/feedthebeast/comments/1vzds0/big_reactors_efficiency_speculation_and_questions/
  81. Big Reactors API code: https://github.com/erogenousbeef/BigReactors/blob/master/erogenousbeef/bigreactors/common/multiblock/tileentity/TileEntityReactorComputerPort.java
  82. Big Reactors API: http://big-reactors.com/cc_api.html
  83.  
  84. ChangeLog:
  85. 0.3.8 - Update to ComputerCraft 1.6 API.
  86. 0.3.7 - Fix typo when initializing TurbineNames array.
  87.     Fix Issue #1, turbine display is using the Reactor buffer size (10M RF) instead of the Turbine buffer size (1M RF).
  88. 0.3.6 - Fix multi-reactors displaying on the correct monitors (thanks HybridFusion).
  89.     Fix rod auto-adjust text position.
  90.     Reactors store 10M RF and Turbines store 1M RF in their buffer.
  91.     Add more colour to displayAllStatus().
  92.     Sleep for only two seconds instead of five.
  93.     Fix getDeviceStoredEnergyBufferPercent() for Reactors storing 10M RF in buffer.
  94.     Keep actively cooled reactors between 0-300^C (non-configurable for now).
  95. 0.3.5 - Do not discover connected devices every loop - nicer on servers. Reset computer anytime number of connected devices change.
  96.     Fix multi-reactor setups to display the additional reactors on monitors, rather than the last one found.
  97.     Fix passive reactor display having auto-adjust and energy buffer overwrite each other (removes rod count).
  98. 0.3.4 - Fix arithmetic for checking if we have enough monitors for the number of reactors.
  99.     Turbines are optimal at 900, 1800, *and* 2700 RPM
  100.     Increase loop timer from 1 to 5 to be nicer to servers
  101. 0.3.3 - Add Big Reactor Turbine support
  102.     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)
  103.     Display monitor number on top left of each monitor as "M#" to help find which monitor is which.
  104.     Enabling debug will use the last monitor found, if more than one, to print out debug info (also written to file)
  105.     Add monitor layout requirements to simplify code
  106.     Only clear monitors when we're about to use them (e.g. turbine monitors no longer clear, then wait for all reactors to update)
  107.     Fix getDeviceStoredEnergyBufferPercent(), was off by a decimal place
  108.     Just use first Control Rod level for entire reactor, they are no longer treated individually in BR 0.3
  109.     Allow for one monitor for n number of reactors and m number of turbines
  110.     Auto-adjust turbine flow rate by 25 mB to keep rotor speed at 900 or 1,800 RPM.
  111.     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)
  112.     Print monitor name and device (reactor|turbine) name in blue to monitor associated for easier design by users.
  113.     Remove version number from monitors to free up space for monitor names.
  114.     Add option of right-clicking on "Enabled"/"Disabled" of auto-adjust to toggle it.
  115. 0.3.2 - Allow for rod control to override (disable) auto-adjust via UI (Rhonyn)
  116. 0.3.1 - Add fuel consumption per tick to display
  117. 0.3.0 - Add multi-monitor support! Sends one reactor's data to all monitors.
  118.     print function now takes table to support optional specified monitor
  119.     Set "numRods" every cycle for some people (mechaet)
  120.     Don't redirect terminal output with multiple monitor support
  121.     Log troubleshooting data to reactorcontrol.log
  122.     FC_API no longer used (copied and modified what I needed)
  123.     Multi-reactor support is theoretically implemented, but it is UNTESTED!
  124.     Updated for Big Reactor 0.3 (no longer works with 0.2)
  125.     BR getFuelTemperature() now returns many significant digits, just use math.ceil()
  126.     BR 0.3 removed individual rod temperatures, now it's only reactor-level temperature
  127. 0.2.4 - Simplify math, don't divide by a simple large number and then multiply by 100 (#/10000000*100)
  128.     Fix direct-connected (no modem) devices. getDeviceSide -> FC_API.getDeviceSide (simple as that :))
  129. 0.2.3 - Check bounds on reactor.setRodControlLevel(#,#), Big Reactor doesn't check for us.
  130. 0.2.2 - Do not auto-start the reactor if it was manually powered off (autoStart=false)
  131. 0.2.1 - Lower/raise only the hottest/coldest Control Rod while trying to control the reactor temperature.
  132.     "<" Rod Control buttons was off by one (to the left)
  133. 0.2.0 - Lolmer Edition :)
  134.     Add min/max stored energy percentage (default is 15%/85%), configurable via ReactorOptions file.
  135.     No reason to keep burning fuel if our power output is going nowhere. :)
  136.     Use variables variable for the title and version.
  137.     Try to keep the temperature between configured values (default is 850^C-950^C)
  138.     Add Waste and number of Control/Fuel Rods to displayBards()
  139.  
  140. TODO:
  141. - Save parameters per reactor instead of one global set for all reactors
  142. - Add min/max RF/t output and have it override temperature concerns (maybe?)
  143. - Add support for wireless modems, see http://computercraft.info/wiki/Modem_%28API%29, will not be secure (anyone can send/listen to your channels)!
  144. - Add support for any sized monitor (minimum 3x3), dynamic allocation/alignment
  145. - Lookup using pcall for better error handling http://www.computercraft.info/forums2/index.php?/topic/10992-using-pcall/
  146.  
  147. ]]--
  148.  
  149.  
  150. -- Some global variables
  151. local progVer = "0.3.8"
  152. local progName = "EZ-NUKE "
  153. local sideClick, xClick, yClick = nil, 0, 0
  154. local loopTime = 2
  155. local controlRodAdjustAmount = 1 -- Default Reactor Rod Control % adjustment amount
  156. local flowRateAdjustAmount = 25 -- Default Turbine Flow Rate in mB adjustment amount
  157. local debugMode = false
  158. -- These need to be updated for multiple reactors
  159. local baseControlRodLevel = nil
  160. local reactorRodOverride = false -- Rod override for Reactors
  161. -- End multi-reactor cleanup section
  162. local minStoredEnergyPercent = nil -- Max energy % to store before activate
  163. local maxStoredEnergyPercent = nil -- Max energy % to store before shutdown
  164. local minReactorTemp = nil -- Minimum reactor temperature (^C) to maintain
  165. local maxReactorTemp = nil -- Maximum reactor temperature (^C) to maintain
  166. local autoStart = {} -- Array for automatically starting reactors
  167. local monitorList = {} -- Empty monitor array
  168. local monitorNames = {} -- Empty array of monitor names
  169. local reactorList = {} -- Empty reactor array
  170. local reactorNames = {} -- Empty array of reactor names
  171. local turbineList = {} -- Empty turbine array
  172. local turbineNames = {} -- Empty array of turbine names
  173. local turbineFlowRateOverride = {} -- Flow rate override for each Turbine
  174. local turbineMonitorOffset = 0 -- Turbines are assigned monitors after reactors
  175.  
  176. term.clear()
  177. term.setCursorPos(2,1)
  178. term.write("Initializing program...")
  179.  
  180.  
  181. -- File needs to exist for append "a" later and zero it out if it already exists
  182. -- Always initalize this file to avoid confusion with old files and the latest run
  183. local logFile = fs.open("reactorcontrol.log", "w")
  184. if logFile then
  185.     logFile.writeLine("Minecraft time: Day "..os.day().." at "..textutils.formatTime(os.time(),true))
  186.     logFile.close()
  187. else
  188.     error("Could not open file reactorcontrol.log for writing")
  189. end
  190.  
  191.  
  192. -- Helper functions
  193.  
  194.  
  195. -- round() function from
  196. -- http://www.computercraft.info/forums2/index.php?/topic/4023-lua-printformat-with-floating-point-numbers/page__view__findpost__p__31037
  197. local function round(num, places)
  198.     num = tostring(num)
  199.     local inc = false
  200.  
  201.     -- Make sure decimal is a valid integer for later arithmetic
  202.     local decimal = string.find(num, "%.") or 0
  203.  
  204.     if (num:len() - decimal) <= places then
  205.         return tonumber(num)
  206.     end --already rounded, nothing to do.
  207.  
  208.     local digit = tonumber(num:sub(decimal + places + 1))
  209.     num = num:sub(1, decimal + places)
  210.  
  211.     if digit <= 4 then
  212.         return tonumber(num)
  213.     end --no incrementation needed, return truncated number
  214.  
  215.     local newNum = ""
  216.     for i=num:len(), 1, -1 do
  217.             digit = tonumber(num:sub(i))
  218.             if digit == 9 then
  219.                     if i > 1 then
  220.                             newNum = "0"..newNum
  221.                     else
  222.                             newNum = "10"..newNum
  223.                     end
  224.             elseif digit == nil then
  225.                     newNum = "."..newNum
  226.             else
  227.                     if i > 1 then
  228.                             newNum = num:sub(1,i-1)..(digit + 1)..newNum
  229.                     else
  230.                             newNum = (digit + 1)..newNum
  231.                     end
  232.                     return tonumber(newNum) --No more 9s found, so we are done incrementing. Copy remaining digits, then return number.
  233.             end -- if digit == 9 then
  234.     end -- for i=num:len(), 1, -1 do
  235.     return tonumber(newNum)
  236. end -- function round(num, places
  237.  
  238.  
  239. local function printLog(printStr)
  240.     if debugMode then
  241.         -- If multiple monitors, use the last monitor for debugging if debug is enabled
  242.         if #monitorList > 1 then
  243.             term.redirect(monitorList[#monitorList]) -- Redirect to last monitor for debugging
  244.             monitorList[#monitorList].setTextScale(0.5) -- Fit more logs on screen
  245.             write(printStr.."\n")   -- May need to use term.scroll(x) if we output too much, not sure
  246.             term.restore()
  247.         end -- if #monitorList > 1 then
  248.  
  249.         local logFile = fs.open("reactorcontrol.log", "a") -- See http://computercraft.info/wiki/Fs.open
  250.         if logFile then
  251.             logFile.writeLine(printStr)
  252.             logFile.close()
  253.         else
  254.             error("Cannot open file reactorcontrol.log for appending!")
  255.         end -- if logFile then
  256.     end -- if debugMode then
  257. end -- function printLog(printStr)
  258.  
  259.  
  260. local function print(printParams)
  261.     -- Default to xPos=1, yPos=1, and first monitor
  262.     setmetatable(printParams,{__index={xPos=1, yPos=1, monitorIndex=1}})
  263.     local printString, xPos, yPos, monitorIndex =
  264.         printParams[1], -- Required parameter
  265.         printParams[2] or printParams.xPos,
  266.         printParams[3] or printParams.yPos,
  267.         printParams[4] or printParams.monitorIndex
  268.  
  269.     local monitor = nil
  270.     monitor = monitorList[monitorIndex]
  271.  
  272.     if not monitor then
  273.         printLog("monitorList["..monitorIndex.."] in print() was not a valid monitor")
  274.         return -- Invalid monitorIndex
  275.     end
  276.  
  277.     monitor.setCursorPos(xPos, yPos)
  278.     monitor.write(printString)
  279. end -- function print(printParams)
  280.  
  281.  
  282. -- Replaces the one from FC_API (http://pastebin.com/A9hcbZWe) and adding multi-monitor support
  283. local function printCentered(printString, yPos, monitorIndex)
  284.     local monitor = nil
  285.     monitor = monitorList[monitorIndex]
  286.  
  287.     if not monitor then
  288.         printLog("monitorList["..monitorIndex.."] in printCentered() was not a valid monitor")
  289.         return -- Invalid monitorIndex
  290.     end
  291.  
  292.     local width, height = monitor.getSize()
  293.     local monitorNameLength = 0
  294.  
  295.     -- Special changes for title bar
  296.     if yPos == 1 then
  297.         -- Add monitor name to first line
  298.         monitorNameLength = monitorNames[monitorIndex]:len()
  299.  
  300.         -- Leave room for "offline" and "online" on the right except for overall status display
  301.         if (#monitorList ~= 1) and (monitorIndex ~= 1) then
  302.             width = width - 7
  303.         end
  304.     end
  305.  
  306.     monitor.setCursorPos(math.floor(width/2) - math.ceil(printString:len()/2) +  monitorNameLength/2, yPos)
  307.     monitor.clearLine()
  308.     monitor.write(printString)
  309.  
  310.     monitor.setTextColor(colors.blue)
  311.     print{monitorNames[monitorIndex], 1, 1, monitorIndex}
  312.     monitor.setTextColor(colors.white)
  313. end -- function printCentered(printString, yPos, monitorIndex)
  314.  
  315.  
  316. -- Print text padded from the left side
  317. -- Clear the left side of the screen
  318. local function printLeft(printString, yPos, monitorIndex)
  319.     local monitor = nil
  320.     monitor = monitorList[monitorIndex]
  321.  
  322.     if not monitor then
  323.         printLog("monitorList["..monitorIndex.."] in printLeft() was not a valid monitor")
  324.         return -- Invalid monitorIndex
  325.     end
  326.  
  327.     local gap = 1
  328.     local width = monitor.getSize()
  329.  
  330.     -- Clear left-half of the monitor
  331.  
  332.     for curXPos = 1, (width / 2) do
  333.         monitor.setCursorPos(curXPos, yPos)
  334.         monitor.write(" ")
  335.     end
  336.  
  337.     -- Write our string left-aligned
  338.     monitor.setCursorPos(1+gap, yPos)
  339.     monitor.write(printString)
  340. end
  341.  
  342.  
  343. -- Print text padded from the right side
  344. -- Clear the right side of the screen
  345. local function printRight(printString, yPos, monitorIndex)
  346.     local monitor = nil
  347.     monitor = monitorList[monitorIndex]
  348.  
  349.     if not monitor then
  350.         printLog("monitorList["..monitorIndex.."] in printRight() was not a valid monitor")
  351.         return -- Invalid monitorIndex
  352.     end
  353.  
  354.     -- Make sure printString is a string
  355.     printString = tostring(printString)
  356.  
  357.     local gap = 1
  358.     local width = monitor.getSize()
  359.  
  360.     -- Clear right-half of the monitor
  361.     for curXPos = (width/2), width do
  362.         monitor.setCursorPos(curXPos, yPos)
  363.         monitor.write(" ")
  364.     end
  365.  
  366.     -- Write our string right-aligned
  367.     monitor.setCursorPos(math.floor(width) - math.ceil(printString:len()+gap), yPos)
  368.     monitor.write(printString)
  369. end
  370.  
  371.  
  372. -- Replaces the one from FC_API (http://pastebin.com/A9hcbZWe) and adding multi-monitor support
  373. local function clearMonitor(printString, monitorIndex)
  374.     local monitor = nil
  375.     monitor = monitorList[monitorIndex]
  376.  
  377.     if not monitor then
  378.         printLog("monitorList["..monitorIndex.."] in clearMonitor() was not a valid monitor")
  379.         return -- Invalid monitorIndex
  380.     end
  381.  
  382.     local gap = 2
  383.     monitor.clear()
  384.     local width, height = monitor.getSize()
  385.  
  386.     printCentered(printString, 1, monitorIndex)
  387.     monitor.setTextColor(colors.blue)
  388.     print{monitorNames[monitorIndex], 1, 1, monitorIndex}
  389.     monitor.setTextColor(colors.white)
  390.  
  391.     for i=1, width do
  392.         monitor.setCursorPos(i, gap)
  393.         monitor.write("-")
  394.     end
  395.  
  396.     monitor.setCursorPos(1, gap+1)
  397. end -- function clearMonitor(printString, monitorIndex)
  398.  
  399.  
  400. -- Return a list of all connected (including via wired modems) devices of "deviceType"
  401. local function getDevices(deviceType)
  402.     local deviceName = nil
  403.     local deviceIndex = 1
  404.     local deviceList, deviceNames = {}, {} -- Empty array, which grows as we need
  405.     local peripheralList = peripheral.getNames() -- Get table of connected peripherals
  406.  
  407.     deviceType = deviceType:lower() -- Make sure we're matching case here
  408.  
  409.     for peripheralIndex = 1, #peripheralList do
  410.         -- Log every device found
  411.         -- printLog("Found "..peripheral.getType(peripheralList[peripheralIndex]).."["..peripheralIndex.."] attached as \""..peripheralList[peripheralIndex].."\".")
  412.         if (string.lower(peripheral.getType(peripheralList[peripheralIndex])) == deviceType) then
  413.             -- Log devices found which match deviceType and which device index we give them
  414.             printLog("Found "..peripheral.getType(peripheralList[peripheralIndex]).."["..peripheralIndex.."] as index \"["..deviceIndex.."]\" attached as \""..peripheralList[peripheralIndex].."\".")
  415.             deviceNames[deviceIndex] = peripheralList[peripheralIndex]
  416.             deviceList[deviceIndex] = peripheral.wrap(peripheralList[peripheralIndex])
  417.             deviceIndex = deviceIndex + 1
  418.         end
  419.     end -- for peripheralIndex = 1, #peripheralList do
  420.  
  421.     return deviceList, deviceNames
  422. end -- function getDevices(deviceType)
  423.  
  424. -- Draw a line across the entire x-axis
  425. local function drawLine(yPos, monitorIndex)
  426.     local monitor = nil
  427.     monitor = monitorList[monitorIndex]
  428.  
  429.     if not monitor then
  430.         printLog("monitorList["..monitorIndex.."] in drawLine() was not a valid monitor")
  431.         return -- Invalid monitorIndex
  432.     end
  433.  
  434.     local width, height = monitor.getSize()
  435.  
  436.     for i=1, width do
  437.         monitor.setCursorPos(i, yPos)
  438.         monitor.write("-")
  439.     end
  440. end -- function drawLine(yPos,monitorIndex)
  441.  
  442.  
  443. -- Display a solid bar of specified color
  444. local function drawBar(startXPos, startYPos, endXPos, endYPos, color, monitorIndex)
  445.     local monitor = nil
  446.     monitor = monitorList[monitorIndex]
  447.  
  448.     if not monitor then
  449.         printLog("monitorList["..monitorIndex.."] in drawBar() was not a valid monitor")
  450.         return -- Invalid monitorIndex
  451.     end
  452.  
  453.     -- PaintUtils only outputs to term., not monitor.
  454.     -- See http://www.computercraft.info/forums2/index.php?/topic/15540-paintutils-on-a-monitor/
  455.     term.redirect(monitor)
  456.     paintutils.drawLine(startXPos, startYPos, endXPos, endYPos, color)
  457.     monitor.setBackgroundColor(colors.black) -- PaintUtils doesn't restore the color
  458. term.restore()
  459. end -- function drawBar(startXPos, startYPos,endXPos,endYPos,color,monitorIndex)
  460.  
  461.  
  462. -- Display single pixel color
  463. local function drawPixel(xPos, yPos, color, monitorIndex)
  464.     local monitor = nil
  465.     monitor = monitorList[monitorIndex]
  466.  
  467.     if not monitor then
  468.         printLog("monitorList["..monitorIndex.."] in drawPixel() was not a valid monitor")
  469.         return -- Invalid monitorIndex
  470.     end
  471.  
  472.     -- PaintUtils only outputs to term., not monitor.
  473.     -- See http://www.computercraft.info/forums2/index.php?/topic/15540-paintutils-on-a-monitor/
  474.     term.redirect(monitor)
  475.     paintutils.drawPixel(xPos, yPos, color)
  476.     monitor.setBackgroundColor(colors.black) -- PaintUtils doesn't restore the color
  477.     term.restore()
  478. end -- function drawPixel(xPos, yPos, color, monitorIndex)
  479.  
  480.  
  481. -- End helper functions
  482.  
  483.  
  484. -- Then initialize the monitors
  485. local function findMonitors()
  486.     -- Empty out old list of monitors
  487.     monitorList = {}
  488.  
  489.     printLog("Finding monitors...")
  490.     monitorList, monitorNames = getDevices("monitor")
  491.  
  492.     if #monitorList == 0 then
  493.         printLog("No monitors found!")
  494.         error("Can't find any monitors!")
  495.     else
  496.         for monitorIndex = 1, #monitorList do
  497.             local monitor = nil
  498.             monitor = monitorList[monitorIndex]
  499.  
  500.             if not monitor then
  501.                 printLog("monitorList["..monitorIndex.."] in findMonitors() was not a valid monitor")
  502.                 break -- Invalid monitorIndex
  503.             end
  504.  
  505.             local monitorX, monitorY = monitor.getSize()
  506.             printLog("Verifying monitor["..monitorIndex.."] is of size x:"..monitorX.." by y:"..monitorY)
  507.  
  508.             -- Check for minimum size to allow for monitor.setTextScale(0.5) to work for 3x2 debugging monitor, changes getSize()
  509.             if monitorX < 29 or monitorY < 12 then
  510.                 term.redirect(monitor)
  511.                 monitor.clear()
  512.                 printLog("Removing monitor "..monitorIndex.." for incorrect size")
  513.                 monitor.setCursorPos(1,2)
  514.                 write("Monitor is the wrong size!\n")
  515.                 write("Needs to be 3x2.")
  516.                 term.restore()
  517.  
  518.                 table.remove(monitorList, monitorIndex) -- Remove invalid monitor from list
  519.                 if monitorIndex == #monitorList then    -- If we're at the end already, break from loop
  520.                     break
  521.                 else
  522.                     monitorIndex = monitorIndex - 1 -- We just removed an element
  523.                 end -- if monitorIndex == #monitorList then
  524.  
  525.             end -- if monitorX ~= 29 or monitorY ~= 12 then
  526.         end -- for monitorIndex = 1, #monitorList do
  527.     end -- if #monitorList == 0 then
  528. end -- local function findMonitors()
  529.  
  530.  
  531. -- Initialize all Big Reactors - Reactors
  532. local function findReactors()
  533.     -- Empty out old list of reactors
  534.     newReactorList = {}
  535.  
  536.     printLog("Finding reactors...")
  537.     newReactorList, reactorNames = getDevices("BigReactors-Reactor")
  538.  
  539.     if #newReactorList == 0 then
  540.         printLog("No reactors found!")
  541.         error("Can't find any reactors!")
  542.     else  -- Placeholder
  543.         for reactorIndex = 1, #newReactorList do
  544.             local reactor = nil
  545.             reactor = newReactorList[reactorIndex]
  546.  
  547.             if not reactor then
  548.                 printLog("reactorList["..reactorIndex.."] in findReactors() was not a valid Big Reactor")
  549.                 return -- Invalid reactorIndex
  550.             end
  551.  
  552.             -- If number of found reactors changed, re-initialize them all for now
  553.             -- For now, initialize reactors to the same baseControlRodLevel
  554.             if #newReactorList ~= #reactorList then
  555.                 reactor.setAllControlRodLevels(baseControlRodLevel)
  556.  
  557.                 -- Auto-start reactor when needed (e.g. program startup) by default, or use existing value
  558.                 autoStart[reactorIndex] = true
  559.             end -- if #newReactorList ~= #reactorList then
  560.         end -- for reactorIndex = 1, #newReactorList do
  561.     end -- if #newReactorList == 0 then
  562.  
  563.     -- Overwrite old reactor list with the now updated list
  564.     reactorList = newReactorList
  565.  
  566.     -- Check if we have enough monitors for the number of reactors
  567.     if (#reactorList ~= 1) and ((#turbineList + #reactorList) + 1 < #monitorList) then
  568.         printLog("You need "..(#reactorList + 1).." monitors for your "..#reactorList.." connected reactors")
  569.     end
  570.  
  571.     -- Start turbine monitor offset after reactors get monitors
  572.     -- This assumes that there is a monitor for each turbine and reactor, plus the overall monitor display
  573.     turbineMonitorOffset = #reactorList + 1 -- #turbineList will start at "1" if turbines found and move us just beyond #reactorList and status monitor range
  574. end -- function findReactors()
  575.  
  576.  
  577. -- Initialize all Big Reactors - Turbines
  578. local function findTurbines()
  579.     -- Empty out old list of turbines
  580.     newTurbineList = {}
  581.  
  582.     printLog("Finding turbines...")
  583.     newTurbineList, turbineNames = getDevices("BigReactors-Turbine")
  584.  
  585.     if #newTurbineList == 0 then
  586.         printLog("No turbines found") -- Not an error
  587.     else
  588.         for turbineIndex = 1, #newTurbineList do
  589.             local turbine = nil
  590.             turbine = newTurbineList[turbineIndex]
  591.  
  592.             if not turbine then
  593.                 printLog("turbineList["..turbineIndex.."] is not a valid Big Reactors Turbine")
  594.                 return -- Invalid turbineIndex
  595.             end
  596.  
  597.             -- If number of found turbines changed, re-initialize them all for now
  598.             if #newTurbineList ~= #turbineList then
  599.                 -- Default is to allow flow rate auto-adjust
  600.                 turbineFlowRateOverride[turbineIndex] = false
  601.             end -- if #newTurbineList ~= #turbineList then
  602.         end -- for turbineIndex = 1, #newTurbineList do
  603.  
  604.         -- Overwrite old turbine list with the now updated list
  605.         turbineList = newTurbineList
  606.  
  607.         -- Check if we have enough monitors for the number of turbines
  608.         if #monitorList < (#reactorList + #turbineList + 1) then
  609.             printLog("You need "..(#reactorList + #turbineList + 1).." monitors for your "..#reactorList.." connected reactors and "..#turbineList.." connected turbines")
  610.         end
  611.     end -- if #newTurbineList == 0 then
  612. end -- function findTurbines()
  613.  
  614.  
  615. -- Return current energy buffer in a specific reactor by %
  616. local function getReactorStoredEnergyBufferPercent(reactor)
  617.     if not reactor then
  618.         printLog("getReactorStoredEnergyBufferPercent() did not receive a valid Big Reactor Reactor")
  619.         return -- Invalid reactorIndex
  620.     end
  621.  
  622.     local energyBufferStorage = reactor.getEnergyStored()
  623.     return (math.floor(energyBufferStorage/100000)) -- (buffer/10000000 RF)*100%
  624. end -- function getReactorStoredEnergyBufferPercent(reactor)
  625.  
  626.  
  627. -- Return current energy buffer in a specific Turbine by %
  628. local function getTurbineStoredEnergyBufferPercent(turbine)
  629.     if not turbine then
  630.         printLog("getTurbineStoredEnergyBufferPercent() did not receive a valid Big Reactor Turbine")
  631.         return -- Invalid reactorIndex
  632.     end
  633.  
  634.     local energyBufferStorage = turbine.getEnergyStored()
  635.     return (math.floor(energyBufferStorage/10000)) -- (buffer/1000000 RF)*100%
  636. end -- function getTurbineStoredEnergyBufferPercent(turbine)
  637.  
  638.  
  639. -- Modify reactor control rod levels to keep temperature with defined parameters, but
  640. -- wait an in-game half-hour for the temperature to stabalize before modifying again
  641. local function temperatureControl(reactorIndex)
  642.     local reactor = nil
  643.     reactor = reactorList[reactorIndex]
  644.     if not reactor then
  645.         printLog("reactorList["..reactorIndex.."] in temperatureControl() was not a valid Big Reactor")
  646.         return -- Invalid reactorIndex
  647.     end
  648.  
  649.     local rodPercentage = math.ceil(reactor.getControlRodLevel(0))
  650.     local reactorTemp = math.ceil(reactor.getFuelTemperature())
  651.     local localMinReactorTemp, localMaxReactorTemp = minReactorTemp, maxReactorTemp
  652.  
  653.     -- No point modifying control rod levels for temperature if the reactor is offline
  654.     if reactor.getActive() then
  655.         -- Actively cooled reactors should range between 0^C-300^C
  656.         if reactor.isActivelyCooled() then
  657.             localMinReactorTemp = 0
  658.             localMaxReactorTemp = 300
  659.         end
  660.  
  661.         -- Don't bring us to 100, that's effectively a shutdown
  662.         if (reactorTemp > localMaxReactorTemp) and (rodPercentage ~= 99) then
  663.             -- If more than double our maximum temperature, increase rodPercentage faster
  664.             if reactorTemp > (2 * localMaxReactorTemp) then
  665.                 -- Check bounds, Big Reactor doesn't do this for us. :)
  666.                 if (rodPercentage + (10 * controlRodAdjustAmount)) > 99 then
  667.                     reactor.setAllControlRodLevels(99)
  668.                 else
  669.                     reactor.setAllControlRodLevels(rodPercentage + (10 * controlRodAdjustAmount))
  670.                 end
  671.             else
  672.                 -- Check bounds, Big Reactor doesn't do this for us. :)
  673.                 if (rodPercentage + controlRodAdjustAmount) > 99 then
  674.                     reactor.setAllControlRodLevels(99)
  675.                 else
  676.                     reactor.setAllControlRodLevels(rodPercentage + controlRodAdjustAmount)
  677.                 end
  678.             end -- if reactorTemp > (2 * localMaxReactorTemp) then
  679.         elseif (reactorTemp < localMinReactorTemp) and (rodPercentage ~= 0) then
  680.             -- If less than half our minimum temperature, decrease rodPercentage faster
  681.             if reactorTemp < (localMinReactorTemp / 2) then
  682.                 -- Check bounds, Big Reactor doesn't do this for us. :)
  683.                 if (rodPercentage - (10 * controlRodAdjustAmount)) < 0 then
  684.                     reactor.setAllControlRodLevels(0)
  685.                 else
  686.                     reactor.setAllControlRodLevels(rodPercentage - (10 * controlRodAdjustAmount))
  687.                 end
  688.             else
  689.                 -- Check bounds, Big Reactor doesn't do this for us. :)
  690.                 if (rodPercentage - controlRodAdjustAmount) < 0 then
  691.                     reactor.setAllControlRodLevels(0)
  692.                 else
  693.                     reactor.setAllControlRodLevels(rodPercentage - controlRodAdjustAmount)
  694.                 end
  695.             end -- if reactorTemp < (localMinReactorTemp / 2) then
  696.  
  697.             baseControlRodLevel = rodPercentage
  698.         end -- if (reactorTemp > localMaxReactorTemp) and (rodPercentage < 99) then
  699.     end -- if reactor.getActive() then
  700. end -- function temperatureControl(reactorIndex)
  701.  
  702.  
  703. -- Load saved reactor parameters if ReactorOptions file exists
  704. local function loadReactorOptions()
  705.     local reactorOptions = fs.open("ReactorOptions", "r") -- See http://computercraft.info/wiki/Fs.open
  706.  
  707.     if reactorOptions then
  708.         baseControlRodLevel = reactorOptions.readLine()
  709.         -- The following values were added by Lolmer
  710.         minStoredEnergyPercent = reactorOptions.readLine()
  711.         maxStoredEnergyPercent = reactorOptions.readLine()
  712.         minReactorTemp = reactorOptions.readLine()
  713.         maxReactorTemp = reactorOptions.readLine()
  714.         reactorRodOverride = reactorOptions.readLine() -- Should be string "true" or "false"
  715.  
  716.         -- If we succeeded in reading a string, convert it to a number
  717.         if baseControlRodLevel ~= nil then
  718.             baseControlRodLevel = tonumber(baseControlRodLevel)
  719.         end
  720.  
  721.         if minStoredEnergyPercent ~= nil then
  722.             minStoredEnergyPercent = tonumber(minStoredEnergyPercent)
  723.         end
  724.  
  725.         if maxStoredEnergyPercent ~= nil then
  726.             maxStoredEnergyPercent = tonumber(maxStoredEnergyPercent)
  727.         end
  728.  
  729.         if minReactorTemp ~= nil then
  730.             minReactorTemp = tonumber(minReactorTemp)
  731.         end
  732.  
  733.         if maxReactorTemp ~= nil then
  734.             maxReactorTemp = tonumber(maxReactorTemp)
  735.         end
  736.  
  737.         if reactorRodOverride == "true" then
  738.             reactorRodOverride = true
  739.         else
  740.             reactorRodOverride = false
  741.         end
  742.  
  743.         reactorOptions.close()
  744.     end -- if reactorOptions then
  745.  
  746.     -- Set default values if we failed to read any of the above
  747.     if baseControlRodLevel == nil then
  748.         baseControlRodLevel = 90
  749.     end
  750.  
  751.     if minStoredEnergyPercent == nil then
  752.         minStoredEnergyPercent = 15
  753.     end
  754.  
  755.     if maxStoredEnergyPercent == nil then
  756.         maxStoredEnergyPercent = 85
  757.     end
  758.  
  759.     if minReactorTemp == nil then
  760.         minReactorTemp = 850
  761.     end
  762.  
  763.     if maxReactorTemp == nil then
  764.         maxReactorTemp = 950
  765.     end
  766. end -- function loadReactorOptions()
  767.  
  768.  
  769. -- Save our reactor parameters
  770. local function saveReactorOptions()
  771.     local reactorOptions = fs.open("ReactorOptions", "w") -- See http://computercraft.info/wiki/Fs.open
  772.  
  773.     -- If we can save the files, save them
  774.     if reactorOptions then
  775.         local reactorIndex = 1
  776.         reactorOptions.writeLine(math.ceil(reactorList[1].getControlRodLevel(0))) -- Store just the first reactor for now
  777.         -- The following values were added by Lolmer
  778.         reactorOptions.writeLine(minStoredEnergyPercent)
  779.         reactorOptions.writeLine(maxStoredEnergyPercent)
  780.         reactorOptions.writeLine(minReactorTemp)
  781.         reactorOptions.writeLine(maxReactorTemp)
  782.         reactorOptions.writeLine(reactorRodOverride)
  783.         reactorOptions.close()
  784.     else
  785.         printLog("Failed to open file ReactorOptions for writing!")
  786.     end -- if reactorOptions then
  787. end -- function saveReactorOptions()
  788.  
  789.  
  790. local function displayReactorBars(barParams)
  791.     -- Default to first reactor and first monitor
  792.     setmetatable(barParams,{__index={reactorIndex=1, monitorIndex=1}})
  793.     local reactorIndex, monitorIndex =
  794.         barParams[1] or barParams.reactorIndex,
  795.         barParams[2] or barParams.monitorIndex
  796.  
  797.     -- Grab current monitor
  798.     local monitor = nil
  799.     monitor = monitorList[monitorIndex]
  800.     if not monitor then
  801.         printLog("monitorList["..monitorIndex.."] in displayReactorBars() was not a valid monitor")
  802.         return -- Invalid monitorIndex
  803.     end
  804.  
  805.     -- Grab current reactor
  806.     local reactor = nil
  807.     reactor = reactorList[reactorIndex]
  808.     if not reactor then
  809.         printLog("reactorList["..reactorIndex.."] in displayReactorBars() was not a valid Big Reactor")
  810.         return -- Invalid reactorIndex
  811.     end
  812.  
  813.     -- Draw border lines
  814.     local width, height = monitor.getSize()
  815.  
  816.     for i=3, 5 do
  817.         monitor.setCursorPos(22, i)
  818.         monitor.write("|")
  819.     end
  820.  
  821.     drawLine(2, monitorIndex)
  822.     drawLine(6, monitorIndex)
  823.  
  824.     -- Draw some text
  825.     local fuelString = "Fuel: "
  826.     local tempString = "Temp: "
  827.     local energyBufferString = "Producing: "
  828.  
  829.     local padding = math.max(string.len(fuelString), string.len(tempString), string.len(energyBufferString))
  830.  
  831.     local fuelPercentage = math.ceil(reactor.getFuelAmount()/reactor.getFuelAmountMax()*100)
  832.     print{fuelString,2,3,monitorIndex}
  833.     print{fuelPercentage.." %",padding+2,3,monitorIndex}
  834.  
  835.     local reactorTemp = math.ceil(reactor.getFuelTemperature())
  836.     print{tempString,2,5,monitorIndex}
  837.     print{reactorTemp.." C",padding+2,5,monitorIndex}
  838.  
  839.     local rodPercentage = math.ceil(reactor.getControlRodLevel(0))
  840.     -- Allow controlling Reactor Control Rod Level from GUI
  841.     -- Decrease rod button: 23X, 4Y
  842.     -- Increase rod button: 28X, 4Y
  843.     if (xClick == 23) and (yClick == 4) and (sideClick == monitorNames[monitorIndex]) then
  844.         --Decrease rod level by amount
  845.         newRodPercentage = rodPercentage - (5 * controlRodAdjustAmount)
  846.         if newRodPercentage < 0 then
  847.             newRodPercentage = 0
  848.         end
  849.         sideClick, xClick, yClick = 0, 0, 0
  850.  
  851.         reactor.setAllControlRodLevels(newRodPercentage)
  852.  
  853.         -- Save updated rod percentage
  854.         baseControlRodLevel = newRodPercentage
  855.         rodPercentage = newRodPercentage
  856.     end -- if (xClick == 23) and (yClick == 4) and (sideClick == monitorNames[monitorIndex]) then
  857.  
  858.     if (xClick == 29) and (yClick == 4) and (sideClick == monitorNames[monitorIndex]) then
  859.         --Increase rod level by amount
  860.         newRodPercentage = rodPercentage + (5 * controlRodAdjustAmount)
  861.         if newRodPercentage > 100 then
  862.             newRodPercentage = 100
  863.         end
  864.         sideClick, xClick, yClick = 0, 0, 0
  865.  
  866.         reactor.setAllControlRodLevels(newRodPercentage)
  867.  
  868.         -- Save updated rod percentage
  869.         baseControlRodLevel = newRodPercentage
  870.         rodPercentage = newRodPercentage
  871.     end -- if (xClick == 29) and (yClick == 4) and (sideClick == monitorNames[monitorIndex]) then
  872.  
  873.     print{"Rod (%)",23,3,monitorIndex}
  874.     print{"<     >",23,4,monitorIndex}
  875.     print{rodPercentage,25,4,monitorIndex}
  876.  
  877.     -- getEnergyProducedLastTick() is used for both RF/t (passively cooled) and mB/t (actively cooled)
  878.     local energyBuffer = reactor.getEnergyProducedLastTick()
  879.     print{energyBufferString,2,4,monitorIndex}
  880.  
  881.     -- Actively cooled reactors do not produce energy, only hot fluid mB/t to be used in a turbine
  882.     -- still uses getEnergyProducedLastTick for mB/t of hot fluid generated
  883.     if not reactor.isActivelyCooled() then
  884.         -- Draw stored energy buffer bar
  885.         drawBar(2,8,28,8,colors.gray,monitorIndex)
  886.  
  887.         local curStoredEnergyPercent = getReactorStoredEnergyBufferPercent(reactor)
  888.         if curStoredEnergyPercent > 4 then
  889.             drawBar(2, 8, math.floor(26*curStoredEnergyPercent/100)+2, 8, colors.yellow, monitorIndex)
  890.         elseif curStoredEnergyPercent > 0 then
  891.             drawPixel(2, 8, colors.yellow, monitorIndex)
  892.         end -- if curStoredEnergyPercent > 4 then
  893.  
  894.         print{"Energy Buffer",2,7,monitorIndex}
  895.         print{curStoredEnergyPercent, width-(string.len(curStoredEnergyPercent)+3),7,monitorIndex}
  896.         print{"%",28,7,monitorIndex}
  897.  
  898.         print{math.ceil(energyBuffer).." RF/t",padding+2,4,monitorIndex}
  899.     else
  900.         print{math.ceil(energyBuffer).." mB/t",padding+2,4,monitorIndex}
  901.     end -- if not reactor.isActivelyCooled() then
  902.  
  903.     -- Print rod override status
  904.     local reactorRodOverrideStatus = ""
  905.  
  906.     print{"Rod Auto-adjust:",2,9,monitorIndex}
  907.  
  908.     if not reactorRodOverride then
  909.         reactorRodOverrideStatus = "Enabled"
  910.         monitor.setTextColor(colors.green)
  911.     else
  912.         reactorRodOverrideStatus = "Disabled"
  913.         monitor.setTextColor(colors.red)
  914.     end -- if not reactorRodOverride then
  915.  
  916.     print{reactorRodOverrideStatus, width - string.len(reactorRodOverrideStatus) - 1, 9, monitorIndex}
  917.     monitor.setTextColor(colors.white)
  918.  
  919.     local numRods = reactor.getNumberOfControlRods() - 1 -- Call every time as some people modify their reactor without rebooting the computer
  920.  
  921.     print{"Reactivity: "..math.ceil(reactor.getFuelReactivity()).." %", 2, 10, monitorIndex}
  922.     print{"Fuel: "..round(reactor.getFuelConsumedLastTick(),3).." mB/t", 2, 11, monitorIndex}
  923.     print{"Waste: "..reactor.getWasteAmount().." mB", width-(string.len(reactor.getWasteAmount())+10), 11, monitorIndex}
  924.  
  925.     monitor.setTextColor(colors.blue)
  926.     printCentered(reactorNames[reactorIndex],12,monitorIndex)
  927.     monitor.setTextColor(colors.white)
  928. end -- function displayReactorBars(barParams)
  929.  
  930.  
  931. local function reactorStatus(statusParams)
  932.     -- Default to first reactor and first monitor
  933.     setmetatable(statusParams,{__index={reactorIndex=1, monitorIndex=1}})
  934.     local reactorIndex, monitorIndex =
  935.         statusParams[1] or statusParams.reactorIndex,
  936.         statusParams[2] or statusParams.monitorIndex
  937.  
  938.     -- Grab current monitor
  939.     local monitor = nil
  940.     monitor = monitorList[monitorIndex]
  941.     if not monitor then
  942.         printLog("monitorList["..monitorIndex.."] in reactorStatus() was not a valid monitor")
  943.         return -- Invalid monitorIndex
  944.     end
  945.  
  946.     -- Grab current reactor
  947.     local reactor = nil
  948.     reactor = reactorList[reactorIndex]
  949.     if not reactor then
  950.         printLog("reactorList["..reactorIndex.."] in reactorStatus() was not a valid Big Reactor")
  951.         return -- Invalid reactorIndex
  952.     end
  953.  
  954.     local width, height = monitor.getSize()
  955.     local reactorStatus = ""
  956.  
  957.     if reactor.getConnected() then
  958.         if reactor.getActive() then
  959.             reactorStatus = "ONLINE"
  960.             monitor.setTextColor(colors.green)
  961.         else
  962.             reactorStatus = "OFFLINE"
  963.             monitor.setTextColor(colors.red)
  964.         end -- if reactor.getActive() then
  965.  
  966.         if xClick >= (width - string.len(reactorStatus) - 1) and xClick <= (width-1) and (sideClick == monitorNames[monitorIndex]) then
  967.             if yClick == 1 then
  968.                 reactor.setActive(not reactor.getActive()) -- Toggle reactor status
  969.                 sideClick, xClick, yClick = 0, 0, 0 -- Reset click after we register it
  970.  
  971.                 -- If someone offlines the reactor (offline after a status click was detected), then disable autoStart
  972.                 if not reactor.getActive() then
  973.                     autoStart[reactorIndex] = false
  974.                 end
  975.             end -- if yClick == 1 then
  976.         end -- if (xClick >= (width - string.len(reactorStatus) - 1) and xClick <= (width-1)) and (sideClick == monitorNames[monitorIndex]) then
  977.  
  978.         -- Allow disabling rod level auto-adjust and only manual rod level control
  979.         if ((xClick > 23 and xClick < 28 and yClick == 4)
  980.                 or (xClick > 20 and xClick < 27 and yClick == 9))
  981.                 and (sideClick == monitorNames[monitorIndex]) then
  982.             reactorRodOverride = not reactorRodOverride -- Toggle reactor rod override status
  983.             sideClick, xClick, yClick = 0, 0, 0 -- Reset click after we register it
  984.         end -- if (xClick > 23) and (xClick < 28) and (yClick == 4) and (sideClick == monitorNames[monitorIndex]) then
  985.  
  986.     else
  987.         reactorStatus = "DISCONNECTED"
  988.         monitor.setTextColor(colors.red)
  989.     end -- if reactor.getConnected() then
  990.  
  991.     print{reactorStatus, width - string.len(reactorStatus) - 1, 1, monitorIndex}
  992.     monitor.setTextColor(colors.white)
  993. end -- function reactorStatus(statusParams)
  994.  
  995.  
  996. -- Display all found reactors' status to monitor 1
  997. -- This is only called if multiple reactors and/or a reactor plus at least one turbine are found
  998. local function displayAllStatus()
  999.     local reactor, turbine = nil, nil
  1000.     local onlineReactor, onlineTurbine = 0, 0
  1001.     local totalReactorRF, totalReactorSteam, totalTurbineRF = 0, 0, 0
  1002.     local totalReactorFuelConsumed = 0
  1003.     local totalCoolantStored, totalSteamStored, totalEnergy, totalMaxEnergyStored = 0, 0, 0, 0 -- Total turbine and reactor energy buffer and overall capacity
  1004.     local maxSteamStored = (2000*#turbineList)+(5000*#reactorList)
  1005.     local maxCoolantStored = (2000*#turbineList)+(5000*#reactorList)
  1006.  
  1007.     local monitor, monitorIndex = nil, 1
  1008.     monitor = monitorList[monitorIndex]
  1009.     if not monitor then
  1010.         printLog("monitorList["..monitorIndex.."] in reactorStatus() was not a valid monitor")
  1011.         return -- Invalid monitorIndex
  1012.     end
  1013.  
  1014.     for reactorIndex = 1, #reactorList do
  1015.         reactor = reactorList[reactorIndex]
  1016.         if not reactor then
  1017.             printLog("reactorList["..reactorIndex.."] in main() was not a valid Big Reactor")
  1018.             break -- Invalid reactorIndex
  1019.         end -- if not reactor then
  1020.  
  1021.         if reactor.getConnected() then
  1022.             if reactor.getActive() then
  1023.                 onlineReactor = onlineReactor + 1
  1024.                 totalReactorFuelConsumed = totalReactorFuelConsumed + reactor.getFuelConsumedLastTick()
  1025.             end -- reactor.getActive() then
  1026.  
  1027.             -- Actively cooled reactors do not produce or store energy
  1028.             if not reactor.isActivelyCooled() then
  1029.                 totalMaxEnergyStored = totalMaxEnergyStored + 10000000 -- Reactors store 10M RF
  1030.                 totalEnergy = totalEnergy + reactor.getEnergyStored()
  1031.                 totalReactorRF = totalReactorRF + reactor.getEnergyProducedLastTick()
  1032.             else
  1033.                 totalReactorSteam = totalReactorSteam + reactor.getEnergyProducedLastTick()
  1034.                 totalSteamStored = totalSteamStored + reactor.getHotFluidAmount()
  1035.                 totalCoolantStored = totalCoolantStored + reactor.getCoolantAmount()
  1036.             end -- if not reactor.isActivelyCooled() then
  1037.         end -- if reactor.getConnected() then
  1038.     end -- for reactorIndex = 1, #reactorList do
  1039.  
  1040.     for turbineIndex = 1, #turbineList do
  1041.         turbine = turbineList[turbineIndex]
  1042.         if not turbine then
  1043.             printLog("turbineList["..turbineIndex.."] in main() was not a valid Big Reactor")
  1044.             break -- Invalid turbineIndex
  1045.         end -- if not turbine then
  1046.  
  1047.         if turbine.getConnected() then
  1048.             if turbine.getActive() then
  1049.                 onlineTurbine = onlineTurbine + 1
  1050.             end
  1051.  
  1052.             totalMaxEnergyStored = totalMaxEnergyStored + 1000000 -- Turbines store 1M RF
  1053.             totalEnergy = totalEnergy + turbine.getEnergyStored()
  1054.             totalTurbineRF = totalTurbineRF + turbine.getEnergyProducedLastTick()
  1055.             totalSteamStored = totalSteamStored + turbine.getInputAmount()
  1056.             totalCoolantStored = totalCoolantStored + turbine.getOutputAmount()
  1057.         end -- if turbine.getConnected() then
  1058.     end -- for turbineIndex = 1, #turbineList do
  1059.  
  1060.     print{"Reactors online/found: "..onlineReactor.."/"..#reactorList, 2, 3, monitorIndex}
  1061.     print{"Turbines online/found: "..onlineTurbine.."/"..#turbineList, 2, 4, monitorIndex}
  1062.  
  1063.     if totalReactorRF ~= 0 then
  1064.         monitor.setTextColor(colors.blue)
  1065.         printRight("Reactor", 9, monitorIndex)
  1066.         monitor.setTextColor(colors.white)
  1067.         printRight(math.ceil(totalReactorRF).." (RF/t)", 10, monitorIndex)
  1068.     end
  1069.  
  1070.     if #turbineList then
  1071.         -- Display liquids
  1072.         monitor.setTextColor(colors.blue)
  1073.         printLeft("Steam (mB)", 6, monitorIndex)
  1074.         monitor.setTextColor(colors.white)
  1075.         printLeft(math.ceil(totalSteamStored).."/"..maxSteamStored, 7, monitorIndex)
  1076.         printLeft(math.ceil(totalReactorSteam).." mB/t", 8, monitorIndex)
  1077.         monitor.setTextColor(colors.blue)
  1078.         printRight("Coolant (mB)", 6, monitorIndex)
  1079.         monitor.setTextColor(colors.white)
  1080.         printRight(math.ceil(totalCoolantStored).."/"..maxCoolantStored, 7, monitorIndex)
  1081.  
  1082.         monitor.setTextColor(colors.blue)
  1083.         printLeft("Turbine", 9, monitorIndex)
  1084.         monitor.setTextColor(colors.white)
  1085.         printLeft(math.ceil(totalTurbineRF).." RF/t", 10, monitorIndex)
  1086.     end -- if #turbineList then
  1087.  
  1088.     printRight("Fuel: "..round(totalReactorFuelConsumed,3).." mB/t", 11, monitorIndex)
  1089.     print{"Buffer: "..math.ceil(totalEnergy,3).."/"..totalMaxEnergyStored.." RF", 2, 12, monitorIndex}
  1090. end -- function displayAllStatus()
  1091.  
  1092.  
  1093. -- Get turbine status
  1094. local function displayTurbineBars(turbineIndex, monitorIndex)
  1095.     -- Grab current monitor
  1096.     local monitor = nil
  1097.     monitor = monitorList[monitorIndex]
  1098.     if not monitor then
  1099.         printLog("monitorList["..monitorIndex.."] in displayTurbineBars() was not a valid monitor")
  1100.         return -- Invalid monitorIndex
  1101.     end
  1102.  
  1103.     -- Grab current turbine
  1104.     local turbine = nil
  1105.     turbine = turbineList[turbineIndex]
  1106.     if not turbine then
  1107.         printLog("turbineList["..turbineIndex.."] in displayTurbineBars() was not a valid Big Turbine")
  1108.         return -- Invalid turbineIndex
  1109.     end
  1110.  
  1111.     -- Draw border lines
  1112.     local width, height = monitor.getSize()
  1113.  
  1114.     for i=3, 5 do
  1115.         monitor.setCursorPos(21, i)
  1116.         monitor.write("|")
  1117.     end
  1118.  
  1119.     drawLine(2,monitorIndex)
  1120.     drawLine(6,monitorIndex)
  1121.  
  1122.     -- Allow controlling Turbine Flow Rate from GUI
  1123.     -- Decrease flow rate button: 22X, 4Y
  1124.     -- Increase flow rate button: 28X, 4Y
  1125.     local turbineFlowRate = math.ceil(turbine.getFluidFlowRateMax())
  1126.     if (xClick == 22) and (yClick == 4) and (sideClick == monitorNames[monitorIndex]) then
  1127.         --Decrease rod level by amount
  1128.         newTurbineFlowRate = turbineFlowRate - flowRateAdjustAmount
  1129.         if newTurbineFlowRate < 0 then
  1130.             newTurbineFlowRate = 0
  1131.         end
  1132.         sideClick, xClick, yClick = 0, 0, 0
  1133.  
  1134.         -- Check bounds [0,2000]
  1135.         if newTurbineFlowRate > 2000 then
  1136.             newTurbineFlowRate = 2000
  1137.         elseif newTurbineFlowRate < 0 then
  1138.             newTurbineFlowRate = 25 -- Don't go to zero, might as well power off
  1139.         end
  1140.  
  1141.         turbine.setFluidFlowRateMax(newTurbineFlowRate)
  1142.  
  1143.         -- Save updated Turbine Flow Rate
  1144.         turbineFlowRate = newTurbineFlowRate
  1145.     end -- if (xClick == 22) and (yClick == 4) and (sideClick == monitorNames[monitorIndex]) then
  1146.  
  1147.     if (xClick == 29) and (yClick == 4) and (sideClick == monitorNames[monitorIndex]) then
  1148.         --Increase rod level by amount
  1149.         newTurbineFlowRate = turbineFlowRate + flowRateAdjustAmount
  1150.         if newTurbineFlowRate > 2000 then
  1151.             newTurbineFlowRate = 2000
  1152.         end
  1153.         sideClick, xClick, yClick = 0, 0, 0
  1154.  
  1155.         -- Check bounds [0,2000]
  1156.         if newTurbineFlowRate > 2000 then
  1157.             newTurbineFlowRate = 2000
  1158.         elseif newTurbineFlowRate < 0 then
  1159.             newTurbineFlowRate = 25 -- Don't go to zero, might as well power off
  1160.         end
  1161.  
  1162.         turbine.setFluidFlowRateMax(newTurbineFlowRate)
  1163.  
  1164.         -- Save updated Turbine Flow Rate
  1165.         turbineFlowRate = newTurbineFlowRate
  1166.     end -- if (xClick == 29) and (yClick == 4) and (sideClick == monitorNames[monitorIndex]) then
  1167.  
  1168.     print{"  Flow",22,3,monitorIndex}
  1169.     print{"<      >",22,4,monitorIndex}
  1170.     print{turbineFlowRate,23,4,monitorIndex}
  1171.     print{"  mB/t",22,5,monitorIndex}
  1172.  
  1173.     local rotorSpeedString = "Speed: "
  1174.     local energyBufferString = "Producing: "
  1175.  
  1176.     local padding = math.max(string.len(rotorSpeedString), string.len(energyBufferString))
  1177.  
  1178.     local energyBuffer = turbine.getEnergyProducedLastTick()
  1179.     print{energyBufferString,1,4,monitorIndex}
  1180.     print{math.ceil(energyBuffer).." RF/t",padding+1,4,monitorIndex}
  1181.  
  1182.     local rotorSpeed = math.ceil(turbine.getRotorSpeed())
  1183.     print{rotorSpeedString,1,5,monitorIndex}
  1184.     print{rotorSpeed.." RPM",padding+1,5,monitorIndex}
  1185.  
  1186.     -- PaintUtils only outputs to term., not monitor.
  1187.     -- See http://www.computercraft.info/forums2/index.php?/topic/15540-paintutils-on-a-monitor/
  1188.  
  1189.     -- Draw stored energy buffer bar
  1190.     drawBar(1,8,28,8,colors.gray,monitorIndex)
  1191.     --paintutils.drawLine(2, 8, 28, 8, colors.gray)
  1192.  
  1193.     local curStoredEnergyPercent = getTurbineStoredEnergyBufferPercent(turbine)
  1194.     if curStoredEnergyPercent > 4 then
  1195.         drawBar(1, 8, math.floor(26*curStoredEnergyPercent/100)+2, 8, colors.yellow,monitorIndex)
  1196.     elseif curStoredEnergyPercent > 0 then
  1197.         drawPixel(1, 8, colors.yellow, monitorIndex)
  1198.     end -- if curStoredEnergyPercent > 4 then
  1199.  
  1200.     print{"Energy Buffer",1,7,monitorIndex}
  1201.     print{curStoredEnergyPercent, width-(string.len(curStoredEnergyPercent)+3),7,monitorIndex}
  1202.     print{"%",28,7,monitorIndex}
  1203.  
  1204.     -- Print rod override status
  1205.     local turbineFlowRateOverrideStatus = ""
  1206.  
  1207.     print{"Flow Auto-adjust:",2,10,monitorIndex}
  1208.  
  1209.     if not turbineFlowRateOverride[turbineIndex] then
  1210.         turbineFlowRateOverrideStatus = "Enabled"
  1211.         monitor.setTextColor(colors.green)
  1212.     else
  1213.         turbineFlowRateOverrideStatus = "Disabled"
  1214.         monitor.setTextColor(colors.red)
  1215.     end -- if not reactorRodOverride then
  1216.  
  1217.     print{turbineFlowRateOverrideStatus, width - string.len(turbineFlowRateOverrideStatus) - 1, 10, monitorIndex}
  1218.     monitor.setTextColor(colors.white)
  1219.  
  1220.     monitor.setTextColor(colors.blue)
  1221.     printCentered(turbineNames[turbineIndex],12,monitorIndex)
  1222.     monitor.setTextColor(colors.white)
  1223.  
  1224.     -- Need equation to figure out rotor efficiency and display
  1225. end -- function displayTurbineBars(statusParams)
  1226.  
  1227.  
  1228. -- Display turbine status
  1229. local function turbineStatus(turbineIndex, monitorIndex)
  1230.     -- Grab current monitor
  1231.     local monitor = nil
  1232.     monitor = monitorList[monitorIndex]
  1233.     if not monitor then
  1234.         printLog("monitorList["..monitorIndex.."] in turbineStatus() was not a valid monitor")
  1235.         return -- Invalid monitorIndex
  1236.     end
  1237.  
  1238.     -- Grab current turbine
  1239.     local turbine = nil
  1240.     turbine = turbineList[turbineIndex]
  1241.     if not turbine then
  1242.         printLog("turbineList["..turbineIndex.."] in turbineStatus() was not a valid Big Turbine")
  1243.         return -- Invalid turbineIndex
  1244.     end
  1245.  
  1246.     local width, height = monitor.getSize()
  1247.     local turbineStatus = ""
  1248.  
  1249.     if turbine.getConnected() then
  1250.         if turbine.getActive() then
  1251.             turbineStatus = "ONLINE"
  1252.             monitor.setTextColor(colors.green)
  1253.         else
  1254.             turbineStatus = "OFFLINE"
  1255.             monitor.setTextColor(colors.red)
  1256.         end -- if turbine.getActive() then
  1257.  
  1258.         if (xClick >= (width - string.len(turbineStatus) - 1)) and (xClick <= (width-1)) and (sideClick == monitorNames[monitorIndex]) then
  1259.             if yClick == 1 then
  1260.                 turbine.setActive(not turbine.getActive()) -- Toggle turbine status
  1261.                 sideClick, xClick, yClick = 0, 0, 0 -- Reset click after we register it
  1262.             end -- if yClick == 1 then
  1263.         end -- if (xClick >= (width - string.len(turbineStatus) - 1)) and (xClick <= (width-1)) and (sideClick == monitorNames[monitorIndex]) then
  1264.  
  1265.         -- Allow disabling/enabling flow rate auto-adjust
  1266.         if ((xClick > 23 and xClick < 28 and yClick == 4)
  1267.                 or (xClick > 20 and xClick < 27 and yClick == 10))
  1268.                 and (sideClick == monitorNames[monitorIndex]) then
  1269.             turbineFlowRateOverride[turbineIndex] = not turbineFlowRateOverride[turbineIndex] -- Toggle turbine rod override status
  1270.             sideClick, xClick, yClick = 0, 0, 0 -- Reset click after we register it
  1271.         end
  1272.  
  1273.     else
  1274.         turbineStatus = "DISCONNECTED"
  1275.         monitor.setTextColor(colors.red)
  1276.     end -- if turbine.getConnected() then
  1277.  
  1278.     print{turbineStatus, width - string.len(turbineStatus) - 1, 1, monitorIndex}
  1279.     monitor.setTextColor(colors.white)
  1280. end -- function function turbineStatus(turbineIndex, monitorIndex)
  1281.  
  1282.  
  1283. -- Maintain Turbine flow rate at 900 or 1,800 RPM
  1284. local function flowRateControl(turbineIndex)
  1285.     -- Grab current turbine
  1286.     local turbine = nil
  1287.     turbine = turbineList[turbineIndex]
  1288.     if not turbine then
  1289.         printLog("turbineList["..turbineIndex.."] in flowRateControl() was not a valid Big Turbine")
  1290.         return -- Invalid turbineIndex
  1291.     end
  1292.  
  1293.     -- No point modifying control rod levels for temperature if the turbine is offline
  1294.     if turbine.getActive() then
  1295.         local flowRate = turbine.getFluidFlowRate()
  1296.         local flowRateUserMax = math.ceil(turbine.getFluidFlowRateMax())
  1297.         local rotorSpeed = math.ceil(turbine.getRotorSpeed())
  1298.         local newFlowRate = 0
  1299.  
  1300.         -- If we're not at max flow-rate and an optimal RPM, let's do something
  1301.         -- also don't do anything if the current flow rate hasn't caught up to the user defined flow rate maximum
  1302.         if (((rotorSpeed % 900) ~= 0) and (flowRate ~= 2000) and (flowRate == flowRateUserMax))
  1303.             or (flowRate == 0) then
  1304.             -- Make sure we are not going too fast
  1305.             if rotorSpeed > 2700 then
  1306.                 newFlowRate = flowRateUserMax - flowRateAdjustAmount
  1307.             -- Make sure we're not going too slow
  1308.             elseif rotorSpeed < 900 then
  1309.                 newFlowRate = flowRateUserMax + flowRateAdjustAmount
  1310.             -- We're not at optimal RPM or flow-rate and we're not out-of-bounds
  1311.             else
  1312.                 return
  1313.             end
  1314.  
  1315.             -- Check bounds [0,2000]
  1316.             if newFlowRate > 2000 then
  1317.                 newFlowRate = 2000
  1318.             elseif newFlowRate < 0 then
  1319.                 newFlowRate = 25 -- Don't go to zero, might as well power off
  1320.             end
  1321.  
  1322.             turbine.setFluidFlowRateMax(newFlowRate)
  1323.         end -- if ((rotorSpeed % 900) ~= 0) and (flowRate ~= 2000) and (flowRate == flowRateUserMax) then
  1324.     end -- if turbine.getActive() then
  1325. end -- function flowRateControl(turbineIndex)
  1326.  
  1327.  
  1328. function main()
  1329.     -- Load reactor parameters and initialize systems
  1330.     loadReactorOptions()
  1331.  
  1332.     -- Get our initial list of connected monitors and reactors
  1333.     -- and initialize every cycle in case the connected devices change
  1334.     findMonitors()
  1335.     findReactors()
  1336.     findTurbines()
  1337.  
  1338.     while not finished do
  1339.         local reactor = nil
  1340.         local monitorIndex = 1
  1341.  
  1342.         -- For multiple reactors/monitors, monitor #1 is reserved for overall status
  1343.         -- or for multiple reactors/turbines and only one monitor
  1344.         if (((#reactorList + #turbineList) > 1) and (#monitorList > 1)) or
  1345.             (((#reactorList + #turbineList) > 1) and (#monitorList == 1)) then
  1346.                 local monitor = nil
  1347.                 monitor = monitorList[monitorIndex]
  1348.                 if not monitor then
  1349.                     printLog("monitorList["..monitorIndex.."] in turbineStatus() was not a valid monitor")
  1350.                     return -- Invalid monitorIndex
  1351.                 end
  1352.  
  1353.             clearMonitor(progName.." "..progVer, monitorIndex) -- Clear monitor and draw borders
  1354.             printCentered(progName.." "..progVer, 1, monitorIndex)
  1355.             displayAllStatus()
  1356.             monitorIndex = 2
  1357.         end
  1358.  
  1359.         -- Iterate through reactors
  1360.         for reactorIndex = 1, #reactorList do
  1361.             local monitor = nil
  1362.             monitor = monitorList[monitorIndex]
  1363.             if not monitor then
  1364.                 printLog("monitorList["..monitorIndex.."] in turbineStatus() was not a valid monitor")
  1365.                 return -- Invalid monitorIndex
  1366.             end
  1367.  
  1368.             local reactorMonitorIndex = monitorIndex + reactorIndex - 1 -- reactorIndex starts at 1
  1369.  
  1370.             clearMonitor(progName, reactorMonitorIndex) -- Clear monitor and draw borders
  1371.             printCentered(progName, 1, reactorMonitorIndex)
  1372.  
  1373.             -- Display reactor status, includes "Disconnected" but found reactors
  1374.             reactorStatus{reactorIndex, reactorMonitorIndex}
  1375.  
  1376.             reactor = reactorList[reactorIndex]
  1377.             if not reactor then
  1378.                 printLog("reactorList["..reactorIndex.."] in main() was not a valid Big Reactor")
  1379.                 break -- Invalid reactorIndex
  1380.             end
  1381.  
  1382.             if reactor.getConnected() then
  1383.                 local curStoredEnergyPercent = getReactorStoredEnergyBufferPercent(reactor)
  1384.  
  1385.                 -- Shutdown reactor if current stored energy % is >= desired level, otherwise activate
  1386.                 -- First pass will have curStoredEnergyPercent=0 until displayBars() is run once
  1387.                 if curStoredEnergyPercent >= maxStoredEnergyPercent then
  1388.                     reactor.setActive(false)
  1389.                 -- Do not auto-start the reactor if it was manually powered off (autoStart=false)
  1390.                 elseif (curStoredEnergyPercent <= minStoredEnergyPercent) and (autoStart[reactorIndex] == true) then
  1391.                     reactor.setActive(true)
  1392.                 end
  1393.  
  1394.                 -- Don't try to auto-adjust control rods if manual control is requested
  1395.                 if not reactorRodOverride then
  1396.                     temperatureControl(reactorIndex)
  1397.                 end
  1398.  
  1399.                 displayReactorBars{reactorIndex,reactorMonitorIndex}
  1400.             end -- if reactor.getConnected() then
  1401.         end -- for reactorIndex = 1, #reactorList do
  1402.  
  1403.         -- Monitors for turbines start after turbineMonitorOffset
  1404.         for turbineIndex = 1, #turbineList do
  1405.             local monitor = nil
  1406.             monitor = monitorList[monitorIndex]
  1407.             if not monitor then
  1408.                 printLog("monitorList["..monitorIndex.."] in turbineStatus() was not a valid monitor")
  1409.                 return -- Invalid monitorIndex
  1410.             end
  1411.  
  1412.             local turbineMonitorIndex = turbineIndex+turbineMonitorOffset
  1413.             clearMonitor(progName, turbineMonitorIndex) -- Clear monitor and draw borders
  1414.             printCentered(progName, 1, turbineMonitorIndex)
  1415.  
  1416.             -- Display turbine status, includes "Disconnected" but found turbines
  1417.             turbineStatus(turbineIndex, turbineMonitorIndex)
  1418.  
  1419.             turbine = turbineList[turbineIndex]
  1420.             if not turbine then
  1421.                 printLog("turbineList["..turbineIndex.."] in main() was not a valid Big Turbine")
  1422.                 break -- Invalid turbineIndex
  1423.             end
  1424.  
  1425.             if turbine.getConnected() then
  1426.                 if not turbineFlowRateOverride[turbineIndex] then
  1427.                     flowRateControl(turbineIndex)
  1428.                 end
  1429.  
  1430.                 displayTurbineBars(turbineIndex,turbineMonitorIndex)
  1431.             end
  1432.         end -- for reactorIndex = 1, #reactorList do
  1433.  
  1434.         sleep(loopTime) -- Sleep
  1435.         saveReactorOptions()
  1436.     end -- while not finished do
  1437. end -- main()
  1438.  
  1439.  
  1440. local function eventHandler()
  1441.     while not finished do
  1442.         -- http://computercraft.info/wiki/Os.pullEvent
  1443.         -- http://www.computercraft.info/forums2/index.php?/topic/1516-ospullevent-what-is-it-and-how-is-it-useful/
  1444.         event, arg1, arg2, arg3 = os.pullEvent()
  1445.  
  1446.         if event == "monitor_touch" then
  1447.             sideClick, xClick, yClick = arg1, math.floor(arg2), math.floor(arg3)
  1448.             printLog("Side: "..arg1.." Monitor touch X: "..xClick.." Y: "..yClick)
  1449.         elseif event == "char" and not inManualMode then
  1450.             local ch = string.lower(arg1)
  1451.             if ch == "q" then
  1452.                 finished = true
  1453.             elseif ch == "r" then
  1454.                 finished = true
  1455.                 os.reboot()
  1456.             end -- if ch == "q" then
  1457.         end -- if event == "monitor_touch" then
  1458.     end -- while not finished do
  1459. end -- function eventHandler()
  1460.  
  1461.  
  1462. while not finished do
  1463.     parallel.waitForAny(eventHandler, main)
  1464.     sleep(loopTime)
  1465. end -- while not finished do
  1466.  
  1467.  
  1468. -- Clear up after an exit
  1469. term.clear()
  1470. term.setCursorPos(1,1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement