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