mardi 11 septembre 2012

Téléinformation 5/5 (Affichage des valeurs)

Pour l'affichage, j'ai décider d'utiliser le framework http://www.highcharts.com/ qui est très flexible en terme d'affichage et plutôt facile à paramétrer.



J'ai un premier fichier index.html contenant le code suivant :
<FRAMESET ROWS="500,500">
<FRAME SRC="index.php">
<FRAME SRC="index2.php">
</FRAMESET>


Le fichier index.php m'affichera les courbes de consommation instantannées mesurées
Le fichier index2.php m'affichera les graphes de consommation sur une journée, mois et le tarif associé

Pour ce qui est de index.php, voici le code :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Using Highcharts with PHP and MySQL</title>

<script type="text/javascript" src="js/jquery-1.7.2.min.js" ></script>
<script type="text/javascript" src="js/highcharts.js" ></script>
<script type="text/javascript" src="js/themes/gray.js"></script>

<script type="text/javascript">
    var chart;
   
function GetUrlParameter( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

    $(document).ready(function() {
                var options = {
                    chart: {
                        renderTo: 'container',
                        defaultSeriesType: 'spline',
                        zoomType: 'x'
                    },
                    title: {
                        text: 'Consommation électrique',
                        x: -20 //center
                    },
                    rangeSelector : {
                        buttons : [{
                          type : 'hour',
                          count : 1,
                          text : '1h'
                        },{
                          type : 'hour',
                          count : 3,
                          text : '3h'
                        },{
                          type : 'hour',
                          count : 6,
                          text : '6h'
                        },{
                          type : 'hour',
                          count : 9,
                          text : '9h'
                        },{
                          type : 'hour',
                          count : 12,
                          text : '12h'
                        },{
                          type : 'all',
                          count : 1,
                          text : 'All'
                        }],
                        selected : 5,
                        inputEnabled : false
                    },
                    xAxis: {
                        type: 'datetime',
                        //tickInterval: 3600 * 1000, // one hour
                        //tickWidth: 0,
                        //gridLineWidth: 1,
                        maxZoom: 12 * 3600000, // 12 hours
                        //labels: {
                        //    align: 'center',
                        //    x: -3,
                        //    y: 20,
                        //    formatter: function() {
                        //        return Highcharts.dateFormat('%d.%m.%y', this.value) + '<br/>' + Highcharts.dateFormat('%H:%M',this.value) ;
                        //    }
                        //}
                       
                    },
                    yAxis: { // Primary yAxis,
                        title: {
                            text: 'Consommation',
                        },
                        min: 0,
                        labels: {
                            formatter: function() {
                                return this.value +' Watts';
                            },
                            style: {
                                color: '#808080'
                            }
                        }
                    },           
                    legend: {
                        backgroundColor: '0',
                        reversed: false
                    },
                    plotOptions: {
                        spline: {
                            lineWidth: 4,
                            states: {
                                hover: {
                                    lineWidth: 5
                                }
                            },
                            marker: {
                                enabled: false,
                                states: {
                                    hover: {
                                        enabled: true,
                                        symbol: 'circle',
                                        radius: 5,
                                        lineWidth: 1
                                    }
                                }
                            }
                        }
                    },
                    series: [{
                        type: 'spline',
                        name: 'Heures Pleines',
                        color: 'red',
                        yAxis: 0
                    }, {
                        type: 'spline',
                        color: 'blue',
                        name: 'Heures Creuses',
                        yAxis: 0
                    }],
                    //exporting: {
                    //    url: 'http://export.highcharts.com/index-utf8-encode.php'
                    //}
                }
                // Load data asynchronously using jQuery. On success, add the data
                // to the options and initiate the chart.
                // This data is obtained by exporting a GA custom report to TSV.
                // http://api.jquery.com/jQuery.get/
               
                jQuery.get('data.php?periode='+GetUrlParameter('periode'), null, function(tsv) {
                    var lines = [];
                    HCHP = [];
                    HCHC = [];
                    try {
                        // split the data return into lines and parse them
                        tsv = tsv.split(/\n/g);
                        jQuery.each(tsv, function(i, line) {
                            line = line.split(/\t/);
                            date = Date.parse(line[0].replace(/-/g,'/').replace(/\.\d*$/,'') +' UTC');
                            //date = Date.parse(line[0] +' UTC');
                            if (line[1] == "HP" && line[2] != '') {
                       
                                HCHP.push([    date, parseInt(line[2].replace(',', '')) ]);
                                HCHC.push([    date, 0 ]);
                            } else if (line[1] == "HC" && line[2] != '') {
                           
                                HCHP.push([    date, 0    ]);
                                HCHC.push([    date, parseInt(line[2].replace(',', '')) ]);
                            }
                        });
                    } catch (e) {  }
                    options.series[0].data = HCHP;
                    options.series[1].data = HCHC;
                   
                    chart = new Highcharts.Chart(options);
                });
            });
</script>
</head>
<body>
<style>
input[type="submit"]{
width:100px;
height:30px;
margin-left:20px;
font-size:1em;
font-weight:bold;
border:none;
color:#cecece;
text-shadow:0px -1px 0px #000;
background:#1f2026;
background:-moz-linear-gradient(top,#1f2026,#15161a);
background:-webkit-gradient(linear,left top,left bottom,from(#1f2026),to(#15161a));
-webkit-border-radius:5px;
   -moz-border-radius:5px;
        border-radius:5px;
-webkit-box-shadow:0px 0px 1px #000;
   -moz-box-shadow:0px 0px 1px #000;
        box-shadow:0px 0px 1px #000;
}
input[type="submit"]:hover{
background:#343640;
background:-moz-linear-gradient(top,#343640,#15161a);
background:-webkit-gradient(linear,left top,left bottom,from(#343640),to(#15161a));
}
</style>
<div id="container" style="width: 100%; height: 400px; margin: 0 auto"></div>
                    <br /><br />
    <form method="GET" action="<?php echo $_SERVER['PHP_SELF'];?>" style="text-align: center;" >
        <input type="submit" value="1jour" name="periode">
        <input type="submit" value="8jours" name="periode">
        <input type="submit" value="1mois" name="periode">
        <input type="submit" value="6mois" name="periode">
        <input type="submit" value="1an" name="periode">
    </form>
</body>
</html>


Pour index2.php, voici le code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Using Highcharts with PHP and MySQL</title>

<script type="text/javascript" src="js/jquery-1.7.2.min.js" ></script>
<script type="text/javascript" src="js/highcharts.js" ></script>
<script type="text/javascript" src="js/themes/gray.js"></script>

<script type="text/javascript">
    var chart;
   
function GetUrlParameter( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
  // prix tarif HP/HC EDF
var prixHP = 0.1312;
var prixHC = 0.0895;
  // Abpnnement pour disjoncteur 45 A
var abonnement = 112.87;

    $(document).ready(function() {
                var options = {
                    chart: {
                        renderTo: 'container',
                        defaultSeriesType: 'column'
                    },
                    title: {
                        text: 'Consommation électrique',
                        x: -20 //center
                    },
                    xAxis: [{
                        //categories: ['Apples', 'Oranges', 'Pears']
                        //type: 'datetime'
                        //tickInterval: 3600 * 1000, // one hour
                        //tickWidth: 0,
                        //gridLineWidth: 1,
                        //maxZoom: 12 * 3600000, // 12 hours
                        //labels: {
                        //    align: 'center',
                        //    x: -3,
                        //    y: 20,
                        //    formatter: function() {
                        //        return Highcharts.dateFormat('%d.%m.%y', this.value) + '<br/>' + Highcharts.dateFormat('%H:%M',this.value) ;
                        //    }
                        //}
                       
                    }],
                    yAxis: [{
                        title: {
                            text: 'Heures Creuses  -  Heures Pleines',
                        },
                        min: 0,
                        labels: {
                            formatter: function() {
                                return this.value +' kWh';
                            },
                            style: {
                                color: '#808080'
                            }
                        },
                        stackLabels: {
                            formatter: function() {
                                return Highcharts.numberFormat(this.total, 1) + ' kWh';
                            },
                            enabled: true
                        }
                    }],
                    tooltip: {
                        formatter: function() {
                            totalHP=prixHP*((this.series.name == 'Heures Pleines')? this.y :this.point.stackTotal-this.y);
                            totalHC=prixHC*((this.series.name == 'Heures Creuses')? this.y :this.point.stackTotal-this.y);
                            totalprix=Highcharts.numberFormat(( totalHP + totalHC),2);
                            tooltip = '<b> '+ this.x +' <b><br /><b>Consommation : '+ Highcharts.numberFormat(this.total, 1) +' kWh<b><br />';
                            tooltip += 'HP : '+ Highcharts.numberFormat(totalHP,2) + ' Euro / HC : ' + Highcharts.numberFormat(totalHC,2) + ' Euro<br />';
                            tooltip += '<b> Total: '+ totalprix +' Euro<b>';
                            return tooltip;
                        }
                    },
                   
                    legend: {
                        backgroundColor: '0',
                        reversed: false
                    },
                    plotOptions: {
                        column: {
                            stacking: 'normal',
                        }
                    },
                    series: [{
                        name : 'Heures Pleines',
                        color: 'red',
                        dataLabels: {
                            enabled: true,
                            color: '#FFFFFF'
                        },
                        type: 'column'
                    }, {
                        name : 'Heures Creuses',
                        color: 'blue',
                        dataLabels: {
                            enabled: true,
                            color: '#FFFFFF'
                        },
                        type: 'column'
                    }],
                    //exporting: {
                    //    url: 'http://export.highcharts.com/index-utf8-encode.php'
                    //}
                }
                // Load data asynchronously using jQuery. On success, add the data
                // to the options and initiate the chart.
                // This data is obtained by exporting a GA custom report to TSV.
                // http://api.jquery.com/jQuery.get/
               
                jQuery.get('data2.php?periode='+GetUrlParameter('periode'), null, function(tsv) {
                    var lines = [];
                    HCHP = [];
                    HCHC = [];
                    date = [];
                    try {
                        // split the data return into lines and parse them
                        tsv = tsv.split(/\n/g);
                        jQuery.each(tsv, function(i, line) {
                            line = line.split(/\t/);
                            //date = Date.parse(line[0].replace(/-/g,'/').replace(/\.\d*$/,'') +' UTC');
                            //date = Date.parse(line[1] +' UTC');
                            if (line[1] != '') {
                                date.push([line[1]]);
                            }
                            if (line[2] != '') {
                                HCHP.push([line[1],    parseFloat(line[2].replace(',', ''),10) ]);   
                            }
                            if (line[3] != '') {
                                HCHC.push([line[1],    parseFloat(line[3].replace(',', ''),10) ]);
                            }
                        });
                    } catch (e) {  }
                    options.series[0].data = HCHP;
                    options.series[1].data = HCHC;
                    options.xAxis[0].categories = date;
                   
                    chart = new Highcharts.Chart(options);
                });
            });
</script>
</head>
<body>
<style>
input[type="submit"]{
width:100px;
height:30px;
margin-left:20px;
font-size:1em;
font-weight:bold;
border:none;
color:#cecece;
text-shadow:0px -1px 0px #000;
background:#1f2026;
background:-moz-linear-gradient(top,#1f2026,#15161a);
background:-webkit-gradient(linear,left top,left bottom,from(#1f2026),to(#15161a));
-webkit-border-radius:5px;
   -moz-border-radius:5px;
        border-radius:5px;
-webkit-box-shadow:0px 0px 1px #000;
   -moz-box-shadow:0px 0px 1px #000;
        box-shadow:0px 0px 1px #000;
}
input[type="submit"]:hover{
background:#343640;
background:-moz-linear-gradient(top,#343640,#15161a);
background:-webkit-gradient(linear,left top,left bottom,from(#343640),to(#15161a));
}
</style>
<div id="container" style="width: 100%; height: 400px; margin: 0 auto"></div>
                    <br /><br />
    <form method="GET" action="<?php echo $_SERVER['PHP_SELF'];?>" style="text-align: center;" >
        <input type="submit" value="jours" name="periode">
        <input type="submit" value="semaines" name="periode">
        <input type="submit" value="mois" name="periode">
    </form>
</body>
</html>


index.php et index2.php appel respectivement data.php et data2.php pour extraire le données de la base de donnée. L'avantage est que l'extraction des données de fait en parallèle de l'affichage.

data.php :
<?php
if (isset($_GET['periode'])) {
  $periode = $_GET['periode'] ;
} else  $periode = "8jours" ;

$con = mysql_connect("xxxxx","
xxxxx","xxxxx");

if (!$con) {
  die('Could not connect: ' . mysql_error());
}

mysql_select_db("
xxxxx", $con);


switch ($periode) {
    case "1jour":
        $result = mysql_query("SELECT * FROM teleinfo WHERE TO_DAYS(NOW()) - TO_DAYS(temps) < 1 ORDER BY id ");
        break;
    case "8jours":
        $result = mysql_query("SELECT * FROM teleinfo WHERE TO_DAYS(NOW()) - TO_DAYS(temps) < 8 ORDER BY id ");
        break;
    case "1mois":
        $result = mysql_query("SELECT * FROM teleinfo WHERE TO_DAYS(NOW()) - TO_DAYS(temps) < 31 ORDER BY id ");
        break;
    case "6mois":
        $result = mysql_query("SELECT * FROM teleinfo WHERE TO_DAYS(NOW()) - TO_DAYS(temps) < 180 ORDER BY id ");
        break;
    case "1an":
        $result = mysql_query("SELECT * FROM teleinfo WHERE TO_DAYS(NOW()) - TO_DAYS(temps) < 365 ORDER BY id ");
        break;
    default:
        $result = mysql_query("SELECT * FROM teleinfo WHERE TO_DAYS(NOW()) - TO_DAYS(temps) < 1 ORDER BY id ");
        break;
}

while($row = mysql_fetch_array($result)) {
  echo $row['temps']. "\t" . $row['ptec']. "\t" . $row['papp']. "\n";
}
mysql_close($con);
?>



data2.php :
<?php
if (isset($_GET['periode'])) {
  $periode = $_GET['periode'] ;
} else  $periode = "jours" ;

$con = mysql_connect("
xxxxx","xxxxx","xxxxx");

if (!$con) {
  die('Could not connect: ' . mysql_error());
}

mysql_select_db("
xxxxx", $con);


switch ($periode) {
    case "jours":
        $result = mysql_query("SELECT temps, DATE_FORMAT(temps, '%a %e' ) AS 'periode', ROUND( ((MAX( `hchp` ) - MIN( `hchp` ) ) /1000), 1), ROUND( ((MAX( `hchc` ) - MIN( `hchc` ) ) /1000), 1) FROM teleinfo GROUP BY periode ORDER BY id");
        break;
    case "semaines":
        $result = mysql_query("SELECT temps, DATE_FORMAT( temps, 'sem %v' ) AS 'periode', ROUND( ((MAX( `hchp` ) - MIN( `hchp` ) ) /1000), 1), ROUND( ((MAX( `hchc` ) - MIN( `hchc` ) ) /1000), 1) FROM teleinfo GROUP BY periode ORDER BY id");
        break;
    case "mois":
        $result = mysql_query("SELECT temps, DATE_FORMAT( temps, '%b' ) AS 'periode', ROUND( ((MAX( `hchp` ) - MIN( `hchp` ) ) /1000), 1), ROUND( ((MAX( `hchc` ) - MIN( `hchc` ) ) /1000), 1) FROM teleinfo GROUP BY periode ORDER BY id");
        break;
    default:
        $result = mysql_query("SELECT temps, DATE_FORMAT( temps, '%a %e' ) AS 'periode', ROUND( ((MAX( `hchp` ) - MIN( `hchp` ) ) /1000), 1), ROUND( ((MAX( `hchc` ) - MIN( `hchc` ) ) /1000), 1) FROM teleinfo GROUP BY periode ORDER BY id");
        break;
}


while($row = mysql_fetch_array($result)) {
  echo $row['temps'] . "\t" . $row[1]. "\t" . $row['2']. "\t" . $row['3']. "\n";
}
mysql_close($con);
?>


Il faut de plus un répertoire js/ contenant les fichiers que vous trouverez dans le framework sur le site :
js/jquery-1.7.2.min.js
(ou plus récent)

js/highcharts.js
js/themes/gray.js