2016-07-14 71 views
1

我想監視一個無限運行的命令的輸出,並且每隔一段時間打印一行。它顯示硬件按鈕的事件,每行顯示一個按鈕。如何檢測連續按下按鈕的頻率?

我的腳本在接收行時應該運行其他命令,但問題是這些行的內容不能決定必須運行哪個命令,而是給定延遲內的行數。

換句話說,用戶可以多次推動這個被監視的按鈕,並且根據按鈕被按下的頻率執行不同的命令。用戶在兩次按壓之間有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秒倒計時,並在計數超時而沒有其他事件時重置計數器並執行相應的命令。

回答

1

在執行COMMAND1之前,您可以設置一個等待所需時間的單次推送功能,記錄它的pid爲$!,並在實際收到所需時間之前的雙推時終止該功能。

這裏是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

  • 雙推:PUSH_NUM=1
  • 特里普爾推:PUSH_NUM=2
  • etc

您將擁有wait_push函數中的所有命令處理。這考慮了所有連續推送事件之間的剩餘時間(其不超過MAX_DELAYms)

+0

有趣的方法。我不知道如何修改它,而不僅僅是2次? –

+0

我用動態數字推動 –

+0

更新了答案,我很抱歉,但是有一個誤解。我不希望command1在推動次數較多時運行,command2運行次數較多,但我有很多命令(例如5個),每個按鈕次數與不同的命令相對應。 –