4c9828ffdbfb057ee4ae78be79bafeb77f4b7385
[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 }
20
21 /*
22  * Returns an array
23  * 0 => kWh counter value (file content)
24  * 1 => last update (file mtime)
25  */
26 function ampy_get_old_counter_info() {
27         $fd = fopen(COUNTERFILE, 'r');
28         $mtime = fstat($fd)['mtime'];
29         $counter = (double)fread($fd, 128);
30         fclose($fd);
31         #echo($mtime.'<br>');
32         #echo('counter='.$counter.'<br>');
33         return [$counter, $mtime];
34 }
35
36 /*
37  * Returns how many kWh have been spent since a date.
38  * @param mtime seconds since epoch
39  * @return float kW.h
40  */
41 function ampy_get_kwh_since($mtime) {
42         
43         $params = [
44                 '--daemon', RRDSOCK,
45                 '-s', $mtime,
46                 'DEF:watts='.RRDFILE.':watts:AVERAGE',
47                 'VDEF:avg=watts,AVERAGE',
48                 #'VDEF:last=watts,LAST',
49                 'PRINT:avg:%lf',
50                 #'PRINT:last:%lf',
51         ];
52         $info=rrd_graph( '-', $params);
53         #print_r($info);
54         $watts_since_counter = (double)$info['calcpr'][0];
55         #echo('watts_since_counter='.$watts_since_counter.'<br>');
56         #echo('hours_since_counter='.((time() - $mtime) / 3600.).'<br>');
57         $wh_since_counter = $watts_since_counter * (time() - $mtime) / 3600.;
58         #echo('wh_since_counter='.$wh_since_counter.'<br>');
59         return $wh_since_counter / 1000.;
60
61 }
62
63 function ampy_get_counter() {
64         $counter_mtime = ampy_get_old_counter_info();
65         $counter = $counter_mtime[0];
66         $mtime = $counter_mtime[1];
67
68         $counter += ampy_get_kwh_since($mtime);
69         #echo('newcounter='.($counter/1000).' kWh<br>');
70
71         return $counter;
72 }
73 ?>