Making classes final to make inheritance impossible
[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 final 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                                         //made by changwoo
291                                         if (packetData.get("type").equals("zcl_zone_status_change_notification")){
292                                                 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
293                                                 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
294                                                 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
295                                                 int status = Integer.parseInt(packetData.get("status"), 10);
296                                                 boolean successOrFail = false;
297                                                 if(packetData.get("attributes").equals("success")) successOrFail=true;
298                                                 callbackMessage = new IoTZigbeeMessageZclZoneStatusChangeNotification(packetId, clusterId, profileId, status, successOrFail);
299
300                                         //made by changwoo
301                                         } else if (packetData.get("type").equals("zcl_write_attributes_response")) {
302
303                                                 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
304                                                 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
305                                                 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
306                                                 boolean successOrFail = false;
307                                                 if(packetData.get("attributes").equals("success")) successOrFail=true;
308                                                 
309                                                 callbackMessage = new IoTZigbeeMessageZclWriteAttributesResponse(packetId, clusterId, profileId, successOrFail);
310
311                                         } else if (packetData.get("type").equals("zcl_read_attributes_response")) {
312                                                 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
313                                                 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
314                                                 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
315
316                                                 List<IoTZigbeeMessageZclReadAttributesResponse.Attribute> attrList = new ArrayList<IoTZigbeeMessageZclReadAttributesResponse.Attribute>();
317
318                                                 String[] attributes = packetData.get("attributes").split(";");
319                                                 for (String attr : attributes) {
320                                                         attr = attr.trim();
321                                                         String[] parts = attr.split(",");
322
323                                                         if (parts.length == 2) {
324                                                                 parts[0] = parts[0].trim();
325                                                                 parts[1] = parts[1].trim();
326
327                                                                 IoTZigbeeMessageZclReadAttributesResponse.Attribute at = new IoTZigbeeMessageZclReadAttributesResponse.Attribute(Integer.parseInt(parts[0], 16), 0, false, null);
328                                                                 attrList.add(at);
329                                                         } else {
330                                                                 parts[0] = parts[0].trim();
331                                                                 parts[1] = parts[1].trim();
332                                                                 parts[2] = parts[2].trim();
333                                                                 parts[3] = parts[3].trim();
334                                                                 IoTZigbeeMessageZclReadAttributesResponse.Attribute at = new IoTZigbeeMessageZclReadAttributesResponse.Attribute(Integer.parseInt(parts[0], 16), Integer.parseInt(parts[1], 16), true, hexStringToByteArray(parts[3]));
335                                                                 attrList.add(at);
336                                                         }
337                                                 }
338
339                                                 callbackMessage = new IoTZigbeeMessageZclReadAttributesResponse(packetId, clusterId, profileId, attrList);
340
341                                         } else if (packetData.get("type").equals("zcl_configure_reporting_response")) {
342                                                 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
343                                                 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
344                                                 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
345
346                                                 if (packetData.get("attributes").equals("all_success")) {
347                                                         callbackMessage = new IoTZigbeeMessageZclConfigureReportingResponse(packetId, clusterId, profileId, true, null);
348                                                 } else {
349                                                         List<IoTZigbeeMessageZclConfigureReportingResponse.Attribute> attrList = new ArrayList<IoTZigbeeMessageZclConfigureReportingResponse.Attribute>();
350
351                                                         String[] attributes = packetData.get("attributes").split(";");
352                                                         for (String attr : attributes) {
353                                                                 attr = attr.trim();
354                                                                 String[] parts = attr.split(",");
355                                                                 parts[0] = parts[0].trim();
356                                                                 parts[1] = parts[1].trim();
357                                                                 parts[2] = parts[2].trim();
358                                                                 IoTZigbeeMessageZclConfigureReportingResponse.Attribute at = new IoTZigbeeMessageZclConfigureReportingResponse.Attribute(Integer.parseInt(parts[0], 16), parts[1].equals("success"), parts[2].equals("reported"));
359                                                                 attrList.add(at);
360                                                         }
361                                                         callbackMessage = new IoTZigbeeMessageZclConfigureReportingResponse(packetId, clusterId, profileId, false, attrList);
362                                                 }
363
364                                         } else if (packetData.get("type").equals("zcl_report_attributes")) {
365                                                 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
366                                                 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
367                                                 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
368
369                                                 List<IoTZigbeeMessageZclReportAttributes.Attribute> attrList = new ArrayList<IoTZigbeeMessageZclReportAttributes.Attribute>();
370
371                                                 String[] attributes = packetData.get("attributes").split(";");
372                                                 for (String attr : attributes) {
373                                                         attr = attr.trim();
374                                                         String[] parts = attr.split(",");
375
376                                                         parts[0] = parts[0].trim();
377                                                         parts[1] = parts[1].trim();
378                                                         parts[2] = parts[2].trim();
379                                                         IoTZigbeeMessageZclReportAttributes.Attribute at = new IoTZigbeeMessageZclReportAttributes.Attribute(Integer.parseInt(parts[0], 16), Integer.parseInt(parts[1], 16), hexStringToByteArray(parts[2]));
380                                                         attrList.add(at);
381                                                 }
382
383                                                 callbackMessage = new IoTZigbeeMessageZclReportAttributes(packetId, clusterId, profileId, attrList);
384
385                                         } else if (packetData.get("type").equals("zcl_read_attributes")) {
386                                                 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
387                                                 boolean success = packetData.get("response").equals("success");
388
389                                                 if (success) {
390                                                         callbackMessage = new IoTZigbeeMessageZclReadAttributes(packetId, success, "");
391                                                 } else {
392                                                         callbackMessage = new IoTZigbeeMessageZclReadAttributes(packetId, success, packetData.get("reason"));
393                                                 }
394
395                                         } else if (packetData.get("type").equals("zcl_configure_reporting")) {
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 IoTZigbeeMessageZclConfigureReporting(packetId, success, "");
401                                                 } else {
402                                                         callbackMessage = new IoTZigbeeMessageZclConfigureReporting(packetId, success, packetData.get("reason"));
403                                                 }
404
405                                         } else if (packetData.get("type").equals("zdo_bind_request")) {
406                                                 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
407                                                 boolean success = packetData.get("response").equals("success");
408
409                                                 if (success) {
410                                                         callbackMessage = new IoTZigbeeMessageZdoBindResponse(packetId, success, "");
411                                                 } else {
412                                                         callbackMessage = new IoTZigbeeMessageZdoBindResponse(packetId, success, packetData.get("reason"));
413                                                 }
414                                         }
415
416                                         else if (packetData.get("type").equals("zdo_unbind_request")) {
417                                                 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
418                                                 boolean success = packetData.get("response").equals("success");
419
420                                                 if (success) {
421                                                         callbackMessage = new IoTZigbeeMessageZdoUnBindResponse(packetId, success, "");
422                                                 } else {
423                                                         callbackMessage = new IoTZigbeeMessageZdoUnBindResponse(packetId, success, packetData.get("reason"));
424                                                 }
425                                         }
426
427                                         if (callbackMessage != null) {
428                                                 for (IoTZigbeeCallback c : callbackList) {
429                                                         c.newMessageAvailable(callbackMessage);
430                                                 }
431                                         }
432                                 }
433
434
435
436                         } catch (Exception e) {
437                                 e.printStackTrace();
438                         }
439                 }
440         }
441
442         public static String changeHexEndianness(String hexData) {
443
444                 List<String> pairedValues = new ArrayList<String>();
445                 for (int i = 0; i < hexData.length(); i += 2) {
446                         String part = hexData.substring(i, Math.min(i + 2, hexData.length()));
447                         pairedValues.add(part);
448                 }
449
450                 String retString  = "";
451                 for (int i = (pairedValues.size() - 1); i >= 0; i--) {
452                         retString += pairedValues.get(i);
453                 }
454                 return retString;
455         }
456
457         // taken from: http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java
458         public static byte[] hexStringToByteArray(String s) {
459                 int len = s.length();
460                 byte[] data = new byte[len / 2];
461                 for (int i = 0; i < len; i += 2) {
462                         data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
463                                               + Character.digit(s.charAt(i + 1), 16));
464                 }
465                 return data;
466         }
467
468 }
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484