#!/bin/sh

# $1 is the hostname or IP address URL stub to capture the data from,
# eg http://10.0.0.1/
HOSTSTUB=$1

# $2 is the logging directory to use.
# If not set, data will be written to stdout.
LOGDIR=$2

# $3 is the source address to connect from (eg when multi-homed).
# If not set, defaults will be used.
SOURCEADDR=$3
BA=""
if [ "" != "$SOURCEADDR" ]; then
    BA="--bind-address=$SOURCEADDR"
fi

# Capture basic live data from Enphase
# at least enough to match the simulations in
# electricity-storage-whole-household-2018.html
# ie at least storage percentage and net grid flow.
#
# Output of form:
#20180827T08:45Z consumption.readingTime 1535359490 consumption.net.wNow -1542.719 consumption.total.wNow 288.502 production.wNow 1831.22 storage.percentFull 85 storage.wNow -268 storage.readingTime 1535359340

# Also set flags in the directory indicating:
#   * exporting/spilling to grid, ie consumption.net.wNow is -ve (EXPORT.flag)
# Flags are removed in case of error.
FEXPORT=EXPORT.flag
FLAGS=$LOGDIR/$FEXPORT

RECORD=`wget -q $BA -O - $1/production.json | python3 -c "import sys, json; data=json.load(sys.stdin); print('consumption.readingTime', data['consumption'][0]['readingTime'], 'consumption.net.wNow', data['consumption'][1]['wNow'], 'consumption.total.wNow', data['consumption'][0]['wNow'], 'production.wNow', data['production'][1]['wNow'], 'storage.percentFull', data['storage'][0]['percentFull'], 'storage.wNow', data['storage'][0]['wNow'], 'storage.readingTime', data['storage'][0]['readingTime'], 'storage.whNow', data['storage'][0]['whNow']);"`
# Error if record is empty.
if [ "" = "$RECORD" ]; then rm -f $FLAGS; exit 1; fi

# Not logging to a directory?
if [ "" = "$LOGDIR" ]; then echo $RECORD; exit 0; fi

## Net import/consumption W; strictly +ve.
#IMPORTW=`echo $RECORD | awk '{if($4>0) {print $4} else {print 0}}'`
## If exporting create FEXPORT if absent, else remove FEXPORT.
#if [ "$IMPORTW" -ge "0" ]; then rm -f $LOGDIR/$FEXPORT; else
  #  if [ ! -f $LOGDIR/$FEXPORT ]; then touch $LOGDIR/$FEXPORT; fi
#fi

# Net export W; strictly +ve.
# Clamped to zero unless exporting more than 'noise' export threshold.
# Greater than dump load (~16W) to/from off-grid system + 5W ACB margin,
# Implies that batteries are full or filling as fast as possible.
# DHD20210614: until today ET=25, now raising it until off-grid effect ~10%.
# to avoid flapping when close to balance.
ET=125
EXPORTW=`echo $RECORD | awk '{if($4 > -'$ET') {print 0} else {print int(-$4)}}'`
# If exporting create FEXPORT if absent, else remove FEXPORT.
if [ "$EXPORTW" -le "0" ]; then rm -f $LOGDIR/$FEXPORT; else
    if [ ! -f $LOGDIR/$FEXPORT ]; then touch $LOGDIR/$FEXPORT; fi
fi

TARGETFILE=`date -u +%Y%m%d`.log
DATA="`date -u +%Y%m%dT%H:%MZ` $RECORD"
echo $DATA >> ${LOGDIR}/${TARGETFILE}

exit 0
