<?php

define('SYSFS_INPUT',    '/sys/class/thermal/thermal_zone0/temp');	# must be readable
define('OUTPUT_BASEDIR', '/var/tmp');					# must be writable

define('POLL_INTERVAL',     30);	# seconds
define('DELAYED_THRESHOLD', 2);		# seconds

$output_file = OUTPUT_BASEDIR . '/cpu-thermals-' . date('Ymd') . '.log';

file_put_contents(
	$output_file,
	'# Collector started: ' . date('r') . "\n",
	FILE_APPEND | LOCK_EX);

if (!is_readable(SYSFS_INPUT))
	die('FATAL: ' . SYSFS_INPUT . ' not readable');

if (!is_writable(OUTPUT_BASEDIR))
	die('FATAL: ' . OUTPUT_BASEDIR . ' not writable');

bcscale(2);

$poll_last    = $timestamp = time();
$poll_delayed = false;

while (true) {
	$cpu_temperature = trim(file_get_contents(SYSFS_INPUT));

	if (bccomp(microtime(true) - $timestamp, DELAYED_THRESHOLD) == 1)	# may not be not perfect, but
		$poll_delayed = true;						# it's simple and good enough

	$poll_status = ($poll_delayed ? 'delayed' : 'plain');	# e.g. can de delayed here

	file_put_contents(					# ... or even here
		$output_file,
		date('Ymd-His') . "\t{$cpu_temperature}\t{$poll_status}\n",
		FILE_APPEND | LOCK_EX);

	while (true) {						# but, such delays will be
		$timestamp_new = microtime(true);		# handled properly here

		if (($poll_delayed = (bccomp($timestamp_new - $timestamp, DELAYED_THRESHOLD) == 1))
		    || (bccomp($timestamp_new, $poll_last + POLL_INTERVAL) == 1)) {
	
			$poll_last = $timestamp = intval($timestamp_new);
			break;
		}

		$timestamp = intval($timestamp_new);
		usleep(900000);					# avoid second-level "wraps"
	}
}

