Make base_presence runnable from anywhere.
authorScott Gasch <[email protected]>
Wed, 27 Jul 2022 18:45:07 +0000 (11:45 -0700)
committerScott Gasch <[email protected]>
Wed, 27 Jul 2022 18:45:07 +0000 (11:45 -0700)
base_presence.py

index 4b8791d3b0b2220c6d61b7392a3e71a905d152ce..6464e9752a0875506f908b9608a16c35eaa497a0 100755 (executable)
@@ -32,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.",
@@ -114,77 +114,61 @@ class PresenceDetection(object):
         """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:
-        """Internal method for updating from code running on the house
-        network."""
-
+    @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=20.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:
-        """Internal method for updating from code running on the cabing
-        network."""
+    def _get_raw_data(self, location: Location) -> Optional[str]:
+        from os.path import exists
 
-        from exec_utils import cmd
-
-        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:
-        """Internal method that, Given a filename that contains MAC addresses
-        seen on the network recently, reads it in and calls
-        _parse_raw_macs_file with the contents.
-
-        Args:
-            filename: The name of the file to read
-            location: The location we're reading from
-
-        """
-        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."""