More tests on http chuncked transfer
[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
10 $speed=@(int)$_GET['speed'];
11 if ($speed <= 0)
12         $speed=1;  // seconds
13
14
15 header("Content-Type: text/json");
16 header("Transfer-Encoding: chunked");
17 flush();
18
19
20 // Send chunk to browser
21 function send_chunk($chunk)
22 {
23         // The chunk must fill the output buffer or php won't send it
24         $chunk = str_pad($chunk, 4096);
25
26         printf("%x\r\n%s\r\n", strlen($chunk), $chunk);
27         flush();
28 }
29
30 while (True) {
31         exec("/usr/bin/rrdtool flushcached --daemon ".RRDSOCK." ".RRDFILE);
32
33         $info=rrd_lastupdate(RRDFILE);
34         if ($info === FALSE)
35                 $result=[
36                         'last_update' => 'unknown',
37                         'watts' => 'unknown',
38                         'error' => rrd_error(),
39                 ];
40         else
41                 $result=[
42                         'last_update' => $info['last_update'],
43                         'watts' => (float)$info['data'][0],
44                 ];
45         send_chunk(json_encode($result));
46         sleep($speed);
47 }
48 ?>