-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathreactor.lua
More file actions
514 lines (398 loc) · 14.9 KB
/
reactor.lua
File metadata and controls
514 lines (398 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
os.loadAPI("lib/f")
os.loadAPI("lib/button")
local targetStrength = 50
local maxTemp = 7750
local safeTemp = 3000
local lowFieldPer = 15
local activateOnCharge = true
local version = 0.3
local autoInputGate = 1
local curInputGate = 222000
local mon, monitor, monX, monY
local reactor
local fluxgate
local inputFluxgate
local ri
local action = "None since reboot"
local actioncolor = colors.gray
local emergencyCharge = false
local emergencyTemp = false
monitor = f.periphSearch("monitor")
-- inputFluxgate = f.periphSearch("flow_gate")
-- fluxgate = f.getPeripheral("flow_gate")
reactor = f.periphSearch("draconic_reactor")
function detectFlowGates()
local gates = {peripheral.find("flow_gate")}
if #gates < 2 then
error("Error: Less than 2 flow gates detected!")
return nil, nil
end
print("Please set input flow gate to **10 RF/t** manually.")
local inputGate, outputGate, inputName, outputName
while not inputGate do
sleep(1) -- Wait before checking again
for _, name in pairs(peripheral.getNames()) do
if peripheral.getType(name) == "flow_gate" then
local gate = peripheral.wrap(name)
local setFlow = gate.getSignalLowFlow()
if setFlow == 10 then
inputGate, inputName = gate, name
print("Detected input gate:", name)
else
outputGate, outputName = gate, name
end
end
end
end
if not outputGate then
print("Error: Could not identify output gate!")
return nil, nil
end
return inputGate, outputGate, inputName, outputName
end
function saveFlowGateNames(inputName, outputName)
local file = fs.open("flowgate_names.txt", "w")
file.writeLine(inputName)
file.writeLine(outputName)
file.close()
print("Saved flow gate names for reboot!")
end
function loadFlowGateNames()
if not fs.exists("flowgate_names.txt") then
print("No saved flow gate names found! Running detection again...")
return nil, nil, nil, nil
end
local file = fs.open("flowgate_names.txt", "r")
local inputName = file.readLine()
local outputName = file.readLine()
file.close()
print("Loaded saved flow gate names:", inputName, outputName)
if peripheral.isPresent(inputName) and peripheral.isPresent(outputName) then
return peripheral.wrap(inputName), peripheral.wrap(outputName), inputName, outputName
else
print("Saved peripherals not found! Running detection again...")
return nil, nil, nil, nil
end
end
function setupFlowGates()
-- Try to load saved names
local inputFluxgate, outputFluxgate, inputName, outputName = loadFlowGateNames()
-- If names don't exist, detect manually
if not inputFluxgate or not outputFluxgate then
inputFluxgate, outputFluxgate, inputName, outputName = detectFlowGates()
if inputFluxgate and outputFluxgate then
saveFlowGateNames(inputName, outputName)
else
error("Flow gate setup failed! Make sure to set the input flow gate to 10 before running the script again!")
return nil, nil
end
end
return inputFluxgate, outputFluxgate
end
inputFluxgate, fluxgate = setupFlowGates()
if monitor == nil then
error("No valid monitor was found")
end
if fluxgate == nil then
error("No valid flow gate was found")
end
if inputFluxgate == nil then
error("No input flow gate was found. Please put the low signal value to 10")
end
if reactor == nil then
error("No reactor was found")
end
monX, monY = monitor.getSize()
mon = {}
mon.monitor, mon.X, mon.Y = monitor, monX, monY
f.firstSet(mon)
function mon.clear()
mon.monitor.setBackgroundColor(colors.black)
mon.monitor.clear()
mon.monitor.setCursorPos(1,1)
button.screen()
end
function save_config()
sw = fs.open("reactorconfig.txt", "w")
sw.writeLine(autoInputGate)
sw.writeLine(curInputGate)
sw.close()
end
function load_config()
sr = fs.open("reactorconfig.txt", "r")
autoInputGate = tonumber(sr.readLine())
curInputGate = tonumber(sr.readLine())
sr.close()
end
if fs.exists("reactorconfig.txt") == false then
save_config()
else
load_config()
end
function reset()
term.clear()
term.setCursorPos(1,1)
end
function reactorStatus(r)
local statusTable = {
running = {"Online", colors.green},
cold = {"Offline", colors.gray},
warming_up = {"Charging", colors.orange},
cooling = {"Cooling Down", colors.blue},
stopping = {"Shutting Down", colors.red} -- Default case
}
-- Return status or default to "Shutting Down"
return statusTable[r] or statusTable["stopping"]
end
local lastTerminalValues = {}
function drawTerminalText(x, y, label, newValue)
local key = label -- Use label as key to track changes
-- Only update if the value changed
if lastTerminalValues[key] ~= newValue then
term.setCursorPos(x, y)
term.clearLine() -- Clear only the current line
term.write(label .. ": " .. newValue)
lastTerminalValues[key] = newValue -- Store new value
end
end
function reactorControl()
reset() -- Clear the terminal once at startup
while true do
local ri = reactor.getReactorInfo()
if not ri then
print("Reactor not setup correctly. Retrying in 2s...")
sleep(2)
goto continue
end
-- Update terminal output
local i = 1
for k, v in pairs(ri) do
drawTerminalText(1, i, k, tostring(v))
i = i + 1
end
i = i + 1
drawTerminalText(1, i, "Output Gate", fluxgate.getSignalLowFlow())
i = i + 1
drawTerminalText(1, i, "Input Gate", inputFluxgate.getSignalLowFlow())
-- Reactor Control Logic
if emergencyCharge then
reactor.chargeReactor()
end
if ri.status == "warming_up" then
inputFluxgate.setSignalLowFlow(900000)
emergencyCharge = false
elseif ri.status == "stopping" and ri.temperature < safeTemp and emergencyTemp then
reactor.activateReactor()
emergencyTemp = false
elseif ri.status == "warming_up" and activateOnCharge then
reactor.activateReactor()
end
-- Auto-adjust power flow
if ri.status == "running" then
local fluxval = autoInputGate == 1
and ri.fieldDrainRate / (1 - (targetStrength / 100))
or curInputGate
i = i + 1
drawTerminalText(1, i, "Target Gate", fluxval)
inputFluxgate.setSignalLowFlow(fluxval)
end
-- Emergency Safeguards
checkReactorSafety(ri)
sleep(0.2) -- Keeps CPU usage low while maintaining constant monitoring
::continue::
end
end
function checkReactorSafety(ri)
local fuelPercent = 100 - math.ceil(ri.fuelConversion / ri.maxFuelConversion * 10000) * 0.01
local fieldPercent = math.ceil(ri.fieldStrength / ri.maxFieldStrength * 10000) * 0.01
if fuelPercent <= 10 then
emergencyShutdown("Fuel Low! Refuel Now!")
elseif fieldPercent <= lowFieldPer and ri.status == "running" then
emergencyShutdown("Field Strength Below "..lowFieldPer.."%!")
reactor.chargeReactor()
emergencyCharge = true
elseif ri.temperature > maxTemp then
emergencyShutdown("Reactor Overheated!")
emergencyTemp = true
end
end
function emergencyShutdown(message)
reactor.stopReactor()
actioncolor = colors.red
action = message
ActionMenu()
end
local MenuText = "Loading..."
function clearMenuArea()
-- Ensure we clear enough space for buttons
for i = 26, monY-1 do
f.draw_line(mon, 2, i, monX-2, colors.black)
end
button.clearTable() -- Clear stored button references
f.draw_line(mon, 2, 26, monX-2, colors.gray) -- Redraw top of the menu box
f.draw_line(mon, 2, monY-1, monX-2, colors.gray) -- Redraw bottom border
f.draw_line_y(mon, 2, 26, monY-1, colors.gray) -- Left border
f.draw_line_y(mon, monX-1, 26, monY-1, colors.gray) -- Right border
f.draw_text(mon, 4, 26, " "..MenuText.." ", colors.white, colors.black)
end
function toggleReactor()
ri = reactor.getReactorInfo()
if ri.status == "running" then
reactor.stopReactor()
elseif ri.status == "stopping" then
reactor.activateReactor()
else
reactor.chargeReactor()
end
end
function ActionMenu()
currentMenu = "action"
MenuText = "ATTENTION"
clearMenuArea()
button.setButton("action", action, buttonMain, 5, 28, monX-4, 30, 0, 0, colors.red)
button.screen()
end
function rebootSystem()
os.reboot()
end
function buttonControls()
if currentMenu == "controls" then return end
currentMenu = "controls"
MenuText = "CONTROLS"
clearMenuArea() -- Clear old buttons
local sLength = 6+(string.len("Toggle Reactor")+1)
button.setButton("toggle", "Toggle Reactor", toggleReactor, 6, 28, sLength, 30, 0, 0, colors.blue)
local sLength2 = (sLength+12+(string.len("Reboot"))+1)
button.setButton("reboot", "Reboot", rebootSystem, sLength+12, 28, sLength2, 30, 0, 0, colors.blue)
local sLength3 = 4+(string.len("Back")+1)
button.setButton("back", "Back", buttonMain, 4, 32, sLength3, 34, 0, 0, colors.blue)
button.screen()
end
function changeOutputValue(num, val)
local cFlow = fluxgate.getSignalLowFlow()
if val == 1 then
cFlow = cFlow+num
else
cFlow = cFlow-num
end
fluxgate.setSignalLowFlow(cFlow)
updateReactorInfo()
end
function outputMenu()
if currentMenu == "output" then return end
currentMenu = "output"
MenuText = "OUTPUT"
clearMenuArea() -- Clear old buttons
-- Define button data (Label, Value, Change Type)
local buttonData = {
{label = ">>>>", value = 1000000, changeType = 1}, -- +1,000,000
{label = ">>>", value = 100000, changeType = 1}, -- +100,000
{label = ">>", value = 10000, changeType = 1}, -- +10,000
{label = ">", value = 1000, changeType = 1}, -- +1,000
{label = "<", value = 1000, changeType = 0}, -- -1,000
{label = "<<", value = 10000, changeType = 0}, -- -10,000
{label = "<<<", value = 100000, changeType = 0}, -- -100,000
{label = "<<<<", value = 1000000, changeType = 0}, -- -1,000,000
}
-- Determine the starting X position dynamically
local spacing = 2
local buttonY = 28 -- Button row position
-- Add buttons dynamically
local currentX = monX - 7
for _, data in ipairs(buttonData) do
local buttonLength = string.len(data.label) + 1
local startX = currentX - buttonLength
local endX = startX + buttonLength
button.setButton(data.label, data.label, changeOutputValue, startX, buttonY, endX, buttonY + 2, data.value, data.changeType, colors.blue)
currentX = currentX - buttonLength - spacing -- Move left for the next button
end
-- Add "Back" button at the bottom
local backLength = 4 + string.len("Back") + 1
button.setButton("back", "Back", buttonMain, 4, 32, backLength, 34, 0, 0, colors.blue)
-- Refresh screen
button.screen()
end
function buttonMain()
if currentMenu == "main" then return end
currentMenu = "main"
MenuText = "MAIN MENU"
clearMenuArea() -- Clear old buttons
local sLength = 4+(string.len("Controls")+1)
button.setButton("controls", "Controls", buttonControls, 4, 28, sLength, 30, 0, 0, colors.blue)
local sLength2 = (sLength+13+(string.len("Output"))+1)
button.setButton("output", "Output", outputMenu, sLength+13, 28, sLength2, 30, 0, 0, colors.blue)
button.screen()
end
local lastValues = {}
function reactorInfoScreen()
mon.clear()
f.draw_text(mon, 2, 38, "Made by: StormFusions v"..version, colors.gray, colors.black)
-- Draw Static UI Elements (Frames, Labels)
f.draw_line(mon, 2, 22, monX-2, colors.gray)
f.draw_line(mon, 2, 2, monX-2, colors.gray)
f.draw_line_y(mon, 2, 2, 22, colors.gray)
f.draw_line_y(mon, monX-1, 2, 22, colors.gray)
f.draw_text(mon, 4, 2, " INFO ", colors.white, colors.black)
f.draw_line(mon, 2, 26, monX-2, colors.gray)
f.draw_line(mon, 2, monY-1, monX-2, colors.gray)
f.draw_line_y(mon, 2, 26, monY-1, colors.gray)
f.draw_line_y(mon, monX-1, 26, monY-1, colors.gray)
f.draw_text(mon, 4, 26, " "..MenuText.." ", colors.white, colors.black)
-- Loop to continuously update screen
while true do
updateReactorInfo()
sleep(1)
end
end
function updateReactorInfo()
ri = reactor.getReactorInfo()
if not ri then return end
-- Update only when values change
drawUpdatedText(4, 4, "Status:", reactorStatus(ri.status)[1], reactorStatus(ri.status)[2])
drawUpdatedText(4, 5, "Generation:", f.format_int(ri.generationRate).." rf/t", colors.lime)
local tempColor = getTempColor(ri.temperature)
drawUpdatedText(4, 7, "Temperature:", f.format_int(ri.temperature).."C", tempColor)
drawUpdatedText(4, 9, "Output Gate:", f.format_int(fluxgate.getSignalLowFlow()).." rf/t", colors.lightBlue)
drawUpdatedText(4, 10, "Input Gate:", f.format_int(inputFluxgate.getSignalLowFlow()).." rf/t", colors.lightBlue)
local satPercent = getPercentage(ri.energySaturation, ri.maxEnergySaturation)
drawUpdatedText(4, 12, "Energy Saturation:", satPercent.."%", colors.green)
f.progress_bar(mon, 4, 13, monX-7, satPercent, 100, colors.green, colors.lightGray)
local fieldPercent = getPercentage(ri.fieldStrength, ri.maxFieldStrength)
local fieldColor = getFieldColor(fieldPercent)
drawUpdatedText(4, 15, "Field Strength:", fieldPercent.."%", fieldColor)
f.progress_bar(mon, 4, 16, monX-7, fieldPercent, 100, fieldColor, colors.lightGray)
local fuelPercent = 100 - getPercentage(ri.fuelConversion, ri.maxFuelConversion)
local fuelColor = getFuelColor(fuelPercent)
drawUpdatedText(4, 18, "Fuel:", fuelPercent.."%", fuelColor)
f.progress_bar(mon, 4, 19, monX-7, fuelPercent, 100, fuelColor, colors.lightGray)
end
function drawUpdatedText(x, y, label, value, color)
local key = label
if lastValues[key] ~= value then
f.draw_text_lr(mon, x, y, 3, " ", " ", colors.white, color, colors.black)
f.draw_text_lr(mon, x, y, 3, label, value, colors.white, color, colors.black)
lastValues[key] = value
end
end
function getTempColor(temp)
if temp <= 5000 then return colors.green end
if temp <= 6500 then return colors.orange end
return colors.red
end
function getFieldColor(percent)
if percent >= 50 then return colors.blue end
if percent > 30 then return colors.orange end
return colors.red
end
function getFuelColor(percent)
if percent >= 70 then return colors.green end
if percent > 30 then return colors.orange end
return colors.red
end
function getPercentage(value, maxValue)
return math.ceil(value / maxValue * 10000) * 0.01
end
mon.clear()
mon.monitor.setTextScale(0.5)
buttonMain() -- Initialize buttons before the event listener
parallel.waitForAny(reactorInfoScreen, reactorControl, button.clickEvent)