#!/bin/sh
# Extracts just timestamp and "Power" value from stdin.
# Output should be suitable to feed to (eg) gnuplot.
# DHD20221010: allows for the power to have a fraction part.
#
# Usage:
#     $0 [-pf]
#
#         -pf  add power-factor extra trailing value

DOPF=false
if [ "-pf" = "$1" ]; then
    DOPF=true
fi

# Sample input:
#2022-10-10T09:46:01Z {"StatusSNS":{"Time":"2022-10-10T10:46:02","ENERGY":{"TotalStartTime":"2022-10-05T19:17:26","Total":3.054,"Yesterday":1.230,"Today":0.027,"Power":102.0,"ApparentPower":102.0,"ReactivePower":0.0,"Factor":1.00,"Voltage":249,"Current":0.410}}}

# Run something like:
#% cat LBplug-2022-10-10.log.gz | sh ./powerExtractZ.sh > input.dat

if [ "false" = "$DOPF" ]; then

# Sample output:
#2022-10-10T09:46:01Z 102.0

    # Retain the timestamp.
    # Discard everything else other than the Power decimal.
    exec sed -e 's/ {.*"Power": *\([0-9][0-9.]*\),.*$/ \1/'

else

# Sample output:
#2026-07-20T13:51:55Z 29.3 0.98
#2026-07-20T14:52:06Z 28.6 0.94

    exec awk '{
        datetime=$1
        wherepower=match($2, /"Power":*[0-9][0-9.]*,/);
        power=substr($2, wherepower+8, RLENGTH-9);
        wherefactor=match($2, /"Factor":*[0-9][0-9.]*,/);
        factor=substr($2, wherefactor+9, RLENGTH-10);
        print datetime, power, factor
        }'

fi
