timeofday hack, no sunrise/sunset calc yet
[svn42.git] / track-presence.py
old mode 100644 (file)
new mode 100755 (executable)
index 0d76030..abd529e
@@ -1,5 +1,6 @@
 #!/usr/bin/python
 # -*- coding: utf-8 -*-
+from __future__ import with_statement
 import os
 import os.path
 import sys
@@ -14,6 +15,7 @@ import select
 import subprocess
 import types
 import ConfigParser
+import traceback
 
 logger = logging.getLogger()
 logger.setLevel(logging.INFO)
@@ -39,14 +41,16 @@ class UWSConfig:
     self.config_parser.add_section('door')
     self.config_parser.set('door','cmd_socket',"/var/run/tuer/door_cmd.socket")
     self.config_parser.add_section('sensors')
-    self.config_parser.set('sensors','remote_cmd',"ssh -o PasswordAuthentication=no %RHOST% %RSHELL% %RSOCKET%")
-    self.config_parser.set('sensors','remote_host',"slug.realraum.at")
-    self.config_parser.set('sensors','remote_socket',"/var/run/tuer/door_cmd.socket")
-    self.config_parser.set('sensors','remote_shell',"serial")
+    self.config_parser.set('sensors','remote_cmd',"ssh -i /flash/tuer/id_rsa -o PasswordAuthentication=no -o StrictHostKeyChecking=no %RHOST% %RSHELL% %RSOCKET%")
+    self.config_parser.set('sensors','remote_host',"root@slug.realraum.at")
+    self.config_parser.set('sensors','remote_socket',"/var/run/powersensordaemon/cmd.sock")
+    self.config_parser.set('sensors','remote_shell',"usocket")
     self.config_parser.add_section('tracker')
-    self.config_parser.set('tracker','sec_wait_movement_after_door_closed',2.0)
-    self.config_parser.set('tracker','sec_general_movement_timeout',1800)
+    self.config_parser.set('tracker','sec_wait_movement_after_door_closed',"15.0")
+    self.config_parser.set('tracker','sec_general_movement_timeout',3600)
     self.config_parser.set('tracker','server_socket',"/var/run/tuer/presence.socket")
+    self.config_parser.set('tracker','photo_flashlight',950)
+    self.config_parser.set('tracker','photo_artif_light',150)
     self.config_parser.add_section('debug')
     self.config_parser.set('debug','enabled',"False")
     self.config_mtime=0
@@ -64,7 +68,7 @@ class UWSConfig:
       while self.currently_writing:
         self.finished_writing.wait()
       self.currently_reading+=1
-    
+
   def unguardReading(self):
     with self.lock:
       self.currently_reading-=1
@@ -138,29 +142,38 @@ class UWSConfig:
 
 ######## Status Listener Threads ############
 
-def trackSensorStatusThread(uwscfg,status_tracker):
+def trackSensorStatusThread(uwscfg,status_tracker,connection_listener):
   #RE_TEMP = re.compile(r'temp\d: (\d+\.\d+)')
-  RE_PHOTO = re.compile(r'photo\d: (\d+\.\d+)')
-  RE_MOVEMENT = re.compile(r'movement|button\d?')
+  RE_PHOTO = re.compile(r'photo\d: .*(\d+)')
+  RE_MOVEMENT = re.compile(r'movement|button\d?|PanicButton')
   RE_ERROR = re.compile(r'Error: (.+)')
   while True:
     uwscfg.checkConfigUpdates()
+    sshp = None
     try:
       cmd = uwscfg.sensors_remote_cmd.replace("%RHOST%",uwscfg.sensors_remote_host).replace("%RSHELL%",uwscfg.sensors_remote_shell).replace("%RSOCKET%",uwscfg.sensors_remote_socket).split(" ")
-      sshp = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=False)
-      time.sleep(1.5)
+      logging.debug("trackSensorStatusThread: Executing: "+" ".join(cmd))
+      sshp = subprocess.Popen(cmd, bufsize=1024, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False)
+      logging.debug("trackSensorStatusThread: pid %d: running=%d" % (sshp.pid,sshp.poll() is None))
       if not sshp.poll() is None:
-        raise Exception("trackSensorStatusThread: subprocess %d finished, returncode: %d" % (sshp.pid,sshp.returncode))
-      (stdoutdata, stderrdata) = sshp.communicate(input="listen movement\n")
-      (stdoutdata, stderrdata) = sshp.communicate(input="listen button\n")
-      (stdoutdata, stderrdata) = sshp.communicate(input="listen photo0\n")
+        raise Exception("trackSensorStatusThread: subprocess %d not started ?, returncode: %d" % (sshp.pid,sshp.returncode))
+      #sshp.stdin.write("listen movement\nlisten button\nlisten sensor\n")
+      time.sleep(5) #if we send listen bevor usocket is running, we will never get output
+      #sshp.stdin.write("listen all\n")
+      logging.debug("trackSensorStatusThread: send: listen movement, etc")
+      sshp.stdin.write("listen movement\n")
+      sshp.stdin.write("listen button\n")
+      sshp.stdin.write("listen sensor\n")
+      #sshp.stdin.write("sample temp0\n")
+      sshp.stdin.flush()
       while True:
-        line = sshp.stdout.readline()
-        logging.debug("Got Line: " + line)
-        if line == "":
-          raise Exception("EOF on Subprocess, daemon seems to have quit")
         if not sshp.poll() is None:
           raise Exception("trackSensorStatusThread: subprocess %d finished, returncode: %d" % (sshp.pid,sshp.returncode))
+        line = sshp.stdout.readline()
+        if len(line) < 1:
+          raise Exception("EOF on Subprocess, daemon seems to have quit, returncode: %d",sshp.returncode)
+        logging.debug("trackSensorStatusThread: Got Line: " + line)
+        connection_listener.distributeData(line)
         m = RE_MOVEMENT.match(line)
         if not m is None:
           status_tracker.movementDetected()
@@ -174,7 +187,8 @@ def trackSensorStatusThread(uwscfg,status_tracker):
           logging.error("trackSensorStatusThread: got: "+line) 
     except Exception, ex:
       logging.error("trackSensorStatusThread: "+str(ex)) 
-      if sshp.poll() is None:
+      traceback.print_exc(file=sys.stdout)
+      if not sshp is None and sshp.poll() is None:
         if sys.hexversion >= 0x020600F0:
           sshp.terminate()
         else:
@@ -189,13 +203,15 @@ def trackSensorStatusThread(uwscfg,status_tracker):
       time.sleep(5)  
   
 
-def trackDoorStatusThread(uwscfg, status_tracker):
+def trackDoorStatusThread(uwscfg, status_tracker,connection_listener):
   #socket.setdefaulttimeout(10.0) #affects all new Socket Connections (urllib as well)
   RE_STATUS = re.compile(r'Status: (\w+), idle')
   RE_REQUEST = re.compile(r'Request: (\w+) (?:Card )?(.+)')
   RE_ERROR = re.compile(r'Error: (.+)')
   while True:
     uwscfg.checkConfigUpdates()
+    conn=None
+    sockhandle=None      
     try:
       if not os.path.exists(uwscfg.door_cmd_socket):
         logging.debug("Socketfile '%s' not found, waiting 5 secs" % uwscfg.door_cmd_socket)
@@ -206,24 +222,35 @@ def trackDoorStatusThread(uwscfg, status_tracker):
       conn = os.fdopen(sockhandle.fileno())
       sockhandle.send("listen\n")
       sockhandle.send("status\n")
+      last_who=None
       while True:
         line = conn.readline()
-        logging.debug("Got Line: " + line)
+        logging.debug("trackDoorStatusThread: Got Line: " + line)
         
-        if line == "":
+        if len(line) < 1:
           raise Exception("EOF on Socket, daemon seems to have quit")
         
+        connection_listener.distributeData(line)
+        
         m = RE_STATUS.match(line)
         if not m is None:
-          (status,who) = m.group(1,2)
+          status = m.group(1)
           if status == "opened":
-            status_tracker.doorOpen(who)
+            status_tracker.doorOpen(last_who)
           if status == "closed":
-            status_tracker.doorClosed(who)
+            status_tracker.doorClosed(last_who)
+          last_who = None
+          continue
+        m = RE_REQUEST.match(line)
+        if not m is None:  
+          last_who = m.group(2)
+          continue
     except Exception, ex:
-      logging.error("main: "+str(ex)) 
+      logging.error("main: "+str(ex))
+      traceback.print_exc(file=sys.stdout) 
       try:
-        sockhandle.close()
+        if not sockhandle is None:
+          sockhandle.close()
       except:
         pass
       conn=None
@@ -237,10 +264,13 @@ class StatusTracker: #(threading.Thread):
     self.uwscfg=uwscfg
     self.status_change_handler = None
     #State locked by self.lock
+    self.door_open_previously=None
     self.door_open=False
     self.door_manual_switch_used=False
     self.last_door_operation_unixts=0
     self.last_movement_unixts=0
+    self.last_light_value=0
+    self.last_light_unixts=0
     self.lock=threading.Lock()
     #Notify State locked by self.presence_notify_lock
     self.last_somebody_present_result=False
@@ -252,19 +282,29 @@ class StatusTracker: #(threading.Thread):
     self.uwscfg.checkConfigUpdates()
     self.lock.acquire()
     self.door_open=True
-    self.door_manual_switch_used=(who is None or len(who) == 0)
-    self.last_door_operation_unixts=time.time()
+    if not self.door_open_previously is None:
+      self.door_manual_switch_used=(who is None or len(who) == 0)
+      self.last_door_operation_unixts=time.time()
+    if self.door_open != self.door_open_previously:
+      self.lock.release()
+      self.checkPresenceStateChangeAndNotify()
+      self.lock.acquire()
+      self.door_open_previously = self.door_open
     self.lock.release()
-    self.checkPresenceStateChangeAndNotify()
-
+    
   def doorClosed(self,who):
     self.uwscfg.checkConfigUpdates()
     self.lock.acquire()
     self.door_open=False
-    self.door_manual_switch_used=(who is None or len(who) == 0)
-    self.last_door_operation_unixts=time.time()
+    if not self.door_open_previously is None:
+      self.door_manual_switch_used=(who is None or len(who) == 0)
+      self.last_door_operation_unixts=time.time()
+    if self.door_open != self.door_open_previously:
+      self.lock.release()
+      self.checkPresenceStateChangeAndNotify()
+      self.lock.acquire()
+      self.door_open_previously = self.door_open
     self.lock.release()
-    self.checkPresenceStateChangeAndNotify()
 
   def movementDetected(self):
     self.uwscfg.checkConfigUpdates()
@@ -273,25 +313,41 @@ class StatusTracker: #(threading.Thread):
     self.lock.release()
     self.checkPresenceStateChangeAndNotify()
 
-  def currentLightLevel(self):
+  def currentLightLevel(self, value):
     self.uwscfg.checkConfigUpdates()
-    #...
+    self.last_light_unixts=time.time()
+    self.last_light_value=value;
     self.checkPresenceStateChangeAndNotify()
   
+  def checkLight(self, somebody_present=None):
+    if somebody_present is None:
+      somebody_present=self.somebodyPresent()
+    
+    if self.last_light_value > int(self.uwscfg.tracker_photo_flashlight):
+      return "Light: flashlight"
+    elif self.last_light_value > int(self.uwscfg.tracker_photo_artif_light):
+      if not somebody_present and self.last_light_unixts > self.last_door_operation_unixts:
+        return "Light: forgotten"
+      else:
+        return "Light: on"      
+    else:
+      return "Light: off"
+
+  
   #TODO: check brightness level from cam or an arduino sensor
   def somebodyPresent(self):
     global uwscfg
     with self.lock:
       if (self.door_open):
         return True
-      elif (time.time() - self.last_door_operation_unixts <= self.uwscfg.tracker_sec_wait_movement):
+      elif (time.time() - self.last_door_operation_unixts <= float(self.uwscfg.tracker_sec_wait_movement_after_door_closed)):
         #start timer, checkPresenceStateChangeAndNotify after tracker_sec_wait_movement
         if not self.timer is None:
           self.timer.cancel()
-        self.timer=threading.Timer(self.uwscfg.tracker_sec_wait_movement, self.checkPresenceStateChangeAndNotify)
+        self.timer=threading.Timer(float(self.uwscfg.tracker_sec_wait_movement_after_door_closed), self.checkPresenceStateChangeAndNotify)
         self.timer.start()
         return True
-      elif (self.last_movement_unixts > self.last_door_operation_unixts and time.time() - self.last_movement_unixts < self.uwscfg.tracker_sec_general_movement_timeout):
+      elif (self.last_movement_unixts > self.last_door_operation_unixts and (self.door_manual_switch_used or ( time.time() - self.last_movement_unixts < float(self.uwscfg.tracker_sec_general_movement_timeout)))):
         return True
       else:
         return False
@@ -319,15 +375,17 @@ class ConnectionListener:
   
   def statusString(self,somebody_present):
     if somebody_present:
-      return "Status: people present" + "\n"
+      return "Presence: yes" + "\n"
     else:
-      return "Status: room empty" + "\n"
+      return "Presence: no" + "\n"
   
   def updateStatus(self,somebody_present):
-    presence_status_data = self.statusString(somebody_present)
+    self.distributeData(self.statusString(somebody_present))
+    
+  def distributeData(self,data):
     with self.lock:
       for socket_to_send_to in self.client_sockets:
-        socket_to_send_to.send(presence_status_data)
+        socket_to_send_to.send(data)
     
   def serve(self):
     self.server_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
@@ -342,8 +400,7 @@ class ConnectionListener:
       for socket_to_read in ready_to_read:
         if socket_to_read == self.server_socket:
           newsocketconn, addr = self.server_socket.accept()
-          presence_status_data = self.statusString(self.status_tracker.somebodyPresent())
-          newsocketconn.send(presence_status_data)
+          newsocketconn.send(self.statusString(self.status_tracker.somebodyPresent()))
           with self.lock:
             self.client_sockets.append(newsocketconn)
         else:
@@ -378,12 +435,14 @@ else:
 
 #Status Tracker keeps track of stuff and derives peoples presence from current state
 status_tracker = StatusTracker(uwscfg)
+#ConnectionListener servers incoming socket connections and distributes status update
+connection_listener = ConnectionListener(uwscfg, status_tracker)
 #Thread listening for door status changes
-track_doorstatus_thread = threading.Thread(target=trackDoorStatusThread,args=(uwscfg,status_tracker),name="trackDoorStatusThread")
+track_doorstatus_thread = threading.Thread(target=trackDoorStatusThread,args=(uwscfg,status_tracker,connection_listener),name="trackDoorStatusThread")
 track_doorstatus_thread.start()
 #Thread listening for movement
-track_sensorstatus_thread = threading.Thread(target=trackSensorStatusThread,args=(uwscfg,status_tracker),name="trackSensorStatusThread")
+track_sensorstatus_thread = threading.Thread(target=trackSensorStatusThread,args=(uwscfg,status_tracker,connection_listener),name="trackSensorStatusThread")
 track_sensorstatus_thread.start()
-#ConnectionListener servers incoming socket connections and distributes status update
-connection_listener = ConnectionListener(uwscfg, status_tracker)
-connection_listener.serve()
\ No newline at end of file
+
+#main routine: serve connections
+connection_listener.serve()