espeasy sonoff pulse counter Metern

Post Reply
megamarco83
Posts: 97
Joined: Tue Apr 14, 2015 9:25 am

Re: espeasy sonoff pulse counter Metern

Post by megamarco83 » Fri Dec 21, 2018 12:41 am

jeanmarc wrote:
Wed Dec 19, 2018 4:29 pm
For the live you need to set the value $val_live, i dunno what it is.
For the reboot bug, change the line 48 in "Retrieve last know value in csv" part (was int) :

Code: Select all

datareturn = (float) trim($array[$meternum]);
hi Jeanmarc i find a little bug on reboot.
if before reboot the raspberry, the espeasy has a total of 5 for example
in the json i have
{"virt_tot":1217.33,"esp_count":0.05}
in the csv i have 1217.33

now i reboot the raspberry.

i have after the reboot that my value recorded in csv will be 1217.38 ----> previous 1217.33 + 0.05
but when i reboot the value should not be added with 0.05 but should be the same of csv.
could be possible to add a check in php? if there is the json -> add the total taken from espeasy
if there isn't the json (means reboot) -> simply copy the value in json and reset the counter total (i do not know how to reset the total, but i know that command: http://IP_OF_ESP/?cmd=reboot
will reboot the espeasy.

otherwise, i have this in cron:
07 05 5,10,15,20,25,30 * * root /sbin/shutdown -r now

every 5 days at 05:07 i reboot the raspberry
how i can add in cron the command to reboot also the espeasy?
http://192.168.0.204/?cmd=reboot

thanks

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

Re: espeasy sonoff pulse counter Metern

Post by jeanmarc » Fri Dec 21, 2018 7:36 am

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://IP_OF_ESP/json?tasknr=2'; // espeasy url
$initial   = 0; // initial virtual meter value
$urlreboot = 'http://IP_OF_ESP/?cmd=reboot'; // restart counting on reboot

// 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 = (float) 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['TaskValues'][0]['Value'];
    $val_count = $espjson['TaskValues'][1]['Value'];
    $val_count /= 100; // 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 {
        // Reboot
        $ch = curl_init($urlreboot);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 3000); // error
        if ((curl_exec($ch)) === false) {
            die(curl_error($ch) . "\n");
        }
        curl_close($ch);
        
        $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
            $previous['virt_tot'] = retrievecsv($metnum, $lines, ${'PASSO' . $metnum});
        } else { // restarting from scratch !
            $previous['virt_tot'] = $initial;
        }
        $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);
    }
}
?>
Why rebooting everyday, it's not windows :geek:

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

Re: espeasy sonoff pulse counter Metern

Post by megamarco83 » Fri Dec 21, 2018 11:11 am

jeanmarc wrote:
Fri Dec 21, 2018 7:36 am
Try this
hi, i try and the esp is rebooting
but if i reboot the raspberry, at new boot the json is created before rebooting esp, so the new json created at raspberry boot is with the old count before reboot esp.
can we reboot the esp before reading the json if json is not present?

jeanmarc wrote:
Fri Dec 21, 2018 7:36 am
Why rebooting everyday, it's not windows :geek:
ahahah :)
i reboot raspberry evry 5 days to delete temporary files and to have a "clean" data :-)
but enyway if we not reboot the espeasy if there isn't the json file, at manual reboot, we will have errors on gas counting, because php will add the the "total" thinking on a usage, but was only reboot not usage :)
so i think that php should be reboot in every case the esp if json is not present, right?

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

Re: espeasy sonoff pulse counter Metern

Post by jeanmarc » Fri Dec 21, 2018 11:59 am

That's what it should do, see aroud the line 143.
Did you set a volatile path for req_espeasy.json file as /dev/shm/ ?

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

Re: espeasy sonoff pulse counter Metern

Post by megamarco83 » Fri Dec 21, 2018 3:00 pm

jeanmarc wrote:
Fri Dec 21, 2018 11:59 am
That's what it should do, see aroud the line 143.
Did you set a volatile path for req_espeasy.json file as /dev/shm/ ?
yes my req_espeasy.json is in /dev/shm/

i test better:

now i have inside req_espeasy.json
{"virt_tot":1218.10,"esp_count":0.02}

Code: Select all

pi@raspberrypi:~ $ curl http://192.168.0.204/json?tasknr=3
{
"TaskValues": [
{"ValueNumber":1,
"Name":"Count",
"NrDecimals":0,
"Value":0
},
{"ValueNumber":2,
"Name":"Total",
"NrDecimals":0,
"Value":2
},
{"ValueNumber":3,
"Name":"Time",
"NrDecimals":0,
"Value":958117
}],
"TTL":10000,
"DataAcquisition": [
{"Controller":1,
"IDX":0,
"Enabled":"false"
},
{"Controller":2,
"IDX":0,
"Enabled":"false"
},
{"Controller":3,
"IDX":0,
"Enabled":"false"
}],
"TaskInterval":10,
"Type":"Generic - Pulse counter",
"TaskName":"gas",
"TaskEnabled":"true",
"TaskNumber":3
}
you can see that esp has total=2 so recorded correctly in req_espeasy.json


and metern dashboard table is:
gas --- 0,79 m3 1.218,12 m3

now i reboot reaspberry with sudo reboot (hour 14:52)

now raspberry is rebooted (hour 14:53) i can see in /run/shm the json file related to nm_memory.json and nm_livememory.json but NOT req_espeasy.json (because it will be created every 5min so not yet created) (still 14:53) and my esp is not rebooted

in metern gas meter total is 1.218,12
gas --- 0,79 m3 1.218,12 m3
my esp is not rebooted and json not created yet

now 14:55 my is esp is rebooted
in /run/shm i see the others json that are updated at 14:55 but i can't see again req_espeasy.json till 14:55:21 that is now created

but now meter show:
gas --- 0,81 m3 1.218,14 m3

also in the csv i find 1218.14 at 14:55

but the total is 0 in esp

Code: Select all

pi@raspberrypi:~ $ curl http://192.168.0.204/json?tasknr=3
{
"TaskValues": [
{"ValueNumber":1,
"Name":"Count",
"NrDecimals":0,
"Value":0
},
{"ValueNumber":2,
"Name":"Total",
"NrDecimals":0,
"Value":0
},
{"ValueNumber":3,
"Name":"Time",
"NrDecimals":0,
"Value":958117
}],
"TTL":10000,
"DataAcquisition": [
{"Controller":1,
"IDX":0,
"Enabled":"false"
},
{"Controller":2,
"IDX":0,
"Enabled":"false"
},
{"Controller":3,
"IDX":0,
"Enabled":"false"
}],
"TaskInterval":10,
"Type":"Generic - Pulse counter",
"TaskName":"gas",
"TaskEnabled":"true",
"TaskNumber":3
}

it seams that at the time of reboot (14:52) and when the system come back on (14:53) the value is correct. but metern record the data in csv before rebooting esp

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

Re: espeasy sonoff pulse counter Metern

Post by megamarco83 » Fri Dec 21, 2018 3:40 pm

small update with second try

now is 15:27
gas --- 0,98 m3 1.218,31 m3

json:

Code: Select all

{"virt_tot":1218.31,"esp_count":0.19}
updated at 15:25:19

esp total count = 19

now at 15:27 i reboot system and nm_memory.json is created at 15:28:25
my esp is not reboot
metern show:

Code: Select all

gas	---	0,98 m3	1.218,31 m3
now are 15:25 and json of esp is not created
esp is rebooted

now are 15:26 and json esp this time is not created...all meter in metern show 0 (lost connection)...i guess that req_espeasy.php is going in a loop because it not find the json.

now are 15:28 and json of esp is not yet created
my esp is on line from 3minutes
all metern meters are still zero (lost connection) nm_memory.json is still updated at 15:28:25

now are 15:36 and json of esp are not yest created
my esp is on line from 6 minutes
all metern meters are still zero (lost connection) nm_memory.json is still updated at 15:28:25

i now lunch esp php manually using test in metern
result:

Code: Select all

20(1218.31*m3) is a valid entry !
json of esp is now creatd
metern go online and all meters now are working
as you can see the report o json is now correct, because esp was rebooted before creating json, so value are correct, but json will be never created till i launch manually the command inside metern...



could be a solution to put the command:

Code: Select all

req_espeasy -total
inside the indicator not logged?
so when mN_ILIVEMEMORY.json will create the req_espeasy.json?

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

Re: espeasy sonoff pulse counter Metern

Post by jeanmarc » Fri Dec 21, 2018 4:59 pm

Maybe 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://IP_OF_ESP/json?tasknr=2'; // espeasy url
$initial   = 0; // initial virtual meter value
$urlreboot = 'http://IP_OF_ESP/?cmd=reboot'; // restart counting on reboot

// 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 = (float) 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
    if (!file_exists($prevfile)) {
        // Reboot
        $ch = curl_init($urlreboot);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 3000); // error
        if ((curl_exec($ch)) === false) {
            die(curl_error($ch) . "\n");
        }
        curl_close($ch);
        sleep(1);
    }
    
    $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['TaskValues'][0]['Value'];
    $val_count = $espjson['TaskValues'][1]['Value'];
    $val_count /= 100; // 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
            $previous['virt_tot'] = retrievecsv($metnum, $lines, ${'PASSO' . $metnum});
        } else { // restarting from scratch !
            $previous['virt_tot'] = $initial;
        }
        $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);
    }
}
?>

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

Re: espeasy sonoff pulse counter Metern

Post by megamarco83 » Fri Dec 21, 2018 5:30 pm

hi jeanmarc with this one we solved the issue of rebooting esp at 05 or 10 or 15 or 20 ... minutes

i reboot raspberry at 17:27 and esp was rebootet at 17:28 (when raspberry come back alive)

the value on csv is correct, but all the json are now blocked (no updated) and all live value are zero (lost connection)

if i try to execute manually the command inside metern on gas meter i receive:

Code: Select all

Command : req_espeasy -total

Connection timed out after 3001 milliseconds is not valid, the correct format is 20(1234.5*m3)
and when i execute this command my esp is rebooted. (was alive)

and also after execute that above command esp reboot and is again alive, but no jsons updated (all meters are still to zero) and no req_espeasy.json

if i click again to test the gas command, esp is rebooted again

so it means that is going in a loop... and req_espeasy.json is no more created and still not present also after the 5minutes


p.s. for the gas i'm using the meter20 with only command:

Code: Select all

 req_espeasy -total

and i put also the same command also in Indicator(s) configuration (Not logged)

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

Re: espeasy sonoff pulse counter Metern

Post by jeanmarc » Fri Dec 21, 2018 5:43 pm

So 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://IP_OF_ESP/json?tasknr=2'; // espeasy url
$initial   = 0; // initial virtual meter value
$urlreboot = 'http://IP_OF_ESP/?cmd=reboot'; // restart counting on reboot

// 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 = (float) trim($array[$meternum]);
        if ($datareturn == '') {
            $datareturn = null;
        }
        if ($j == $contalines) {
            $datareturn = 0;
        }
    }
    if ($datareturn > $passo) {
        $datareturn -= $passo;
    }
    return $datareturn;
}

if ($argv[1] == '-total' && !file_exists($prevfile)) {
	// Reboot
	$ch = curl_init($urlreboot);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 3000); // error
	if ((curl_exec($ch)) === false) {
	    die(curl_error($ch) . "\n");
	}
	curl_close($ch);
	sleep(1);
}

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['TaskValues'][0]['Value'];
    $val_count = $espjson['TaskValues'][1]['Value'];
    $val_count /= 100; // 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
            $previous['virt_tot'] = retrievecsv($metnum, $lines, ${'PASSO' . $metnum});
        } else { // restarting from scratch !
            $previous['virt_tot'] = $initial;
        }
        $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);
    }
}
?>
How long does it take for your esp to reboot ?

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

Re: espeasy sonoff pulse counter Metern

Post by megamarco83 » Fri Dec 21, 2018 8:07 pm

jeanmarc wrote:
Fri Dec 21, 2018 5:43 pm
So this one..

How long does it take for your esp to reboot ?
it takes about 6-7 seconds to take the network and warm-up
so i need to change the sleep inside the code from 1second to 8seconds?

Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest