-
Notifications
You must be signed in to change notification settings - Fork 4
/
blip.lua
executable file
·311 lines (268 loc) · 8.88 KB
/
blip.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
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
#!/usr/bin/env lem
--
-- This file is part of blipserver.
-- Copyright 2011,2016 Emil Renner Berthing
-- Copyright 2016 Kristian Nielsen <[email protected]>
--
-- blipserver is free software: you can redistribute it and/or
-- modify it under the terms of the GNU General Public License as
-- published by the Free Software Foundation, either version 3 of
-- the License, or (at your option) any later version.
--
-- blipserver is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with blipserver. If not, see <http://www.gnu.org/licenses/>.
--
local utils = require 'lem.utils'
local queue = require 'lem.queue'
local io = require 'lem.io'
local httpserv = require 'lem.http.server'
local hathaway = require 'lem.hathaway'
local assert = assert
local format = string.format
local tonumber = tonumber
local whichdb = 'postgres'
--local whichdb = 'mariadb'
local serialdev = '/dev/serial/blipduino'
--local serialdev = '/dev/tty'
local dbauth, postgres, qpostgres, mariadb, qmariadb
if (whichdb == 'mariadb') then
mariadb = require 'lem.mariadb'
qmariadb = require 'lem.mariadb.queued'
dbauth = {host="192.168.1.7",user="blipserver",passwd="pass",db="blipserver"}
end
if (whichdb == 'postgres') then
postgres = require 'lem.postgres'
qpostgres = require 'lem.postgres.queued'
dbauth = 'user=powermeter dbname=powermeter'
end
local blip = queue.new()
function runq_mariadb(db, query, ...)
if (db.conn) then
local r, m, e = (db[query][2]):run(...)
if (r or (e ~= 2006 and e ~= 2013)) then
return r, m, e
end
end
-- Try to reconnect
db.conn = assert(qmariadb.connect(dbauth))
for q_name, q in pairs(db) do
if (q_name ~= "conn") then
if (type(q) == "string") then
q = {q}
db[q_name] = q
end
q[2] = assert((db.conn):prepare(q[1]))
end
end
return assert(db[query][2]):run(...)
end
function runq_postgres(db, name, ...)
if (db.conn) then
local r, m = ((db.conn):run(name, ...))
-- ToDo: Check for connection lost failure, and if so, fall
-- through to reconnect and retry the query.
return r, m
end
-- Try to connect
db.conn = assert(qpostgres.connect(dbauth))
for q_name, q in pairs(db) do
if (q_name ~= "conn") then
-- Convert to postgres-style placeholders $N
local idx = 0
local f = function ()
idx = idx+1
return "$" .. idx
end
local pq = string.gsub(q, "%?", f)
assert((db.conn):prepare(q_name, pq))
end
end
return (db.conn):run(name, ...)
end
local runq
if (whichdb == 'mariadb') then
runq = runq_mariadb
end
if (whichdb == 'postgres') then
runq = runq_postgres
end
utils.spawn(function()
local serial = assert(io.open(serialdev, 'r'))
local db = {
put = 'INSERT INTO readings VALUES (?, ?)'
}
local now = utils.now
-- discard first two readings
assert(serial:read('*l'))
assert(serial:read('*l'))
while true do
local ms = assert(serial:read('*l'))
local stamp = format('%0.f', now() * 1000)
-- print(stamp, ms, blip.n)
blip:signal(stamp, ms)
assert(runq(db, 'put', stamp, ms))
-- print('waiting for next event')
end
end)
local function sendfile(content, path)
local file = assert(io.open(path))
local size = assert(file:size())
return function(req, res)
res.headers['Content-Type'] = content
res.headers['Content-Length'] = size
res.file = file
end
end
local index_html = sendfile('text/html; charset=UTF-8', 'index.html')
local oldindex_html = sendfile('text/html; charset=UTF-8', 'oldindex.html')
local labibus_html = sendfile('text/html; charset=UTF-8', 'power_labibus.html')
local lastweek_html = sendfile('text/html; charset=UTF-8', 'lastweek.html')
local lastmonth_html = sendfile('text/html; charset=UTF-8', 'lastmonth.html')
local lastyear_html = sendfile('text/html; charset=UTF-8', 'lastyear.html')
--hathaway.debug = print
hathaway.import()
GET('/', index_html)
GET('/index.html', index_html)
GET('/oldblips.html', index_html)
GET('/oldindex.html', oldindex_html)
GET('/labibus', labibus_html)
GET('/labibus.html', labibus_html)
GET('/lastweek.html', lastweek_html)
GET('/lastmonth.html', lastmonth_html)
GET('/lastyear.html', lastyear_html)
GET('/jquery.js', sendfile('text/javascript; charset=UTF-8', 'jquery.js'))
GET('/jquery.flot.js', sendfile('text/javascript; charset=UTF-8', 'jquery.flot.js'))
GET('/excanvas.js', sendfile('text/javascript; charset=UTF-8', 'excanvas.js'))
GET('/ribbon.png', sendfile('image/png', 'ribbon.png'))
GET('/favicon.ico', sendfile('image/x-icon', 'favicon.ico'))
local function apiheaders(headers)
headers['Content-Type'] = 'text/javascript; charset=UTF-8'
headers['Cache-Control'] = 'max-age=0, must-revalidate'
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'GET'
headers['Access-Control-Allow-Headers'] = 'origin, x-requested-with, accept'
headers['Access-Control-Max-Age'] = '60'
end
local function apioptions(req, res)
apiheaders(res.headers)
res.status = 200
end
OPTIONS('/blip', apioptions)
GET('/blip', function(req, res)
apiheaders(res.headers)
local stamp, ms = blip:get()
res:add('[%s,%s]', stamp, ms)
end)
local function add_json(res, values)
res:add('[')
local n = #values
if n > 0 then
for i = 1, n-1 do
local point = values[i]
res:add('[%s,%s],', point[1], point[2])
end
local point = values[n]
res:add('[%s,%s]', point[1], point[2])
end
res:add(']')
end
local function add_json5(res, values)
res:add('[')
local n = #values
if n > 0 then
for i = 1, n-1 do
local point = values[i]
res:add('[%s,%s,%s,%s,%s],', point[1], point[2], point[3], point[4], point[5])
end
local point = values[n]
res:add('[%s,%s,%s,%s,%s]', point[1], point[2], point[3], point[4], point[5])
end
res:add(']')
end
local db = {
get = 'SELECT stamp, ms FROM readings WHERE stamp >= ? ORDER BY stamp LIMIT 2000',
range = 'SELECT stamp, ms FROM readings WHERE stamp >= ? AND stamp <= ? ' ..
'ORDER BY stamp LIMIT 100000',
last = 'SELECT stamp, ms FROM readings ORDER BY stamp DESC LIMIT 1',
aggregate = 'SELECT ?*((stamp - ?) DIV ?) hour_stamp, COUNT(ms) ' ..
'FROM readings ' ..
'WHERE stamp >=? AND stamp < ?+?*? ' ..
'GROUP BY hour_stamp ORDER BY hour_stamp',
hourly = 'SELECT stamp, events, wh, min_ms, max_ms FROM usage_hourly ' ..
'WHERE stamp >= ? AND stamp <= ? ORDER BY stamp',
minutely = 'SELECT stamp, events, wh, min_ms, max_ms FROM usage_minutely ' ..
'WHERE stamp >= ? AND stamp <= ? ORDER BY stamp LIMIT 100000'
}
if (whichdb == 'postgres') then
db.aggregate = 'SELECT ?::DOUBLE PRECISION*DIV(stamp - ?, ?) hour_stamp, COUNT(ms) FROM readings WHERE stamp >=? AND stamp < ?+?::DOUBLE PRECISION*? GROUP BY hour_stamp ORDER BY hour_stamp'
end
OPTIONS('/last', apioptions)
GET('/last', function(req, res)
apiheaders(res.headers)
local point = assert(runq(db, 'last'))[1]
res:add('[%s,%s]', point[1], point[2])
end)
OPTIONSM('^/since/(%d+)$', apioptions)
GETM('^/since/(%d+)$', function(req, res, since)
if #since > 15 then
httpserv.bad_request(req, res)
return
end
apiheaders(res.headers)
add_json(res, assert(runq(db, 'get', since)))
end)
OPTIONSM('^/range/(%d+)/(%d+)$', apioptions)
GETM('^/range/(%d+)/(%d+)$', function(req, res, since, upto)
if #since > 15 or #upto > 15 then
httpserv.bad_request(req, res)
return
end
apiheaders(res.headers)
add_json(res, assert(runq(db, 'range', since, upto)))
end)
OPTIONSM('^/aggregate/(%d+)/(%d+)/(%d+)$', apioptions)
GETM('^/aggregate/(%d+)/(%d+)/(%d+)$', function(req, res, since, interval, count)
if #since > 15 or #interval > 15 or #count > 15 or tonumber(count) > 1000 then
httpserv.bad_request(req, res)
return
end
apiheaders(res.headers)
add_json(res, assert(runq(db, 'aggregate', interval, since,
interval, since, since, interval, count)))
end)
OPTIONSM('^/hourly/(%d+)/(%d+)$', apioptions)
GETM('^/hourly/(%d+)/(%d+)$', function(req, res, since, last)
if #since > 15 or #last > 15 then
httpserv.bad_request(req, res)
return
end
apiheaders(res.headers)
add_json5(res, assert(runq(db, 'hourly', since, last)))
end)
OPTIONSM('^/minutely/(%d+)/(%d+)$', apioptions)
GETM('^/minutely/(%d+)/(%d+)$', function(req, res, since, last)
if #since > 15 or #last > 15 then
httpserv.bad_request(req, res)
return
end
apiheaders(res.headers)
add_json5(res, assert(runq(db, 'minutely', since, last)))
end)
OPTIONSM('^/last/(%d+)$', apioptions)
GETM('^/last/(%d+)$', function(req, res, ms)
if #ms > 15 then
httpserv.bad_request(req, res)
return
end
apiheaders(res.headers)
local since = format('%0.f',
utils.now() * 1000 - tonumber(ms))
add_json(res, assert(runq(db, 'get', since)))
end)
assert(Hathaway('*', arg[1] or 8080))
-- vim: syntax=lua ts=2 sw=2 noet: