Bonjour à tous,
Je suis à la recherche d'un script qui me permettrait de calculer la moyenne de la production de mes panneaux solaires toutes les x minutes, et qui se remettrait à zéro à la fin de chaque période?
Merci d'avance pour votre aide
nico_du_57 a écrit:Bonjour à tous,
Je suis à la recherche d'un script qui me permettrait de calculer la moyenne de la production de mes panneaux solaires toutes les x minutes, et qui se remettrait à zéro à la fin de chaque période?
Merci d'avance pour votre aide
nico_du_57 a écrit:Bonjour Opa95,
Tout d'abord, merci pour ta réponse.
Lorsque tu parles du calctulateur, tu sous-entends le "calculight" présent dans le store? Si oui, j'ai essayé de réfléchir à la formule à entrer, mais je bloque dessus...
Si c'est d'un autre calculateur, j'ai essayé le "calculateur mathématique" mais je n'ai pas réussi non plus...
<?php
define("MEM","mem");
// Create an object to compute the formula
$evaleedomus = new sdk_EvalMath;
// Get formula from VAR1
$formula = getArg("formula");
$deltaT = getArg("dt",false,0);//calcul de moyenne temporelle minutes
$reset = getArg("reset",false,0);
$round = getArg("round",false,3);
$now = time();
if (!isset($formula)) $formula = "0";
// basic evaluation:
$result = $evaleedomus->sdk_evaluate($formula);
if ($deltaT > 0) {
$old_data = loadVariable(MEM);
if (!$old_data) {
$old_data = array('value' => $result, 'date' => $now);
saveVariable(MEM,$old_data);
}
$duree = ($now - $old_data['date'])/60;
$old_value = $old_data['value'];
$periode = $deltaT;
//echo "<duree>".$duree."</duree>"."<periode>".$periode."</duree>";
if (($duree > $periode) || $reset) {
$data['value'] = $result;
$data['date'] = $now;
saveVariable(MEM,$data);
}
if ($duree != 0) $moyenne = ($result - $old_value)/$duree;
}
@sdk_header('text/xml');
if ($deltaT == 0){
$xml .= "<result>".$result."</result>";
}
elseif (!$round) {
$xml = '<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL;
$xml .= "<root>";
$xml .= "<result>".$result."</result>";
$xml .= "<moyenne_1m>".$moyenne."</moyenne_1m>";
$xml .= "<moyenne_1h>".($moyenne*60)."</moyenne_1m>";
$xml .= "<duree>".round($duree,2)."</duree>";
$xml .= "</root>";
}
else {
$xml = '<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL;
$xml .= "<root>";
$xml .= "<result>".round($result,$round)."</result>";
$xml .= "<moyenne_1m>".round($moyenne,$round)."</moyenne_1m>";
$xml .= "<moyenne_1h>".round($moyenne*60,$round)."</moyenne_1h>";
$xml .= "<duree>".round($duree,2)."</duree>";
$xml .= "</root>";
}
echo $xml;
/*
Script développé par :
Mickael VIALAT - http://www.planete-domotique.com
Basé sur l'excellent travail de Miles Kaufmann : EvalMath Class
Merci de partager toute modification ou amélioration de ce script avec la communauté eedomus
sur le forum : http://forum.eedomus.com
modification : calcul de moyenne temporelle (opa95) 20220921
VAR2 contient dt : durée de calcul de la moyenne, si dt==0, comportement habituel
l'appel devient http://localhost/script/?exec=calculator.php&formula=[VAR1]&dt=[VAR2]
si on rajoute &reset=1, réinitialisation du calcul
au lieu de http://localhost/script/?exec=calculator.php&formula=[VAR1]
Si la fréquence de lecture est supérieure à dt, la valeur n'est pas remise à 0.
================================================================================
EvalMath - PHP Class to safely evaluate math expressions
Copyright (C) 2005 Miles Kaufmann <http://www.twmagic.com/>
================================================================================
LICENSE
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1 Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
class sdk_EvalMath {
var $suppress_errors = false;
var $last_error = null;
var $v = array('e'=>2.71,'pi'=>3.14); // variables (and constants)
var $f = array(); // user-defined functions
var $vb = array('e', 'pi'); // constants
var $fb = array( // built-in functions
'device', 'abs', 'acos', 'asin', 'atan', 'cos', 'deg2rad', 'exp', 'floor', 'log', 'pow', 'rad2deg', 'rand', 'round', 'sin', 'sqrt');
var $devicetab = array(); // user-defined functions
function sdk_EvalMath()
{
// make the variables a little more accurate
$this->v['pi'] = pi();
$this->v['e'] = exp(1);
}
function sdk_evaluate($expr)
{
$this->last_error = null;
$expr = trim($expr);
if (substr($expr, -1, 1) == ';') $expr = substr($expr, 0, strlen($expr)-1); // strip semicolons at the end
$arr = $this->sdk_nfx($expr);
return $this->sdk_pfx($arr); // straight up evaluation, woo
}
//===================== HERE BE INTERNAL METHODS ====================\\
// Convert infix to postfix notation
function sdk_nfx($expr)
{
$index = 0;
$stack = new sdk_EvalMathStack;
$output = array(); // postfix form of expression, to be passed to pfx()
$expr = trim(strtolower($expr));
$ops = array('+', '-', '*', '/', '^', '_');
$ops_r = array('+'=>0,'-'=>0,'*'=>0,'/'=>0,'^'=>1); // right-associative operator?
$ops_p = array('+'=>0,'-'=>0,'*'=>1,'/'=>1,'_'=>1,'^'=>2); // operator precedence
$expecting_op = false; // we use this in syntax-checking the expression
// and determining when a - is a negation
if (preg_match("/[^\w\s+*^\/()\.,-]/", $expr, $matches))
{ // make sure the characters are all good
return $this->sdk_trigger("illegal character '{$matches[0]}'");
}
while(1)
{ // 1 Infinite Loop ;)
$op = substr($expr, $index, 1); // get the first character at the current index
// find out if we're currently at the beginning of a number/variable/function/parenthesis/operand
$ex = preg_match('/^([a-z]\w*\(?|\d+(?:\.\d*)?|\.\d+|\()/', substr($expr, $index), $match);
//===============
if ($op == '-' && !$expecting_op)
{ // is it a negation instead of a minus?
$stack->sdk_push('_'); // put a negation on the stack
$index++;
}
else
if ($op == '_')
{ // we have to explicitly deny this, because it's legal on the stack
return $this->sdk_trigger("illegal character '_'"); // but not in the input expression
}
else
if ((in_array($op, $ops) || $ex) && $expecting_op)
{ // are we putting an operator on the stack?
if ($ex) { // are we expecting an operator but have a number/variable/function/opening parethesis?
$op = '*'; $index--; // it's an implicit multiplication
}
// heart of the algorithm:
while($stack->count > 0 && ($o2 = $stack->sdk_last()) && in_array($o2, $ops) && ($ops_r[$op] ? $ops_p[$op] < $ops_p[$o2] : $ops_p[$op] <= $ops_p[$o2]))
{
$output[] = $stack->sdk_pop(); // pop stuff off the stack into the output
}
// many thanks: http://en.wikipedia.org/wiki/Reverse_Polish_notation#The_algorithm_in_detail
$stack->sdk_push($op); // finally put OUR operator onto the stack
$index++;
$expecting_op = false;
//===============
}
else
if ($op == ')' && $expecting_op)
{ // ready to close a parenthesis?
while (($o2 = $stack->sdk_pop()) != '(')
{ // pop off the stack back to the last (
if ($o2===null) return $this->sdk_trigger("unexpected ')'");
else $output[] = $o2;
}
if (preg_match("/^([a-z]\w*)\($/", $stack->sdk_last(2), $matches))
{ // did we just close a function?
$fnn = $matches[1]; // get the function name
$arg_count = $stack->sdk_pop(); // see how many arguments there were (cleverly stored on the stack, thank you)
$output[] = $stack->sdk_pop(); // pop the function and push onto the output
if (in_array($fnn, $this->fb))
{ // check the argument count
if($arg_count > 1)
return $this->sdk_trigger("too many arguments ($arg_count given, 1 expected)");
}
else
{ // did we somehow push a non-function on the stack? this should never happen
return $this->sdk_trigger("internal error 1");
}
}
$index++;
//===============
}
else
if ($op == ',' && $expecting_op)
{ // did we just finish a function argument?
while (($o2 = $stack->sdk_pop()) != '(')
{
if ($o2===null) return $this->sdk_trigger("unexpected ','"); // oops, never had a (
else $output[] = $o2; // pop the argument expression stuff and push onto the output
}
// make sure there was a function
if (!preg_match("/^([a-z]\w*)\($/", $stack->sdk_last(2), $matches))
return $this->sdk_trigger("unexpected ','");
$stack->sdk_push($stack->sdk_pop()+1); // increment the argument count
$stack->sdk_push('('); // put the ( back on, we'll need to pop back to it again
$index++;
$expecting_op = false;
//===============
}
else
if ($op == '(' && !$expecting_op)
{
$stack->sdk_push('('); // that was easy
$index++;
$allow_neg = true;
//===============
}
else
if ($ex && !$expecting_op)
{ // do we now have a function/variable/number?
$expecting_op = true;
$val = $match[1];
if (preg_match("/^([a-z]\w*)\($/", $val, $matches))
{ // may be func, or variable w/ implicit multiplication against parentheses...
if (in_array($matches[1], $this->fb) or array_key_exists($matches[1], $this->f))
{ // it's a func
$stack->sdk_push($val);
$stack->sdk_push(1);
$stack->sdk_push('(');
$expecting_op = false;
}
else
{ // it's a var w/ implicit multiplication
$val = $matches[1];
$output[] = $val;
}
}
else
{ // it's a plain old var or num
$output[] = $val;
}
$index += strlen($val);
//===============
}
else
if ($op == ')')
{ // miscellaneous error checking
return $this->sdk_trigger("unexpected ')'");
}
else
if (in_array($op, $ops) && !$expecting_op)
{
return $this->sdk_trigger("unexpected operator '$op'");
}
else
{ // I don't even want to know what you did to get here
return $this->sdk_trigger("an unexpected error occured");
}
if ($index == strlen($expr))
{
if (in_array($op, $ops))
{ // did we end with an operator? bad.
return $this->sdk_trigger("operator '$op' lacks operand");
}
else
break;
}
while (substr($expr, $index, 1) == ' ')
{ // step the index past whitespace (pretty much turns whitespace
$index++; // into implicit multiplication if no operator is there)
}
}
while (($op = $stack->sdk_pop())!=null)
{ // pop everything off the stack and push onto output
if ($op == '(') return $this->sdk_trigger("expecting ')'"); // if there are (s on the stack, ()s were unbalanced
$output[] = $op;
}
return $output;
}
function sdk_device($val)
{
$valtab = getValue($val);
if (isset($valtab['value']))
return $valtab['value'];
else
return 0;
}
// evaluate postfix notation
function sdk_pfx($tokens, $vars = array())
{
if ($tokens == false) return false;
$stack = new sdk_EvalMathStack;
foreach ($tokens as $token)
{ // nice and easy
// if the token is a binary operator, pop two values off the stack, do the operation, and push the result back on
if (in_array($token, array('+', '-', '*', '/', '^')))
{
if (($op2 = $stack->sdk_pop())===null) return $this->sdk_trigger("internal error 2");
if (($op1 = $stack->sdk_pop())===null) return $this->sdk_trigger("internal error 3");
switch ($token) {
case '+':
$stack->sdk_push($op1+$op2); break;
case '-':
$stack->sdk_push($op1-$op2); break;
case '*':
$stack->sdk_push($op1*$op2); break;
case '/':
if ($op2 == 0) return $this->sdk_trigger("division by zero");
$stack->sdk_push($op1/$op2); break;
case '^':
$stack->sdk_push(pow($op1, $op2)); break;
}
// if the token is a unary operator, pop one value off the stack, do the operation, and push it back on
}
else
if ($token == "_")
{
$stack->sdk_push(-1*$stack->sdk_pop());
// if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on
}
else
if (preg_match("/^([a-z]\w*)\($/", $token, $matches))
{ // it's a function!
$fnn = $matches[1];
if (in_array($fnn, $this->fb)) { // built-in function:
if (($op1 = $stack->sdk_pop())===null) return $this->sdk_trigger("internal error 4");
$fnn = preg_replace("/^arc/", "a", $fnn); // for the 'arc' trig synonyms
switch ($fnn)
{
case "device" :
$stack->sdk_push($this->sdk_device($op1));
break;
case "abs":
$stack->sdk_push(abs($op1));
break;
case "acos":
$stack->sdk_push(acos($op1));
break;
case "asin":
$stack->sdk_push(asin($op1));
break;
case "atan":
$stack->sdk_push(atan($op1));
break;
case "cos":
$stack->sdk_push(cos($op1));
break;
case "deg2rad":
$stack->sdk_push(deg2rad($op1));
break;
case "exp":
$stack->sdk_push(exp($op1));
break;
case "floor":
$stack->sdk_push(floor($op1));
break;
case "log":
$stack->sdk_push(log($op1));
break;
case "pow":
$stack->sdk_push(pow($op1));
break;
case "rad2deg":
$stack->sdk_push(rad2deg($op1));
break;
case "rand":
$stack->sdk_push(rand($op1));
break;
case "round":
$stack->sdk_push(round($op1));
break;
case "sin":
$stack->sdk_push(sin($op1));
break;
case "sqrt":
$stack->sdk_push(sqrt($op1));
break;
}
}
else
if (array_key_exists($fnn, $this->f))
{ // user function
// get args
$args = array();
for ($i = count($this->f[$fnn]['args'])-1; $i >= 0; $i--)
{
if (($args[$this->f[$fnn]['args'][$i]] = $stack->sdk_pop())===null) return $this->sdk_trigger("internal error 5");
}
$stack->sdk_push($this->sdk_pfx($this->f[$fnn]['func'], $args)); // yay... recursion!!!!
}
// if the token is a number or variable, push it on the stack
}
else
{
if (is_numeric($token))
{
$stack->sdk_push($token);
}
else
if (array_key_exists($token, $this->v))
{
$stack->sdk_push($this->v[$token]);
}
else
if (array_key_exists($token, $vars))
{
$stack->sdk_push($vars[$token]);
}
else
{
return $this->sdk_trigger("undefined variable '$token'");
}
}
}
// when we're out of tokens, the stack should have a single element, the final result
if ($stack->count != 1) return $this->sdk_trigger("internal error 6");
return $stack->sdk_pop();
}
// trigger an error, but nicely, if need be
function sdk_trigger($msg)
{
$this->last_error = $msg;
if (!$this->suppress_errors) echo $msg;
return false;
}
}
class sdk_EvalMathStack
{
var $stack = array();
var $count = 0;
function sdk_push($val)
{
$this->stack[$this->count] = $val;
$this->count++;
}
function sdk_pop()
{
if ($this->count > 0)
{
$this->count--;
return $this->stack[$this->count];
}
return null;
}
function sdk_last($n=1)
{
if (isset($this->stack[$this->count-$n]))
{
return $this->stack[$this->count-$n];
}
return;
}
}
?>
nico_du_57 a écrit:Super, merci pour toutes ces informations. J'ai vais faire cela.
Pour répondre à ta précédente question concernant le totalisateur, j'ai une valeur de production de mes panneaux solaires par minute de la part du device. Pourrais-je me servir de ces données dans ce cas de figure?
nico_du_57 a écrit:Par contre, peux-tu me dire à quelle valeur correspond "dt"? l'intervalle de temps sur lequel est calculée la moyenne?
opa95 a écrit:Il faudrait un peu plus de détail.
Quel est le nom du php que tu as sauvé : calculator.php ou calculator1.php?
Avec une moyenne sur 1 minute, et une fréquence de 1 mesure par minute, tu risques de ne rien voir.
Il vaudrait mieux VAR2=1 et une mesure toute les 5 minutes.
Quelle est l'erreur affichée?
Sinon, passe en mode "tester" et montre moi le résultat du XML
nico_du_57 a écrit:opa95 a écrit:Il faudrait un peu plus de détail.
Quel est le nom du php que tu as sauvé : calculator.php ou calculator1.php?
Avec une moyenne sur 1 minute, et une fréquence de 1 mesure par minute, tu risques de ne rien voir.
Il vaudrait mieux VAR2=1 et une mesure toute les 5 minutes.
Quelle est l'erreur affichée?
Sinon, passe en mode "tester" et montre moi le résultat du XML
En fait je ne sais pas comment modifier le nom du php...
http://localhost/script/?exec=calculator.php&formula=[VAR1]
http://localhost/script/?exec=calculator1.php&formula=[VAR1]&dt=[VAR2]
Retour vers Scripts & Périphériques du store
Utilisateurs parcourant ce forum : Aucun utilisateur inscrit et 27 invité(s)