Cleanup config in preparation for zookeeper-based dynamic configs.
[python_utils.git] / base_presence.py
index f18b870daceaa4e97cf47d5c7b68f90da1a2ed24..c4d61da3ca4687be7f0baa945cd684de0483552a 100755 (executable)
@@ -1,5 +1,14 @@
 #!/usr/bin/env python3
 
+# © Copyright 2021-2022, Scott Gasch
+
+"""This is a module dealing with trying to guess a person's location
+based on the location of certain devices (e.g. phones, laptops)
+belonging to that person.  It works with networks I run that log
+device MAC addresses active.
+
+"""
+
 import datetime
 import logging
 import re
@@ -23,7 +32,7 @@ cfg = config.add_commandline_args(
 )
 cfg.add_argument(
     "--presence_macs_file",
-    type=argparse_utils.valid_filename,
+    type=str,
     default="/home/scott/cron/persisted_mac_addresses.txt",
     metavar="FILENAME",
     help="The location of persisted_mac_addresses.txt to use.",
@@ -38,7 +47,15 @@ cfg.add_argument(
 
 
 class PresenceDetection(object):
+    """This is a module dealing with trying to guess a person's location
+    based on the location of certain devices (e.g. phones, laptops)
+    belonging to that person.  It works with networks I run that log
+    device MAC addresses active.
+    """
+
     def __init__(self) -> None:
+        """C'tor"""
+
         # Note: list most important devices first.
         self.devices_by_person: Dict[Person, List[str]] = {
             Person.SCOTT: [
@@ -75,6 +92,10 @@ class PresenceDetection(object):
         self.last_update: Optional[datetime.datetime] = None
 
     def maybe_update(self) -> None:
+        """Determine if our state is stale and needs to be updated and do
+        it, if so.
+        """
+
         if self.last_update is None:
             self.update()
         else:
@@ -90,71 +111,76 @@ class PresenceDetection(object):
                 self.update()
 
     def update(self) -> None:
+        """Unconditionally update our state."""
+
         self.dark_locations = set()
-        if self.run_location is Location.HOUSE:
-            self.update_from_house()
-        elif self.run_location is Location.CABIN:
-            self.update_from_cabin()
-        else:
-            raise Exception("Where the hell is this running?!")
+        self._update_house()
+        self._update_cabin()
         self.last_update = datetime.datetime.now()
 
-    def update_from_house(self) -> None:
+    @staticmethod
+    def _get_raw_data_via_ssh(location: Location) -> Optional[str]:
         from exec_utils import cmd
 
+        canonical = {
+            Location.HOUSE: '[email protected]',
+            Location.CABIN: '[email protected]',
+        }
         try:
-            persisted_macs = config.config['presence_macs_file']
-        except KeyError:
-            persisted_macs = '/home/scott/cron/persisted_mac_addresses.txt'
-        self.read_persisted_macs_file(persisted_macs, Location.HOUSE)
-        try:
-            raw = cmd(
-                "ssh [email protected] 'cat /home/scott/cron/persisted_mac_addresses.txt'",
-                timeout_seconds=10.0,
+            return cmd(
+                f"ssh {canonical[location]} 'cat /home/scott/cron/persisted_mac_addresses.txt'",
+                timeout_seconds=30.0,
             )
-            self.parse_raw_macs_file(raw, Location.CABIN)
-        except Exception as e:
-            logger.exception(e)
-            msg = "Can't see the cabin right now; presence detection impared."
-            warnings.warn(msg)
-            logger.warning(msg, stacklevel=2)
-            self.dark_locations.add(Location.CABIN)
+        except Exception:
+            return None
 
-    def update_from_cabin(self) -> None:
-        from exec_utils import cmd
+    def _get_raw_data(self, location: Location) -> Optional[str]:
+        from os.path import exists
 
-        try:
-            persisted_macs = config.config['presence_macs_file']
-        except KeyError:
-            persisted_macs = '/home/scott/cron/persisted_mac_addresses.txt'
-        self.read_persisted_macs_file(persisted_macs, Location.CABIN)
-        try:
-            raw = cmd(
-                "ssh [email protected] 'cat /home/scott/cron/persisted_mac_addresses.txt'",
-                timeout_seconds=10.0,
+        if self.run_location == location:
+            persisted_macs = config.config.get(
+                'presence_macs_file', '/home/scott/cron/persisted_mac_addresses.txt'
             )
-            self.parse_raw_macs_file(raw, Location.HOUSE)
-        except Exception as e:
-            logger.exception(e)
+            if exists(persisted_macs):
+                with open(persisted_macs, 'r') as rf:
+                    return rf.read()
+            else:
+                return PresenceDetection._get_raw_data_via_ssh(location)
+        else:
+            return PresenceDetection._get_raw_data_via_ssh(location)
+        return None
+
+    def _update_house(self) -> None:
+        data = self._get_raw_data(Location.HOUSE)
+        if data:
+            self._parse_raw_macs_file(data, Location.HOUSE)
+        else:
             msg = "Can't see the house right now; presence detection impared."
-            logger.warning(msg)
-            warnings.warn(msg, stacklevel=2)
+            warnings.warn(msg)
+            logger.warning(msg, stacklevel=2)
             self.dark_locations.add(Location.HOUSE)
 
-    def read_persisted_macs_file(self, filename: str, location: Location) -> None:
-        if location is Location.UNKNOWN:
-            return
-        with open(filename, "r") as rf:
-            lines = rf.read()
-        self.parse_raw_macs_file(lines, location)
+    def _update_cabin(self) -> None:
+        data = self._get_raw_data(Location.CABIN)
+        if data:
+            self._parse_raw_macs_file(data, Location.CABIN)
+        else:
+            msg = "Can't see the cabin right now; presence detection impared."
+            warnings.warn(msg)
+            logger.warning(msg, stacklevel=2)
+            self.dark_locations.add(Location.CABIN)
+
+    def _parse_raw_macs_file(self, raw: str, location: Location) -> None:
+        """Internal method that parses the contents of the MACs file."""
 
-    def parse_raw_macs_file(self, raw: str, location: Location) -> None:
         lines = raw.split("\n")
 
         # CC:F4:11:D7:FA:EE, 2240, 10.0.0.22 (side_deck_high_home), Google, 1611681990
         cabin_count = 0
         for line in lines:
             line = line.strip()
+            if 'using fake authentication data for X11' in line:
+                continue
             if len(line) == 0:
                 continue
             logger.debug('%s> %s', location, line)
@@ -183,6 +209,16 @@ class PresenceDetection(object):
             self.weird_mac_at_cabin = True
 
     def is_anyone_in_location_now(self, location: Location) -> bool:
+        """Determine if anyone is in a given location based on the presence of
+        MAC files seen recently on the network.
+
+        Args:
+            location: the location in question
+
+        Returns:
+            True if someone is detected or False otherwise.
+        """
+
         self.maybe_update()
         if location in self.dark_locations:
             raise Exception(f"Can't see {location} right now; answer undefined.")
@@ -196,6 +232,16 @@ class PresenceDetection(object):
         return False
 
     def where_is_person_now(self, name: Person) -> Location:
+        """Given a person, see if we can determine their location based on
+        network MAC addresses.
+
+        Args:
+            name: The person we're looking for.
+
+        Returns:
+            The Location where we think they are (including UNKNOWN).
+        """
+
         self.maybe_update()
         if len(self.dark_locations) > 0:
             msg = f"Can't see {self.dark_locations} right now; answer confidence impacted"
@@ -219,17 +265,11 @@ class PresenceDetection(object):
             if mac not in self.names_by_mac:
                 continue
             mac_name = self.names_by_mac[mac]
-            logger.debug(
-                'Looking for %s... check for mac %s (%s)',
-                name, mac, mac_name
-            )
+            logger.debug('Looking for %s... check for mac %s (%s)', name, mac, mac_name)
             for location in self.location_ts_by_mac:
                 if mac in self.location_ts_by_mac[location]:
                     ts = (self.location_ts_by_mac[location])[mac]
-                    logger.debug(
-                        'Seen %s (%s) at %s since %s',
-                        mac, mac_name, location, ts
-                    )
+                    logger.debug('Seen %s (%s) at %s since %s', mac, mac_name, location, ts)
                     tiebreaks[location] = ts
 
             (
@@ -257,10 +297,8 @@ def main() -> None:
     for person in Person:
         print(f'{person} => {p.where_is_person_now(person)}')
     print()
-
-
-#    for location in Location:
-#        print(f'{location} => {p.is_anyone_in_location_now(location)}')
+    for location in Location:
+        print(f'{location} => {p.is_anyone_in_location_now(location)}')
 
 
 if __name__ == '__main__':