#!/bin/sh
#
# Version 25226
#
# You can add this script to your cron tab to periodically update the Reactor System entity
# with some Pi-specific measurements (stored in extended attributes).
#
# ***NOTE*** If you have user authentication enabled, your ACL configuration may interfere
#            with this script. Please see the documentation for user authentication for information.
#
# Ref: https://www.raspberrypi.org/documentation/raspbian/applications/vcgencmd.md
#

RD=${REACTOR_DATA_PREFIX:-.}

LOG=/tmp/rpi-status.log

[ -t 1 ] && echo "Running in interactive mode (stdout is a TTY)"

[ -f ${RD}/storage/baseurl.sh ] && . ${RD}/storage/baseurl.sh  # load REACTOR_BASEURL hint file
[ -f ./config/baseurl.sh ] && . ./config/baseurl.sh
[ -t 1 ] && echo "BASEURL=${REACTOR_BASEURL}"

# System temperature
temp=$( vcgencmd measure_temp | sed -e "s/^.*=\(.*\)'.*/\\1/" )
[ -t 1 ] && echo "System temperature: ${temp}"
curl -k -L -s -q -o - \
    "${REACTOR_BASEURL:-http://127.0.0.1:8111}/api/v1/entity/reactor_system>system/attribute/x_reactor_system_extra.sys_temp/set?value=$temp&type=real" >${LOG} 2>&1

# CPU core voltage (normally 0.85 on my RPI4)
temp=$( vcgencmd measure_volts core | sed -e "s/^.*=\(.*\)V.*/\\1/" )
[ -t 1 ] && echo "      Core voltage: ${temp} (0.85V is nominal)"
curl -k -L -s -q -o - \
    "${REACTOR_BASEURL:-http://127.0.0.1:8111}/api/v1/entity/reactor_system>system/attribute/x_reactor_system_extra.sys_cpu_volts/set?value=$temp&type=real" >>${LOG} 2>&1

# Throttling (ref: https://www.raspberrypi.com/documentation/computers/os.html#vcgencmd)
temp=$( vcgencmd get_throttled | sed -e "s/^.*=\(.*\)/\\1/" )
[ -t 1 ] && echo " Raw throttle bits: ${temp}"
temp=$(( temp & 0xffff ))  # we only care about lower 16 bits (current); upper is historical.
curl -k -L -s -q -o - \
    "${REACTOR_BASEURL:-http://127.0.0.1:8111}/api/v1/entity/reactor_system>system/attribute/x_reactor_system_extra.sys_throttled/set?value=$temp&type=int" >>${LOG} 2>&1

# Other things/queries we could do: "measure_volts sdram_[cip]" (core, I/O, phy), "measure_clock (arm|core)"
