检查网络上的设备连接,然后根据连接发送操作

时间:2015-12-18 17:50:37

标签: bash raspberry-pi kodi

即使我有一些经验,我对bash脚本也相当新。

我正在寻找我的Raspberry Pi来检测我的手机,当它在网络上可用时,当它播放音频片段时,我已通过下面的脚本管理。

我有一个问题,但是,当我的手机在网络上可用时,我不希望音频保持循环;我需要它播放一次,然后一旦播放完就停止播放音频剪辑。但是,我确实希望脚本继续运行,以便下次我的手机在网络上可用时检测到。

也许有更好的方法,如果有,我很想听听你的建议。

#!/bin/sh

if ping -c 10 192.168.1.4 &> /dev/null
then
    kodi-send --action="PlayMedia(/storage/music/welcome.mp3)"
    ping 192.168.1.4 &> /dev/null
else
    ./checkforerikphone.sh
fi

2 个答案:

答案 0 :(得分:3)

试试这个

#!/bin/bash

while : ; do
    if ping -c 10 192.168.1.4 &> /dev/null ; then
       kodi-send --action="PlayMedia(/storage/music/welcome.mp3)"
    fi
    sleep 600  
done

此解决方案永远运行while :。每10分钟检查一下您的手机是否处于活动状态。因此,这可以显着降低您生活中的噪音,但它也可以让您知道手机仍处于连接状态。

您可以将sleep 600更改为sleep 300并每5分钟检查一次,或者您当然可以将600更改为您可以使用的任意秒数。

根据您的规范,这不是一个完美的解决方案,但管理锁定文件可能很复杂。 熟悉这个解决方案,然后考虑添加像

这样的东西
 if ping ... ; then
   if ! [[ -e /tmp/phoneOnLine ]] ; then
     kodi-send ...
     echo "Found phone at $(date)" > /tmp/phoneOnLine
   fi
else
    echo "no phone found"
    /bin/rm -f /tmp/phoneOnLine
fi

您肯定会发现这不起作用的极端情况,因此请准备好调试代码。我会在每个逻辑路径(if / else / ...)中添加echo msg。了解代码是如何工作的。

另外为了防止脚本被伪造,我会在启动时删除该文件。

所以可能的完整解决方案是

#!/bin/bash

#file may not exist, ignore error msg with "2> /dev/null"
/bin/rm -f /tmp/phoneOnLine 2> /dev/null

#loop forever   
while : ; do
    # check for phone
    if ping -c 10 192.168.1.4 &> /dev/null ; then
        # check for "lock" file
        if ! [[ -e /tmp/phoneOnLine ]] ; then
           kodi-send --action="PlayMedia(/storage/music/welcome.mp3)"                              
           echo "Found phone at $(date)" > /tmp/phoneOnLine
        else
           echo "Phone already found" 
        fi   # !! -e /tmp/ph
    else     # no ping
         echo "no phone found"
         /bin/rm -f /tmp/phoneOnLine 2>/dev/null
    fi       # ping
    sleep 600  
done

答案 1 :(得分:2)

请尝试以下操作:

#!/bin/bash

#when result of ping $? is 0, the phone is detected
ACTIVE=0

#default startup as NOT ACTIVE(not detected) => !0
pre_available=1

# loop forever
while :
do
    #ping and store outcome in "available"
    ping -c 10 192.168.0.8 > /dev/null
    available=$?    
    #if phone was not active and just got active (detected)
    if [[ "$pre_available" != "$ACTIVE"  && "$available" == "$ACTIVE" ]]
    then
        #do your stuff
        kodi-send --action="PlayMedia(/storage/music/welcome.mp3)"              
    fi
    #store availability for next iteration
    pre_available=$available
done
相关问题