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>
30 public 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 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);
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);
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);
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);
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);
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);
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";
183 message += "attribute_ids: ";
185 for (Integer i : attributeIds) {
186 message += String.format("%04x", i) + ",";
189 message = message.substring(0, message.length() - 1);
192 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
193 socket.send(sendPacket);
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";
208 if (reportableChange != null) {
209 message += "reportable_change: ";
210 for (Byte b : reportableChange) {
211 message += String.format("%02x", (int)b);
216 DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(strHostAddress), iDstPort);
217 socket.send(sendPacket);
220 public void registerCallback(IoTZigbeeCallback callbackTo) {
221 callbackList.add(callbackTo);
224 public void close() throws InterruptedException {
227 // wait for the threads to end
228 receiveThread.join();
235 * close() called by the garbage collector right before trashing object
237 public void Finalize() throws SocketException, InterruptedException {
241 throw new SocketException("Socket not closed before object destruction, must call close method.");
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);
253 private void receieveWorker() {
254 while (!(endTask.get())) {
256 byte[] recBuffer = new byte[SOCKET_RECEIVE_BUFFER_SIZE];
258 DatagramPacket recPacket = new DatagramPacket(recBuffer, recBuffer.length);
259 socket.receive(recPacket);
261 // Convert the UDP data into a string format
262 String dataString = new String(recPacket.getData());
264 // split the data by line so we can start procesisng
265 String[] lines = dataString.split("\n");
267 Map<String, String> packetData = new HashMap<String, String>();
268 for (String line : lines) {
271 String trimmedLine = line.trim();
272 // make sure this is a valid data line and not just blank
273 if (trimmedLine.length() == 0) {
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]);
284 if (packetData.get("type").equals("send_address_response")) {
285 didSuccesfullySendAddress.set(true);
288 IoTZigbeeMessage callbackMessage = null;
290 if (packetData.get("type").equals("zcl_read_attributes_response")) {
291 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
292 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
293 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
295 List<IoTZigbeeMessageZclReadAttributesResponse.Attribute> attrList = new ArrayList<IoTZigbeeMessageZclReadAttributesResponse.Attribute>();
297 String[] attributes = packetData.get("attributes").split(";");
298 for (String attr : attributes) {
300 String[] parts = attr.split(",");
302 if (parts.length == 2) {
303 parts[0] = parts[0].trim();
304 parts[1] = parts[1].trim();
306 IoTZigbeeMessageZclReadAttributesResponse.Attribute at = new IoTZigbeeMessageZclReadAttributesResponse.Attribute(Integer.parseInt(parts[0], 16), 0, false, null);
309 parts[0] = parts[0].trim();
310 parts[1] = parts[1].trim();
311 parts[2] = parts[2].trim();
312 parts[3] = parts[3].trim();
313 IoTZigbeeMessageZclReadAttributesResponse.Attribute at = new IoTZigbeeMessageZclReadAttributesResponse.Attribute(Integer.parseInt(parts[0], 16), Integer.parseInt(parts[1], 16), true, hexStringToByteArray(parts[3]));
318 callbackMessage = new IoTZigbeeMessageZclReadAttributesResponse(packetId, clusterId, profileId, attrList);
320 } else if (packetData.get("type").equals("zcl_configure_reporting_response")) {
321 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
322 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
323 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
325 if (packetData.get("attributes").equals("all_success")) {
326 callbackMessage = new IoTZigbeeMessageZclConfigureReportingResponse(packetId, clusterId, profileId, true, null);
328 List<IoTZigbeeMessageZclConfigureReportingResponse.Attribute> attrList = new ArrayList<IoTZigbeeMessageZclConfigureReportingResponse.Attribute>();
330 String[] attributes = packetData.get("attributes").split(";");
331 for (String attr : attributes) {
333 String[] parts = attr.split(",");
334 parts[0] = parts[0].trim();
335 parts[1] = parts[1].trim();
336 parts[2] = parts[2].trim();
337 IoTZigbeeMessageZclConfigureReportingResponse.Attribute at = new IoTZigbeeMessageZclConfigureReportingResponse.Attribute(Integer.parseInt(parts[0], 16), parts[1].equals("success"), parts[2].equals("reported"));
340 callbackMessage = new IoTZigbeeMessageZclConfigureReportingResponse(packetId, clusterId, profileId, false, attrList);
343 } else if (packetData.get("type").equals("zcl_report_attributes")) {
344 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
345 int clusterId = Integer.parseInt(packetData.get("cluster_id"), 16);
346 int profileId = Integer.parseInt(packetData.get("profile_id"), 16);
348 List<IoTZigbeeMessageZclReportAttributes.Attribute> attrList = new ArrayList<IoTZigbeeMessageZclReportAttributes.Attribute>();
350 String[] attributes = packetData.get("attributes").split(";");
351 for (String attr : attributes) {
353 String[] parts = attr.split(",");
355 parts[0] = parts[0].trim();
356 parts[1] = parts[1].trim();
357 parts[2] = parts[2].trim();
358 IoTZigbeeMessageZclReportAttributes.Attribute at = new IoTZigbeeMessageZclReportAttributes.Attribute(Integer.parseInt(parts[0], 16), Integer.parseInt(parts[1], 16), hexStringToByteArray(parts[2]));
362 callbackMessage = new IoTZigbeeMessageZclReportAttributes(packetId, clusterId, profileId, attrList);
364 } else if (packetData.get("type").equals("zcl_read_attributes")) {
365 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
366 boolean success = packetData.get("response").equals("success");
369 callbackMessage = new IoTZigbeeMessageZclReadAttributes(packetId, success, "");
371 callbackMessage = new IoTZigbeeMessageZclReadAttributes(packetId, success, packetData.get("reason"));
374 } else if (packetData.get("type").equals("zcl_configure_reporting")) {
375 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
376 boolean success = packetData.get("response").equals("success");
379 callbackMessage = new IoTZigbeeMessageZclConfigureReporting(packetId, success, "");
381 callbackMessage = new IoTZigbeeMessageZclConfigureReporting(packetId, success, packetData.get("reason"));
384 } else if (packetData.get("type").equals("zdo_bind_request")) {
385 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
386 boolean success = packetData.get("response").equals("success");
389 callbackMessage = new IoTZigbeeMessageZdoBindResponse(packetId, success, "");
391 callbackMessage = new IoTZigbeeMessageZdoBindResponse(packetId, success, packetData.get("reason"));
395 else if (packetData.get("type").equals("zdo_unbind_request")) {
396 int packetId = Integer.parseInt(packetData.get("packet_id"), 16);
397 boolean success = packetData.get("response").equals("success");
400 callbackMessage = new IoTZigbeeMessageZdoUnBindResponse(packetId, success, "");
402 callbackMessage = new IoTZigbeeMessageZdoUnBindResponse(packetId, success, packetData.get("reason"));
406 if (callbackMessage != null) {
407 for (IoTZigbeeCallback c : callbackList) {
408 c.newMessageAvailable(callbackMessage);
415 } catch (Exception e) {
421 public static String changeHexEndianness(String hexData) {
423 List<String> pairedValues = new ArrayList<String>();
424 for (int i = 0; i < hexData.length(); i += 2) {
425 String part = hexData.substring(i, Math.min(i + 2, hexData.length()));
426 pairedValues.add(part);
429 String retString = "";
430 for (int i = (pairedValues.size() - 1); i >= 0; i--) {
431 retString += pairedValues.get(i);
436 // taken from: http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java
437 public static byte[] hexStringToByteArray(String s) {
438 int len = s.length();
439 byte[] data = new byte[len / 2];
440 for (int i = 0; i < len; i += 2) {
441 data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
442 + Character.digit(s.charAt(i + 1), 16));