do floating average of people present. OMG in bash? how dare you?

master
Level2 Pidor 2016-01-29 23:27:11 +01:00
parent 668081a828
commit 4f6ee9d2e2
1 changed files with 56 additions and 6 deletions

View File

@ -1,27 +1,77 @@
#!/bin/bash #!/bin/bash
#update peoplecounter number in realtime #update peoplecounter number in realtime
#but: this is too intrusive. should only update when the count of #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<n;i++) {
print p[i] > stats # welcome to awk world
}
}
' "$STATSFILE"
}
PEOPLECOUNTERIP=$(cat $(dirname "$0")"/peoplecounterip.txt") PEOPLECOUNTERIP=$(cat $(dirname "$0")"/peoplecounterip.txt")
state="online" state="online"
while true while true
do do
# scrape new value
p="$( p="$(
wget -qO - "http://$PEOPLECOUNTERIP/output.cgi?t=$(date +%s)" | wget -qO - "http://$PEOPLECOUNTERIP/output.cgi?t=$(date +%s)" |
sed 's/.*Occupancy://'| sed 's/.*Occupancy://'|
awk '{print $2}')" awk '{print $2}')"
if [ "$p" != "" ] if [ "$p" != "" ] # oh we got something
then then
oldp="$(cat /run/peoplecounter)" oldp="$(getlastpeople)"
echo "$p" > /run/peoplecounter addcount "$p"
if [ "$p" != "$oldp" ] if [ "$p" != "$oldp" ]
then then
logger $(basename $0) changed from $oldp to $p people logger $(basename $0) changed from $oldp to $p people
if [ "$p" -gt "$oldp" ] if [ "$p" -gt "$oldp" ]
then then
echo "$p" > /run/peoplecountermax echo "$p" > "$MAXFILE"
fi fi
fi fi
getaveragepeople > "$PRESENCY"
if [ "$state" = "offline" ] if [ "$state" = "offline" ]
then then
state="online" state="online"
@ -34,5 +84,5 @@ do
logger $(basename $0) people counter offline logger $(basename $0) people counter offline
fi fi
fi fi
sleep 10 sleep "$INTERVAL"
done done