Reduce import scopes, remove cycles.
[python_utils.git] / presence.py
1 #!/usr/bin/env python3
2
3 import datetime
4 from collections import defaultdict
5 import enum
6 import logging
7 import re
8 from typing import Dict, List
9
10 import argparse_utils
11 import config
12
13 logger = logging.getLogger(__name__)
14
15 cfg = config.add_commandline_args(
16     f"Presence Detection ({__file__})",
17     "Args related to detection of human beings in locations.",
18 )
19 cfg.add_argument(
20     "--presence_macs_file",
21     type=argparse_utils.valid_filename,
22     default = "/home/scott/cron/persisted_mac_addresses.txt",
23     metavar="FILENAME",
24     help="The location of persisted_mac_addresses.txt to use."
25 )
26
27
28 class Person(enum.Enum):
29     UNKNOWN = 0
30     SCOTT = 1
31     LYNN = 2
32     ALEX = 3
33     AARON_AND_DANA = 4
34     AARON = 4
35     DANA = 4
36
37
38 @enum.unique
39 class Location(enum.Enum):
40     UNKNOWN = 0
41     HOUSE = 1
42     CABIN = 2
43
44
45 class PresenceDetection(object):
46     def __init__(self) -> None:
47         # Note: list most important devices first.
48         self.devices_by_person: Dict[Person, List[str]] = {
49             Person.SCOTT: [
50                 "3C:28:6D:10:6D:41",
51                 "D4:61:2E:88:18:09",
52                 "6C:40:08:AE:DC:2E",
53                 "14:7D:DA:6A:20:D7",
54             ],
55             Person.LYNN: [
56                 "08:CC:27:63:26:14",
57                 "B8:31:B5:9A:4F:19",
58             ],
59             Person.ALEX: [
60                 "0C:CB:85:0C:8B:AE",
61                 "D0:C6:37:E3:36:9A",
62             ],
63             Person.AARON_AND_DANA: [
64                 "98:B6:E9:E5:5A:7C",
65                 "D6:2F:37:CA:B2:9B",
66                 "6C:E8:5C:ED:17:26",
67                 "90:E1:7B:13:7C:E5",
68                 "6E:DC:7C:75:02:1B",
69                 "B2:16:1A:93:7D:50",
70                 "18:65:90:DA:3A:35",
71                 "22:28:C8:7D:3C:85",
72                 "B2:95:23:69:91:F8",
73                 "96:69:2C:88:7A:C3",
74             ],
75         }
76         self.weird_mac_at_cabin = False
77         self.location_ts_by_mac: Dict[
78             Location, Dict[str, datetime.datetime]
79         ] = defaultdict(dict)
80         self.names_by_mac: Dict[str, str] = {}
81         self.update()
82
83     def update(self) -> None:
84         from exec_utils import cmd
85         persisted_macs = config.config['presence_macs_file']
86         self.read_persisted_macs_file(persisted_macs, Location.HOUSE)
87         raw = cmd(
88             "ssh [email protected] 'cat /home/scott/cron/persisted_mac_addresses.txt'"
89         )
90         self.parse_raw_macs_file(raw, Location.CABIN)
91
92     def read_persisted_macs_file(
93         self, filename: str, location: Location
94     ) -> None:
95         if location is Location.UNKNOWN:
96             return
97         with open(filename, "r") as rf:
98             lines = rf.read()
99         self.parse_raw_macs_file(lines, location)
100
101     def parse_raw_macs_file(self, raw: str, location: Location) -> None:
102         lines = raw.split("\n")
103
104         # CC:F4:11:D7:FA:EE, 2240, 10.0.0.22 (side_deck_high_home), Google, 1611681990
105         cabin_count = 0
106         for line in lines:
107             line = line.strip()
108             if len(line) == 0:
109                 continue
110             logger.debug(f'{location}> {line}')
111             if "cabin_" in line:
112                 continue
113             if location == Location.CABIN:
114                 cabin_count += 1
115             try:
116                 (mac, count, ip_name, mfg, ts) = line.split(",")
117             except Exception as e:
118                 logger.error(f'SKIPPED BAD LINE> {line}')
119                 logger.exception(e)
120                 continue
121             mac = mac.strip()
122             (self.location_ts_by_mac[location])[
123                 mac
124             ] = datetime.datetime.fromtimestamp(int(ts.strip()))
125             ip_name = ip_name.strip()
126             match = re.match(r"(\d+\.\d+\.\d+\.\d+) +\(([^\)]+)\)", ip_name)
127             if match is not None:
128                 name = match.group(2)
129                 self.names_by_mac[mac] = name
130         if cabin_count > 0:
131             self.weird_mac_at_cabin = True
132
133     def is_anyone_in_location_now(self, location: Location) -> bool:
134         for person in Person:
135             if person is not None:
136                 loc = self.where_is_person_now(person)
137                 if location == loc:
138                     return True
139         if location == location.CABIN and self.weird_mac_at_cabin:
140             return True
141         return False
142
143     def where_is_person_now(self, name: Person) -> Location:
144         import dict_utils
145
146         if name is Person.UNKNOWN:
147             if self.weird_mac_at_cabin:
148                 return Location.CABIN
149             else:
150                 return Location.UNKNOWN
151         votes: Dict[Location, int] = {}
152         tiebreaks: Dict[Location, datetime.datetime] = {}
153         credit = 10000
154         for mac in self.devices_by_person[name]:
155             if mac not in self.names_by_mac:
156                 continue
157             for location in self.location_ts_by_mac:
158                 if mac in self.location_ts_by_mac[location]:
159                     ts = (self.location_ts_by_mac[location])[mac]
160                     tiebreaks[location] = ts
161             location = dict_utils.key_with_min_value(tiebreaks)
162             v = votes.get(location, 0)
163             votes[location] = v + credit
164             credit = int(
165                 credit * 0.667
166             )  # Note: list most important devices first
167             if credit <= 0:
168                 credit = 1
169         if len(votes) > 0:
170             item = dict_utils.item_with_max_value(votes)
171             return item[0]
172         return Location.UNKNOWN