-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcosm.lua
More file actions
83 lines (73 loc) · 2.56 KB
/
cosm.lua
File metadata and controls
83 lines (73 loc) · 2.56 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
--required for parsing XML response from Cosm
local lom = require 'lxp.lom'
local xpath = require 'webscriptio/lib/xpath.lua'
local read_current = function (apikey,feed, datastream)
local response = http.request {
method='get',
url = 'http://api.cosm.com/v2/feeds/'..feed..'/datastreams/'..datastream,
headers = { ["X-PachubeApiKey"] = tostring(apikey) } }
return json.parse(response.content).current_value
end
local read_24h = function (apikey, feed, datastream)
local response = http.request {
method='get',
url = 'http://api.cosm.com/v2/feeds/'..feed..'/datastreams/'..datastream..'/?duration=24hours&interval=60',
headers = { ["X-PachubeApiKey"] = tostring(apikey) } }
local values = json.parse(response.content).datapoints
local sum = 0
local debug =""
local max = -math.huge
local min = math.huge
if values ~= null then
for i=1,# values do
sum=sum+values[i].value
max = math.max( max, values[i].value)
min = math.min( min, values[i].value)
end
return {sum/#values, max, min}
else
return "Feed must be frozen!"
end
end
-- returns something like: {"datastreams": ["cpu_0,2012-11-08T17:30:28.877620Z,24.50", "cpu_1,2012-11-08T17:30:28.877620Z,26.57"], "size": 2}
local list_datastreams = function(apikey, feed)
local response = http.request {
method='get',
url = 'http://api.cosm.com/v2/feeds/'..feed..'.csv',
headers = { ["X-PachubeApiKey"] = tostring(apikey) } }
local datastreams = split(tostring(response.content), '\n')
return {size=#datastreams, datastreams=datastreams}
end
split = function(s, pattern, maxsplit)
local pattern = pattern or ' '
local maxsplit = maxsplit or -1
local s = s
local t = {}
local patsz = #pattern
while maxsplit ~= 0 do
local curpos = 1
local found = string.find(s, pattern)
if found ~= nil then
table.insert(t, string.sub(s, curpos, found - 1))
curpos = found + patsz
s = string.sub(s, curpos)
else
table.insert(t, string.sub(s, curpos))
break
end
maxsplit = maxsplit - 1
if maxsplit == 0 then
table.insert(t, string.sub(s, curpos - patsz - 1))
end
end
return t
end
local isAlive = function(apikey, feed)
local response = http.request {
method='get',
url = 'http://api.cosm.com/v2/feeds/'..feed..'.xml',
headers = { ["X-PachubeApiKey"] = tostring(apikey) } }
local condition = xpath.selectNodes(lom.parse(response.content), '//status')[1]
return condition[1]
end
return { read_current = read_current, read_24h = read_24h, list_datastreams = list_datastreams, isAlive = isAlive }