#!/bin/sh

# temper - report temperature and humidity from PCsensor USB temper sensors
# version 1.0
# Requires the "read-all" command

# Generates output that looks like
#   /dev/hidraw1    TEMPerV1.2      23.62   XX
#   /dev/hidraw3    TEMPer2HumiV1.x 24.09   29.3
# Which is device path, type, temperature in Celsius, humidity in %
# If humidity is not available from the device, it prints XX

# The -f option prints temperatures in Fahrenheit

# Uses the read-all command to collect the actual data
# by EdorFaus from the TEMPered package
#   which is likely linux-only - uses libusb, HIDAPI
# https://github.com/edorfaus/TEMPered
# Which seems to me to be the best software for reading PCsensor devices

# temper is a quick hack written to produce easy to parse output
# be used with the check_temper Nagios plugin

# https://www.syonex.com/resources/software/
# John Sellens jsellens@syonex.com
# Use as you wish, provided "AS IS", no warranties


# One could argue that this should be in C and not use read-all at all


PATH=/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/sbin:/usr/sbin
export PATH

myname=`basename "$0"`
umask 022

tfile="/tmp/$myname.$$" 
trap "rm -f '$tfile'" EXIT

err=0

logerr() {
    if [ $# -gt 0 ]; then
	logger -t "$myname" -p user.error -- "$$ - $@"
    else
	xargs -L 1 -r logger -t "$myname" -p user.error -- "$$ -"
    fi
}

error() {
    echo 1>&2 "$myname:" "$@"
    logerr "$@"
    err=1
}

fatal() {
    error "$@"
    exit 1
}

usage() {
    fatal "usage: $myname [-f]"
}

f="no"
if [ "$1" = "-f" ]; then
    f="yes"
    shift
fi
if [ $# -gt 0 ]; then
    usage
fi

read-all >"$tfile" 2>&1
if [ $? -ne 0 ]; then
    cat 1>&2 "$tfile"
    fatal read-all failed
fi

awk -v f="$f" < "$tfile" '
    BEGIN { CONVFMT = "%.2f"; }
    /^Device / {
	if ( devname != "" ) { printf "\t%s\t%s\n", temp, hum; }
	devname = $2;
	temp="XX"
	hum="XX"
	printf "%s", devname;
	next;
    }
    /Device type name/ { printf "\t%s", $NF; }
    $1 == "Temperature:" {
	temp = $2;
	sub( /[^0-9]*C$/, "", temp );
	if ( f == "yes" ) {
	    temp = temp * 9 / 5 + 32;
	}
    }
    $1 == "Humidity:" { hum = $2; sub( /%RH/, "", hum ); }
    END {
	if ( devname != "" ) { printf "\t%.2f\t%s\n", temp, hum; }
    }
    '

exit 0
