I have an Arduino via an Ethernet Shield printing out a value every second via AJAX. I would like to graph this value in Flot. This requires the value to be put in a JSON format like this
[[epochtimestamp, value], [epochtimestamp, value]]
So I was wondering if you could help me use JavaScript/AJAX (or PHP if you think it is appropriate) to every second get this value and add it to the JSON inside the .txt file (used to store the previous values), so Flot can read all the values and create a time-based graph of these values but update the graph every second through AJAX.
Here is the basic process which needs to happen every second.
Here is some code I have started but it would have to be called by AJAX every second and wouldn't do the entire job.
<?php
$file = 'data.txt';
$webpage = 'test.txt';
$t = time(); // Open the file to get existing content
$current = file_get_contents($file);
$data = file_get_contents($webpage);
// Append a new person to the file
if ($current < 1) {
$current .= "[[" + $t + "," + $data + "]";
} else {
$current .= ", " + "[" + $t + "," + $data + "]";
} // Write the contents back to the file
file_put_contents($file, $current);
echo $current;
?>
I'm not sure if it would be easier to do with Javascript/AJAX?
Take a look at the source of flot's real-time updating example.
You could call your PHP script via AJAX from the browser, your client code should look like the following.
// Initialize your empty plot
var plot = $.plot("#myPlot", [], {
series: {
shadowSize: 0 // Drawing is faster without shadows
},
yaxis: {
min: 0,
max: 100
},
xaxis: {
show: false
}
});
function update() {
// Make an ajax call to your script to get data provided by your script
// Which reads that data.txt from Arduino.
$.ajax({
url: "yourhost/yourscript.php",
context: document.body
}).done(function(response) {
// Get the ajax response
data = response;
// If data is not null, set your plot's data.
if (data != null)
plot.setData(data);
// Draw the plot.
plot.draw();
// Re-invoke update.
update();
});
}
// Initial call to the update func.
update();