#!/usr/bin/env bash
# This script updates graphs for power usage of the BabyRack.
# # Steve Jones 2026-10-14

# Address of the Shelly PM Mini v3.
export Shelly_IP="192.168.1.197"

# cd to where the script and data exist.
export DataFolder="$( dirname -- "${BASH_SOURCE[0]}" )"
cd ${DataFolder}

# Where is the RRD File?
export RRD_File="${DataFolder}/Shelly_Power.rrd"

# Query for Power being used at the moment
export Power=$(curl -s http://${Shelly_IP}/rpc/Shelly.GetStatus | jq -r '.["pm1:0"].apower')

# Update RRD with the single value
rrdtool update "${RRD_File}" "N:${Power}"

generate_graph() {
  local time_frame=$1
  local output_file=$2
  local title=$3
  local rlabel=$4
  local rscale=$5

  rrdtool graph "${output_file}" \
    --start "${time_frame}" \
    --title "${title}" \
    --units-exponent 0 \
    --vertical-label "Watts" \
    --right-axis-label "${rlabel}" \
    --right-axis-format "%6.2lf" \
    --right-axis "${rscale}:0" \
    --width 800 --height 240 \
    --slope-mode \
    DEF:p="${RRD_File}":power:AVERAGE \
    LINE2:p#00FF00:"Power (W) " \
    GPRINT:p:LAST:"Current\:%6.1lf W" \
    GPRINT:p:AVERAGE:"Avg\:%6.1lf W" \
    GPRINT:p:MAX:"Max\:%6.1lf W\l"
}

# Generate the 4 power graphics
generate_graph "-1day" \
	"Shelly_Daily.png" \
	"Baby Rack Daily Power (24 hours)" \
	"Cost per Day (¢)" \
	"0.239976"

generate_graph "-1week" \
	"Shelly_Weekly.png" \
	"Baby Rack Weekly Power (7 days)" \
	"Cost per Week ($)" \
	"0.016798"

generate_graph "-1month" \
	"Shelly_Monthly.png" \
	"Baby Rack Monthly Power (30 days)" \
	"Cost per Month ($)" \
	"0.0719928"

generate_graph "-1year" \
	"Shelly_Yearly.png" \
	"Baby Rack Yearly Power (365 days)" \
	"Cost per Year ($)" \
	"0.875912"

# Cost of 1KWh of electricity in cents (¢)=9.99999 from my bill.
# The scaling number as the last argument to of the 'generate_graph'
# script is;
#  9.99999 * 24 / 1000 = 0.239976 # Cents per day divided by 1000 (KWh)
# 0.239976 * 7 / 100 = 0.016798   # Cents per week, divided for dollars
# 0.239976 * 30 / 100 = 0.719928  # Cents per month, div for dollars
# 0.239976 * 365 / 100 = 0.875912 # Cents per year, div for dollars
