Skip to content

Instantly share code, notes, and snippets.

@vimagick
Last active February 6, 2024 03:35
Show Gist options
  • Save vimagick/a1cec280ae51e8b67f32f449f6e9c62d to your computer and use it in GitHub Desktop.
Save vimagick/a1cec280ae51e8b67f32f449f6e9c62d to your computer and use it in GitHub Desktop.
hcitool lescan (with 30 sec window)
#!/bin/bash
set -euo pipefail
BLE_DEV=hci0
DEDUP_WINDOW=30
MQTT_BROKER=broker.hivemq.com
MQTT_PORT=8883
MQTT_QOS=2
MQTT_TOPIC=blescan
MQTT_OPTS="--capath /etc/ssl/certs/"
MQTT_OPTS_MACOS="--cafile /etc/ssl/cert.pem"
if [[ $EUID -ne $(id -u root) ]]; then
exec sudo -iu root "$(realpath $0)"
fi
hciconfig $BLE_DEV down && hciconfig $BLE_DEV up
echo -e "# On Linux\nmosquitto_sub -h $MQTT_BROKER -p $MQTT_PORT $MQTT_OPTS -t $MQTT_TOPIC -v"
echo
echo -e "# On MacOS\nmosquitto_sub -h $MQTT_BROKER -p $MQTT_PORT $MQTT_OPTS_MACOS -t $MQTT_TOPIC -v"
echo
#stdbuf -oL hcitool -i $BLE_DEV lescan --passive --duplicates --discovery=g |
# stdbuf -oL awk -v w=$DEDUP_WINDOW 'NR>1 && systime()-a[$1]>w {a[$1]=systime(); print a[$1], $1}' |
# tee /dev/stderr |
# mosquitto_pub -h $MQTT_BROKER -p $MQTT_PORT ${MQTT_OPTS} -t $MQTT_TOPIC -l -q $MQTT_QOS
hcitool -i $BLE_DEV lescan --passive --duplicates --discovery=g >/dev/null 2>&1 &
stdbuf -oL hcidump -i $BLE_DEV -t |
stdbuf -oL awk '/HCI Event/{ts=mktime(gensub(/[T:-]/," ","g",$1"T"$2))}; /bdaddr/{addr=$2}; /RSSI/{rssi=$2;print ts,addr,rssi}' |
stdbuf -oL awk -v w=$DEDUP_WINDOW 'systime()-seen[$2]>w {seen[$2]=systime();print $1,$2,$3}' |
jq -c -R --unbuffered 'split(" ")|{"ts":.[0]|tonumber, "addr":.[1], "rssi":.[2]|tonumber}' |
tee /dev/stderr |
mosquitto_pub -h $MQTT_BROKER -p $MQTT_PORT ${MQTT_OPTS} -t $MQTT_TOPIC -l -q $MQTT_QOS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment