如何检测连续按下按钮的频率?

时间:2016-07-14 11:33:43

标签: linux multithreading bash

我想监视一个无限运行的命令的输出,并且不时地打印一行。它显示硬件按钮的事件,每行表示推送。

我的脚本在接收到行时应该运行其他命令,但问题是这些行的内容不是决定必须运行哪个命令,而是给定延迟中的行数。

换句话说,用户可以多次按下该被监视的按钮,并且将根据按下按钮的频率执行不同的命令。在根据连续按下的次数选择命令之前,用户在两次按下之间有2秒的时间。

我目前有一个具有这种结构的Bash脚本:

#!/bin/bash
lasttouch="0"

MONITORING_COMMAND
| while read line; do     
    if [ $(date +%s --date="2 seconds ago") -lt $lasttouch ]       
    then
        COMMAND2
    else
        lasttouch=$(date +%s)
        COMMAND1
    fi    
done

然而,这最多只能处理两次连续按下,并且每次事件都会执行COMMAND1,即使后续按下并且COMMAND2也应该运行。

我实际上不知道如何在Bash中正确实现这一点。我想我需要某种多线程,一个线程监听传入的线路并增加一个计数器,另一个线程在每个事件后运行倒计时2秒并重置计数器并在倒计时超时后执行适当的命令而不需要额外的事件。 / p>

1 个答案:

答案 0 :(得分:1)

您可以在执行 $scope.showOverlay = false; $scope.myData = {}; $scope.style = [{ id: "1", style: "one" }, { id: "2", style: "Two" }, { id: "3", style: "Three" }]; $scope.doClick = function (style, index) { $scope.selectedStyle = index; $scope.styleTags = style.style; $scope.showOverlay = true; } 之前为单次推送设置一个等待所需时间的函数,用COMMAND1记录其pid并在实际接收到所需时间之前的双推时将其终止。< / p>

以下是延迟700毫秒的示例:

$!

您可以增加推送号编辑变量#!/bin/bash MONITORING_COMMAND="your monitoring command here" PUSH_NUM=1 #1 => until double push detection | 2 => until triple push detection etc... MAX_DELAY=700 #the delay in between push in milliseconds inc=0 remaining_delay=0 # wait_push <command value> <time left to sleep before taking the push> wait_push() { if [ ! -z "$2" ]; then sleep $2 fi inc=0 #switch between all your command here #COMMAND0 : normal push #COMMAND1 : double push #COMMAND2 : triple push etc.. echo "push is detected here: execute $1 here" pid="" lasttouch="" } $MONITORING_COMMAND | while read line ; do current=$(($(date +%s%N)/1000000)) if [ ! -z "$lasttouch" ]; then diff=`expr $current - $lasttouch` if test $diff -lt $MAX_DELAY then inc=$((inc+1)) if [ "$inc" -lt $PUSH_NUM ]; then if [ ! -z "$pid" ]; then kill $pid 2>/dev/null wait $pid 2>/dev/null fi remaining_delay=$((remaining_delay-diff)) time=`awk -v delay=$remaining_delay 'BEGIN { print (delay / 1000) }'` #normal push wait_push "COMMAND${inc}" $time & pid=$! continue elif [ "$inc" == $PUSH_NUM ]; then if [ ! -z "$pid" ]; then kill $pid 2>/dev/null wait $pid 2>/dev/null fi wait_push "COMMAND${inc}" continue fi else inc=0 fi fi if [ "$inc" == 0 ]; then remaining_delay=$MAX_DELAY time=`awk -v delay=$MAX_DELAY 'BEGIN { print (delay / 1000) }'` #normal push wait_push "COMMAND${inc}" $time & pid=$! fi lasttouch=$current done

  • 双推:PUSH_NUM
  • tripple push:PUSH_NUM=1

您将在PUSH_NUM=2函数中进行所有命令处理。这考虑了所有连续推送事件(不超过wait_push ms)

之间的剩余时间