1 package iotruntime.zigbee;
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;
14 import java.util.HashMap;
15 import java.util.concurrent.ConcurrentHashMap;
17 import java.util.HashSet;
18 import java.nio.charset.StandardCharsets;
19 import java.util.concurrent.Semaphore;
21 import iotruntime.slave.IoTZigbeeAddress;
22 import iotruntime.slave.IoTDeviceAddress;
26 * @author Ali Younis <ayounis @ uci.edu>, Changwoo Lee, Jiawei Gu
30 public final class IoTZigbee {
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;
39 * IoTZigbee class properties
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
49 private final IoTZigbeeAddress zigbeeAddress;
51 // list that holds the callbacks
52 private List<IoTZigbeeCallback> callbackList = new ArrayList<IoTZigbeeCallback>();
55 * IoTZigbee class concurrency and concurrency control
57 private Thread receiveThread = null;
59 private AtomicBoolean endTask = new AtomicBoolean(false);
60 private AtomicBoolean didSuccesfullySendAddress = new AtomicBoolean(false);
65 public IoTZigbee(IoTDeviceAddress iotDevAdd, IoTZigbeeAddress zigAddress) throws SocketException, IOException, InterruptedException {
67 strHostAddress = iotDevAdd.getHostAddress();
68 iSrcPort = iotDevAdd.getSourcePortNumber();
69 iDstPort = iotDevAdd.getDestinationPortNumber();
71 zigbeeAddress = zigAddress;
73 socket = new DatagramSocket(iSrcPort);
74 socket.setSendBufferSize(SOCKET_SEND_BUFFER_SIZE);
75 socket.setReceiveBufferSize(SOCKET_RECEIVE_BUFFER_SIZE);
77 receiveThread = new Thread(new Runnable() {
82 receiveThread.start();
85 public void init() throws IOException {
86 while (!didSuccesfullySendAddress.get()) {
91 Thread.sleep(RESEND_WAIT_TIME);
92 } catch (Exception e) {
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);
112 public void sendLockOrUnlockDoorRequest(int packetId, int clusterId, int profileId, int deviceEndpoint, int value) throws IOException {
113 String message = "type: zcl_lock_or_unlock_door_request\n";
114 message += "packet_id: " + String.format("%04x", packetId) + "\n";
115 message += "value: " + String.format("%01x", value) + "\n";
116 message += "cluster_id: " + String.format("%04x", clusterId) + "\n";
117 message += "profile_id: " + String.format("%04x", profileId) + "\n";
118 message += "device_address_long: " + zigbeeAddress.getAddress() + "\n";
119 message += "device_endpoint: " + String.format("%02x", deviceEndpoint) + "\n";
120 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
121 socket.send(sendPacket);
125 public void sendReadDoorStatusRequest(int packetId, int clusterId, int profileId, int deviceEndpoint, int framecontrol, int commandframe, int attribute_id) throws IOException {
126 String message = "type: zcl_read_door_status_request\n";
127 message += "packet_id: " + String.format("%04x", packetId) + "\n";
128 message += "framecontrol: " + String.format("%02x", framecontrol) + "\n";
129 message += "cluster_id: " + String.format("%04x", clusterId) + "\n";
130 message += "profile_id: " + String.format("%04x", profileId) + "\n";
131 message += "device_address_long: " + zigbeeAddress.getAddress() + "\n";
132 message += "device_endpoint: " + String.format("%02x", deviceEndpoint) + "\n";
133 message += "commandframe: " + String.format("%02x", commandframe) + "\n";
134 message += "attribute_id: " + String.format("%04x", attribute_id) + "\n";
135 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
136 socket.send(sendPacket);
140 public void sendBroadcastingRouteRecordRequest(int packetId) throws IOException {
141 String message = "type: zdo_broadcast_route_record_request\n";
142 message += "packet_id: " + String.format("%04x", packetId) + "\n";
143 message += "device_address_long: " + zigbeeAddress.getAddress() + "\n";
144 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
145 socket.send(sendPacket);
149 public void sendEnrollmentResponse(int packetId, int clusterId, int profileId, int deviceEndpoint) throws IOException {
150 String message = "type: zcl_enrollment_response\n";
151 message += "packet_id: " + String.format("%04x", packetId) + "\n";
152 message += "device_address_long: " + zigbeeAddress.getAddress() + "\n";
153 message += "cluster_id: " + String.format("%04x", clusterId) + "\n";
154 message += "profile_id: " + String.format("%04x", profileId) + "\n";
155 message += "device_endpoint: " + String.format("%02x", deviceEndpoint) + "\n";
156 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
157 socket.send(sendPacket);
161 public void sendWriteAttributesCommand(int packetId, int clusterId, int profileId, int deviceEndpoint) throws IOException {
162 String message = "type: zcl_write_attributes\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 += "profile_id: " + String.format("%04x", profileId) + "\n";
167 message += "device_endpoint: " + String.format("%02x", deviceEndpoint) + "\n";
168 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
169 socket.send(sendPacket);
173 public void sendManagementPermitJoiningRequest(int packetId, int clusterId, int deviceEndpoint) throws IOException {
174 String message = "type: management_permit_joining_request\n";
175 message += "packet_id: " + String.format("%04x", packetId) + "\n";
176 message += "device_address_long: " + zigbeeAddress.getAddress() + "\n";
177 message += "cluster_id: " + String.format("%04x", clusterId) + "\n";
178 message += "device_endpoint: " + String.format("%02x", deviceEndpoint) + "\n";
179 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
180 socket.send(sendPacket);
183 public void sendBindRequest(int packetId, int clusterId, int deviceEndpoint) throws IOException {
184 String message = "type: zdo_bind_request\n";
185 message += "packet_id: " + String.format("%04x", packetId) + "\n";
186 message += "device_address_long: " + zigbeeAddress.getAddress() + "\n";
187 message += "cluster_id: " + String.format("%04x", clusterId) + "\n";
188 message += "device_endpoint: " + String.format("%02x", deviceEndpoint) + "\n";
189 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
190 socket.send(sendPacket);
193 public void sendUnBindRequest(int packetId, int clusterId, int deviceEndpoint) throws IOException {
194 String message = "type: zdo_unbind_request\n";
195 message += "packet_id: " + String.format("%04x", packetId) + "\n";
196 message += "device_address_long: " + zigbeeAddress.getAddress() + "\n";
197 message += "cluster_id: " + String.format("%04x", clusterId) + "\n";
198 message += "device_endpoint: " + String.format("%02x", deviceEndpoint) + "\n";
199 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
200 socket.send(sendPacket);
203 public void sendReadAttributesCommand(int packetId, int clusterId, int profileId, int deviceEndpoint, List<Integer> attributeIds) throws IOException {
204 String message = "type: zcl_read_attributes\n";
205 message += "packet_id: " + String.format("%04x", packetId) + "\n";
206 message += "device_address_long: " + zigbeeAddress.getAddress() + "\n";
207 message += "cluster_id: " + String.format("%04x", clusterId) + "\n";
208 message += "profile_id: " + String.format("%04x", profileId) + "\n";
209 message += "device_endpoint: " + String.format("%02x", deviceEndpoint) + "\n";
211 message += "attribute_ids: ";
213 for (Integer i : attributeIds) {
214 message += String.format("%04x", i) + ",";
217 message = message.substring(0, message.length() - 1);
220 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
221 socket.send(sendPacket);
224 public void sendConfigureReportingCommand(int packetId, int clusterId, int profileId, int src_endpoint, int dest_endpoint, int attributeId, int dataType, int minReportingInterval, int maxReportingInterval, byte[] reportableChange) throws IOException {
225 String message = "type: zcl_configure_reporting\n";
226 message += "packet_id: " + String.format("%04x", packetId) + "\n";
227 message += "device_address_long: " + zigbeeAddress.getAddress() + "\n";
228 message += "cluster_id: " + String.format("%04x", clusterId) + "\n";
229 message += "profile_id: " + String.format("%04x", profileId) + "\n";
230 message += "src_endpoint: " + String.format("%02x", src_endpoint) + "\n";
231 message += "device_endpoint: " + String.format("%02x", dest_endpoint) + "\n";
232 message += "attribute_id: " + String.format("%04x", attributeId) + "\n";
233 message += "data_type: " + String.format("%02x", dataType) + "\n";
234 message += "min_reporting_interval: " + String.format("%04x", minReportingInterval) + "\n";
235 message += "max_reporting_interval: " + String.format("%04x", maxReportingInterval) + "\n";
237 if (reportableChange != null) {
238 message += "reportable_change: ";
239 for (Byte b : reportableChange) {
240 message += String.format("%02x", (int)b);
245 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
246 socket.send(sendPacket);
249 public void sendConfigureReportingCommand(int packetId, int clusterId, int profileId, int dest_endpoint, int attributeId, int dataType, int minReportingInterval, int maxReportingInterval, byte[] reportableChange) throws IOException {
250 sendConfigureReportingCommand(packetId, clusterId, profileId, 0x00, dest_endpoint, attributeId, dataType, minReportingInterval, maxReportingInterval, reportableChange);
253 public void registerCallback(IoTZigbeeCallback callbackTo) {
254 callbackList.add(callbackTo);
257 public void close() throws InterruptedException {
260 // wait for the threads to end
261 receiveThread.join();
268 * close() called by the garbage collector right before trashing object
270 public void Finalize() throws SocketException, InterruptedException {
274 throw new SocketException("Socket not closed before object destruction, must call close method.");
278 private void sendDeviceAddress() throws IOException {
279 String message = "type: send_address\n";
280 message += "packet_id: 00\n";
281 message += "device_address_long: " + zigbeeAddress.getAddress() + "\n";
282 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
283 socket.send(sendPacket);
286 private void receieveWorker() {
287 while (!(endTask.get())) {
289 byte[] recBuffer = new byte[SOCKET_RECEIVE_BUFFER_SIZE];
291 DatagramPacket recPacket = new DatagramPacket(recBuffer, recBuffer.length);
292 socket.receive(recPacket);
294 // Convert the UDP data into a string format
295 String dataString = new String(recPacket.getData());
297 // split the data by line so we can start procesisng
298 String[] lines = dataString.split("\n");
300 Map<String, String> packetData = new HashMap<String, String>();
301 for (String line : lines) {
304 String trimmedLine = line.trim();
305 // make sure this is a valid data line and not just blank
306 if (trimmedLine.length() == 0) {
310 // Split the data into parts
311 String[] parts = trimmedLine.split(":");
312 parts[0] = parts[0].trim();
313 parts[1] = parts[1].trim();
314 packetData.put(parts[0], parts[1]);
317 if (packetData.get("type").equals("send_address_response")) {
318 didSuccesfullySendAddress.set(true);
321 IoTZigbeeMessage callbackMessage = null;
324 if (packetData.get("type").equals("zcl_zone_status_change_notification")){
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);
328 int status = Integer.parseInt(packetData.get("status"), 10);
329 boolean successOrFail = false;
330 if(packetData.get("attributes").equals("success")) successOrFail=true;
331 callbackMessage = new IoTZigbeeMessageZclZoneStatusChangeNotification(packetId, clusterId, profileId, status, successOrFail);
334 } else if (packetData.get("type").equals("zcl_write_attributes_response")) {
336 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
337 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
338 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
339 boolean successOrFail = false;
340 if(packetData.get("attributes").equals("success")) successOrFail=true;
342 callbackMessage = new IoTZigbeeMessageZclWriteAttributesResponse(packetId, clusterId, profileId, successOrFail);
344 } else if (packetData.get("type").equals("zcl_read_attributes_response")) {
345 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
346 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
347 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
349 List<IoTZigbeeMessageZclReadAttributesResponse.Attribute> attrList = new ArrayList<IoTZigbeeMessageZclReadAttributesResponse.Attribute>();
351 String[] attributes = packetData.get("attributes").split(";");
352 for (String attr : attributes) {
354 String[] parts = attr.split(",");
356 if (parts.length == 2) {
357 parts[0] = parts[0].trim();
358 parts[1] = parts[1].trim();
360 IoTZigbeeMessageZclReadAttributesResponse.Attribute at = new IoTZigbeeMessageZclReadAttributesResponse.Attribute(Integer.parseInt(parts[0], 16), 0, false, null);
363 parts[0] = parts[0].trim();
364 parts[1] = parts[1].trim();
365 parts[2] = parts[2].trim();
366 parts[3] = parts[3].trim();
367 IoTZigbeeMessageZclReadAttributesResponse.Attribute at = new IoTZigbeeMessageZclReadAttributesResponse.Attribute(Integer.parseInt(parts[0], 16), Integer.parseInt(parts[1], 16), true, hexStringToByteArray(parts[3]));
372 callbackMessage = new IoTZigbeeMessageZclReadAttributesResponse(packetId, clusterId, profileId, attrList);
374 } else if (packetData.get("type").equals("zcl_configure_reporting_response")) {
375 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
376 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
377 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
379 if (packetData.get("attributes").equals("all_success")) {
380 callbackMessage = new IoTZigbeeMessageZclConfigureReportingResponse(packetId, clusterId, profileId, true, null);
382 List<IoTZigbeeMessageZclConfigureReportingResponse.Attribute> attrList = new ArrayList<IoTZigbeeMessageZclConfigureReportingResponse.Attribute>();
384 String[] attributes = packetData.get("attributes").split(";");
385 for (String attr : attributes) {
387 String[] parts = attr.split(",");
388 parts[0] = parts[0].trim();
389 parts[1] = parts[1].trim();
390 parts[2] = parts[2].trim();
391 IoTZigbeeMessageZclConfigureReportingResponse.Attribute at = new IoTZigbeeMessageZclConfigureReportingResponse.Attribute(Integer.parseInt(parts[0], 16), parts[1].equals("success"), parts[2].equals("reported"));
394 callbackMessage = new IoTZigbeeMessageZclConfigureReportingResponse(packetId, clusterId, profileId, false, attrList);
397 } else if (packetData.get("type").equals("zcl_report_attributes")) {
398 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
399 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
400 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
402 List<IoTZigbeeMessageZclReportAttributes.Attribute> attrList = new ArrayList<IoTZigbeeMessageZclReportAttributes.Attribute>();
404 String[] attributes = packetData.get("attributes").split(";");
405 for (String attr : attributes) {
407 String[] parts = attr.split(",");
409 parts[0] = parts[0].trim();
410 parts[1] = parts[1].trim();
411 parts[2] = parts[2].trim();
412 IoTZigbeeMessageZclReportAttributes.Attribute at = new IoTZigbeeMessageZclReportAttributes.Attribute(Integer.parseInt(parts[0], 16), Integer.parseInt(parts[1], 16), hexStringToByteArray(parts[2]));
416 callbackMessage = new IoTZigbeeMessageZclReportAttributes(packetId, clusterId, profileId, attrList);
418 } else if (packetData.get("type").equals("zcl_read_attributes")) {
419 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
420 boolean success = packetData.get("response").equals("success");
423 callbackMessage = new IoTZigbeeMessageZclReadAttributes(packetId, success, "");
425 callbackMessage = new IoTZigbeeMessageZclReadAttributes(packetId, success, packetData.get("reason"));
428 } else if (packetData.get("type").equals("zcl_configure_reporting")) {
429 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
430 boolean success = packetData.get("response").equals("success");
433 callbackMessage = new IoTZigbeeMessageZclConfigureReporting(packetId, success, "");
435 callbackMessage = new IoTZigbeeMessageZclConfigureReporting(packetId, success, packetData.get("reason"));
438 } else if (packetData.get("type").equals("zdo_bind_request")) {
439 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
440 boolean success = packetData.get("response").equals("success");
443 callbackMessage = new IoTZigbeeMessageZdoBindResponse(packetId, success, "");
445 callbackMessage = new IoTZigbeeMessageZdoBindResponse(packetId, success, packetData.get("reason"));
449 else if (packetData.get("type").equals("zdo_unbind_request")) {
450 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
451 boolean success = packetData.get("response").equals("success");
454 callbackMessage = new IoTZigbeeMessageZdoUnBindResponse(packetId, success, "");
456 callbackMessage = new IoTZigbeeMessageZdoUnBindResponse(packetId, success, packetData.get("reason"));
460 if (callbackMessage != null) {
461 for (IoTZigbeeCallback c : callbackList) {
462 c.newMessageAvailable(callbackMessage);
469 } catch (Exception e) {
475 public static String changeHexEndianness(String hexData) {
477 List<String> pairedValues = new ArrayList<String>();
478 for (int i = 0; i < hexData.length(); i += 2) {
479 String part = hexData.substring(i, Math.min(i + 2, hexData.length()));
480 pairedValues.add(part);
483 String retString = "";
484 for (int i = (pairedValues.size() - 1); i >= 0; i--) {
485 retString += pairedValues.get(i);
490 // taken from: http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java
491 public static byte[] hexStringToByteArray(String s) {
492 int len = s.length();
493 byte[] data = new byte[len / 2];
494 for (int i = 0; i < len; i += 2) {
495 data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
496 + Character.digit(s.charAt(i + 1), 16));