Used isort to sort imports. Also added to the git pre-commit hook.
[python_utils.git] / base_presence.py
index cd62bb71892a9d7aa4f534b0411166b3e53a1d6b..ad852f9f7ebce82d5a76c6d7f1436a78670489e7 100755 (executable)
@@ -1,19 +1,19 @@
 #!/usr/bin/env python3
 
 import datetime
-from collections import defaultdict
 import logging
 import re
-from typing import Dict, List, Set
+import warnings
+from collections import defaultdict
+from typing import Dict, List, Optional, Set
 
 # Note: this module is fairly early loaded.  Be aware of dependencies.
 import argparse_utils
 import bootstrap
 import config
+import site_config
 from type.locations import Location
 from type.people import Person
-import site_config
-
 
 logger = logging.getLogger(__name__)
 
@@ -24,16 +24,16 @@ cfg = config.add_commandline_args(
 cfg.add_argument(
     "--presence_macs_file",
     type=argparse_utils.valid_filename,
-    default = "/home/scott/cron/persisted_mac_addresses.txt",
+    default="/home/scott/cron/persisted_mac_addresses.txt",
     metavar="FILENAME",
-    help="The location of persisted_mac_addresses.txt to use."
+    help="The location of persisted_mac_addresses.txt to use.",
 )
 cfg.add_argument(
     '--presence_tolerable_staleness_seconds',
     type=argparse_utils.valid_duration,
     default=datetime.timedelta(seconds=60 * 5),
     metavar='DURATION',
-    help='Max acceptable age of location data before auto-refreshing'
+    help='Max acceptable age of location data before auto-refreshing',
 )
 
 
@@ -42,16 +42,16 @@ class PresenceDetection(object):
         # Note: list most important devices first.
         self.devices_by_person: Dict[Person, List[str]] = {
             Person.SCOTT: [
-                "3C:28:6D:10:6D:41", # pixel3
-                "6C:40:08:AE:DC:2E", # laptop
+                "DC:E5:5B:0F:03:3D",  # pixel6
+                "6C:40:08:AE:DC:2E",  # laptop
             ],
             Person.LYNN: [
-                "08:CC:27:63:26:14", # motog7
-                "B8:31:B5:9A:4F:19", # laptop
+                "08:CC:27:63:26:14",  # motog7
+                "B8:31:B5:9A:4F:19",  # laptop
             ],
             Person.ALEX: [
-                "0C:CB:85:0C:8B:AE", # phone
-                "D0:C6:37:E3:36:9A", # laptop
+                "0C:CB:85:0C:8B:AE",  # phone
+                "D0:C6:37:E3:36:9A",  # laptop
             ],
             Person.AARON_AND_DANA: [
                 "98:B6:E9:E5:5A:7C",
@@ -74,7 +74,7 @@ class PresenceDetection(object):
         ] = defaultdict(dict)
         self.names_by_mac: Dict[str, str] = {}
         self.dark_locations: Set[Location] = set()
-        self.last_update = None
+        self.last_update: Optional[datetime.datetime] = None
 
     def maybe_update(self) -> None:
         if self.last_update is None:
@@ -82,7 +82,10 @@ class PresenceDetection(object):
         else:
             now = datetime.datetime.now()
             delta = now - self.last_update
-            if delta.total_seconds() > config.config['presence_tolerable_staleness_seconds'].total_seconds():
+            if (
+                delta.total_seconds()
+                > config.config['presence_tolerable_staleness_seconds'].total_seconds()
+            ):
                 logger.debug(
                     f"It's been {delta.total_seconds()}s since last update; refreshing now."
                 )
@@ -100,6 +103,7 @@ class PresenceDetection(object):
 
     def update_from_house(self) -> None:
         from exec_utils import cmd
+
         try:
             persisted_macs = config.config['presence_macs_file']
         except KeyError:
@@ -113,11 +117,14 @@ class PresenceDetection(object):
             self.parse_raw_macs_file(raw, Location.CABIN)
         except Exception as e:
             logger.exception(e)
-            logger.warning("Can't see the cabin right now; presence detection impared.")
+            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 update_from_cabin(self) -> None:
         from exec_utils import cmd
+
         try:
             persisted_macs = config.config['presence_macs_file']
         except KeyError:
@@ -131,12 +138,12 @@ class PresenceDetection(object):
             self.parse_raw_macs_file(raw, Location.HOUSE)
         except Exception as e:
             logger.exception(e)
-            logger.warning("Can't see the house right now; presence detection impared.")
+            msg = "Can't see the house right now; presence detection impared."
+            logger.warning(msg)
+            warnings.warn(msg, stacklevel=2)
             self.dark_locations.add(Location.HOUSE)
 
-    def read_persisted_macs_file(
-        self, filename: str, location: Location
-    ) -> None:
+    def read_persisted_macs_file(self, filename: str, location: Location) -> None:
         if location is Location.UNKNOWN:
             return
         with open(filename, "r") as rf:
@@ -156,7 +163,7 @@ class PresenceDetection(object):
             if "cabin_" in line:
                 continue
             if location == Location.CABIN:
-                logger.debug('Cabin count: {cabin_count}')
+                logger.debug(f'Cabin count: {cabin_count}')
                 cabin_count += 1
             try:
                 (mac, count, ip_name, mfg, ts) = line.split(",")
@@ -165,9 +172,9 @@ class PresenceDetection(object):
                 logger.exception(e)
                 continue
             mac = mac.strip()
-            (self.location_ts_by_mac[location])[
-                mac
-            ] = datetime.datetime.fromtimestamp(int(ts.strip()))
+            (self.location_ts_by_mac[location])[mac] = datetime.datetime.fromtimestamp(
+                int(ts.strip())
+            )
             ip_name = ip_name.strip()
             match = re.match(r"(\d+\.\d+\.\d+\.\d+) +\(([^\)]+)\)", ip_name)
             if match is not None:
@@ -193,9 +200,11 @@ class PresenceDetection(object):
     def where_is_person_now(self, name: Person) -> Location:
         self.maybe_update()
         if len(self.dark_locations) > 0:
-            logger.warning(
+            msg = (
                 f"Can't see {self.dark_locations} right now; answer confidence impacted"
             )
+            logger.warning(msg)
+            warnings.warn(msg, stacklevel=2)
         logger.debug(f'Looking for {name}...')
 
         if name is Person.UNKNOWN:
@@ -205,6 +214,7 @@ class PresenceDetection(object):
                 return Location.UNKNOWN
 
         import dict_utils
+
         votes: Dict[Location, int] = {}
         tiebreaks: Dict[Location, datetime.datetime] = {}
         credit = 10000
@@ -219,14 +229,15 @@ class PresenceDetection(object):
                     logger.debug(f'Seen {mac} ({mac_name}) at {location} since {ts}')
                     tiebreaks[location] = ts
 
-            (most_recent_location, first_seen_ts) = dict_utils.item_with_max_value(tiebreaks)
+            (
+                most_recent_location,
+                first_seen_ts,
+            ) = dict_utils.item_with_max_value(tiebreaks)
             bonus = credit
             v = votes.get(most_recent_location, 0)
             votes[most_recent_location] = v + bonus
             logger.debug(f'{name}: {location} gets {bonus} votes.')
-            credit = int(
-                credit * 0.2
-            )  # Note: list most important devices first
+            credit = int(credit * 0.2)  # Note: list most important devices first
             if credit <= 0:
                 credit = 1
         if len(votes) > 0:
@@ -242,8 +253,10 @@ 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__':