我正在尝试在我的脚本中实现一些逻辑,但我认为我遗漏了一些东西,因为它没有像应该的那样触发。
我的想法很简单,我希望脚本能够通过管道响应同一终端中运行的另一个二进制文件的文本流。输出如下所示
Received 835186
Received 835186
over and over
我试图制定一个逻辑来只选择其中一个而不是全部。
这是我的代码
#!/bin/bash
TOGGLE="/toggle"
RUN=0
NUM2=1
lights (){
if [ ! -e $TOGGLE ]; then
#below if line i suspect is not triggering but can't see why
if [ $RUN == "0" ]; then
touch $TOGGLE
#/l-off.py
echo "off"
((RUN=RUN+1))
else
rm $TOGGLE
#/l-on.py
echo "on"
((RUN=RUN+1))
fi
fi
# togggle_func
}
timclear (){
while [ $RUN == "1" ];do
sleep 2s
RUN=0
done &
}
togggle_func () {
if [ "$RUN" -ge "$NUM2" ]; then
#RUN=0
timclear
#return
# else
# lights
fi
}
#lines below that i want to control how many times its triggered
while read line; do
if [[ "$line" == "Received 835186" ]] || [[ "$line" == "Received 818562" ]]; then
#togggle_func
lights
dt=$(date '+%r %d/%m/%Y')
echo "Light Switch Pressed at $dt"
echo "run $RUN"
echo "num $NUM2"
fi
done
我的问题仍然是,我如何让这个脚本运行管道本身,因为我现在像这样从 cli 运行它/RFSniffer | /Rf_Test2.sh
提前致谢
答案1
怎么样:
#!/bin/bash
TOGGLE="/toggle"
RUN=0
NUM2=1
RFSNIFFERCMD="/RFSNIFFER"
lights (){
if [ ! -e $TOGGLE ]; then
#below if line i suspect is not triggering but can't see why
if [ $RUN == "0" ]; then
touch $TOGGLE
#/l-off.py
echo "off"
((RUN=RUN+1))
else
rm $TOGGLE
#/l-on.py
echo "on"
((RUN=RUN+1))
fi
fi
# togggle_func
}
timclear (){
while [ $RUN == "1" ];do
sleep 2s
RUN=0
done &
}
togggle_func () {
if [ "$RUN" -ge "$NUM2" ]; then
#RUN=0
timclear
#return
# else
# lights
fi
}
#lines below that i want to control how many times its triggered
$RFSNIFFERCMD | while read line
do
if [[ "$line" == "Received 835186" ]] || [[ "$line" == "Received 818562" ]]; then
#togggle_func
lights
dt=$(date '+%r %d/%m/%Y')
echo "Light Switch Pressed at $dt"
echo "run $RUN"
echo "num $NUM2"
fi
done
关键之处在于对距离文本底部 11 行的 while 循环进行更改,以便提供信息。
如果我可以进一步批评该脚本,您似乎依赖于创建和删除文件 /toggle。这似乎是一种糟糕的状态跟踪方式,使用变量可能会更有效。至少,确保 TOGGLE 文件具有文件扩展名,并且可以写入/读取 RAMDISK(例如 Ubuntu 上的 /dev/shm)
答案2
这很难以评论的形式发布,但我试过。我想知道下面我更简单的脚本是否适合您要做的事情(并且更容易调试)。我没有使用复杂的循环,而是以秒为单位跟踪时间来处理去抖动。
#! /bin/bash
RFSNIFFERCMD="/RFSNIFFER"
DEBOUNCE=5
OLDTIME=$((`date +%s`-$DEBOUNCE))
TOGGLEFILE=/dev/shm/toggle.file
$RFSNIFFERCMD | while read line
do
if [ "$line." == "Received 835186." ] || [ "$line." == "Received 818562." ]
then
NOW=`date +%s`
if [ $(($NOW - $OLDTIME)) -lt $DEBOUNCE ]
then
echo "Ignoring change at $NOW / $OLDTIME"
elif [ -e $TOGGLEFILE ]
then
OLDTIME=$NOW
rm $TOGGLEFILE
echo "Turn On"
else
OLDTIME=$NOW
touch $TOGGLEFILE
echo "Turn Off"
fi
fi
done