#!/usr/bin/env python
# coding: utf-8
"""\
Usage: temper-temper-log

Reads 'temper-poll -c' for room temperature data.  Writes the temperature
found to stdout on one line, preceded by the Unix UTC time in seconds
and the Log source ID.

Before you can use this utility you must have a TEMPer USB thermometer
plugged in, and the temper-python package must be installed and configured.
See their documentation for that procedure.

Sample log from a TEMPer:

1471573103 TEMPER 37.000
1471573104 TEMPER 37.000
1471573105 TEMPER 37.000

Field 1: Unix UTC time in seconds
Field 1: Log source (TEMPER)
Field 3: CPU temperature in degrees C

Sample crontab usage:

# take and log CPU temp every 5 minutes
*/5 * * * * /usr/local/sbin/temper-temp-log >> /var/log/ntpstats/temps

"""

from __future__ import print_function

import time
import subprocess

# sadly subprocess.check_output() is not in Python 2.6
proc = subprocess.Popen(["temper-poll", "-c"],
                        stdout=subprocess.PIPE,
                        stderr=subprocess.STDOUT,
                        universal_newlines=True)
output = proc.communicate()[0]

now = int(time.time())

try:
    temp = float(output)
    print(str(now) + ' TEMPER ' + str(temp))
except:
    # bad data, ignore it
    raise SystemExit(1)
