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