7772479e7ffc7ebec4dd384c2842e24fdab9fb15
[ampy.git] / html / currentjson_chunked.php
1 <?php
2 /*
3  * Experimental version that return chunked http response.
4  *
5  * Pulling the values is no longer needed as the one request will output
6  * the updates every second.
7  */
8 require_once('config.php');
9 require_once("ampy.inc.php");
10
11 $speed=@(int)$_GET['speed'];
12 if ($speed <= 0)
13         $speed=1;  // seconds
14
15
16 header("Content-Type: text/json");
17 header("Transfer-Encoding: chunked");
18 flush();
19
20
21 // Send chunk to browser
22 function send_chunk($chunk)
23 {
24         // The chunk must fill the output buffer or php won't send it
25         //$chunk = str_pad($chunk, 4096);
26
27         printf("%x\r\n%s\r\n", strlen($chunk), $chunk);
28         flush();
29         ob_flush();
30 }
31
32 while (True) {
33         ampy_flush_rrd_daemon();
34
35         $info=rrd_lastupdate(RRDFILE);
36         if ($info === FALSE)
37                 $result=[
38                         'last_update' => 'unknown',
39                         'watts' => 'unknown',
40                         'error' => rrd_error(),
41                 ];
42         else
43                 $result=[
44                         'last_update' => $info['last_update'],
45                         'watts' => (float)$info['data'][0],
46                 ];
47         $result['counter'] = ampy_get_counter();
48         send_chunk(json_encode($result));
49         sleep($speed);
50 }
51 ?>