5 function getConfig(configname)
7 local uci=require("uci")
16 logging = cur.get(config,"logging","enabled")
18 mqtt_host = cur.get(config,"mqtt","host")
19 mqtt_port = cur.get(config,"mqtt","port")
20 mqtt_id = cur.get(config,"mqtt","id")
21 mqtt_topic = cur.get(config,"mqtt","topic")
23 mqtt_user = cur.get(config,"mqtt","user")
24 mqtt_passwd = cur.get(config,"mqtt","password")
26 if mqtt_host and not mqtt_id then
27 socket = require("socket")
28 posix = require("posix")
29 hostname = socket.dns.gethostname()
31 mqtt_id="beaconmon-"..hostname.."-"..pid
34 if mqtt_host and not mqtt_port then
38 if mqtt_host and not mqtt_topic then
39 mqtt_topic = 'beaconmon/{type}/{details}'
44 function capture(cmd, raw)
45 local f = assert(io.popen(cmd, 'r'))
46 local s = assert(f:read('*a'))
48 if raw then return s end
49 s = string.gsub(s, '^%s+', '')
50 s = string.gsub(s, '%s+$', '')
51 s = string.gsub(s, '[\n\r]+', ' ')
55 function mqtt_encode(str)
57 str = string.gsub (str, "\n", "")
58 str = string.gsub (str, "/", "-")
63 function printLog(str)
64 if logging=="yes" then
65 capture("logger -t beaconmon "..str)
71 function run_command(cmd)
73 local file = assert(io.popen(cmd, 'r'))
74 local output = file:read('*all')
81 run_command("/bin/kill `/usr/bin/pgrep btmon`")
82 run_command("/bin/kill `/usr/bin/pgrep hcitool`")
83 f = assert(io.popen ("/usr/bin/stdbuf -o0 /usr/bin/btmon"))
84 run_command("/usr/bin/hciconfig hci0 down")
85 run_command("/usr/bin/hciconfig hci0 up")
86 f_null = assert(io.popen ("/usr/bin/hcitool lescan --duplicates --passive"))
97 return (s:gsub("^%s*(.-)%s*$", "%1"))
100 function mqtt_pub(path,value)
101 res=mqtt_client:publish(path,value)
102 printLog("Pub "..path.." "..value.." returned "..res);
106 function process_packet(packet)
114 mac = packet['Address']
115 uuid = packet['uuid']
116 type = packet['Type']
117 name = packet['Name (complete)']
119 if type=='iBeacon' then
129 if not (type=="unknown") then
130 mqtt_path=string.gsub(mqtt_topic,"{(.-)}",
133 return mqtt_encode(type)
134 elseif name=="details" then
135 return mqtt_encode(details)
137 return '{'..name..'}'
141 if not pcall(mqtt_pub,mqtt_path,dump(packet)) then
142 printLog('Reconnecting MQTT...')
143 mqtt_client:connect(mqtt_id)
150 function starts(String,Start)
151 return string.sub(String,1,string.len(Start))==Start
154 function split(inputstr, sep)
159 for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
183 value=trim(table.concat(t,':',2))
184 if name=="Address" then
185 value=split(value)[1]
191 if starts(str,'> HCI Event: LE Meta Event (0x3e)') then
193 elseif starts(str,'RSSI:') then
195 process_packet(packet)
205 io.stdout:setvbuf('no')
206 io.stdin:setvbuf('no')
211 MQTT = require "mosquitto"
212 mqtt_client = MQTT.new(mqtt_id)
214 mqtt_client:login_set(mqtt_user, mqtt_passwd)
216 mqtt_client:connect(mqtt_host,mqtt_port)