espeasy sonoff pulse counter Metern

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

Re: espeasy sonoff pulse counter Metern

Post by jeanmarc » Fri Dec 21, 2018 10:35 pm

yup try that :ugeek:

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

Re: espeasy sonoff pulse counter Metern

Post by megamarco83 » Sat Nov 09, 2019 1:24 pm

jeanmarc wrote:
Fri Dec 21, 2018 10:35 pm
yup try that :ugeek:
Hi jeanmarc, i'm using pulse counter up to now sice 6months and it works good. The problem is that espeasy some times is blocking due to a problem with pulse sensor that is interfering with espeasy firmware. I asked on espeasy forum and it seams that is a know bug. What is happening is that esp reboot itself and the problem linked with metern is that sometimes, not every time, when esp reboot metern will be blocked. I mean that i find metern ON but all the counters are at zero value and the graphics are blocked. To make metern run i need semply to login as adim in metern and thet put it off and in a while on again. In this case metern will be working again.
I have donoticZ with a script that ping all IP addresses of my esp and if someone is not respond i will have a notify. I would like to extend this feature to metern, can you suggest to me how i can check if metern is blocked? Thanks

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

Re: espeasy sonoff pulse counter Metern

Post by jeanmarc » Sat Nov 09, 2019 1:39 pm

You could make a script that restart mN if your esp in not pingable (call bootmn.php)
But, there might be a problem if your esp don't respond mN will restart continuously then.. need some sort of restart counter :think:

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

Re: espeasy sonoff pulse counter Metern

Post by megamarco83 » Sat Nov 09, 2019 1:49 pm

Yes, i think that it will create a loop of metern reboot.
But for me is not a problem login to metern as admin and then make it off and then on again.
But how i can 'ping' / check if metern is blocked?
Thanks

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

Re: espeasy sonoff pulse counter Metern

Post by jeanmarc » Sat Nov 09, 2019 4:08 pm

I come up with this, use pingtester -start &

Code: Select all

 <?php
// A simple script to ping a device then do a command 
// ln -s /srv/http/comapps/pingtester.php /usr/bin/pingtester and chmod +x pingtester.php

$ip = '192.168.0.1';
$docmd  = '/usr/bin/curl http://localhost/metern/scripts/bootmn.php';

function pingDomain($domain)
{
    $starttime = microtime(true);
    $file      = @fsockopen($domain, 80, $errno, $errstr, 10);
    $stoptime  = microtime(true);
    $status    = 0;
    
    if (!$file) {
        $status = -1;
    } else {
        fclose($file);
        $status = ($stoptime - $starttime) * 1000;
        $status = floor($status);
    }
    return $status;
}

if (isset($argv[1])) {
	if ($argv[1] == '-start') {
		while (true) {
		    $time = 0;
		    $time = pingDomain("$ip");
		    if ($time == -1) { // Connection broken
		        exec($docmd);
		    }
		    sleep(600); // check each 5 min
		}
		
	} elseif ($argv[1] == '-stop') {
		sleep(1);
		exec('pkill -f pingtester > /dev/null 2>&1 &');
	} else {
		die("Abording: no valid argument given\n");
	}
} else {
die("Usage: pingtester { start | stop }\n");
}
?> 
I suppose mN ain't blocked as it register missing values right ? (check in csv)

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

Re: espeasy sonoff pulse counter Metern

Post by jeanmarc » Sat Nov 09, 2019 4:17 pm

BTW, there is a "Warn connection lost" in mN, you should get notify if your esp don't respond.

I guess it could happen that one of your com app is stuck and mN is waiting. If the app is well writed it should quit after a moment, in req_espeasy.php i put a CONNECTTIMEOUT_MS to 3 sec.
You may also trick an app by adding "timeout --kill-after=15s 10s" before.

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

Re: espeasy sonoff pulse counter Metern

Post by megamarco83 » Sat Nov 09, 2019 6:43 pm

jeanmarc wrote:
Sat Nov 09, 2019 4:17 pm
BTW, there is a "Warn connection lost" in mN, you should get notify if your esp don't respond.

I guess it could happen that one of your com app is stuck and mN is waiting. If the app is well writed it should quit after a moment, in req_espeasy.php i put a CONNECTTIMEOUT_MS to 3 sec.
You may also trick an app by adding "timeout --kill-after=15s 10s" before.
Hi JM and thanks for your help!
yes, you are right, inside req_espeasy.php there is the connecttimeout
i attach to you the file (that is the file that you wride and provide to us)
i do not use others comapp only: reqsdm and req_espeasy, poolerconsumi, pool123s, eflow.
i do not catch your suggestion of adding the timeout --kill. where i have to use/insert the command?

this is the req_espeasy.php

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  = '/var/www/metern'; // without / at the end
$metnum    = 20; // Vitual meter number

$url       = 'http://192.168.0.204/json?tasknr=1'; // espeasy url  CHANGE LINE 138  -> $val_count /=100; // 1 impulse = 0.01m3 gas 
$initial   = 630.0; // initial virtual meter value  (x gas era 1214.95)
$urlreboot = 'http://192.168.0.204/?cmd=reboot'; // restart counting on reboot   ---> line 73 mettere sleep 

// 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(11);  //was 14
}

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 /= 4000; // 1 impulse = 0.01m3 gas scrivere: $val_count /= 100      se 1 impulse = 0.25m3 h20 scrivere: $val_count /= 4000
    $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);
    }
}
?>
thanks

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

Re: espeasy sonoff pulse counter Metern

Post by megamarco83 » Sat Nov 09, 2019 6:55 pm

jeanmarc wrote:
Sat Nov 09, 2019 4:08 pm
I come up with this, use pingtester -start &

Code: Select all

 <?php
// A simple script to ping a device then do a command 
// ln -s /srv/http/comapps/pingtester.php /usr/bin/pingtester and chmod +x pingtester.php

$ip = '192.168.0.1';
$docmd  = '/usr/bin/curl http://localhost/metern/scripts/bootmn.php';

function pingDomain($domain)
{
    $starttime = microtime(true);
    $file      = @fsockopen($domain, 80, $errno, $errstr, 10);
    $stoptime  = microtime(true);
    $status    = 0;
    
    if (!$file) {
        $status = -1;
    } else {
        fclose($file);
        $status = ($stoptime - $starttime) * 1000;
        $status = floor($status);
    }
    return $status;
}

if (isset($argv[1])) {
	if ($argv[1] == '-start') {
		while (true) {
		    $time = 0;
		    $time = pingDomain("$ip");
		    if ($time == -1) { // Connection broken
		        exec($docmd);
		    }
		    sleep(600); // check each 5 min
		}
		
	} elseif ($argv[1] == '-stop') {
		sleep(1);
		exec('pkill -f pingtester > /dev/null 2>&1 &');
	} else {
		die("Abording: no valid argument given\n");
	}
} else {
die("Usage: pingtester { start | stop }\n");
}
?> 
I suppose mN ain't blocked as it register missing values right ? (check in csv)
Hi JM i tested the script, i put IP of my metern: 192.168.0.105
then:

Code: Select all

sudo ln -s /var/www/comapps/pingtester.php /usr/bin/pingtester
then:

Code: Select all

sudo chmod +x pingtester.php
now from putty i receive this errors:

Code: Select all

pi@raspberrypi:/var/www/comapps $ sudo pingtester -start &
[1] 25973
pi@raspberrypi:/var/www/comapps $ /usr/bin/pingtester: 1: /usr/bin/pingtester: cannot open ?php: No such file
/usr/bin/pingtester: 2: /usr/bin/pingtester: //: Permission denied
/usr/bin/pingtester: 3: /usr/bin/pingtester: //: Permission denied
/usr/bin/pingtester: 5: /usr/bin/pingtester: =: not found
/usr/bin/pingtester: 6: /usr/bin/pingtester: =: not found
/usr/bin/pingtester: 8: /usr/bin/pingtester: Syntax error: "(" unexpected
and if i not use the"sudo" command:

Code: Select all

pi@raspberrypi:/var/www/comapps $ pingtester -start &
[1] 19935
pi@raspberrypi:/var/www/comapps $ /usr/bin/pingtester: riga 1: ?php: File o directory non esistente
/usr/bin/pingtester: riga 2: //: È una directory
/usr/bin/pingtester: riga 3: //: È una directory
/usr/bin/pingtester: riga 5: =: comando non trovato
/usr/bin/pingtester: riga 6: =: comando non trovato
/usr/bin/pingtester: riga 8: errore di sintassi vicino al token non atteso "$domain"
/usr/bin/pingtester: riga 8: `function pingDomain($domain)'
this is my pingtester.php

Code: Select all

 <?php
// A simple script to ping a device then do a command 
// ln -s /var/www/comapps/pingtester.php /usr/bin/pingtester and chmod +x pingtester.php

$ip = '192.168.0.105';
$docmd  = '/usr/bin/curl http://localhost/metern/scripts/bootmn.php';

function pingDomain($domain)
{
    $starttime = microtime(true);
    $file      = @fsockopen($domain, 80, $errno, $errstr, 10);
    $stoptime  = microtime(true);
    $status    = 0;
    
    if (!$file) {
        $status = -1;
    } else {
        fclose($file);
        $status = ($stoptime - $starttime) * 1000;
        $status = floor($status);
    }
    return $status;
}

if (isset($argv[1])) {
	if ($argv[1] == '-start') {
		while (true) {
		    $time = 0;
		    $time = pingDomain("$ip");
		    if ($time == -1) { // Connection broken
		        exec($docmd);
		    }
		    sleep(600); // check each 5 min
		}
		
	} elseif ($argv[1] == '-stop') {
		sleep(1);
		exec('pkill -f pingtester > /dev/null 2>&1 &');
	} else {
		die("Abording: no valid argument given\n");
	}
} else {
die("Usage: pingtester { start | stop }\n");
}
?> 
jeanmarc wrote:
Sat Nov 09, 2019 4:08 pm
I suppose mN ain't blocked as it register missing values right ? (check in csv)
yes, you are right when metern is blockect it not register any values in csv, and the graphics are not updates, if i simply enter with adim login and i put off and then on again meterN the cvs start to be registered and the graphics start again with new values, and also the live value inside the dashboard will appear again and not be equal to zero anymore.
[/quote]

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

Re: espeasy sonoff pulse counter Metern

Post by jeanmarc » Sat Nov 09, 2019 9:39 pm

just add #!/usr/bin/php in top of the script

Code: Select all

#!/usr/bin/php
<?php
...
For the timeout thing you should do in a php script :

Code: Select all

exec(timeout --kill-after=15s 10s theapp);
Maybe you should try to find which app does not respond when mN is stuck. You may then request all comapps to see which one doesn't respond.

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

Re: espeasy sonoff pulse counter Metern

Post by megamarco83 » Sun Nov 10, 2019 12:06 am

jeanmarc wrote:
Sat Nov 09, 2019 9:39 pm
just add #!/usr/bin/php in top of the script

Code: Select all

#!/usr/bin/php
<?php
...
that's my pingertester.php:

Code: Select all

#!/usr/bin/php
 <?php
// A simple script to ping a device then do a command 
// ln -s /var/www/comapps/pingtester.php /usr/bin/pingtester and chmod +x pingtester.php

$ip = '192.168.0.105';
$docmd  = '/usr/bin/curl http://localhost/metern/scripts/bootmn.php';

function pingDomain($domain)
{
    $starttime = microtime(true);
    $file      = @fsockopen($domain, 80, $errno, $errstr, 10);
    $stoptime  = microtime(true);
    $status    = 0;
    
    if (!$file) {
        $status = -1;
    } else {
        fclose($file);
        $status = ($stoptime - $starttime) * 1000;
        $status = floor($status);
    }
    return $status;
}

if (isset($argv[1])) {
	if ($argv[1] == '-start') {
		while (true) {
		    $time = 0;
		    $time = pingDomain("$ip");
		    if ($time == -1) { // Connection broken
		        exec($docmd);
		    }
		    sleep(600); // check each 5 min
		}
		
	} elseif ($argv[1] == '-stop') {
		sleep(1);
		exec('pkill -f pingtester > /dev/null 2>&1 &');
	} else {
		die("Abording: no valid argument given\n");
	}
} else {
die("Usage: pingtester { start | stop }\n");
}
?> 
if i use the command i receive:

Code: Select all

pi@raspberrypi:/var/www/comapps $ sudo pingtester -start &
[1] 13243
pi@raspberrypi:/var/www/comapps $ sudo: pingtester: comando non trovato

and the script stuck in that condition.
to quit i have to press CTRL+C
jeanmarc wrote:
Sat Nov 09, 2019 9:39 pm
For the timeout thing you should do in a php script :

Code: Select all

exec(timeout --kill-after=15s 10s theapp);
Maybe you should try to find which app does not respond when mN is stuck. You may then request all comapps to see which one doesn't respond.
sorry for my poor knowledge of linux and php, but i do not understand here i have to put this code:

Code: Select all

exec(timeout --kill-after=15s 10s theapp);
related to question: which app doesn't reposnd when meterN is stuck, i bet, but i'm 99% sure that is the req_espeasy.php because of i have this problem only since i'm using this app, and i try to not use it for a period of time and the problem desappear. So i'm pretty sure that the "guilty" app is 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  = '/var/www/metern'; // without / at the end
$metnum    = 20; // Vitual meter number

$url       = 'http://192.168.0.204/json?tasknr=1'; // espeasy url  CHANGE LINE 138  -> $val_count /=100; // 1 impulse = 0.01m3 gas 
$initial   = 630.0; // initial virtual meter value  (x gas era 1214.95)
$urlreboot = 'http://192.168.0.204/?cmd=reboot'; // restart counting on reboot   ---> line 73 mettere sleep 

// 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(11);  //was 14
}

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 /= 4000; // 1 impulse = 0.01m3 gas scrivere: $val_count /= 100      se 1 impulse = 0.25m3 h20 scrivere: $val_count /= 4000
    $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);
    }
}
?>

Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest