www/getdevices.php

changeset 714
24749c296a50
parent 713
ea24b4ce02b1
child 715
f5d85af156ab
equal deleted inserted replaced
713:ea24b4ce02b1 714:24749c296a50
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 $response = array(
52 'error' => false,
53 'msg' => 'Ok',
54 );
55
56
57 if (isset($_POST['update'])) {
58
59 $cmd = "DEVICE PUT " . $_POST['uuid'] . "\r\n";
60 $cmd .= "TYPE," . $_POST['type'] . "\r\n";
61 $cmd .= "DIRECTION," . $_POST['direction'] . "\r\n";
62 $cmd .= "VALUE," . $_POST['value'] . "\r\n"; // Only for outputs
63 $cmd .= "OFFSET," . $_POST['offset'] . "\r\n"; // Only analog
64 $cmd .= "PRESENT," . $_POST['present'] . "\r\n";
65 $cmd .= "ADDRESS," . $_POST['address'] . "\r\n"; // Not for auto detected
66 $cmd .= "SUBDEVICE," . $_POST['subdevice'] . "\r\n"; // Not for auto detected
67 $cmd .= "GPIOPIN," . $_POST['gpiopin'] . "\r\n";
68 $cmd .= "DESCRIPTION," . $_POST['description'] . "\r\n";
69 $cmd .= "COMMENT," . $_POST['comment'] . "\r\n";
70 $cmd .= ".";
71 $answer = send_cmd($cmd);
72 $arr = explode("\r\n", $answer);
73 if (! startsWith($arr[0], "219")) {
74 $response['error'] = true;
75 $response['msg'] = $arr[0];
76 }
77 exit(json_encode($response));
78
79 } else if (isset($_POST['add'])) {
80
81 $answer = send_cmd("DEVICE ADD " . $_POST['type']);
82 $arr = explode("\r\n", $answer);
83 if (! startsWith($arr[0], "211")) {
84 $response['error'] = true;
85 $response['msg'] = $arr[0];
86 }
87 exit(json_encode($response));
88
89 } else if (isset($_POST['del'])) {
90
91 $answer = send_cmd("DEVICE DEL " . $_POST['uuid']);
92 $arr = explode("\r\n", $answer);
93 if (! startsWith($arr[0], "211")) {
94 $response['error'] = true;
95 $response['msg'] = $arr[0];
96 }
97 exit(json_encode($response));
98
99 } else {
100
101 $answer = send_cmd("DEVICE JSON");
102 header("Content-type: application/json");
103
104 $arr = explode("\r\n", $answer);
105 if (startsWith($arr[0], "212")) {
106 echo $arr[1];
107 } else {
108 echo '{}';
109 }
110 }
111
112 ?>

mercurial