回家/离家检测

2023年3月24日 · 274 字 · 1 分钟

如何检测回家/离家…

所需器材:

  • Raspberry 4B

在 Raspberry 上起一个服务,每分钟 ping 一下手机,如果 ping 的结果:从不成功到成功,则表示回家; 从成功到不成功,则表示离家。有点粗糙,但是简单易实现。

#!/bin/bash

token=${ding_token}
echo "$(date +%Y-%m-%d\ %H:%M:%S) [${token}]"

FILE="/tmp/at_home"
[ -f "$FILE" ] && old=1 || old=0
echo "$(date +%Y-%m-%d\ %H:%M:%S) : old =  ${old}"

ret=$(ping -W 1 -c 5  192.168.2.88)
echo ${ret}
echo "---"

[[ "${ret}" == *"100% packet loss"* ]] && now=0 || now=1
echo "$(date +%Y-%m-%d\ %H:%M:%S) : now = ${now}"

if [ ${old} == 1 ]; then
    # 上次结果在家
    if [[ ${now} == 0 ]]; then
        # 这次结果不在家
        echo $(date +%Y-%m-%d\ %H:%M:%S) ": Leave Home"
        curl -s "https://oapi.dingtalk.com/robot/send?access_token=${token}" \
            -H 'Content-Type: application/json' \
            -d "{\"msgtype\": \"text\",\"text\": {\"content\":\"[HA] Leave Home!!!\"}}"
        rm ${FILE}
    else 
        echo $(date +%Y-%m-%d\ %H:%M:%S) ": At home"
    fi
else
    # 上次结果不在家
    if [[ ${now} == 0 ]]; then
        # 这次结果不在家
        echo $(date +%Y-%m-%d\ %H:%M:%S) ": Not at home"
    else 
        echo $(date +%Y-%m-%d\ %H:%M:%S) ": Back home"
        curl -s "https://oapi.dingtalk.com/robot/send?access_token=${token}" \
          -H 'Content-Type: application/json' \
          -d "{\"msgtype\": \"text\",\"text\": {\"content\":\"[HA] Back Home!!!\"}}"
        touch ${FILE}  
        # 可以打开电视了 :)
    fi
fi

echo ""