From 4f6ee9d2e2010a061652a3337f7a5503bac9f6c0 Mon Sep 17 00:00:00 2001 From: Level2 Pidor Date: Fri, 29 Jan 2016 23:27:11 +0100 Subject: [PATCH] do floating average of people present. OMG in bash? how dare you? --- scripts/peoplecounter-realtime.sh | 62 ++++++++++++++++++++++++++++--- 1 file changed, 56 insertions(+), 6 deletions(-) diff --git a/scripts/peoplecounter-realtime.sh b/scripts/peoplecounter-realtime.sh index a5cbe31..cc80e4a 100755 --- a/scripts/peoplecounter-realtime.sh +++ b/scripts/peoplecounter-realtime.sh @@ -1,27 +1,77 @@ #!/bin/bash #update peoplecounter number in realtime #but: this is too intrusive. should only update when the count of -@ people has not changed for a certain time +# people has not changed for a certain time +if [ "$(basename $0)" = "peoplecounter-realtime-dev.sh" ] +then # switch between dev and prod config dynamically by script name + DEV="-dev" +else + DEV="" +fi +STATSFILE="/run/peoplecounter$DEV" +SAMPLES=12 # how many records to keep in file +INTERVAL=10 # how long to wait between polls +MAXFILE="/run/peoplecountermax$DEV" +PRESENCY="/run/presency$DEV" # value shown on website +# /run/peoplecounter lists all recent reads, newest at end +# let's have some management functions instead of a database +if [ ! -f "$STATSFILE" ] +then + touch "$STATSFILE" +fi +function getmaxpeople() { + awk 'BEGIN {v=0} + $1 > v {v=$1} + END {print v}' "$STATSFILE" +} +function getaveragepeople() { + awk 'BEGIN {t=n=0} + {t+=$1 + n++} + END {print int(t/n+0.4)}' "$STATSFILE" +} +function getlastpeople() { + awk 'BEGIN{v=0} + {v=$1} + END{print v}' "$STATSFILE" +} +function addcount() { + awk -v new="$1" -v samples="$SAMPLES" -v stats="$STATSFILE" ' + BEGIN{n=0} + {p[++n]=$1} + END{ + p[++n]=new + n++ # yes you can do off by 1 errors in awk + start=n-samples + if(start<1) {start=1} + for(i=start;i stats # welcome to awk world + } + } + ' "$STATSFILE" +} PEOPLECOUNTERIP=$(cat $(dirname "$0")"/peoplecounterip.txt") state="online" while true do + # scrape new value p="$( wget -qO - "http://$PEOPLECOUNTERIP/output.cgi?t=$(date +%s)" | sed 's/.*Occupancy://'| awk '{print $2}')" - if [ "$p" != "" ] + if [ "$p" != "" ] # oh we got something then - oldp="$(cat /run/peoplecounter)" - echo "$p" > /run/peoplecounter + oldp="$(getlastpeople)" + addcount "$p" if [ "$p" != "$oldp" ] then logger $(basename $0) changed from $oldp to $p people if [ "$p" -gt "$oldp" ] then - echo "$p" > /run/peoplecountermax + echo "$p" > "$MAXFILE" fi fi + getaveragepeople > "$PRESENCY" if [ "$state" = "offline" ] then state="online" @@ -34,5 +84,5 @@ do logger $(basename $0) people counter offline fi fi - sleep 10 + sleep "$INTERVAL" done