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