#!/bin/sh

# Script to dump current temperature value 
export PATH="${PATH}:/ciena/bin:/ciena/scripts"
SAROSREG="$(which sarosreg)"
SARNREG="$(which sarnreg)"
DEVTREE_MODEL="/sys/firmware/devicetree/base/model"

saros_temp()
{
	local t
	t=$(${SAROSREG} "${1}" | tail -n 1)
	t=${t##* }
	[ "$((t))" -lt 128 ] || t=$((t - 256))
	echo -n "$((t))"
}

sarn_temp()
{
	local t
	t=$(${SARNREG} "${1}" | tail -n 1)
	t=${t##* }
	[ "$((t))" -lt 128 ] || t=$((t - 256))
	echo -n "$((t))"
}

brdname="$(tr -d '\0' <$DEVTREE_MODEL)" 2> /dev/null || brdname=""
case "${brdname}" in
3922*|3924*|3926*|3928*) ;;
default)
	echo "Unsupported board type '${brdname}'" >&2
	exit 1
esac

# Query the current temp values of the zynqmp temp sensors exposed via sysfs
echo "ZynqMp temps:"
for f in temp0_ps temp1_remote temp2_pl ; do
	# Read to raw value of the temp sensor
	raw=$(cat "/sys/devices/platform/amba/ffa50000.ams/iio:device0/in_${f}_temp_raw")
	# Convert to Celsius * 10M using on-chip ref transfer function
	# See ug580 "UltraScale Architecture System Monitor" for the ADC
	# transfer functions for the SYSMONE4 temperature sensors. The
	# PS uses an internal reference. We assume the PL does as well.
	temp10M=$(( ((raw * 5093140064)/(1 << 16)) - 2802308787 ))
	# Round to 2 decimal digits
	temp10M=$(( temp10M + 50000))
	# Get 2 digits of decimal
	decimalT=$(( (temp10M/100000) % 100 ))
	# Get integer portion
	integerT=$(( temp10M/10000000 ))
	case "${f}" in
	temp0_ps)	type="LPD" ;;
	temp1_remote)	type="FPD" ;;
	temp2_pl)	type="PL" ;;
	esac

	printf "%s\t%u.%02u C\n" "${type}" "${integerT}" "${decimalT}"
done

# If we have a sarosreg command query the temp sensors connected to the fpga
[ -x "${SAROSREG}" ] && {
	echo
	echo "Saros temps:"
	for f in $(seq 0 4) ; do
		lTemp=$(saros_temp SAROS_TEMP_DATA${f}.LOCAL)
		rTemp=$(saros_temp SAROS_TEMP_DATA${f}.REMOTE)
		printf "%s\tlocal\t%5d C\tremote\t%5d C\n" "DATA${f}" "${lTemp}" "${rTemp}"
	done
}

# If we have a sarnreg command and sarnreg finds a sarn device then
# query the temp sensors connected to the fpga
[ -x "${SARNREG}" ] && $(${SARNREG} > /dev/null 2>&1) && {
	echo
	echo "Sarn temps:"
	for f in $(seq 0 3) ; do
		lTemp=$(sarn_temp SARN_TEMP_DATA${f}.LOCAL)
		rTemp=$(sarn_temp SARN_TEMP_DATA${f}.REMOTE)
		printf "%s\tlocal\t%5d C\tremote\t%5d C\n" "DATA${f}" "${lTemp}" "${rTemp}"
	done
}
