<?php
-$RRDFILE="/home/nirgal/ampy/power.rrd";
-$info=rrd_lastupdate($RRDFILE);
+require("config.php");
+
+exec("/usr/bin/rrdtool flushcached --daemon ".RRDSOCK." ".RRDFILE);
+
+$fd = fopen(COUNTERFILE, 'r');
+$mtime = fstat($fd)['mtime'];
+$counter = (double)fread($fd, 128) * 1000;
+fclose($fd);
+#echo($mtime.'<br>');
+#echo('counter='.$counter.'<br>');
+
+$params = [
+ '--daemon', RRDSOCK,
+ '-s', $mtime,
+ 'DEF:watts='.RRDFILE.':watts:AVERAGE',
+ 'VDEF:avg=watts,AVERAGE',
+ #'VDEF:last=watts,LAST',
+ 'PRINT:avg:%lf',
+ #'PRINT:last:%lf',
+];
+/*header("Content-Type: text/plain");
+foreach ($params as $param) echo(escapeshellarg($param)." ");
+return;*/
+$info=rrd_graph( '-', $params);
+#print_r($info);
+$watts_since_counter = (double)$info['calcpr'][0];
+#$watts_last = (double)$info['calcpr'][1];
+#echo('watts_since_counter='.$watts_since_counter.'<br>');
+#echo('hours_since_counter='.((time() - $mtime) / 3600.).'<br>');
+$wh_since_counter = $watts_since_counter * (time() - $mtime) / 3600.;
+#echo('wh_since_counter='.$wh_since_counter.'<br>');
+$newcounter = $counter + $wh_since_counter;
+#echo('newcounter='.$newcounter.' kWh<br>');
+
+$info=rrd_lastupdate(RRDFILE);
if ($info === FALSE)
$result=[
'last_update' => 'unknown',
else
$result=[
'last_update' => $info['last_update'],
- 'watts' => $info['data'][0]
+ 'watts' => (double)$info['data'][0]
];
+
+#$result=[];
+#$result['watts'] = $watts_last;
+$result['counter'] = $newcounter / 1000.;
+
header("Content-Type: text/json");
echo(json_encode($result));
?>