a7729188d89fc7c685581e9b774e257278e8bfde
[iot2.git] / iotjava / iotruntime / zigbee / IoTZigbee.java
1 package iotruntime.zigbee;
2
3 // Java packages
4 import java.io.IOException;
5 import java.net.DatagramPacket;
6 import java.net.DatagramSocket;
7 import java.net.InetAddress;
8 import java.net.SocketException;
9 import java.net.UnknownHostException;
10 import java.util.concurrent.atomic.AtomicBoolean;
11 import java.util.List;
12 import java.util.ArrayList;
13 import java.util.Map;
14 import java.util.HashMap;
15 import java.util.concurrent.ConcurrentHashMap;
16 import java.util.Set;
17 import java.util.HashSet;
18 import java.nio.charset.StandardCharsets;
19 import java.util.concurrent.Semaphore;
20
21 import iotruntime.slave.IoTZigbeeAddress;
22 import iotruntime.slave.IoTDeviceAddress;
23
24 /** Class IoTZigbee
25  *
26  * @author      Ali Younis <ayounis @ uci.edu>
27  * @version     1.0
28  * @since       2016-04-12
29  */
30 public class IoTZigbee {
31
32         public final int SOCKET_SEND_BUFFER_SIZE = 1024;
33         public final int SOCKET_RECEIVE_BUFFER_SIZE = 1024;
34         public final int SHORT_ADDRESS_UPDATE_TIME_MSEC = 10000;
35         public final int SHORT_ADDRESS_UPDATE_TIME_FAST_MSEC = 500;
36         public final int RESEND_WAIT_TIME = 500;
37
38         /**
39          * IoTZigbee class properties
40          */
41
42         // UDP connection stuff
43         private final String strHostAddress;
44         private final int iSrcPort;
45         private final int iDstPort;
46         private DatagramSocket socket;  // the socket interface that we are guarding
47         private boolean didClose;                                                               // make sure that the clean up was done correctly
48
49         private final IoTZigbeeAddress zigbeeAddress;
50
51         // list that holds the callbacks
52         private List<IoTZigbeeCallback> callbackList = new ArrayList<IoTZigbeeCallback>();
53
54         /**
55          * IoTZigbee class concurrency and concurrency control
56          */
57         private Thread receiveThread = null;
58
59         private AtomicBoolean endTask = new AtomicBoolean(false);
60         private AtomicBoolean didSuccesfullySendAddress = new AtomicBoolean(false);
61
62         /**
63          * Class constructor
64          */
65         public IoTZigbee(IoTDeviceAddress iotDevAdd, IoTZigbeeAddress zigAddress) throws SocketException, IOException, InterruptedException {
66
67                 strHostAddress = iotDevAdd.getHostAddress();
68                 iSrcPort = iotDevAdd.getSourcePortNumber();
69                 iDstPort = iotDevAdd.getDestinationPortNumber();
70                 didClose = false;
71                 zigbeeAddress = zigAddress;
72
73                 socket = new DatagramSocket(iSrcPort);
74                 socket.setSendBufferSize(SOCKET_SEND_BUFFER_SIZE);
75                 socket.setReceiveBufferSize(SOCKET_RECEIVE_BUFFER_SIZE);
76
77                 receiveThread = new Thread(new Runnable() {
78                         public void run() {
79                                 receieveWorker();
80                         }
81                 });
82                 receiveThread.start();
83         }
84
85         public void init() throws IOException {
86                 while (!didSuccesfullySendAddress.get()) {
87
88                         sendDeviceAddress();
89
90                         try {
91                                 Thread.sleep(RESEND_WAIT_TIME);
92                         } catch (Exception e) {
93                                 e.printStackTrace();
94                         }
95                 }
96         }
97
98         //made by changwoo
99         public void sendChangeSwtichRequest(int packetId, int clusterId, int profileId, int value, int deviceEndpoint) throws IOException {
100                 String message = "type: zcl_change_switch_request\n";
101                 message += "packet_id: " + String.format("%04x", packetId) + "\n";
102                 message += "value: " + String.format("%01x", value) + "\n";
103                 message += "cluster_id: " + String.format("%04x", clusterId) + "\n";
104                 message += "profile_id: " + String.format("%04x", profileId) + "\n";
105                 message += "device_address_long: " + zigbeeAddress.getAddress() + "\n";
106                 message += "device_endpoint: " + String.format("%02x", deviceEndpoint) + "\n";
107                 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
108                 socket.send(sendPacket);
109         }
110
111         //made by changwoo
112         public void sendBroadcastingRouteRecordRequest(int packetId) throws IOException {
113                 String message = "type: zdo_broadcast_route_record_request\n";
114                 message += "packet_id: " + String.format("%04x", packetId) + "\n";
115                 message += "device_address_long: " + zigbeeAddress.getAddress() + "\n";
116                 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
117                 socket.send(sendPacket);
118         }
119
120         //made by changwoo
121         public void sendEnrollmentResponse(int packetId, int clusterId, int profileId, int deviceEndpoint) throws IOException {
122                 String message = "type: zcl_enrollment_response\n";
123                 message += "packet_id: " + String.format("%04x", packetId) + "\n";
124                 message += "device_address_long: " + zigbeeAddress.getAddress() + "\n";
125                 message += "cluster_id: " + String.format("%04x", clusterId) + "\n";
126                 message += "profile_id: " + String.format("%04x", profileId) + "\n";
127                 message += "device_endpoint: " + String.format("%02x", deviceEndpoint) + "\n";
128                 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
129                 socket.send(sendPacket);
130         }
131
132         //made by changwoo
133         public void sendWriteAttributesCommand(int packetId, int clusterId, int profileId, int deviceEndpoint) throws IOException {
134                 String message = "type: zcl_write_attributes\n";
135                 message += "packet_id: " + String.format("%04x", packetId) + "\n";
136                 message += "device_address_long: " + zigbeeAddress.getAddress() + "\n";
137                 message += "cluster_id: " + String.format("%04x", clusterId) + "\n";
138                 message += "profile_id: " + String.format("%04x", profileId) + "\n";
139                 message += "device_endpoint: " + String.format("%02x", deviceEndpoint) + "\n";
140                 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
141                 socket.send(sendPacket);
142         }
143
144         //made by changwoo
145         public void sendManagementPermitJoiningRequest(int packetId, int clusterId, int deviceEndpoint) throws IOException {
146                 String message = "type: management_permit_joining_request\n";
147                 message += "packet_id: " + String.format("%04x", packetId) + "\n";
148                 message += "device_address_long: " + zigbeeAddress.getAddress() + "\n";
149                 message += "cluster_id: " + String.format("%04x", clusterId) + "\n";
150                 message += "device_endpoint: " + String.format("%02x", deviceEndpoint) + "\n";
151                 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
152                 socket.send(sendPacket);
153         }
154
155         public void sendBindRequest(int packetId, int clusterId, int deviceEndpoint) throws IOException {
156                 String message = "type: zdo_bind_request\n";
157                 message += "packet_id: " + String.format("%04x", packetId) + "\n";
158                 message += "device_address_long: " + zigbeeAddress.getAddress() + "\n";
159                 message += "cluster_id: " + String.format("%04x", clusterId) + "\n";
160                 message += "device_endpoint: " + String.format("%02x", deviceEndpoint) + "\n";
161                 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
162                 socket.send(sendPacket);
163         }
164
165         public void sendUnBindRequest(int packetId, int clusterId, int deviceEndpoint) throws IOException {
166                 String message = "type: zdo_unbind_request\n";
167                 message += "packet_id: " + String.format("%04x", packetId) + "\n";
168                 message += "device_address_long: " + zigbeeAddress.getAddress() + "\n";
169                 message += "cluster_id: " + String.format("%04x", clusterId) + "\n";
170                 message += "device_endpoint: " + String.format("%02x", deviceEndpoint) + "\n";
171                 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
172                 socket.send(sendPacket);
173         }
174
175         public void sendReadAttributesCommand(int packetId, int clusterId, int profileId, int deviceEndpoint, List<Integer> attributeIds) throws IOException {
176                 String message = "type: zcl_read_attributes\n";
177                 message += "packet_id: " + String.format("%04x", packetId) + "\n";
178                 message += "device_address_long: " + zigbeeAddress.getAddress() + "\n";
179                 message += "cluster_id: " + String.format("%04x", clusterId) + "\n";
180                 message += "profile_id: " + String.format("%04x", profileId) + "\n";
181                 message += "device_endpoint: " + String.format("%02x", deviceEndpoint) + "\n";
182
183                 message += "attribute_ids: ";
184
185                 for (Integer i : attributeIds) {
186                         message += String.format("%04x", i) + ",";
187                 }
188
189                 message = message.substring(0, message.length() - 1);
190                 message += "\n";
191
192                 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
193                 socket.send(sendPacket);
194         }
195
196         public void sendConfigureReportingCommand(int packetId, int clusterId, int profileId, int deviceEndpoint, int attributeId, int dataType, int minReportingInterval, int maxReportingInterval, byte[] reportableChange) throws IOException {
197                 String message = "type: zcl_configure_reporting\n";
198                 message += "packet_id: " + String.format("%04x", packetId) + "\n";
199                 message += "device_address_long: " + zigbeeAddress.getAddress() + "\n";
200                 message += "cluster_id: " + String.format("%04x", clusterId) + "\n";
201                 message += "profile_id: " + String.format("%04x", profileId) + "\n";
202                 message += "device_endpoint: " + String.format("%02x", deviceEndpoint) + "\n";
203                 message += "attribute_id: " + String.format("%04x", attributeId) + "\n";
204                 message += "data_type: " + String.format("%02x", dataType) + "\n";
205                 message += "min_reporting_interval: " + String.format("%04x", minReportingInterval) + "\n";
206                 message += "max_reporting_interval: " + String.format("%04x", maxReportingInterval) + "\n";
207
208                 if (reportableChange != null) {
209                         message += "reportable_change: ";
210                         for (Byte b : reportableChange) {
211                                 message += String.format("%02x", (int)b);
212                         }
213                         message += "\n";
214                 }
215
216                 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
217                 socket.send(sendPacket);
218         }
219
220         public void registerCallback(IoTZigbeeCallback callbackTo) {
221                 callbackList.add(callbackTo);
222         }
223
224         public void close() throws InterruptedException {
225                 endTask.set(true);
226
227                 // wait for the threads to end
228                 receiveThread.join();
229
230                 socket.close();
231                 didClose = true;
232         }
233
234         /**
235          * close() called by the garbage collector right before trashing object
236          */
237         public void Finalize() throws SocketException, InterruptedException {
238
239                 if (!didClose) {
240                         close();
241                         throw new SocketException("Socket not closed before object destruction, must call close method.");
242                 }
243         }
244
245         private void sendDeviceAddress() throws IOException {
246                 String message = "type: send_address\n";
247                 message += "packet_id: 00\n";
248                 message += "device_address_long: " + zigbeeAddress.getAddress() + "\n";
249                 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
250                 socket.send(sendPacket);
251         }
252
253         private void receieveWorker() {
254                 while (!(endTask.get())) {
255
256                         byte[] recBuffer = new byte[SOCKET_RECEIVE_BUFFER_SIZE];
257                         try {
258                                 DatagramPacket recPacket = new DatagramPacket(recBuffer, recBuffer.length);
259                                 socket.receive(recPacket);
260
261                                 // Convert the UDP data into a string format
262                                 String dataString = new String(recPacket.getData());
263
264                                 // split the data by line so we can start procesisng
265                                 String[] lines = dataString.split("\n");
266
267                                 Map<String, String> packetData = new HashMap<String, String>();
268                                 for (String line : lines) {
269
270                                         // trim the line
271                                         String trimmedLine = line.trim();
272                                         // make sure this is a valid data line and not just blank
273                                         if (trimmedLine.length() == 0) {
274                                                 continue;
275                                         }
276
277                                         // Split the data into parts
278                                         String[] parts = trimmedLine.split(":");
279                                         parts[0] = parts[0].trim();
280                                         parts[1] = parts[1].trim();
281                                         packetData.put(parts[0], parts[1]);
282                                 }
283
284                                 if (packetData.get("type").equals("send_address_response")) {
285                                         didSuccesfullySendAddress.set(true);
286
287                                 } else {
288                                         IoTZigbeeMessage callbackMessage = null;
289
290                                         if (packetData.get("type").equals("zcl_read_attributes_response")) {
291                                                 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
292                                                 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
293                                                 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
294
295                                                 List<IoTZigbeeMessageZclReadAttributesResponse.Attribute> attrList = new ArrayList<IoTZigbeeMessageZclReadAttributesResponse.Attribute>();
296
297                                                 String[] attributes = packetData.get("attributes").split(";");
298                                                 for (String attr : attributes) {
299                                                         attr = attr.trim();
300                                                         String[] parts = attr.split(",");
301
302                                                         if (parts.length == 2) {
303                                                                 parts[0] = parts[0].trim();
304                                                                 parts[1] = parts[1].trim();
305
306                                                                 IoTZigbeeMessageZclReadAttributesResponse.Attribute at = new IoTZigbeeMessageZclReadAttributesResponse.Attribute(Integer.parseInt(parts[0], 16), 0, false, null);
307                                                                 attrList.add(at);
308                                                         } else {
309                                                                 parts[0] = parts[0].trim();
310                                                                 parts[1] = parts[1].trim();
311                                                                 parts[2] = parts[2].trim();
312                                                                 parts[3] = parts[3].trim();
313                                                                 IoTZigbeeMessageZclReadAttributesResponse.Attribute at = new IoTZigbeeMessageZclReadAttributesResponse.Attribute(Integer.parseInt(parts[0], 16), Integer.parseInt(parts[1], 16), true, hexStringToByteArray(parts[3]));
314                                                                 attrList.add(at);
315                                                         }
316                                                 }
317
318                                                 callbackMessage = new IoTZigbeeMessageZclReadAttributesResponse(packetId, clusterId, profileId, attrList);
319
320                                         } else if (packetData.get("type").equals("zcl_configure_reporting_response")) {
321                                                 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
322                                                 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
323                                                 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
324
325                                                 if (packetData.get("attributes").equals("all_success")) {
326                                                         callbackMessage = new IoTZigbeeMessageZclConfigureReportingResponse(packetId, clusterId, profileId, true, null);
327                                                 } else {
328                                                         List<IoTZigbeeMessageZclConfigureReportingResponse.Attribute> attrList = new ArrayList<IoTZigbeeMessageZclConfigureReportingResponse.Attribute>();
329
330                                                         String[] attributes = packetData.get("attributes").split(";");
331                                                         for (String attr : attributes) {
332                                                                 attr = attr.trim();
333                                                                 String[] parts = attr.split(",");
334                                                                 parts[0] = parts[0].trim();
335                                                                 parts[1] = parts[1].trim();
336                                                                 parts[2] = parts[2].trim();
337                                                                 IoTZigbeeMessageZclConfigureReportingResponse.Attribute at = new IoTZigbeeMessageZclConfigureReportingResponse.Attribute(Integer.parseInt(parts[0], 16), parts[1].equals("success"), parts[2].equals("reported"));
338                                                                 attrList.add(at);
339                                                         }
340                                                         callbackMessage = new IoTZigbeeMessageZclConfigureReportingResponse(packetId, clusterId, profileId, false, attrList);
341                                                 }
342
343                                         } else if (packetData.get("type").equals("zcl_report_attributes")) {
344                                                 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
345                                                 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
346                                                 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
347
348                                                 List<IoTZigbeeMessageZclReportAttributes.Attribute> attrList = new ArrayList<IoTZigbeeMessageZclReportAttributes.Attribute>();
349
350                                                 String[] attributes = packetData.get("attributes").split(";");
351                                                 for (String attr : attributes) {
352                                                         attr = attr.trim();
353                                                         String[] parts = attr.split(",");
354
355                                                         parts[0] = parts[0].trim();
356                                                         parts[1] = parts[1].trim();
357                                                         parts[2] = parts[2].trim();
358                                                         IoTZigbeeMessageZclReportAttributes.Attribute at = new IoTZigbeeMessageZclReportAttributes.Attribute(Integer.parseInt(parts[0], 16), Integer.parseInt(parts[1], 16), hexStringToByteArray(parts[2]));
359                                                         attrList.add(at);
360                                                 }
361
362                                                 callbackMessage = new IoTZigbeeMessageZclReportAttributes(packetId, clusterId, profileId, attrList);
363
364                                         } else if (packetData.get("type").equals("zcl_read_attributes")) {
365                                                 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
366                                                 boolean success = packetData.get("response").equals("success");
367
368                                                 if (success) {
369                                                         callbackMessage = new IoTZigbeeMessageZclReadAttributes(packetId, success, "");
370                                                 } else {
371                                                         callbackMessage = new IoTZigbeeMessageZclReadAttributes(packetId, success, packetData.get("reason"));
372                                                 }
373
374                                         } else if (packetData.get("type").equals("zcl_configure_reporting")) {
375                                                 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
376                                                 boolean success = packetData.get("response").equals("success");
377
378                                                 if (success) {
379                                                         callbackMessage = new IoTZigbeeMessageZclConfigureReporting(packetId, success, "");
380                                                 } else {
381                                                         callbackMessage = new IoTZigbeeMessageZclConfigureReporting(packetId, success, packetData.get("reason"));
382                                                 }
383
384                                         } else if (packetData.get("type").equals("zdo_bind_request")) {
385                                                 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
386                                                 boolean success = packetData.get("response").equals("success");
387
388                                                 if (success) {
389                                                         callbackMessage = new IoTZigbeeMessageZdoBindResponse(packetId, success, "");
390                                                 } else {
391                                                         callbackMessage = new IoTZigbeeMessageZdoBindResponse(packetId, success, packetData.get("reason"));
392                                                 }
393                                         }
394
395                                         else if (packetData.get("type").equals("zdo_unbind_request")) {
396                                                 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
397                                                 boolean success = packetData.get("response").equals("success");
398
399                                                 if (success) {
400                                                         callbackMessage = new IoTZigbeeMessageZdoUnBindResponse(packetId, success, "");
401                                                 } else {
402                                                         callbackMessage = new IoTZigbeeMessageZdoUnBindResponse(packetId, success, packetData.get("reason"));
403                                                 }
404                                         }
405
406                                         if (callbackMessage != null) {
407                                                 for (IoTZigbeeCallback c : callbackList) {
408                                                         c.newMessageAvailable(callbackMessage);
409                                                 }
410                                         }
411                                 }
412
413
414
415                         } catch (Exception e) {
416                                 e.printStackTrace();
417                         }
418                 }
419         }
420
421         public static String changeHexEndianness(String hexData) {
422
423                 List<String> pairedValues = new ArrayList<String>();
424                 for (int i = 0; i < hexData.length(); i += 2) {
425                         String part = hexData.substring(i, Math.min(i + 2, hexData.length()));
426                         pairedValues.add(part);
427                 }
428
429                 String retString  = "";
430                 for (int i = (pairedValues.size() - 1); i >= 0; i--) {
431                         retString += pairedValues.get(i);
432                 }
433                 return retString;
434         }
435
436         // taken from: http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java
437         public static byte[] hexStringToByteArray(String s) {
438                 int len = s.length();
439                 byte[] data = new byte[len / 2];
440                 for (int i = 0; i < len; i += 2) {
441                         data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
442                                               + Character.digit(s.charAt(i + 1), 16));
443                 }
444                 return data;
445         }
446
447 }
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463