-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbatmon.lua
84 lines (77 loc) · 2.03 KB
/
batmon.lua
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
--5
local socket = nil
local Table = nil
local conf = {}
local total = 0
local function map(tbl, f)
local t = {}
for k,v in pairs(tbl) do
t[k] = f(v)
end
return t
end
local function sum(tbl)
Table.reduce(tbl, function (a, b) return a + b end)
end
function init()
if not fs.exists('lib/table.lua') then
shell.run('installer', 'lib/table.lua')
end
Table = require('lib/table')
if fs.exists('var/batmon.conf') then
local file = fs.open('var/batmon.conf', 'r')
conf = textutils.unserialise(file.readAll())
file.close()
else
conf = {
hidden = false,
group = nil
}
local file = fs.open('var/batmon.conf', 'w')
file.write(textutils.serialise(conf))
file.close()
end
if fs.exists('websocket.lua') then
socket = require('websocket')
end
end
function start()
if socket then
socket.group(conf.group or nil)
socket.hidden(conf.hidden or false)
socket.connect('batmon', true)
end
end
function monitor()
while true do
local bats = { peripheral.find('thermalexpansion:storage_cell') }
local stored = sum(Table.map(bats, function(b) return b.getRFStored() end)) / 1000
local total = sum(Table.map(bats, function(b) return b.getRFCapacity() end)) / 1000
if socket then
socket.info({
{
key = 'stored',
value = stored,
type = 'number'
},
{
key = 'total',
value = total,
type = 'number'
},
{
key = 'percent',
value = total > 0 and (stored * 100 / total) or 0,
type = 'number'
}
})
end
sleep(1)
end
end
init()
local loops = {
start, monitor
}
if socket then table.insert(loops, socket.runtime) end
parallel.waitForAll(unpack(loops))