public void init() throws InterruptedException {
for(LightBulbTest lifx : lifx_light_bulb.values()) {
- Thread thread = new Thread(new Runnable() {
- public void run() {
+ //Thread thread = new Thread(new Runnable() {
+ // public void run() {
lifx.init();
- }
- });
- thread.start();
+ // }
+ //});
+ //thread.start();
Thread.sleep(1000);
for (int i = 0; i < 5; i++) {
Thread.sleep(500);
}
- thread.join();
+ //thread.join();
}
}
}
include $(BASE)/common.mk
-all: interfaces annotation drivers Lifxtest
+all: interfaces annotation drivers Lifxtest SmartLights
PHONY += interfaces
interfaces:
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 {
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(byte latestFrame[], long timeStamp) {
+ mainObj.newCameraFrameAvailable(latestFrame, timeStamp);
}
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!");
- }
+ Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { byte[].class, long.class },
+ new Class<?>[] { null, null });
+ newCameraFrameAvailable((byte[]) paramObj[0], (long) paramObj[1]);
}
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!");
}
rmiCall = new IoTRMICall(_port, _skeletonAddress, _rev);
set0Allowed = new ArrayList<Integer>(Arrays.asList(object0Permission));
listCallbackObj = new ArrayList<CameraCallback>();
+ set0Allowed.add(-9999);
___initCallBack();
}
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) {
+ int methodId = IoTRMIObject.getMethodId(method);
+ if (!set0Allowed.contains(methodId)) {
+ throw new Error("Callback object for CameraCallback is not allowed to access method: " + methodId);
+ }
skel.invokeMethod(rmiObj);
} else {
throw new Error("CameraCallback: Object with Id " + objId + " not found!");
private IoTRMICall rmiCall;
private String callbackAddress;
private int[] ports;
-
private final static int objectId = 0;
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
+ 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 ../iotcode/interfaces/Resolution*.class
.PHONY: $(PHONY)
// counts the number of frames since a background image is added to algorithm
private int frameCounter = 0;
-
+ private CameraSmart _camera;
/*******************************************************************************************************************************************
**
*
* @return [void] None.
*/
- public void newCameraFrameAvailable(CameraSmart _camera) {
+ public void newCameraFrameAvailable(byte[] latestFrame, long timeStamp) {
BufferedImage img = null;
try {
// Parse the byte array into a Buffered Image
- InputStream in = new ByteArrayInputStream(_camera.getLatestFrame());
+ //InputStream in = new ByteArrayInputStream(_camera.getLatestFrame());
+ InputStream in = new ByteArrayInputStream(latestFrame);
img = ImageIO.read(in);
} catch (RemoteException e) {
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();
+ // timestamp from camera into timestamp buffer
+ long dateLong = timeStamp;
possibleDate = new Date(dateLong);
imageWriteLock.unlock(); // Never forget to unlock
@config private IoTSet<LightBulbSmart> mainRoomLightBulbs;
@config private IoTSet<CameraSmart> cameras;
-
/*
* IoT Sets of Things that are not devices such as rooms
*/
- @config private IoTSet<Room> rooms;
+ @config private IoTSet<RoomSmart> rooms;
/*
* IoT Relations
*/
- @config private IoTRelation<Room,CameraSmart> roomCameraRel;
- @config private IoTRelation<Room,LightBulbSmart> roomMainBulbRel;
+ @config private IoTRelation<RoomSmart,CameraSmart> roomCameraRel;
+ @config private IoTRelation<RoomSmart,LightBulbSmart> roomMainBulbRel;
/*
* The state that the room main lights are supposed to be in
*/
- Map<Room, Boolean> roomLightOnOffStatus =
- new HashMap<Room, Boolean>();
- Map<Room, ColorTemperature> roomLightColorTemperature =
- new HashMap<Room, ColorTemperature>();
+ Map<RoomSmart, Boolean> roomLightOnOffStatus =
+ new HashMap<RoomSmart, Boolean>();
+ Map<RoomSmart, ColorTemperature> roomLightColorTemperature =
+ new HashMap<RoomSmart, ColorTemperature>();
/*
* Motion detectors that are bound to specific cameras
/** 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 _room [RoomSmart] , RoomSmart 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) {
+ private boolean roomDidHaveMotionRecently(RoomSmart _room, int _numberOfSeconds) {
long currentTimeSeconds = (new Date()).getTime() / 1000;
// Loop through all the motion sensors in the room
long secondsSinceStartOfDay = currentTimeSeconds - (beginningOfToday.getTime() / 1000);
- for (Room room : rooms.values()) {
+ for (RoomSmart room : rooms.values()) {
// before 8:30 am
if (secondsSinceStartOfDay <= 30600) {
*/
private void setMainBulbs() throws RemoteException {
- for (Room room : rooms.values()) {
+ for (RoomSmart room : rooms.values()) {
// Lights in room should be turned off
if (!roomLightOnOffStatus.get(room)) {
*/
public void init() throws RemoteException, InterruptedException {
-
+ System.out.println("Initialized init()!");
// Initialize the rooms
- for (Room room : rooms.values()) {
+ for (RoomSmart 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));
}
-
+ System.out.println("Initialized rooms!");
// Setup the cameras, start them all and assign each one a motion detector
for (CameraSmart cam : cameras.values()) {
// Remember which motion detector is for what camera
camMotionDetect.put(cam, mo);
}
-
+ System.out.println("Initialized cameras!");
//Initialize the light-bulbs, will turn off the bulb
for (LightBulbSmart bulb : mainRoomLightBulbs.values()) {
+ System.out.println("Trying to init bulb?");
bulb.init();
+ System.out.println("Done init!");
Thread.sleep(1000);
}
+ System.out.println("Initialized bulbs!");
// Run the main loop that will keep check the bulbs and rooms periodically
while (true) {
lastTimeChecked = currentTimeSeconds;
// Check for motion in rooms and if there is motion then turn on the lights
- for (Room room : rooms.values()) {
+ for (RoomSmart room : rooms.values()) {
if (roomDidHaveMotionRecently(room, MOTION_TIME_THRESHOLD)) {
for (CameraSmartCallback c : callbackList) {
- c.newCameraFrameAvailable(this);
+ c.newCameraFrameAvailable(this.getLatestFrame(), this.getTimestamp());
}
} else {
--- /dev/null
+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.*;
+
+public class CameraSmartCallback_CallbackStub implements CameraSmartCallback {
+
+ private IoTRMICall rmiCall;
+ private String callbackAddress;
+ private int[] ports;
+
+ private int objectId = 0;
+
+
+ public CameraSmartCallback_CallbackStub(IoTRMICall _rmiCall, String _callbackAddress, int _objectId, int[] _ports) throws Exception {
+ callbackAddress = _callbackAddress;
+ objectId = _objectId;
+ rmiCall = _rmiCall;
+ ports = _ports;
+ }
+
+ public void newCameraFrameAvailable(byte latestFrame[], long timeStamp) {
+ int methodId = 0;
+ Class<?> retType = void.class;
+ Class<?>[] paramCls = new Class<?>[] { byte[].class, long.class };
+ Object[] paramObj = new Object[] { latestFrame, timeStamp };
+ rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);
+ }
+
+}
import iotrmi.Java.IoTRMIObject;
import iotcode.interfaces.*;
-import SmartLightsController.CameraSmartCallback_CallbackStub;
public class Camera_Skeleton implements Camera {
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]);
+ rmiCall = new IoTRMICall(ports[0], (String) paramObj[1], (int) paramObj[2]);
}
public void ___init() {
# Skeleton/original interface
INTERFACE_CLASS=LightBulb
# Stub
-INTERFACE_STUB_CLASS=LightBulbTest
+#INTERFACE_STUB_CLASS=LightBulbTest
+INTERFACE_STUB_CLASS=LightBulbSmart
private IoTRMIObject rmiObj;
private String callbackAddress;
- private final static int object0Id = 0; //LightBulbTest
- private static Integer[] object0Permission = { 2, 6, 1, 3, 4, 8, 0, 5, 7, 9 };
+ private final static int object0Id = 0; //LightBulbSmart
+ private static Integer[] object0Permission = { 2, 10, 1, 3, 11, 8, 12, 7, 13, 9, 6, 16, 17, 4, 0, 14, 15, 5 };
private static List<Integer> set0Allowed;
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
+ cd $(BIN_DIR)/iotcode/AmcrestCamera; $(JAR) $(JARFLAGS) AmcrestCamera.jar ../../iotcode/AmcrestCamera/*.class ../../iotcode/interfaces/Camera*.class ../../iotcode/interfaces/Resolution*.class
PHONY += labroom
labroom:
package iotcode.interfaces;
-import java.util.List;
-import java.util.ArrayList;
-
public interface CameraCallback {
- public void newCameraFrameAvailable(CameraSmart _camera);
+ public void newCameraFrameAvailable(byte latestFrame[], long timeStamp);
}
package iotcode.interfaces;
-import java.util.List;
-import java.util.ArrayList;
-
public interface CameraSmartCallback {
- public void newCameraFrameAvailable(Camera _camera);
+ public void newCameraFrameAvailable(byte latestFrame[], long timeStamp);
}
println("// Callback properties");
println("private IoTRMIObject rmiObj;");
println("List<" + callbackType + "> listCallbackObj;");
- println("private static int objIdCnt = 0;");
+ println("private int objIdCnt = 0;");
// Generate permission stuff for callback stubs
DeclarationHandler decHandler = mapIntDeclHand.get(callbackType);
InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(callbackType);
println("// Callback properties");
println("private IoTRMIObject rmiObj;");
println("List<" + callbackType + "> listCallbackObj;");
- println("private static int objIdCnt = 0;");
+ println("private int objIdCnt = 0;");
// Generate permission stuff for callback stubs
DeclarationHandler decHandler = mapIntDeclHand.get(callbackType);
InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(callbackType);
println("private String callbackAddress;");
// Callback
if (callbackExist) {
- println("private static int objIdCnt = 0;");
+ println("private int objIdCnt = 0;");
println("private IoTRMICall rmiCall;");
println("private int[] ports;\n");
}
// Callback
if (callbackExist) {
- println("private static int objIdCnt = 0;");
+ println("private int objIdCnt = 0;");
println("private IoTRMICall rmiCall;");
println("private int[] ports;\n");
}
*/
private IoTRMIUtil rmiUtil;
private IoTSocketClient rmiClient;
- //private List<String> listMethodId; // Map from method ID to signature
/**
// Send method info
byte[] methodBytes = methodToBytes(objectId, methodId, paramCls, paramObj);
- //System.out.println("Method RMICall: " + Arrays.toString(methodBytes));
try {
rmiClient.sendBytes(methodBytes);
- //System.out.println("Sent bytes RMICall!!!");
} catch (IOException ex) {
ex.printStackTrace();
throw new Error("IoTRMICall: Error when sending bytes - rmiClient.sendBytes()");
/**
* sendBytes() sends an array of bytes
*/
- public void sendBytes(byte vals[]) throws IOException
+ public synchronized void sendBytes(byte vals[]) throws IOException
{
int len = vals.length;
// Write the length first - convert to array of 4 bytes
/**
* receiveBytes() receives an array of bytes
*/
- public byte[] receiveBytes(byte val[]) throws IOException
+ public synchronized byte[] receiveBytes(byte val[]) throws IOException
{
int i;
int totalbytes = 0;
int numbytes;
+
// Wait until input is available
while(input.available() == 0);
// Read the maxlen first - read 4 bytes here
/**
* Close socket connection
*/
- public void close() throws IOException
+ public synchronized void close() throws IOException
{
sock.close();
}
/**
* Send ACK
*/
- public void sendAck() throws IOException
+ public synchronized void sendAck() throws IOException
{
int ack;
ack = 0;
/**
* Receive ACK
*/
- public void receiveAck() throws IOException
+ public synchronized void receiveAck() throws IOException
{
int ack;
ack = (int) input.read();
RuntimeOutput.print("Communication Port: " + hmComPort.get(iIndex), bVerbose);
RuntimeOutput.print("RMI Registry Port: " + hmRMIRegPort.get(iIndex), bVerbose);
RuntimeOutput.print("RMI Stub Port: " + hmRMIStubPort.get(iIndex), bVerbose);
+ RuntimeOutput.print("\n", bVerbose);
}
}
+ for(Integer i : hsCallbackPort)
+ RuntimeOutput.print("RMI callback Port: " + i, bVerbose);
+ RuntimeOutput.print("\n", bVerbose);
for(int iPort : hsDevicePort) {
-
RuntimeOutput.print("Device Port: " + iPort, bVerbose);
-
}
+ RuntimeOutput.print("\n", bVerbose);
}
}
int iNumCallbackPorts = Integer.parseInt(STR_NUM_CALLBACK_PORTS);
Integer[] rmiCallbackPorts = commHan.getCallbackPorts(strObjName, iNumCallbackPorts);
+
// Iterate over port numbers and set up policies
for (int i=0; i<iNumCallbackPorts; i++) {
routerConfig.configureRouterMainPolicies(strRouterAdd, strIoTSlaveControllerHostAdd, strIoTSlaveObjectHostAdd,
strObjClassName, strObjClassInterfaceName, strObjStubClsIntfaceName,
commHan.getRMIRegPort(strObjName), commHan.getRMIStubPort(strObjName),
commHan.getCallbackPorts(strObjName, iNumOfPorts));
-
// ROUTING POLICY: first and second controller objects in IoTRelation
routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strFirstIoTSlaveObjectHostAdd,
strSecondIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL);
// == COMMUNICATION WITH IOTSLAVE CONTROLLER TO FILL IN IOTRELATION (SECOND OBJECT)
commMasterToSlave(new MessageGetObject(IoTCommCode.GET_IOTRELATION_SECOND_OBJECT,
objSecObj.getIoTSlaveObjectHostAdd(), objSecObj.getObjectName(), objSecObj.getObjectClassName(),
- objSecObj.getObjectClassInterfaceName(), objInitInfo.getObjectStubClassInterfaceName(),
+ objSecObj.getObjectClassInterfaceName(), objSecObj.getObjectStubClassInterfaceName(),
objSecObj.getRMIRegistryPort(), objSecObj.getRMIStubPort(), objSecObj.getRMICallbackPorts()),
"Get IoTRelation second object!", inStream, outStream);
}
private Socket socket;
private ObjectOutputStream outStream;
private ObjectInputStream inStream;
+ private Map<String,Object> mapObjNameStub;
/**
* IoTSet object, e.g. IoTSet<ProximitySensor> proximity_sensors;
socket = null;
outStream = null;
inStream = null;
+ mapObjNameStub = new HashMap<String,Object>();
STR_JAR_FILE_PATH = null;
STR_OBJ_CLS_PFX = null;
// Translating into the actual Message class
MessageGetObject sMessage = (MessageGetObject) sIoTMasterMsg;
- // Instantiate the stub and put in the object
- String strObjStubName = sMainObjectName + "." + sMessage.getObjectStubInterfaceName() + STUB_CLASS_SUFFIX;
- RuntimeOutput.print("IoTSlave: Stub object: " + strObjStubName, BOOL_VERBOSE);
- Class<?> clsStub = Class.forName(strObjStubName); // Port number is integer
- Class[] clsStubParams = { int.class, String.class, String.class, int.class, int[].class };
- Constructor<?> objStubCons = clsStub.getDeclaredConstructor(clsStubParams);
- Integer[] portsInteger = sMessage.getRMICallbackPorts();
- int[] ports = Arrays.stream(portsInteger).mapToInt(Integer::intValue).toArray();
- int rev = 0;
- String callbackAddress = InetAddress.getLocalHost().getHostAddress(); // Callback address is this machine's address
- Object objStubParams[] = { sMessage.getRMIStubPort(), sMessage.getHostAddress(), callbackAddress,
- rev, ports };
- RuntimeOutput.print("IoTSlave: Creating RMI stub: " +
- sMessage.getHostAddress() + ":" + sMessage.getRMIRegPort() +
- " with callback address: " + callbackAddress + " and RMI stub port: " + sMessage.getRMIStubPort(), BOOL_VERBOSE);
- Object stubObj = objStubCons.newInstance(objStubParams);
- RuntimeOutput.print("IoTSlave: Object name: " + sMessage.getObjectName(), BOOL_VERBOSE);
- RuntimeOutput.print("IoTSlave: Stub address: " + callbackAddress, BOOL_VERBOSE);
- // Class conversion to interface class of this class,
- // e.g. ProximitySensorImpl has ProximitySensor interface
+ Object stubObjConv = null;
+ String strObjectName = sMessage.getObjectName();
String strObjClassInterfaceName = STR_OBJ_CLS_PFX + "." + STR_INTERFACE_PFX + "." +
sMessage.getObjectStubInterfaceName();
Class<?> clsInf = Class.forName(strObjClassInterfaceName);
- Object stubObjConv = clsInf.cast(stubObj);
+ if (mapObjNameStub.containsKey(strObjectName)) {
+ RuntimeOutput.print("IoTSlave: Getting back object on slave: " + strObjectName, BOOL_VERBOSE);
+ stubObjConv = clsInf.cast(mapObjNameStub.get(strObjectName));
+ } else {
+ // Instantiate the stub and put in the object
+ String strObjStubName = sMainObjectName + "." + sMessage.getObjectStubInterfaceName() + STUB_CLASS_SUFFIX;
+ Class<?> clsStub = Class.forName(strObjStubName); // Port number is integer
+ Class[] clsStubParams = { int.class, String.class, String.class, int.class, int[].class };
+ Constructor<?> objStubCons = clsStub.getDeclaredConstructor(clsStubParams);
+ Integer[] portsInteger = sMessage.getRMICallbackPorts();
+ int[] ports = Arrays.stream(portsInteger).mapToInt(Integer::intValue).toArray();
+
+ int rev = 0;
+ String callbackAddress = InetAddress.getLocalHost().getHostAddress(); // Callback address is this machine's address
+ Object objStubParams[] = { sMessage.getRMIStubPort(), sMessage.getHostAddress(), callbackAddress,
+ rev, ports };
+ RuntimeOutput.print("IoTSlave: Creating RMI stub: " +
+ sMessage.getHostAddress() + ":" + sMessage.getRMIRegPort() +
+ " with callback address: " + callbackAddress + " and RMI stub port: " + sMessage.getRMIStubPort(), BOOL_VERBOSE);
+ Object stubObj = objStubCons.newInstance(objStubParams);
+ // Class conversion to interface class of this class,
+ // e.g. ProximitySensorImpl has ProximitySensor interface
+ RuntimeOutput.print("IoTSlave: Registering new stub object: " + strObjectName, BOOL_VERBOSE);
+ mapObjNameStub.put(strObjectName, stubObj);
+ stubObjConv = clsInf.cast(stubObj);
+ }
return stubObjConv;
}
public interface CameraCallback {
- public void newCameraFrameAvailable(Camera _camera);
+ public void newCameraFrameAvailable(byte latestFrame[], long timeStamp);
capability Callback {
description = "Callback method";
- method = "newCameraFrameAvailable(Camera _camera)";
+ method = "newCameraFrameAvailable(byte latestFrame[], long timeStamp)";
}
}
VERBOSE=Yes
#Number of callback ports
-NUMBER_CALLBACK_PORTS=4
+NUMBER_CALLBACK_PORTS=1