Skip to content

Instantly share code, notes, and snippets.

@AgustinPelaez
Created July 24, 2014 14:59
Show Gist options
  • Select an option

  • Save AgustinPelaez/a7a4967406c4cb1260d6 to your computer and use it in GitHub Desktop.

Select an option

Save AgustinPelaez/a7a4967406c4cb1260d6 to your computer and use it in GitHub Desktop.
A Lua code to measure the latency from an Openwrt router and send this value to the Ubidots Cloud.
#!usr/bin/env lua
-- Loading main configuration
local config = require "config"
-- Library to read command 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 host = string.format("http://%s:%d", config.host, config.port or 80)
-- Getting the retrieved token
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/v1.6/variables/%s/values/", host, var_id),
method = "POST",
headers = {
['X-Auth-Token'] = config.token,
['Content-Type'] = "application/json",
['Content-Length'] = string.len(dtime)
},
redirect = true,
source = ltn12.source.string(dtime),
sink = ltn12.sink.file(io.stdout)
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment