+#!/usr/bin/lua
+
+json = require("json")
+
+function getConfig(configname)
+
+ local status,uci = pcall(require,"uci")
+
+ local config
+
+ if status then
+
+ if configname then
+ config=configname
+ else
+ config="beacon"
+ end
+
+ local cur=uci.cursor()
+
+ logging = cur.get(config,"logging","enabled")
+
+ mqtt_host = cur.get(config,"mqtt","host")
+ mqtt_port = cur.get(config,"mqtt","port")
+ mqtt_id = cur.get(config,"mqtt","id")
+ mqtt_topic = cur.get(config,"mqtt","topic")
+
+ mqtt_user = cur.get(config,"mqtt","user")
+ mqtt_passwd = cur.get(config,"mqtt","password")
+
+ else
+
+ local status,ini = pcall(require,"ini")
+ if not status then
+ os.exit(1)
+ end
+
+ if configname then
+ config=configname
+ else
+ config="/etc/beacon.ini"
+ end
+
+ local cur=ini.parse_file(config)
+
+ logging = cur["logging"]["enabled"]
+
+ mqtt_host = cur["mqtt"]["host"]
+ mqtt_port = cur["mqtt"]["port"]
+ mqtt_id = cur["mqtt"]["id"]
+ mqtt_topic = cur["mqtt"]["topic"]
+
+ mqtt_user = cur["mqtt"]["user"]
+ mqtt_passwd = cur["mqtt"]["password"]
+
+ end
+
+ if mqtt_host and not mqtt_id then
+ socket = require("socket")
+ posix = require("posix")
+ hostname = socket.dns.gethostname()
+ pid = posix.getpid()
+ mqtt_id="beaconmon-"..hostname.."-"..pid
+ end
+
+ if mqtt_host and not mqtt_port then
+ mqtt_port = 1883
+ end
+
+ if mqtt_host and not mqtt_topic then
+ mqtt_topic = 'beaconmon/{type}/{details}'
+ end
+
+end
+
+function capture(cmd, raw)
+ local f = assert(io.popen(cmd, 'r'))
+ local s = assert(f:read('*a'))
+ f:close()
+ if raw then return s end
+ s = string.gsub(s, '^%s+', '')
+ s = string.gsub(s, '%s+$', '')
+ s = string.gsub(s, '[\n\r]+', ' ')
+ return s
+end
+
+function mqtt_encode(str)
+ if (str) then
+ str = string.gsub (str, "\n", "")
+ str = string.gsub (str, ":", "-")
+ str = string.gsub (str, "/", "-")
+ str = string.gsub (str, " ", "_")
+ end
+ return str
+end
+
+function printLog(str)
+ if logging=="yes" then
+ capture("logger -t beaconmon \""..str.."\"")
+ else
+ print(str)
+ end
+end