|
1 <?php |
|
2 |
|
3 function open_socket() |
|
4 { |
|
5 $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); |
|
6 |
|
7 if (!($sock === false)) { |
|
8 if (socket_connect($sock, "localhost", 6554)) { |
|
9 socket_set_option($sock, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 15, 'usec' => 0)); |
|
10 } else { |
|
11 socket_close($sock); |
|
12 } |
|
13 } |
|
14 return $sock; |
|
15 } |
|
16 |
|
17 |
|
18 /** |
|
19 * @param string $command to send to the server. |
|
20 * @return string with the complete reply from the |
|
21 * server. This can be a multiline reply. |
|
22 */ |
|
23 function send_cmd($command) |
|
24 { |
|
25 $sock = open_socket(); |
|
26 if ($sock == false) { |
|
27 return ""; |
|
28 } |
|
29 socket_write($sock, $command . "\r\n", 4096); |
|
30 |
|
31 $answer = ""; |
|
32 while (1) { |
|
33 $line = socket_read($sock, 4096); |
|
34 if ($line === '') |
|
35 break; |
|
36 $answer .= $line; |
|
37 } |
|
38 socket_close($sock); |
|
39 |
|
40 return $answer; |
|
41 } |
|
42 |
|
43 |
|
44 function startsWith($haystack, $needle) |
|
45 { |
|
46 return !strncmp($haystack, $needle, strlen($needle)); |
|
47 } |
|
48 |
|
49 $answer = send_cmd("DEVICES JSON"); |
|
50 |
|
51 $arr = explode("\r\n", $answer); |
|
52 if (startsWith($arr[0], "212")) { |
|
53 |
|
54 /* |
|
55 * Build reply with only temperature sensors. |
|
56 */ |
|
57 $sensors[] = array( |
|
58 'uuid' => '', |
|
59 'name' => 'Not Assigned' |
|
60 ); |
|
61 |
|
62 $rows = json_decode($arr[1], true); |
|
63 |
|
64 foreach($rows as $item) { |
|
65 if ($item['direction'] == "OUT_BIN") { |
|
66 $sensors[] = array( |
|
67 'uuid' => $item['uuid'], |
|
68 'name' => $item['description']." ".$item['comment'] |
|
69 ); |
|
70 } |
|
71 } |
|
72 header("Content-type: application/json"); |
|
73 exit(json_encode($sensors)); |
|
74 } |
|
75 |
|
76 header("Content-type: application/json"); |
|
77 echo '{}'; |
|
78 |
|
79 ?> |