3 local random = math.random
4 local json = require "json"
5 math.randomseed(os.time())
8 local template ='xxxx-xxxx'
9 return string.gsub(template, '[x]', function (c)
10 local v = random(0, 0xf)
11 return string.format('%x', v)
15 function process_MSG(mid, topic, payload)
16 pcall(function(topic,payload)
17 payload = json.decode(payload)
18 local time = os.date(payload['Time'])
19 if not time then time = os.date(payload['time']); end
20 local model = payload['model']
21 local id = payload['id']
23 device = payload['device']
25 model = device['model']
26 id = device['ieeeAddr']
29 for sensor_type,sensor_data in pairs(payload) do
30 if sensor_type ~= "Time" and sensor_type ~= "TempUnit" and sensor_type ~= "model" and sensor_type ~="id" and sensor_type ~= "time" and sensor_type ~= "device" and sensor_type ~="linkquality" and sensor_type ~= "battery" and sensor_type ~= "last_seen" and sensor_type ~= "voltage" then
32 conn:execute(string.format("CALL meteo.submit_mqtt('%s','%s','%s','%s',NULL)", topic,model,sensor_type,sensor_data))
34 print(string.format("%s/%s (%s) -> %s", topic, model, sensor_type, sensor_data))
36 for param,value in pairs(sensor_data) do
37 conn:execute(string.format("CALL meteo.submit_mqtt('%s','%s','%s','%s',NULL)", topic,sensor_type,param,value))
39 print(string.format("%s/%s (%s) -> %s", topic, sensor_type, param, value))
45 conn:execute('select 1') -- will fail if connection to DB broken
51 if not config_name then
52 config_name = "weathermon_mqtt"
55 mqtt_host = uci.get(config_name,"mqtt","server")
60 mqtt_port = uci.get(config_name,"mqtt","port")
65 mqtt_user = uci.get(config_name,"mqtt","username")
66 mqtt_pwd = uci.get(config_name,"mqtt","password")
68 mqtt_id = "wm-mqtt-"..uuid()
70 db_server = uci.get(config_name,"db","server")
71 db_name = uci.get(config_name,"db","db")
72 db_user = uci.get(config_name,"db","username")
73 db_pwd = uci.get(config_name,"db","password")
75 env = require("luasql.mysql").mysql()
76 conn = env:connect(db_name,db_user,db_pwd,db_server)
77 conn:execute("SET NAMES utf8")
79 MQTT = require "mosquitto"
80 mqtt_client = MQTT.new(mqtt_id)
82 mqtt_client:login_set(mqtt_user, mqtt_pwd)
85 mqtt_client:connect("estia.rvb-home.lan",1883)
86 mqtt_client.ON_MESSAGE = process_MSG
88 cur = conn:execute("SELECT DISTINCT topic FROM mqtt_topics WHERE topic<>''")
91 mqtt_client:subscribe(rec)
95 mqtt_client:loop_forever()