#!/bin/bash # bluetooth device to check DEVICE="00:00:00:00:00:00" # seconds between each signal check in normal mode NEAR_CHECK_INTERVAL=4 FAR_CHECK_INTERVAL=4 # seconds to wait to recheck near or far signal before running commands NEAR_RECHECK_INTERVAL=0.5 FAR_RECHECK_INTERVAL=0.5 # times to run the recheck NEAR_RECHECK_TIMES=1 FAR_RECHECK_TIMES=3 # rssi threshold between near and far THRESHOLD=-16 # commands to run when state changes FAR_COMMAND='/usr/bin/gnome-screensaver-command --activate' # command to run when device goes out of range NEAR_COMMAND='/usr/bin/gnome-screensaver-command --deactivate' # command to run when device comes into range connected=0 function connect { connected=0 for s in `hcitool con`; do if [ "$s" == "$DEVICE" ]; then connected=1; fi done if [ $connected -eq 0 ]; then echo "Attempting connection..." if [ -z "`hcitool cc $DEVICE 2>&1`" ] || [ -z "`l2ping -c 2 $DEVICE 2>&1`" ]; then echo "Connected." connected=1 else echo "ERROR: Cannot connect to device $DEVICE." connected=0 fi fi } connect while [ $connected -eq 0 ]; do connect sleep 3 done echo "Monitoring proximity of device $DEVICE"; let prox=$NEAR_RECHECK_TIMES+1 while [ -z "" ]; do connect if [ $prox -gt 0 ]; then int=$NEAR_CHECK_INTERVAL else int=$FAR_CHECK_INTERVAL fi badsig=0 if [ $connected -eq 1 ]; then str="RSSI return value: " rssi=`hcitool rssi $DEVICE | grep "$str" | sed -e "s/$str//g"` if [ $rssi -le $THRESHOLD ]; then badsig=1 elif [ $rssi -ge $[$THRESHOLD+2] ] && [ $prox -le $NEAR_RECHECK_TIMES ]; then if [ $prox -eq $NEAR_RECHECK_TIMES ]; then $NEAR_COMMAND > /dev/null 2>&1 let prox=$NEAR_RECHECK_TIMES+1 else int=$NEAR_RECHECK_INTERVAL if [ $prox -le 0 ]; then let prox=1 else let prox++ fi fi fi if [ $prox -gt 0 ]; then echo "RSSI = $rssi, device is within proximity." else echo "RSSI = $rssi, device is out of proximity." fi else badsig=1 fi if [ $badsig -eq 1 ] && [ $prox -ge -$FAR_RECHECK_TIMES ]; then if [ $prox -eq -$FAR_RECHECK_TIMES ]; then $FAR_COMMAND > /dev/null 2>&1 let prox=-$FAR_RECHECK_TIMES-1 else int=$FAR_RECHECK_INTERVAL if [ $prox -ge 0 ]; then let prox=-1 else let prox-- fi fi fi sleep $int done