1 package iotruntime.slave;
4 import iotruntime.zigbee.*;
5 import iotruntime.messages.*;
6 import iotruntime.master.RuntimeOutput;
10 import java.io.FileInputStream;
11 import java.io.FileOutputStream;
12 import java.io.ObjectInputStream;
13 import java.io.ObjectOutputStream;
14 import java.io.InputStream;
15 import java.io.OutputStream;
16 import java.io.IOException;
17 import java.io.FileNotFoundException;
18 import java.lang.ClassNotFoundException;
19 import java.lang.Class;
20 import java.lang.reflect.*;
21 import java.lang.ClassLoader;
22 import java.net.InetAddress;
23 import java.net.Socket;
24 import java.net.UnknownHostException;
26 import java.net.URLClassLoader;
27 import java.rmi.registry.LocateRegistry;
28 import java.rmi.registry.Registry;
29 import java.rmi.Remote;
30 import java.rmi.RemoteException;
31 import java.rmi.AlreadyBoundException;
32 import java.rmi.NotBoundException;
33 import java.rmi.server.UnicastRemoteObject;
34 import java.util.Arrays;
35 import java.util.Properties;
36 import java.util.HashMap;
40 import net.lingala.zip4j.exception.ZipException;
41 import net.lingala.zip4j.core.ZipFile;
43 /** Class IoTSlave is run by IoTMaster on a different JVM's.
44 * It needs to respond to IoTMaster's commands
46 * @author Rahmadi Trimananda <rahmadi.trimananda @ uci.edu>
50 public class IoTSlave {
53 * IoTSlave class properties
55 private Message sIoTMasterMsg;
56 private String sIoTMasterHostAdd;
57 private String sMainObjectName;
59 private int iRMIRegPort;
60 private int iRMIStubPort;
61 private String strFieldName;
62 private Class<?> clsMain;
63 private Object objMainCls;
64 private Object iRelFirstObject;
65 private Object iRelSecondObject;
66 private Socket socket;
67 private ObjectOutputStream outStream;
68 private ObjectInputStream inStream;
69 private Map<String,Object> mapObjNameStub;
72 * IoTSet object, e.g. IoTSet<ProximitySensor> proximity_sensors;
73 * IoTRelation object, e.g. IoTRelation<ProximitySensor, LightBulb> ps_lb_relation;
75 private ISet<Object> isetObject;
76 private IoTSet<Object> iotsetObject;
77 private IRelation<Object,Object> irelObject;
78 private IoTRelation<Object,Object> iotrelObject;
80 // Constants that are to be extracted from config file
81 private static String STR_JAR_FILE_PATH;
82 private static String STR_OBJ_CLS_PFX;
83 private static String STR_INTERFACE_PFX;
84 private static String SKEL_CLASS_SUFFIX;
85 private static String STUB_CLASS_SUFFIX;
86 private static boolean BOOL_VERBOSE;
87 private static boolean CAPAB_BASED_RMI;
90 * IoTSlave class constants - not to be changed by users
92 private static final String STR_IOT_SLAVE_NAME = "IoTSlave";
93 private static final String STR_CFG_FILE_EXT = ".config";
94 private static final String STR_CLS_FILE_EXT = ".class";
95 private static final String STR_JAR_FILE_EXT = ".jar";
96 private static final String STR_ZIP_FILE_EXT = ".zip";
97 private static final String STR_UNZIP_DIR = "./";
98 private static final Class<?>[] STR_URL_PARAM = new Class[] {URL.class };
99 private static final String STR_YES = "Yes";
100 private static final String STR_NO = "No";
106 public IoTSlave(String[] argInp) {
108 sIoTMasterMsg = null;
109 sIoTMasterHostAdd = argInp[0];
110 iComPort = Integer.parseInt(argInp[1]);
111 iRMIRegPort = Integer.parseInt(argInp[2]);
112 iRMIStubPort = Integer.parseInt(argInp[3]);
113 sMainObjectName = null;
121 iRelFirstObject = null;
122 iRelSecondObject = null;
126 mapObjNameStub = new HashMap<String,Object>();
128 STR_JAR_FILE_PATH = null;
129 STR_OBJ_CLS_PFX = null;
130 STR_INTERFACE_PFX = null;
131 SKEL_CLASS_SUFFIX = null;
132 STUB_CLASS_SUFFIX = null;
133 BOOL_VERBOSE = false;
134 CAPAB_BASED_RMI = false;
138 * A method to initialize constants from config file
142 private void parseIoTSlaveConfigFile() {
143 // Parse configuration file
144 Properties prop = new Properties();
145 String strCfgFileName = STR_IOT_SLAVE_NAME + STR_CFG_FILE_EXT;
146 File file = new File(strCfgFileName);
148 FileInputStream fis = new FileInputStream(file);
150 } catch (IOException ex) {
151 System.out.println("IoTMaster: Error reading config file: " + strCfgFileName);
152 ex.printStackTrace();
154 System.out.println("IoTMaster: Extracting information from config file: " + strCfgFileName);
155 // Initialize constants from config file
156 STR_JAR_FILE_PATH = prop.getProperty("JAR_FILE_PATH");
157 STR_OBJ_CLS_PFX = prop.getProperty("OBJECT_CLASS_PREFIX");
158 STR_INTERFACE_PFX = prop.getProperty("INTERFACE_PREFIX");
159 SKEL_CLASS_SUFFIX = prop.getProperty("SKEL_CLASS_SUFFIX");
160 STUB_CLASS_SUFFIX = prop.getProperty("STUB_CLASS_SUFFIX");
161 if (prop.getProperty("VERBOSE").equals(STR_YES)) {
164 if (prop.getProperty("CAPAB_BASED_RMI").equals(STR_YES)) {
165 CAPAB_BASED_RMI = true;
168 System.out.println("JAR_FILE_PATH=" + STR_JAR_FILE_PATH);
169 System.out.println("OBJECT_CLASS_PREFIX=" + STR_OBJ_CLS_PFX);
170 System.out.println("INTERFACE_PREFIX=" + STR_INTERFACE_PFX);
171 System.out.println("SKEL_CLASS_SUFFIX=" + SKEL_CLASS_SUFFIX);
172 System.out.println("STUB_CLASS_SUFFIX=" + STUB_CLASS_SUFFIX);
173 System.out.println("CAPAB_BASED_RMI=" + CAPAB_BASED_RMI);
174 System.out.println("IoTMaster: Information extracted successfully!");
178 * Adds the content pointed by the URL to the classpath dynamically at runtime (hack!!!)
180 * @param url the URL pointing to the content to be added
181 * @throws IOException
182 * @see <a href="http://stackoverflow.com/questions/60764/how-should-i-load-jars-dynamically-at-runtime</a>
184 private static void addURL(URL url) throws IOException {
186 URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader();
187 Class<?> sysclass = URLClassLoader.class;
191 Method method = sysclass.getDeclaredMethod("addURL", STR_URL_PARAM);
192 method.setAccessible(true);
193 method.invoke(sysloader,new Object[] { url });
195 } catch (Throwable t) {
198 throw new IOException("IoTSlave: Could not add URL to system classloader!");
203 * A private method to create object
207 private void createCapabBasedRMIJava(MessageCreateObject sMessage) throws
208 ClassNotFoundException, NoSuchMethodException, UnknownHostException {
211 System.out.println("\n\nDEBUG: Create capab based RMI here!");
212 System.out.println("DEBUG: sMessage host address: " + sMessage.getHostAddress());
213 System.out.println("DEBUG: sMessage object class: " + sMessage.getObjectClass());
214 System.out.println("DEBUG: sMessage object name: " + sMessage.getObjectName());
215 System.out.println("DEBUG: sMessage interface name: " + sMessage.getObjectInterfaceName());
216 System.out.println("DEBUG: sMessage reg port: " + sMessage.getRMIRegPort());
217 System.out.println("DEBUG: sMessage stub port: " + sMessage.getRMIStubPort());
218 System.out.println("DEBUG: sMessage object fields: " + Arrays.toString(sMessage.getObjectFields()));
219 System.out.println("DEBUG: sMessage object fields: " + Arrays.toString(sMessage.getObjectFldCls()));
220 System.out.println("\n\n");
222 // Instantiate the skeleton and put in the object
223 String strObjSkelName = STR_OBJ_CLS_PFX + "." + sMessage.getObjectClass() +
224 "." + sMessage.getObjectInterfaceName() + SKEL_CLASS_SUFFIX;
225 RuntimeOutput.print("IoTSlave: Skeleton object: " + strObjSkelName, BOOL_VERBOSE);
226 Class<?> clsSkel = Class.forName(strObjSkelName);
227 Class<?> clsInt = Class.forName(STR_OBJ_CLS_PFX + "." + STR_INTERFACE_PFX +
228 "." + sMessage.getObjectInterfaceName());
229 Class[] clsSkelParams = { clsInt, String.class, int.class }; // Port number is integer
230 Constructor<?> objSkelCons = clsSkel.getDeclaredConstructor(clsSkelParams);
231 String callbackAddress = InetAddress.getLocalHost().getHostAddress(); // Callback address is this machine's address
232 Object objSkelParams[] = { objMainCls, callbackAddress, iRMIStubPort };
233 // Create a new thread for each skeleton
234 Thread objectThread = new Thread(new Runnable() {
237 Object objSkel = objSkelCons.newInstance(objSkelParams);
238 } catch (InstantiationException |
239 IllegalAccessException |
240 InvocationTargetException ex) {
241 ex.printStackTrace();
245 objectThread.start();
246 RuntimeOutput.print("IoTSlave: Done generating object!", BOOL_VERBOSE);
250 * A private method to create object
254 private void createObject() throws IOException,
255 ClassNotFoundException, NoSuchMethodException, InstantiationException,
256 RemoteException, AlreadyBoundException, IllegalAccessException,
257 InvocationTargetException {
260 System.out.println("\n\nDEBUG: CREATE DRIVER OBJECT!!!\n\n");
262 // Translating into the actual Message class
263 MessageCreateObject sMessage = (MessageCreateObject) sIoTMasterMsg;
264 // Instantiate object using reflection
265 String strObjClassName = STR_OBJ_CLS_PFX + "." + sMessage.getObjectClass() +
266 "." + sMessage.getObjectClass();
267 File file = new File(STR_JAR_FILE_PATH + sMessage.getObjectClass() + STR_JAR_FILE_EXT);
268 RuntimeOutput.print("IoTSlave: DEBUG print path: " + STR_JAR_FILE_PATH +
269 sMessage.getObjectClass() + STR_JAR_FILE_EXT, BOOL_VERBOSE);
270 addURL(file.toURI().toURL());
271 clsMain = Class.forName(strObjClassName);
272 Class[] clsParams = sMessage.getObjectFldCls();
273 Constructor<?> ct = clsMain.getDeclaredConstructor(clsParams);
274 Object objParams[] = sMessage.getObjectFields();
275 objMainCls = ct.newInstance(objParams);
276 RuntimeOutput.print("IoTSlave: Creating RMI skeleton: " +
277 sMessage.getHostAddress() + ":" + sMessage.getRMIRegPort() +
278 " with RMI stub port: " + iRMIStubPort, BOOL_VERBOSE);
279 if (CAPAB_BASED_RMI) {
280 // Use the new capability-based RMI in Java
281 createCapabBasedRMIJava(sMessage);
283 // Register object to RMI - there are 2 ports: RMI registry port and RMI stub port
284 Object objStub = (Object)
285 UnicastRemoteObject.exportObject((Remote) objMainCls, iRMIStubPort);
286 Registry registry = LocateRegistry.createRegistry(iRMIRegPort);
287 registry.bind(sMessage.getObjectName(), (Remote) objStub);
289 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
290 RuntimeOutput.print("IoTSlave: Registering object via RMI!", BOOL_VERBOSE);
296 * A private method to transfer file
300 private void transferFile() throws IOException,
301 UnknownHostException, FileNotFoundException {
303 // Translating into the actual Message class
304 MessageSendFile sMessage = (MessageSendFile) sIoTMasterMsg;
306 // Send back the received message as acknowledgement
307 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
309 // Write file to the current location
310 Socket filesocket = new Socket(sIoTMasterHostAdd, iComPort);
311 InputStream inFileStream = filesocket.getInputStream();
312 OutputStream outFileStream = new FileOutputStream(sMessage.getFileName());
313 byte[] bytFile = new byte[Math.toIntExact(sMessage.getFileSize())];
316 while ((iCount = inFileStream.read(bytFile)) > 0) {
317 outFileStream.write(bytFile, 0, iCount);
319 // Unzip if this is a zipped file
320 if (sMessage.getFileName().contains(STR_ZIP_FILE_EXT)) {
321 RuntimeOutput.print("IoTSlave: Unzipping file: " + sMessage.getFileName(), BOOL_VERBOSE);
323 ZipFile zipFile = new ZipFile(sMessage.getFileName());
324 zipFile.extractAll(STR_UNZIP_DIR);
325 } catch (ZipException ex) {
326 System.out.println("IoTSlave: Error in unzipping file!");
327 ex.printStackTrace();
330 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
331 RuntimeOutput.print("IoTSlave: Receiving file transfer!", BOOL_VERBOSE);
335 * A private method to create a main object
339 private void createMainObject() throws IOException,
340 ClassNotFoundException, InstantiationException, IllegalAccessException,
341 InvocationTargetException {
343 // Translating into the actual Message class
344 MessageCreateMainObject sMessage = (MessageCreateMainObject) sIoTMasterMsg;
347 System.out.println("\n\nDEBUG: CREATE MAIN OBJECT!!!");
348 System.out.println("DEBUG: sMessage object name: " + sMessage.getObjectName());
350 // Getting controller class
351 File file = new File(STR_JAR_FILE_PATH + sMessage.getObjectName() + STR_JAR_FILE_EXT);
352 RuntimeOutput.print("IoTSlave: DEBUG print path: " + STR_JAR_FILE_PATH +
353 sMessage.getObjectName() + STR_JAR_FILE_EXT, BOOL_VERBOSE);
354 addURL(file.toURI().toURL());
355 // We will always have a package name <object name>.<object name>
356 // e.g. SmartLightsController.SmartLightsController
357 sMainObjectName = sMessage.getObjectName();
358 clsMain = Class.forName(sMainObjectName + "." + sMainObjectName);
359 objMainCls = clsMain.newInstance();
361 // Send back the received message as acknowledgement
362 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
363 RuntimeOutput.print("IoTSlave: Instantiating main controller/device class "
364 + sMessage.getObjectName(), BOOL_VERBOSE);
369 * A private method to create a new IoTSet
373 private void createNewIoTSet() throws IOException {
375 // Translating into the actual Message class
376 MessageCreateSetRelation sMessage = (MessageCreateSetRelation) sIoTMasterMsg;
379 System.out.println("\n\nDEBUG: CREATE NEW IOT SET!!!");
380 System.out.println("DEBUG: sMessage object field name: " + sMessage.getObjectFieldName());
382 // Initialize field name
383 strFieldName = sMessage.getObjectFieldName();
384 RuntimeOutput.print("IoTSlave: Setting up field " + strFieldName, BOOL_VERBOSE);
386 // Creating a new IoTSet object
387 isetObject = new ISet<Object>();
389 // Send back the received message as acknowledgement
390 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
391 RuntimeOutput.print("IoTSlave: Creating a new IoTSet object!", BOOL_VERBOSE);
396 * A private method to create a new IoTRelation
400 private void createNewIoTRelation() throws IOException {
402 // Translating into the actual Message class
403 MessageCreateSetRelation sMessage = (MessageCreateSetRelation) sIoTMasterMsg;
406 System.out.println("\n\nDEBUG: CREATE NEW IOT RELATION!!!");
407 System.out.println("DEBUG: sMessage object field name: " + sMessage.getObjectFieldName());
409 // Initialize field name
410 strFieldName = sMessage.getObjectFieldName();
411 RuntimeOutput.print("IoTSlave: Setting up field " + strFieldName, BOOL_VERBOSE);
413 // Creating a new IoTRelation object
414 irelObject = new IRelation<Object,Object>();
416 // Send back the received message as acknowledgement
417 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
418 RuntimeOutput.print("IoTSlave: Creating a new IoTRelation object!", BOOL_VERBOSE);
423 * A private method to get an object from the registry
427 private Object getObjectFromRegistry() throws RemoteException,
428 ClassNotFoundException, NotBoundException {
430 // Translating into the actual Message class
431 MessageGetObject sMessage = (MessageGetObject) sIoTMasterMsg;
433 // Locate RMI registry and add object into IoTSet
435 LocateRegistry.getRegistry(sMessage.getHostAddress(), sMessage.getRMIRegPort());
436 RuntimeOutput.print("IoTSlave: Looking for RMI registry: " +
437 sMessage.getHostAddress() + ":" + sMessage.getRMIRegPort() +
438 " with RMI stub port: " + sMessage.getRMIStubPort(), BOOL_VERBOSE);
439 Object stubObj = registry.lookup(sMessage.getObjectName());
440 RuntimeOutput.print("IoTSlave: Looking for object name: " + sMessage.getObjectName(), BOOL_VERBOSE);
442 // Class conversion to interface class of this class,
443 // e.g. ProximitySensorImpl has ProximitySensor interface
444 String strObjClassInterfaceName = STR_OBJ_CLS_PFX + "." + STR_INTERFACE_PFX + "." +
445 sMessage.getObjectInterfaceName();
446 Class<?> clsInf = Class.forName(strObjClassInterfaceName);
447 Object stubObjConv = clsInf.cast(stubObj);
453 * A private method to get an object and create a stub
455 * This is using the capability-based RMI skeleton and stub scheme
459 private Object getObjectFromStub() throws RemoteException,
460 ClassNotFoundException, NoSuchMethodException, InstantiationException,
461 IllegalAccessException, NotBoundException, InvocationTargetException, UnknownHostException {
463 // Translating into the actual Message class
464 MessageGetObject sMessage = (MessageGetObject) sIoTMasterMsg;
466 System.out.println("DEBUG: sMessage host address: " + sMessage.getHostAddress());
467 System.out.println("DEBUG: sMessage object class: " + sMessage.getObjectClass());
468 System.out.println("DEBUG: sMessage object name: " + sMessage.getObjectName());
469 System.out.println("DEBUG: sMessage interface name: " + sMessage.getObjectInterfaceName());
470 System.out.println("DEBUG: sMessage reg port: " + sMessage.getRMIRegPort());
471 System.out.println("DEBUG: sMessage stub port: " + sMessage.getRMIStubPort());
472 System.out.println("DEBUG: sMessage callback ports: " + Arrays.toString(sMessage.getRMICallbackPorts()));
473 System.out.println("\n\n");
475 Object stubObjConv = null;
476 String strObjectName = sMessage.getObjectName();
477 String strObjClassInterfaceName = STR_OBJ_CLS_PFX + "." + STR_INTERFACE_PFX + "." +
478 sMessage.getObjectStubInterfaceName();
479 Class<?> clsInf = Class.forName(strObjClassInterfaceName);
480 if (mapObjNameStub.containsKey(strObjectName)) {
481 RuntimeOutput.print("IoTSlave: Getting back object on slave: " + strObjectName, BOOL_VERBOSE);
482 stubObjConv = clsInf.cast(mapObjNameStub.get(strObjectName));
484 // Instantiate the stub and put in the object
485 String strObjStubName = sMainObjectName + "." + sMessage.getObjectStubInterfaceName() + STUB_CLASS_SUFFIX;
486 Class<?> clsStub = Class.forName(strObjStubName); // Port number is integer
487 Class[] clsStubParams = { int.class, String.class, String.class, int.class, int[].class };
488 Constructor<?> objStubCons = clsStub.getDeclaredConstructor(clsStubParams);
489 Integer[] portsInteger = sMessage.getRMICallbackPorts();
490 int[] ports = Arrays.stream(portsInteger).mapToInt(Integer::intValue).toArray();
493 String callbackAddress = InetAddress.getLocalHost().getHostAddress(); // Callback address is this machine's address
494 Object objStubParams[] = { sMessage.getRMIStubPort(), sMessage.getHostAddress(), callbackAddress,
496 RuntimeOutput.print("IoTSlave: Creating RMI stub: " +
497 sMessage.getHostAddress() + ":" + sMessage.getRMIRegPort() +
498 " with callback address: " + callbackAddress + " and RMI stub port: " + sMessage.getRMIStubPort(), BOOL_VERBOSE);
499 Object stubObj = objStubCons.newInstance(objStubParams);
500 // Class conversion to interface class of this class,
501 // e.g. ProximitySensorImpl has ProximitySensor interface
502 RuntimeOutput.print("IoTSlave: Registering new stub object: " + strObjectName, BOOL_VERBOSE);
503 mapObjNameStub.put(strObjectName, stubObj);
504 stubObjConv = clsInf.cast(stubObj);
511 * A private method to get an IoTSet object
515 private void getIoTSetObject() throws IOException,
516 ClassNotFoundException, RemoteException, NotBoundException, NoSuchMethodException,
517 InstantiationException, IllegalAccessException, InvocationTargetException {
520 System.out.println("\n\nDEBUG: GET IOT SET OBJECT!!!");
522 Object objRegistry = null;
524 objRegistry = getObjectFromStub();
526 objRegistry = getObjectFromRegistry();
527 isetObject.add(objRegistry);
528 RuntimeOutput.print("IoTSlave: This IoTSet now has: " + isetObject.size() + " entry(s)", BOOL_VERBOSE);
530 // Send back the received message as acknowledgement
531 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
532 RuntimeOutput.print("IoTSlave: Getting an object for IoTSet!", BOOL_VERBOSE);
536 * A private method to get an IoTRelation first object
540 private void getIoTRelationFirstObject() throws IOException,
541 ClassNotFoundException, RemoteException, NotBoundException, NoSuchMethodException,
542 InstantiationException, IllegalAccessException, InvocationTargetException {
545 System.out.println("\n\nDEBUG: GET IOT RELATION FIRST OBJECT!!!");
547 Object objRegistry = null;
549 objRegistry = getObjectFromStub();
551 objRegistry = getObjectFromRegistry();
552 iRelFirstObject = objRegistry;
554 // Send back the received message as acknowledgement
555 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
556 RuntimeOutput.print("IoTSlave: Getting a first object for IoTRelation!", BOOL_VERBOSE);
561 * A private method to get an IoTRelation second object
565 private void getIoTRelationSecondObject() throws IOException,
566 ClassNotFoundException, RemoteException, NotBoundException, NoSuchMethodException,
567 InstantiationException, IllegalAccessException, InvocationTargetException {
570 System.out.println("\n\nDEBUG: GET IOT RELATION SECOND OBJECT!!!");
572 Object objRegistry = null;
574 objRegistry = getObjectFromStub();
576 objRegistry = getObjectFromRegistry();
577 iRelSecondObject = objRegistry;
579 // Now add the first and the second object into IoTRelation
580 irelObject.put(iRelFirstObject, iRelSecondObject);
581 RuntimeOutput.print("IoTSlave: This IoTRelation now has: " + irelObject.size() + " entry(s)", BOOL_VERBOSE);
583 // Send back the received message as acknowledgement
584 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
585 RuntimeOutput.print("IoTSlave: Getting a second object for IoTRelation!", BOOL_VERBOSE);
590 * A private method to reinitialize IoTSet field
594 private void reinitializeIoTSetField() throws IOException,
595 IllegalAccessException, NoSuchFieldException {
597 // Reinitialize IoTSet field after getting all the objects
598 iotsetObject = new IoTSet<Object>(isetObject.values());
601 System.out.println("\n\nDEBUG: REINITIALIZE IOT SET FIELD!!!");
602 System.out.println("DEBUG: Field name: " + strFieldName + "\n\n");
604 // Private fields need getDeclaredField(), while public fields use getField()
605 Field fld = clsMain.getDeclaredField(strFieldName);
606 boolean bAccess = fld.isAccessible();
607 fld.setAccessible(true);
608 fld.set(objMainCls, iotsetObject);
609 fld.setAccessible(bAccess);
610 RuntimeOutput.print("IoTSlave: Reinitializing field " + strFieldName, BOOL_VERBOSE);
612 // Send back the received message as acknowledgement
613 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
614 RuntimeOutput.print("IoTSlave: Reinitializing IoTSet field!", BOOL_VERBOSE);
619 * A private method to reinitialize IoTRelation field
623 private void reinitializeIoTRelationField() throws IOException,
624 IllegalAccessException, NoSuchFieldException {
626 // Reinitialize IoTSet field after getting all the objects
627 iotrelObject = new IoTRelation<Object,Object>(irelObject.relationMap(), irelObject.size());
630 System.out.println("\n\nDEBUG: REINITIALIZE IOT RELATION FIELD!!!");
631 System.out.println("DEBUG: Field name: " + strFieldName + "\n\n");
633 // Private fields need getDeclaredField(), while public fields use getField()
634 Field fld = clsMain.getDeclaredField(strFieldName);
635 boolean bAccess = fld.isAccessible();
636 fld.setAccessible(true);
637 fld.set(objMainCls, iotrelObject);
638 fld.setAccessible(bAccess);
639 RuntimeOutput.print("IoTSlave: Reinitializing field " + strFieldName, BOOL_VERBOSE);
641 // Send back the received message as acknowledgement
642 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
643 RuntimeOutput.print("IoTSlave: Reinitializing IoTRelation field!", BOOL_VERBOSE);
648 * A private method to get the device driver object's IoTSet
650 * This is to handle device driver's IoTSet that contains IP addresses
654 private void getDeviceIoTSetObject() throws IOException {
656 // Translating into the actual Message class
657 MessageGetDeviceObject sMessage = (MessageGetDeviceObject) sIoTMasterMsg;
660 System.out.println("\n\nDEBUG: GET DEVICE IOT SET OBJECT!!!");
661 System.out.println("DEBUG: sMessage host address: " + sMessage.getHostAddress());
662 System.out.println("DEBUG: sMessage source port: " + sMessage.getSourceDeviceDriverPort());
663 System.out.println("DEBUG: sMessage destination port: " + sMessage.getDestinationDeviceDriverPort());
664 System.out.println("DEBUG: sMessage source wild card: " + sMessage.isSourcePortWildCard());
665 System.out.println("DEBUG: sMessage desination wild card: " + sMessage.isDestinationPortWildCard() + "\n\n");
667 // Get IoTSet objects for IP address set on device driver/controller
668 IoTDeviceAddress objDeviceAddress = new IoTDeviceAddress(sMessage.getHostAddress(),
669 sMessage.getSourceDeviceDriverPort(),
670 sMessage.getDestinationDeviceDriverPort(),
671 sMessage.isSourcePortWildCard(),
672 sMessage.isDestinationPortWildCard());
673 RuntimeOutput.print("IoTSlave: Device address transferred: " + sMessage.getHostAddress(), BOOL_VERBOSE);
674 isetObject.add(objDeviceAddress);
675 RuntimeOutput.print("IoTSlave: This IoTSet now has: " + isetObject.size() + " entry(s)", BOOL_VERBOSE);
677 // Send back the received message as acknowledgement
678 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
679 RuntimeOutput.print("IoTSlave: Getting an object for IoTSet!", BOOL_VERBOSE);
684 * A private method to get the device driver object's IoTSet for IoTZigbeeAddress
686 * This is to handle device driver's IoTSet that contains Zigbee addresses
690 private void getZBDevIoTSetObject() throws IOException {
692 // Translating into the actual Message class
693 MessageGetSimpleDeviceObject sMessage = (MessageGetSimpleDeviceObject) sIoTMasterMsg;
696 System.out.println("\n\nDEBUG: GET ZIGBEE DEVICE IOT SET OBJECT!!!");
697 System.out.println("DEBUG: sMessage host address: " + sMessage.getHostAddress());
698 System.out.println("DEBUG: sMessage source port: " + sMessage.getSourceDeviceDriverPort());
699 System.out.println("DEBUG: sMessage destination port: " + sMessage.getDestinationDeviceDriverPort());
700 System.out.println("DEBUG: sMessage source wild card: " + sMessage.isSourcePortWildCard());
701 System.out.println("DEBUG: sMessage desination wild card: " + sMessage.isDestinationPortWildCard() + "\n\n");
703 // Get IoTSet objects for IP address set on device driver/controller
704 IoTZigbeeAddress objZBDevAddress = new IoTZigbeeAddress(sMessage.getHostAddress());
705 RuntimeOutput.print("IoTSlave: Device address transferred: " + sMessage.getHostAddress(), BOOL_VERBOSE);
706 isetObject.add(objZBDevAddress);
707 RuntimeOutput.print("IoTSlave: This IoTSet now has: " + isetObject.size() + " entry(s)", BOOL_VERBOSE);
709 // Send back the received message as acknowledgement
710 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
711 RuntimeOutput.print("IoTSlave: Getting an object for IoTSet!", BOOL_VERBOSE);
717 * A private method to get IoTAddress objects for IoTSet
721 private void getAddIoTSetObject() throws IOException {
723 // Translating into the actual Message class
724 MessageGetSimpleDeviceObject sMessage = (MessageGetSimpleDeviceObject) sIoTMasterMsg;
727 System.out.println("\n\nDEBUG: GET ADD IOT SET OBJECT!!!");
728 System.out.println("DEBUG: sMessage host address: " + sMessage.getHostAddress() +);
730 // Get IoTSet objects for IP address set on device driver/controller
731 IoTAddress objAddress = new IoTAddress(sMessage.getHostAddress());
732 RuntimeOutput.print("IoTSlave: Address transferred: " + sMessage.getHostAddress(), BOOL_VERBOSE);
733 isetObject.add(objAddress);
734 RuntimeOutput.print("IoTSlave: This IoTSet now has: " + isetObject.size() + " entry(s)", BOOL_VERBOSE);
735 // Send back the received message as acknowledgement
736 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
737 RuntimeOutput.print("IoTSlave: Getting an object for IoTSet!", BOOL_VERBOSE);
742 * A private method to invoke init() method in the controller object
746 private void invokeInitMethod() throws IOException {
749 System.out.println("\n\nDEBUG: INVOKE INIT METHOD!!!");
754 Class<?> noparams[] = {};
755 Method method = clsMain.getDeclaredMethod("init", noparams);
756 method.invoke(objMainCls);
757 } catch (NoSuchMethodException |
758 IllegalAccessException |
759 InvocationTargetException ex) {
760 System.out.println("IoTSlave: Exception: "
762 ex.printStackTrace();
767 // Start a new thread to invoke the init function
768 RuntimeOutput.print("IoTSlave: Invoke init method! Job done!", BOOL_VERBOSE);
770 // Send back the received message as acknowledgement
771 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
776 * A public method to do communication with IoTMaster
778 * @params iIndex Integer index
781 public void commIoTMaster() {
785 // Loop, receive and process commands from IoTMaster
786 socket = new Socket(sIoTMasterHostAdd, iComPort);
787 outStream = new ObjectOutputStream(socket.getOutputStream());
788 inStream = new ObjectInputStream(socket.getInputStream());
792 // Get the first payload
793 RuntimeOutput.print("IoTSlave: Slave waiting...", BOOL_VERBOSE);
794 sIoTMasterMsg = (Message) inStream.readObject();
796 // Check payload message from IoTMaster and make a decision
797 switch (sIoTMasterMsg.getMessage()) {
807 case CREATE_MAIN_OBJECT:
811 case CREATE_NEW_IOTSET:
815 case CREATE_NEW_IOTRELATION:
816 createNewIoTRelation();
819 case GET_IOTSET_OBJECT:
823 case GET_IOTRELATION_FIRST_OBJECT:
824 getIoTRelationFirstObject();
827 case GET_IOTRELATION_SECOND_OBJECT:
828 getIoTRelationSecondObject();
831 case REINITIALIZE_IOTSET_FIELD:
832 reinitializeIoTSetField();
835 case REINITIALIZE_IOTRELATION_FIELD:
836 reinitializeIoTRelationField();
839 case GET_DEVICE_IOTSET_OBJECT:
840 getDeviceIoTSetObject();
843 case GET_ZB_DEV_IOTSET_OBJECT:
844 getZBDevIoTSetObject();
847 case GET_ADD_IOTSET_OBJECT:
848 getAddIoTSetObject();
851 case INVOKE_INIT_METHOD:
863 RuntimeOutput.print("IoTSlave: Session ends!", BOOL_VERBOSE);
865 // Closing streams and end session
869 RuntimeOutput.print("IoTSlave: Closing!", BOOL_VERBOSE);
870 // We have to continuously loop because we are preserving our stubs and skeletons
873 } catch (IOException |
874 ClassNotFoundException |
875 NoSuchMethodException |
876 InstantiationException |
877 AlreadyBoundException |
878 IllegalAccessException |
879 InvocationTargetException |
881 NoSuchFieldException ex) {
882 System.out.println("IoTSlave: Exception: "
884 ex.printStackTrace();
888 public static void main(String args[]) {
889 IoTSlave iotSlave = new IoTSlave(args);
890 iotSlave.parseIoTSlaveConfigFile();
891 iotSlave.commIoTMaster();