par opa95 » 29 Oct 2024 20:21
Bonjour Misterden
misterden a écrit:bientôt le retour des jours rouges...
Pensez vous que le script sur le store sera mis à jour à temps ? L'ensemble de mes règles électriques ( chauffage/filtration/charge VE ) sont dépendantes de ce script ( surtout quand c'est rouge ).
Je ne sais pas quand le script sera effectivement disponible sur le store.
J'ai fini le script depuis un certain temps et ça tourne sans problème sur rte et edf, juste un souci sur le site de selectra qui est utilisé en secours.
Pour ceux qui sont pressés, voici la dernière version avec de mini-corrections par rapport à la dernière version publiée dans cette discussion.
Il suffit de remplacer le script par la version ci-dessous
J'ai aussi la doc à disposition.
- Code : Tout sélectionner
<?php
/*****************************************************************************
** Script Tempo pour eedomus (Documentation : voir fichier md)
** Script qui permet de récupérer au format XML les données Tempo avec l'api rte, edf et sites Selectra (3 sites) :
** Les données sont stockées en mémoire et le polling sur les sites est réglé par la valeur de 'timer' : appels sur les sites seulement si données manquantes.
** Polling automatique au passage à 0h00, 6h00, 6h15, 6h30*, 8h00*, 11h30*, 12h15* et 22h (* si necessaire). Pour un fonctionnement efficace, on peut régler la fréquence des devices à une valeur faible (2 ou 5 minutes).
** Un polling complémentaire, est réglé par timer pour limiter les appels successifs des devices (timer = 20 par défaut)
** On peut restreindre l'utilisation des sources : src absent ou 0 ou 7 toutes les sources, 1 rte, 2 edf, 3 rte+edf, 4 selectra, 5 rte + selectra, 6 edf + selectra
** Il n'y a que quelques appels par jour : en général 1 (0 le samedi) plus 1 pour les tarifs (journalier ou hebdomadaire ou mensuel), quel que soit le nombre de devices créés. Le reste du temps les appels renvoient le contenu de la mémoire et gérent l'état actuel (0h, 6h et 22h).
****************************************************************************
** - URL de la Requête
**: - http://localhost/script/?exec=edf_tempo.php
** - ou http://localhost/script/?exec=edf_tempo.php&tarifs=[VAR1]&timer=[VAR2]&reset=[VAR3]
** avec
** VAR1 : tarifs (Bleu valeurs,Blanc valeurs, rouge valeurs) valeurs (hp,hc ou hc,hp) ou période de mise à jour [D ou W ou M] (Day,Week,Month) ou vide W par défaut (ex 0.1296,0.1609,0.1486,0.1894,0.1568,0.7562, ou W)
** VAR2 : vide ou durée du timer (minutes) 20 par défaut, si <0 lecture immédiate
** VAR3 : reset (0 par défaut, 1 sinon, si négatif 1 seul reset, sauf si changement de valeur négative) effacement mémoire et relecture des données
** - Fréquence de la Requête : 2 ou 5 pour mettre à jour l'affichage plus souvent lors des passage programmés; le polling réel est réglé par 'timer'
** autres commandes ajouter à la fin de la ligne de commande ou à la suite d'une variable :
** source &src=1 [0..7] (7 par défaut)
** nom mémoire : &mem=nom (OLDtempo par défaut)
** mode debug : &debug=0 (0 par défaut,-1,1) (-1 infos, 1 tout)
** modification état : &setstate=chp:val avec chp = [A,D,C,T] (Aujourdhui, Demain, Compte, Tarif), ou vide; pour chp=A ou D val = ND,BLUE,WHITE,RED; possible si manuel = 1 (0 sinon)
** manuel : &manuel=1 (par défaut) ou 0 (autorise setstate)
** simul : décalage temporel (heures décimales) : &simul=yyyyy (0 par défaut)
****************************************************************************
Resultats : //champ ou /root/tempo/champ (ou /root/debug/champ)
voir les champs en mode test ou dans sdk_print
********************************************************************************
urls compatibles : (normalement rte dès 6h15, Selectra dès 6h30, edf dès 8h)
api rte : https://www.services-rte.com/cms/open_data/v1/tempo?season=2024-2025
api edf : https://www.api-couleur-tempo.fr/api/joursTempo?periode=2024-2025,
autres (tarifs) la valeur #selectra ou #selectra2 est adaptée au site
https://selectra.info/energie/fournisseurs/edf/tempo#selectra,
https://www.fournisseurs-electricite.com/edf/tarifs/tempo#selectra,
https://prix-elec.com/tarifs/fournisseurs/edf/tempo#selectra2
******************************************************************************
** Evolution des versions :
** 2017-07-26 (DjMomo) :V1.0 - Version initiale
** ....
** V4.0 : Restriction à Tempo, utilisation des API Rte, Edf et Selectra (opa95 et Merguez07, 2024-10-01) minimisation des appels (mise en cache local), état du jour, du lendemain, actuel (couleur et tarif), décompte des jours (bleus, blancs, rouges)
*******************************************************************************/
//Initialisations
define('VER','V4.0');
define('NBW','43');
define('NBR','22');
define('DEFTIMER','20');//20 minutes
define('MEM','OLDtempo');
define('MANUAL','1');//autorise la commande manuelle
define('DEFTARIF','W');//Weekly
define('TSTART',60000);//début start 06h00:00
define('TRTE',61500);//lecture rte 06h15:00
define('TSEL',63000);//lecture selectra 06h30:00
define('TEDF',80500);//lecture edf 8h05:00
define('TSTOP',220000);//fin HP 22h00:00
define('TMAT',110000);//11h00:00
define('NOON',121500);//12h15:00
$colors['rte'] = array(1=>'BLUE','WHITE','RED',0=>'ND');
$colors['eed'] = array($colors['rte'][1]=>'BLEU',$colors['rte'][2]=>'BLANC',$colors['rte'][3]=>'ROUGE',$colors['rte'][0]=>'ND');
// XML header
@sdk_header('text/xml');
$xml = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
$xml .= "<!--\n";
echo $xml;//print header for debugging
//necessary
$mem_name = getArg('mem',false,MEM);
$reset_ = getArg('reset',false);//réinitialisation totale
if ($reset_=='') $reset_=0;
$timer_ = getArg('timer',false);//
if ($timer_=='') $timer_=DEFTIMER;
$timer = abs(60*$timer_);// secondes
$simul = getArg('simul',false,0);
$time_now = time() + $simul;
$debug = getArg('debug',false,0);
$manual_ = getArg('manuel',false,MANUAL);
$action = '';
$set_state_ = strtoupper(getArg('setstate',false,''));
if ($set_state_ == ''){$set_state[0] = '';$set_state[1] = 0;
}else{
$set_state = explode(':',$set_state_);
// if (!in_array($set_state[0],array('A','D','C','T'))) $set_state[0] = '';
if (!in_array($set_state[0],array('D','C','T'))) $set_state[0] = '';
if (count($set_state)<2) $set_state[1] = '';
//if ($set_state[1] == 'ND') $set_state[1] = '';
$action = 'setstate';
}
if ($debug >0) var_dump($_GET);
$src_ = getArg('src',false,7)%7;
if (!$src_) $src_ = 7;
$src['rte'] = 1&$src_;
$src['edf'] = (2&$src_)/2;
$src['alt'] = (4&$src_)/4;
//reset?
if ('' == $mem = loadVariable($mem_name)) $reset = 1;
else {
if ($reset_>0) {$reset = 1;
}elseif ($reset_<0) {//reset_ < 0
$reset = ($reset_ && ($reset_ != $mem['st']['reset']))?1:0;//reset change de valeur
}
if (($time_now - $mem['fileTimestamp'])>86400) $reset = 1;//too old file
if (!in_array($mem['todayColor'],$colors['rte'])) $reset=1;
if (array_key_exists('manual',$mem['st'])) {
$manual = ($manual_!='')?$manual_:$mem['st']['manual'];
}else $manual = MANUAL;
}
if ($reset) {
sdk_init($mem_name,$time_now);
}//poll print die
else $mem['st']['reset'] = $reset_;
//action?
$adjustFile = 0;
if ( ($action == 'setstate') && $manual && ($set_state[0] != '')){
if ($set_state[1] == ''){
switch ($set_state[0]) {
// case 'A' : $mem['st']['today'] = 0;$timer=0.01;$timer_=-0.01;break;
case 'D' : $mem['st']['tomoro'] = 0;$timer=0.01;$timer_=-0.01;$mem['tomoroColor'] = $colors['rte'][0];break;
case 'C' :
$mem['st']['count'] = 0;$req_fields['count'] = 1;$timer=0.01;$timer_=-0.01;break;
case 'T' :
$mem['st']['rates'] = 0;$req_fields['rates'] = 1;$timer=0.01;$timer_=-0.01;break;
}
}else{
if (in_array($set_state[1],$colors['eed'])) {
foreach($colors['eed'] as $key => $color)
if ($color == $set_state[1]) {$set_state[1] = $key;break;}
}
if (!in_array($set_state[1],$colors['rte']))
$set_state[1]='ND';
switch ($set_state[0]) {
case 'D' :
$mem['tomoroDate'] = sdk_day($time_now,1);
$mem['tomoroColor'] = $set_state[1];
$mem['st']['tomoro'] = $mem['tomoroDate'];
break;
// case 'A' :
$mem['todayColor'] = $set_state[1];
break;
}
$timer=0.01;$timer_=-0.01;
$req_fields['tomoro'] = 0;//requested fields
$action = 'read';
}
}
if ($time_now < $mem['fileTimestamp']) { // simulation (recul)
$action = 'simul';
$timer = -0.01;//minutes partial reset
}else{//search for modifications
$today_week = date('D',$time_now);
$hour_now = date('His',$time_now)+0;
$hour_file = date('His',$mem['fileTimestamp'])+0;
$mem['todayDate'] = sdk_day($time_now);
$mem['tomoroDate'] = sdk_day($time_now,1);
if ($today_week != $mem['todayWeek']) {//midnight
$action = 'midnite';
}elseif (($hour_file<TSTART) && ($hour_now>=TSTART)) {
$action = 'read';$adjustFile=1;
}elseif (($hour_file<TSTOP) && ($hour_now>=TSTOP)) {
$action = 'read';$adjustFile=1;
}else{
$actions = array(TRTE=>'startrte',TSEL=>'startalt',TEDF=>'startedf',TMAT=>'poll',NOON=>'poll');
foreach (array(TRTE,TSEL,TEDF,TMAT,NOON) as $timeOut){
if (($hour_file<$timeOut) && ($hour_now>=$timeOut)){
$action = $actions[$timeOut];break;}
}
}
if ($action == ''){
if (($time_now - $mem['fileTimestamp'])>$timer) {$action = 'timer';
}elseif ($timer_<0) {$action = 'timer_';}
else {$action = 'read';}
}
}
switch ($action){
case 'read' : break;
case 'midnite' :
$month_now = date('m',$time_now);
$year_now = date('Y',$time_now);
$hour_file_ = 0;
$action = 'read';
$mem['todayWeek'] = $today_week;
if ($month_now>=9) $season = $year_now.'-'.($year_now+1);
else $season = ($year_now-1).'-'.$year_now;
$mem['count']['rte'] = $mem['count']['edf'] = $mem['count']['alt1'] = $mem['count']['alt2'] = $mem['count']['alt3'] = 0;//reset counters
$mem['st']['tomoro'] = $mem['st']['count'] = 0;
if ($mem['todayColor'] != $colors['rte'][0]) //!='ND'
$mem['yesterColor'] = $mem['todayColor'];//oldvalue
if (!in_array($mem['tomoroColor'],$colors['rte'])) $mem['tomoroColor'] = $colors['rte'][0];//ND
elseif ($mem['tomoroColor'] != $colors['rte'][0]){ //!='ND'
$mem['todayColor'] = $mem['tomoroColor'];//oldvalue
$mem[$mem['todayColor']]['dec']++;
}
switch ($mem['todayWeek']) {
case 'Sat' :
$mem['tomoroColor'] = $colors['rte'][1];//Sunday
$mem['st']['tomoro'] = $mem['tomoroDate'];
break;
case 'Sun' : $mem['todayColor'] = $colors['rte'][1];break;
default : $mem['tomoroColor'] = $colors['rte'][0];
}
$mem[$mem['todayColor']]['rem'] = $mem[$mem['todayColor']]['tot'] - $mem[$mem['todayColor']]['dec'];
$adjustFile = 1;
break;
default :
$req_fields = array('tomoro' => 0,'count' => 0,'rates' => 0);//requested fields
if ($action != 'setstate'){
if ($hour_now < TRTE) $src['rte'] = 0;
if ($hour_now < TSEL) $src['alt'] = 0;
if ($hour_now < TEDF) $src['edf'] = 0;
}
$adjustFile = 1;
switch ($action){
case 'timer' :
if ($mem['st']['tomoro'] == $mem['tomoroDate']){
$action = 'read';
break 2;
}
$req_fields['tomoro'] = $req_fields['count'] = 1;
break;
case 'timer_' :
$mem['st']['rates'] = 0;
$req_fields['rates'] = 1;
case 'simul' :
$mem['st']['tomoro'] = $mem['st']['count'] = 0;
$req_fields['tomoro'] = $req_fields['count'] = 1;
break;
case 'startalt' : $req_fields['rates'] = 1;
case 'startedf' :
case 'startrte' :
if (($mem['st']['tomoro'] != $mem['tomoroDate']) || ($mem['st']['count'] != $mem['tomoroDate']) || $req_fields['rates']) {
$req_fields['tomoro'] = $req_fields['count'] = 1;
}
break;
case 'setstate' : $action ='read';
if ($set_state[0] == 'D') {
$req_fields['tomoro'] = $req_fields['count'] = 1;
}
break;
case 'poll' : break;
default : $adjustFile = 0;
}
$result = sdk_poll($action,$req_fields);
$adjustFile = ($result==1)?1: $adjustFile;
}
sdk_print($adjustFile);//die
function sdk_now()
{
global $time_now;
global $mem;
$hour = date('His',$time_now);
$mem['hchp'] = (($hour<TSTART) || ($hour>TSTOP))?'HC':'HP';
if ($hour<TSTART) {
$mem['nowDate'] = $mem['yesterDate'];
$mem['nowColor'] = $mem['yesterColor'];
}else{
$mem['nowDate'] = $mem['todayDate'];
$mem['nowColor'] = $mem['todayColor'];
}
}
function sdk_init_tarifs (){
global $time_now;
global $colors;
global $mem;
$tarifs = getArg('tarifs',false,'');//BHC, BHP, WHC, WHP, RHC, RHP
$rates = array('D','W','M');//Dayly,Weekly,Monthly,No
if ($tarifs==''){$tarifs=DEFTARIF;}
elseif (!strpos('@'.$tarifs,',')){
$tarifs = trim(strtoupper($tarifs));
$tarifs = 'M';
foreach($rates as $item){
if (strpos('@'.$tarifs,$item) == 1) {
$tarifs = $item;
break;
}
}
}else{
$i = 0;
$tarifs_ = explode(',',$tarifs);
foreach ($colors['rte'] as $col){
if ($col == $colors['rte'][0]) continue;
if ( ($tarifs_[$i]) && ($tarifs_[$i]<$tarifs_[$i+1])){
$mem[$col]['HP'] = $tarifs_[$i+1];
$mem[$col]['HC'] = $tarifs_[$i];
}else{
$mem[$col]['HC'] = $tarifs_[$i+1];
$mem[$col]['HP'] = $tarifs_[$i];
}
$i += 2;
}
$tarifs = DEFTARIF;
}
$mem['tarifsRef'] = $tarifs;
return $tarifs;
}
function sdk_init($mem_name,$time,$reset_='')
{
global $mem;
global $colors;
global $reset_;
global $time_now;
global $debug;
global $adjustFile;
$month = date('m',$time);
$year = date('Y',$time);
$nb_blue = 365-NBW-NBR;
if ($month>=9) {
$season = $year.'-'.($year+1);
$nb_blue += date('L',strtotime('next year'));
}else{
$season = ($year-1).'-'.$year;
$nb_blue += date('L',$time);
}
deleteVariable($mem_name);
$mem = array ('version' => VER, 'season'=>$season,
'todayDate'=>0,'todayColor'=>'ND','tomoroDate'=>0,'todayWeek'=>'x','tomoroColor'=>'ND',
'yesterDate'=>0,'yesterColor'=>'ND',
'nowDate'=>0,'nowColor'=>'ND',
'hchp' => 'HP', 'tarifsRef' => 'ND',
'BLUE' => array('rem'=>$nb_blue,'dec'=>0,'tot'=>$nb_blue,'HC'=>'0.1296','HP'=>'0.1609'),
'WHITE' => array('rem'=>NBW,'dec'=>0,'tot'=>NBW,'HC'=>'0.1486','HP'=>'0.1894'),
'RED' => array('rem'=>NBR,'dec'=>0,'tot'=>NBR,'HC'=>'0.1568','HP'=>'0.7562'),
'ND' => array('HC'=>'0','HP'=>'0'),
'ratePeriod'=>'W','count' => array('rte' => 0,'edf' => 0,'alt1' => 0,'alt2' => 0,'alt3' => 0),
'st'=>array('tomoro'=>'0','count'=>0,'rates'=>-1,'reset'=>0,'fileTime'=>-1, 'manual'=>MANUAL),
'fileTimestamp' => '0',
) ;
$mem['st']['fileTime'] = date('His',$time_now);
$adjustFile = 1;
$mem['todayDate'] = date('Y-m-d',$time);
$mem['tomoroDate'] = sdk_day($time,1);
$mem['yesterDate'] = sdk_day($time,-1);
$mem['todayWeek'] = date('D',$time);
if (strpos($mem['todayDate'],'09-01'))
$mem['yesterColor'] = $mem['todayColor'] = $colors['rte'][1];
switch ($mem['todayWeek']) {
case 'Sat' : $mem['tomoroColor'] = $colors['rte'][1];break;//dimanche
case 'Sun' : $mem['todayColor'] = $colors['rte'][1];break;
default : $mem['tomoroColor'] = $colors['rte'][0];
}
if ($reset_<0) $mem['st']['reset'] = $reset_;
sdk_init_tarifs();
if ($debug >0) echo "Action : init\n";
$req_fields['tomoro'] = $req_fields['count'] = $req_fields['rates'] = 1;
$result = sdk_poll('reset',$req_fields);
$adjustFile = ($result==1)?1: $adjustFile;
sdk_print();//die
}
function sdk_print($adjustFile = 1)
{//suppose impression entete
global $mem;
global $test;
if (!$test) $test = 'test';
global $mem_name;
global $debug;
global $colors;
global $timer_;
global $action;
global $src_;
global $time_now;
$days = array( 'Sun'=>'Dimanche', 'Mon'=>'Lundi', 'Tue'=>'Mardi', 'Wed'=>'Mercredi', 'Thu'=>'Jeudi', 'Fri'=>'Vendredi', 'Sat'=>'Samedi');
sdk_now();
if ($adjustFile) {
$mem['fileTimestamp'] = $time_now;
$mem['st']['fileTime'] = date('His',$time_now);
}
saveVariable($mem_name,$mem);
if($debug >0) {echo "Save :\n";var_dump($mem);}
// Génération du XML
$xml = "-->\n";
$xml .= "<root>\n";
$xml .= " <tempo>\n";
$xml .= ' <version>'.$mem['version']."</version>\n";
$xml .= ' <maintenant>'.$colors['eed'][$mem['nowColor']]."</maintenant>\n";
$xml .= ' <hchp>'.$mem['hchp']."</hchp>\n";
$xml .= ' <tarif_now>'.$mem[$mem['nowColor']][$mem['hchp']]."</tarif_now>\n";
$xml .= ' <aujourdhui>'.$colors['eed'][$mem['todayColor']]."</aujourdhui>\n";
$xml .= ' <tarifs_aujourdhui>'.$mem[$mem['todayColor']]['HC'].'/'.$mem[$mem['todayColor']]['HP']."</tarifs_aujourdhui>\n";
$xml .= ' <demain>'.$colors['eed'][$mem['tomoroColor']]."</demain>\n";
$xml .= ' <tarifs_demain>'.$mem[$mem['tomoroColor']]['HC'].'/'.$mem[$mem['tomoroColor']]['HP']."</tarifs_demain>\n";
$xml .= " <decompte_bleu>" . $mem['BLUE']['dec']."</decompte_bleu>\n";
$xml .= " <decompte_blanc>".$mem['WHITE']['dec']."</decompte_blanc>\n";
$xml .= ' <decompte_rouge>'.$mem['RED']['dec']."</decompte_rouge>\n";
$xml .= " <reste_bleu>" . $mem['BLUE']['rem']."</reste_bleu>\n";
$xml .= " <reste_blanc>".$mem['WHITE']['rem']."</reste_blanc>\n";
$xml .= ' <reste_rouge>'.$mem['RED']['rem']."</reste_rouge>\n";
$xml .= " <total_bleu>" . $mem['BLUE']['tot']."</total_bleu>\n";
$xml .= " <total_blanc>".$mem['WHITE']['tot']."</total_blanc>\n";
$xml .= ' <total_rouge>'.$mem['RED']['tot']."</total_rouge>\n";
$xml .= ' <date_now>'.$mem['nowDate']."</date_now>\n";
$xml .= ' <date_aujourdhui>'.$days[$mem['todayWeek']].' '.$mem['todayDate']."</date_aujourdhui>\n";
$xml .= ' <date_demain>'.$mem['tomoroDate']."</date_demain>\n";
$xml .= ' <filetime>'.$mem['st']['fileTime']."</filetime>\n";
$xml .= ' <counts>'.$mem['count']['rte'].'/'.$mem['count']['edf'].'/'.$mem['count']['alt1'].'/'.$mem['count']['alt2'].'/'.$mem['count']['alt3'].'/'."</counts>\n";
$xml .= ' <test>'.$test."</test>\n";
$xml .= " </tempo>\n";
if ($debug){
$xml .= " <debug>\n";
$xml .= ' <reset>'.$mem['st']['reset']."</reset>\n";
$xml .= ' <action>'.$action."</action>\n";
$xml .= ' <season>'.$mem['season']."</season>\n";
$xml .= ' <date_fichier>'.date('Y-m-d H:i:s',$mem['fileTimestamp'])."</date_fichier>\n";
$xml .= ' <timestamp>'.$mem['fileTimestamp']."</timestamp>\n";
$xml .= ' <date_lecture>'.date('Y-m-d H:i:s',$time_now)."</date_lecture>\n";
$xml .= ' <timer>'.abs($timer_)."</timer>\n";
$xml .= ' <tarifs>'.$mem['BLUE']['HC'].','.$mem['BLUE']['HP'].','.$mem['WHITE']['HC'].','.$mem['WHITE']['HP'].','.$mem['RED']['HC'].','.$mem['RED']['HP']."</tarifs>\n";
$xml .= ' <bleu_hc>'.$mem['BLUE']['HC']."</bleu_hc>\n";
$xml .= ' <bleu_hp>'.$mem['BLUE']['HP']."</bleu_hp>\n";
$xml .= ' <blanc_hc>'.$mem['WHITE']['HC']."</blanc_hc>\n";
$xml .= ' <blanc_hp>'.$mem['WHITE']['HP']."</blanc_hp>\n";
$xml .= ' <rouge_hc>'.$mem['RED']['HC']."</rouge_hc>\n";
$xml .= ' <rouge_hp>'.$mem['RED']['HP']."</rouge_hp>\n";
$xml .= ' <index_alt>'.$mem['st']['rates']."</index_alt>\n";
$xml .= ' <src>'.$src_."</src>\n";
$state_ = '';
foreach ($mem['st'] as $key => $state){
if ($state == $mem['tomoroDate']) {
$state_ .= strtoupper($key).',';
continue;
}elseif ( ($key == 'rates') && $mem['st']['rates']) {$state_ .= strtoupper($key).',';continue;}
elseif( ($key == 'reset') && $mem['st']['reset']){$state_ .= strtoupper($key).',';continue;}
else $state_ .= strtolower($key).',';
}
$xml .= ' <state>'.$state_."</state>\n";
$xml .= " </debug>\n";
}
$xml .= "</root>\n";
echo $xml;
die;
}
function sdk_day($time,$nbDays = 0) {//Unix
//creation date à partir du temps unix décale de $nbDays
//sortie jourFrançais jj/mm
$time += 86400*$nbDays;
$ret= date('Y-m-d',$time);
return $ret;
}
function sdk_poll($action = 'read',&$req_fields)
{
global $src;
global $mem;
global $reset_;
global $time_now;
global $colors;
global $debug;
global $adjustFile;
if ($action=='reset'){
$mem['st']['tomoro'] = $mem['st']['count'] = $mem['st']['rates']= 0;
$req_fields['tomoro'] = $req_fields['count'] = $req_fields['rates'] = 1;
$mem['st']['reset'] = $reset_;
}
if ($debug) echo "Polling : $action\n";
if ($src['rte']) {
$result = sdk_poll_rte_edf('rte',$req_fields,sdk_day($time_now,1));
$adjustFile = ($result)?1: $adjustFile;
}
if ($src['edf']) {
$result = sdk_poll_rte_edf('edf',$req_fields,sdk_day($time_now,1));
$adjustFile = ($result==1)?1: $adjustFile;
}
if ($src['alt']){
switch($mem['ratePeriod']){
case 'W' : $alt = date('W',$time_now);break;
case 'M' : $alt = date('m',$time_now);break;
case 'D' : $alt = date('z',$time_now);break;
default : $alt = -1;
}
if ((($mem['st']['tomoro'] != $mem['tomoroDate']) || ($mem['st']['count'] != $mem['tomoroDate']) || ($mem['st']['rates'] != $alt))) {
$result = sdk_poll_alt($alt,$req_fields);
$adjustFile = ($result==1)?1: $adjustFile;
}
}
foreach ($colors['rte'] as $key => $col){
if (!$key) continue;
$mem[$col]['rem'] = $mem[$col]['tot'] - $mem[$col]['dec'];
}
return $adjustFile;
}
function sdk_poll_rte_edf($src_,&$req_fields,$tomoro_date,$season='')
{
global $debug;
global $time_now;
global $mem;
global $colors;
global $url_history;
if (!($req_fields['tomoro'] || $req_fields['count'])) return 0;
if (($mem['st']['tomoro'] == $tomoro_date) && ($mem['st']['count'] == $tomoro_date)) return 0;
$url_history = ($src_=='rte')? 'https://www.services-rte.com/cms/open_data/v1/tempo?season=': 'https://www.api-couleur-tempo.fr/api/joursTempo?periode=';
if ($season=='') $season = $mem['season'];
$url = $url_history.$season;
if ($debug >0) echo "url : $url\n";
$info = array();
$response = httpQuery($url,'GET',NULL,NULL,NULL,false,false,$info);
if ($debug >0) {echo"Polling Info : $src_\n";var_dump($info);}
if (!$info || ($info["http_code"]!=200)) {
if ($debug >0){
echo 'Erreur : $url code : ';
if ($info) echo $info['http_code'];
echo "\n";
}
return 0;
}
$res_arr = sdk_json_decode($response);
if (is_array($res_arr) && (count($res_arr)<1)) return 0;
if ($debug >0) {echo"Polling Result : $src_\n";var_dump($res_arr);}
$mem['BLUE']['dec'] = $mem['WHITE']['dec'] = $mem['RED']['dec'] = 0;
if ($tomoro_date=='') $tomoro_date = $mem['tomoroDate'];
if ($src_ == 'rte'){
$mem['count']['rte']++;
if ($debug >0) echo "poll rte \n";
foreach($res_arr['values'] as $key => $item){
if ($item == 'false') continue;
if ($key != $tomoro_date) $mem[$item]['dec']++;
else $mem['tomoroColor'] = $item;
if ($key == $mem['todayDate'])
$mem['todayColor'] = $item;
}
}else{
$mem['count']['edf']++;
if ($debug >0) echo "poll edf \n";
foreach($res_arr as $item){
if ($item['codeJour']){
if ($item['dateJour'] != $tomoro_date) $mem[$colors['rte'][$item['codeJour']]]['dec']++;
else {
$mem['tomoroColor'] = $colors['rte'][$item['codeJour']];
break;
}
if ($item['dateJour'] == $mem['todayDate'])
$mem['todayColor'] = $colors['rte'][$item['codeJour']];
}
}
}
if ($mem['tomoroColor'] != $colors['rte'][0]){//!ND
$mem['st']['tomoro'] = $tomoro_date;
$req_fields['tomoro'] = 0;
$mem['st']['count'] = $tomoro_date;
$req_fields['count'] = 0;
}
$ret = ($mem['st']['tomoro'] == $tomoro_date) && ($mem['st']['count'] == $tomoro_date);
return $ret;
}
function sdk_multiextract($string,$startStr,$stopStr='',&$start,$startIn = false,$stopIn = false) { // Extraire une chaine de caracteres suivant plusieurs separateurs
// startStr : string ou array recherche de startStr ou de startStr[0], puis de startStr[1]à partir de là, puis ...
// stopStr : string ou array recherche de stopStr ou de stopStr[0], puis de stopStr[1]à partir de là, puis ...
// renvoi de la portion de $string entre le dernier startStr et le dernier stopStr
// Si outer les balises sont incluses, sinon elles ne sont pas incluses
// start est remis a jour
// eviter les caractères non standards
// si startStr (ou stopStr) de la forme
// array(array('a','b'),array('d','e')) recherche de (a puis b) ou bien (d puis e), si séquence 1 absente
// array('ab', 'ef') recherche de 'ab' puis 'ef'
// 'abc' recherche de 'abc'
$found = true;
if (!is_array($startStr)) {
$startStr = array($startStr);
}
foreach ($startStr as $codes){
if (!is_array($codes)) {
$codes = $startStr;//$codes = array($codes);
}
$beg = $start;
$startPos = '';
foreach ($codes as $code) {
$startLen = strlen($code);
if ( ($startLen != 0) && (($pos = strpos(substr($string,$beg),$code)) !== false) ) {
if ($startPos == '') $startPos = $beg + $pos;
$beg = $beg + $pos + $startLen;
}
else {
$beg = $start;
if ($startPos == '') $startPos = $beg;
$found = false;
break;
}
}
if ($found) break;
}
$start = $beg;
$found = true;
if (!is_array($stopStr)) {
$stopStr = array($stopStr);
}
foreach ($stopStr as $codes){
if (!is_array($codes)) {
$codes = $stopStr;//$codes = array($codes);
}
$end = $start;
$stopPos = '';
foreach ($codes as $code) {
$stopLen = strlen($code);
if ( ($stopLen != 0) && (($pos = strpos(substr($string,$end+1),$code)) !== false) ) {
$end = $end + 1 + $pos;
if ($stopPos == '') $stopPos = $end;
}
else {
$end = $start;
if ($stopPos == '') $stopPos = $end;
$found = false;
break;
}
}
if ($found) break;
}
if ($startIn) $beg = $startPos;
if ($stopIn) $end += $stopLen;
else $end = $stopPos;
$launch = substr($string,$beg,$end-$beg);
return $launch;
}
function sdk_extract($string,$startStr,$stopStr='',$start = 0,$startIn = false,$stopIn = false) { // Ectraire une chaine de caracteres suivant plusieurs separateurs
// appel de sdk_multiextract, start inchangé
$launch = sdk_multiextract($string,$startStr,$stopStr,$start,$startIn,$stopIn );
return $launch;
}
function sdk_poll_alt($alt,&$req_fields){
{
global $debug;
global $time_now;
global $mem;
global $colors;
global $url_alt;
if (!($req_fields['tomoro'] || $req_fields['count'] || $req_fields['rates'])) return 0;
if ($alt != $mem['todayWeek']) $mem['st']['rates'] = -1;
$urls_alt = array(1 =>
'https://selectra.info/energie/fournisseurs/edf/tempo#selectra',
'https://www.fournisseurs-electricite.com/edf/tarifs/tempo#selectra',
'https://prix-elec.com/tarifs/fournisseurs/edf/tempo#selectra2'
);
$months_fr = array('janvier' => 'January', 'février' => 'February','mars' => 'March','avril' => 'April','mai' => 'May','juin' => 'June','juillet' => 'July','août' => 'August','septembre' => 'September','octobre' => 'October','novembre' => 'November','décembre' => 'December');
$months = array(1 => 'January','February','March','April','May','June','July','August','September','October','November','December');
$colors['alt'] = array('bleu'=>'BLUE','blanc'=>'WHITE','rouge'=>'RED','ND'=>'ND');
$info = array();
$ret = 1;
for ($iurl=1;$iurl<=count($urls_alt);$iurl++){
list($url_alt,$type) = explode('#',$urls_alt[$iurl]);
$respAlt = trim(httpQuery($url_alt,'GET',NULL,NULL,NULL,false,false,$info));
if (strpos($respAlt,'html') === false) $result = 0;
else {$result = 1;break;}
}
if ($debug >0) {echo"Polling Info : $url_alt\n";var_dump($info);}
if ($result) {//traitement des données annexes
$erreur = 0;
$mem['count']['alt'.$iurl]++;
if ($debug >0) {echo"Polling : alt$iurl\n";var_dump($mem['count']);}
switch ($type) {
case 'selectra' :
$sep2 = array(array('<!-- END'),array('<div class='),array('rouges'));
$sep = array('badge--secondary">','card__title">');
$start = 0;
$block = trim(strtolower(sdk_extract($respAlt,$sep,$sep2,$start,false,false))).' rouges##';//pas de MaJ $start
/*
tempo mardi 29/10
...
*/
$err_num = 1;
if (strlen($block) == 0) {$erreur = $err_num;break;}
//lecture block
//extraction infos Aujourd'hui
// dates
$sep = array('tempo ');
$sep2 = array('</h2');
$temp = trim(sdk_multiextract($block,$sep,$sep2,$start));//MaJ $start //"mardi 29/10"
$day = explode(" ",$temp);
$jour = explode("/",$day[1]);
$jour[1] = $months[$jour[1]];
$date = strtotime($jour[0]." ".$jour[1]);//"29 October"
$date = sdk_day($date);//"2024-10-29"
$day0='today';$day1='tomoro';
if ($date == $mem['yesterDate']) {$day0='yester';$day1='today';}
//couleur0
$sep2 = array('<');
$sep = array('tempo');// couleur
$color0 = $colors['alt'][strtolower(trim(sdk_multiextract($block,$sep,$sep2,$start)))];
//extraction infos demain
$sep = array('tempo ');
$sep2 = array('</h2');
$temp = trim(sdk_multiextract($block,$sep,$sep2,$start));//MaJ $start //"mercredi 30/10"
$day = explode(" ",$temp);
$jour = explode("/",$day[1]);
$jour[1] = $months[$jour[1]];
$date2 = strtotime($jour[0]." ".$jour[1]);//"30 October"
$date2 = sdk_day($date2);//"2024-10-30"
//couleur1
$sep2 = array('<');
$sep = array('tempo');// couleur
$color1 = $colors['alt'][strtolower(trim(sdk_multiextract($block,$sep,$sep2,$start)))];
if ($req_fields['tomoro'] && ($mem['st']['tomoro'] != $mem['tomoroDate'])){
$mem[$day0.'Color'] = $color0;
$mem[$day1.'Color'] = $color1;
if ($day1 == 'tomoro') $mem['st']['tomoro'] = $mem['tomoroDate'];
}
// bilan
$sep2 = array(array('</'),array('##'));
$sep = array('reste','<strong>');
$nbTot = $mem['BLUE']['tot']+$mem['WHITE']['tot']+$mem['RED']['tot'];
for ($i =0;$i<3;$i++) {
$temp = strtolower(trim(sdk_multiextract($block,$sep,$sep2,$start)));
//"241 jours tempo bleus"
$sep = array('<strong>');
$nb = (int)$temp;
$nbTot -= $nb;
if ($req_fields['tomoro'] && ($mem['st']['count'] != $mem['tomoroDate'])){
foreach ($colors['alt'] as $key => $col){
if (strpos($temp,$key)>1) {
$mem[$colors['alt'][$key]]['rem'] = $nb;
$mem[$colors['alt'][$key]]['dec'] = $mem[$colors['alt'][$key]]['tot'] - $nb;
break;
}
}
}
$nbJours = (strtotime($mem['todayDate'])-strtotime(substr($mem['season'],0,4).'-08-31'))/86400;
if ($nbTot == $nbJours) $mem['st']['count'] = $mem['tomoroDate'];
}
if ($req_fields['rates'] && ($mem['st']['rates'] != $alt)){
$sep2 = array(array('<!-- END'),array('</tr'));
$sep = array('<th>Abonnement','<strong>','<strong>','</td>');
$start = 0;
$block = trim(strtolower(sdk_extract($respAlt,$sep,$sep2,$start,false,false)));//pas de MaJ $start
$sep2 = array(' ');
$sep = array('<td>');
$tarifs = 1;
foreach ($colors['alt'] as $key => $col){
if ($col==$colors['rte'][0]) continue;
$temp = trim(strtolower(sdk_multiextract($block,$sep,$sep2,$start)))+0;//MaJ $start
if ($temp>0) $mem[$col]['HC'] = $temp;
else $tarifs = 0;
$temp = trim(strtolower(sdk_multiextract($block,$sep,$sep2,$start)))+0;//MaJ $start
if ($temp>0) $mem[$col]['HP'] = $temp;
else $tarifs = 0;
}
if ($tarifs) {
$mem['st']['rates'] = $alt;
$mem['todayWeek'] != $alt;
}
}
break;
case 'selectra2' :
$sep2 = array(array('<th>12 kVA'));
$sep = array('list-card--stretch">');
$start = 0;
$block = trim(sdk_extract($respAlt,$sep,$sep2,$start,false,false));//pas de MaJ $start
$block = str_replace(array('bleus','blancs','rouges'),array('bleu','blanc','rouge'),$block);
$err_num = 1;
if (strlen($block) == 0) {$erreur = $err_num;break;}
//lecture block
//extraction infos Aujourd'hui
// date
$sep = array('card__title">');
$sep2 = array('</h');
$temp = trim(str_replace(array('Tempo','/'),' ',sdk_multiextract($block,$sep,$sep2,$start)));//MaJ $start //"vendredi 27 09"
$day = explode(" ",$temp);
$date = substr($mem['todayDate'],0,4).'-'.$day[2].'-'.$day[1];//"2024-09-11"
$day0='today';$day1='tomoro';
if ($date == $mem['yesterDate']) {$day0='yester';$day1='today';}
//couleur0
$sep2 = array('<');
$sep = array('span>');// couleur
$color0 = $colors['alt'][strtolower(trim(trim(trim(sdk_multiextract($block,$sep,$sep2,$start)),'Tempo')))];
//extraction infos demain
$sep = array('card__title">');
$sep2 = array('</h');
$temp = trim(str_replace(array('Tempo','/'),' ',sdk_multiextract($block,$sep,$sep2,$start)));//MaJ $start //"vendredi 27 09"
$day = explode(" ",$temp);
$date = substr($mem['tomoroDate'],0,4).'-'.$day[2].'-'.$day[1];//"2024-09-11"
//couleur0
$sep2 = array('<');
$sep = array('span>');// couleur
$color1 = $colors['alt'][strtolower(trim(trim(trim(sdk_multiextract($block,$sep,$sep2,$start)),'Tempo')))];// couleur1
if ($req_fields['tomoro'] && ($mem['st']['tomoro'] != $mem['tomoroDate'])){
$mem[$day0.'Color'] = $color0;
$mem[$day1.'Color'] = $color1;
if ($day1 == 'tomoro') $mem['st']['tomoro'] = $mem['tomoroDate'];
}
// bilan
$sep2 = array(array('</p'),array('##'));
$sep = array('col-md-6">');
if ($req_fields['count'] && ($mem['st']['count'] != $mem['tomoroDate'])){
$mem['RED']['rem'] = trim(sdk_multiextract($block,$sep,$sep2,$start));
$mem['RED']['dec'] = $mem['RED']['tot'] - $mem['RED']['rem'];
}
if ($req_fields['rates'] && ($mem['st']['rates'] != $alt)){
$sep = array(array('kVA</th>','</td>'));
$sep2 = array('kVA');
$temp = trim(sdk_multiextract($block,$sep,$sep2,$start));
$sep2 = array(' ');
$sep = array('<td>');
$tarifs = 1;
foreach ($colors['alt'] as $key => $col){
if ($col==$colors['rte'][0]) continue;
$temp = trim(strtolower(sdk_multiextract($block,$sep,$sep2,$start)))+0;//MaJ $start
if ($temp>0) $mem[$col]['HC'] = $temp;
else $tarifs = 0;
$temp = trim(strtolower(sdk_multiextract($block,$sep,$sep2,$start)))+0;//MaJ $start
if ($temp>0) $mem[$col]['HP'] = $temp;
else $tarifs = 0;
}
if ($tarifs) {$mem['st']['rates'] = $alt;}
}
break;
}
if ($debug >0) {echo"Polling : alt$iurl\n";var_dump($mem['st']);}
}
}
return $ret;
}
?>
eedomus+, Zibase V1, RFP1000, RFXcom, RadioDriver CPL 630 X2D, capteurs puissance OWL, thermometres Oregon, téléinfo (USB Linky), detecteurs ouverture X2D, pilotage chauffage X2D, Ecoflow River PRO, PAC Shogun (Atlantic-Cozytouch)