Created
August 30, 2013 21:14
-
-
Save AgustinPelaez/6394342 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env lua | |
-- Loading main configuration | |
local config = require "conf" | |
-- Library to read commando output | |
local io = require "io" | |
-- Load the http module | |
local http = require "socket.http" | |
-- loading ltn12 and json libraries from luci framework | |
local ltn12 = require "luci.ltn12" | |
local json = require "luci.json" | |
local tb = {} | |
local host = string.format("http://%s:%d", config.host, config.port or 80) | |
-- connect to server and retrieves this manual | |
-- and print it to a table | |
-- FIXME: Fix url format to allow host and apikey as parameters. | |
local rs, code = http.request{ | |
url = string.format('%s/api/auth/token', host), | |
sink = ltn12.sink.table(tb), | |
method = "POST", | |
headers = { | |
['X-Ubidots-ApiKey'] = config.apikey | |
} | |
} | |
-- Getting the retrieved token | |
if tb[1] ~= nil and code == 201 then | |
tk = string.match(tb[1], '%s+"(%w+)"') | |
for var_id, var_ip in pairs(config.variables) do | |
print(var_id, var_ip) | |
local f = io.popen(string.format('ping -c 1 -W 4 %s | grep ttl', var_ip)) | |
local l = f:read("*a") | |
f:close() | |
local rtime = '-1' | |
if l ~= '' then | |
-- Getting response time from ping output. | |
rtime = string.match(l, "time=(%d+\.%d*)") | |
end | |
print(rtime) | |
local dtime = string.format('{"value": %s}', rtime) | |
print(dtime) | |
-- Post value to retrieved variable | |
local rsp, code, tr = http.request{ | |
url=string.format("%s/api/variables/%s/values/", host, var_id), | |
method = "POST", | |
headers = { | |
['X-Auth-Token'] = tk, | |
['Content-Type'] = "application/json", | |
['content-length'] = string.len(dtime) | |
}, | |
redirect = true, | |
source = ltn12.source.string(dtime), | |
sink = ltn12.sink.file(io.stdout) | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment