espeasy sonoff pulse counter Metern

jeanmarc
Posts: 1764
Joined: Thu Aug 29, 2013 7:16 am

Re: espeasy sonoff pulse counter Metern

Post by jeanmarc » Sun Dec 09, 2018 6:36 pm

sorry, there was a typo, that's print_r($espjson)
Could you retry ?
You cannot set a starting value, i could look at that later on.

megamarco83
Posts: 69
Joined: Tue Apr 14, 2015 9:25 am

Re: espeasy sonoff pulse counter Metern

Post by megamarco83 » Sun Dec 09, 2018 6:39 pm

Code: Select all

pi@raspberrypi:~ $ req_espeasy -total
Array
(
    [TaskValues] => Array
        (
            [0] => Array
                (
                    [ValueNumber] => 1
                    [Name] => Count
                    [NrDecimals] => 2
                    [Value] => 0
                )

            [1] => Array
                (
                    [ValueNumber] => 2
                    [Name] => Total
                    [NrDecimals] => 2
                    [Value] => 26
                )

            [2] => Array
                (
                    [ValueNumber] => 3
                    [Name] => Time
                    [NrDecimals] => 2
                    [Value] => 63040
                )

        )

    [TTL] => 1000
    [DataAcquisition] => Array
        (
            [0] => Array
                (
                    [Controller] => 1
                    [IDX] => 0
                    [Enabled] => false
                )

            [1] => Array
                (
                    [Controller] => 2
                    [IDX] => 0
                    [Enabled] => false
                )

            [2] => Array
                (
                    [Controller] => 3
                    [IDX] => 0
                    [Enabled] => false
                )

        )

    [TaskInterval] => 1
    [Type] => Generic - Pulse counter
    [TaskName] => gas
    [TaskEnabled] => true
    [TaskNumber] => 3
)
Abording: Cannot get last Total value

jeanmarc
Posts: 1764
Joined: Thu Aug 29, 2013 7:16 am

Re: espeasy sonoff pulse counter Metern

Post by jeanmarc » Mon Dec 10, 2018 10:05 am

hmm, could you rather try this as test.php?

Code: Select all

#!/usr/bin/php
<?php
$url      = 'http://192.168.1.140/json?tasknr=2'; // espeasy url

   $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 3000); // error
    $espjson = array();
    if (($espjson = curl_exec($ch)) === false) {
        die(curl_error($ch) . "\n");
    }
    curl_close($ch);

echo $espjson;
$espjson = json_decode($espjson, true);
    // Test :
    //print_r($espjson);

echo "is that $espjson['TaskValues'][0][1]['Value'] ?";

?>


megamarco83
Posts: 69
Joined: Tue Apr 14, 2015 9:25 am

Re: espeasy sonoff pulse counter Metern

Post by megamarco83 » Mon Dec 10, 2018 10:11 am

i create test.php change my sonoff IP 192.168.0.204 and my task = 3
give it the permission 755
then:

Code: Select all

pi@raspberrypi:/var/www/comapps $ sudo php test.php
PHP Parse error:  syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in /var/www/comapps/test.php on line 19
pi@raspberrypi:/var/www/comapps $

jeanmarc
Posts: 1764
Joined: Thu Aug 29, 2013 7:16 am

Re: espeasy sonoff pulse counter Metern

Post by jeanmarc » Mon Dec 10, 2018 10:18 am

that's normal, you can comment echo "is that .."
I am looking for the json return.

megamarco83
Posts: 69
Joined: Tue Apr 14, 2015 9:25 am

Re: espeasy sonoff pulse counter Metern

Post by megamarco83 » Mon Dec 10, 2018 11:00 am

jeanmarc wrote:
Mon Dec 10, 2018 10:18 am
that's normal, you can comment echo "is that .."
I am looking for the json return.
ok, i comment the line that you suggest, and this is the output now:

Code: Select all

pi@raspberrypi:/var/www/comapps $ sudo php test.php
{
"TaskValues": [
{"ValueNumber":1,
"Name":"Count",
"NrDecimals":2,
"Value":0.00
},
{"ValueNumber":2,
"Name":"Total",
"NrDecimals":2,
"Value":0.00
},
{"ValueNumber":3,
"Name":"Time",
"NrDecimals":2,
"Value":0.00
}],
"TTL":1000,
"DataAcquisition": [
{"Controller":1,
"IDX":0,
"Enabled":"false"
},
{"Controller":2,
"IDX":0,
"Enabled":"false"
},
{"Controller":3,
"IDX":0,
"Enabled":"false"
}],
"TaskInterval":1,
"Type":"Generic - Pulse counter",
"TaskName":"gas",
"TaskEnabled":"true",
"TaskNumber":3
}

jeanmarc
Posts: 1764
Joined: Thu Aug 29, 2013 7:16 am

Re: espeasy sonoff pulse counter Metern

Post by jeanmarc » Mon Dec 10, 2018 2:06 pm

Ok try this one :

Code: Select all

#!/usr/bin/php
<?php
// A simple script to request a espeasy counter that doesn't always increase (after a surge) and make virtual meter.
// You should set your meter ID in meterN and define a non null pass over value (like 100000)
// chmod +x then ln -s /srv/http/comapps/req_espeasy.php /usr/bin/req_espeasy
// Use req_espeasy -total as main command -live as live command

// Config
$pathtomn = '/srv/http/metern'; // without / at the end
$metnum   = 1; // Vitual meter number
$url      = 'http://192.168.1.140/json?tasknr=2'; // espeasy url

// No edit should be needed bellow
if (isset($_SERVER['REMOTE_ADDR'])) {
    die('Direct access not permitted');
}
if (isset($argv[2])) {
    die("Abording: Too many arguments\n");
}
if (!isset($argv[1])) {
    die("\nUsage: req_espeasy { total | live | Humidity | prev }\n
    -total : Virtual total counter
    -live : Counter live value
    -Humidity : Show humidity value
    -prev : Show previous file
    \n");
}
// Save previous values in a file, make sure the http user can write there
$prevfile = '/dev/shm/req_espeasy.json';
if (file_exists($prevfile) && !is_writable($prevfile)) {
    die("$prevfile not writable");
}

define('checkaccess', TRUE);
include("$pathtomn/config/config_main.php");
include("$pathtomn/config/memory.php");
include("$pathtomn/config/config_met$metnum.php");

function retrievecsv($meternum, $csvarray, $passo) // Retrieve last know value in csv
{
    $datareturn = null;
    $contalines = count($csvarray);
    $j          = 0;
    while (!isset($datareturn)) {
        $j++;
        $array      = preg_split('/,/', $csvarray[$contalines - $j]);
        $datareturn = (int) trim($array[$meternum]);
        if ($datareturn == '') {
            $datareturn = null;
        }
        if ($j == $contalines) {
            $datareturn = 0;
        }
    }
    if ($datareturn > $passo) {
        $datareturn -= $passo;
    }
    return $datareturn;
}

if ($argv[1] == '-live' || $argv[1] == '-total' || $argv[1] == '-Humidity') { // Get last values
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 3000); // error
    $espjson = array();
    if (($espjson = curl_exec($ch)) === false) {
        die(curl_error($ch) . "\n");
    }
    curl_close($ch);
    
    // Testing
    /*
    $espjson = '
    {  
    "TaskValues":[  
    {  
    "ValueNumber":1,
    "Name":"Count",
    "NrDecimals":2,
    "Value":10.00
    },
    {  
    "ValueNumber":2,
    "Name":"Total",
    "NrDecimals":2,
    "Value":0.00
    },
    {  
    "ValueNumber":3,
    "Name":"Time",
    "NrDecimals":2,
    "Value":0.00
    }
    ],
    "TTL":1000,
    "DataAcquisition":[  
    {  
    "Controller":1,
    "IDX":0,
    "Enabled":"false"
    },
    {  
    "Controller":2,
    "IDX":0,
    "Enabled":"false"
    },
    {  
    "Controller":3,
    "IDX":0,
    "Enabled":"false"
    }
    ],
    "TaskInterval":1,
    "Type":"Generic - Pulse counter",
    "TaskName":"gas",
    "TaskEnabled":"true",
    "TaskNumber":3
    }';
    */
    $espjson   = json_decode($espjson, true);
    // Get values from json
    //$val_live  = $espjson['Count'];
    $val_count = $espjson['TaskValues'][1]['Value'];
    $val_humid = $espjson['TaskValues'][1]['Value'];
    //print_r($espjson);
}



if ($argv[1] == '-live') {
    if (!isset($val_live)) {
        die("Abording: Cannot get live Count value\n");
    }
    $val    = (float) $val_live;
    $outstr = utf8_decode("${'LID' . $metnum}($val*${'LIVEUNIT' . $metnum})\n");
    echo "$outstr";
} elseif ($argv[1] == '-total') {
    if (!isset($val_count)) {
        die("Abording: Cannot get last Total value\n");
    }
    // Retrieve previous virtual meter value
    if (file_exists($prevfile)) {
        $data     = file_get_contents($prevfile);
        $previous = json_decode($data, true);
    } else {
        $tdfile  = date('Ymd');
        $tdfile  = $pathtomn . '/data/csv/' . $tdfile . '.csv';
        $ytdfile = date('Ymd', strtotime("-1 day"));
        $ytdfile = $pathtomn . '/data/csv/' . $ytdfile . '.csv';
        
        if (file_exists($tdfile)) {
            $lines = file($tdfile);
        } else if (file_exists($ytdfile)) {
            $lines = file($ytdfile);
        }
        if (file_exists($tdfile) || file_exists($ytdfile)) { // today or yesterday
            $contalines           = count($lines);
            $previous['virt_tot'] = retrievecsv($metnum, $lines, ${'PASSO' . $metnum});
        } else { // restarting from scratch !
            $previous['virt_tot'] = 0;
        }
        $previous['esp_count'] = 0;
    }
    $last = (float) $val_count;
    $prev = (float) $previous['esp_count'];
    if ($last > $prev) {
        $diff = $last - $prev; // Increment vitural meter
        $previous['virt_tot'] += $diff;
        if ($previous['virt_tot'] >= ${'PASSO' . $metnum}) { // passed over
            $previous['virt_tot'] -= ${'PASSO' . $metnum};
        }
        $previous['esp_count'] = $espjson['Total'];
    } elseif ($last < $prev) { // surge or esp counter restart
        $previous['esp_count'] = 0;
    }
    
    // Saving previous values
    $data = json_encode($previous);
    file_put_contents($prevfile, $data);
    $val    = $previous['virt_tot'];
    // Output
    $outstr = utf8_decode("${'ID' . $metnum}($val*${'UNIT' . $metnum})\n");
    echo "$outstr";
} elseif ($argv[1] == '-Humidity') {
    $val    = $val_humid;
    $outstr = utf8_decode("Humidity($val*hum)\n");
    echo "$outstr";
} elseif ($argv[1] == '-prev') {
    if (file_exists($prevfile)) {
        echo "\n$prevfile :\n\n";
        $data     = file_get_contents($prevfile);
        $previous = json_decode($data, true);
        print_r($previous);
    }
}
?>
Where is your live value ?

megamarco83
Posts: 69
Joined: Tue Apr 14, 2015 9:25 am

Re: espeasy sonoff pulse counter Metern

Post by megamarco83 » Mon Dec 10, 2018 2:42 pm

my task on espeasy (number 3) is showing:
count=0
total=4
time=5990

Code: Select all

pi@raspberrypi:/var/www/comapps $ sudo req_espeasy -total
PHP Notice:  Undefined index: Total in /var/www/comapps/req_espeasy.php on line 172
20(1207*m3)

pi@raspberrypi:/var/www/comapps $ sudo req_espeasy -live
Abording: Cannot get live Count value
pi@raspberrypi:/var/www/comapps $
i set in metern metr20
name=gas
type=gas
meterid=20
command = req_espeasy -total
unit= m3
passover= 100000


for live:
meterid=20
mode=value
live command= req_espeasy -live
live unit=m3

there is something wrong in my configuration?

is i use test inside metern:


Command : req_espeasy -total

PHP Notice: Undefined index: Total in /var/www/comapps/req_espeasy.php on line 17220(1215*m3) is not valid, the correct format is 20(1234.5*m3)



Command : req_espeasy -total

Abording: Cannot get live Count value is not valid, the correct format is 20(1234.5*m3)





is my gas counter is starting from value = 1195.07 where i can set it?


EDIT: last question: my gas meter has this conversion: evey n° 1 impulse = 0.01m3 gas
where is the conversion setting in the script, there isn't?

jeanmarc
Posts: 1764
Joined: Thu Aug 29, 2013 7:16 am

Re: espeasy sonoff pulse counter Metern

Post by jeanmarc » Mon Dec 10, 2018 3:13 pm

ok ok, hard to debug like that. Your config is ok, try this

Code: Select all

#!/usr/bin/php
<?php
// A simple script to request a espeasy counter that doesn't always increase (after a surge) and make virtual meter.
// You should set your meter ID in meterN and define a non null pass over value (like 100000)
// chmod +x then ln -s /srv/http/comapps/req_espeasy.php /usr/bin/req_espeasy
// Use req_espeasy -total as main command -live as live command

// Config
$pathtomn = '/srv/http/metern'; // without / at the end
$metnum   = 1; // Vitual meter number
$url      = 'http://192.168.1.140/json?tasknr=2'; // espeasy url

// No edit should be needed bellow
if (isset($_SERVER['REMOTE_ADDR'])) {
    die('Direct access not permitted');
}
if (isset($argv[2])) {
    die("Abording: Too many arguments\n");
}
if (!isset($argv[1])) {
    die("\nUsage: req_espeasy { total | live | Humidity | prev }\n
    -total : Virtual total counter
    -live : Counter live value
    -Humidity : Show humidity value
    -prev : Show previous file
    \n");
}
// Save previous values in a file, make sure the http user can write there
$prevfile = '/dev/shm/req_espeasy.json';
if (file_exists($prevfile) && !is_writable($prevfile)) {
    die("$prevfile not writable");
}

define('checkaccess', TRUE);
include("$pathtomn/config/config_main.php");
include("$pathtomn/config/memory.php");
include("$pathtomn/config/config_met$metnum.php");

function retrievecsv($meternum, $csvarray, $passo) // Retrieve last know value in csv
{
    $datareturn = null;
    $contalines = count($csvarray);
    $j          = 0;
    while (!isset($datareturn)) {
        $j++;
        $array      = preg_split('/,/', $csvarray[$contalines - $j]);
        $datareturn = (int) trim($array[$meternum]);
        if ($datareturn == '') {
            $datareturn = null;
        }
        if ($j == $contalines) {
            $datareturn = 0;
        }
    }
    if ($datareturn > $passo) {
        $datareturn -= $passo;
    }
    return $datareturn;
}

if ($argv[1] == '-live' || $argv[1] == '-total' || $argv[1] == '-Humidity') { // Get last values
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 3000); // error
    $espjson = array();
    if (($espjson = curl_exec($ch)) === false) {
        die(curl_error($ch) . "\n");
    }
    curl_close($ch);
    
    // Testing
    /*
    $espjson = '
    {  
    "TaskValues":[  
    {  
    "ValueNumber":1,
    "Name":"Count",
    "NrDecimals":2,
    "Value":10000.00
    },
    {  
    "ValueNumber":2,
    "Name":"Total",
    "NrDecimals":2,
    "Value":1000.00
    },
    {  
    "ValueNumber":3,
    "Name":"Time",
    "NrDecimals":2,
    "Value":0.00
    }
    ],
    "TTL":1000,
    "DataAcquisition":[  
    {  
    "Controller":1,
    "IDX":0,
    "Enabled":"false"
    },
    {  
    "Controller":2,
    "IDX":0,
    "Enabled":"false"
    },
    {  
    "Controller":3,
    "IDX":0,
    "Enabled":"false"
    }
    ],
    "TaskInterval":1,
    "Type":"Generic - Pulse counter",
    "TaskName":"gas",
    "TaskEnabled":"true",
    "TaskNumber":3
    }';
*/    
    $espjson   = json_decode($espjson, true);
    // Get values from json
    //$val_live  = $espjson['Count'];
    $val_count = $espjson['TaskValues'][1]['Value'];
    $val_count /=1000; // 1 impulse = 0.01m3 gas
    $val_humid = $espjson['TaskValues'][1]['Value'];
    //print_r($espjson);
}



if ($argv[1] == '-live') {
    if (!isset($val_live)) {
        die("Abording: Cannot get live Count value\n");
    }
    $val    = (float) $val_live;
    $outstr = utf8_decode("${'LID' . $metnum}($val*${'LIVEUNIT' . $metnum})\n");
    echo "$outstr";
} elseif ($argv[1] == '-total') {
    if (!isset($val_count)) {
        die("Abording: Cannot get last Total value\n");
    }
    // Retrieve previous virtual meter value
    if (file_exists($prevfile)) {
        $data     = file_get_contents($prevfile);
        $previous = json_decode($data, true);
    } else {
        $tdfile  = date('Ymd');
        $tdfile  = $pathtomn . '/data/csv/' . $tdfile . '.csv';
        $ytdfile = date('Ymd', strtotime("-1 day"));
        $ytdfile = $pathtomn . '/data/csv/' . $ytdfile . '.csv';
        
        if (file_exists($tdfile)) {
            $lines = file($tdfile);
        } else if (file_exists($ytdfile)) {
            $lines = file($ytdfile);
        }
        if (file_exists($tdfile) || file_exists($ytdfile)) { // today or yesterday
            $contalines           = count($lines);
            $previous['virt_tot'] = retrievecsv($metnum, $lines, ${'PASSO' . $metnum});
        } else { // restarting from scratch !
            $previous['virt_tot'] = 0;
        }
        $previous['esp_count'] = 0;
    }
    $last = (float) $val_count;
    $prev = (float) $previous['esp_count'];
    if ($last > $prev) {
        $diff = $last - $prev; // Increment vitural meter
        $previous['virt_tot'] += $diff;
        if ($previous['virt_tot'] >= ${'PASSO' . $metnum}) { // passed over
            $previous['virt_tot'] -= ${'PASSO' . $metnum};
        }
        $previous['esp_count'] = $val_count;
    } elseif ($last < $prev) { // surge or esp counter restart
        $previous['esp_count'] = 0;
    }
    
    // Saving previous values
    $data = json_encode($previous);
    file_put_contents($prevfile, $data);
    $val    = $previous['virt_tot'];
    // Output
    $outstr = utf8_decode("${'ID' . $metnum}($val*${'UNIT' . $metnum})\n");
    echo "$outstr";
} elseif ($argv[1] == '-Humidity') {
    $val    = $val_humid;
    $outstr = utf8_decode("Humidity($val*hum)\n");
    echo "$outstr";
} elseif ($argv[1] == '-prev') {
    if (file_exists($prevfile)) {
        echo "\n$prevfile :\n\n";
        $data     = file_get_contents($prevfile);
        $previous = json_decode($data, true);
        print_r($previous);
    }
}
?>
You'll see at line 121 how to get values from your json.
You cannot set a starting value yet, i have to find some times to tweak the script.

megamarco83
Posts: 69
Joined: Tue Apr 14, 2015 9:25 am

Re: espeasy sonoff pulse counter Metern

Post by megamarco83 » Mon Dec 10, 2018 3:37 pm

jeanmarc wrote:
Mon Dec 10, 2018 3:13 pm
ok ok, hard to debug like that. Your config is ok, try this

You'll see at line 121 how to get values from your json.
You cannot set a starting value yet, i have to find some times to tweak the script.
ok, i try also this new script now total is working, but on my understanding is not correct the total 1202...
when you think that you could have time we can have a look on it better?
thanks!

Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest