micodus_server/html/ws.lua

66 lines
1.4 KiB
Lua
Raw Normal View History

2025-02-14 20:14:53 +01:00
#!/usr/bin/lua
local json = require("json")
local server = require("nginx.websocket.server")
local sqlite = require("lsqlite3")
local basepath = "/home/paul/git/micodus_server"
local dbfile = string.format("%s/data/tracker.db",basepath)
local query = [[
SELECT time,latitude,longitude,height,speed,direction,serial
FROM log
ORDER BY time DESC
LIMIT 1;
]]
--ngx.shared.geo:set("last_time","")
function getdata()
local db = sqlite.open(dbfile,sqlite3.OPEN_READONLY)
local res, vm = db:nrows(query)
local data
for row in res, vm do
data = {
["time"]=row.time,
["latitude"]=row.latitude,
["longitude"]=row.longitude,
["height"]=row.height,
["speed"]=row.speed,
["direction"]=row.direction,
["serial"]=row.serial,
}
end
db:close()
return data
end
function geows()
local locstr = nil
local wb, err = server:new {
timeout = 5000,
max_payload_len = 65535
}
if not wb then
ngx.log(ngx.ERR, "failed to new websocket: ", err)
return ngx.exit(444)
end
local last_time = nil
while true do
local data = getdata()
if data.time ~= last_time then
local locstr = json.encode(data)
local bytes, err = wb:send_text(locstr)
if not bytes then
ngx.log(ngx.ERR, "failed to send text: ", err)
return ngx.exit(444)
end
last_time = data.time
end
ngx.sleep(1)
end
wb:send_close()
end
geows()