Process Temperature Data And Display A Graph

This is the second installment of my One Wire Temperature Sensor With Cron & FTP tutorial. This guide will show you how to process and display the data files that have been generated and uploaded to our website.
It is presumed that you have some basic knowledge of web design using HTML and PHP.

I have recently updated the charts and am now using Highcharts to display the data. It is very pleasing to the eye and easy to configure. To download the source files please visit their site: Highcharts.com/download, download the source files and unzip to your site.
The “charts” folder needs to be located in the same directory as your temperature logfiles. There are many different types of chart to choose from and I suggest you have a good look at which one will suit your needs.

Right! Now to get scripting. I will be using a mixture of HTML for the actual displaying of data and PHP to do the hard work in the background processing the data to make it viewer friendly.

Firstly, create a file called graph.php using your favorite text editor (Mine is Notepad++). Copy/paste the following code (comments included as explanation):

<?php

## Put todays date into a variable for later use...

$date= date("d-m-Y");

## Tell PHP the location of our datafile for the current date...
## file_get_contents() retrieves the contents and places it into a 
## variable as a string.

$txt_file= file_get_contents('temp_log_' .$date. '.txt');

## Do a little error checking and display a message if the text 
## file is missing...

if(!$txt_file) {
echo "<br>ERROR - There is no information for this date.";

## If the file is present lets get going...

} else {

## Retrieve each row from the file.  The explode() function
## in this instance is using each new line ("\n") as a delimiter
## and assigning the entire file to a variable ($rows)...
 
$rows= explode("\n", $txt_file);

## As the explode() function will treat the last line as a new 
## record, we need to remove the last record (which is a blank line).  
## array_pop() does this for us automatically...

array_pop($rows);

## Setup two blank arrays for our data.  One for the time and one
## for the temperatures...

$temp=array();
$time=array();

## Now we use a foreach statement to parse each row so that we can 
## process them and sort our data. We assign each row to a 
## variable ($data)...

foreach($rows as $row => $data)
{

## Break down the individual record using (,) as delimiter.

$total= explode(",", $data);

## Extract the time from the record and make it loo pretty...

$t= explode(":", $total[1]);
$time[]= "$t[0]:$t[1]";

## Extract the temperature data from the record...
## floor() rounds the number down to the nearest integer.  
## We then multiply this by 100 and divide the rounded down 
## figure by 100.  This gives our temperature in a huma 
## readable fashion with the correct decimal places... 

$temp[]= floor($total[2] * 100) / 100;

## Notice that within this foreach statement I have 
## used the two variables $temp & $time with [] appended 
## to the end.  Doing this saves our new, re-fashioned 
## readings back to the variable turning it into an array of 
## all the data...

## then we end the foreach statement...

}

## Now we use the implode function to accumulate each row 
## that we have processed and save it back to an array.  
## We use (,) as our delimiter again...

$tempa= implode(",", $temp);
$timea= implode(",", $time);

## We have two, human-readable, arrays of data that we can 
## now pass to our graph...
?>

Now! The graph that I used is the one entitled “line-basic”. I used it for it’s simplicity for this tutorial. Please try to adapt others once you have completed this.
I have pasted the code from the line-basic htm file into graph.php. The only editing is the link for the config files for the graph and the actual data that will be fed into the graph.

Reopen our file graph.php. in the “head” of the file insert:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

Now insert the following into the file. Ensure that it is underneath our PHP code otherwise it wont work:

<script type="text/javascript">
$(function () {
        $('#container').highcharts({
            chart: {
                type: 'line',
                marginRight: 130,
                marginBottom: 25
            },
            title: {
                text: 'Todays Temperature Chart',
                x: -20 //center
            },
            subtitle: {
                text: 'Source: My Raspberry Pi',
                x: -20
            },
            xAxis: {
                categories: [<?php echo $timea; ?>]
            },
            yAxis: {
                title: {
                    text: 'Temperature'
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            },
            tooltip: {
                valueSuffix: ''
            },
            legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'top',
                x: -10,
                y: 100,
                borderWidth: 0
            },
            series: [{
                name: 'Celcius',
                data: [<?php echo $tempa; ?>]
            }]
        });
    });
</script>

Now all that needs to be done is to display the chart. Paste the following into our file. This needs to be placed into the “body” of the script:

<script src="charts/js/highcharts.js"></script>
<script src="charts/js/modules/exporting.js"></script>
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>

There we have it! Fire up your favorite browser, navigate to graph.php and see the wonders that you have created… πŸ˜€

This entry was posted in php, Scripting, Tutorial, Uncategorized and tagged , , , . Bookmark the permalink.

7 Responses to Process Temperature Data And Display A Graph

  1. Pingback: One Wire Temperature Sensor With Cron & FTP |

  2. Andreas says:

    Hello,
    Thanks for your project. I added a second sensor. and transfer the measurement data via ftp in the following format.
    07-07-2013,05:30:02,22.625,22.625,
    07-07-2013,06:00:02,22.625,22.625,
    07-07-2013,06:30:01,22.687,22.75,
    07-07-2013,07:00:01,22.812,22.875,
    07-07-2013,07:30:01,22.937,23.0,
    07-07-2013,08:00:02,22.937,23.125,
    07-07-2013,08:30:01,23.187,23.25,
    07-07-2013,09:00:01,23.187,23.5,
    07-07-2013,09:30:01,23.187,23.562,
    07-07-2013,10:00:01,23.562,23.625,

    how do I modify the PHP file so I can get the second temperature is also displayed?
    Can you help me there?
    regards
    Andreas

    • drewibbo says:

      Hi Andreas,

      To display the data from a second sensor you only need to add to the “series” section in the graph data. Find the following:

      series: [{
      name: 'Celcius',
      data: [< ?php echo $tempa; ?>]
      }]

      Now add in as many as you like (e.g):

      series: [{
      name: 'Celcius',
      data: [< ?php echo $tempa; ?>]
      }, {
      name: 'Internal',
      data: [< ?php echo $internala; ?>]
      }]

      Hope this helps
      Andy πŸ˜€

  3. Pedro says:

    Hi..
    Great code.

    I’m saving to notepad the date, time, and temperatura of one sensor of temperatura, in this format:
    2013/07/29 12:30:00 23 ΒΊC

    there is any problem with this format? i can change the same.

    Can you put the image of the graph here, for we see the result?

    Thanks

  4. Steve says:

    Hi andy I have been following this to get my own graph to work but it wont work I dont know what I am doing wrong. I get Internal server error 500 I know I am doing something wrong with my php file. Is there any chance that I can download the whole of the script.

    Hear is mine by the way. Many thanks Steve.

    <?php

    $date= date("d-m-Y");

    $txt_file= file_get_contents('temp_log_' .$date. '.txt');

    if(!$txt_file) {
    echo "ERROR – There is no information for this date.”;
    } else {
    $rows= explode(“\n”, $txt_file);
    array_pop($rows);
    $temp=array();
    $time=array();
    foreach($rows as $row => $data)
    {
    $total= explode(“,”, $data);
    $t= explode(“:”, $total[1]);
    $time[]= “$t[0]:$t[1]”;
    $temp[]= floor($total[2] * 100) / 100;
    }
    $tempa= implode(“,”, $temp);
    $timea= implode(“,”, $time);

    ?>

    Highcharts Example

    $(function () {
    $(‘#container’).highcharts({
    chart: {
    type: ‘line-basic’,
    marginRight: 130,
    marginBottom: 25
    },
    title: {
    text: ‘Todays Temperature Chart’,
    x: -20 //center
    },
    subtitle: {
    text: ‘Source: My Raspberry Pi’,
    x: -20
    },
    xAxis: {
    categories: []
    },
    yAxis: {
    title: {
    text: ‘Temperature’
    },
    plotLines: [{
    value: 0,
    width: 1,
    color: ‘#808080’
    }]
    },
    tooltip: {
    valueSuffix: ”
    },
    legend: {
    layout: ‘vertical’,
    align: ‘right’,
    verticalAlign: ‘top’,
    x: -10,
    y: 100,
    borderWidth: 0
    },
    series: [{
    name: ‘Celcius’,
    data: []
    }]
    });
    });

    • drewibbo says:

      Hi Steve,

      It looks like you’re not using the $tempa & $timea variables.

      Amend the following:

      xAxis: {
      categories: [<?php echo $timea; ?>]
      },

      And

      series: [{
      name: 'Celcius',
      data: [<?php echo $tempa; ?>]
      }]

      This should sort it out hopefully. πŸ˜€

  5. Michael says:

    Hi Andy

    Great project, thanks very much. This is my first attempt at using PHP and JS and am having problems getting this to work, can you help please?

    I added a } at the end of the PHP section as I was getting an unexpected end of file message but now I’m getting another error message:-
    PHP Notice: Undefined offset: 1 in /var/www/graph.php on line 62
    PHP Notice: Undefined offset: 2 in /var/www/graph.php on line 70

    which are:-

    62 $time[]= “$t[0]:$t[1]”;

    70 $temp[]= floor($total[2] * 100) / 100;

    here is all my code:-

    <?php

    ## Put todays date into a variable for later use…

    $date= date("d-m-Y");

    ## Tell PHP the location of our datafile for the current date…
    ## file_get_contents() retrieves the contents and places it into a
    ## variable as a string.

    $txt_file= file_get_contents('temp_log_' .$date. '.txt');

    ## Do a little error checking and display a message if the text
    ## file is missing…

    if(!$txt_file) {
    echo "ERROR – There is no information for this date.”;

    ## If the file is present lets get going…

    } else {

    ## Retrieve each row from the file. The explode() function
    ## in this instance is using each new line (“\n”) as a delimiter
    ## and assigning the entire file to a variable ($rows)…

    $rows= explode(“\n”, $txt_file);

    ## As the explode() function will treat the last line as a new
    ## record, we need to remove the last record (which is a blank line).
    ## array_pop() does this for us automatically…

    array_pop($rows);

    ## Setup two blank arrays for our data. One for the time and one
    ## for the temperatures…

    $temp=array();
    $time=array();

    ## Now we use a foreach statement to parse each row so that we can
    ## process them and sort our data. We assign each row to a
    ## variable ($data)…

    foreach($rows as $row => $data)
    {

    ## Break down the individual record using (,) as delimiter.

    $total= explode(“,”, $data);

    ## Extract the time from the record and make it loo pretty…

    $t= explode(“:”, $total[1]);
    $time[]= “$t[0]:$t[1]”;

    ## Extract the temperature data from the record…
    ## floor() rounds the number down to the nearest integer.
    ## We then multiply this by 100 and divide the rounded down
    ## figure by 100. This gives our temperature in a huma
    ## readable fashion with the correct decimal places…

    $temp[]= floor($total[2] * 100) / 100;

    ## Notice that within this foreach statement I have
    ## used the two variables $temp & $time with [] appended
    ## to the end. Doing this saves our new, re-fashioned
    ## readings back to the variable turning it into an array of
    ## all the data…

    ## then we end the foreach statement…

    }

    ## Now we use the implode function to accumulate each row
    ## that we have processed and save it back to an array.
    ## We use (,) as our delimiter again…

    $tempa= implode(“,”, $temp);
    $timea= implode(“,”, $time);

    ## We have two, human-readable, arrays of data that we can
    ## now pass to our graph…
    }
    ?>

    $(function () {
    $(‘#container’).highcharts({
    chart: {
    type: ‘line’,
    marginRight: 130,
    marginBottom: 25
    },
    title: {
    text: ‘Todays Temperature Chart’,
    x: -20 //center
    },
    subtitle: {
    text: ‘Source: My Raspberry Pi’,
    x: -20
    },
    xAxis: {
    categories: []
    },
    yAxis: {
    title: {
    text: ‘Temperature’
    },
    plotLines: [{
    value: 0,
    width: 1,
    color: ‘#808080’
    }]
    },
    tooltip: {
    valueSuffix: ”
    },
    legend: {
    layout: ‘vertical’,
    align: ‘right’,
    verticalAlign: ‘top’,
    x: -10,
    y: 100,
    borderWidth: 0
    },
    series: [{
    name: ‘Celcius’,
    data: []
    }]
    });
    });

Leave a Reply

Your email address will not be published. Required fields are marked *