#!/bin/sh
# Poll for power (and other) readings as JSON from
# the Local Bytes smart power monitoring plug.
# Write to stdout or log to a temporary file.
#
# One use is to poll from cron every minute and log to temporary file(s).

# Usage:
#     $0 [-log]
#
#     -log  append record to temporary directory log file and run silently,
#           else write raw record to stdout (nothing in case of error).

# Should be efficient so that it can be left running for hours or days.
# Should be robust in case of the plug going off-line etc.

LOGGING="false"
if [ "-log" = "$1" ]; then
     LOGGING="true"
     shift
fi

# Get Base URL for the plug.
# We don't publish this IP address for marginal security gain!
BaseURL="`cat script/.private/LB_monitoring_plug_base_URL.txt`"
if [ "" = "$BaseURL" ]; then
    echo "ERROR: missing BaseURL" 1>&2
    exit 1
fi

# Part URL to poll for JSON power values.
PartURLPower="cm?cmnd=Status%208"

# Fetch status.
# At most two tries, with 15s timeouts, to avoid hanging if plug is off.
STATUS="`wget -q -t 2 -T 15 $BaseURL$PartURLPower -O -`"

# Exit with an error code if status could not be fetched.
if [ "" = "$STATUS" ]; then exit 1; fi

# If not logging, write to stdout and exit.
if [ "true" != "$LOGGING" ]; then
    echo "$STATUS"
    exit 0
fi

# If logging, directory to log to.
LOGDIR=data/.private/tmp
if [ ! -d "$LOGDIR" ]; then
    mkdir -p $LOGDIR
fi
if [ ! -d "$LOGDIR" ]; then
    echo "ERROR: cannot find/create LOGDIR $LOGDIR" 1>&2
    exit 1
fi

# Append record of this form:
#     2022-10-10T13:31:56Z {"StatusSNS":{"Time":"2022-10-10T14:31:56","ENERGY":{"TotalStartTime":"2022-10-05T19:17:26","Total":0.003,"Yesterday":0.000,"Today":0.003,"Power": 0,"ApparentPower": 0,"ReactivePower": 0,"Factor":0.00,"Voltage":247,"Current":0.000}}}
# to daily log file of form:
#    data/.private/tmp/LBplug-2022-10-10.log
#
# Note that the timestamp has precision of 1 second.
TIMESTAMP="`date -u '+%Y-%m-%dT%H:%M:%SZ'`"
FILE="$LOGDIR/LBplug-`date -u '+%Y-%m-%d'`.log"

echo "$TIMESTAMP $STATUS" >> $FILE
exit 0
