#!/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 [coreName]]
#
#     -log  append record to temporary directory log file and run silently,
#           else write raw record to stdout (nothing in case of error).
#
#           coreName is an (ASCII) short alphanumeric name used to build
#           a log directory path under
#               data/coreName/log/live
#           with parent directories being created as required beneath coreName.

# 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"
CORENAME=""
if [ "-log" = "$1" ]; then
     LOGGING="true"
     CORENAME="$2"
     shift 2
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 one try, with 10s timeouts, to avoid hanging if plug is off.
STATUS="$(wget -q -t 1 -T 10 "$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 [ "" != "$CORENAME" ]; then
    LOGDIR="data/$CORENAME/log/live"
fi
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/20260719-LB.log
#
# To 2026-07-19 was 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/$(date -u '+%Y%m%d')-LB.log"

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