947fa665448c477fe44a53af1aca6b90854c2d03
[ampy.git] / html / ampy.inc.php
1 <?php
2 /*
3  * Ampy helpers
4  */
5
6 require_once('config.php');
7
8 function ampy_flush_rrd_daemon() {
9         exec("/usr/bin/rrdtool flushcached --daemon ".escapeshellarg(RRDSOCK)." ".escapeshellarg(RRDFILE));
10 }
11
12 /*
13  * Initialized the counter file with an absolute value.
14  * Note that the file mtime is important.
15  */
16 function ampy_set_counter($newcounter) {
17         file_put_contents(COUNTERFILE.'.new', $newcounter);
18         rename(COUNTERFILE.'.new', COUNTERFILE);
19         trigger_error("Counter was reset to $newcounter", E_USER_WARNING);
20 }
21
22 /*
23  * Returns an array
24  * 0 => kWh counter value (file content)
25  * 1 => last update (file mtime)
26  */
27 function ampy_get_old_counter_info() {
28         $fd = fopen(COUNTERFILE, 'r');
29         $mtime = fstat($fd)['mtime'];
30         $counter = (double)fread($fd, 128);
31         fclose($fd);
32         #echo($mtime.'<br>');
33         #echo('counter='.$counter.'<br>');
34         return [$counter, $mtime];
35 }
36
37 /*
38  * Returns how many kWh have been spent since a date.
39  * @param mtime seconds since epoch
40  * @return float kW.h
41  */
42 function ampy_get_kwh_since($mtime) {
43         
44         $params = [
45                 '--daemon', RRDSOCK,
46                 '-s', $mtime,
47                 'DEF:watts='.RRDFILE.':watts:AVERAGE',
48                 'VDEF:avg=watts,AVERAGE',
49                 #'VDEF:last=watts,LAST',
50                 'PRINT:avg:%lf',
51                 #'PRINT:last:%lf',
52         ];
53         $info=rrd_graph( '-', $params);
54         #print_r($info);
55         $watts_since_counter = (double)$info['calcpr'][0];
56         #echo('watts_since_counter='.$watts_since_counter.'<br>');
57         #echo('hours_since_counter='.((time() - $mtime) / 3600.).'<br>');
58         $wh_since_counter = $watts_since_counter * (time() - $mtime) / 3600.;
59         #echo('wh_since_counter='.$wh_since_counter.'<br>');
60         return $wh_since_counter / 1000.;
61
62 }
63
64 function ampy_get_counter() {
65         $counter_mtime = ampy_get_old_counter_info();
66         $counter = $counter_mtime[0];
67         $mtime = $counter_mtime[1];
68
69         $counter += ampy_get_kwh_since($mtime);
70         #echo('newcounter='.($counter/1000).' kWh<br>');
71
72         return $counter;
73 }
74 ?>