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 submitValue(type,id,param,val)
96 if web_url and val then
98 local url = web_url.."?stype="..url_encode(type).."&sid="..url_encode(id).."¶m="..url_encode(param).."&value="..url_encode(val)
101 url = url:gsub("//","//"..web_user..":"..web_pass.."@",1)
104 local result,code = http.request (url)
106 if code ~= 200 and backlog_con then
107 printLog("writing record to backlog...")
108 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))
114 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))
119 function storeRecord(id,sensor,param,value)
121 if not records[id] then
125 records[id]["timestamp"] = os.date("%Y-%m-%dT%H:%M:%S")
127 if not records[id][sensor] then
128 records[id][sensor] = {}
131 records[id][sensor][param] = value
135 function processJson(str)
141 for key,value in pairs(msg) do
143 if key=="model" or key=="device" then
145 elseif key=="id" then
147 elseif key=='time' then
155 if not sensor_id then
156 sensor_id = web_devid
159 if not (sensor_type==nil or sensor_id==nil or sensor_type=='' or sensor_id=='') then
160 if next(sensor)==nil then
161 sensor["command"]="alarm"
164 for k,v in pairs(sensor) do
165 storeRecord(sensor_id,sensor_type,k,v)
166 printLog("Type = "..sensor_type..", ID = "..sensor_id..", Param = "..k..", Value = \""..v.."\"")
168 submitValue(sensor_type,sensor_id,k,v)
171 mqtt_path=string.gsub(mqtt_topic,"{(.-)}",
174 return mqtt_encode(web_devid)
175 elseif name=="type" then
176 return mqtt_encode(sensor_type)
177 elseif name=="id" then
178 return mqtt_encode(sensor_id)
179 elseif name=="param" then
182 return '{'..name..'}'
185 if not mqtt_client:socket() then
186 mqtt_client:reconnect()
188 mqtt_client:publish(mqtt_path,v,0,0)
193 printLog("Cannot parse sensor input: "..str)
198 function processLine(str)
201 msg_type=msg[1] or ''
202 msg_body=msg[2] or ''
203 if msg_type=="STATUS" then
204 printLog("Status: "..msg_body)
205 elseif msg_type=="ERROR" then
206 printLog("Error: "..msg_body)
207 elseif msg_type=="SENSOR" then
208 printLog("SENSOR: "..msg_body)
209 sens = split(msg_body,",")
213 sensor_id = web_devid
214 for i,rec in ipairs(sens) do
221 elseif key=="ID" then
228 if not (sensor_type==nil or sensor_id==nil or sensor_type=='' or sensor_id=='') then
230 for k,v in pairs(sensor) do
231 storeRecord(sensor_id,sensor_type,k,v)
232 printLog("Type = "..sensor_type..", ID = "..sensor_id..", Param = "..k..", Value = "..v)
234 submitValue(sensor_type,sensor_id,k,v)
237 mqtt_path=string.gsub(mqtt_topic,"{(.-)}",
241 elseif name=="type" then
243 elseif name=="id" then
245 elseif name=="param" then
248 return '{'..name..'}'
251 mqtt_client:publish(mqtt_path,v,0,0)
256 printLog("Cannot parse sensor input: "..msg_body)
258 elseif msg_type=="ALARM" then
259 printLog("ALARM: "..msg_body)
260 sens = split(msg_body,",")
264 sensor_id = web_devid
266 for i,rec in ipairs(sens) do
273 elseif key=="ID" then
278 if not (alarm_type==nil or alarm_id==nil or alarm_type=='' or alarm_id=='') then
280 mqtt_path=string.gsub(mqtt_alarm_topic,"{(.-)}",
284 elseif name=="type" then
286 elseif name=="id" then
289 return '{'..name..'}'
292 mqtt_client:publish(mqtt_path,msg_body,0,0)
297 " \""..string.gsub(alarm_type,"\"","\\\"")..
298 "\" \""..string.gsub(alarm_id,"\"","\\\"")..
299 "\" \""..string.gsub(msg_body,"\"","\\\"").."\""
303 printLog("Cannot parse alarm input: "..msg_body)
311 signal.signal(signal.SIGTERM, function(signum)
313 printLog("Terminating...")
314 local pids = get_children()
315 for k,v in pairs(pids) do
316 printLog("Terminating subprocess "..tostring(v).."...")
317 signal.kill(v,signal.SIGTERM)
319 printLog("Exiting...")
324 if backlogdb or logdb then
325 local dbdriver = require "luasql.sqlite3"
326 env = assert(dbdriver.sqlite3())
330 if not file_exists(backlogdb) then
333 backlog_con = assert(env:connect(backlogdb))
334 backlog_con:execute("CREATE TABLE queue(time_stamp datetime,sensor_id varchar(16),sensor varchar(16),param varchar(16),value float)")
338 if not file_exists(logdb) then
341 log_con = assert(env:connect(logdb))
342 log_con:execute("CREATE TABLE log(time_stamp datetime,sensor_id varchar(16),sensor varchar(16),param varchar(16),value float)")
343 log_con:execute("CREATE INDEX log_idx ON log(sensor_id,sensor,param,time_stamp)")
347 http = require("socket.http")
348 http.TIMEOUT = web_timeout
352 MQTT = require "mosquitto"
353 mqtt_client = MQTT.new(mqtt_id)
355 mqtt_client:login_set(mqtt_user, mqtt_passwd)
357 mqtt_client:connect(mqtt_host,mqtt_port)
361 serialin=io.open(serial_port,"r")
362 elseif input_file == "-" then
364 elseif input_file then
365 serialin=io.open(input_file,"r")
366 elseif input_exec then
367 serialin=io.popen(input_exec,"r")
369 printLog("No input selected")
373 serialin:setvbuf('no')
379 line=serialin:read("*l")
387 printLog("Received: "..line)
388 if startswith(line,'{') then
402 local f = io.open(dump_file,"w")
404 io.write(json.encode(records))