A bunch of changes...
[python_utils.git] / base_presence.py
1 #!/usr/bin/env python3
2
3 import datetime
4 from collections import defaultdict
5 import logging
6 import re
7 from typing import Dict, List, Set
8
9 # Note: this module is fairly early loaded.  Be aware of dependencies.
10 import argparse_utils
11 import bootstrap
12 import config
13 from type.locations import Location
14 from type.people import Person
15 import site_config
16
17
18 logger = logging.getLogger(__name__)
19
20 cfg = config.add_commandline_args(
21     f"Presence Detection ({__file__})",
22     "Args related to detection of human beings in locations.",
23 )
24 cfg.add_argument(
25     "--presence_macs_file",
26     type=argparse_utils.valid_filename,
27     default = "/home/scott/cron/persisted_mac_addresses.txt",
28     metavar="FILENAME",
29     help="The location of persisted_mac_addresses.txt to use."
30 )
31 cfg.add_argument(
32     '--presence_tolerable_staleness_seconds',
33     type=argparse_utils.valid_duration,
34     default=datetime.timedelta(seconds=60 * 5),
35     metavar='DURATION',
36     help='Max acceptable age of location data before auto-refreshing'
37 )
38
39
40 class PresenceDetection(object):
41     def __init__(self) -> None:
42         # Note: list most important devices first.
43         self.devices_by_person: Dict[Person, List[str]] = {
44             Person.SCOTT: [
45                 "3C:28:6D:10:6D:41", # pixel3
46                 "6C:40:08:AE:DC:2E", # laptop
47             ],
48             Person.LYNN: [
49                 "08:CC:27:63:26:14", # motog7
50                 "B8:31:B5:9A:4F:19", # laptop
51             ],
52             Person.ALEX: [
53                 "0C:CB:85:0C:8B:AE", # phone
54                 "D0:C6:37:E3:36:9A", # laptop
55             ],
56             Person.AARON_AND_DANA: [
57                 "98:B6:E9:E5:5A:7C",
58                 "D6:2F:37:CA:B2:9B",
59                 "6C:E8:5C:ED:17:26",
60                 "90:E1:7B:13:7C:E5",
61                 "6E:DC:7C:75:02:1B",
62                 "B2:16:1A:93:7D:50",
63                 "18:65:90:DA:3A:35",
64                 "22:28:C8:7D:3C:85",
65                 "B2:95:23:69:91:F8",
66                 "96:69:2C:88:7A:C3",
67             ],
68         }
69         self.run_location = site_config.get_location()
70         logger.debug(f"run_location is {self.run_location}")
71         self.weird_mac_at_cabin = False
72         self.location_ts_by_mac: Dict[
73             Location, Dict[str, datetime.datetime]
74         ] = defaultdict(dict)
75         self.names_by_mac: Dict[str, str] = {}
76         self.dark_locations: Set[Location] = set()
77         self.last_update = None
78
79     def maybe_update(self) -> None:
80         if self.last_update is None:
81             self.update()
82         else:
83             now = datetime.datetime.now()
84             delta = now - self.last_update
85             if delta.total_seconds() > config.config['presence_tolerable_staleness_seconds'].total_seconds():
86                 logger.debug(
87                     f"It's been {delta.total_seconds()}s since last update; refreshing now."
88                 )
89                 self.update()
90
91     def update(self) -> None:
92         self.dark_locations = set()
93         if self.run_location is Location.HOUSE:
94             self.update_from_house()
95         elif self.run_location is Location.CABIN:
96             self.update_from_cabin()
97         else:
98             raise Exception("Where the hell is this running?!")
99         self.last_update = datetime.datetime.now()
100
101     def update_from_house(self) -> None:
102         from exec_utils import cmd
103         try:
104             persisted_macs = config.config['presence_macs_file']
105         except KeyError:
106             persisted_macs = '/home/scott/cron/persisted_mac_addresses.txt'
107         self.read_persisted_macs_file(persisted_macs, Location.HOUSE)
108         try:
109             raw = cmd(
110                 "ssh [email protected] 'cat /home/scott/cron/persisted_mac_addresses.txt'",
111                 timeout_seconds=10.0,
112             )
113             self.parse_raw_macs_file(raw, Location.CABIN)
114         except Exception as e:
115             logger.exception(e)
116             logger.warning("Can't see the cabin right now; presence detection impared.")
117             self.dark_locations.add(Location.CABIN)
118
119     def update_from_cabin(self) -> None:
120         from exec_utils import cmd
121         try:
122             persisted_macs = config.config['presence_macs_file']
123         except KeyError:
124             persisted_macs = '/home/scott/cron/persisted_mac_addresses.txt'
125         self.read_persisted_macs_file(persisted_macs, Location.CABIN)
126         try:
127             raw = cmd(
128                 "ssh [email protected] 'cat /home/scott/cron/persisted_mac_addresses.txt'",
129                 timeout_seconds=10.0,
130             )
131             self.parse_raw_macs_file(raw, Location.HOUSE)
132         except Exception as e:
133             logger.exception(e)
134             logger.warning("Can't see the house right now; presence detection impared.")
135             self.dark_locations.add(Location.HOUSE)
136
137     def read_persisted_macs_file(
138         self, filename: str, location: Location
139     ) -> None:
140         if location is Location.UNKNOWN:
141             return
142         with open(filename, "r") as rf:
143             lines = rf.read()
144         self.parse_raw_macs_file(lines, location)
145
146     def parse_raw_macs_file(self, raw: str, location: Location) -> None:
147         lines = raw.split("\n")
148
149         # CC:F4:11:D7:FA:EE, 2240, 10.0.0.22 (side_deck_high_home), Google, 1611681990
150         cabin_count = 0
151         for line in lines:
152             line = line.strip()
153             if len(line) == 0:
154                 continue
155             logger.debug(f'{location}> {line}')
156             if "cabin_" in line:
157                 continue
158             if location == Location.CABIN:
159                 logger.debug('Cabin count: {cabin_count}')
160                 cabin_count += 1
161             try:
162                 (mac, count, ip_name, mfg, ts) = line.split(",")
163             except Exception as e:
164                 logger.error(f'SKIPPED BAD LINE> {line}')
165                 logger.exception(e)
166                 continue
167             mac = mac.strip()
168             (self.location_ts_by_mac[location])[
169                 mac
170             ] = datetime.datetime.fromtimestamp(int(ts.strip()))
171             ip_name = ip_name.strip()
172             match = re.match(r"(\d+\.\d+\.\d+\.\d+) +\(([^\)]+)\)", ip_name)
173             if match is not None:
174                 name = match.group(2)
175                 self.names_by_mac[mac] = name
176         if cabin_count > 0:
177             logger.debug('Weird MAC at the cabin')
178             self.weird_mac_at_cabin = True
179
180     def is_anyone_in_location_now(self, location: Location) -> bool:
181         self.maybe_update()
182         if location in self.dark_locations:
183             raise Exception(f"Can't see {location} right now; answer undefined.")
184         for person in Person:
185             if person is not None:
186                 loc = self.where_is_person_now(person)
187                 if location == loc:
188                     return True
189         if location == location.CABIN and self.weird_mac_at_cabin:
190             return True
191         return False
192
193     def where_is_person_now(self, name: Person) -> Location:
194         self.maybe_update()
195         if len(self.dark_locations) > 0:
196             logger.warning(
197                 f"Can't see {self.dark_locations} right now; answer confidence impacted"
198             )
199         logger.debug(f'Looking for {name}...')
200
201         if name is Person.UNKNOWN:
202             if self.weird_mac_at_cabin:
203                 return Location.CABIN
204             else:
205                 return Location.UNKNOWN
206
207         import dict_utils
208         votes: Dict[Location, int] = {}
209         tiebreaks: Dict[Location, datetime.datetime] = {}
210         credit = 10000
211         for mac in self.devices_by_person[name]:
212             if mac not in self.names_by_mac:
213                 continue
214             mac_name = self.names_by_mac[mac]
215             logger.debug(f'Looking for {name}... check for mac {mac} ({mac_name})')
216             for location in self.location_ts_by_mac:
217                 if mac in self.location_ts_by_mac[location]:
218                     ts = (self.location_ts_by_mac[location])[mac]
219                     logger.debug(f'Seen {mac} ({mac_name}) at {location} since {ts}')
220                     tiebreaks[location] = ts
221
222             (most_recent_location, first_seen_ts) = dict_utils.item_with_max_value(tiebreaks)
223             bonus = credit
224             v = votes.get(most_recent_location, 0)
225             votes[most_recent_location] = v + bonus
226             logger.debug(f'{name}: {location} gets {bonus} votes.')
227             credit = int(
228                 credit * 0.2
229             )  # Note: list most important devices first
230             if credit <= 0:
231                 credit = 1
232         if len(votes) > 0:
233             (location, value) = dict_utils.item_with_max_value(votes)
234             if value > 2001:
235                 return location
236         return Location.UNKNOWN
237
238
239 @bootstrap.initialize
240 def main() -> None:
241     p = PresenceDetection()
242     for person in Person:
243         print(f'{person} => {p.where_is_person_now(person)}')
244     print()
245     for location in Location:
246         print(f'{location} => {p.is_anyone_in_location_now(location)}')
247
248
249 if __name__ == '__main__':
250     main()