<?php
define( "EOL", "\n");

cli_set_process_title($topicName);
file_put_contents("/proc/".getmypid()."/comm",$topicName);

function checkCRC($t, $crc)
{
	logger(DEBUG, _("Entering function checkCRC"));
	$s1 = 0;
	$t = substr($t, 0, -2);
	$a = str_split($t);
	foreach($a as $char)
	{
		$s1 = ($s1 + ord($char));
	}
	$s1 = ($s1 & 0x3F) + 0x20;
	logger(DEBUG, sprintf(_("resultat = %x => CRC = %x"), $s1, ord($crc)));
	if ($s1 == ord($crc))
	{
		return true;
	}else
	{
		return false;
	}
}

function now()
{
	return new DateTime("now");
}

function signalHandler($signal)
{
	global $bbSerialPort, $connected, $client, $logFh;
	$x = 0;
	dio_close($bbSerialPort);
	while ($connected)
	{
		if ( $x++ > 60)
		{
			$client->disconnect();
			fclose($logFh);
			exit (1);
		}
		$client->loop();
	}
	sleep(4);
	fclose($logFh);
	exit(0);
}

function logger($level, $log, $notif = false)
{
	global $logFh, $logLevel, $notificationLevel;
	if ($level & $logLevel)
	{
		fwrite($logFh, "$level : $log" . EOL);
		print ("$level : $log" . EOL);
	}
}

date_default_timezone_set('Europe/Paris');

if (! $logFh = fopen("/var/log/linky2mqtt.log", "w") )
{
	echo _("error opening log file") . EOL;
}else
{
	echo _("Log file opened") . EOL;
}

//signal handling
pcntl_signal(SIGTERM, 'signalHandler');// Termination ('kill' was called)
pcntl_signal(SIGHUP, 'signalHandler'); // Terminal log-out
pcntl_signal(SIGINT, 'signalHandler');
?>
