Advertisement
NolanSyKinsley

Untitled

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