Clean up duplicate php code to inc file
[ampy.git] / html / currentjson.php
index 41b39ed953a7d91bd32bb665e504cccee7d198b2..cdd300dacc213757eda183cfe368e05871ac512e 100644 (file)
@@ -1,44 +1,16 @@
 <?php
 
-require("config.php");
+require_once("config.php");
+require_once("ampy.inc.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>');
+ampy_flush_rrd_daemon();
 
 $info=rrd_lastupdate(RRDFILE);
 if ($info === FALSE)
        $result=[
                'last_update' => 'unknown',
-               'watts' => 'unknown'
+               'watts' => 'unknown',
+               'error' => rrd_error(),
        ];
 else
        $result=[
@@ -46,9 +18,7 @@ else
                'watts' => (double)$info['data'][0]
        ];
 
-#$result=[];
-#$result['watts'] = $watts_last;
-$result['counter'] = $newcounter / 1000.;
+$result['counter'] = ampy_get_counter();
 
 header("Content-Type: text/json");
 echo(json_encode($result));