3 local json = require("json")
4 local signal = require("posix.signal")
8 function getConfig(configname)
12 local uci=require("uci")
13 local cur=uci.cursor()
21 web_url = cur.get(config,"web","url")
22 web_user = cur.get(config,"web","user")
23 web_timeout = cur.get(config,"web","timeout")
24 web_pass = cur.get(config,"web","password")
26 if not web_timeout then
30 web_devid = get_devid(config)
32 logging = cur.get(config,"logging","enabled")
33 touch_file = cur.get(config,"logging","touch_file")
35 backlogdb = cur.get(config,"process","backlogdb")
36 logdb = cur.get(config,"process","logdb")
38 serial_port = cur.get(config,"serial","port")
39 serial_baud = cur.get(config,"serial","baud")
41 input_file = cur.get(config,"input","file")
42 input_exec = cur.get(config,"input","exec")
43 alarm_exec = cur.get(config,"alarm","exec")
47 command = "stty -F "..serial_port.." "..serial_baud
52 mqtt_host = cur.get(config,"mqtt","host")
53 mqtt_port = cur.get(config,"mqtt","port")
54 mqtt_id = cur.get(config,"mqtt","id")
55 mqtt_topic = cur.get(config,"mqtt","topic")
56 mqtt_alarm_topic = cur.get(config,"mqtt","alarm_topic")
58 mqtt_user = cur.get(config,"mqtt","user")
59 mqtt_passwd = cur.get(config,"mqtt","password")
61 if mqtt_host and not mqtt_id then
62 mqtt_id="weather-"..web_devid
65 if mqtt_host and not mqtt_port then
69 if mqtt_host and not mqtt_topic then
70 mqtt_topic = 'weathermon/{dev}/{type}/{id}/{param}'
73 if mqtt_host and not mqtt_alarm_topic then
74 mqtt_alarm_topic = 'alarm/{dev}/{type}/{id}'
77 dump_file = cur.get(config,"process","dump_file")
81 function printLog(str)
83 capture("logger -t weathermon "..str)
85 elseif logging=="syslog" then
86 capture("logger -t weathermon "..str)
87 elseif logging=="stdout" then
92 function unlock_db(file)
94 print("Unlocking DB "..file)
95 os.execute("sqlite3 -readonly \""..file.."\" \".backup /tmp/weathermon.db\"")
96 os.execute("mv /tmp/weathermon.db \""..file.."\"")
100 function submitValue(type,id,param,val)
104 if web_url and val then
106 local url = web_url.."?stype="..url_encode(type).."&sid="..url_encode(id).."¶m="..url_encode(param).."&value="..url_encode(val)
109 url = url:gsub("//","//"..web_user..":"..web_pass.."@",1)
112 local result,code = http.request (url)
114 if code ~= 200 and backlogdb then
115 printLog("writing record to backlog...")
116 local backlog_con = assert(env:connect(backlogdb))
117 local n,err = backlog_con:execute(string.format("INSERT INTO queue(time_stamp,sensor_id,sensor,param,value) VALUES (datetime('now','localtime'),'%s','%s','%s',%f)",id,type,param,val))
120 if err == "LuaSQL: database is locked" then
121 unlock_db(backlogdb);
130 local log_con = assert(env:connect(logdb))
131 local n,err = log_con:execute(string.format("INSERT INTO log(time_stamp,sensor_id,sensor,param,value) VALUES (datetime('now','localtime'),'%s','%s','%s',%f)",id,type,param,val))
134 if err == "LuaSQL: database is locked" then
142 function storeRecord(id,sensor,param,value)
144 if not records[id] then
148 records[id]["timestamp"] = os.date("%Y-%m-%dT%H:%M:%S")
150 if not records[id][sensor] then
151 records[id][sensor] = {}
154 records[id][sensor][param] = value
158 function processJson(str)
164 for key,value in pairs(msg) do
166 if key=="model" or key=="device" then
168 elseif key=="id" then
170 elseif key=='time' then
178 if not sensor_id then
179 sensor_id = web_devid
182 if not (sensor_type==nil or sensor_id==nil or sensor_type=='' or sensor_id=='') then
184 for k,v in pairs(sensor) do
185 storeRecord(sensor_id,sensor_type,k,v)
186 printLog("Type = "..sensor_type..", ID = "..sensor_id..", Param = "..k..", Value = \""..v.."\"")
188 submitValue(sensor_type,sensor_id,k,v)
191 mqtt_path=string.gsub(mqtt_topic,"{(.-)}",
194 return mqtt_encode(web_devid)
195 elseif name=="type" then
196 return mqtt_encode(sensor_type)
197 elseif name=="id" then
198 return mqtt_encode(sensor_id)
199 elseif name=="param" then
202 return '{'..name..'}'
205 if not mqtt_client:socket() then
206 mqtt_client:reconnect()
208 mqtt_client:publish(mqtt_path,v,0,false)
213 printLog("Cannot parse sensor input: "..str)
218 function processLine(str)
221 msg_type=msg[1] or ''
222 msg_body=msg[2] or ''
223 if msg_type=="STATUS" then
224 printLog("Status: "..msg_body)
225 elseif msg_type=="ERROR" then
226 printLog("Error: "..msg_body)
227 elseif msg_type=="SENSOR" then
228 printLog("SENSOR: "..msg_body)
229 sens = split(msg_body,",")
233 sensor_id = web_devid
234 for i,rec in ipairs(sens) do
241 elseif key=="ID" then
248 if not (sensor_type==nil or sensor_id==nil or sensor_type=='' or sensor_id=='') then
250 for k,v in pairs(sensor) do
251 storeRecord(sensor_id,sensor_type,k,v)
252 printLog("Type = "..sensor_type..", ID = "..sensor_id..", Param = "..k..", Value = "..v)
254 submitValue(sensor_type,sensor_id,k,v)
257 mqtt_path=string.gsub(mqtt_topic,"{(.-)}",
261 elseif name=="type" then
263 elseif name=="id" then
265 elseif name=="param" then
268 return '{'..name..'}'
271 if not mqtt_client:socket() then
272 mqtt_client:reconnect()
274 mqtt_client:publish(mqtt_path,v,0,false)
279 printLog("Cannot parse sensor input: "..msg_body)
281 elseif msg_type=="ALARM" then
282 printLog("ALARM: "..msg_body)
283 sens = split(msg_body,",")
287 sensor_id = web_devid
289 for i,rec in ipairs(sens) do
296 elseif key=="ID" then
301 if not (alarm_type==nil or alarm_id==nil or alarm_type=='' or alarm_id=='') then
303 mqtt_path=string.gsub(mqtt_alarm_topic,"{(.-)}",
307 elseif name=="type" then
309 elseif name=="id" then
312 return '{'..name..'}'
315 if not mqtt_client:socket() then
316 mqtt_client:reconnect()
318 mqtt_client:publish(mqtt_path,msg_body,0,false)
323 " \""..string.gsub(alarm_type,"\"","\\\"")..
324 "\" \""..string.gsub(alarm_id,"\"","\\\"")..
325 "\" \""..string.gsub(msg_body,"\"","\\\"").."\""
329 printLog("Cannot parse alarm input: "..msg_body)
337 signal.signal(signal.SIGTERM, function(signum)
339 printLog("Terminating...")
340 local pids = get_children()
341 for k,v in pairs(pids) do
342 printLog("Terminating subprocess "..tostring(v).."...")
343 signal.kill(v,signal.SIGTERM)
345 printLog("Exiting...")
350 if backlogdb or logdb then
351 local dbdriver = require "luasql.sqlite3"
352 env = assert(dbdriver.sqlite3())
356 if not file_exists(backlogdb) then
359 local backlog_con = assert(env:connect(backlogdb))
360 backlog_con:execute("CREATE TABLE queue(time_stamp datetime,sensor_id varchar(16),sensor varchar(16),param varchar(16),value float)")
365 if not file_exists(logdb) then
368 local log_con = assert(env:connect(logdb))
369 log_con:execute("CREATE TABLE log(time_stamp datetime,sensor_id varchar(16),sensor varchar(16),param varchar(16),value float)")
370 log_con:execute("CREATE INDEX log_idx ON log(sensor_id,sensor,param,time_stamp)")
375 http = require("socket.http")
376 http.TIMEOUT = web_timeout
380 MQTT = require "mosquitto"
381 mqtt_client = MQTT.new(mqtt_id)
383 mqtt_client:login_set(mqtt_user, mqtt_passwd)
385 mqtt_client:connect(mqtt_host,mqtt_port)
389 serialin=io.open(serial_port,"r")
390 elseif input_file == "-" then
392 elseif input_file then
393 serialin=io.open(input_file,"r")
394 elseif input_exec then
395 serialin=io.popen(input_exec,"r")
397 printLog("No input selected")
401 serialin:setvbuf('no')
407 line=serialin:read("*l")
415 printLog("Received: "..line)
416 if startswith(line,'{') then
430 local f = io.open(dump_file,"w")
432 io.write(json.encode(records))