par opa95 » 20 Août 2024 07:20
bonjour bigjohn007
bigjohn007 a écrit:Bonjour,
J'ai une valeur //power qui peut être positive ou négative. J'ai besoin qu'elle soit toujours positive.
J'ai une valeur //pf qui peut être positive ou négative. J'ai besoin qu'elle garde son signe d'origine.
Ensuite je cherche à faire la division entre les deux. J'ai utilisé la fonction abs mais cela ne fonctionne pas.
- Code : Tout sélectionner
abs(//power) div //pf
Power est un nombre décimal, idem pour pf. L'expression "//power div //pf" fonctionne
il faut utiliser le plugin "Calculateur Mathématique" du store qui utilise le script "calculator.php".
Tu peux suivre les discussions sur le forum :
[url]https://forum.eedomus.com/viewtopic.php?f=50&t=11449&hilit=abs
[/url]
Le script en ligne comporte depuis l'origine 2 petits bugs qui ne devraient pas te gêner : la fonction "pow" ne marche pas (c'est une fonction à 2 paramètres au lieu de 1) et quelques opérations utilisant une valeur nulle peuvent na pas fonctionner.
Pour ton problème, la formule sera de créer 2 devices initiaux, un qui récupère la puissance d'adresse ip_power : xxxxxxx et un qui récupère la seconde valeur ip_pf : yyyyyyy
Ensuite tu mets dans "Calculateur Mathématique" (dans VAR1) la valeur de la formule :
- Code : Tout sélectionner
abs((device(xxxxxx))/device(yyyyyy))
.
Si tu as des problèmes de résultat, j'ai diverses versions de "calculator.php" qui corrigent les bugs et créent de nouvelles fonctions, opérateurs,... dons certaines sont encore en cours de nettoyage.
Voici la version simple (V1.0.1) qui corrige les bugs, elle peut remplacer le script original (identique à l'original, sans les bugs).
- Code : Tout sélectionner
<?php
define('VER', '1.0.1');
// Create an object to compute the formula
$evaleedomus = new sdk_EvalMath;
// Get formula from VAR1
$formula = getArg("formula");
if (!isset($formula)) $formula = "0";
// basic evaluation:
$result = $evaleedomus->sdk_evaluate($formula);
@sdk_header('text/xml');
$xml = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
$xml .= "<!-- Ver ".VER."-->\n";
$xml .= "<result>".$result."</result>";
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
Version 1.0 :version initiale
Version 1.0.1 :Corrections bugs (opa95) : suppressio pow(), correction tests (== -> ===)
================================================================================
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', '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 ($o===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 "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;
}
}
?>
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)