Pre-release demo version
[ampy.git] / html / currentjson.php
index f3c8f315871e464a9106ec669c79d0fa14998d26..41b39ed953a7d91bd32bb665e504cccee7d198b2 100644 (file)
@@ -1,7 +1,40 @@
 <?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',
@@ -10,8 +43,13 @@ if ($info === FALSE)
 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));
 ?>