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('BEGIN TRANSACTION')
109 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))
110 backlog_con:execute('COMMIT')
116 log_con:execute('BEGIN TRANSACTION')
117 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))
118 log_con:execute('COMMIT')
123 function storeRecord(id,sensor,param,value)
125 if not records[id] then
129 records[id]["timestamp"] = os.date("%Y-%m-%dT%H:%M:%S")
131 if not records[id][sensor] then
132 records[id][sensor] = {}
135 records[id][sensor][param] = value
139 function processJson(str)
145 for key,value in pairs(msg) do
147 if key=="model" or key=="device" then
149 elseif key=="id" then
151 elseif key=='time' then
159 if not sensor_id then
160 sensor_id = web_devid
163 if not (sensor_type==nil or sensor_id==nil or sensor_type=='' or sensor_id=='') then
165 for k,v in pairs(sensor) do
166 storeRecord(sensor_id,sensor_type,k,v)
167 printLog("Type = "..sensor_type..", ID = "..sensor_id..", Param = "..k..", Value = \""..v.."\"")
169 submitValue(sensor_type,sensor_id,k,v)
172 mqtt_path=string.gsub(mqtt_topic,"{(.-)}",
175 return mqtt_encode(web_devid)
176 elseif name=="type" then
177 return mqtt_encode(sensor_type)
178 elseif name=="id" then
179 return mqtt_encode(sensor_id)
180 elseif name=="param" then
183 return '{'..name..'}'
186 if not mqtt_client:socket() then
187 mqtt_client:reconnect()
189 mqtt_client:publish(mqtt_path,v,0,false)
194 printLog("Cannot parse sensor input: "..str)
199 function processLine(str)
202 msg_type=msg[1] or ''
203 msg_body=msg[2] or ''
204 if msg_type=="STATUS" then
205 printLog("Status: "..msg_body)
206 elseif msg_type=="ERROR" then
207 printLog("Error: "..msg_body)
208 elseif msg_type=="SENSOR" then
209 printLog("SENSOR: "..msg_body)
210 sens = split(msg_body,",")
214 sensor_id = web_devid
215 for i,rec in ipairs(sens) do
222 elseif key=="ID" then
229 if not (sensor_type==nil or sensor_id==nil or sensor_type=='' or sensor_id=='') then
231 for k,v in pairs(sensor) do
232 storeRecord(sensor_id,sensor_type,k,v)
233 printLog("Type = "..sensor_type..", ID = "..sensor_id..", Param = "..k..", Value = "..v)
235 submitValue(sensor_type,sensor_id,k,v)
238 mqtt_path=string.gsub(mqtt_topic,"{(.-)}",
242 elseif name=="type" then
244 elseif name=="id" then
246 elseif name=="param" then
249 return '{'..name..'}'
252 if not mqtt_client:socket() then
253 mqtt_client:reconnect()
255 mqtt_client:publish(mqtt_path,v,0,false)
260 printLog("Cannot parse sensor input: "..msg_body)
262 elseif msg_type=="ALARM" then
263 printLog("ALARM: "..msg_body)
264 sens = split(msg_body,",")
268 sensor_id = web_devid
270 for i,rec in ipairs(sens) do
277 elseif key=="ID" then
282 if not (alarm_type==nil or alarm_id==nil or alarm_type=='' or alarm_id=='') then
284 mqtt_path=string.gsub(mqtt_alarm_topic,"{(.-)}",
288 elseif name=="type" then
290 elseif name=="id" then
293 return '{'..name..'}'
296 if not mqtt_client:socket() then
297 mqtt_client:reconnect()
299 mqtt_client:publish(mqtt_path,msg_body,0,false)
304 " \""..string.gsub(alarm_type,"\"","\\\"")..
305 "\" \""..string.gsub(alarm_id,"\"","\\\"")..
306 "\" \""..string.gsub(msg_body,"\"","\\\"").."\""
310 printLog("Cannot parse alarm input: "..msg_body)
318 signal.signal(signal.SIGTERM, function(signum)
320 printLog("Terminating...")
321 local pids = get_children()
322 for k,v in pairs(pids) do
323 printLog("Terminating subprocess "..tostring(v).."...")
324 signal.kill(v,signal.SIGTERM)
326 printLog("Exiting...")
331 if backlogdb or logdb then
332 local dbdriver = require "luasql.sqlite3"
333 env = assert(dbdriver.sqlite3())
337 if not file_exists(backlogdb) then
340 backlog_con = assert(env:connect(backlogdb))
341 backlog_con:execute("CREATE TABLE queue(time_stamp datetime,sensor_id varchar(16),sensor varchar(16),param varchar(16),value float)")
345 if not file_exists(logdb) then
348 log_con = assert(env:connect(logdb))
349 log_con:execute("CREATE TABLE log(time_stamp datetime,sensor_id varchar(16),sensor varchar(16),param varchar(16),value float)")
350 log_con:execute("CREATE INDEX log_idx ON log(sensor_id,sensor,param,time_stamp)")
354 http = require("socket.http")
355 http.TIMEOUT = web_timeout
359 MQTT = require "mosquitto"
360 mqtt_client = MQTT.new(mqtt_id)
362 mqtt_client:login_set(mqtt_user, mqtt_passwd)
364 mqtt_client:connect(mqtt_host,mqtt_port)
368 serialin=io.open(serial_port,"r")
369 elseif input_file == "-" then
371 elseif input_file then
372 serialin=io.open(input_file,"r")
373 elseif input_exec then
374 serialin=io.popen(input_exec,"r")
376 printLog("No input selected")
380 serialin:setvbuf('no')
386 line=serialin:read("*l")
394 printLog("Received: "..line)
395 if startswith(line,'{') then
409 local f = io.open(dump_file,"w")
411 io.write(json.encode(records))