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;
13 import java.util.HashMap;
14 import java.util.concurrent.ConcurrentHashMap;
16 import java.util.HashSet;
17 import java.nio.charset.StandardCharsets;
18 import java.util.concurrent.Semaphore;
23 * @author Ali Younis <ayounis @ uci.edu>, Changwoo Lee <changwl2 @ uci.edu>
25 * @since 2016-04-12, 2016-10-28
27 public class IoTZigbee {
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;
36 * IoTZigbee class properties
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
46 private final IoTZigbeeAddress zigbeeAddress;
48 // list that holds the callbacks
49 private List<IoTZigbeeCallback> callbackList = new ArrayList<IoTZigbeeCallback>();
52 * IoTZigbee class concurrency and concurrency control
54 private Thread receiveThread = null;
56 private AtomicBoolean endTask = new AtomicBoolean(false);
57 private AtomicBoolean didSuccesfullySendAddress = new AtomicBoolean(false);
62 public IoTZigbee(IoTDeviceAddress iotDevAdd, IoTZigbeeAddress zigAddress) throws SocketException, IOException, InterruptedException {
64 strHostAddress = iotDevAdd.getHostAddress();
65 iSrcPort = iotDevAdd.getSourcePortNumber();
66 iDstPort = iotDevAdd.getDestinationPortNumber();
68 zigbeeAddress = zigAddress;
70 socket = new DatagramSocket(iSrcPort);
71 socket.setSendBufferSize(SOCKET_SEND_BUFFER_SIZE);
72 socket.setReceiveBufferSize(SOCKET_RECEIVE_BUFFER_SIZE);
74 receiveThread = new Thread(new Runnable() {
79 receiveThread.start();
82 public void init() throws IOException {
83 while (!didSuccesfullySendAddress.get()) {
88 Thread.sleep(RESEND_WAIT_TIME);
89 } catch (Exception e) {
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);
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);
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);
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);
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);
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);
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);
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";
179 message += "attribute_ids: ";
181 for (Integer i : attributeIds) {
182 message += String.format("%04x", i) + ",";
185 message = message.substring(0, message.length() - 1);
188 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
189 socket.send(sendPacket);
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";
204 if (reportableChange != null) {
205 message += "reportable_change: ";
206 for (Byte b : reportableChange) {
207 message += String.format("%02x", (int)b);
212 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
213 socket.send(sendPacket);
216 public void registerCallback(IoTZigbeeCallback callbackTo) {
218 callbackList.add(callbackTo);
222 public void close() throws InterruptedException {
225 // wait for the threads to end
226 receiveThread.join();
233 * close() called by the garbage collector right before trashing object
235 public void Finalize() throws SocketException, InterruptedException {
239 throw new SocketException("Socket not closed before object destruction, must call close method.");
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);
251 private void receieveWorker() {
252 while (!(endTask.get())) {
254 byte[] recBuffer = new byte[SOCKET_RECEIVE_BUFFER_SIZE];
256 DatagramPacket recPacket = new DatagramPacket(recBuffer, recBuffer.length);
257 socket.receive(recPacket);
259 // Convert the UDP data into a string format
260 String dataString = new String(recPacket.getData());
262 // split the data by line so we can start procesisng
263 String[] lines = dataString.split("\n");
265 Map<String, String> packetData = new HashMap<String, String>();
266 for (String line : lines) {
269 String trimmedLine = line.trim();
270 // make sure this is a valid data line and not just blank
271 if (trimmedLine.length() == 0) {
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]);
282 if (packetData.get("type").equals("send_address_response")) {
283 didSuccesfullySendAddress.set(true);
286 IoTZigbeeMessage callbackMessage = null;
290 if (packetData.get("type").equals("zcl_match_descriptor_response")) {
291 System.out.println("zcl_match_descriptor_response message arrives");
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;
299 callbackMessage = new IoTZigbeeMessageMatchDescriptorResponse(packetId, clusterId, profileId, successOrFail);
304 if (packetData.get("type").equals("zcl_zone_status_change_notification")){
305 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
306 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
307 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
308 int status = Integer.parseInt(packetData.get("status"), 10);
309 boolean successOrFail = false;
310 if(packetData.get("attributes").equals("success")) successOrFail=true;
311 callbackMessage = new IoTZigbeeMessageZclZoneStatusChangeNotification(packetId, clusterId, profileId, status, successOrFail);
314 } else if (packetData.get("type").equals("zcl_write_attributes_response")) {
316 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
317 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
318 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
319 boolean successOrFail = false;
320 if(packetData.get("attributes").equals("success")) successOrFail=true;
322 callbackMessage = new IoTZigbeeMessageZclWriteAttributesResponse(packetId, clusterId, profileId, successOrFail);
324 } else if (packetData.get("type").equals("zcl_read_attributes_response")) {
325 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
326 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
327 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
329 List<IoTZigbeeMessageZclReadAttributesResponse.Attribute> attrList = new ArrayList<IoTZigbeeMessageZclReadAttributesResponse.Attribute>();
331 String[] attributes = packetData.get("attributes").split(";");
332 for (String attr : attributes) {
334 String[] parts = attr.split(",");
336 if (parts.length == 2) {
337 parts[0] = parts[0].trim();
338 parts[1] = parts[1].trim();
340 IoTZigbeeMessageZclReadAttributesResponse.Attribute at = new IoTZigbeeMessageZclReadAttributesResponse.Attribute(Integer.parseInt(parts[0], 16), 0, false, null);
343 parts[0] = parts[0].trim();
344 parts[1] = parts[1].trim();
345 parts[2] = parts[2].trim();
346 parts[3] = parts[3].trim();
347 IoTZigbeeMessageZclReadAttributesResponse.Attribute at = new IoTZigbeeMessageZclReadAttributesResponse.Attribute(Integer.parseInt(parts[0], 16), Integer.parseInt(parts[1], 16), true, hexStringToByteArray(parts[3]));
352 callbackMessage = new IoTZigbeeMessageZclReadAttributesResponse(packetId, clusterId, profileId, attrList);
354 } else if (packetData.get("type").equals("zcl_configure_reporting_response")) {
355 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
356 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
357 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
359 if (packetData.get("attributes").equals("all_success")) {
360 callbackMessage = new IoTZigbeeMessageZclConfigureReportingResponse(packetId, clusterId, profileId, true, null);
362 List<IoTZigbeeMessageZclConfigureReportingResponse.Attribute> attrList = new ArrayList<IoTZigbeeMessageZclConfigureReportingResponse.Attribute>();
364 String[] attributes = packetData.get("attributes").split(";");
365 for (String attr : attributes) {
367 String[] parts = attr.split(",");
368 parts[0] = parts[0].trim();
369 parts[1] = parts[1].trim();
370 parts[2] = parts[2].trim();
371 IoTZigbeeMessageZclConfigureReportingResponse.Attribute at = new IoTZigbeeMessageZclConfigureReportingResponse.Attribute(Integer.parseInt(parts[0], 16), parts[1].equals("success"), parts[2].equals("reported"));
374 callbackMessage = new IoTZigbeeMessageZclConfigureReportingResponse(packetId, clusterId, profileId, false, attrList);
377 } else if (packetData.get("type").equals("zcl_report_attributes")) {
378 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
379 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
380 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
382 List<IoTZigbeeMessageZclReportAttributes.Attribute> attrList = new ArrayList<IoTZigbeeMessageZclReportAttributes.Attribute>();
384 String[] attributes = packetData.get("attributes").split(";");
385 for (String attr : attributes) {
387 String[] parts = attr.split(",");
389 parts[0] = parts[0].trim();
390 parts[1] = parts[1].trim();
391 parts[2] = parts[2].trim();
392 IoTZigbeeMessageZclReportAttributes.Attribute at = new IoTZigbeeMessageZclReportAttributes.Attribute(Integer.parseInt(parts[0], 16), Integer.parseInt(parts[1], 16), hexStringToByteArray(parts[2]));
396 callbackMessage = new IoTZigbeeMessageZclReportAttributes(packetId, clusterId, profileId, attrList);
398 } else if (packetData.get("type").equals("zcl_read_attributes")) {
399 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
400 boolean success = packetData.get("response").equals("success");
403 callbackMessage = new IoTZigbeeMessageZclReadAttributes(packetId, success, "");
405 callbackMessage = new IoTZigbeeMessageZclReadAttributes(packetId, success, packetData.get("reason"));
408 } else if (packetData.get("type").equals("zcl_configure_reporting")) {
409 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
410 boolean success = packetData.get("response").equals("success");
413 callbackMessage = new IoTZigbeeMessageZclConfigureReporting(packetId, success, "");
415 callbackMessage = new IoTZigbeeMessageZclConfigureReporting(packetId, success, packetData.get("reason"));
418 } else if (packetData.get("type").equals("zdo_bind_request")) {
419 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
420 boolean success = packetData.get("response").equals("success");
423 callbackMessage = new IoTZigbeeMessageZdoBindResponse(packetId, success, "");
425 callbackMessage = new IoTZigbeeMessageZdoBindResponse(packetId, success, packetData.get("reason"));
429 else if (packetData.get("type").equals("zdo_unbind_request")) {
430 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
431 boolean success = packetData.get("response").equals("success");
434 callbackMessage = new IoTZigbeeMessageZdoUnBindResponse(packetId, success, "");
436 callbackMessage = new IoTZigbeeMessageZdoUnBindResponse(packetId, success, packetData.get("reason"));
440 if (callbackMessage != null) {
441 for (IoTZigbeeCallback c : callbackList) {
442 c.newMessageAvailable(callbackMessage);
449 } catch (Exception e) {
455 public static String changeHexEndianness(String hexData) {
457 List<String> pairedValues = new ArrayList<String>();
458 for (int i = 0; i < hexData.length(); i += 2) {
459 String part = hexData.substring(i, Math.min(i + 2, hexData.length()));
460 pairedValues.add(part);
463 String retString = "";
464 for (int i = (pairedValues.size() - 1); i >= 0; i--) {
465 retString += pairedValues.get(i);
470 // taken from: http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java
471 public static byte[] hexStringToByteArray(String s) {
472 int len = s.length();
473 byte[] data = new byte[len / 2];
474 for (int i = 0; i < len; i += 2) {
475 data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
476 + Character.digit(s.charAt(i + 1), 16));