I have not quite figured out how to do this, but this is how I got around it. I simply wait 5 seconds after the sudo rfcomm connect 0 AA:BB:CC:DD:EE:FF 10
command, and then I check to see if there is a connection. I suspect that this actually works perfectly, as the next iteration will catch any mistakes made, but don't quote me on it. Perhaps a more experience . I have included the minimal working example (MWE) so you can follow it.
MWE:
#!/bin/bash
phone1="AA:BB:CC:DD:EE:FF" #Address of phone
inside=1 # Whether the phone is 'inside' the house (0) or 'outside (1)
phoneDetected ()
{
# Search for phone
hcitool rssi $phone1 &>/dev/null
ret=$?
# If search was unsuccessful,
if [ $ret -ne 0 ]
then
# Add phone
sudo rfcomm connect 0 $phone1 10 &>/dev/null &
# Note: the return code of rfcomm will almost always be 0,
# so don't rely on it if you are looking for failed connections,
# instead wait 5 seconds for rfcomm to connect, then check
# connection again. Note this is not fool proof as an rfcomm
# command taking longer than 5 seconds could break this program,
# however, it generally only takes 2 seconds.
sleep 5
hcitool rssi $phone1 &>/dev/null
ret=$?
fi;
# Case 1) we are now connected (ret=0) and we were previously outside (inside=1)
if [ $ret -eq 0 ] && [ $inside -eq 1 ]
then
# change state to inside and do something (I am playing a song)
inside=0
mplayer /home/pi/documents/rasbpi/raspi1/media/audio/1.mp3 &>/dev/null
# Case 2) we are no longer connected (ret=1) but we were previously inside (inside=0)
elif [ $ret -eq 1 ] && [ $inside -eq 0 ]
then
# change state to outside and do something (I am playing another song)
inside=1
mplayer /home/pi/documents/rasbpi/raspi1/media/audio/2.mp3 &>/dev/null
fi;
}
# run an infinite loop
while :
do
phoneDetected $phone1
done