Clean up duplicate php code to inc file
[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 }
30
31 while (True) {
32         ampy_flush_rrd_daemon();
33
34         $info=rrd_lastupdate(RRDFILE);
35         if ($info === FALSE)
36                 $result=[
37                         'last_update' => 'unknown',
38                         'watts' => 'unknown',
39                         'error' => rrd_error(),
40                 ];
41         else
42                 $result=[
43                         'last_update' => $info['last_update'],
44                         'watts' => (float)$info['data'][0],
45                 ];
46         $result['counter'] = ampy_get_counter();
47         send_chunk(json_encode($result));
48         sleep($speed);
49 }
50 ?>