Skip to content

Instantly share code, notes, and snippets.

@mveinot
Created May 28, 2015 12:00
Show Gist options
  • Save mveinot/5f95eaa142f4bb6ba5e3 to your computer and use it in GitHub Desktop.
Save mveinot/5f95eaa142f4bb6ba5e3 to your computer and use it in GitHub Desktop.
<?php
$address = isset($_GET['address'])?$_GET['address']:null;
header("Access-Control-Allow-Origin: *");
header("Content-type: application/json");
function get_w1_address($address)
{
$bus_addr = substr($address,0,2).'-';
for ($i = -4; $i >= -14; $i += -2)
{
$bus_addr .= substr($address,$i,2);
}
return $bus_addr;
}
function get_w1_temp($address)
{
$temp_array = array();
$temp = 9999;
$sys_sensor_output = file("/sys/bus/w1/devices/$address/w1_slave");
preg_match('/^.*\s+crc=\S\S\s+(\w+)$/', $sys_sensor_output[0], $temp_array);
if ($temp_array[1] == 'YES')
{
preg_match('/^.*\s+t=(-?\d+)$/', $sys_sensor_output[1], $temp_array);
$temp = $temp_array[1] / 1000;
}
return $temp;
// return 9999;
}
if ($address)
{
$bus_addr = get_w1_address($address);
$count = 0;
do {
$temp = get_w1_temp($bus_addr);
$count++;
} while ($temp == 9999 && !($count <= 3));
if ($temp == 9999)
{
print "{\"status\":\"fail\", \"payload\":{\"message\":\"failed to read sensor $address - tried 3 times!\"}}";
} else
{
print "{\"status\":\"ok\", \"payload\":{\"tempC\":\"$temp\"}}";
}
} else
{
print "{\"status\":\"fail\", \"payload\":{\"message\":\"no address provided\"}}";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment