2013-10-01 85 views
1

我正在嘗試使用藍牙加密狗(並非試圖做任何事情破壞地球,只是確定我的手機在該地區),將手機連接到我的RaspberryPi。如果我將手機的藍牙設置爲併發出以下命令,我會得到以下輸出(在任何人開始向我講述這是如何破壞安全性之前,讓我提醒您,那是而不是我的實際電話藍牙ID):使用rfcomm檢查連接是否成功

命令:

sudo rfcomm connect 0 AA:BB:CC:DD:EE:FF 10 
echo $? 

輸出:

Connected /dev/rfcomm0 to AA:BB:CC:DD:EE:FF on channel 10 
Press CTRL-C for hangup 
0 

現在,如果我將手機的藍牙關閉,併發出相同的命令,我會得到以下輸出(同樣,所有ID已被更改以保護無辜者)。

命令:

sudo rfcomm connect 0 AA:BB:CC:DD:EE:FF 10 
echo $? 

輸出:

Can't connect RFCOMM socket: Host is down 
0 

因爲我試圖確定當手機在房間裏,它離開的時候,我需要一些方法(一些其他方式)檢測加密狗何時可以連接並且無法連接。我該如何去實現這個目標? (注:我嘗試從建築物拆卸手機,甚至完全關閉它)

編輯:我已經考慮捕捉stderr消息,像這樣

error=$`sudo rfcomm connect 0 AA:BB:CC:DD:EE:FF 10 >/dev/null` & 
if [ $error=="Can't connect RFCOMM socket: Host is down" ] 
then 
    ... 
fi; 

測試它,但問題是, rfcomm必須在後臺運行。

回答

2

我還沒弄清楚如何做到這一點,但這是我如何解決它的。我只需在sudo rfcomm connect 0 AA:BB:CC:DD:EE:FF 10命令之後等待5秒鐘,然後檢查是否有連接。我懷疑這實際上是完美的,因爲下一次迭代會捕獲任何錯誤,但不要引用它。也許更多的經驗。我已經包含了最低工作示例(MWE),以便您可以遵循它。

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