#!/bin/bash
# A script to log s-meter readings.

# Need this option to make the final command in the pipe run in the current shell.
shopt -s lastpipe

# Set the frequency and mode:
echo 'F 3920000' | nc -q 1 localhost 4532
echo 'M AM 6000' | nc -q 1 localhost 4532

while :
do
    dBr=0;
    # Take the running average of 10 signal strength measurements
    for i in {1..10}
    do    
        # Read the signal strength meter, which is dB relative to S9.
        echo 'l STRENGTH' | nc -q 1 localhost 4532 | read dBr_new
        #dBr=$dBr_new
        # Echo to stdout.
        #echo "$dBr"
        
        if (($i==1))
        then
            # If this is the first measurement, no need to average.
            dBr=$dBr_new
            #echo "$dBr"
        else
            # bash can't do floating point arithmetic, so use awk to calculate the average.
            dBr_ave=`awk "BEGIN {print ($dBr+$dBr_new)/2}"`
            #echo "$dBr" $dBr_new $dBr_ave
            # Update dBr.
            dBr=$dBr_ave
        fi
        #echo "$dBr"
        
        # Wait 6s.
        sleep 6
    done
    # Echo 60s average to stdout.
    echo "Filtered average: $(date --utc +%H:%M), $dBr"
    # Append to a log file.
    echo "$(date --utc +%H:%M), $dBr" >> log-$(date --utc +%F).csv
done
