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