41b39ed953a7d91bd32bb665e504cccee7d198b2
[ampy.git] / html / currentjson.php
1 <?php
2
3 require("config.php");
4
5 exec("/usr/bin/rrdtool flushcached --daemon ".RRDSOCK." ".RRDFILE);
6
7 $fd = fopen(COUNTERFILE, 'r');
8 $mtime = fstat($fd)['mtime'];
9 $counter = (double)fread($fd, 128) * 1000;
10 fclose($fd);
11 #echo($mtime.'<br>');
12 #echo('counter='.$counter.'<br>');
13
14 $params = [
15         '--daemon', RRDSOCK,
16         '-s', $mtime,
17         'DEF:watts='.RRDFILE.':watts:AVERAGE',
18         'VDEF:avg=watts,AVERAGE',
19         #'VDEF:last=watts,LAST',
20         'PRINT:avg:%lf',
21         #'PRINT:last:%lf',
22 ];
23 /*header("Content-Type: text/plain");
24 foreach ($params as $param) echo(escapeshellarg($param)." ");
25 return;*/
26 $info=rrd_graph( '-', $params);
27 #print_r($info);
28 $watts_since_counter = (double)$info['calcpr'][0];
29 #$watts_last = (double)$info['calcpr'][1];
30 #echo('watts_since_counter='.$watts_since_counter.'<br>');
31 #echo('hours_since_counter='.((time() - $mtime) / 3600.).'<br>');
32 $wh_since_counter = $watts_since_counter * (time() - $mtime) / 3600.;
33 #echo('wh_since_counter='.$wh_since_counter.'<br>');
34 $newcounter = $counter + $wh_since_counter;
35 #echo('newcounter='.$newcounter.' kWh<br>');
36
37 $info=rrd_lastupdate(RRDFILE);
38 if ($info === FALSE)
39         $result=[
40                 'last_update' => 'unknown',
41                 'watts' => 'unknown'
42         ];
43 else
44         $result=[
45                 'last_update' => $info['last_update'],
46                 'watts' => (double)$info['data'][0]
47         ];
48
49 #$result=[];
50 #$result['watts'] = $watts_last;
51 $result['counter'] = $newcounter / 1000.;
52
53 header("Content-Type: text/json");
54 echo(json_encode($result));
55 ?>