Minor fixes in LifxLightBulb driver (not fully tested yet)
[iot2.git] / benchmarks / HomeSecurityController / HomeSecurityController.java
1 package HomeSecurityController;
2
3 // Standard Java Packages
4 import java.util.Date;
5 import java.util.Iterator;
6 import java.util.ArrayList;
7 import java.util.HashMap;
8 import java.util.List;
9 import java.util.Map;
10
11 import java.util.HashSet;
12 import java.util.concurrent.atomic.AtomicBoolean;
13 import java.util.concurrent.ConcurrentHashMap;
14
15 // RMI packages
16 import java.rmi.RemoteException;
17 import java.rmi.server.UnicastRemoteObject;
18
19 // IoT Runtime Packages
20 import iotruntime.slave.IoTSet;
21 import iotruntime.slave.IoTRelation;
22 import iotcode.annotation.*;
23
24 // IoT Driver Packages
25 import iotcode.interfaces.*;
26
27 // Checker annotations
28 //import iotchecker.qual.*;
29
30 /** Class Home Security Controller for the home security application benchmark
31  *
32  * @author      Rahmadi Trimananda <rtrimana @ uci.edu>
33  * @version     1.0
34  * @since       2016-12-14
35  */
36 public class HomeSecurityController implements SmartthingsSensorCallback {
37
38         /*
39          *  Constants
40          */
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
45         private static final int SECOND_TO_TURN_OFF = 1;                // in seconds
46
47         /**
48          *  IoT Sets and Relations
49          *  <p>
50          *  Devices involved:
51          *  1) Multipurpose sensor (detect windows open/close) - Smartthings sensor
52          *  2) Motion sensor (detect motion in certain radius) - Smartthings sensor
53          *  3) Water leak sensor (detect leakage) - Smartthings sensor
54          *  4) Camera (detect motion)
55          *  5) Alarm (using ESP board) - assuming 1 house alarm
56          *  6) Room (object as place of device)
57          *
58          *  Additionals (for more extensive home management)
59          *  7) Doorlock (detect open/locked)
60          *  8) Power outlet (detect on/off, monitor watt)
61          */
62         // This comprises multipurpose, motion, and water leak sensors
63         // TODO: Per 01/2017, doorlock and outlet are not ready, ESP board will be used for alarm
64         @config private IoTSet<SmartthingsSensorSmart> smartSensorsSet;
65         @config private IoTSet<CameraSmart> camSet;
66         @config private IoTSet<AlarmSmart> alarmSet;
67         @config private IoTSet<RoomSmart> roomSet;
68         //@config private IoTSet<DoorLock> doorlockSet;
69         //@config private IoTSet<Outlet> outletSet;
70
71         @config private IoTRelation<RoomSmart, SmartthingsSensorSmart> roomSensorRelation;
72         @config private IoTRelation<RoomSmart, CameraSmart> roomCameraRelation;
73         //@config private IoTRelation<RoomSmart, DoorLock> roomDoorLockRelation;
74         //@config private IoTRelation<RoomSmart, Outlet> roomOutletRelation;
75
76         /*******************************************************************************************************************************************
77         **
78         **  Variables
79         **
80         *******************************************************************************************************************************************/
81         long lastTimeChecked = 0;
82
83         private static int sensorId = 0;
84
85         /*******************************************************************************************************************************************
86         **
87         **  States data structures
88         **
89         *******************************************************************************************************************************************/
90         // Camera and motion detection
91         private Map<CameraSmart, MotionDetection> camMotionDetect =
92                 new HashMap<CameraSmart, MotionDetection>();
93         // Smartthings sensors (true = motion, leakage, etc.)
94         private Map<Integer, Boolean> senDetectStatus =
95                 new ConcurrentHashMap<Integer, Boolean>();
96         // Camera (true = motion)
97         private Map<CameraSmart, Boolean> camDetectStatus =
98                 new HashMap<CameraSmart, Boolean>();
99         // Doorlock (true = open - not locked)
100         //private Map<DoorLock, Boolean> doorlockStatus =
101         //      new HashMap<DoorLock, Boolean>();
102         // Outlet (true = on - outlet is used)
103         //private Map<Outlet, Boolean> outletStatus =
104         //      new HashMap<Outlet, Boolean>();
105
106         // Alarm status
107         private Map<Integer, Boolean> alarmStatus =
108                 new HashMap<Integer, Boolean>();
109
110         public HomeSecurityController() {
111
112         }
113
114
115         /*******************************************************************************************************************************************
116         **
117         **  Helper Methods
118         **
119         *******************************************************************************************************************************************/
120
121
122         /** Method to initialize Smartthings sensors
123          *
124          *   @return [void] None.
125          */
126         private void initSmartthingsSensors(RoomSmart rm) {
127
128                 // Get and init the IAS sensors for this specific room
129                 HashSet<SmartthingsSensorSmart> sensors = roomSensorRelation.get(rm);
130                 for (SmartthingsSensorSmart sen : sensors) {
131         
132                         try {
133                                 // Initialize sensors
134                                 sen.init();
135                                 System.out.println("DEBUG: Initialized smartthings sensor! ID: " + sensorId + " Room ID: " + rm.getRoomID());
136                                 senDetectStatus.put(sensorId, false);
137                                 System.out.println("DEBUG: Initialized sensor detection to false!");
138                                 sen.setId(sensorId++);
139                                 sen.registerCallback(this);
140                                 System.out.println("DEBUG: Registered sensor callback!");
141                         } catch (Exception e) {
142                                 e.printStackTrace();
143                         }
144                 }
145         }
146
147
148         /** Method to initialize cameras
149          *
150          *   @return [void] None.
151          */
152         private void initCameras(RoomSmart rm) {
153
154                 // Get and init the IAS sensors for this specific room
155                 HashSet<CameraSmart> cameras = roomCameraRelation.get(rm);
156                 // Setup the cameras, start them all and assign each one a motion detector
157                 for (CameraSmart cam : cameras) {
158
159                         // Each camera will have a motion detector unique to it since the motion detection has state
160                         MotionDetection mo = new MotionDetection(12, 0.5f, 10, 10);
161
162                         // initialize the camera, might need to setup some stuff internally
163                         cam.init();
164
165                         // set the camera parameters.
166                         cam.setFPS(CAMERA_FPS);
167                         cam.setResolution(Resolution.RES_VGA);
168
169                         // camera will call the motion detector directly with data not this controller
170                         cam.registerCallback(mo);
171
172                         // Start the camera (example is start the HTTP stream if it is a network camera)
173                         cam.start();
174                         System.out.println("DEBUG: Initialized camera!");
175
176                         // Remember which motion detector is for what camera
177                         camMotionDetect.put(cam, mo);
178
179                         // Initialize detection to false
180                         camDetectStatus.put(cam, false);
181                 }
182         }
183
184
185         /** Method to initialize alarms
186          *
187          *   @return [void] None.
188          */
189         private void initAlarms() {
190
191                 // Get and init the alarm (this single alarm set can serve multiple zones / rooms)
192                 Iterator alarmIt = alarmSet.iterator();
193                 AlarmSmart alm = (AlarmSmart) alarmIt.next();
194                 // init the alarm controller, do it here since it only needs to be done once per controller
195                 try {
196                         alm.init();
197                         System.out.println("DEBUG: Initialized alarm!");
198                         // TODO: Check that this initialization works for multiple times - might be that setZone() only works once!
199                         //for (RoomSmart room : roomSet.values()) {
200                         //      turnOffAlarms(room.getRoomID());
201                         //      System.out.println("DEBUG: Initialized alarm for room (turn off): " + room.getRoomID());
202                         //}
203                 } catch (Exception e) {
204                         e.printStackTrace();
205                 }
206         }
207
208
209         /** Method to initialize doorlocks
210          *
211          *   @return [void] None.
212          */
213         private void initDoorLocks(RoomSmart rm) {
214
215                 // Get and init the doorlocks for this specific room
216                 /*HashSet<DoorLock> doorlocks = roomDoorLockRelation.get(rm);
217                 for (DoorLock doorlock : doorlocks) {
218         
219                         try {
220                                 // Initialize doorlocks
221                                 doorlock.init();
222                                 System.out.println("DEBUG: Initialized doorlock!");
223                         } catch (Exception e) {
224                                 e.printStackTrace();
225                         }
226                 }*/
227         }
228
229
230         /** Method to initialize power outlets
231          *
232          *   @return [void] None.
233          */
234         private void initOutlets(RoomSmart rm) {
235
236                 // Get and init the outlets for this specific room
237                 /*HashSet<Outlet> outlets = roomOutletRelation.get(rm);
238                 for (Outlet outlet : outlets) {
239         
240                         try {
241                                 // Initialize outlets
242                                 outlet.init();
243                                 System.out.println("DEBUG: Initialized outlet!");
244                         } catch (Exception e) {
245                                 e.printStackTrace();
246                         }
247                 }*/
248         }
249
250
251         /** Method to detect if a room has seen motion within the last few seconds (time specified as parameter).
252          *   Checks all the motion detectors for the given room
253          *
254          *   @param _room            [RoomSmart] , Room of interest.
255          *   @param _numberOfSeconds [int]  , Number of seconds in the past that we consider recent.
256          *   @param _upperThreshold  [int]  , Number of seconds as an upper bound before we turn off.
257          *
258          *   @return [boolean] None.
259          */
260         private boolean roomDidHaveMotionRecently(RoomSmart _room, int _numberOfSeconds) {
261                 long currentTimeSeconds = (new Date()).getTime() / 1000;
262
263                 // Loop through all the cameras in the room
264                 for (CameraSmart cam : roomCameraRelation.get(_room)) {
265                         long lastDetectedMotionSeconds = currentTimeSeconds;
266
267                         Date motionTime = ((MotionDetection)camMotionDetect.get(cam)).getTimestampOfLastMotion();
268
269                         // Motion was detected at least once
270                         if (motionTime != null) {
271                                 lastDetectedMotionSeconds = motionTime.getTime() / 1000;
272                         } else {
273                                 // motionTime == null means this is the initialization phase
274                                 // so we put false
275                                 return false;
276                         }
277
278                         // Did detect motion recently
279                         if (Math.abs(currentTimeSeconds - lastDetectedMotionSeconds) < _numberOfSeconds) {
280                                 return true;
281                         }
282                 }
283
284                 return false;
285         }
286
287
288         /** Method to update state data structures for Smartthings sensors
289          *
290          *   @return [void] None.
291          */
292         public void newReadingAvailable(int _sensorId, int _value, boolean _activeValue) {
293
294                 System.out.println("DEBUG: Sensor reading value: " + _value);
295                 if(_activeValue) {
296                         System.out.println("DEBUG: Sensor is detecting something: " + _activeValue);
297                         senDetectStatus.put(_sensorId, true);
298
299                 } else {
300                         //System.out.println("DEBUG: Sensor is not detecting something: " + _activeValue);
301                         senDetectStatus.put(_sensorId, false);
302                 } 
303         }
304
305
306         /** Method to update state data structures for doorlocks
307          *
308          *   @return [void] None.
309          */
310         private void updateDoorLockStatus(RoomSmart rm) {
311
312                 // Get and init the outlets for this specific room
313                 /*HashSet<DoorLock> doorlocks = roomDoorLockRelation.get(rm);
314                 for (DoorLock doorlock : doorlocks) {
315         
316                         // Change is detected! Set to true for report...
317                         if(isChangeDetected()) {
318
319                                 doorlockStatus.put(doorlock, true);
320                         } else {
321
322                                 doorlockStatus.put(doorlock, false);
323                         }
324                 }*/
325         }
326
327
328         /** Method to update state data structures for outlets
329          *
330          *   @return [void] None.
331          */
332         private void updateOutletStatus(RoomSmart rm) {
333
334                 // Get and init the outlets for this specific room
335                 /*HashSet<Outlet> outlets = roomOutletRelation.get(rm);
336                 for (Outlet outlet : outlets) {
337         
338                         // Change is detected! Set to true for report...
339                         if(isChangeDetected()) {
340
341                                 outletStatus.put(outlet, true);
342                         } else {
343
344                                 outletStatus.put(outlet, false);
345                         }
346                 }*/
347         }
348
349
350         /** Update the status of all devices
351          *
352          *   @return [void] None.
353          */
354         private void updateUniversalStatus() {
355
356                 // Check for motion in rooms and if there is motion then report
357                 for (RoomSmart room : roomSet.values()) {
358
359                         // Update status of camera
360                         updateCameraStatus(room);
361
362                         // Update status of doorlocks
363                         //updateDoorLockStatus(room);
364
365                         // Update status of outlets
366                         //updateOutletStatus(room);
367                 }
368         }
369
370
371         /** Update the status of all devices
372          *
373          *   @return [void] None.
374          */
375         private void updateCameraStatus(RoomSmart room) {
376
377                 HashSet<CameraSmart> cameras = roomCameraRelation.get(room);
378                 if (roomDidHaveMotionRecently(room, MOTION_TIME_THRESHOLD)) {
379
380                         // Motion was detected
381                         System.out.println("DEBUG: Camera detected something!");
382                         for(CameraSmart cam : cameras)
383                                 camDetectStatus.put(cam, true);
384                 } else {
385
386                         // No motion was detected
387                         //System.out.println("DEBUG: Camera didn't detect anything!");
388                         for(CameraSmart cam : cameras)
389                                 camDetectStatus.put(cam, false);
390                 }
391         }
392
393         /** Method to turn on alarms
394          *
395          *   @return [void] None.
396          */
397         private void turnOnAlarms(int zoneId) {
398
399                 // Get and init the alarm (this single alarm set can serve multiple zones / rooms)
400                 Iterator alarmIt = alarmSet.iterator();
401                 AlarmSmart alm = (AlarmSmart) alarmIt.next();
402                 alm.setZone(zoneId, true, SECOND_TO_TURN_OFF);
403         }
404
405
406         /** Method to turn off alarms
407          *
408          *   @return [void] None.
409          */
410         private void turnOffAlarms(int zoneId) {
411
412                 // Get and init the alarm (this single alarm set can serve multiple zones / rooms)
413                 Iterator alarmIt = alarmSet.iterator();
414                 AlarmSmart alm = (AlarmSmart) alarmIt.next();
415                 // Turn this alarm off indefinitely
416                 alm.setZone(zoneId, false, SECOND_TO_TURN_ON);
417         }
418
419
420         /** Check status of devices and turn on alarm accordingly
421          *  <p>
422          *  Simple rule is whenever any sensor or camera detect something unusual
423          *      (sensor/camera becomes active) then we sound the corresponding alarm.
424          *  This means we send the signal to the right zone in the EspAlarm
425          *
426          *   @return [void] None.
427          */
428         private void decideToTurnOnAlarm() {
429
430                 int zoneId = 0;
431
432                 // Check for motion in rooms and if there is motion then report
433                 for (RoomSmart room : roomSet.values()) {
434
435                         // Loop through all the cameras in the room
436                         for (CameraSmart cam : roomCameraRelation.get(room)) {
437
438                                 // Get the right camera and the right detection status (true or false)
439                                 if (camDetectStatus.get(cam)) {
440                                         zoneId = room.getRoomID();
441                                         turnOnAlarms(zoneId);
442                                         System.out.println("DETECTION: Camera active in room: " + zoneId);
443                                 }
444                         }
445
446                         // Loop through all the cameras in the room
447                         for (SmartthingsSensorSmart sensor : roomSensorRelation.get(room)) {
448
449                                 // Get the right sensor and the right detection status (true or false)
450                                 //System.out.println("ABOUT TO DETECT: Reading sensor: " + sensor.getId());
451                                 if (senDetectStatus.get(sensor.getId())) {
452                                         zoneId = room.getRoomID();
453                                         turnOnAlarms(zoneId);
454                                         System.out.println("DETECTION: Sensor active in room: " + zoneId);
455                                         System.out.println("DETECTION: Detection by sensor: " + sensor.getId());
456                                 }
457                         }
458                 }
459         }
460
461
462         /** Check status of devices and turn off alarm accordingly
463          *  <p>
464          *  If everything (camera and sensors) is set back to normal
465          *  then the system will turn off the alarm
466          *
467          *   @return [void] None.
468          */
469         // TODO: Need to fix this part later
470         // TODO: Perhaps we should use a phone app to turn off the alarm
471         /*private void decideToTurnOffAlarm() {
472
473                 // Check for motion in rooms and if there is motion then report
474                 for (RoomSmart room : roomSet.values()) {
475
476                         int zoneId = room.getRoomID();
477                         // Loop through all the cameras in the room
478                         for (CameraSmart cam : roomCameraRelation.get(room)) {
479
480                                 // Get the right camera and the right detection status (true or false)
481                                 if (camDetectStatus.get(cam))   // Camera still active so alarm is still on, so false for off-alarm status
482
483                                         alarmStatus.put(zoneId, false);
484
485                                 else
486
487                                         alarmStatus.put(zoneId, true);
488                                 
489                         }
490
491                         // Loop through all the cameras in the room
492                         for (SmartthingsSensor sensor : roomSensorRelation.get(room)) {
493
494                                 // Get the right sensor and the right detection status (true or false)
495                                 if (senDetectStatus.get(sensor.getId()))        // Sensor still active so alarm is still on, so false for off-alarm status
496
497                                         alarmStatus.put(zoneId, false);
498
499                                 else
500
501                                         alarmStatus.put(zoneId, true);
502                         }
503                 }
504
505                 // Turn on alarm in the right zone
506                 for (Map.Entry<Integer, Boolean> alEnt : alarmStatus.entrySet()) {
507                         if (alEnt.getValue())   // if this zone is true, that means we need to turn off its alarm
508                                 turnOffAlarms(alEnt.getKey());
509                 }
510         }*/
511
512
513         /*******************************************************************************************************************************************
514         **
515         **  Public Methods
516         **
517         *******************************************************************************************************************************************/
518
519         /** Initialization method, called by the runtime (effectively the main of the controller)
520          *   This method runs a continuous loop and is blocking
521          *
522          *   @return [void] None;
523          */
524         public void init() {
525
526                 // Iterate over the set of rooms
527                 for (RoomSmart rm : roomSet.values()) {
528
529                         // Init all Smartthings sensors
530                         initSmartthingsSensors(rm);
531
532                         // Init all cameras
533                         initCameras(rm);
534
535                         // Init all doorlocks
536                         //initDoorLocks();
537
538                         // Init all outlets
539                         //initOutlets();
540                 }
541
542                 // Init all alarms
543                 initAlarms();
544
545                 System.out.println("DEBUG: Initialized all devices! Now starting detection loop!");
546
547                 // Run the main loop that will keep checking the sensors and cameras periodically
548                 while (true) {
549
550                         // Run this code every <specified time>
551                         long currentTimeSeconds = (new Date()).getTime() / 1000;
552                         if ((currentTimeSeconds - lastTimeChecked) > CHECK_TIME_WAIT) {
553                                 lastTimeChecked = currentTimeSeconds;
554
555                                 // Update the status of all devices
556                                 updateUniversalStatus();
557
558                                 // Decide to turn on alarm if any of the sensor/camera detects something unusual
559                                 decideToTurnOnAlarm();
560
561                                 // Decide to turn off alarm if every sensor/camera goes back to normal
562                                 //decideToTurnOffAlarm();
563
564                         } else {
565
566                                 try {
567
568                                         Thread.sleep(CHECK_TIME_WAIT * 100); // sleep for a tenth of the time
569
570                                 } catch (Exception e) {
571
572                                         e.printStackTrace();
573                                 }
574                         }
575
576                 }
577         }
578 }
579
580