4 from collections import defaultdict
9 from typing import Dict, List
17 logger = logging.getLogger(__name__)
19 cfg = config.add_commandline_args(
20 f"Presence Detection ({__file__})",
21 "Args related to detection of human beings in locations.",
24 "--presence_macs_file",
25 type=argparse_utils.valid_filename,
26 default = "/home/scott/cron/persisted_mac_addresses.txt",
28 help="The location of persisted_mac_addresses.txt to use."
32 class Person(enum.Enum):
43 class Location(enum.Enum):
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]] = {
67 Person.AARON_AND_DANA: [
80 self.location_ts_by_mac: Dict[
81 Location, Dict[str, datetime.datetime]
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)
89 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
109 logger.debug(f'{location}> {line}')
111 (mac, count, ip_name, mfg, ts) = line.split(",")
112 except Exception as e:
113 logger.error(f'SKIPPED BAD LINE> {line}')
117 (self.location_ts_by_mac[location])[
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
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)
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] = {}
140 for mac in self.devices_by_person[name]:
141 if mac not in self.names_by_mac:
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
152 ) # Note: list most important devices first
156 item = dict_utils.item_with_max_value(votes)
158 return Location.UNKNOWN
161 @bootstrap.initialize
164 p = PresenceDetection()
167 print(f'{loc}: {p.is_anyone_in_location_now(loc)}')
170 print(f'{u}: {p.where_is_person_now(u)}')
174 if __name__ == '__main__':