ad852f9f7ebce82d5a76c6d7f1436a78670489e7
[python_utils.git] / base_presence.py
1 #!/usr/bin/env python3
2
3 import datetime
4 import logging
5 import re
6 import warnings
7 from collections import defaultdict
8 from typing import Dict, List, Optional, Set
9
10 # Note: this module is fairly early loaded.  Be aware of dependencies.
11 import argparse_utils
12 import bootstrap
13 import config
14 import site_config
15 from type.locations import Location
16 from type.people import Person
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                 "DC:E5:5B:0F:03:3D",  # pixel6
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: Optional[datetime.datetime] = 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 (
86                 delta.total_seconds()
87                 > config.config['presence_tolerable_staleness_seconds'].total_seconds()
88             ):
89                 logger.debug(
90                     f"It's been {delta.total_seconds()}s since last update; refreshing now."
91                 )
92                 self.update()
93
94     def update(self) -> None:
95         self.dark_locations = set()
96         if self.run_location is Location.HOUSE:
97             self.update_from_house()
98         elif self.run_location is Location.CABIN:
99             self.update_from_cabin()
100         else:
101             raise Exception("Where the hell is this running?!")
102         self.last_update = datetime.datetime.now()
103
104     def update_from_house(self) -> None:
105         from exec_utils import cmd
106
107         try:
108             persisted_macs = config.config['presence_macs_file']
109         except KeyError:
110             persisted_macs = '/home/scott/cron/persisted_mac_addresses.txt'
111         self.read_persisted_macs_file(persisted_macs, Location.HOUSE)
112         try:
113             raw = cmd(
114                 "ssh [email protected] 'cat /home/scott/cron/persisted_mac_addresses.txt'",
115                 timeout_seconds=10.0,
116             )
117             self.parse_raw_macs_file(raw, Location.CABIN)
118         except Exception as e:
119             logger.exception(e)
120             msg = "Can't see the cabin right now; presence detection impared."
121             warnings.warn(msg)
122             logger.warning(msg, stacklevel=2)
123             self.dark_locations.add(Location.CABIN)
124
125     def update_from_cabin(self) -> None:
126         from exec_utils import cmd
127
128         try:
129             persisted_macs = config.config['presence_macs_file']
130         except KeyError:
131             persisted_macs = '/home/scott/cron/persisted_mac_addresses.txt'
132         self.read_persisted_macs_file(persisted_macs, Location.CABIN)
133         try:
134             raw = cmd(
135                 "ssh [email protected] 'cat /home/scott/cron/persisted_mac_addresses.txt'",
136                 timeout_seconds=10.0,
137             )
138             self.parse_raw_macs_file(raw, Location.HOUSE)
139         except Exception as e:
140             logger.exception(e)
141             msg = "Can't see the house right now; presence detection impared."
142             logger.warning(msg)
143             warnings.warn(msg, stacklevel=2)
144             self.dark_locations.add(Location.HOUSE)
145
146     def read_persisted_macs_file(self, filename: str, location: Location) -> None:
147         if location is Location.UNKNOWN:
148             return
149         with open(filename, "r") as rf:
150             lines = rf.read()
151         self.parse_raw_macs_file(lines, location)
152
153     def parse_raw_macs_file(self, raw: str, location: Location) -> None:
154         lines = raw.split("\n")
155
156         # CC:F4:11:D7:FA:EE, 2240, 10.0.0.22 (side_deck_high_home), Google, 1611681990
157         cabin_count = 0
158         for line in lines:
159             line = line.strip()
160             if len(line) == 0:
161                 continue
162             logger.debug(f'{location}> {line}')
163             if "cabin_" in line:
164                 continue
165             if location == Location.CABIN:
166                 logger.debug(f'Cabin count: {cabin_count}')
167                 cabin_count += 1
168             try:
169                 (mac, count, ip_name, mfg, ts) = line.split(",")
170             except Exception as e:
171                 logger.error(f'SKIPPED BAD LINE> {line}')
172                 logger.exception(e)
173                 continue
174             mac = mac.strip()
175             (self.location_ts_by_mac[location])[mac] = datetime.datetime.fromtimestamp(
176                 int(ts.strip())
177             )
178             ip_name = ip_name.strip()
179             match = re.match(r"(\d+\.\d+\.\d+\.\d+) +\(([^\)]+)\)", ip_name)
180             if match is not None:
181                 name = match.group(2)
182                 self.names_by_mac[mac] = name
183         if cabin_count > 0:
184             logger.debug('Weird MAC at the cabin')
185             self.weird_mac_at_cabin = True
186
187     def is_anyone_in_location_now(self, location: Location) -> bool:
188         self.maybe_update()
189         if location in self.dark_locations:
190             raise Exception(f"Can't see {location} right now; answer undefined.")
191         for person in Person:
192             if person is not None:
193                 loc = self.where_is_person_now(person)
194                 if location == loc:
195                     return True
196         if location == location.CABIN and self.weird_mac_at_cabin:
197             return True
198         return False
199
200     def where_is_person_now(self, name: Person) -> Location:
201         self.maybe_update()
202         if len(self.dark_locations) > 0:
203             msg = (
204                 f"Can't see {self.dark_locations} right now; answer confidence impacted"
205             )
206             logger.warning(msg)
207             warnings.warn(msg, stacklevel=2)
208         logger.debug(f'Looking for {name}...')
209
210         if name is Person.UNKNOWN:
211             if self.weird_mac_at_cabin:
212                 return Location.CABIN
213             else:
214                 return Location.UNKNOWN
215
216         import dict_utils
217
218         votes: Dict[Location, int] = {}
219         tiebreaks: Dict[Location, datetime.datetime] = {}
220         credit = 10000
221         for mac in self.devices_by_person[name]:
222             if mac not in self.names_by_mac:
223                 continue
224             mac_name = self.names_by_mac[mac]
225             logger.debug(f'Looking for {name}... check for mac {mac} ({mac_name})')
226             for location in self.location_ts_by_mac:
227                 if mac in self.location_ts_by_mac[location]:
228                     ts = (self.location_ts_by_mac[location])[mac]
229                     logger.debug(f'Seen {mac} ({mac_name}) at {location} since {ts}')
230                     tiebreaks[location] = ts
231
232             (
233                 most_recent_location,
234                 first_seen_ts,
235             ) = dict_utils.item_with_max_value(tiebreaks)
236             bonus = credit
237             v = votes.get(most_recent_location, 0)
238             votes[most_recent_location] = v + bonus
239             logger.debug(f'{name}: {location} gets {bonus} votes.')
240             credit = int(credit * 0.2)  # Note: list most important devices first
241             if credit <= 0:
242                 credit = 1
243         if len(votes) > 0:
244             (location, value) = dict_utils.item_with_max_value(votes)
245             if value > 2001:
246                 return location
247         return Location.UNKNOWN
248
249
250 @bootstrap.initialize
251 def main() -> None:
252     p = PresenceDetection()
253     for person in Person:
254         print(f'{person} => {p.where_is_person_now(person)}')
255     print()
256
257
258 #    for location in Location:
259 #        print(f'{location} => {p.is_anyone_in_location_now(location)}')
260
261
262 if __name__ == '__main__':
263     main()