-
Notifications
You must be signed in to change notification settings - Fork 0
/
reactor_api
111 lines (80 loc) · 2.45 KB
/
reactor_api
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
Reactor = {}
Reactor.__index = Reactor
function Reactor:new(periph_name)
local self = setmetatable({}, Reactor)
self.periph_name = periph_name
self.periph = peripheral.wrap(periph_name)
if self.periph == nil or not self.periph.getConnected() then
error("Unable to connect to peripheral: " .. tostring(self.periph_name))
end
self.moving_window = 30
self.last_fuel = {}
self.energy_produced = {}
for i = 1, self.moving_window do
self.last_fuel[i] = self.periph.getFuelAmount()
self.energy_produced[i] = 0
end
return self
end
function Reactor:get_stored_amount()
local stored = self.periph.getEnergyStored()
return stored
end
function Reactor:get_stored_percentage()
local stored = self.periph.getEnergyStored()
local max_stored = 1e7
local stored_percentage = (100.0 * stored) / max_stored
return stored_percentage
end
function Reactor:adjust_control_level()
local optimal = 51
local stored_percentage = self:get_stored_percentage()
if stored_percentage > optimal then
self.control_level = math.min(math.floor(stored_percentage + 1), 100)
else
self.control_level = optimal
end
self.periph.setAllControlRodLevels(self.control_level)
end
function Reactor:get_control_level()
return self.control_level
end
function Reactor:get_fuel_level()
return self.last_fuel[#self.last_fuel]
end
function Reactor:get_fuel_percentage()
local max_fuel = self.periph.getFuelAmountMax()
local stored_fuel = self:get_fuel_level()
return (100.0 * stored_fuel) / max_fuel
end
function Reactor:is_active()
return self.periph.getActive()
end
function Reactor:toggle_active_state()
local active = self:is_active()
self:set_active(not active)
return not active
end
function Reactor:get_efficiency()
-- total energy produced over recorded period
local total_power = sum(self.energy_produced)
-- total fuel used over recorded period
local total_fuel_use = self.last_fuel[1] - self.last_fuel[#self.last_fuel]
return total_power / total_fuel_use
end
function Reactor:update_state()
table.remove(self.last_fuel, 1)
table.insert(self.last_fuel, self.periph.getFuelAmount())
table.remove(self.energy_produced, 1)
table.insert(self.energy_produced, self.periph.getEnergyProducedLastTick())
end
function Reactor:set_active(state)
self.periph.setActive(state)
end
function sum(tbl)
local total = 0.0
for i = 1, #tbl do
total = total + tbl[i]
end
return total
end