<?php

/*
 *  Copyright (C) 2019 Tony L. Clark
 *  Author:  Tony Clark <tclark@villamontage.com> (2016)
 *
 *  hdc_raw_to_celcius.php -- 
 *
 *  This is the backend tool for converting raw HDC sensor data
 *  into its proper celcius temperature reading.

 */


$scriptName="hdc_raw_to_celcius.php";

$version="0.1.2";
print ("Script name is $scriptName and version is $version <br /><br />");


/* Function to convert raw HDC10xx ambient temp hex string into celcius temperature.
 * Example calls:  $chk_amb_temp = hex2temperature(substr($mood_key,20,4));
 * Takes raw mood_key sensor data; converts LSB and MSB order; converts to binary;
 * right shifts by 2 bits; and divides by 32 to arrive at degrees C value.
 *
 * Calls to function made as follows for examaple:  
 *   http://serverIP/hdc_raw_to_celcius.php?rawValue=205C
 */ 
 
function hex2temperature($hex) {
	$temperature = 0;

	$LSBhex = substr($hex,0,2);  // Isolate raw hex string
	$MSBhex = substr($hex,2,2);
	
	echo "<br />LSB value is ".$LSBhex."<br />";
	echo "<br />MSB value is ".$MSBhex."<br />";

	$MSBLSB = $MSBhex.$LSBhex;
	echo "<br />Converted hex string before binary conversion is ".$MSBLSB."<br />";

	$rawTempBin = base_convert($MSBLSB, 16, 2);
	echo "<br />Binary version of raw data in corrected order before shifting is ".$rawTempBin."<br />";

	//$rawTempBinShift = $rawTempBin >> 2;  // Right shift by 2 positions
	$rawTempBinShift = substr($rawTempBin, 0, strlen($rawTempBin)-2);
	echo "<br />Binary value after right shift by 2 is ".$rawTempBinShift."<br />";

	$rawTempDec = base_convert($rawTempBinShift, 2, 10); // Convert from binary to decimal
	
        $temperature = $rawTempDec/32;   // Calculate celcius value
	
    return $temperature;
}
// End of hex2temperature function


echo "<hr>";

///////////////////////////////////////////////////////////

$rawValue = $_GET['rawValue'];
$rawValue = trim($rawValue);

$result = hex2temperature($rawValue);

echo "<b>01: The raw hex string value to be converted to celcius is the following:</b><br>";
echo $rawValue;
echo "<br />";

echo "<b>02: The corresponding celcius value is the following:</b><br>";
echo $result;

echo "</br>";

echo "<hr>";

///////////////////////////////////////////////////////////

//End of hdc_raw_to_celcius

?> 
