1 package HomeSecurityController;
3 // Standard Java Packages
5 import java.util.Iterator;
6 import java.util.ArrayList;
7 import java.util.HashMap;
11 import java.util.HashSet;
12 import java.util.concurrent.atomic.AtomicBoolean;
13 import java.util.concurrent.ConcurrentHashMap;
16 import java.rmi.RemoteException;
17 import java.rmi.server.UnicastRemoteObject;
19 // IoT Runtime Packages
20 import iotruntime.slave.IoTSet;
21 import iotruntime.slave.IoTRelation;
22 import iotcode.annotation.*;
24 // IoT Driver Packages
25 import iotcode.interfaces.*;
27 // Checker annotations
28 //import iotchecker.qual.*;
30 /** Class Home Security Controller for the home security application benchmark
32 * @author Rahmadi Trimananda <rtrimana @ uci.edu>
36 public class HomeSecurityController implements SmartthingsSensorCallback {
41 private static final int MOTION_TIME_THRESHOLD = 60; // in seconds
42 private static final int CAMERA_FPS = 15;
43 private static final int CHECK_TIME_WAIT = 1; // in seconds
44 private static final int SECOND_TO_TURN_ON = 60; // in seconds
47 * IoT Sets and Relations
50 * 1) Multipurpose sensor (detect windows open/close) - Smartthings sensor
51 * 2) Motion sensor (detect motion in certain radius) - Smartthings sensor
52 * 3) Water leak sensor (detect leakage) - Smartthings sensor
53 * 4) Camera (detect motion)
54 * 5) Alarm (using ESP board) - assuming 1 house alarm
55 * 6) Room (object as place of device)
57 * Additionals (for more extensive home management)
58 * 7) Doorlock (detect open/locked)
59 * 8) Power outlet (detect on/off, monitor watt)
61 // This comprises multipurpose, motion, and water leak sensors
62 // TODO: Per 01/2017, doorlock and outlet are not ready, ESP board will be used for alarm
63 @config private IoTSet<SmartthingsSensorSmart> smartSensorsSet;
64 @config private IoTSet<CameraSmart> camSet;
65 @config private IoTSet<AlarmSmart> alarmSet;
66 @config private IoTSet<RoomSmart> roomSet;
67 //@config private IoTSet<DoorLock> doorlockSet;
68 //@config private IoTSet<Outlet> outletSet;
70 @config private IoTRelation<RoomSmart, SmartthingsSensorSmart> roomSensorRelation;
71 @config private IoTRelation<RoomSmart, CameraSmart> roomCameraRelation;
72 //@config private IoTRelation<RoomSmart, DoorLock> roomDoorLockRelation;
73 //@config private IoTRelation<RoomSmart, Outlet> roomOutletRelation;
75 /*******************************************************************************************************************************************
79 *******************************************************************************************************************************************/
80 long lastTimeChecked = 0;
82 private static int sensorId = 0;
84 /*******************************************************************************************************************************************
86 ** States data structures
88 *******************************************************************************************************************************************/
89 // Camera and motion detection
90 private Map<CameraSmart, MotionDetection> camMotionDetect =
91 new HashMap<CameraSmart, MotionDetection>();
92 // Smartthings sensors (true = motion, leakage, etc.)
93 private Map<Integer, Boolean> senDetectStatus =
94 new ConcurrentHashMap<Integer, Boolean>();
95 // Camera (true = motion)
96 private Map<CameraSmart, Boolean> camDetectStatus =
97 new HashMap<CameraSmart, Boolean>();
98 // Doorlock (true = open - not locked)
99 //private Map<DoorLock, Boolean> doorlockStatus =
100 // new HashMap<DoorLock, Boolean>();
101 // Outlet (true = on - outlet is used)
102 //private Map<Outlet, Boolean> outletStatus =
103 // new HashMap<Outlet, Boolean>();
106 private Map<Integer, Boolean> alarmStatus =
107 new HashMap<Integer, Boolean>();
109 public HomeSecurityController() {
114 /*******************************************************************************************************************************************
118 *******************************************************************************************************************************************/
121 /** Method to initialize Smartthings sensors
123 * @return [void] None.
125 private void initSmartthingsSensors(RoomSmart rm) {
127 // Get and init the IAS sensors for this specific room
128 HashSet<SmartthingsSensorSmart> sensors = roomSensorRelation.get(rm);
129 for (SmartthingsSensorSmart sen : sensors) {
132 // Initialize sensors
134 sen.setId(sensorId++);
135 System.out.println("DEBUG: Initialized smartthings sensor!");
136 } catch (Exception e) {
143 /** Method to initialize cameras
145 * @return [void] None.
147 private void initCameras(RoomSmart rm) {
149 // Get and init the cameras for this specific room
150 HashSet<CameraSmart> cameras = roomCameraRelation.get(rm);
151 // Setup the cameras, start them all and assign each one a motion detector
152 for (CameraSmart cam : camSet.values()) {
154 // Each camera will have a motion detector unique to it since the motion detection has state
155 MotionDetection mo = new MotionDetection(12, 0.5f, 10, 10);
157 // initialize the camera, might need to setup some stuff internally
160 // set the camera parameters.
161 cam.setFPS(CAMERA_FPS);
162 cam.setResolution(Resolution.RES_VGA);
164 // camera will call the motion detector directly with data not this controller
165 cam.registerCallback(mo);
167 // Start the camera (example is start the HTTP stream if it is a network camera)
169 System.out.println("DEBUG: Initialized camera!");
171 // Remember which motion detector is for what camera
172 camMotionDetect.put(cam, mo);
177 /** Method to initialize alarms
179 * @return [void] None.
181 private void initAlarms() {
183 // Get and init the alarm (this single alarm set can serve multiple zones / rooms)
184 Iterator alarmIt = alarmSet.iterator();
185 AlarmSmart alm = (AlarmSmart) alarmIt.next();
186 // init the alarm controller, do it here since it only needs to be done once per controller
189 System.out.println("DEBUG: Initialized alarm!");
190 } catch (Exception e) {
196 /** Method to initialize doorlocks
198 * @return [void] None.
200 private void initDoorLocks(RoomSmart rm) {
202 // Get and init the doorlocks for this specific room
203 /*HashSet<DoorLock> doorlocks = roomDoorLockRelation.get(rm);
204 for (DoorLock doorlock : doorlocks) {
207 // Initialize doorlocks
209 System.out.println("DEBUG: Initialized doorlock!");
210 } catch (Exception e) {
217 /** Method to initialize power outlets
219 * @return [void] None.
221 private void initOutlets(RoomSmart rm) {
223 // Get and init the outlets for this specific room
224 /*HashSet<Outlet> outlets = roomOutletRelation.get(rm);
225 for (Outlet outlet : outlets) {
228 // Initialize outlets
230 System.out.println("DEBUG: Initialized outlet!");
231 } catch (Exception e) {
238 /** Method to detect if a room has seen motion within the last few seconds (time specified as parameter).
239 * Checks all the motion detectors for the given room
241 * @param _room [RoomSmart] , Room of interest.
242 * @param _numberOfSeconds [int] , Number of seconds in the past that we consider recent.
243 * @param _upperThreshold [int] , Number of seconds as an upper bound before we turn off.
245 * @return [void] None.
247 private void updateCameraStatus(RoomSmart _room, int _numberOfSeconds) {
248 long currentTimeSeconds = (new Date()).getTime() / 1000;
250 // Loop through all the cameras in the room
251 for (CameraSmart cam : roomCameraRelation.get(_room)) {
252 long lastDetectedMotionSeconds = currentTimeSeconds;
254 Date motionTime = ((MotionDetection)camMotionDetect.get(cam)).getTimestampOfLastMotion();
256 // Motion was detected at least once
257 if (motionTime != null) {
258 lastDetectedMotionSeconds = motionTime.getTime() / 1000;
260 // motionTime == null means this is the initialization phase
262 camDetectStatus.put(cam, false);
265 // Did detect motion recently
266 if (Math.abs(currentTimeSeconds - lastDetectedMotionSeconds) < _numberOfSeconds) {
267 camDetectStatus.put(cam, true);
273 /** Method to update state data structures for Smartthings sensors
275 * @return [void] None.
277 public void newReadingAvailable(int _sensorId, int _value, boolean _activeValue) {
279 System.out.println("DEBUG: Sensor reading value: " + _value);
282 senDetectStatus.put(_sensorId, true);
286 senDetectStatus.put(_sensorId, false);
291 /** Method to update state data structures for doorlocks
293 * @return [void] None.
295 private void updateDoorLockStatus(RoomSmart rm) {
297 // Get and init the outlets for this specific room
298 /*HashSet<DoorLock> doorlocks = roomDoorLockRelation.get(rm);
299 for (DoorLock doorlock : doorlocks) {
301 // Change is detected! Set to true for report...
302 if(isChangeDetected()) {
304 doorlockStatus.put(doorlock, true);
307 doorlockStatus.put(doorlock, false);
313 /** Method to update state data structures for outlets
315 * @return [void] None.
317 private void updateOutletStatus(RoomSmart rm) {
319 // Get and init the outlets for this specific room
320 /*HashSet<Outlet> outlets = roomOutletRelation.get(rm);
321 for (Outlet outlet : outlets) {
323 // Change is detected! Set to true for report...
324 if(isChangeDetected()) {
326 outletStatus.put(outlet, true);
329 outletStatus.put(outlet, false);
335 /** Update the status of all devices
337 * @return [void] None.
339 private void updateUniversalStatus() {
341 // Check for motion in rooms and if there is motion then report
342 for (RoomSmart room : roomSet.values()) {
344 // Update status of camera
345 updateCameraStatus(room, MOTION_TIME_THRESHOLD);
347 // Update status of doorlocks
348 //updateDoorLockStatus(room);
350 // Update status of outlets
351 //updateOutletStatus(room);
356 /** Method to turn on alarms
358 * @return [void] None.
360 private void turnOnAlarms(int zoneId) {
362 // Get and init the alarm (this single alarm set can serve multiple zones / rooms)
363 Iterator alarmIt = alarmSet.iterator();
364 AlarmSmart alm = (AlarmSmart) alarmIt.next();
365 alm.setZone(zoneId, true, SECOND_TO_TURN_ON);
369 /** Method to turn off alarms
371 * @return [void] None.
373 private void turnOffAlarms(int zoneId) {
375 // Get and init the alarm (this single alarm set can serve multiple zones / rooms)
376 Iterator alarmIt = alarmSet.iterator();
377 AlarmSmart alm = (AlarmSmart) alarmIt.next();
378 // Turn this alarm off indefinitely
379 alm.setZone(zoneId, false, -1);
383 /** Check status of devices and turn on alarm accordingly
385 * Simple rule is whenever any sensor or camera detect something unusual
386 * (sensor/camera becomes active) then we sound the corresponding alarm.
387 * This means we send the signal to the right zone in the EspAlarm
389 * @return [void] None.
391 private void decideToTurnOnAlarm() {
395 // Check for motion in rooms and if there is motion then report
396 for (RoomSmart room : roomSet.values()) {
398 // Loop through all the cameras in the room
399 for (CameraSmart cam : roomCameraRelation.get(room)) {
401 // Get the right camera and the right detection status (true or false)
402 if (camDetectStatus.get(cam)) {
403 zoneId = room.getRoomID();
404 turnOnAlarms(zoneId);
405 System.out.println("DETECTION: Camera active in room: " + zoneId);
409 // Loop through all the cameras in the room
410 for (SmartthingsSensorSmart sensor : roomSensorRelation.get(room)) {
412 // Get the right sensor and the right detection status (true or false)
413 if (senDetectStatus.get(sensor.getId())) {
414 zoneId = room.getRoomID();
415 turnOnAlarms(zoneId);
416 System.out.println("DETECTION: Sensor active in room: " + zoneId);
423 /** Check status of devices and turn off alarm accordingly
425 * If everything (camera and sensors) is set back to normal
426 * then the system will turn off the alarm
428 * @return [void] None.
430 // TODO: Need to fix this part later
431 // TODO: Perhaps we should use a phone app to turn off the alarm
432 /*private void decideToTurnOffAlarm() {
434 // Check for motion in rooms and if there is motion then report
435 for (RoomSmart room : roomSet.values()) {
437 int zoneId = room.getRoomID();
438 // Loop through all the cameras in the room
439 for (CameraSmart cam : roomCameraRelation.get(room)) {
441 // Get the right camera and the right detection status (true or false)
442 if (camDetectStatus.get(cam)) // Camera still active so alarm is still on, so false for off-alarm status
444 alarmStatus.put(zoneId, false);
448 alarmStatus.put(zoneId, true);
452 // Loop through all the cameras in the room
453 for (SmartthingsSensor sensor : roomSensorRelation.get(room)) {
455 // Get the right sensor and the right detection status (true or false)
456 if (senDetectStatus.get(sensor.getId())) // Sensor still active so alarm is still on, so false for off-alarm status
458 alarmStatus.put(zoneId, false);
462 alarmStatus.put(zoneId, true);
466 // Turn on alarm in the right zone
467 for (Map.Entry<Integer, Boolean> alEnt : alarmStatus.entrySet()) {
468 if (alEnt.getValue()) // if this zone is true, that means we need to turn off its alarm
469 turnOffAlarms(alEnt.getKey());
474 /*******************************************************************************************************************************************
478 *******************************************************************************************************************************************/
480 /** Initialization method, called by the runtime (effectively the main of the controller)
481 * This method runs a continuous loop and is blocking
483 * @return [void] None;
487 // Iterate over the set of rooms
488 for (RoomSmart rm : roomSet.values()) {
490 // Init all Smartthings sensors
491 initSmartthingsSensors(rm);
496 // Init all doorlocks
506 // Run the main loop that will keep checking the sensors and cameras periodically
509 // Run this code every <specified time>
510 long currentTimeSeconds = (new Date()).getTime() / 1000;
511 if ((currentTimeSeconds - lastTimeChecked) > CHECK_TIME_WAIT) {
512 lastTimeChecked = currentTimeSeconds;
514 // Update the status of all devices
515 updateUniversalStatus();
517 // Decide to turn on alarm if any of the sensor/camera detects something unusual
518 decideToTurnOnAlarm();
520 // Decide to turn off alarm if every sensor/camera goes back to normal
521 //decideToTurnOffAlarm();
527 Thread.sleep(CHECK_TIME_WAIT * 100); // sleep for a tenth of the time
529 } catch (Exception e) {