<!doctype html>
<html lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://code.highcharts.com/themes/gray.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://code.highcharts.com/stock/modules/export-data.js"></script>
<script src="\RGraph.common.core.js"></script>
<script src="\RGraph.common.dynamic.js"></script>
<script src="\RGraph.gauge.js"></script>
<link rel="stylesheet" href="index.css">
</head>
 <script type="text/javascript">
// fonction charge le graphe et les jauges au chargement de la page  
window.onload = function (){    
    RGraph.AJAX.getCSV({url: '/getData', callback: myCallback});
    readTextFile('temperature.csv');
}
// rafraîchissement des jauges
setInterval(function() {    
    RGraph.AJAX.getCSV({url: '/getData', callback: myCallback});
}, 1000);       // rafraîchissement des jauges toute les minutes (1000 pour toutes les secondes, 60000 pour toutes les minutes)
// rafraîchissement du graphe
setInterval(function() {    
    readTextFile('temperature.csv');        
    RGraph.AJAX.getCSV({url: '/getData', callback: myCallback});
}, 60000);  // rafraîchissement du graphique toute les heures (60000 pour toutes les minutes, 60000*60 pour toutes les heures)
// la fonction callback pour les jauges
function myCallback (data)
{       
    // on efface les précédentes jauges
    RGraph.reset(document.getElementById('cvs'));           
    RGraph.reset(document.getElementById('cvs2'));
    RGraph.reset(document.getElementById('cvs3'));
    
    // on recrée les jauges avec les nouvelles datas 
    gauge = new RGraph.Gauge({
        id: 'cvs',
        min: -20,
        max: 60,
        value: data[0],
        options: {
            textColor: 'white',
            backgroundColor: 'black',
            borderOuter:     'grey',
            borderInner:     'black',
            borderOutline:   'black',
            shadow:           true,
            shadowColor:     'grey',
            centerpinColor:  'black',
            labelsValue: true, 
            labelsValueDecimals: 1,
            labelsValueBounding: false,
            labelsValueYPos: 0.75,
            labelsValueBold: true,
            labelsValueUnitsPost: ' °C',
            titleTop: 'DHT22',
            titleBottom: 'Température',                
            colorsRanges: [[-20, 0, '#0000FF'], [0, 15,'#00FFFF'], [15, 30, '#00FF47'], [30, 40, '#FFFF00'], [40,60,'#FF4A00']] ,                
            adjustable: true,
            textSize: 12
        }
    }).draw()
    
    gauge2 = new RGraph.Gauge({
        id: 'cvs2',
        min: 0,
        max: 100,
        value: data[1],
        options: {
            textColor: 'white',
            backgroundColor: 'black',
            borderOuter:     'grey',
            borderInner:     'black',
            borderOutline:   'black',
            shadow:           true,
            shadowColor:     'grey',
            centerpinColor:  'black',
            labelsValue: true, 
            labelsValueDecimals: 1,
            labelsValueBounding: false,
            labelsValueYPos: 0.75,
            labelsValueBold: true,
            labelsValueUnitsPost: ' %',
            titleTop: 'DHT22',
            titleBottom: 'Humidité',                
            colorsRanges: [[0, 40, '#DC3912'], [40, 50,'#FF9900'], [50, 75, '#00FF00'], [75, 85, '#FF9900'], [85,100,'#DC3912']] ,
            adjustable: true,
            textSize: 12
        }
    }).draw()       
    
    gauge3 = new RGraph.Gauge({
        id: 'cvs3',
        min: -20,
        max: 60,
        value: data[2],
        options: {
            textColor: 'white',
            backgroundColor: 'black',
            borderOuter:     'grey',
            borderInner:     'black',
            borderOutline:   'black',
            shadow:           true,
            shadowColor:     'grey',
            centerpinColor:  'black',
            labelsValue: true, 
            labelsValueDecimals: 1,
            labelsValueBounding: false,
            labelsValueYPos: 0.75,
            labelsValueBold: true,
            labelsValueUnitsPost: ' °C',
            titleTop: 'DS18B20',
            titleBottom: 'Température\nde l\'eau',                
            colorsRanges: [[-20, 0, '#0000FF'], [0, 15,'#00FFFF'], [15, 30, '#00FF47'], [30, 40, '#FFFF00'], [40,60,'#FF4A00']] ,                
            adjustable: true,
            textSize: 12
        }
    }).draw()
}   
// fonction qui lit le fichier csv, récup les infos et dessine le graphe    
function readTextFile(file)
{
    /* traitement du fichier csv */ 
    
    var temp = [];                                    // on crée un tableau vide nommé temp pour y stocké la température extérieur
    var humi = [];                                    // on crée un tableau vide nommé humi pour y stocké l' humidité extérieur
    var tempEau = [];                                 // on crée un tableau vide nommé tempEau pour y stocké la température de l'eau
    var rawFile = new XMLHttpRequest();               // on crée une requète ajax 
    rawFile.open("GET", file, true);                  // on ouvre le fichier csv
    rawFile.onreadystatechange = function ()          // si le fichier existe et est bien lu
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var text = rawFile.responseText;                       // on copie le contenu dans une variable
                if(text != null){                                      // si c'est pas vide 
                    (text.split(";")).forEach(function(element){       // on définie le ";" comme fin de ligne
                        var tableauInt = [];                           // on crée un tableau nommé tableauInt
                        (element.split(",")).forEach(function(i){      // on définie le "," comme séparateur de champs
                            var reel = parseFloat(i);                  // on incrémente le tableau ligne par ligne champs par champs
                            tableauInt.push(reel);
                        });
                        // les champs du tableau tableauInt sont maintenant comme ceci timestamp,temp,humi,tempEau
                        // or pour les graphiques de la famille highstock il faut timestamp,temp puis timestamp,humi puis timestamp,tempEau
                        // pour afficher le graphique, c'est le découpage ci dessous
                        tableauInt[0] = tableauInt[0]*1000; 
                        var tableauInt2 = [];   
                        tableauInt2[0] = tableauInt[0]; 
                        tableauInt2[1] = tableauInt[2]; 
                        var tableauInt3 = [];   
                        tableauInt3[0] = tableauInt[0]; 
                        tableauInt3[1] = tableauInt[3]; 
                        // on envoie le nouveau format dans les tableaux temp, humi et tempEau                          
                        temp.push(tableauInt);
                        humi.push(tableauInt2); 
                        tempEau.push(tableauInt3);                  
                    });             
                }           
                // on les prend en compte
                temp.pop();             
                humi.pop();             
                tempEau.pop();              
                
                // création du graphique
                Highcharts.stockChart('container', {                           // on crée le graphe dans la div id container (html)        
                    chart: {                        
                        backgroundColor: {
                            linearGradient: { x1: 0, y1: 0, x2: 1, y2: 1 },
                            stops: [
                                [0, '#2a2a2b'],
                                [1, '#3e3e40']
                            ]
                        }
                    },                  
                    time: {
                        useUTC: false
                    },
                yAxis: [{                                          // 1er axe y
                        gridLineColor: '#707073',
                        lineColor: '#707073',
                        minorGridLineColor: '#505053',
                        tickColor: '#707073',
                        tickWidth: 1,
                        title: {
                            text: 'température',                 
                            style: {
                                color: 'yellow',   
                            }
                        },                             
                        opposite: false,                        
                        labels: {               
                            format: '{value} °C',  
                            style: {
                                color: 'yellow',
                            }
                        }
                    }, {                                           // 2eme axe y
                        gridLineColor: '#707073',
                        lineColor: '#707073',
                        minorGridLineColor: '#505053',
                        tickColor: '#707073',
                        tickWidth: 1,
                        title: {
                            text: 'humidité',           
                            style: {
                                color: '#99D1F1',   
                            }
                        },                  
                        opposite: true,        
                        labels: {
                            format: '{value} %',      
                            style: {
                                color: '#99D1F1',  
                            }
                        }
                    }, {                                          // 3eme axe y
                        gridLineColor: '#707073',
                        lineColor: '#707073',
                        minorGridLineColor: '#505053',
                        tickColor: '#707073',
                        tickWidth: 1,
                        title: {
                            text: 'température de l\'eau',                 
                            style: {
                                color: 'white',   
                            }
                        },                             
                        opposite: false,                        
                        labels: {               
                            format: '{value} °C',  
                            style: {
                                color: 'yellow',
                            }
                        }
                    }],
                    rangeSelector: {
                        buttons: [{
                        count: 1,
                        type: 'hour',
                        text: 'Heure'
                        },
                        
                        {
                        count: 1,
                        type: 'day',
                        text: 'jour'
                        },{
                        count: 1,
                        type: 'month',
                        text: 'mois'
                        }, {
                        type: 'all',
                        text: 'All'
                        }],
                        buttonSpacing:5,
                        buttonTheme: {
                            fill: 'none',
                                stroke: 'none',
                                'stroke-width': 0,
                                r: 8,
                                style: {
                                    color: 'white',
                                },
                                states: {
                                    hover: {
                                        fill: '#345fb5',
                                    },
                                    select: {
                                        fill: '#F1EE99',
                                        style: {
                                            color: 'black'
                                        }
                                    }                                   
                                }
                            },
                            inputBoxBorderColor: '#F1EE99',
                            inputStyle: {
                                backgroundColor: '#333',
                                color: 'yellow'
                            },
                            labelStyle: {
                                color: 'yellow'
                            }  
                        },
                    inputBoxWidth: 200,
                    inputBoxHeight: 18,
                    navigator: {
                        handles: {
                            backgroundColor: '#666',
                            borderColor: '#AAA'
                        },
                        outlineColor: '#CCC',
                        maskFill: 'rgba(255,255,255,0.1)',
                        
                        xAxis: {
                            gridLineColor: '#505053'
                        }
                    },                  
                    scrollbar: {
                        barBackgroundColor: '#808083',
                        barBorderColor: '#808083',
                        buttonArrowColor: '#CCC',
                        buttonBackgroundColor: '#606063',
                        buttonBorderColor: '#606063',
                        rifleColor: '#FFF',
                        trackBackgroundColor: '#404043',
                        trackBorderColor: '#404043'
                    },
                    title: {
                        text: 'Courbe de température'
                    },
                    exporting: {
                        enabled: false
                    },      
                    series: [{                         // série du  1er axe y
                        yAxis: 0,                                                   
                        name: 'température',               
                        data: temp,
                        color: 'yellow',                        
                        tooltip: {          
                            color: 'yellow',      
                            valueSuffix: ' °C'        
                        },
                        navigatorOptions: {                         
                            color: '#7798BF',
                            lineColor: 'yellow'                 
                        },
                        showInNavigator: true
                    },{                                // serie du  2eme axe y
                        yAxis: 1,                
                        name: 'humidité',              
                        data: humi,
                        color: '#99D1F1',
                        tooltip: {      
                            color: '#99D1F1',            
                            valueSuffix: ' %'        
                        },
                        navigatorOptions: {                         
                            color: '#7798BF',
                            lineColor: '#99D1F1'                    
                        },
                        showInNavigator: true
                    },{                                // serie du  3eme axe y
                        yAxis: 0,                                                   
                        name: 'température de l\'eau',             
                        data: tempEau,
                        color: 'white',                     
                        tooltip: {          
                            color: 'white',      
                            valueSuffix: ' °C'        
                        },
                        navigatorOptions: {                         
                            color: '#7798BF',
                            lineColor: 'white'                  
                        },
                        showInNavigator: true
                    }]
                });
            }
        }
    }
    rawFile.send(null);
}
</script>
</head>
<body>
    <h1>Piscine</h1>
    <div id="jauge">
        <canvas id="cvs" width="300" height="300">[No canvas support]</canvas>
        <canvas id="cvs2" width="300" height="300">[No canvas support]</canvas>
        <canvas id="cvs3" width="300" height="300">[No canvas support]</canvas>
    </div>
    <div id="container"</div>
</body>
</html>