#!/usr/bin/lua local random = math.random local json = require "json" math.randomseed(os.time()) local function uuid() local template ='xxxx-xxxx' return string.gsub(template, '[x]', function (c) local v = random(0, 0xf) return string.format('%x', v) end) end function process_MSG(mid, topic, payload) print(topic, payload) pcall(function(topic,payload) print(payload) payload = json.decode(payload) local time = os.date(payload['Time']) if not time then time = os.date(payload['time']); end local model = payload['model'] local id = payload['id'] for sensor_type,sensor_data in pairs(payload) do if sensor_type ~= "Time" and sensor_type ~= "TempUnit" and sensor_type ~= "model" and sensor_type ~="id" and sensor_type ~= "time" then if model then conn:execute(string.format("CALL meteo.submit_mqtt('%s','%s','%s','%s',NULL)", topic,model,sensor_type,sensor_data)) conn:commit() print(topic,model,sensor_type,sensor_data) else for param,value in pairs(sensor_data) do conn:execute(string.format("CALL meteo.submit_mqtt('%s','%s','%s','%s',NULL)", topic,sensor_type,param,value)) conn:commit() print(topic,sensor_type,param,value) end end end end end, topic, payload) end uci = require "uci" config_name = arg[1] if not config_name then config_name = "weathermon_mqtt" end mqtt_host = uci.get(config_name,"mqtt","server") if not mqtt_host then mqtt_host="127.0.0.1" end mqtt_port = uci.get(config_name,"mqtt","port") if not mqtt_port then mqtt_host=1883 end mqtt_user = uci.get(config_name,"mqtt","username") mqtt_pwd = uci.get(config_name,"mqtt","password") mqtt_id = "wm-mqtt-"..uuid() db_server = uci.get(config_name,"db","server") db_name = uci.get(config_name,"db","db") db_user = uci.get(config_name,"db","username") db_pwd = uci.get(config_name,"db","password") env = require("luasql.mysql").mysql() conn = env:connect(db_name,db_user,db_pwd,db_server) conn:execute("SET NAMES utf8") MQTT = require "mosquitto" mqtt_client = MQTT.new(mqtt_id) if mqtt_user then mqtt_client:login_set(mqtt_user, mqtt_pwd) end mqtt_client:connect("estia.rvb-home.lan",1883) mqtt_client.ON_MESSAGE = process_MSG cur = conn:execute("SELECT DISTINCT topic FROM mqtt_topics WHERE topic<>''") rec = cur:fetch() while rec do mqtt_client:subscribe(rec) rec = cur:fetch() end mqtt_client:loop_forever()