6 require_once('config.php');
8 function ampy_flush_rrd_daemon() {
9 exec("/usr/bin/rrdtool flushcached --daemon ".escapeshellarg(RRDSOCK)." ".escapeshellarg(RRDFILE));
13 * Initialized the counter file with an absolute value.
14 * Note that the file mtime is important.
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);
24 * 0 => kWh counter value (file content)
25 * 1 => last update (file mtime)
27 function ampy_get_old_counter_info() {
28 $fd = fopen(COUNTERFILE, 'r');
29 $mtime = fstat($fd)['mtime'];
30 $counter = (double)fread($fd, 128);
33 #echo('counter='.$counter.'<br>');
34 return [$counter, $mtime];
38 * Returns how many kWh have been spent since a date.
39 * The information is based on what has been recorded in the RRD database.
40 * @param mtime seconds since epoch
43 function ampy_get_kwh_since($mtime) {
48 'DEF:watts='.RRDFILE.':watts:AVERAGE',
49 'VDEF:avg=watts,AVERAGE',
50 #'VDEF:last=watts,LAST',
54 $info=rrd_graph( '-', $params);
56 $watts_since_counter = (double)$info['calcpr'][0];
57 #echo('watts_since_counter='.$watts_since_counter.'<br>');
58 #echo('hours_since_counter='.((time() - $mtime) / 3600.).'<br>');
59 $wh_since_counter = $watts_since_counter * (time() - $mtime) / 3600.;
60 #echo('wh_since_counter='.$wh_since_counter.'<br>');
61 return $wh_since_counter / 1000.;
66 * Get counter current value
67 * The value is based on:
68 * last value stored in counter file + ampy_get_kwh_since
69 * @return float kWh on the counter.
71 function ampy_get_counter() {
72 $counter_mtime = ampy_get_old_counter_info();
73 $counter = $counter_mtime[0];
74 $mtime = $counter_mtime[1];
76 $counter += ampy_get_kwh_since($mtime);
77 #echo('newcounter='.($counter/1000).' kWh<br>');
83 * Return all the information.
84 * Make sure you call ampy_flush_rrd_daemon() first if you need real time
86 * @return array['lastupdate'=>timestamps,
87 * 'watts'=>last_watt_value,
88 * 'counter'=>total_kWh,
90 function ampy_get_info() {
91 $info=rrd_lastupdate(RRDFILE);
94 //'last_update' => 'unknown',
95 //'watts' => 'unknown',
96 'error' => rrd_error(),
100 'last_update' => $info['last_update'],
101 'watts' => (double)$info['data'][0],
104 $result['counter'] = ampy_get_counter();