#!/bin/sh

# BTProximity by Thomas Kear <qupada@initng.org>
# Inspired by scripts from gentoo-wiki.com, but designed for KDE users
# No warranty expressed or implied, if it breaks you get to keep both pieces.

# TODO: make the script disconnect on exit, rather than leaving open rfcomm channel. 

DEVICE="R520m"  # Use 'hccontrol -n ubt0hci Inquiry' to find
INTERVAL="2"  # Seconds
MIN_RSSI="-9"  # Min = -10
HCITOOL="/usr/local/bin/sudo /usr/sbin/hccontrol -n ubt0hci"
DATE="date +%X"  # Format to log times in, default = HH:MM:SS (24 hour), 'date --help' for info
CONN=""


log () {
	# Log to console
	echo $1

	# Log to file
	#echo $1 >> /var/log/BTProximity.log
}

# Script to run when device leaves proximity
device_out () {
	log "`${DATE}`: Device left proximity"
	proximity="out"
	# Only change commands below this line
	dcop kdesktop KScreensaverIface lock &> /dev/null  # Start KDE Screensaver
	#amixer -c 0 cset numid=216 0 &> /dev/null &  # Mutes speakers on an audigy 2zs, will need modifying for other cards.
}

#Script to run when device enters proximity
device_in () {
	log "`${DATE}`: Device entered proximity"
	proximity="in"
	# only change commands below this line
	killall -9 kdesktop_lock 2> /dev/null &  #  Stop KDE Screensaver.  -9 might seem a bit harsh, but works fine
	#amixer -c 0 cset numid=216 1 2> /dev/null &  # Unmutes speakers, as above.
}


#  This keeps trying to connect until it succeeds, may cause a few % CPU usage, but better than failing to unlock
connect () {
	while `check_disconnected`
	do
		CONN=`${HCITOOL} Create_Connection ${DEVICE} | awk '/^Connection handle:/ {print $3;}'`
		if `check_connected`
		then
			log "`${DATE}`: Connected to ${DEVICE}"
			sleep 3  # RSSI returns stupid values if measured immediately after connecting, wait a couple of seconds
		fi
		sleep ${INTERVAL}
	done
}

#Returns 0 if connected, 1 otherwise
check_connected () {
	CONN=`${HCITOOL} Read_Connection_List | awk "/^${DEVICE}/ {print \\$2;}"`
	[ -n "$CONN" ] && return 0 || return 1
}
#Opposite of above, 1 if connected
check_disconnected () {
	CONN=`${HCITOOL} Read_Connection_List | awk "/^${DEVICE}/ {print \\$2;}"`
	[ -z "$CONN" ] && return 0 || return 1
}

proximity="in"
while :
do	
	#Connect to bluetooth device
	check_disconnected && connect
	
	#Get RSSI from bluetooth device
	rssi=`${HCITOOL} Read_RSSI ${CONN} | awk '/^RSSI:/ {print $2;}'`
	#echo "CONN=${CONN} rssi=${rssi}"
	if [ ${rssi} -le ${MIN_RSSI} ]
	then
		# Exit proximity
		[ ${proximity} = "in" ] && device_out
	else
		# Enter proximity
		[ ${proximity} = "out" ] && device_in
	fi
	
	# Wait for interval set at the top, and cycle
	sleep ${INTERVAL}
done
