Leinoset.org Web development and Mobile development, Front - and Backend, Android applications & games, design

Front- and Backend development, Web and Graphical design, Mobile application development
Front- and Backend development, Web and Graphical design, Mobile application development

Python Temper-poll and temperature to website with PHP

22 June 2015

I ordered from DX.com TEMPer USB thermometer sensor for PC. Temper-poll you can find from website https://github.com/padelt/temper-python and following their instructions you can install temper-poll and make calibrations.

You can call directly thermometer sensor from command line with:

temper-poll

This will return you information about that device has been found and temperature in Celsius and Fahrenheit.

To get this information to website I made very simple PHP solution. First helper function take temperature to parts:

<?php  
function tempParts($temp, $index) {  
  $parts = explode('.', number_format($temp, 1));  
  return $parts[$index];  
}  
?>

Then actual we need to read temperature by executing Python temper-poll command using PHP (This has been updated 9.10.2015 to compensate error if usb-stick won't return temperature).

<html><body><p>

<?php 

  $command = "temper-poll -cq"; //We need only Celsius temperature

  // initialize variables
  $output = array();
  $return_var = -1; // get return if our command is success or not.
  $counter = 0;

  while ($return_var != 0 && $counter<10) {
    // continue until we get temperature
    exec($command, $output, $return_var);
        if ($return_var != 0) {
            echo "<br>connection to usb stick failed.. please wait, trying again<br>";
            $counter++; // ten tries only.
            sleep (5); // give usb-stick 5 seconds to "wakeup"
        }
   }

   if ($return_var != 0) {
   echo "Measuring failed..";
   exit(0);
    }else {
    foreach($output as $key => $value)
    {
    $temp = $value;
    }
  }

  print tempParts($temp,0)."<span>.".tempParts($temp,1);
  echo "</span>";  echo "strong&deg;/strong"; 
  ?>

</p></body></html>

Simple as that, this example requires that you'll have thermometer sensor plugged to your server.