www/getonewire.php

changeset 696
fe042f9484ac
equal deleted inserted replaced
695:ea20d8adbcaa 696:fe042f9484ac
1 <?php
2
3
4 function open_socket()
5 {
6 $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
7
8 if (!($sock === false)) {
9 if (socket_connect($sock, "localhost", 6554)) {
10 socket_set_option($sock, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 15, 'usec' => 0));
11 } else {
12 socket_close($sock);
13 }
14 }
15 return $sock;
16 }
17
18
19 /**
20 * @param string $command to send to the server.
21 * @return string with the complete reply from the
22 * server. This can be a multiline reply.
23 */
24 function send_cmd($command)
25 {
26 $sock = open_socket();
27 if ($sock == false) {
28 return "";
29 }
30 socket_write($sock, $command . "\r\n", 4096);
31
32 $answer = "";
33 while (1) {
34 $line = socket_read($sock, 4096);
35 if ($line === '')
36 break;
37 $answer .= $line;
38 }
39 socket_close($sock);
40
41 return $answer;
42 }
43
44
45 function startsWith($haystack, $needle)
46 {
47 return !strncmp($haystack, $needle, strlen($needle));
48 }
49
50
51 $answer = send_cmd("ONEWIRE JSON");
52 header("Content-type: application/json");
53
54 $arr = explode("\r\n", $answer);
55 if (startsWith($arr[0], "212")) {
56 echo $arr[1];
57 } else {
58 echo '{}';
59 }
60

mercurial