4 from collections import defaultdict
8 from typing import Dict, List
13 logger = logging.getLogger(__name__)
15 cfg = config.add_commandline_args(
16 f"Presence Detection ({__file__})",
17 "Args related to detection of human beings in locations.",
20 "--presence_macs_file",
21 type=argparse_utils.valid_filename,
22 default = "/home/scott/cron/persisted_mac_addresses.txt",
24 help="The location of persisted_mac_addresses.txt to use."
28 class Person(enum.Enum):
39 class Location(enum.Enum):
45 class PresenceDetection(object):
46 def __init__(self) -> None:
47 # Note: list most important devices first.
48 self.devices_by_person: Dict[Person, List[str]] = {
63 Person.AARON_AND_DANA: [
76 self.weird_mac_at_cabin = False
77 self.location_ts_by_mac: Dict[
78 Location, Dict[str, datetime.datetime]
80 self.names_by_mac: Dict[str, str] = {}
83 def update(self) -> None:
84 from exec_utils import cmd
85 persisted_macs = config.config['presence_macs_file']
86 self.read_persisted_macs_file(persisted_macs, Location.HOUSE)
90 self.parse_raw_macs_file(raw, Location.CABIN)
92 def read_persisted_macs_file(
93 self, filename: str, location: Location
95 if location is Location.UNKNOWN:
97 with open(filename, "r") as rf:
99 self.parse_raw_macs_file(lines, location)
101 def parse_raw_macs_file(self, raw: str, location: Location) -> None:
102 lines = raw.split("\n")
104 # CC:F4:11:D7:FA:EE, 2240, 10.0.0.22 (side_deck_high_home), Google, 1611681990
110 logger.debug(f'{location}> {line}')
113 if location == Location.CABIN:
116 (mac, count, ip_name, mfg, ts) = line.split(",")
117 except Exception as e:
118 logger.error(f'SKIPPED BAD LINE> {line}')
122 (self.location_ts_by_mac[location])[
124 ] = datetime.datetime.fromtimestamp(int(ts.strip()))
125 ip_name = ip_name.strip()
126 match = re.match(r"(\d+\.\d+\.\d+\.\d+) +\(([^\)]+)\)", ip_name)
127 if match is not None:
128 name = match.group(2)
129 self.names_by_mac[mac] = name
131 self.weird_mac_at_cabin = True
133 def is_anyone_in_location_now(self, location: Location) -> bool:
134 for person in Person:
135 if person is not None:
136 loc = self.where_is_person_now(person)
139 if location == location.CABIN and self.weird_mac_at_cabin:
143 def where_is_person_now(self, name: Person) -> Location:
146 if name is Person.UNKNOWN:
147 if self.weird_mac_at_cabin:
148 return Location.CABIN
150 return Location.UNKNOWN
151 votes: Dict[Location, int] = {}
152 tiebreaks: Dict[Location, datetime.datetime] = {}
154 for mac in self.devices_by_person[name]:
155 if mac not in self.names_by_mac:
157 for location in self.location_ts_by_mac:
158 if mac in self.location_ts_by_mac[location]:
159 ts = (self.location_ts_by_mac[location])[mac]
160 tiebreaks[location] = ts
161 location = dict_utils.key_with_min_value(tiebreaks)
162 v = votes.get(location, 0)
163 votes[location] = v + credit
166 ) # Note: list most important devices first
170 item = dict_utils.item_with_max_value(votes)
172 return Location.UNKNOWN