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 deviceEndpoint, 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 += "device_endpoint: " + String.format("%02x", deviceEndpoint) + "\n";
231 message += "attribute_id: " + String.format("%04x", attributeId) + "\n";
232 message += "data_type: " + String.format("%02x", dataType) + "\n";
233 message += "min_reporting_interval: " + String.format("%04x", minReportingInterval) + "\n";
234 message += "max_reporting_interval: " + String.format("%04x", maxReportingInterval) + "\n";
236 if (reportableChange != null) {
237 message += "reportable_change: ";
238 for (Byte b : reportableChange) {
239 message += String.format("%02x", (int)b);
244 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
245 socket.send(sendPacket);
248 public void registerCallback(IoTZigbeeCallback callbackTo) {
249 callbackList.add(callbackTo);
252 public void close() throws InterruptedException {
255 // wait for the threads to end
256 receiveThread.join();
263 * close() called by the garbage collector right before trashing object
265 public void Finalize() throws SocketException, InterruptedException {
269 throw new SocketException("Socket not closed before object destruction, must call close method.");
273 private void sendDeviceAddress() throws IOException {
274 String message = "type: send_address\n";
275 message += "packet_id: 00\n";
276 message += "device_address_long: " + zigbeeAddress.getAddress() + "\n";
277 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
278 socket.send(sendPacket);
281 private void receieveWorker() {
282 while (!(endTask.get())) {
284 byte[] recBuffer = new byte[SOCKET_RECEIVE_BUFFER_SIZE];
286 DatagramPacket recPacket = new DatagramPacket(recBuffer, recBuffer.length);
287 socket.receive(recPacket);
289 // Convert the UDP data into a string format
290 String dataString = new String(recPacket.getData());
292 // split the data by line so we can start procesisng
293 String[] lines = dataString.split("\n");
295 Map<String, String> packetData = new HashMap<String, String>();
296 for (String line : lines) {
299 String trimmedLine = line.trim();
300 // make sure this is a valid data line and not just blank
301 if (trimmedLine.length() == 0) {
305 // Split the data into parts
306 String[] parts = trimmedLine.split(":");
307 parts[0] = parts[0].trim();
308 parts[1] = parts[1].trim();
309 packetData.put(parts[0], parts[1]);
312 if (packetData.get("type").equals("send_address_response")) {
313 didSuccesfullySendAddress.set(true);
316 IoTZigbeeMessage callbackMessage = null;
319 if (packetData.get("type").equals("zcl_zone_status_change_notification")){
320 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
321 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
322 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
323 int status = Integer.parseInt(packetData.get("status"), 10);
324 boolean successOrFail = false;
325 if(packetData.get("attributes").equals("success")) successOrFail=true;
326 callbackMessage = new IoTZigbeeMessageZclZoneStatusChangeNotification(packetId, clusterId, profileId, status, successOrFail);
329 } else if (packetData.get("type").equals("zcl_write_attributes_response")) {
331 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
332 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
333 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
334 boolean successOrFail = false;
335 if(packetData.get("attributes").equals("success")) successOrFail=true;
337 callbackMessage = new IoTZigbeeMessageZclWriteAttributesResponse(packetId, clusterId, profileId, successOrFail);
339 } else if (packetData.get("type").equals("zcl_read_attributes_response")) {
340 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
341 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
342 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
344 List<IoTZigbeeMessageZclReadAttributesResponse.Attribute> attrList = new ArrayList<IoTZigbeeMessageZclReadAttributesResponse.Attribute>();
346 String[] attributes = packetData.get("attributes").split(";");
347 for (String attr : attributes) {
349 String[] parts = attr.split(",");
351 if (parts.length == 2) {
352 parts[0] = parts[0].trim();
353 parts[1] = parts[1].trim();
355 IoTZigbeeMessageZclReadAttributesResponse.Attribute at = new IoTZigbeeMessageZclReadAttributesResponse.Attribute(Integer.parseInt(parts[0], 16), 0, false, null);
358 parts[0] = parts[0].trim();
359 parts[1] = parts[1].trim();
360 parts[2] = parts[2].trim();
361 parts[3] = parts[3].trim();
362 IoTZigbeeMessageZclReadAttributesResponse.Attribute at = new IoTZigbeeMessageZclReadAttributesResponse.Attribute(Integer.parseInt(parts[0], 16), Integer.parseInt(parts[1], 16), true, hexStringToByteArray(parts[3]));
367 callbackMessage = new IoTZigbeeMessageZclReadAttributesResponse(packetId, clusterId, profileId, attrList);
369 } else if (packetData.get("type").equals("zcl_configure_reporting_response")) {
370 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
371 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
372 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
374 if (packetData.get("attributes").equals("all_success")) {
375 callbackMessage = new IoTZigbeeMessageZclConfigureReportingResponse(packetId, clusterId, profileId, true, null);
377 List<IoTZigbeeMessageZclConfigureReportingResponse.Attribute> attrList = new ArrayList<IoTZigbeeMessageZclConfigureReportingResponse.Attribute>();
379 String[] attributes = packetData.get("attributes").split(";");
380 for (String attr : attributes) {
382 String[] parts = attr.split(",");
383 parts[0] = parts[0].trim();
384 parts[1] = parts[1].trim();
385 parts[2] = parts[2].trim();
386 IoTZigbeeMessageZclConfigureReportingResponse.Attribute at = new IoTZigbeeMessageZclConfigureReportingResponse.Attribute(Integer.parseInt(parts[0], 16), parts[1].equals("success"), parts[2].equals("reported"));
389 callbackMessage = new IoTZigbeeMessageZclConfigureReportingResponse(packetId, clusterId, profileId, false, attrList);
392 } else if (packetData.get("type").equals("zcl_report_attributes")) {
393 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
394 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
395 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
397 List<IoTZigbeeMessageZclReportAttributes.Attribute> attrList = new ArrayList<IoTZigbeeMessageZclReportAttributes.Attribute>();
399 String[] attributes = packetData.get("attributes").split(";");
400 for (String attr : attributes) {
402 String[] parts = attr.split(",");
404 parts[0] = parts[0].trim();
405 parts[1] = parts[1].trim();
406 parts[2] = parts[2].trim();
407 IoTZigbeeMessageZclReportAttributes.Attribute at = new IoTZigbeeMessageZclReportAttributes.Attribute(Integer.parseInt(parts[0], 16), Integer.parseInt(parts[1], 16), hexStringToByteArray(parts[2]));
411 callbackMessage = new IoTZigbeeMessageZclReportAttributes(packetId, clusterId, profileId, attrList);
413 } else if (packetData.get("type").equals("zcl_read_attributes")) {
414 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
415 boolean success = packetData.get("response").equals("success");
418 callbackMessage = new IoTZigbeeMessageZclReadAttributes(packetId, success, "");
420 callbackMessage = new IoTZigbeeMessageZclReadAttributes(packetId, success, packetData.get("reason"));
423 } else if (packetData.get("type").equals("zcl_configure_reporting")) {
424 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
425 boolean success = packetData.get("response").equals("success");
428 callbackMessage = new IoTZigbeeMessageZclConfigureReporting(packetId, success, "");
430 callbackMessage = new IoTZigbeeMessageZclConfigureReporting(packetId, success, packetData.get("reason"));
433 } else if (packetData.get("type").equals("zdo_bind_request")) {
434 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
435 boolean success = packetData.get("response").equals("success");
438 callbackMessage = new IoTZigbeeMessageZdoBindResponse(packetId, success, "");
440 callbackMessage = new IoTZigbeeMessageZdoBindResponse(packetId, success, packetData.get("reason"));
444 else if (packetData.get("type").equals("zdo_unbind_request")) {
445 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
446 boolean success = packetData.get("response").equals("success");
449 callbackMessage = new IoTZigbeeMessageZdoUnBindResponse(packetId, success, "");
451 callbackMessage = new IoTZigbeeMessageZdoUnBindResponse(packetId, success, packetData.get("reason"));
455 if (callbackMessage != null) {
456 for (IoTZigbeeCallback c : callbackList) {
457 c.newMessageAvailable(callbackMessage);
464 } catch (Exception e) {
470 public static String changeHexEndianness(String hexData) {
472 List<String> pairedValues = new ArrayList<String>();
473 for (int i = 0; i < hexData.length(); i += 2) {
474 String part = hexData.substring(i, Math.min(i + 2, hexData.length()));
475 pairedValues.add(part);
478 String retString = "";
479 for (int i = (pairedValues.size() - 1); i >= 0; i--) {
480 retString += pairedValues.get(i);
485 // taken from: http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java
486 public static byte[] hexStringToByteArray(String s) {
487 int len = s.length();
488 byte[] data = new byte[len / 2];
489 for (int i = 0; i < len; i += 2) {
490 data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
491 + Character.digit(s.charAt(i + 1), 16));