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 backlogdb then
107 printLog("writing record to backlog...")
108 local backlog_con = assert(env:connect(backlogdb))
109 backlog_con:execute('BEGIN TRANSACTION')
110 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))
111 backlog_con:execute('COMMIT')
118 local log_con = assert(env:connect(logdb))
119 log_con:execute('BEGIN TRANSACTION')
120 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))
121 log_con:execute('COMMIT')
127 function storeRecord(id,sensor,param,value)
129 if not records[id] then
133 records[id]["timestamp"] = os.date("%Y-%m-%dT%H:%M:%S")
135 if not records[id][sensor] then
136 records[id][sensor] = {}
139 records[id][sensor][param] = value
143 function processJson(str)
149 for key,value in pairs(msg) do
151 if key=="model" or key=="device" then
153 elseif key=="id" then
155 elseif key=='time' then
163 if not sensor_id then
164 sensor_id = web_devid
167 if not (sensor_type==nil or sensor_id==nil or sensor_type=='' or sensor_id=='') then
169 for k,v in pairs(sensor) do
170 storeRecord(sensor_id,sensor_type,k,v)
171 printLog("Type = "..sensor_type..", ID = "..sensor_id..", Param = "..k..", Value = \""..v.."\"")
173 submitValue(sensor_type,sensor_id,k,v)
176 mqtt_path=string.gsub(mqtt_topic,"{(.-)}",
179 return mqtt_encode(web_devid)
180 elseif name=="type" then
181 return mqtt_encode(sensor_type)
182 elseif name=="id" then
183 return mqtt_encode(sensor_id)
184 elseif name=="param" then
187 return '{'..name..'}'
190 if not mqtt_client:socket() then
191 mqtt_client:reconnect()
193 mqtt_client:publish(mqtt_path,v,0,false)
198 printLog("Cannot parse sensor input: "..str)
203 function processLine(str)
206 msg_type=msg[1] or ''
207 msg_body=msg[2] or ''
208 if msg_type=="STATUS" then
209 printLog("Status: "..msg_body)
210 elseif msg_type=="ERROR" then
211 printLog("Error: "..msg_body)
212 elseif msg_type=="SENSOR" then
213 printLog("SENSOR: "..msg_body)
214 sens = split(msg_body,",")
218 sensor_id = web_devid
219 for i,rec in ipairs(sens) do
226 elseif key=="ID" then
233 if not (sensor_type==nil or sensor_id==nil or sensor_type=='' or sensor_id=='') then
235 for k,v in pairs(sensor) do
236 storeRecord(sensor_id,sensor_type,k,v)
237 printLog("Type = "..sensor_type..", ID = "..sensor_id..", Param = "..k..", Value = "..v)
239 submitValue(sensor_type,sensor_id,k,v)
242 mqtt_path=string.gsub(mqtt_topic,"{(.-)}",
246 elseif name=="type" then
248 elseif name=="id" then
250 elseif name=="param" then
253 return '{'..name..'}'
256 if not mqtt_client:socket() then
257 mqtt_client:reconnect()
259 mqtt_client:publish(mqtt_path,v,0,false)
264 printLog("Cannot parse sensor input: "..msg_body)
266 elseif msg_type=="ALARM" then
267 printLog("ALARM: "..msg_body)
268 sens = split(msg_body,",")
272 sensor_id = web_devid
274 for i,rec in ipairs(sens) do
281 elseif key=="ID" then
286 if not (alarm_type==nil or alarm_id==nil or alarm_type=='' or alarm_id=='') then
288 mqtt_path=string.gsub(mqtt_alarm_topic,"{(.-)}",
292 elseif name=="type" then
294 elseif name=="id" then
297 return '{'..name..'}'
300 if not mqtt_client:socket() then
301 mqtt_client:reconnect()
303 mqtt_client:publish(mqtt_path,msg_body,0,false)
308 " \""..string.gsub(alarm_type,"\"","\\\"")..
309 "\" \""..string.gsub(alarm_id,"\"","\\\"")..
310 "\" \""..string.gsub(msg_body,"\"","\\\"").."\""
314 printLog("Cannot parse alarm input: "..msg_body)
322 signal.signal(signal.SIGTERM, function(signum)
324 printLog("Terminating...")
325 local pids = get_children()
326 for k,v in pairs(pids) do
327 printLog("Terminating subprocess "..tostring(v).."...")
328 signal.kill(v,signal.SIGTERM)
330 printLog("Exiting...")
335 if backlogdb or logdb then
336 local dbdriver = require "luasql.sqlite3"
337 env = assert(dbdriver.sqlite3())
341 if not file_exists(backlogdb) then
344 local backlog_con = assert(env:connect(backlogdb))
345 backlog_con:execute("CREATE TABLE queue(time_stamp datetime,sensor_id varchar(16),sensor varchar(16),param varchar(16),value float)")
350 if not file_exists(logdb) then
353 local log_con = assert(env:connect(logdb))
354 log_con:execute("CREATE TABLE log(time_stamp datetime,sensor_id varchar(16),sensor varchar(16),param varchar(16),value float)")
355 log_con:execute("CREATE INDEX log_idx ON log(sensor_id,sensor,param,time_stamp)")
360 http = require("socket.http")
361 http.TIMEOUT = web_timeout
365 MQTT = require "mosquitto"
366 mqtt_client = MQTT.new(mqtt_id)
368 mqtt_client:login_set(mqtt_user, mqtt_passwd)
370 mqtt_client:connect(mqtt_host,mqtt_port)
374 serialin=io.open(serial_port,"r")
375 elseif input_file == "-" then
377 elseif input_file then
378 serialin=io.open(input_file,"r")
379 elseif input_exec then
380 serialin=io.popen(input_exec,"r")
382 printLog("No input selected")
386 serialin:setvbuf('no')
392 line=serialin:read("*l")
400 printLog("Received: "..line)
401 if startswith(line,'{') then
415 local f = io.open(dump_file,"w")
417 io.write(json.encode(records))