From f59c5789201487e4fc1101ee5f9c6c75d7918607 Mon Sep 17 00:00:00 2001 From: rtrimana Date: Thu, 15 Dec 2016 17:22:26 -0800 Subject: [PATCH] Porting and compiling SmartLightsController --- .../CameraCallback_CallbackSkeleton.java | 62 ++ .../CameraSmartCallback_CallbackStub.java | 88 +++ .../CameraSmartCallback_Stub.java | 87 +++ .../CameraSmart_CallbackStub.java | 184 ++++++ .../CameraSmart_Stub.java | 183 ++++++ .../Camera_CallbackSkeleton.java | 188 ++++++ .../ColorTemperature.java | 43 ++ .../LightBulbSmart_Stub.java | 184 ++++++ benchmarks/SmartLightsController/Makefile | 19 + .../MotionDetection.java | 463 +++++++++++++++ .../MotionDetectionCallback.java | 23 + .../SmartLightsController/RoomSmart_Stub.java | 36 ++ .../SmartLightsController.config | 1 + .../SmartLightsController.java | 417 ++++++++++++++ .../AmcrestCamera/AmcrestCamera.config | 4 + .../drivers/AmcrestCamera/AmcrestCamera.java | 537 ++++++++++++++++++ .../AmcrestCamera/Camera_Skeleton.java | 208 +++++++ benchmarks/drivers/LabRoom/LabRoom.config | 4 + benchmarks/drivers/LabRoom/LabRoom.java | 20 + benchmarks/drivers/LabRoom/Room_Skeleton.java | 63 ++ .../LifxLightBulb/LifxLightBulb.config | 2 + benchmarks/drivers/Makefile | 14 +- benchmarks/interfaces/Camera.java | 18 + benchmarks/interfaces/CameraCallback.java | 8 + benchmarks/interfaces/CameraSmart.java | 19 + .../interfaces/CameraSmartCallback.java | 9 + benchmarks/interfaces/LightBulbSmart.java | 26 + benchmarks/interfaces/Resolution.java | 8 + benchmarks/interfaces/Room.java | 5 + benchmarks/interfaces/RoomSmart.java | 6 + iotjava/Makefile | 14 +- iotjava/iotpolicy/IoTCompiler.java | 130 +++-- iotjava/iotrmi/Java/IoTRMICall.java | 47 -- iotjava/iotrmi/Java/IoTRMIObject.java | 13 - iotjava/iotrmi/Java/IoTRMIUtil.java | 199 ------- iotjava/iotruntime/slave/IoTSlave.java | 5 +- .../iotpolicy/AmcrestCamera/amcrestcamera.pol | 49 ++ .../AmcrestCamera/motiondetection.pol | 11 + .../AmcrestCamera/motiondetection.req | 3 + .../AmcrestCamera/smartlightscam.req | 3 + localconfig/iotpolicy/LabRoom/labroom.pol | 11 + localconfig/iotpolicy/LabRoom/roomsmart.req | 3 + .../LifxLightBulb/smartlightsbulb.req | 3 + 43 files changed, 3111 insertions(+), 309 deletions(-) create mode 100644 benchmarks/SmartLightsController/CameraCallback_CallbackSkeleton.java create mode 100644 benchmarks/SmartLightsController/CameraSmartCallback_CallbackStub.java create mode 100644 benchmarks/SmartLightsController/CameraSmartCallback_Stub.java create mode 100644 benchmarks/SmartLightsController/CameraSmart_CallbackStub.java create mode 100644 benchmarks/SmartLightsController/CameraSmart_Stub.java create mode 100644 benchmarks/SmartLightsController/Camera_CallbackSkeleton.java create mode 100644 benchmarks/SmartLightsController/ColorTemperature.java create mode 100644 benchmarks/SmartLightsController/LightBulbSmart_Stub.java create mode 100644 benchmarks/SmartLightsController/Makefile create mode 100644 benchmarks/SmartLightsController/MotionDetection.java create mode 100644 benchmarks/SmartLightsController/MotionDetectionCallback.java create mode 100644 benchmarks/SmartLightsController/RoomSmart_Stub.java create mode 100644 benchmarks/SmartLightsController/SmartLightsController.config create mode 100644 benchmarks/SmartLightsController/SmartLightsController.java create mode 100644 benchmarks/drivers/AmcrestCamera/AmcrestCamera.config create mode 100644 benchmarks/drivers/AmcrestCamera/AmcrestCamera.java create mode 100644 benchmarks/drivers/AmcrestCamera/Camera_Skeleton.java create mode 100644 benchmarks/drivers/LabRoom/LabRoom.config create mode 100644 benchmarks/drivers/LabRoom/LabRoom.java create mode 100644 benchmarks/drivers/LabRoom/Room_Skeleton.java create mode 100644 benchmarks/interfaces/Camera.java create mode 100644 benchmarks/interfaces/CameraCallback.java create mode 100644 benchmarks/interfaces/CameraSmart.java create mode 100644 benchmarks/interfaces/CameraSmartCallback.java create mode 100644 benchmarks/interfaces/LightBulbSmart.java create mode 100644 benchmarks/interfaces/Resolution.java create mode 100644 benchmarks/interfaces/Room.java create mode 100644 benchmarks/interfaces/RoomSmart.java create mode 100644 localconfig/iotpolicy/AmcrestCamera/amcrestcamera.pol create mode 100644 localconfig/iotpolicy/AmcrestCamera/motiondetection.pol create mode 100644 localconfig/iotpolicy/AmcrestCamera/motiondetection.req create mode 100644 localconfig/iotpolicy/AmcrestCamera/smartlightscam.req create mode 100644 localconfig/iotpolicy/LabRoom/labroom.pol create mode 100644 localconfig/iotpolicy/LabRoom/roomsmart.req create mode 100644 localconfig/iotpolicy/LifxLightBulb/smartlightsbulb.req diff --git a/benchmarks/SmartLightsController/CameraCallback_CallbackSkeleton.java b/benchmarks/SmartLightsController/CameraCallback_CallbackSkeleton.java new file mode 100644 index 0000000..913092a --- /dev/null +++ b/benchmarks/SmartLightsController/CameraCallback_CallbackSkeleton.java @@ -0,0 +1,62 @@ +package SmartLightsController; + +import java.io.IOException; +import java.util.List; +import java.util.ArrayList; +import java.util.Arrays; +import iotrmi.Java.IoTRMICall; +import iotrmi.Java.IoTRMIObject; + +import iotcode.interfaces.*; + +public class CameraCallback_CallbackSkeleton implements CameraCallback { + + private CameraCallback mainObj; + private int objectId = 0; + private String callbackAddress; + private static int objIdCnt = 0; + private IoTRMICall rmiCall; + private int[] ports; + + + + public CameraCallback_CallbackSkeleton(CameraCallback _mainObj, String _callbackAddress, int _objectId) throws Exception { + callbackAddress = _callbackAddress; + mainObj = _mainObj; + objectId = _objectId; + } + + public void newCameraFrameAvailable(CameraSmart _camera) { + mainObj.newCameraFrameAvailable(_camera); + } + + public void ___regCB(IoTRMIObject rmiObj) throws IOException { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { int[].class, String.class, int.class },new Class[] { null, null, null }); + ports = (int[]) paramObj[0]; + rmiCall = new IoTRMICall((int) paramObj[0], (String) paramObj[1], ports[1]); + } + + public void ___newCameraFrameAvailable(IoTRMIObject rmiObj) { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { int.class }, + new Class[] { null }); + try { + CameraSmart stub0 = new CameraSmart_CallbackStub(rmiCall, callbackAddress, objIdCnt, ports); + objIdCnt++; + newCameraFrameAvailable(stub0); + } catch(Exception ex) { + ex.printStackTrace(); + throw new Error("Exception from callback object instantiation!"); + } + } + + public void invokeMethod(IoTRMIObject rmiObj) throws IOException { + int methodId = rmiObj.getMethodId(); + switch (methodId) { + case 0: ___newCameraFrameAvailable(rmiObj); break; + case -9999: ___regCB(rmiObj); break; + default: + throw new Error("Method Id " + methodId + " not recognized!"); + } + } + +} diff --git a/benchmarks/SmartLightsController/CameraSmartCallback_CallbackStub.java b/benchmarks/SmartLightsController/CameraSmartCallback_CallbackStub.java new file mode 100644 index 0000000..851d631 --- /dev/null +++ b/benchmarks/SmartLightsController/CameraSmartCallback_CallbackStub.java @@ -0,0 +1,88 @@ +package SmartLightsController; + +import java.io.IOException; +import java.util.List; +import java.util.ArrayList; +import java.util.Arrays; +import iotrmi.Java.IoTRMICall; +import iotrmi.Java.IoTRMIObject; + +import iotcode.interfaces.*; + +public class CameraSmartCallback_CallbackStub implements CameraSmartCallback { + + private IoTRMICall rmiCall; + private String callbackAddress; + private int[] ports; + + private int objectId = 0; + // Callback properties + private IoTRMIObject rmiObj; + List listCallbackObj; + private static int objIdCnt = 0; + private final static int object0Id = 0; //CameraSmart + private static Integer[] object0Permission = { 8, 7, 9, 6, 2, 1, 4, 3, 0, 10, 5 }; + private static List set0Allowed; + + + public CameraSmartCallback_CallbackStub(IoTRMICall _rmiCall, String _callbackAddress, int _objectId, int[] _ports) throws Exception { + callbackAddress = _callbackAddress; + objectId = _objectId; + rmiCall = _rmiCall; + ports = _ports; + set0Allowed = new ArrayList(Arrays.asList(object0Permission)); + listCallbackObj = new ArrayList(); + ___initCallBack(); + } + + public void newCameraFrameAvailable(Camera _camera) { + try { + Camera_CallbackSkeleton skel0 = new Camera_CallbackSkeleton(_camera, callbackAddress, objIdCnt++); + listCallbackObj.add(skel0); + } catch (Exception ex) { + ex.printStackTrace(); + throw new Error("Exception when generating skeleton objects!"); + } + + int methodId = 0; + Class retType = void.class; + Class[] paramCls = new Class[] { int.class }; + Object[] paramObj = new Object[] { new Integer(1) }; + rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + } + + public void ___initCallBack() { + Thread thread = new Thread() { + public void run() { + try { + rmiObj = new IoTRMIObject(ports[1]); + while (true) { + byte[] method = rmiObj.getMethodBytes(); + int methodId = IoTRMIObject.getMethodId(method); + if (!set0Allowed.contains(methodId)) { + throw new Error("Callback object for Camera is not allowed to access method: " + methodId); + } + int objId = IoTRMIObject.getObjectId(method); + Camera_CallbackSkeleton skel = (Camera_CallbackSkeleton) listCallbackObj.get(objId); + if (skel != null) { + skel.invokeMethod(rmiObj); + } else { + throw new Error("Camera: Object with Id " + objId + " not found!"); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + throw new Error("Error instantiating class Camera_CallbackSkeleton!"); + } + } + }; + thread.start(); + + int methodId = -9999; + Class retType = void.class; + Class[] paramCls = new Class[] { int[].class, String.class, int.class }; + Object[] paramObj = new Object[] { ports, callbackAddress, 0 }; + rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + } + +} diff --git a/benchmarks/SmartLightsController/CameraSmartCallback_Stub.java b/benchmarks/SmartLightsController/CameraSmartCallback_Stub.java new file mode 100644 index 0000000..5c50b04 --- /dev/null +++ b/benchmarks/SmartLightsController/CameraSmartCallback_Stub.java @@ -0,0 +1,87 @@ +package SmartLightsController; + +import java.io.IOException; +import java.util.List; +import java.util.ArrayList; +import java.util.Arrays; +import iotrmi.Java.IoTRMICall; +import iotrmi.Java.IoTRMIObject; + +import iotcode.interfaces.*; + +public class CameraSmartCallback_Stub implements CameraSmartCallback { + + private IoTRMICall rmiCall; + private String callbackAddress; + private int[] ports; + + private final static int objectId = 0; + // Callback properties + private IoTRMIObject rmiObj; + List listCallbackObj; + private static int objIdCnt = 0; + private final static int object0Id = 0; //CameraSmart + private static Integer[] object0Permission = { 8, 7, 9, 6, 2, 1, 4, 3, 0, 10, 5 }; + private static List set0Allowed; + + + public CameraSmartCallback_Stub(int _port, String _skeletonAddress, String _callbackAddress, int _rev, int[] _ports) throws Exception { + callbackAddress = _callbackAddress; + ports = _ports; + rmiCall = new IoTRMICall(_port, _skeletonAddress, _rev); + set0Allowed = new ArrayList(Arrays.asList(object0Permission)); + listCallbackObj = new ArrayList(); + ___initCallBack(); + } + + public void newCameraFrameAvailable(Camera _camera) { + try { + Camera_CallbackSkeleton skel0 = new Camera_CallbackSkeleton(_camera, callbackAddress, objIdCnt++); + listCallbackObj.add(skel0); + } catch (Exception ex) { + ex.printStackTrace(); + throw new Error("Exception when generating skeleton objects!"); + } + + int methodId = 0; + Class retType = void.class; + Class[] paramCls = new Class[] { int.class }; + Object[] paramObj = new Object[] { new Integer(1) }; + rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + } + + public void ___initCallBack() { + Thread thread = new Thread() { + public void run() { + try { + rmiObj = new IoTRMIObject(ports[0]); + while (true) { + byte[] method = rmiObj.getMethodBytes(); + int methodId = IoTRMIObject.getMethodId(method); + if (!set0Allowed.contains(methodId)) { + throw new Error("Callback object for Camera is not allowed to access method: " + methodId); + } + int objId = IoTRMIObject.getObjectId(method); + Camera_CallbackSkeleton skel = (Camera_CallbackSkeleton) listCallbackObj.get(objId); + if (skel != null) { + skel.invokeMethod(rmiObj); + } else { + throw new Error("Camera: Object with Id " + objId + " not found!"); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + throw new Error("Error instantiating class Camera_CallbackSkeleton!"); + } + } + }; + thread.start(); + + int methodId = -9999; + Class retType = void.class; + Class[] paramCls = new Class[] { int[].class, String.class, int.class }; + Object[] paramObj = new Object[] { ports, callbackAddress, 0 }; + rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + } + +} diff --git a/benchmarks/SmartLightsController/CameraSmart_CallbackStub.java b/benchmarks/SmartLightsController/CameraSmart_CallbackStub.java new file mode 100644 index 0000000..a4819ac --- /dev/null +++ b/benchmarks/SmartLightsController/CameraSmart_CallbackStub.java @@ -0,0 +1,184 @@ +package SmartLightsController; + +import java.io.IOException; +import java.util.List; +import java.util.ArrayList; +import java.util.Arrays; +import iotrmi.Java.IoTRMICall; +import iotrmi.Java.IoTRMIObject; + +import iotcode.interfaces.*; + +public class CameraSmart_CallbackStub implements CameraSmart { + + private IoTRMICall rmiCall; + private String callbackAddress; + private int[] ports; + + private int objectId = 0; + // Callback properties + private IoTRMIObject rmiObj; + List listCallbackObj; + private static int objIdCnt = 0; + private final static int object0Id = 0; //CameraSmartCallback + private static Integer[] object0Permission = { 0 }; + private static List set0Allowed; + + + public CameraSmart_CallbackStub(IoTRMICall _rmiCall, String _callbackAddress, int _objectId, int[] _ports) throws Exception { + callbackAddress = _callbackAddress; + objectId = _objectId; + rmiCall = _rmiCall; + ports = _ports; + set0Allowed = new ArrayList(Arrays.asList(object0Permission)); + listCallbackObj = new ArrayList(); + ___initCallBack(); + } + + public int getMaxFPS() { + int methodId = 8; + Class retType = int.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (int)retObj; + } + + public boolean setFPS(int _fps) { + int methodId = 7; + Class retType = boolean.class; + Class[] paramCls = new Class[] { int.class }; + Object[] paramObj = new Object[] { _fps }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (boolean)retObj; + } + + public int getMinFPS() { + int methodId = 9; + Class retType = int.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (int)retObj; + } + + public boolean setResolution(Resolution _res) { + int methodId = 6; + Class retType = boolean.class; + int paramEnum0[] = new int[1]; + paramEnum0[0] = _res.ordinal(); + Class[] paramCls = new Class[] { int[].class }; + Object[] paramObj = new Object[] { paramEnum0 }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (boolean)retObj; + } + + public void stop() { + int methodId = 2; + Class retType = void.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + } + + public void start() { + int methodId = 1; + Class retType = void.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + } + + public long getTimestamp() { + int methodId = 4; + Class retType = long.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (long)retObj; + } + + public byte[] getLatestFrame() { + int methodId = 3; + Class retType = byte[].class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (byte[])retObj; + } + + public void init() { + int methodId = 0; + Class retType = void.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + } + + public void registerCallback(CameraCallback _callbackTo) { + try { + CameraCallback_CallbackSkeleton skel0 = new CameraCallback_CallbackSkeleton(_callbackTo, callbackAddress, objIdCnt++); + listCallbackObj.add(skel0); + } catch (Exception ex) { + ex.printStackTrace(); + throw new Error("Exception when generating skeleton objects!"); + } + + int methodId = 10; + Class retType = void.class; + Class[] paramCls = new Class[] { int.class }; + Object[] paramObj = new Object[] { new Integer(1) }; + rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + } + + public void ___initCallBack() { + Thread thread = new Thread() { + public void run() { + try { + rmiObj = new IoTRMIObject(ports[1]); + while (true) { + byte[] method = rmiObj.getMethodBytes(); + int methodId = IoTRMIObject.getMethodId(method); + if (!set0Allowed.contains(methodId)) { + throw new Error("Callback object for CameraCallback is not allowed to access method: " + methodId); + } + int objId = IoTRMIObject.getObjectId(method); + CameraCallback_CallbackSkeleton skel = (CameraCallback_CallbackSkeleton) listCallbackObj.get(objId); + if (skel != null) { + skel.invokeMethod(rmiObj); + } else { + throw new Error("CameraCallback: Object with Id " + objId + " not found!"); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + throw new Error("Error instantiating class CameraCallback_CallbackSkeleton!"); + } + } + }; + thread.start(); + + int methodId = -9998; + Class retType = void.class; + Class[] paramCls = new Class[] { int[].class, String.class, int.class }; + Object[] paramObj = new Object[] { ports, callbackAddress, 0 }; + rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + } + + public List getSupportedResolutions() { + int methodId = 5; + Class retType = int[].class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + int[] retEnum = (int[]) retObj; + Resolution[] enumVals = Resolution.values(); + int retLen = retEnum.length; + List enumRetVal = new ArrayList(); + for (int i = 0; i < retLen; i++) { + enumRetVal.add(enumVals[retEnum[i]]); + } + return enumRetVal; + } + +} diff --git a/benchmarks/SmartLightsController/CameraSmart_Stub.java b/benchmarks/SmartLightsController/CameraSmart_Stub.java new file mode 100644 index 0000000..e81b00c --- /dev/null +++ b/benchmarks/SmartLightsController/CameraSmart_Stub.java @@ -0,0 +1,183 @@ +package SmartLightsController; + +import java.io.IOException; +import java.util.List; +import java.util.ArrayList; +import java.util.Arrays; +import iotrmi.Java.IoTRMICall; +import iotrmi.Java.IoTRMIObject; + +import iotcode.interfaces.*; + +public class CameraSmart_Stub implements CameraSmart { + + private IoTRMICall rmiCall; + private String callbackAddress; + private int[] ports; + + private final static int objectId = 0; + // Callback properties + private IoTRMIObject rmiObj; + List listCallbackObj; + private static int objIdCnt = 0; + private final static int object0Id = 0; //CameraSmartCallback + private static Integer[] object0Permission = { 0 }; + private static List set0Allowed; + + + public CameraSmart_Stub(int _port, String _skeletonAddress, String _callbackAddress, int _rev, int[] _ports) throws Exception { + callbackAddress = _callbackAddress; + ports = _ports; + rmiCall = new IoTRMICall(_port, _skeletonAddress, _rev); + set0Allowed = new ArrayList(Arrays.asList(object0Permission)); + listCallbackObj = new ArrayList(); + ___initCallBack(); + } + + public int getMaxFPS() { + int methodId = 8; + Class retType = int.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (int)retObj; + } + + public boolean setFPS(int _fps) { + int methodId = 7; + Class retType = boolean.class; + Class[] paramCls = new Class[] { int.class }; + Object[] paramObj = new Object[] { _fps }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (boolean)retObj; + } + + public int getMinFPS() { + int methodId = 9; + Class retType = int.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (int)retObj; + } + + public boolean setResolution(Resolution _res) { + int methodId = 6; + Class retType = boolean.class; + int paramEnum0[] = new int[1]; + paramEnum0[0] = _res.ordinal(); + Class[] paramCls = new Class[] { int[].class }; + Object[] paramObj = new Object[] { paramEnum0 }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (boolean)retObj; + } + + public void stop() { + int methodId = 2; + Class retType = void.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + } + + public void start() { + int methodId = 1; + Class retType = void.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + } + + public long getTimestamp() { + int methodId = 4; + Class retType = long.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (long)retObj; + } + + public byte[] getLatestFrame() { + int methodId = 3; + Class retType = byte[].class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (byte[])retObj; + } + + public void init() { + int methodId = 0; + Class retType = void.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + } + + public void registerCallback(CameraCallback _callbackTo) { + try { + CameraCallback_CallbackSkeleton skel0 = new CameraCallback_CallbackSkeleton(_callbackTo, callbackAddress, objIdCnt++); + listCallbackObj.add(skel0); + } catch (Exception ex) { + ex.printStackTrace(); + throw new Error("Exception when generating skeleton objects!"); + } + + int methodId = 10; + Class retType = void.class; + Class[] paramCls = new Class[] { int.class }; + Object[] paramObj = new Object[] { new Integer(1) }; + rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + } + + public void ___initCallBack() { + Thread thread = new Thread() { + public void run() { + try { + rmiObj = new IoTRMIObject(ports[0]); + while (true) { + byte[] method = rmiObj.getMethodBytes(); + int methodId = IoTRMIObject.getMethodId(method); + if (!set0Allowed.contains(methodId)) { + throw new Error("Callback object for CameraCallback is not allowed to access method: " + methodId); + } + int objId = IoTRMIObject.getObjectId(method); + CameraCallback_CallbackSkeleton skel = (CameraCallback_CallbackSkeleton) listCallbackObj.get(objId); + if (skel != null) { + skel.invokeMethod(rmiObj); + } else { + throw new Error("CameraCallback: Object with Id " + objId + " not found!"); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + throw new Error("Error instantiating class CameraCallback_CallbackSkeleton!"); + } + } + }; + thread.start(); + + int methodId = -9998; + Class retType = void.class; + Class[] paramCls = new Class[] { int[].class, String.class, int.class }; + Object[] paramObj = new Object[] { ports, callbackAddress, 0 }; + rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + } + + public List getSupportedResolutions() { + int methodId = 5; + Class retType = int[].class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + int[] retEnum = (int[]) retObj; + Resolution[] enumVals = Resolution.values(); + int retLen = retEnum.length; + List enumRetVal = new ArrayList(); + for (int i = 0; i < retLen; i++) { + enumRetVal.add(enumVals[retEnum[i]]); + } + return enumRetVal; + } + +} diff --git a/benchmarks/SmartLightsController/Camera_CallbackSkeleton.java b/benchmarks/SmartLightsController/Camera_CallbackSkeleton.java new file mode 100644 index 0000000..6a6f429 --- /dev/null +++ b/benchmarks/SmartLightsController/Camera_CallbackSkeleton.java @@ -0,0 +1,188 @@ +package SmartLightsController; + +import java.io.IOException; +import java.util.List; +import java.util.ArrayList; +import java.util.Arrays; +import iotrmi.Java.IoTRMICall; +import iotrmi.Java.IoTRMIObject; + +import iotcode.interfaces.*; + +public class Camera_CallbackSkeleton implements Camera { + + private Camera mainObj; + private int objectId = 0; + private String callbackAddress; + private static int objIdCnt = 0; + private IoTRMICall rmiCall; + private int[] ports; + + + + public Camera_CallbackSkeleton(Camera _mainObj, String _callbackAddress, int _objectId) throws Exception { + callbackAddress = _callbackAddress; + mainObj = _mainObj; + objectId = _objectId; + } + + public void init() { + mainObj.init(); + } + + public void start() { + mainObj.start(); + } + + public void stop() { + mainObj.stop(); + } + + public byte[] getLatestFrame() { + return mainObj.getLatestFrame(); + } + + public long getTimestamp() { + return mainObj.getTimestamp(); + } + + public List getSupportedResolutions() { + return mainObj.getSupportedResolutions(); + } + + public boolean setResolution(Resolution _res) { + return mainObj.setResolution(_res); + } + + public boolean setFPS(int _fps) { + return mainObj.setFPS(_fps); + } + + public int getMaxFPS() { + return mainObj.getMaxFPS(); + } + + public int getMinFPS() { + return mainObj.getMinFPS(); + } + + public void registerCallback(CameraSmartCallback _callbackTo) { + mainObj.registerCallback(_callbackTo); + } + + public void ___regCB(IoTRMIObject rmiObj) throws IOException { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { int[].class, String.class, int.class },new Class[] { null, null, null }); + ports = (int[]) paramObj[0]; + rmiCall = new IoTRMICall((int) paramObj[0], (String) paramObj[1], ports[1]); + } + + public void ___init(IoTRMIObject rmiObj) { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { }, + new Class[] { }); + init(); + } + + public void ___start(IoTRMIObject rmiObj) { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { }, + new Class[] { }); + start(); + } + + public void ___stop(IoTRMIObject rmiObj) { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { }, + new Class[] { }); + stop(); + } + + public void ___getLatestFrame(IoTRMIObject rmiObj) throws IOException { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { }, + new Class[] { }); + Object retObj = getLatestFrame(); + rmiObj.sendReturnObj(retObj); + } + + public void ___getTimestamp(IoTRMIObject rmiObj) throws IOException { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { }, + new Class[] { }); + Object retObj = getTimestamp(); + rmiObj.sendReturnObj(retObj); + } + + public void ___getSupportedResolutions(IoTRMIObject rmiObj) throws IOException { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { }, + new Class[] { }); + List retEnum = getSupportedResolutions(); + int retLen = retEnum.size(); + int[] retEnumVal = new int[retLen]; + for (int i = 0; i < retLen; i++) { + retEnumVal[i] = retEnum.get(i).ordinal(); + } + Object retObj = retEnumVal; + rmiObj.sendReturnObj(retObj); + } + + public void ___setResolution(IoTRMIObject rmiObj) throws IOException { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { int[].class }, + new Class[] { null }); + int paramInt0[] = (int[]) paramObj[0]; + Resolution[] enumVals = Resolution.values(); + Resolution paramEnum0 = enumVals[paramInt0[0]]; + Object retObj = setResolution(paramEnum0); + rmiObj.sendReturnObj(retObj); + } + + public void ___setFPS(IoTRMIObject rmiObj) throws IOException { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { int.class }, + new Class[] { null }); + Object retObj = setFPS((int) paramObj[0]); + rmiObj.sendReturnObj(retObj); + } + + public void ___getMaxFPS(IoTRMIObject rmiObj) throws IOException { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { }, + new Class[] { }); + Object retObj = getMaxFPS(); + rmiObj.sendReturnObj(retObj); + } + + public void ___getMinFPS(IoTRMIObject rmiObj) throws IOException { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { }, + new Class[] { }); + Object retObj = getMinFPS(); + rmiObj.sendReturnObj(retObj); + } + + public void ___registerCallback(IoTRMIObject rmiObj) { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { int.class }, + new Class[] { null }); + try { + CameraSmartCallback stub0 = new CameraSmartCallback_CallbackStub(rmiCall, callbackAddress, objIdCnt, ports); + objIdCnt++; + registerCallback(stub0); + } catch(Exception ex) { + ex.printStackTrace(); + throw new Error("Exception from callback object instantiation!"); + } + } + + public void invokeMethod(IoTRMIObject rmiObj) throws IOException { + int methodId = rmiObj.getMethodId(); + switch (methodId) { + case 0: ___init(rmiObj); break; + case 1: ___start(rmiObj); break; + case 2: ___stop(rmiObj); break; + case 3: ___getLatestFrame(rmiObj); break; + case 4: ___getTimestamp(rmiObj); break; + case 5: ___getSupportedResolutions(rmiObj); break; + case 6: ___setResolution(rmiObj); break; + case 7: ___setFPS(rmiObj); break; + case 8: ___getMaxFPS(rmiObj); break; + case 9: ___getMinFPS(rmiObj); break; + case 10: ___registerCallback(rmiObj); break; + case -9998: ___regCB(rmiObj); break; + default: + throw new Error("Method Id " + methodId + " not recognized!"); + } + } + +} diff --git a/benchmarks/SmartLightsController/ColorTemperature.java b/benchmarks/SmartLightsController/ColorTemperature.java new file mode 100644 index 0000000..cc6f1b9 --- /dev/null +++ b/benchmarks/SmartLightsController/ColorTemperature.java @@ -0,0 +1,43 @@ +package SmartLightsController; + +/** Class ColorTemperature to store the color and temperature data. + * + * + * @author Ali Younis + * @version 1.0 + * @since 2016-01-27 + */ +public class ColorTemperature { + + // As a percentage + public double hue; + public double saturation; + public double brightness; + + // In Kelvin + public int temperature; + + /** Constructor + */ + public ColorTemperature() { + this.hue = 0; + this.saturation = 0; + this.brightness = 0; + this.temperature = 0; + } + + /** Constructor + * + * @param _hue [double], Hue as a percentage. + * @param _saturation [double], Saturation as a percentage. + * @param _brightness [double], Brightness as a percentage. + * @param _temperature [double], Temperature as kelvin. + * + */ + public ColorTemperature(double _hue, double _saturation, double _brightness, int _temperature) { + this.hue = _hue; + this.saturation = _saturation; + this.brightness = _brightness; + this.temperature = _temperature; + } +} diff --git a/benchmarks/SmartLightsController/LightBulbSmart_Stub.java b/benchmarks/SmartLightsController/LightBulbSmart_Stub.java new file mode 100644 index 0000000..3e93190 --- /dev/null +++ b/benchmarks/SmartLightsController/LightBulbSmart_Stub.java @@ -0,0 +1,184 @@ +package SmartLightsController; + +import java.io.IOException; +import java.util.List; +import java.util.ArrayList; +import java.util.Arrays; +import iotrmi.Java.IoTRMICall; +import iotrmi.Java.IoTRMIObject; + +import iotcode.interfaces.LightBulbSmart; + +public class LightBulbSmart_Stub implements LightBulbSmart { + + private IoTRMICall rmiCall; + private String callbackAddress; + private int[] ports; + + private final static int objectId = 0; + + + public LightBulbSmart_Stub(int _port, String _skeletonAddress, String _callbackAddress, int _rev, int[] _ports) throws Exception { + callbackAddress = _callbackAddress; + ports = _ports; + rmiCall = new IoTRMICall(_port, _skeletonAddress, _rev); + } + + public void turnOn() { + int methodId = 2; + Class retType = void.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + } + + public double getBrightnessRangeLowerBound() { + int methodId = 10; + Class retType = double.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (double)retObj; + } + + public void turnOff() { + int methodId = 1; + Class retType = void.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + } + + public boolean getState() { + int methodId = 3; + Class retType = boolean.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (boolean)retObj; + } + + public double getBrightnessRangeUpperBound() { + int methodId = 11; + Class retType = double.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (double)retObj; + } + + public double getSaturation() { + int methodId = 8; + Class retType = double.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (double)retObj; + } + + public double getHueRangeLowerBound() { + int methodId = 12; + Class retType = double.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (double)retObj; + } + + public double getHue() { + int methodId = 7; + Class retType = double.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (double)retObj; + } + + public double getHueRangeUpperBound() { + int methodId = 13; + Class retType = double.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (double)retObj; + } + + public int getTemperature() { + int methodId = 9; + Class retType = int.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (int)retObj; + } + + public double getBrightness() { + int methodId = 6; + Class retType = double.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (double)retObj; + } + + public int getTemperatureRangeLowerBound() { + int methodId = 16; + Class retType = int.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (int)retObj; + } + + public int getTemperatureRangeUpperBound() { + int methodId = 17; + Class retType = int.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (int)retObj; + } + + public void setColor(double _hue, double _saturation, double _brightness) { + int methodId = 4; + Class retType = void.class; + Class[] paramCls = new Class[] { double.class, double.class, double.class }; + Object[] paramObj = new Object[] { _hue, _saturation, _brightness }; + rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + } + + public void init() { + int methodId = 0; + Class retType = void.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + } + + public double getSaturationRangeLowerBound() { + int methodId = 14; + Class retType = double.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (double)retObj; + } + + public double getSaturationRangeUpperBound() { + int methodId = 15; + Class retType = double.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (double)retObj; + } + + public void setTemperature(int _temperature) { + int methodId = 5; + Class retType = void.class; + Class[] paramCls = new Class[] { int.class }; + Object[] paramObj = new Object[] { _temperature }; + rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + } + +} diff --git a/benchmarks/SmartLightsController/Makefile b/benchmarks/SmartLightsController/Makefile new file mode 100644 index 0000000..cdbb18d --- /dev/null +++ b/benchmarks/SmartLightsController/Makefile @@ -0,0 +1,19 @@ +BASE = ../.. + +include $(BASE)/common.mk + +BOOFDIR := ../libs/boofcv_libs +BOOFJARS := $(BOOFDIR)/BoofCV-feature-0.21.jar:$(BOOFDIR)/BoofCV-io-0.21.jar:$(BOOFDIR)/BoofCV-visualize-0.21.jar:$(BOOFDIR)/BoofCV-ip-0.21.jar:$(CHECKERJARS) + +JFLAGS = -d $(BIN_DIR) -cp $(BOOFJARS):$(BIN_DIR):. +JARFLAGS = cf + +all: smartlights + +PHONY += smartlights +smartlights: + $(JAVAC) $(JFLAGS) *.java + cp SmartLightsController.config $(BIN_DIR)/SmartLightsController + cd $(BIN_DIR)/SmartLightsController; $(JAR) $(JARFLAGS) SmartLightsController.jar ../SmartLightsController/SmartLightsController*.class ../SmartLightsController/ColorTemperature*.class ../SmartLightsController/MotionDetection*.class ../iotcode/interfaces/Camera*.class ../iotcode/interfaces/Room*.class ../iotcode/interfaces/LightBulb*.class + +.PHONY: $(PHONY) diff --git a/benchmarks/SmartLightsController/MotionDetection.java b/benchmarks/SmartLightsController/MotionDetection.java new file mode 100644 index 0000000..b683327 --- /dev/null +++ b/benchmarks/SmartLightsController/MotionDetection.java @@ -0,0 +1,463 @@ +package SmartLightsController; + +// IoT packages +import iotcode.annotation.*; +import iotcode.interfaces.*; + +// BoofCv packages +import boofcv.alg.background.BackgroundModelStationary; +import boofcv.factory.background.ConfigBackgroundGaussian; +import boofcv.factory.background.FactoryBackgroundModel; +import boofcv.gui.binary.VisualizeBinaryData; +import boofcv.gui.image.ImageGridPanel; +import boofcv.gui.image.ShowImages; +import boofcv.io.MediaManager; +import boofcv.io.UtilIO; +import boofcv.io.image.SimpleImageSequence; +import boofcv.io.image.ConvertBufferedImage; +import boofcv.io.wrapper.DefaultMediaManager; +import boofcv.struct.image.ImageBase; +import boofcv.struct.image.ImageFloat32; +import boofcv.struct.image.ImageType; +import boofcv.struct.image.ImageUInt8; +import boofcv.alg.filter.blur.BlurImageOps; + + +// Standard Java Packages +import java.awt.image.BufferedImage; +import java.util.Date; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.concurrent.atomic.AtomicBoolean; +import java.awt.image.ColorModel; +import java.awt.image.WritableRaster; +import java.util.List; +import java.util.ArrayList; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import javax.imageio.ImageIO; + +// RMI Packages +import java.rmi.RemoteException; + +// For testing +import java.net.*; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +import java.util.Iterator; + +// Checker annotations +//import iotchecker.qual.*; + +/** Class MotionDetection to do motion detection using images + * + * + * @author Ali Younis + * @version 1.0 + * @since 2016-03-21 + */ +class MotionDetection implements CameraCallback { + + // Define Like variables + private static boolean DO_GRAPHICAL_USER_INTERFACE = false; + + /******************************************************************************************************************************************* + ** + ** Constants + ** + *******************************************************************************************************************************************/ + private final float MOTION_DETECTED_THRESHOLD_PERCENTAGE = 15; + + + /******************************************************************************************************************************************* + ** + ** Variables + ** + *******************************************************************************************************************************************/ + + // Timestamp buffer and locks needed for that safety on that buffer + // This is the buffer for post-detection algorithm use + private Date timestampOfLastMotion = null; + private ReadWriteLock timestampReadWriteLock = new ReentrantReadWriteLock(); + private Lock timestampReadLock = timestampReadWriteLock.readLock(); + private Lock timestampWriteLock = timestampReadWriteLock.writeLock(); + + // Flag for when new data is available and ready for processing + private AtomicBoolean newFrameAvailable = new AtomicBoolean(false); + + // Flag for determining if motion has been detected and therefore + // the callbacks should be issued + private AtomicBoolean motionDetected = new AtomicBoolean(false); + + // Image and timestamp buffers and locks needed for that safety on those buffers + // Timestamp buffer for pre-detection algorithm use + private BufferedImage latestImage = null; + private Date possibleDate = null; + private ReadWriteLock imageReadWriteLock = new ReentrantReadWriteLock(); + private Lock imageReadLock = imageReadWriteLock.readLock(); + private Lock imageWriteLock = imageReadWriteLock.writeLock(); + + // List of objects wishing to receive callbacks from this class. + private List + callbackList = new ArrayList(); + + // Variables to help with motion detection + private ConfigBackgroundGaussian configGaussian = null; + private BackgroundModelStationary backgroundDetector = null; + private ImageUInt8 segmented = null; + private ImageFloat32 newFrameFloat = null; + + // counts the number of frames since a background image is added to algorithm + private int frameCounter = 0; + + + + /******************************************************************************************************************************************* + ** + ** Threads + ** + *******************************************************************************************************************************************/ + private Thread workThread = null; + private Thread callBackThread = null; + + /******************************************************************************************************************************************* + ** + ** GUI Stuff (Used Only for Testing) + ** + *******************************************************************************************************************************************/ + ImageGridPanel gui; + + /** Constructor + * + * @param _threshold [float], Variable for gaussian background detector. + * @param _learnSpeed [float], Variable for gaussian background detector. + * @param _initialVariance [float], Variable for gaussian background detector. + * @param _minDifference [float], Variable for gaussian background detector. + * + */ + public MotionDetection(float _threshold, float _learnSpeed, float _initialVariance, float _minDifference) + throws RemoteException { + + // Configure the Gaussian model used for background detection + configGaussian = new ConfigBackgroundGaussian(_threshold, _learnSpeed); + configGaussian.initialVariance = _initialVariance; + configGaussian.minimumDifference = _minDifference; + + // setup the background detector + ImageType imageType = ImageType.single(ImageFloat32.class); + backgroundDetector = FactoryBackgroundModel.stationaryGaussian(configGaussian, imageType); + + // setup the gui if we are going to use it + if (DO_GRAPHICAL_USER_INTERFACE) { + + // create an image grid for images to place on, tile fashion + gui = new ImageGridPanel(1, 2); + + // make the window large so we dont have to manually resize with the mouse + gui.setSize(1920, 1080); + + // Make the window visible and set the title + ShowImages.showWindow(gui, "Static Scene: Background Segmentation", true); + } + + // Launch the worker thread + workThread = new Thread(new Runnable() { + public void run() { + + while (true) { + runMotionDetection(); + } + } + }); + workThread.start(); + + + // Launch the callback thread + callBackThread = new Thread(new Runnable() { + public void run() { + + while (true) { + doCallbacks(); + } + } + }); + callBackThread.start(); + } + + + /******************************************************************************************************************************************* + ** + ** Public Methods + ** + *******************************************************************************************************************************************/ + + /** Method to add a new frame to the motion detector. + * + * @param _newFrame [byte[]], Frame data of new frame. + * @param _timestamp [Date] , Timestamp of new frame. + * + * @return [void] None. + */ + public void addFrame(byte[] _newFrame, Date _timestamp) { + BufferedImage img = null; + + try { + // Parse the byte array into a Buffered Image + InputStream in = new ByteArrayInputStream(_newFrame); + img = ImageIO.read(in); + + } catch (Exception e) { + e.printStackTrace(); + return; + } + + // Save the image and timestamp for use later + imageWriteLock.lock();// lock the image and timestamp buffers since multithread + latestImage = img;// image into image buffer + possibleDate = _timestamp;// timestamp into timestamp buffer + imageWriteLock.unlock();// Never forget to unlock + + // flag the worker thread that there is new data ready for processing + newFrameAvailable.set(true); + } + + /** Method to get the timestamp of the last time motion was detected + * + * @return [Date] timestamp of last motion or null if no motion was ever detected. + */ + public Date getTimestampOfLastMotion() { + Date ret = null; + + // Be safe because multithread + timestampReadLock.lock(); + + // Checks if there was ever motion, if not then timestampOfLastMotion + // will be null + if (timestampOfLastMotion != null) { + // Clone since we don't know what the other person is going to do + // with the timestamp + ret = (Date)timestampOfLastMotion.clone(); + } + + timestampReadLock.unlock(); + + return ret; + } + + + /** Method to add a new frame to the motion detector from a camera + * + * @param _camera [Camera], Camera that has the new data. + * + * @return [void] None. + */ + public void newCameraFrameAvailable(CameraSmart _camera) { + BufferedImage img = null; + + try { + // Parse the byte array into a Buffered Image + InputStream in = new ByteArrayInputStream(_camera.getLatestFrame()); + img = ImageIO.read(in); + + } catch (RemoteException e) { + e.printStackTrace(); + return; + + } catch (Exception e) { + e.printStackTrace(); + return; + + } + + // Save the image and timestamp for use later + imageWriteLock.lock(); // lock the image and timestamp buffers since multithread + latestImage = img; // image into image buffer + + // timestamp from camera into timestamo buffer + long dateLong = _camera.getTimestamp(); + possibleDate = new Date(dateLong); + + imageWriteLock.unlock(); // Never forget to unlock + + // flag the worker thread that there is new data ready for processing + newFrameAvailable.set(true); + } + + /** Method to register an object to recieve callbacks from this motion detector + * + * @param _mdc [MotionDetectionCallback], object to recieve callbacks. + * + * @return [void] None. + */ + public void registerCallback(MotionDetectionCallback _mdc) { + callbackList.add(_mdc); + } + + /******************************************************************************************************************************************* + ** + ** Helper Methods + ** + *******************************************************************************************************************************************/ + + /** Method that constantly loops checking if new data is available. If there is + * new data, it is processed. + * This method should be run on a separate thread. + * + * @return [void] None. + */ + private void runMotionDetection() { + + // check if there is a new frame availble, only runs detection if there is new data to save + // computation time + if (!newFrameAvailable.get()) { + return; + } + + // Lock since we are accessing the data buffers + imageReadLock.lock(); + + // processing data so now the buffered data is old + newFrameAvailable.set(false); + + // copy from buffer to local for processing + Date tmpDate = possibleDate; + + // Allocate space for the segmented image based on the first image we received + // cannot pre-allocate this since we do not know what the size of the images is + // before the first image arrives + if (segmented == null) { + segmented = new ImageUInt8(latestImage.getWidth(), latestImage.getHeight()); + } + + // copy from data buffers and convert into correct data type for BoofCv libraries + newFrameFloat = ConvertBufferedImage.convertFrom(latestImage, newFrameFloat); + + // All done accessing the data buffers + imageReadLock.unlock(); + + // Run background detection + backgroundDetector.segment(newFrameFloat, segmented); + + // Update the background baseline every 10 frames, helps the algorithm + frameCounter++; + if (frameCounter > 10) { + backgroundDetector.updateBackground(newFrameFloat); + frameCounter = 0; + } + + // get the raw pixel data, gray-scale image + byte[] frameData = segmented.getData(); + + // count the number of pixels of the image that was deemed as "motion" + double count = 0; + double countMotion = 0; + for (byte b : frameData) { + count++; + if (b > 0) { + countMotion++; + } + } + + // calculate the percentage of the image that was in motion + double percentMotion = (countMotion / count) * 100.0; + + // Check if a high enough percentage of the image was in motion to say that there was motion in this frame of data + if (percentMotion > MOTION_DETECTED_THRESHOLD_PERCENTAGE) { + + // Motion detected so save timestamp of this frame to another buffer + timestampWriteLock.lock(); + timestampOfLastMotion = (Date)tmpDate.clone(); // clone to a different buffer + timestampWriteLock.unlock(); + + System.out.println("Motion Detected (with percentage: " + Double.toString(percentMotion) + "%)"); + } + + // Do output to the screen if we are using gui mode + if (DO_GRAPHICAL_USER_INTERFACE) { + + // change image data unto correct type for rendering + BufferedImage visualized1 = new BufferedImage(segmented.width, segmented.height, BufferedImage.TYPE_INT_RGB); + VisualizeBinaryData.renderBinary(segmented, false, visualized1); + + // change image data unto correct type for rendering + BufferedImage visualized2 = null; + visualized2 = ConvertBufferedImage.convertTo(newFrameFloat, visualized2, true); + + // place the images into the image grid + gui.setImage(0, 1, visualized1); + gui.setImage(0, 2, visualized2); + + // trigger rendering + gui.repaint(); + } + } + + /** Method that constantly loops checking if the callbacks should be issues and + * issues the callbacks if they should be issues. + * This method should be run on a separate thread. + * + * @return [void] None. + */ + private void doCallbacks() { + + // Keep looping forever for callback + while (true) { + + // If motion detected + if (motionDetected.compareAndSet(true, false)) { + + // Motion was detected so issue callbacks to all objects that registered + // to receive callback from this class. + for (MotionDetectionCallback c : callbackList) { + try { + c.motionDetected(this); + } catch (RemoteException re) { + } + } + + } else { + + // Sleep for 15 millisec to give time for new frame to arrive + try { + Thread.sleep(15); + } catch (InterruptedException ie) { + } + } + } + } + + + + + // /******************************************************************************************************************************************* + // ** Main Method used for testing + // *******************************************************************************************************************************************/ + // public static void main(String[] args) { + // MotionDetection mo = new MotionDetection(12, 0.5f, 10, 10); + + // AmcrestCamera cam = null; + // try { + + // InetAddress addr = InetAddress.getByName("192.168.1.29"); + // cam = new AmcrestCamera(addr, "admin", "55779CatSoundz32"); + // cam.registerCallback(mo); + // cam.start(); + // // cam.streamDisconnect(); + + // } catch (Exception e) { + + // } + + // while (true) { + + // } + + // } +} + diff --git a/benchmarks/SmartLightsController/MotionDetectionCallback.java b/benchmarks/SmartLightsController/MotionDetectionCallback.java new file mode 100644 index 0000000..5517abc --- /dev/null +++ b/benchmarks/SmartLightsController/MotionDetectionCallback.java @@ -0,0 +1,23 @@ +package SmartLightsController; + +/** Interface MotionDetectionCallback for allowing callbacks from the MotionDetection class. + * + * + * @author Ali Younis + * @version 1.0 + * @since 2016-03-21 + */ + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface MotionDetectionCallback extends Remote { + + /** Callback method for when motion is detected. + * + * @param _md [MotionDetection]. + * + * @return [void] None. + */ + public void motionDetected(MotionDetection _md) throws RemoteException; +} diff --git a/benchmarks/SmartLightsController/RoomSmart_Stub.java b/benchmarks/SmartLightsController/RoomSmart_Stub.java new file mode 100644 index 0000000..71bcc3f --- /dev/null +++ b/benchmarks/SmartLightsController/RoomSmart_Stub.java @@ -0,0 +1,36 @@ +package SmartLightsController; + +import java.io.IOException; +import java.util.List; +import java.util.ArrayList; +import java.util.Arrays; +import iotrmi.Java.IoTRMICall; +import iotrmi.Java.IoTRMIObject; + +import iotcode.interfaces.RoomSmart; + +public class RoomSmart_Stub implements RoomSmart { + + private IoTRMICall rmiCall; + private String callbackAddress; + private int[] ports; + + private final static int objectId = 0; + + + public RoomSmart_Stub(int _port, String _skeletonAddress, String _callbackAddress, int _rev, int[] _ports) throws Exception { + callbackAddress = _callbackAddress; + ports = _ports; + rmiCall = new IoTRMICall(_port, _skeletonAddress, _rev); + } + + public int getRoomID() { + int methodId = 0; + Class retType = int.class; + Class[] paramCls = new Class[] { }; + Object[] paramObj = new Object[] { }; + Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj); + return (int)retObj; + } + +} diff --git a/benchmarks/SmartLightsController/SmartLightsController.config b/benchmarks/SmartLightsController/SmartLightsController.config new file mode 100644 index 0000000..5a44766 --- /dev/null +++ b/benchmarks/SmartLightsController/SmartLightsController.config @@ -0,0 +1 @@ +ADDITIONAL_ZIP_FILE=No diff --git a/benchmarks/SmartLightsController/SmartLightsController.java b/benchmarks/SmartLightsController/SmartLightsController.java new file mode 100644 index 0000000..f073df8 --- /dev/null +++ b/benchmarks/SmartLightsController/SmartLightsController.java @@ -0,0 +1,417 @@ +package SmartLightsController; + +// IoT Runtime packages +import iotruntime.slave.IoTSet; +import iotruntime.slave.IoTRelation; + +// IoT driver packages +import iotcode.interfaces.*; +import iotcode.annotation.*; + + +// Standard Java packages +import java.util.HashMap; +import java.util.Map; +import java.util.Date; // TODO: Get rid of all depreciated stuff for date, switch to Calender +import java.util.concurrent.Semaphore; + +// RMI packages +import java.rmi.RemoteException; + +// Checker annotations +//import iotchecker.qual.*; + +/** Class Smart Lights Controller for the smart home application benchmark + * + * @author Ali Younis + * @version 1.0 + * @since 2016-01-27 + */ +public class SmartLightsController { + + /* + * Constants + */ + public static final int MOTION_TIME_THRESHOLD = 60; // in seconds + public static final int CHECK_TIME_WAIT = 1; // in seconds + public static final int COLOR_TEMP_MIN_KELVIN = 2500; // In Kelvin + public static final int COLOR_TEMP_MAX_KELVIN = 9000; // In Kelvin + public static final int CAMERA_FPS = 15; // In frames per second + + /* + * IoT Sets of Devices + */ + @config private IoTSet mainRoomLightBulbs; + @config private IoTSet cameras; + + + /* + * IoT Sets of Things that are not devices such as rooms + */ + @config private IoTSet rooms; + + /* + * IoT Relations + */ + @config private IoTRelation roomCameraRel; + @config private IoTRelation roomMainBulbRel; + + + /* + * The state that the room main lights are supposed to be in + */ + Map roomLightOnOffStatus = + new HashMap(); + Map roomLightColorTemperature = + new HashMap(); + + /* + * Motion detectors that are bound to specific cameras + */ + private Map + camMotionDetect = new HashMap(); + + + /******************************************************************************************************************************************* + ** + ** Variables + ** + *******************************************************************************************************************************************/ + long lastTimeChecked = 0; + + boolean print830 = true; + boolean print1030 = true; + boolean print730 = true; + boolean print930 = true; + boolean printNite = true; + + /******************************************************************************************************************************************* + ** + ** Private Helper Methods + ** + *******************************************************************************************************************************************/ + + /** Method to detect if a room has seen motion within the last few seconds (time specified as parameter). + * Checks all the motion detectors for the given room + * + * @param _room [Room] , Room of interest. + * @param _numberOfSeconds [int] , Number of seconds in the past that we consider recent. + * @param _upperThreshold [int] , Number of seconds as an upper bound before we turn off. + * + * @return [boolean] if motion was detected recently. + */ + private boolean roomDidHaveMotionRecently(Room _room, int _numberOfSeconds) { + long currentTimeSeconds = (new Date()).getTime() / 1000; + + // Loop through all the motion sensors in the room + for (CameraSmart cam : roomCameraRel.get(_room)) { + long lastDetectedMotionSeconds = currentTimeSeconds; + + Date motionTime = ((MotionDetection)camMotionDetect.get(cam)).getTimestampOfLastMotion(); + + // Motion was detected at least once + if (motionTime != null) { + lastDetectedMotionSeconds = motionTime.getTime() / 1000; + } else { + // motionTime == null means this is the initialization phase + // so we return false to initialize the lightbulbs to off + return false; + } + + // Did detect motion recently + if (Math.abs(currentTimeSeconds - lastDetectedMotionSeconds) < _numberOfSeconds) { + return true; + } + } + + return false; + } + + + + /** Set the temperature of the room based on the time of day. + * Do this to make sure people are able to get a good nights sleep. + * based on this: https://justgetflux.com/research.html + * + * @return [void] None; + */ + private void setRoomColorTemperatureForSleep() throws RemoteException { + + long currentTimeSeconds = (new Date()).getTime() / 1000; + Date today = new Date(); + Date beginningOfToday = new Date(today.getYear(), + today.getMonth(), today.getDate()); + + long secondsSinceStartOfDay = currentTimeSeconds - (beginningOfToday.getTime() / 1000); + + for (Room room : rooms.values()) { + + // before 8:30 am + if (secondsSinceStartOfDay <= 30600) { + ColorTemperature colTemp = roomLightColorTemperature.get(room); + colTemp.temperature = COLOR_TEMP_MIN_KELVIN; + roomLightColorTemperature.put(room, colTemp); + + if (print830) { + System.out.println("Before 8:30am!"); + System.out.println("Color temperature: " + colTemp.temperature); + print830 = false; + print1030 = true; + print730 = true; + print930 = true; + printNite = true; + } + + } else if ((secondsSinceStartOfDay > 30600) && (secondsSinceStartOfDay < 37800)) { + // 8:30am - 10:30 am + // Slowly turn lights from warm to work white + double newKelvinValue = (double) (secondsSinceStartOfDay - 30600) / (37800 - 30600); + newKelvinValue = (newKelvinValue * (COLOR_TEMP_MAX_KELVIN - COLOR_TEMP_MIN_KELVIN)) + COLOR_TEMP_MIN_KELVIN; + ColorTemperature colTemp = roomLightColorTemperature.get(room); + colTemp.temperature = (int)newKelvinValue; + roomLightColorTemperature.put(room, colTemp); + + if (print1030) { + System.out.println("8:30am - 10:30am!"); + print830 = true; + print1030 = false; + print730 = true; + print930 = true; + printNite = true; + } + + } else if ((secondsSinceStartOfDay > 37800 ) && (secondsSinceStartOfDay < 70200)) { + // Between 10:30am and 7:30pm + // Keep white Work Light + ColorTemperature colTemp = roomLightColorTemperature.get(room); + colTemp.temperature = COLOR_TEMP_MAX_KELVIN; + roomLightColorTemperature.put(room, colTemp); + + if (print730) { + System.out.println("10:30am - 7:30pm!"); + System.out.println("Color temperature: " + colTemp.temperature); + print830 = true; + print1030 = true; + print730 = false; + print930 = true; + printNite = true; + } + + } else if ((secondsSinceStartOfDay > 70200) && (secondsSinceStartOfDay < 77400)) { + // Between 7:30pm and 9:30pm + // Slowly turn lights from work to warm + double newKelvinValue = (double) (secondsSinceStartOfDay - 30600) / (37800 - 30600); + newKelvinValue = (newKelvinValue * (COLOR_TEMP_MAX_KELVIN - COLOR_TEMP_MIN_KELVIN)) + COLOR_TEMP_MIN_KELVIN; + ColorTemperature colTemp = roomLightColorTemperature.get(room); + colTemp.temperature = (int)newKelvinValue; + roomLightColorTemperature.put(room, colTemp); + + if (print930) { + System.out.println("7:30pm - 9:30pm!"); + print830 = true; + print1030 = true; + print730 = true; + print930 = false; + printNite = true; + } + + } else if (secondsSinceStartOfDay > 77400) { + // past 9:30pm + // Keep warm Light + ColorTemperature colTemp = roomLightColorTemperature.get(room); + colTemp.temperature = COLOR_TEMP_MIN_KELVIN; + roomLightColorTemperature.put(room, colTemp); + + if (printNite) { + System.out.println("After 9:30pm!"); + System.out.println("Color temperature: " + colTemp.temperature); + print830 = true; + print1030 = true; + print730 = true; + print930 = true; + printNite = false; + } + } + } + } + + + + /** Sets bulbs to the proper state. Sets the On/Off state as well as the color. + * The method changes the state of the bulb. It does not calculate what the state + * of the bulb should be, this is done elsewhere. + * + * When setting the color of the bulb, a best attempt effort is made. If the needed + * temperature and color of the bulb is outside the bulb range then the system gets + * as close as it can + * + * @return [void] None; + */ + private void setMainBulbs() throws RemoteException { + + for (Room room : rooms.values()) { + + // Lights in room should be turned off + if (!roomLightOnOffStatus.get(room)) { + + // turn the bulbs off if they are on + for (LightBulbSmart bulb : roomMainBulbRel.get(room)) { + if (bulb.getState()) { + bulb.turnOff(); + System.out.println("SmartLightsController: Send off signal!!!"); + } + } + + } else { + + // Lights in room should be turned on + // set the color of the bulbs + ColorTemperature colTemp = roomLightColorTemperature.get(room); + for (LightBulbSmart bulb : roomMainBulbRel.get(room)) { + // Turn on the bulb if they are off + if (!bulb.getState()) { + bulb.turnOn(); + System.out.println("SmartLightsController: Send on signal!!!"); + } + + // Get the requested color of the room + double hue = colTemp.hue; + double saturation = colTemp.saturation; + double brightness = colTemp.brightness; + int temperature = colTemp.temperature; + + // Make sure hue is in range that light bulb supports + if (hue < bulb.getHueRangeLowerBound()) { + hue = bulb.getHueRangeLowerBound(); + } else if (hue > bulb.getHueRangeUpperBound()) { + hue = bulb.getHueRangeUpperBound(); + } + + // Make sure saturation is in range that light bulb supports + if (saturation < bulb.getSaturationRangeLowerBound()) { + saturation = bulb.getSaturationRangeLowerBound(); + } else if (saturation > bulb.getSaturationRangeUpperBound()) { + saturation = bulb.getSaturationRangeUpperBound(); + } + + // Make sure brightness is in range that light bulb supports + if (brightness < bulb.getBrightnessRangeLowerBound()) { + brightness = bulb.getBrightnessRangeLowerBound(); + } else if (brightness > bulb.getBrightnessRangeUpperBound()) { + brightness = bulb.getBrightnessRangeUpperBound(); + } + + // Make sure temperature is in range that light bulb supports + if (temperature < bulb.getTemperatureRangeLowerBound()) { + temperature = bulb.getTemperatureRangeLowerBound(); + } else if (temperature > bulb.getTemperatureRangeUpperBound()) { + temperature = bulb.getTemperatureRangeUpperBound(); + } + + // Actually set the bulb to that color and temp + bulb.setColor(hue, saturation, brightness); + bulb.setTemperature(temperature); + } + } + } + } + + + /******************************************************************************************************** + ** Public methods, called by the runtime + *********************************************************************************************************/ + + /** Initialization method, called by the runtime (effectively the main of the controller) + * This method runs a continuous loop and is blocking + * + * @return [void] None; + */ + public void init() throws RemoteException, InterruptedException { + + + // Initialize the rooms + for (Room room : rooms.values()) { + + // All rooms start with the lights turned off + roomLightOnOffStatus.put(room, false); + + // All rooms have a default color and temperature + roomLightColorTemperature.put(room, new ColorTemperature(0, 0, 100, 2500)); + } + + + // Setup the cameras, start them all and assign each one a motion detector + for (CameraSmart cam : cameras.values()) { + + // Each camera will have a motion detector unique to it since the motion detection has state + MotionDetection mo = new MotionDetection(12, 0.5f, 10, 10); + + // initialize the camera, might need to setup some stuff internally + cam.init(); + + // set the camera parameters. + cam.setFPS(CAMERA_FPS); + cam.setResolution(Resolution.RES_VGA); + + // camera will call the motion detector directly with data not this controller + cam.registerCallback(mo); + + // Start the camera (example is start the HTTP stream if it is a network camera) + cam.start(); + + // Remember which motion detector is for what camera + camMotionDetect.put(cam, mo); + } + + + //Initialize the light-bulbs, will turn off the bulb + for (LightBulbSmart bulb : mainRoomLightBulbs.values()) { + bulb.init(); + Thread.sleep(1000); + } + + // Run the main loop that will keep check the bulbs and rooms periodically + while (true) { + + // Run this code every + long currentTimeSeconds = (new Date()).getTime() / 1000; + if ((currentTimeSeconds - lastTimeChecked) > CHECK_TIME_WAIT) { + lastTimeChecked = currentTimeSeconds; + + // Check for motion in rooms and if there is motion then turn on the lights + for (Room room : rooms.values()) { + + if (roomDidHaveMotionRecently(room, MOTION_TIME_THRESHOLD)) { + + // Motion was detected + roomLightOnOffStatus.put(room, true); + + } else { + + // No motion was detected + roomLightOnOffStatus.put(room, false); + + } + } + + // Check what the temperature of the light in the room should be + setRoomColorTemperatureForSleep(); + + // Set the bulbs to the new values + setMainBulbs(); + + } else { + try { + Thread.sleep(CHECK_TIME_WAIT * 100); // sleep for a tenth of the time + } catch (Exception e) { + + } + } + + } + } +} + + + + diff --git a/benchmarks/drivers/AmcrestCamera/AmcrestCamera.config b/benchmarks/drivers/AmcrestCamera/AmcrestCamera.config new file mode 100644 index 0000000..b33293e --- /dev/null +++ b/benchmarks/drivers/AmcrestCamera/AmcrestCamera.config @@ -0,0 +1,4 @@ +# Skeleton/original interface +INTERFACE_CLASS=Camera +# Stub +INTERFACE_STUB_CLASS=CameraSmart diff --git a/benchmarks/drivers/AmcrestCamera/AmcrestCamera.java b/benchmarks/drivers/AmcrestCamera/AmcrestCamera.java new file mode 100644 index 0000000..ba3d8e3 --- /dev/null +++ b/benchmarks/drivers/AmcrestCamera/AmcrestCamera.java @@ -0,0 +1,537 @@ +package iotcode.AmcrestCamera; + +// IoT Packages +import iotcode.annotation.*; +import iotcode.interfaces.*; +import iotruntime.IoTHTTP; +import iotruntime.slave.IoTSet; +import iotruntime.slave.IoTDeviceAddress; + +// Standard Java Packages +import java.io.IOException; +import java.io.DataInputStream; +import java.io.InputStream; +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.awt.image.BufferedImage; +import java.awt.image.ColorModel; +import java.awt.image.WritableRaster; +import java.awt.image.BufferedImage; +import javax.imageio.ImageIO; +import java.util.Base64; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.ArrayList; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.Iterator; +import javax.imageio.ImageIO; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.Semaphore; + +// RMI Packages +import java.rmi.Remote; +import java.rmi.RemoteException; + +// Checker annotations +//import iotchecker.qual.*; + +public class AmcrestCamera implements Camera { + + /******************************************************************************************************************************************* + ** + ** Variables + ** + *******************************************************************************************************************************************/ + private String credentialUsername = ""; + private String credentialPassword = ""; + private DataInputStream dataInStream = null; + private boolean isStreamConnected = false; + private byte[] latestImage = null; + private ReadWriteLock imageReadWriteLock = new ReentrantReadWriteLock(); + private Lock imageReadLock = imageReadWriteLock.readLock(); + private Lock imageWriteLock = imageReadWriteLock.writeLock(); + private AtomicBoolean newFrameAvailable = new AtomicBoolean(false); + private ReadWriteLock timestampReadWriteLock = new ReentrantReadWriteLock(); + private Lock timestampReadLock = timestampReadWriteLock.readLock(); + private Lock timestampWriteLock = timestampReadWriteLock.writeLock(); + private Date latestImageTimestamp = null; + private List callbackList = + new CopyOnWriteArrayList (); + private AtomicBoolean doEnd = new AtomicBoolean(false); + private IoTDeviceAddress deviceAddress = null; + private AtomicBoolean didInit = new AtomicBoolean(); + private AtomicBoolean didStart = new AtomicBoolean(); + static Semaphore settingsSettings = new Semaphore(1); + + /******************************************************************************************************************************************* + ** + ** Threads + ** + *******************************************************************************************************************************************/ + private Thread callbackThread = null; + private Thread workerThread = null; + + + /******************************************************************************************************************************************* + ** + ** IoT Sets and Relations + ** + *******************************************************************************************************************************************/ + + // IoTSet of Device Addresses. + // Will be filled with only 1 address. + @config private IoTSet cam_addresses; + + + public AmcrestCamera(String _credentialUsername, String _credentialPassword) throws RemoteException { + credentialUsername = _credentialUsername; + credentialPassword = _credentialPassword; + } + + /******************************************************************************************************************************************* + ** + ** Camera Interface Methods + ** + *******************************************************************************************************************************************/ + + public byte[] getLatestFrame() { + + byte[] newImage = null; + + imageReadLock.lock(); + try { + if (latestImage != null) { + newImage = Arrays.copyOf(latestImage, latestImage.length); + } + } catch (Exception x) { + x.printStackTrace(); + } + imageReadLock.unlock(); + + return newImage; + } + + public long getTimestamp() { + timestampReadLock.lock(); + Date ret = (Date)latestImageTimestamp.clone(); + timestampReadLock.unlock(); + long retLong = ret.getTime(); + return retLong; + } + + public void registerCallback(CameraSmartCallback _callbackTo) { + callbackList.add(_callbackTo); + } + + public boolean setFPS(int _fps) { + try { + settingsSettings.acquire(); + + String camUrlString = "/cgi-bin/configManager.cgi?action=setConfig&Encode[0].MainFormat[0].Video.FPS=" + Integer.toString(_fps); + + try { + + String credsPreBase64 = credentialUsername + ":" + credentialPassword; + String credsBase64 = Base64.getEncoder().encodeToString(credsPreBase64.getBytes("utf-8")); + String httpAuthCredentials = "Basic " + credsBase64; + + IoTHTTP httpConnection = new IoTHTTP(deviceAddress); + httpConnection.setURL(camUrlString); + httpConnection.openConnection(); + httpConnection.setDoInput(true); + httpConnection.setRequestProperty("Authorization", httpAuthCredentials); + httpConnection.connect(); + + InputStream is = httpConnection.getInputStream(); + BufferedInputStream bis = new BufferedInputStream(is); + DataInputStream din = new DataInputStream(bis); + + // wait for a response + try { + Thread.sleep(1000); + } catch (InterruptedException ie) { + } + + byte[] byteBuf = new byte[100]; + try { + int r = din.read(byteBuf, 0, byteBuf.length); + String retString = new String(byteBuf); + + if (!retString.substring(0, 2).equals("OK")) { + httpConnection.disconnect(); + return false; + } + + } catch (Exception e) { + httpConnection.disconnect(); + return false; + // e.printStackTrace(); + } + + httpConnection.disconnect(); + } catch (IOException e) { + return false; + } catch (Exception e) { + return false; + } + } catch (Exception e) { + e.printStackTrace(); + } + settingsSettings.release(); + + return true; + } + + public int getMaxFPS() { + // Hard coded since this is hardware dependant + return 30; + } + + public int getMinFPS() { + // Hard coded since this is hardware dependant + return 5; + } + + public List getSupportedResolutions() { + + // Hard coded since this is hardware dependant + List ret = new ArrayList(); + ret.add(Resolution.RES_1080P); + ret.add(Resolution.RES_720P); + ret.add(Resolution.RES_VGA); + return ret; + } + + public boolean setResolution(Resolution _res) { + + try { + settingsSettings.acquire(); + + + String camUrlString = "/cgi-bin/configManager.cgi?action=setConfig"; + + if (_res == Resolution.RES_1080P) { + camUrlString += "&Encode[0].MainFormat[0].Video.Height=1080&Encode[0].MainFormat[0].Video.Width=1920"; + + } else if (_res == Resolution.RES_720P) { + camUrlString += "&Encode[0].MainFormat[0].Video.Height=720&Encode[0].MainFormat[0].Video.Width=1280"; + + } else if (_res == Resolution.RES_VGA) { + camUrlString += "&Encode[0].MainFormat[0].Video.Height=480&Encode[0].MainFormat[0].Video.Width=640"; + } + + + try { + + String credsPreBase64 = credentialUsername + ":" + credentialPassword; + String credsBase64 = Base64.getEncoder().encodeToString(credsPreBase64.getBytes("utf-8")); + String httpAuthCredentials = "Basic " + credsBase64; + + IoTHTTP httpConnection = new IoTHTTP(deviceAddress); + httpConnection.setURL(camUrlString); + httpConnection.openConnection(); + httpConnection.setDoInput(true); + httpConnection.setRequestProperty("Authorization", httpAuthCredentials); + httpConnection.connect(); + + InputStream is = httpConnection.getInputStream(); + BufferedInputStream bis = new BufferedInputStream(is); + DataInputStream din = new DataInputStream(bis); + + // wait for a response + try { + Thread.sleep(1000); + } catch (InterruptedException ie) { + } + + byte[] byteBuf = new byte[100]; + try { + int r = din.read(byteBuf, 0, byteBuf.length); + String retString = new String(byteBuf); + + if (!retString.substring(0, 2).equals("OK")) { + httpConnection.disconnect(); + return false; + } + + } catch (Exception e) { + httpConnection.disconnect(); + return false; + // e.printStackTrace(); + } + + httpConnection.disconnect(); + } catch (IOException e) { + return false; + } catch (Exception e) { + return false; + } + } catch (Exception e) { + e.printStackTrace(); + } + + settingsSettings.release(); + + return true; + } + + public void start() { + + if (didStart.compareAndSet(false, true) == false) { + return; // already started + } + + + + doEnd.set(false); + + if (!streamConnect()) { + return; + } + + callbackThread = new Thread(new Runnable() { + public void run() { + doCallbacks(); + } + }); + callbackThread.start(); + + workerThread = new Thread(new Runnable() { + public void run() { + doWork(); + } + }); + workerThread.start(); + } + + public void stop() { + if (didStart.compareAndSet(true, false) == false) { + return; // already stopped + } + + doEnd.set(true); + + try { + callbackThread.join(); + workerThread.join(); + } catch (Exception e) { + e.printStackTrace(); + } + + streamDisconnect(); + } + + public void init() { + if (didInit.compareAndSet(false, true) == false) { + return; // already init + } + + // get the device address and save it for later use when creating HTTP connections + Iterator itr = cam_addresses.iterator(); + deviceAddress = (IoTDeviceAddress)itr.next(); + + System.out.println("Address: " + deviceAddress.getCompleteAddress()); + } + + /******************************************************************************************************************************************* + ** + ** Helper Methods + ** + *******************************************************************************************************************************************/ + private byte[] readFromStream(int num) { + byte[] byteBuf = new byte[num]; + try { + dataInStream.readFully(byteBuf, 0, byteBuf.length); + } catch (Exception e) { + e.printStackTrace(); + } + + return byteBuf; + } + + private void findBoundry() { + String boundary = "**************"; + while (true) { + byte b = readFromStream(1)[0]; + boundary = boundary.substring(1); + boundary += (char)b; + + if (boundary.equals("--myboundary\r\n")) { + break; + } + } + } + + private String getLine() { + String line = ""; + while (true) { + byte b = readFromStream(1)[0]; + char c = (char)b; + + if (c == '\n') { + break; + } else if (c != '\r') { + line += c; + } + } + + return line; + } + + private BufferedImage parseImage() { + + findBoundry(); + + String contentTypeString = getLine(); + String contentLengthString = getLine(); + + // remove the new line characters \r\n + readFromStream(2); + + int imageDataLength = Integer.parseInt(contentLengthString.substring(16)); + + byte[] imageDataBuf = readFromStream(imageDataLength); + + // remove the new line characters \r\n + readFromStream(2); + + + try { + InputStream imageInStream = new ByteArrayInputStream(imageDataBuf); + return ImageIO.read(imageInStream); + + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Has Exception"); + + } + + return null; + } + + private boolean streamConnect() { + + try { + + String credsPreBase64 = credentialUsername + ":" + credentialPassword; + String credsBase64 = Base64.getEncoder().encodeToString(credsPreBase64.getBytes("utf-8")); + String httpAuthCredentials = "Basic " + credsBase64; + + IoTHTTP httpConnection = new IoTHTTP(deviceAddress); + httpConnection.setURL("/cgi-bin/mjpg/video.cgi?"); + httpConnection.openConnection(); + httpConnection.setDoInput(true); + httpConnection.setRequestProperty("Authorization", httpAuthCredentials); + httpConnection.connect(); + + InputStream is = httpConnection.getInputStream(); + BufferedInputStream bis = new BufferedInputStream(is); + dataInStream = new DataInputStream(bis); + + isStreamConnected = true; + + } catch (IOException e) { + isStreamConnected = false; + + } catch (Exception e) { + isStreamConnected = false; + } + + return isStreamConnected; + } + + private void streamDisconnect() { + try { + if (isStreamConnected) { + dataInStream.close(); + isStreamConnected = false; + } + } catch (Exception e) { + } + } + + private void doCallbacks() { + + while (!doEnd.get()) { + if (newFrameAvailable.compareAndSet(true, false)) { + + for (CameraSmartCallback c : callbackList) { + + c.newCameraFrameAvailable(this); + } + } else { + + // Sleep for 15 millisec to give time for new frame to arrive + try { + Thread.sleep(15); + } catch (InterruptedException ie) { + } + } + } + + } + + private void doWork() { + + // parse the images that are loaded into the buffer + while (!doEnd.get()) { + + BufferedImage img = parseImage(); + + if (img != null) { + + timestampWriteLock.lock(); + latestImageTimestamp = new Date(); + timestampWriteLock.unlock(); + + imageWriteLock.lock(); + + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ImageIO.write(img, "jpg", baos); + baos.flush(); + latestImage = baos.toByteArray(); + baos.close(); + + } catch (Exception e) { + + } + imageWriteLock.unlock(); + + newFrameAvailable.set(true); + } + + try { + if (dataInStream.available() > 120000) { + dataInStream.skip(120000); + } + } catch (Exception e) { + } + } + + } + +} + + + + + + + + + + + + + + + + diff --git a/benchmarks/drivers/AmcrestCamera/Camera_Skeleton.java b/benchmarks/drivers/AmcrestCamera/Camera_Skeleton.java new file mode 100644 index 0000000..86d9aa8 --- /dev/null +++ b/benchmarks/drivers/AmcrestCamera/Camera_Skeleton.java @@ -0,0 +1,208 @@ +package iotcode.AmcrestCamera; + +import java.io.IOException; +import java.util.List; +import java.util.ArrayList; +import java.util.Arrays; +import iotrmi.Java.IoTRMICall; +import iotrmi.Java.IoTRMIObject; + +import iotcode.interfaces.*; +import SmartLightsController.CameraSmartCallback_CallbackStub; + +public class Camera_Skeleton implements Camera { + + private Camera mainObj; + private IoTRMIObject rmiObj; + + private String callbackAddress; + private static int objIdCnt = 0; + private IoTRMICall rmiCall; + private int[] ports; + + private final static int object0Id = 0; //CameraSmart + private static Integer[] object0Permission = { 8, 7, 9, 6, 2, 1, 4, 3, 0, 10, 5 }; + private static List set0Allowed; + + + public Camera_Skeleton(Camera _mainObj, String _callbackAddress, int _port) throws Exception { + mainObj = _mainObj; + callbackAddress = _callbackAddress; + rmiObj = new IoTRMIObject(_port); + set0Allowed = new ArrayList(Arrays.asList(object0Permission)); + set0Allowed.add(-9998); + ___waitRequestInvokeMethod(); + } + + public void init() { + mainObj.init(); + } + + public void start() { + mainObj.start(); + } + + public void stop() { + mainObj.stop(); + } + + public byte[] getLatestFrame() { + return mainObj.getLatestFrame(); + } + + public long getTimestamp() { + return mainObj.getTimestamp(); + } + + public List getSupportedResolutions() { + return mainObj.getSupportedResolutions(); + } + + public boolean setResolution(Resolution _res) { + return mainObj.setResolution(_res); + } + + public boolean setFPS(int _fps) { + return mainObj.setFPS(_fps); + } + + public int getMaxFPS() { + return mainObj.getMaxFPS(); + } + + public int getMinFPS() { + return mainObj.getMinFPS(); + } + + public void registerCallback(CameraSmartCallback _callbackTo) { + mainObj.registerCallback(_callbackTo); + } + + public void ___regCB() throws IOException { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { int[].class, String.class, int.class },new Class[] { null, null, null }); + ports = (int[]) paramObj[0]; + rmiCall = new IoTRMICall((int) paramObj[0], (String) paramObj[1], ports[0]); + } + + public void ___init() { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { }, + new Class[] { }); + init(); + } + + public void ___start() { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { }, + new Class[] { }); + start(); + } + + public void ___stop() { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { }, + new Class[] { }); + stop(); + } + + public void ___getLatestFrame() throws IOException { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { }, + new Class[] { }); + Object retObj = getLatestFrame(); + rmiObj.sendReturnObj(retObj); + } + + public void ___getTimestamp() throws IOException { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { }, + new Class[] { }); + Object retObj = getTimestamp(); + rmiObj.sendReturnObj(retObj); + } + + public void ___getSupportedResolutions() throws IOException { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { }, + new Class[] { }); + List retEnum = getSupportedResolutions(); + int retLen = retEnum.size(); + int[] retEnumVal = new int[retLen]; + for (int i = 0; i < retLen; i++) { + retEnumVal[i] = retEnum.get(i).ordinal(); + } + Object retObj = retEnumVal; + rmiObj.sendReturnObj(retObj); + } + + public void ___setResolution() throws IOException { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { int[].class }, + new Class[] { null }); + int paramInt0[] = (int[]) paramObj[0]; + Resolution[] enumVals = Resolution.values(); + Resolution paramEnum0 = enumVals[paramInt0[0]]; + Object retObj = setResolution(paramEnum0); + rmiObj.sendReturnObj(retObj); + } + + public void ___setFPS() throws IOException { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { int.class }, + new Class[] { null }); + Object retObj = setFPS((int) paramObj[0]); + rmiObj.sendReturnObj(retObj); + } + + public void ___getMaxFPS() throws IOException { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { }, + new Class[] { }); + Object retObj = getMaxFPS(); + rmiObj.sendReturnObj(retObj); + } + + public void ___getMinFPS() throws IOException { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { }, + new Class[] { }); + Object retObj = getMinFPS(); + rmiObj.sendReturnObj(retObj); + } + + public void ___registerCallback() { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { int.class }, + new Class[] { null }); + try { + CameraSmartCallback stub0 = new CameraSmartCallback_CallbackStub(rmiCall, callbackAddress, objIdCnt, ports); + objIdCnt++; + registerCallback(stub0); + } catch(Exception ex) { + ex.printStackTrace(); + throw new Error("Exception from callback object instantiation!"); + } + } + + private void ___waitRequestInvokeMethod() throws IOException { + while (true) { + rmiObj.getMethodBytes(); + int _objectId = rmiObj.getObjectId(); + int methodId = rmiObj.getMethodId(); + if (_objectId == object0Id) { + if (!set0Allowed.contains(methodId)) { + throw new Error("Object with object Id: " + _objectId + " is not allowed to access method: " + methodId); + } + } + else { + throw new Error("Object Id: " + _objectId + " not recognized!"); + } + switch (methodId) { + case 0: ___init(); break; + case 1: ___start(); break; + case 2: ___stop(); break; + case 3: ___getLatestFrame(); break; + case 4: ___getTimestamp(); break; + case 5: ___getSupportedResolutions(); break; + case 6: ___setResolution(); break; + case 7: ___setFPS(); break; + case 8: ___getMaxFPS(); break; + case 9: ___getMinFPS(); break; + case 10: ___registerCallback(); break; + case -9998: ___regCB(); break; + default: + throw new Error("Method Id " + methodId + " not recognized!"); + } + } + } + +} diff --git a/benchmarks/drivers/LabRoom/LabRoom.config b/benchmarks/drivers/LabRoom/LabRoom.config new file mode 100644 index 0000000..f10cb63 --- /dev/null +++ b/benchmarks/drivers/LabRoom/LabRoom.config @@ -0,0 +1,4 @@ +# Skeleton/original interface +INTERFACE_CLASS=Room +# Stub +INTERFACE_STUB_CLASS=RoomSmart diff --git a/benchmarks/drivers/LabRoom/LabRoom.java b/benchmarks/drivers/LabRoom/LabRoom.java new file mode 100644 index 0000000..745a1a8 --- /dev/null +++ b/benchmarks/drivers/LabRoom/LabRoom.java @@ -0,0 +1,20 @@ +package iotcode.LabRoom; + +import iotcode.interfaces.Room; + +/** LabRoom implements Room as a needed object for room identification + * + * @author Rahmadi Trimananda + * @version 1.0 + * @since 2016-04-22 + */ +public class LabRoom implements Room { + + public LabRoom() { + + } + + public int getRoomID() { + return 0; + } +} diff --git a/benchmarks/drivers/LabRoom/Room_Skeleton.java b/benchmarks/drivers/LabRoom/Room_Skeleton.java new file mode 100644 index 0000000..04da3ed --- /dev/null +++ b/benchmarks/drivers/LabRoom/Room_Skeleton.java @@ -0,0 +1,63 @@ +package iotcode.LabRoom; + +import java.io.IOException; +import java.util.List; +import java.util.ArrayList; +import java.util.Arrays; +import iotrmi.Java.IoTRMICall; +import iotrmi.Java.IoTRMIObject; + +import iotcode.interfaces.Room; + +public class Room_Skeleton implements Room { + + private Room mainObj; + private IoTRMIObject rmiObj; + + private String callbackAddress; + private final static int object0Id = 0; //RoomSmart + private static Integer[] object0Permission = { 0 }; + private static List set0Allowed; + + + public Room_Skeleton(Room _mainObj, String _callbackAddress, int _port) throws Exception { + mainObj = _mainObj; + callbackAddress = _callbackAddress; + rmiObj = new IoTRMIObject(_port); + set0Allowed = new ArrayList(Arrays.asList(object0Permission)); + ___waitRequestInvokeMethod(); + } + + public int getRoomID() { + return mainObj.getRoomID(); + } + + public void ___getRoomID() throws IOException { + Object[] paramObj = rmiObj.getMethodParams(new Class[] { }, + new Class[] { }); + Object retObj = getRoomID(); + rmiObj.sendReturnObj(retObj); + } + + private void ___waitRequestInvokeMethod() throws IOException { + while (true) { + rmiObj.getMethodBytes(); + int _objectId = rmiObj.getObjectId(); + int methodId = rmiObj.getMethodId(); + if (_objectId == object0Id) { + if (!set0Allowed.contains(methodId)) { + throw new Error("Object with object Id: " + _objectId + " is not allowed to access method: " + methodId); + } + } + else { + throw new Error("Object Id: " + _objectId + " not recognized!"); + } + switch (methodId) { + case 0: ___getRoomID(); break; + default: + throw new Error("Method Id " + methodId + " not recognized!"); + } + } + } + +} diff --git a/benchmarks/drivers/LifxLightBulb/LifxLightBulb.config b/benchmarks/drivers/LifxLightBulb/LifxLightBulb.config index 635f884..0a7ddcb 100644 --- a/benchmarks/drivers/LifxLightBulb/LifxLightBulb.config +++ b/benchmarks/drivers/LifxLightBulb/LifxLightBulb.config @@ -1,3 +1,5 @@ +# Skeleton/original interface INTERFACE_CLASS=LightBulb +# Stub INTERFACE_STUB_CLASS=LightBulbTest diff --git a/benchmarks/drivers/Makefile b/benchmarks/drivers/Makefile index 1a1a0a0..64f5d6c 100644 --- a/benchmarks/drivers/Makefile +++ b/benchmarks/drivers/Makefile @@ -10,7 +10,7 @@ JFLAGS = -d $(BIN_DIR) -cp $(BIN_DIR):$(PHONEJARS):$(BOOFJARS):$(JLAYERJARS) JARFLAGS = cf INTFACE_DIR = iotcode/interfaces -all: light +all: light camera labroom # Compile # @@ -20,4 +20,16 @@ light: cp LifxLightBulb/LifxLightBulb.config $(BIN_DIR)/iotcode/LifxLightBulb cd $(BIN_DIR)/iotcode/LifxLightBulb; $(JAR) $(JARFLAGS) LifxLightBulb.jar ../../iotcode/LifxLightBulb/*.class ../../iotcode/interfaces/LightBulb*.class +PHONY += camera +camera: + $(JAVAC) $(JFLAGS) AmcrestCamera/*.java + cp AmcrestCamera/AmcrestCamera.config $(BIN_DIR)/iotcode/AmcrestCamera + cd $(BIN_DIR)/iotcode/AmcrestCamera; $(JAR) $(JARFLAGS) AmcrestCamera.jar ../../iotcode/AmcrestCamera/*.class ../../iotcode/interfaces/Camera*.class + +PHONY += labroom +labroom: + $(JAVAC) $(JFLAGS) LabRoom/*.java + cp LabRoom/LabRoom.config $(BIN_DIR)/iotcode/LabRoom + cd $(BIN_DIR)/iotcode/LabRoom; $(JAR) $(JARFLAGS) LabRoom.jar ../../iotcode/LabRoom/*.class ../../iotcode/interfaces/Room*.class + .PHONY: $(PHONY) diff --git a/benchmarks/interfaces/Camera.java b/benchmarks/interfaces/Camera.java new file mode 100644 index 0000000..ae3a2dc --- /dev/null +++ b/benchmarks/interfaces/Camera.java @@ -0,0 +1,18 @@ +package iotcode.interfaces; + +import java.util.List; +import java.util.ArrayList; + +public interface Camera { + public void init(); + public void start(); + public void stop(); + public byte[] getLatestFrame(); + public long getTimestamp(); + public List getSupportedResolutions(); + public boolean setResolution(Resolution _res); + public boolean setFPS(int _fps); + public int getMaxFPS(); + public int getMinFPS(); + public void registerCallback(CameraSmartCallback _callbackTo); +} diff --git a/benchmarks/interfaces/CameraCallback.java b/benchmarks/interfaces/CameraCallback.java new file mode 100644 index 0000000..e4a07f0 --- /dev/null +++ b/benchmarks/interfaces/CameraCallback.java @@ -0,0 +1,8 @@ +package iotcode.interfaces; + +import java.util.List; +import java.util.ArrayList; + +public interface CameraCallback { + public void newCameraFrameAvailable(CameraSmart _camera); +} diff --git a/benchmarks/interfaces/CameraSmart.java b/benchmarks/interfaces/CameraSmart.java new file mode 100644 index 0000000..9b01792 --- /dev/null +++ b/benchmarks/interfaces/CameraSmart.java @@ -0,0 +1,19 @@ +package iotcode.interfaces; + +import java.util.List; +import java.util.ArrayList; + +public interface CameraSmart { + + public int getMaxFPS(); + public boolean setFPS(int _fps); + public int getMinFPS(); + public boolean setResolution(Resolution _res); + public void stop(); + public void start(); + public long getTimestamp(); + public byte[] getLatestFrame(); + public void init(); + public void registerCallback(CameraCallback _callbackTo); + public List getSupportedResolutions(); +} diff --git a/benchmarks/interfaces/CameraSmartCallback.java b/benchmarks/interfaces/CameraSmartCallback.java new file mode 100644 index 0000000..7febe02 --- /dev/null +++ b/benchmarks/interfaces/CameraSmartCallback.java @@ -0,0 +1,9 @@ +package iotcode.interfaces; + +import java.util.List; +import java.util.ArrayList; + +public interface CameraSmartCallback { + + public void newCameraFrameAvailable(Camera _camera); +} diff --git a/benchmarks/interfaces/LightBulbSmart.java b/benchmarks/interfaces/LightBulbSmart.java new file mode 100644 index 0000000..eb7cc8c --- /dev/null +++ b/benchmarks/interfaces/LightBulbSmart.java @@ -0,0 +1,26 @@ +package iotcode.interfaces; + +import java.util.List; +import java.util.ArrayList; + +public interface LightBulbSmart { + + public void turnOn(); + public double getBrightnessRangeLowerBound(); + public void turnOff(); + public boolean getState(); + public double getBrightnessRangeUpperBound(); + public double getSaturation(); + public double getHueRangeLowerBound(); + public double getHue(); + public double getHueRangeUpperBound(); + public int getTemperature(); + public double getBrightness(); + public int getTemperatureRangeLowerBound(); + public int getTemperatureRangeUpperBound(); + public void setColor(double _hue, double _saturation, double _brightness); + public void init(); + public double getSaturationRangeLowerBound(); + public double getSaturationRangeUpperBound(); + public void setTemperature(int _temperature); +} diff --git a/benchmarks/interfaces/Resolution.java b/benchmarks/interfaces/Resolution.java new file mode 100644 index 0000000..5b67caa --- /dev/null +++ b/benchmarks/interfaces/Resolution.java @@ -0,0 +1,8 @@ +package iotcode.interfaces; + +public enum Resolution { + RES_1080P, + RES_720P, + RES_VGA +} + diff --git a/benchmarks/interfaces/Room.java b/benchmarks/interfaces/Room.java new file mode 100644 index 0000000..c7388fd --- /dev/null +++ b/benchmarks/interfaces/Room.java @@ -0,0 +1,5 @@ +package iotcode.interfaces; + +public interface Room { + public int getRoomID(); +} diff --git a/benchmarks/interfaces/RoomSmart.java b/benchmarks/interfaces/RoomSmart.java new file mode 100644 index 0000000..924f011 --- /dev/null +++ b/benchmarks/interfaces/RoomSmart.java @@ -0,0 +1,6 @@ +package iotcode.interfaces; + +public interface RoomSmart { + + public int getRoomID(); +} diff --git a/iotjava/Makefile b/iotjava/Makefile index f224f0e..1d1b04d 100644 --- a/iotjava/Makefile +++ b/iotjava/Makefile @@ -29,7 +29,19 @@ PHONY += run-compiler-lifx run-compiler-lifx: cp ../localconfig/iotpolicy/LifxLightBulb/*.pol $(BIN_DIR)/iotpolicy/ cp ../localconfig/iotpolicy/LifxLightBulb/*.req $(BIN_DIR)/iotpolicy/ - cd $(BIN_DIR)/iotpolicy; $(JAVA) -cp .:..:../$(PARSERJARS):../$(BIN_DIR) iotpolicy.IoTCompiler lifxlightbulb.pol lifxtest.req -java Java + cd $(BIN_DIR)/iotpolicy; $(JAVA) -cp .:..:../$(PARSERJARS):../$(BIN_DIR) iotpolicy.IoTCompiler lifxlightbulb.pol smartlightsbulb.req -java Java + +PHONY += run-compiler-room +run-compiler-room: + cp ../localconfig/iotpolicy/LabRoom/*.pol $(BIN_DIR)/iotpolicy/ + cp ../localconfig/iotpolicy/LabRoom/*.req $(BIN_DIR)/iotpolicy/ + cd $(BIN_DIR)/iotpolicy; $(JAVA) -cp .:..:../$(PARSERJARS):../$(BIN_DIR) iotpolicy.IoTCompiler labroom.pol roomsmart.req -java Java + +PHONY += run-compiler-cam +run-compiler-cam: + cp ../localconfig/iotpolicy/AmcrestCamera/*.pol $(BIN_DIR)/iotpolicy/ + cp ../localconfig/iotpolicy/AmcrestCamera/*.req $(BIN_DIR)/iotpolicy/ + cd $(BIN_DIR)/iotpolicy; $(JAVA) -cp .:..:../$(PARSERJARS):../$(BIN_DIR) iotpolicy.IoTCompiler amcrestcamera.pol smartlightscam.req motiondetection.pol motiondetection.req -java Java # TODO: Can remove this later - just to test-compile the resulted files from the compiler PHONY += compile diff --git a/iotjava/iotpolicy/IoTCompiler.java b/iotjava/iotpolicy/IoTCompiler.java index 0f696be..4cd5418 100644 --- a/iotjava/iotpolicy/IoTCompiler.java +++ b/iotjava/iotpolicy/IoTCompiler.java @@ -342,6 +342,17 @@ public class IoTCompiler { } + /** + * HELPER: updateIntfaceObjIdMap() updates the mapping between new interface and object Id + */ + private void updateIntfaceObjIdMap(String intface, String newIntface) { + + Integer objId = mapIntfaceObjId.get(intface); + mapNewIntfaceObjId.put(newIntface, objId); + mapIntfaceObjId.put(intface, objId++); + } + + /** * generateJavaInterfaces() generate stub interfaces based on the methods list in Java */ @@ -369,6 +380,7 @@ public class IoTCompiler { // Write interface header println(""); println("public interface " + newIntface + " {\n"); + updateIntfaceObjIdMap(intface, newIntface); // Write methods writeMethodJavaInterface(methods, intDecl); println("}"); @@ -419,8 +431,8 @@ public class IoTCompiler { // Get the object Id Integer objId = mapIntfaceObjId.get(intface); println("private final static int objectId = " + objId + ";"); - mapNewIntfaceObjId.put(newIntface, objId); - mapIntfaceObjId.put(intface, objId++); + //mapNewIntfaceObjId.put(newIntface, objId); + //mapIntfaceObjId.put(intface, objId++); if (callbackExist) { // We assume that each class only has one callback interface for now Iterator it = callbackClasses.iterator(); @@ -511,14 +523,17 @@ public class IoTCompiler { /** * HELPER: writeInitCallbackJavaStub() writes callback initialization in stub */ - private void writeInitCallbackJavaStub(String intface, InterfaceDecl intDecl) { + private void writeInitCallbackJavaStub(String intface, InterfaceDecl intDecl, boolean isGenCallbackStub) { println("public void ___initCallBack() {"); // Generate main thread for callbacks println("Thread thread = new Thread() {"); println("public void run() {"); println("try {"); - println("rmiObj = new IoTRMIObject(ports[0]);"); + if (isGenCallbackStub) // Use the second port for a _CallbackStub class (callback in callback) + println("rmiObj = new IoTRMIObject(ports[1]);"); + else + println("rmiObj = new IoTRMIObject(ports[0]);"); println("while (true) {"); println("byte[] method = rmiObj.getMethodBytes();"); writeJavaMethodCallbackPermission(intface); @@ -544,8 +559,8 @@ public class IoTCompiler { int methodNumId = intDecl.getHelperMethodNumId(method); println("int methodId = " + methodNumId + ";"); println("Class retType = void.class;"); - println("Class[] paramCls = new Class[] { int.class, String.class, int.class };"); - println("Object[] paramObj = new Object[] { ports[0], callbackAddress, 0 };"); + println("Class[] paramCls = new Class[] { int[].class, String.class, int.class };"); + println("Object[] paramObj = new Object[] { ports, callbackAddress, 0 };"); println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);"); println("}\n"); } @@ -982,10 +997,10 @@ public class IoTCompiler { String param = methParams.get(i); if (isArrayOrList(paramType, param)) { // Generate loop println("for (" + getGenericType(paramType) + " cb : " + getSimpleIdentifier(param) + ") {"); - println(callbackType + "_CallbackSkeleton skel" + i + " = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);"); + println(callbackType + "_CallbackSkeleton skel" + i + " = new " + callbackType + "_CallbackSkeleton(cb, callbackAddress, objIdCnt++);"); } else println(callbackType + "_CallbackSkeleton skel" + i + " = new " + callbackType + "_CallbackSkeleton(" + - getSimpleIdentifier(param) + ", objIdCnt++);"); + getSimpleIdentifier(param) + ", callbackAddress, objIdCnt++);"); println("listCallbackObj.add(skel" + i + ");"); if (isArrayOrList(paramType, param)) println("}"); @@ -1002,7 +1017,7 @@ public class IoTCompiler { /** * HELPER: writeMethodJavaStub() writes the methods of the stub class */ - private void writeMethodJavaStub(Collection methods, InterfaceDecl intDecl, Set callbackClasses) { + private void writeMethodJavaStub(Collection methods, InterfaceDecl intDecl, Set callbackClasses, boolean isGenCallbackStub) { boolean isDefined = false; for (String method : methods) { @@ -1037,7 +1052,7 @@ public class IoTCompiler { println("}\n"); // Write the init callback helper method if (isCallbackMethod && !isDefined) { - writeInitCallbackJavaStub(callbackType, intDecl); + writeInitCallbackJavaStub(callbackType, intDecl, isGenCallbackStub); isDefined = true; } } @@ -1079,7 +1094,7 @@ public class IoTCompiler { // Write constructor writeConstructorJavaStub(intface, newStubClass, callbackExist, callbackClasses); // Write methods - writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses); + writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses, false); println("}"); pw.close(); System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".java..."); @@ -1094,7 +1109,7 @@ public class IoTCompiler { private void writePropertiesJavaCallbackStub(String intface, String newIntface, boolean callbackExist, Set callbackClasses) { println("private IoTRMICall rmiCall;"); - println("private String address;"); + println("private String callbackAddress;"); println("private int[] ports;\n"); // Get the object Id println("private int objectId = 0;"); @@ -1121,16 +1136,17 @@ public class IoTCompiler { private void writeConstructorJavaCallbackStub(String intface, String newStubClass, boolean callbackExist, Set callbackClasses) { // TODO: If we want callback in callback, then we need to add address and port initializations - println("public " + newStubClass + "(IoTRMICall _rmiCall, int _objectId) throws Exception {"); + println("public " + newStubClass + "(IoTRMICall _rmiCall, String _callbackAddress, int _objectId, int[] _ports) throws Exception {"); + println("callbackAddress = _callbackAddress;"); println("objectId = _objectId;"); println("rmiCall = _rmiCall;"); + println("ports = _ports;"); if (callbackExist) { Iterator it = callbackClasses.iterator(); String callbackType = (String) it.next(); writeConstructorJavaPermission(intface); println("listCallbackObj = new ArrayList<" + callbackType + ">();"); println("___initCallBack();"); - println("// TODO: Add address and port initialization here if we want callback in callback!"); } println("}\n"); } @@ -1176,7 +1192,7 @@ public class IoTCompiler { writeConstructorJavaCallbackStub(intface, newStubClass, callbackExist, callbackClasses); // Write methods // TODO: perhaps need to generate callback for callback - writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses); + writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses, true); println("}"); pw.close(); System.out.println("IoTCompiler: Generated callback stub class " + newStubClass + ".java..."); @@ -1193,10 +1209,12 @@ public class IoTCompiler { println("private " + intface + " mainObj;"); //println("private int ports;"); println("private IoTRMIObject rmiObj;\n"); + println("private String callbackAddress;"); // Callback if (callbackExist) { println("private static int objIdCnt = 0;"); println("private IoTRMICall rmiCall;"); + println("private int[] ports;\n"); } writePropertiesJavaPermission(intface, intDecl); println("\n"); @@ -1239,8 +1257,9 @@ public class IoTCompiler { */ private void writeConstructorJavaSkeleton(String newSkelClass, String intface, InterfaceDecl intDecl, Collection methods, boolean callbackExist) { - println("public " + newSkelClass + "(" + intface + " _mainObj, int _port) throws Exception {"); + println("public " + newSkelClass + "(" + intface + " _mainObj, String _callbackAddress, int _port) throws Exception {"); println("mainObj = _mainObj;"); + println("callbackAddress = _callbackAddress;"); println("rmiObj = new IoTRMIObject(_port);"); // Generate permission control initialization writeConstructorJavaPermission(intface); @@ -1282,9 +1301,13 @@ public class IoTCompiler { println("public void ___regCB(IoTRMIObject rmiObj) throws IOException {"); else println("public void ___regCB() throws IOException {"); - print("Object[] paramObj = rmiObj.getMethodParams(new Class[] { int.class, String.class, int.class },"); + print("Object[] paramObj = rmiObj.getMethodParams(new Class[] { int[].class, String.class, int.class },"); println("new Class[] { null, null, null });"); - println("rmiCall = new IoTRMICall((int) paramObj[0], (String) paramObj[1], (int) paramObj[2]);"); + println("ports = (int[]) paramObj[0];"); + if (callbackSkeleton) // If this is a callback skeleton then use the other port + println("rmiCall = new IoTRMICall((int) paramObj[0], (String) paramObj[1], ports[1]);"); + else + println("rmiCall = new IoTRMICall((int) paramObj[0], (String) paramObj[1], ports[0]);"); println("}\n"); } @@ -1354,7 +1377,7 @@ public class IoTCompiler { println("int numStubs" + i + " = (int) paramObj[" + offsetPfx + i + "];"); println("List<" + exchParamType + "> stub" + i + " = new ArrayList<" + exchParamType + ">();"); } else { - println(exchParamType + " stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);"); + println(exchParamType + " stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, callbackAddress, objIdCnt, ports);"); println("objIdCnt++;"); } } @@ -1363,12 +1386,12 @@ public class IoTCompiler { String exchParamType = checkAndGetParamClass(getGenericType(paramType)); if (isArray(param)) { println("for (int objId = 0; objId < numStubs" + i + "; objId++) {"); - println("stub" + i + "[objId] = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);"); + println("stub" + i + "[objId] = new " + exchParamType + "_CallbackStub(rmiCall, callbackAddress, objIdCnt, ports);"); println("objIdCnt++;"); println("}"); } else if (isList(paramType)) { println("for (int objId = 0; objId < numStubs" + i + "; objId++) {"); - println("stub" + i + ".add(new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt));"); + println("stub" + i + ".add(new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt, ports));"); println("objIdCnt++;"); println("}"); } @@ -2164,10 +2187,13 @@ public class IoTCompiler { println("private " + intface + " mainObj;"); // For callback skeletons, this is its own object Id println("private int objectId = 0;"); + println("private String callbackAddress;"); // Callback if (callbackExist) { + println("private static int objIdCnt = 0;"); println("private IoTRMICall rmiCall;"); + println("private int[] ports;\n"); } println("\n"); } @@ -2178,7 +2204,8 @@ public class IoTCompiler { */ private void writeConstructorJavaCallbackSkeleton(String newSkelClass, String intface, InterfaceDecl intDecl, Collection methods) { - println("public " + newSkelClass + "(" + intface + " _mainObj, int _objectId) throws Exception {"); + println("public " + newSkelClass + "(" + intface + " _mainObj, String _callbackAddress, int _objectId) throws Exception {"); + println("callbackAddress = _callbackAddress;"); println("mainObj = _mainObj;"); println("objectId = _objectId;"); println("}\n"); @@ -2542,6 +2569,7 @@ public class IoTCompiler { println("#ifndef _" + newIntface.toUpperCase() + "_HPP__"); println("#define _" + newIntface.toUpperCase() + "_HPP__"); println("#include "); + updateIntfaceObjIdMap(intface, newIntface); // Pass in set of methods and get import classes Set methods = intMeth.getValue(); Set includeClasses = getIncludeClasses(methods, intDecl, intface, false); @@ -2566,7 +2594,7 @@ public class IoTCompiler { /** * HELPER: writeMethodCplusStub() writes the methods of the stub */ - private void writeMethodCplusStub(Collection methods, InterfaceDecl intDecl, Set callbackClasses) { + private void writeMethodCplusStub(Collection methods, InterfaceDecl intDecl, Set callbackClasses, boolean isGenCallbackStub) { boolean isDefined = false; for (String method : methods) { @@ -2601,7 +2629,7 @@ public class IoTCompiler { println("}\n"); // Write the init callback helper method if (isCallbackMethod && !isDefined) { - writeInitCallbackCplusStub(callbackType, intDecl); + writeInitCallbackCplusStub(callbackType, intDecl, isGenCallbackStub); writeInitCallbackSendInfoCplusStub(intDecl); isDefined = true; } @@ -2625,12 +2653,12 @@ public class IoTCompiler { String param = methParams.get(i); if (isArrayOrList(paramType, param)) { // Generate loop println("for (" + getGenericType(paramType) + "* cb : " + getSimpleIdentifier(param) + ") {"); - println(callbackType + "_CallbackSkeleton* skel" + i + " = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);"); + println(callbackType + "_CallbackSkeleton* skel" + i + " = new " + callbackType + "_CallbackSkeleton(cb, callbackAddress, objIdCnt++);"); isArrayOrList = true; callbackParam = getSimpleIdentifier(param); } else println(callbackType + "_CallbackSkeleton* skel" + i + " = new " + callbackType + "_CallbackSkeleton(" + - getSimpleIdentifier(param) + ", objIdCnt++);"); + getSimpleIdentifier(param) + ", callbackAddress, objIdCnt++);"); println("vecCallbackObj.push_back(skel" + i + ");"); if (isArrayOrList) println("}"); @@ -3012,8 +3040,8 @@ public class IoTCompiler { // Get the object Id Integer objId = mapIntfaceObjId.get(intface); println("const static int objectId = " + objId + ";"); - mapNewIntfaceObjId.put(newIntface, objId); - mapIntfaceObjId.put(intface, objId++); + //mapNewIntfaceObjId.put(newIntface, objId); + //mapIntfaceObjId.put(intface, objId++); if (callbackExist) { // We assume that each class only has one callback interface for now Iterator it = callbackClasses.iterator(); @@ -3100,11 +3128,14 @@ public class IoTCompiler { /** * HELPER: writeInitCallbackCplusStub() writes the initialization of callback */ - private void writeInitCallbackCplusStub(String intface, InterfaceDecl intDecl) { + private void writeInitCallbackCplusStub(String intface, InterfaceDecl intDecl, boolean isGenCallbackStub) { println("void ___initCallBack() {"); println("bool bResult = false;"); - println("rmiObj = new IoTRMIObject(ports[0], &bResult);"); + if (isGenCallbackStub) // Use the second port for a _CallbackStub class (callback in callback) + println("rmiObj = new IoTRMIObject(ports[1], &bResult);"); + else + println("rmiObj = new IoTRMIObject(ports[0], &bResult);"); println("while (true) {"); println("char* method = rmiObj->getMethodBytes();"); writeCplusMethodCallbackPermission(intface); @@ -3154,9 +3185,9 @@ public class IoTCompiler { int methodNumId = intDecl.getHelperMethodNumId(method); println("int methodId = " + methodNumId + ";"); println("string retType = \"void\";"); - println("string paramCls[] = { \"int\", \"String\", \"int\" };"); + println("string paramCls[] = { \"int*\", \"String\", \"int\" };"); println("int rev = 0;"); - println("void* paramObj[] = { &ports[0], &callbackAddress, &rev };"); + println("void* paramObj[] = { &ports, &callbackAddress, &rev };"); println("void* retObj = NULL;"); println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);"); println("}\n"); @@ -3202,7 +3233,7 @@ public class IoTCompiler { writeConstructorCplusStub(newStubClass, callbackExist, callbackClasses); writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses); // Write methods - writeMethodCplusStub(methods, intDecl, callbackClasses); + writeMethodCplusStub(methods, intDecl, callbackClasses, false); print("}"); println(";"); if (callbackExist) { Iterator it = callbackClasses.iterator(); @@ -3238,7 +3269,7 @@ public class IoTCompiler { println("vector<" + callbackType + "*> vecCallbackObj;"); println("static int objIdCnt;"); // TODO: Need to initialize address and ports if we want to have callback-in-callback - println("string address;"); + println("string callbackAddress;"); println("vector ports;\n"); writePropertiesCplusPermission(callbackType); } @@ -3251,9 +3282,10 @@ public class IoTCompiler { */ private void writeConstructorCplusCallbackStub(String newStubClass, boolean callbackExist, Set callbackClasses) { - println(newStubClass + "(IoTRMICall* _rmiCall, int _objectId) {"); + println(newStubClass + "(IoTRMICall* _rmiCall, int _objectId, vector _ports) {"); println("objectId = _objectId;"); println("rmiCall = _rmiCall;"); + println("ports = _ports;"); if (callbackExist) { Iterator it = callbackClasses.iterator(); String callbackType = (String) it.next(); @@ -3304,7 +3336,7 @@ public class IoTCompiler { writeConstructorCplusCallbackStub(newStubClass, callbackExist, callbackClasses); writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses); // Write methods - writeMethodCplusStub(methods, intDecl, callbackClasses); + writeMethodCplusStub(methods, intDecl, callbackClasses, true); println("};"); if (callbackExist) { Iterator it = callbackClasses.iterator(); @@ -3338,6 +3370,7 @@ public class IoTCompiler { println("static int objIdCnt;"); println("vector<" + exchangeType + "*> vecCallbackObj;"); println("IoTRMICall *rmiCall;"); + println("vector ports;"); } println("IoTRMIObject *rmiObj;\n"); // Keep track of object Ids of all stubs registered to this interface @@ -3491,14 +3524,17 @@ public class IoTCompiler { else println("void ___regCB() {"); println("int numParam = 3;"); - println("int param1 = 0;"); + println("vector param1;"); println("string param2 = \"\";"); println("int param3 = 0;"); - println("string paramCls[] = { \"int\", \"String\", \"int\" };"); + println("string paramCls[] = { \"int*\", \"String\", \"int\" };"); println("void* paramObj[] = { ¶m1, ¶m2, ¶m3 };"); println("rmiObj->getMethodParams(paramCls, numParam, paramObj);"); println("bool bResult = false;"); - println("rmiCall = new IoTRMICall(param1, param2.c_str(), param3, &bResult);"); + if (callbackSkeleton) + println("rmiCall = new IoTRMICall(param1[1], param2.c_str(), param3, &bResult);"); + else + println("rmiCall = new IoTRMICall(param1[0], param2.c_str(), param3, &bResult);"); println("}\n"); } @@ -3577,13 +3613,13 @@ public class IoTCompiler { if (isArrayOrList(paramType, param)) { println("vector<" + exchParamType + "*> stub" + i + ";"); println("for (int objId = 0; objId < numStubs" + i + "; objId++) {"); - println(exchParamType + "* cb" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);"); + println(exchParamType + "* cb" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, callbackAddress, objIdCnt, ports);"); println("stub" + i + ".push_back(cb" + i + ");"); println("vecCallbackObj.push_back(cb" + i + ");"); println("objIdCnt++;"); println("}"); } else { - println(exchParamType + "* stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);"); + println(exchParamType + "* stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, callbackAddress, objIdCnt, ports);"); println("vecCallbackObj.push_back(stub" + i + ");"); println("objIdCnt++;"); } @@ -4232,6 +4268,7 @@ public class IoTCompiler { println("IoTRMICall* rmiCall;"); println("vector<" + exchangeType + "*> vecCallbackObj;"); println("static int objIdCnt;"); + println("vector ports;\n"); } println("\n"); } @@ -4628,13 +4665,14 @@ public class IoTCompiler { // Basically the compiler needs to parse the policy (and requires) files for callback class first private int getNewIntfaceObjectId(String newIntface) { - if (!mapNewIntfaceObjId.containsKey(newIntface)) { - throw new Error("IoTCompiler: Need to parse policy and requires files for callback class first! " + - "Please place the two files for callback class in front...\n"); - } else { +// if (!mapNewIntfaceObjId.containsKey(newIntface)) { +// throw new Error("IoTCompiler: Need to parse policy and requires files for callback class first! " + +// "Please place the two files for callback class in front...\n"); +// return -1; +// } else { int retObjId = mapNewIntfaceObjId.get(newIntface); return retObjId; - } +// } } diff --git a/iotjava/iotrmi/Java/IoTRMICall.java b/iotjava/iotrmi/Java/IoTRMICall.java index bf5d9dc..9211954 100644 --- a/iotjava/iotrmi/Java/IoTRMICall.java +++ b/iotjava/iotrmi/Java/IoTRMICall.java @@ -169,51 +169,4 @@ public class IoTRMICall { return retObj; } - - - public static void main(String[] args) throws Exception { - - String[] test = { "123", "456", "789" }; - byte[] b = IoTRMIUtil.getObjectBytes(test); - - Boolean[] test2 = new Boolean[] { true, false, false }; - byte[] b2 = IoTRMIUtil.getObjectBytes(test2); - - System.out.println(Arrays.toString(b)); - System.out.println(Arrays.toString(b2)); - - String[] c = (String[]) IoTRMIUtil.getParamObjectArray(String[].class, b); - System.out.println(Arrays.toString(c)); - - Boolean[] c2 = (Boolean[]) IoTRMIUtil.getParamObjectArray(Boolean[].class, b2); - System.out.println(Arrays.toString(c2)); - - IoTRMICall rmiCall = new IoTRMICall(1234, "localhost", 0); - byte[] retObjBytes = { 0, 0, 4, -46, 0, 0, 0, 10, 116, 101, 115, 116, 115, 116, 114, 105, 110, 103, 0, 0, 21, 56 }; - //Class[] retCls = new Class[] { int.class, String.class, int.class }; - Object[] retObj = rmiCall.getReturnObjects(retObjBytes, new Class[] { int.class, String.class, int.class }, - new Class[] { null, null, null }); - System.out.println("Ret object 1: " + retObj[0]); - System.out.println("Ret object 2: " + retObj[1]); - System.out.println("Ret object 3: " + retObj[2]); - - // List - /*List list = new ArrayList(); - list.add(12345678l); - list.add(23455432l); - list.add(34566543l); - - byte[] objBytes = IoTRMIUtil.getObjectBytes(list); - System.out.println(Arrays.toString(objBytes)); - Object obj = IoTRMIUtil.getParamObject(List.class, null, Long.class, objBytes); - - @SuppressWarnings("unchecked") - List listStr = (List) obj; - System.out.println("List: " + listStr.toString());*/ - - //@SuppressWarnings("unchecked") - //List listStr = (List) obj; - //System.out.println("List: " + listStr.toString()); - - } } diff --git a/iotjava/iotrmi/Java/IoTRMIObject.java b/iotjava/iotrmi/Java/IoTRMIObject.java index 54ffa6e..3f0c19c 100644 --- a/iotjava/iotrmi/Java/IoTRMIObject.java +++ b/iotjava/iotrmi/Java/IoTRMIObject.java @@ -55,7 +55,6 @@ public class IoTRMIObject { // Receive method info methodBytes = rmiServer.receiveBytes(methodBytes); - //System.out.println("Method: " + Arrays.toString(methodBytes)); return methodBytes; } @@ -236,16 +235,4 @@ public class IoTRMIObject { return retBytes; } - - - public static void main(String[] args) throws Exception { - - int port = 5010; - IoTRMIObject rmiObj = new IoTRMIObject(port); - - Class[] retCls = new Class[] { int.class, String.class, int.class }; - Object[] retObj = new Object[] { 1234, "teststring", 5432 }; - - System.out.println("Bytes: " + Arrays.toString(rmiObj.returnToBytes(retCls, retObj))); - } } diff --git a/iotjava/iotrmi/Java/IoTRMIUtil.java b/iotjava/iotrmi/Java/IoTRMIUtil.java index 170ff59..f593a7a 100644 --- a/iotjava/iotrmi/Java/IoTRMIUtil.java +++ b/iotjava/iotrmi/Java/IoTRMIUtil.java @@ -262,13 +262,6 @@ public class IoTRMIUtil { } else if ( (type == String[].class) || (type == String.class)) { retObj = (Object) byteArrayToStringArray(paramBytes); - //} else if (type.isArray()) { - // This is an array but it's more than 1 dimension, e.g. 2-dimensional, - // 3-dimensional, etc. - // for loop to check inner array perhaps using object - // then call this function recursively - // combine the result altogether - } else throw new Error("IoTRMIUtil: Unrecognizable type: " + type.getName()); @@ -303,15 +296,9 @@ public class IoTRMIUtil { // Arrays } else if (obj.getClass().isArray()) { retObjBytes = getArrayObjectBytes(obj); - // Set and its implementations - /*} else if (obj instanceof Set) { - retObjBytes = setToByteArray((Set) obj);*/ // List and its implementations } else if (obj instanceof List) { retObjBytes = listToByteArray((List) obj); - // Map and its implementations - /*} else if (obj instanceof Map) { - retObjBytes = mapToByteArray((Map) obj);*/ } else throw new Error("IoTRMIUtil: Unrecognizable object: " + obj.getClass()); @@ -366,40 +353,6 @@ public class IoTRMIUtil { } - // Collection data structures - /*public static byte[] setToByteArray(Set set) { - - // Find out the class of the type - Iterator it = set.iterator(); - Object[] arrObj = null; - Object obj = it.next(); - - if (obj instanceof Byte) { - arrObj = set.toArray(new Byte[set.size()]); - } else if (obj instanceof Short) { - arrObj = set.toArray(new Short[set.size()]); - } else if (obj instanceof Integer) { - arrObj = set.toArray(new Integer[set.size()]); - } else if (obj instanceof Long) { - arrObj = set.toArray(new Long[set.size()]); - } else if (obj instanceof Float) { - arrObj = set.toArray(new Float[set.size()]); - } else if (obj instanceof Double) { - arrObj = set.toArray(new Double[set.size()]); - } else if (obj instanceof Character) { - arrObj = set.toArray(new Character[set.size()]); - } else if (obj instanceof Boolean) { - arrObj = set.toArray(new Boolean[set.size()]); - } else if (obj instanceof String) { - arrObj = set.toArray(new String[set.size()]); - } else - throw new Error("IoTRMIUtil: Unrecognizable object: " + obj.getClass()); - - byte[] arrObjBytes = getArrayObjectBytes(arrObj); - return arrObjBytes; - }*/ - - public static byte[] listToByteArray(List list) { // Find out the class of the type @@ -433,132 +386,6 @@ public class IoTRMIUtil { } - // Convert keySet of a Map - /*public static byte[] mapKeyToByteArray(Map map) { - - // Map - // Find out the class of the type for K - Iterator it = map.keySet().iterator(); - Object[] arrObj = null; - Object obj = it.next(); - - if (obj instanceof Byte) { - arrObj = map.keySet().toArray(new Byte[map.size()]); - } else if (obj instanceof Short) { - arrObj = map.keySet().toArray(new Short[map.size()]); - } else if (obj instanceof Integer) { - arrObj = map.keySet().toArray(new Integer[map.size()]); - } else if (obj instanceof Long) { - arrObj = map.keySet().toArray(new Long[map.size()]); - } else if (obj instanceof Float) { - arrObj = map.keySet().toArray(new Float[map.size()]); - } else if (obj instanceof Double) { - arrObj = map.keySet().toArray(new Double[map.size()]); - } else if (obj instanceof Character) { - arrObj = map.keySet().toArray(new Character[map.size()]); - } else if (obj instanceof Boolean) { - arrObj = map.keySet().toArray(new Boolean[map.size()]); - } else if (obj instanceof String) { - arrObj = map.keySet().toArray(new String[map.size()]); - } else - throw new Error("IoTRMIUtil: Unrecognizable object: " + obj.getClass()); - byte[] arrObjBytes = getArrayObjectBytes(arrObj); - - return arrObjBytes; - } - - - // Convert entrySet of a Map - public static byte[] mapEntryToByteArray(Map map) { - - // Map - // Find out the class of the type for V - Iterator it = map.values().iterator(); - Object[] arrObj = null; - Object obj = it.next(); - - if (obj instanceof Byte) { - arrObj = map.values().toArray(new Byte[map.size()]); - } else if (obj instanceof Short) { - arrObj = map.values().toArray(new Short[map.size()]); - } else if (obj instanceof Integer) { - arrObj = map.values().toArray(new Integer[map.size()]); - } else if (obj instanceof Long) { - arrObj = map.values().toArray(new Long[map.size()]); - } else if (obj instanceof Float) { - arrObj = map.values().toArray(new Float[map.size()]); - } else if (obj instanceof Double) { - arrObj = map.values().toArray(new Double[map.size()]); - } else if (obj instanceof Character) { - arrObj = map.values().toArray(new Character[map.size()]); - } else if (obj instanceof Boolean) { - arrObj = map.values().toArray(new Boolean[map.size()]); - } else if (obj instanceof String) { - arrObj = map.values().toArray(new String[map.size()]); - } else - throw new Error("IoTRMIUtil: Unrecognizable object: " + obj.getClass()); - - byte[] arrObjBytes = getArrayObjectBytes(arrObj); - return arrObjBytes; - } - - - // Merge keySet and entrySet of a Map into one long byte array - public static byte[] mapToByteArray(Map map) { - - // Put map size in the packet - byte[] numEntries = intToByteArray(map.size()); - byte[] keySetBytes = mapKeyToByteArray(map); - byte[] entrySetBytes = mapEntryToByteArray(map); - byte[] mapBytes = new byte[INT_LEN + keySetBytes.length + entrySetBytes.length]; - // Copy the bytes - System.arraycopy(numEntries, 0, mapBytes, 0, INT_LEN); - System.arraycopy(keySetBytes, 0, mapBytes, INT_LEN, keySetBytes.length); - System.arraycopy(entrySetBytes, 0, mapBytes, (INT_LEN + keySetBytes.length), entrySetBytes.length); - - return mapBytes; - } - - - // Get a Set object from bytes - public static Object getParamSetObject(Class genericType, byte[] paramBytes) { - - Set retSet = new HashSet(); - Object retObj = null; - if (genericType == Byte.class) { - Byte[] retArr = byteArrayToByteArray(paramBytes); - Collections.addAll(retSet, retArr); - } else if (genericType == Short.class) { - Short[] retArr = byteArrayToShortArray(paramBytes); - Collections.addAll(retSet, retArr); - } else if (genericType == Integer.class) { - Integer[] retArr = byteArrayToIntegerArray(paramBytes); - Collections.addAll(retSet, retArr); - } else if (genericType == Long.class) { - Long[] retArr = byteArrayToLongArray(paramBytes); - Collections.addAll(retSet, retArr); - } else if (genericType == Float.class) { - Float[] retArr = byteArrayToFloatArray(paramBytes); - Collections.addAll(retSet, retArr); - } else if (genericType == Double.class) { - Double[] retArr = byteArrayToDoubleArray(paramBytes); - Collections.addAll(retSet, retArr); - } else if (genericType == Boolean.class) { - Boolean[] retArr = byteArrayToBooleanArray(paramBytes); - Collections.addAll(retSet, retArr); - } else if (genericType == Character.class) { - Character[] retArr = byteArrayToCharacterArray(paramBytes); - Collections.addAll(retSet, retArr); - } else if (genericType == String.class) { - String[] retArr = byteArrayToStringArray(paramBytes); - Collections.addAll(retSet, retArr); - } else - throw new Error("IoTRMIUtil: Unrecognizable object: " + genericType.getSimpleName()); - - return retSet; - }*/ - - // Get a List object from bytes public static Object getParamListObject(Class genericType, byte[] paramBytes) { @@ -598,32 +425,6 @@ public class IoTRMIUtil { } - // Get a Key array for Map object from bytes - /*public static Object getParamMapObject(Class genTypeKey, Class genTypeVal, byte[] paramBytes) { - - // The complete set of bytes always consists of all keys followed by all values - pairs - // Calculate number of elements - byte[] numElBytes = new byte[INT_LEN]; - System.arraycopy(paramBytes, 0, numElBytes, 0, INT_LEN); - int numEl = byteArrayToInt(numElBytes); - int keyLen = numEl * getTypeSize(genTypeKey); - int valLen = numEl * getTypeSize(genTypeVal); - byte[] prmKeyBytes = new byte[keyLen]; - byte[] prmValBytes = new byte[valLen]; - // Copy bytes - System.arraycopy(paramBytes, INT_LEN, prmKeyBytes, 0, keyLen); - System.arraycopy(paramBytes, (INT_LEN + keyLen), prmValBytes, 0, valLen); - // Get array of keys - Object[] retObjKey = (Object[]) getParamObjectArray(genTypeKey, prmKeyBytes); - Object[] retObjVal = (Object[]) getParamObjectArray(genTypeVal, prmValBytes); - // Put everything back to a Map - Map retMap = new HashMap(); - IoTRMITypes.arraysToMap(retMap, retObjKey, retObjVal); - - return retMap; - }*/ - - /** * Converters to byte array */ diff --git a/iotjava/iotruntime/slave/IoTSlave.java b/iotjava/iotruntime/slave/IoTSlave.java index 7db7ea7..a2def7c 100644 --- a/iotjava/iotruntime/slave/IoTSlave.java +++ b/iotjava/iotruntime/slave/IoTSlave.java @@ -211,9 +211,10 @@ public class IoTSlave { Class clsSkel = Class.forName(strObjSkelName); Class clsInt = Class.forName(STR_OBJ_CLS_PFX + "." + STR_INTERFACE_PFX + "." + sMessage.getObjectInterfaceName()); - Class[] clsSkelParams = { clsInt, int.class }; // Port number is integer + Class[] clsSkelParams = { clsInt, String.class, int.class }; // Port number is integer Constructor objSkelCons = clsSkel.getDeclaredConstructor(clsSkelParams); - Object objSkelParams[] = { objMainCls, iRMIStubPort }; + String callbackAddress = InetAddress.getLocalHost().getHostAddress(); // Callback address is this machine's address + Object objSkelParams[] = { objMainCls, callbackAddress, iRMIStubPort }; // Create a new thread for each skeleton Thread objectThread = new Thread(new Runnable() { public void run() { diff --git a/localconfig/iotpolicy/AmcrestCamera/amcrestcamera.pol b/localconfig/iotpolicy/AmcrestCamera/amcrestcamera.pol new file mode 100644 index 0000000..17b583e --- /dev/null +++ b/localconfig/iotpolicy/AmcrestCamera/amcrestcamera.pol @@ -0,0 +1,49 @@ +public interface Camera { + + public void init(); + public void start(); + public void stop(); + public byte[] getLatestFrame(); + public long getTimestamp(); + public List getSupportedResolutions(); + public boolean setResolution(Resolution _res); + public boolean setFPS(int _fps); + public int getMaxFPS(); + public int getMinFPS(); + public void registerCallback(CameraCallback _callbackTo); + + capability Initialize { + description = "Initialize object"; + method = "init()"; + method = "start()"; + method = "stop()"; + method = "registerCallback(CameraCallback _callbackTo)"; + } + + capability Frame { + description = "Latest frame and timestamp"; + method = "getLatestFrame()"; + method = "getTimestamp()"; + } + + capability Resolution { + description = "Manage resolutions"; + method = "getSupportedResolutions()"; + method = "setResolution(Resolution _res)"; + } + + capability FPS { + description = "Manage FPS"; + method = "setFPS(int _fps)"; + method = "getMaxFPS()"; + method = "getMinFPS()"; + } + + enum Resolution { + RES_1080P, + RES_720P, + RES_VGA + } +} + + diff --git a/localconfig/iotpolicy/AmcrestCamera/motiondetection.pol b/localconfig/iotpolicy/AmcrestCamera/motiondetection.pol new file mode 100644 index 0000000..95ace6f --- /dev/null +++ b/localconfig/iotpolicy/AmcrestCamera/motiondetection.pol @@ -0,0 +1,11 @@ +public interface CameraCallback { + + public void newCameraFrameAvailable(Camera _camera); + + capability Callback { + description = "Callback method"; + method = "newCameraFrameAvailable(Camera _camera)"; + } +} + + diff --git a/localconfig/iotpolicy/AmcrestCamera/motiondetection.req b/localconfig/iotpolicy/AmcrestCamera/motiondetection.req new file mode 100644 index 0000000..73f2f86 --- /dev/null +++ b/localconfig/iotpolicy/AmcrestCamera/motiondetection.req @@ -0,0 +1,3 @@ + +requires CameraCallback with Callback as interface CameraSmartCallback; + diff --git a/localconfig/iotpolicy/AmcrestCamera/smartlightscam.req b/localconfig/iotpolicy/AmcrestCamera/smartlightscam.req new file mode 100644 index 0000000..a547d72 --- /dev/null +++ b/localconfig/iotpolicy/AmcrestCamera/smartlightscam.req @@ -0,0 +1,3 @@ + +requires Camera with Initialize, Frame, Resolution, FPS as interface CameraSmart; + diff --git a/localconfig/iotpolicy/LabRoom/labroom.pol b/localconfig/iotpolicy/LabRoom/labroom.pol new file mode 100644 index 0000000..17f3bbd --- /dev/null +++ b/localconfig/iotpolicy/LabRoom/labroom.pol @@ -0,0 +1,11 @@ +public interface Room { + + public int getRoomID(); + + capability Basic { + description = "Get room ID"; + method = "getRoomID()"; + } +} + + diff --git a/localconfig/iotpolicy/LabRoom/roomsmart.req b/localconfig/iotpolicy/LabRoom/roomsmart.req new file mode 100644 index 0000000..71de3c9 --- /dev/null +++ b/localconfig/iotpolicy/LabRoom/roomsmart.req @@ -0,0 +1,3 @@ + +requires Room with Basic as interface RoomSmart; + diff --git a/localconfig/iotpolicy/LifxLightBulb/smartlightsbulb.req b/localconfig/iotpolicy/LifxLightBulb/smartlightsbulb.req new file mode 100644 index 0000000..e3ff561 --- /dev/null +++ b/localconfig/iotpolicy/LifxLightBulb/smartlightsbulb.req @@ -0,0 +1,3 @@ + +requires LightBulb with Initialize, Power, SetColorProperties, GetColorProperties, GetColorPropertiesRange as interface LightBulbSmart; + -- 2.34.1