I am trying to make a simple web GUI for a Raspberry Pi. It is supposed to draw a temperature value on an image using php and JavaScript.
I will use some IPC between PHP and a C++ application I am writing. But right now I just want to read a value from a file and draw it on the image. (The file is a temperature value from a 1wire bus using OWFS)
My problems
The JavaScript function ReadTemps() gets called every 5 seconds, but the PHP values only gets updated when the page refreshes.
I have NO experience in JavaScript.
The code
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Still life web application</title>
<canvas id="myCanvas" width="768" height="576" style="border:0px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<?php
function get_temp()
{
echo round( floatval( file_get_contents( '/mnt/1wire/uncached/vessel/temperature' ) ), 2 );
}
?>
<script>
var bgImg = new Image();
bgImg.src = 'image.jpg';
function ReadTemps()
{
var vessel_temp = '<?php get_vessel_temp(); ?>';
var c = document.getElementById( "myCanvas" );
var ctx = c.getContext( "2d" );
ctx.drawImage( bgImg, 0, 0 );
ctx.font="20px Georgia";
ctx.fillText( vessel_temp + '\u00B0', 330, 430 );
setTimeout( ReadTemps, 5000 );
}
window.onload = ReadTemps;
</script>
</head>
<body>
<a href="javascript:ReadTemps();">Update</a>
</body>
</html>
If I add an alert("hello") in ReadTemps
it pops up every 5 seconds.
The solution
<script>
var bgImg = new Image();
stillImg.src = 'image.jpg';
function ReadTemps()
{
var vessel_temp = loadXMLDoc( 'get_vessel.php' );
var c = document.getElementById( "myCanvas" );
var ctx = c.getContext( "2d" );
ctx.drawImage( bgImg, 0, 0 );
ctx.font="20px Georgia";
ctx.fillText( vessel_temp + '\u00B0', 330, 430 );
setTimeout( ReadTemps, 5000 );
}
function loadXMLDoc( file )
{
var xmlhttp;
if( window.XMLHttpRequest )
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject( "Microsoft.XMLHTTP" );
xmlhttp.open( "GET", file, false );
xmlhttp.send( null );
if( xmlhttp.readyState == 4 && xmlhttp.status == 200 )
return xmlhttp.responseText;
else
return "error";
}
window.onload = ReadTemps;
</script>