Skip to content

Instantly share code, notes, and snippets.

@a-andreyev
Forked from c0ze/ibeacon_scan.sh
Last active June 21, 2017 12:56
Show Gist options
  • Save a-andreyev/0a50f14568cc0ef6e95dcb4b32081eae to your computer and use it in GitHub Desktop.
Save a-andreyev/0a50f14568cc0ef6e95dcb4b32081eae to your computer and use it in GitHub Desktop.
A bash script to parse ibeacon packets
#!/bin/bash
# iBeacon Scan by Arda Karaduman
# + MQTT pub by Alexey Andreyev ([email protected])
function parse_ib_uuid {
UUID=`echo $1 | sed 's/^.\{69\}\(.\{47\}\).*$/\1/'`
UUID=`echo $UUID | sed -e 's/\ //g' -e 's/^\(.\{8\}\)\(.\{4\}\)\(.\{4\}\)\(.\{4\}\)\(.\{12\}\)$/\1-\2-\3-\4-\5/'`
}
function parse_ib_major {
MAJOR=`echo $1 | sed 's/^.\{117\}\(.\{5\}\).*$/\1/'`
MAJOR=`echo $MAJOR | sed 's/\ //g'`
MAJOR=`echo "ibase=16; $MAJOR" | bc`
}
function parse_ib_minor {
MINOR=`echo $1 | sed 's/^.\{123\}\(.\{5\}\).*$/\1/'`
MINOR=`echo $MINOR | sed 's/\ //g'`
MINOR=`echo "ibase=16; $MINOR" | bc`
}
function parse_ib_power {
POWER=`echo $1 | sed 's/^.\{129\}\(.\{2\}\).*$/\1/'`
POWER=`echo "ibase=16; $POWER" | bc`
POWER=$[POWER - 256]
}
function parse_rssi {
LEN=$[${#1} - 2]
RSSI=`echo $1 | sed "s/^.\{$LEN\}\(.\{2\}\).*$/\1/"`
RSSI=`echo "ibase=16; $RSSI" | bc`
RSSI=$[RSSI - 256]
}
function parse_wp_battery {
BATTERY=`echo $1 | sed 's/^.\{63\}\(.\{2\}\).*$/\1/'`
BATTERY=`echo "ibase=16; $BATTERY" | bc`
}
function parse_bt_mac {
BT_MAC=`hcitool dev | grep -o '.\{17\}$'`
}
if [[ $1 == "parse" ]]; then
parse_bt_mac
packet=""
capturing=""
count=0
while read line
do
count=$[count + 1]
if [ "$capturing" ]; then
if [[ $line =~ ^[0-9a-fA-F]{2}\ [0-9a-fA-F] ]]; then
packet="$packet $line"
else
# echo "PACKET: $packet"
if [[ $packet =~ ^04\ 3E\ 2A\ 02\ 01\ .{26}\ 02\ 01 ]]; then
parse_ib_uuid "$packet"
parse_ib_major "$packet"
parse_ib_minor "$packet"
parse_ib_power "$packet"
parse_rssi "$packet"
if [[ $packet =~ ^04\ 3E\ 2A\ 02\ 01\ .{26}\ 02\ 01\ .{17}\ (30|31) ]]; then
parse_wp_battery "$packet"
fi
if [[ $2 == "-b" ]]; then
echo "$UUID $MAJOR $MINOR $POWER $RSSI $BATTERY"
else
mosquitto_pub -h test.mosquitto.org -t "ceratop" -m "{timestamp: \"$(date +%s)\", beaconId: \"$UUID\", rssi: \"-$RSSI\", scannerId: \"$BT_MAC\"}"
echo "UUID: $UUID MAJOR: $MAJOR MINOR: $MINOR POWER: $POWER RSSI: $RSSI BATTERY: $BATTERY"
fi
fi
capturing=""
packet=""
fi
fi
if [ ! "$capturing" ]; then
if [[ $line =~ ^\> ]]; then
packet=`echo $line | sed 's/^>.\(.*$\)/\1/'`
capturing=1
fi
fi
done
else
hcitool lescan 1>/dev/null &
if [ "$(pidof hcitool)" ]; then
hcidump --raw | ./$0 parse $1
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment