#!/usr/bin/lua package.path = package.path..";/home/paul/git/micodus_server/html/?.lua" local const = require("const") local json = require("json") local server = require("nginx.websocket.server") local sqlite = require("lsqlite3") --ngx.shared.geo:set("last_time","") local db = sqlite.open(const.dbfile, sqlite.OPEN_READONLY) function getdata() local res, vm = db:nrows(const.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 handle_ping(wb) local data, typ, err = wb:recv_frame() if data then ngx.log(ndx.ERR,data) end coroutine.yield() end function send_data(wb, last_time) while true do ngx.log(ndx.ERR,"test") local data = getdata() ngx.log(ndx.ERR,data) if data.time ~= last_time then local locstr = json.encode(data) local bytes, err = wb:send_text(locstr) ngx.log(ndx.ERR,bytes) 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(0.5) coroutine.yield() end 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 local h = coroutine.create(handle_ping, wb) local s = coroutine.create(send_data, wb, last_time) local i=0 while true do ngx.log(ngx.ERR,i) coroutine.resume(h,wb) coroutine.resume(s,wb,last_time) if not wb then ngx.log(ngx.ERR, "failed to new websocket: ", err) return ngx.exit(444) end i=i+1 ngx.sleep(0.5) end wb:send_close() end geows()