4 from collections import defaultdict
9 from typing import Dict, List
11 # Note: this module is fairly early loaded. Be aware of dependencies.
16 logger = logging.getLogger(__name__)
18 cfg = config.add_commandline_args(
19 f"Presence Detection ({__file__})",
20 "Args related to detection of human beings in locations.",
23 "--presence_macs_file",
24 type=argparse_utils.valid_filename,
25 default = "/home/scott/cron/persisted_mac_addresses.txt",
27 help="The location of persisted_mac_addresses.txt to use."
31 class Person(enum.Enum):
42 class Location(enum.Enum):
48 class PresenceDetection(object):
49 def __init__(self) -> None:
50 # Note: list most important devices first.
51 self.devices_by_person: Dict[Person, List[str]] = {
53 "3C:28:6D:10:6D:41", # pixel3
54 "6C:40:08:AE:DC:2E", # laptop
57 "08:CC:27:63:26:14", # motog7
58 "B8:31:B5:9A:4F:19", # laptop
61 "0C:CB:85:0C:8B:AE", # phone
62 "D0:C6:37:E3:36:9A", # laptop
64 Person.AARON_AND_DANA: [
77 self.weird_mac_at_cabin = False
78 self.location_ts_by_mac: Dict[
79 Location, Dict[str, datetime.datetime]
81 self.names_by_mac: Dict[str, str] = {}
84 def update(self) -> None:
85 from exec_utils import cmd_with_timeout
87 persisted_macs = config.config['presence_macs_file']
89 persisted_macs = '/home/scott/cron/persisted_mac_addresses.txt'
90 self.read_persisted_macs_file(persisted_macs, Location.HOUSE)
92 raw = cmd_with_timeout(
96 self.parse_raw_macs_file(raw, Location.CABIN)
97 except Exception as e:
100 'Unable to fetch MAC Addresses from meerkat; can\'t do proper presence detection.'
104 def read_persisted_macs_file(
105 self, filename: str, location: Location
107 if location is Location.UNKNOWN:
109 with open(filename, "r") as rf:
111 self.parse_raw_macs_file(lines, location)
113 def parse_raw_macs_file(self, raw: str, location: Location) -> None:
114 lines = raw.split("\n")
116 # CC:F4:11:D7:FA:EE, 2240, 10.0.0.22 (side_deck_high_home), Google, 1611681990
122 logger.debug(f'{location}> {line}')
125 if location == Location.CABIN:
126 logger.debug('Cabin count: {cabin_count}')
129 (mac, count, ip_name, mfg, ts) = line.split(",")
130 except Exception as e:
131 logger.error(f'SKIPPED BAD LINE> {line}')
135 (self.location_ts_by_mac[location])[
137 ] = datetime.datetime.fromtimestamp(int(ts.strip()))
138 ip_name = ip_name.strip()
139 match = re.match(r"(\d+\.\d+\.\d+\.\d+) +\(([^\)]+)\)", ip_name)
140 if match is not None:
141 name = match.group(2)
142 self.names_by_mac[mac] = name
144 logger.debug('Weird MAC at the cabin')
145 self.weird_mac_at_cabin = True
147 def is_anyone_in_location_now(self, location: Location) -> bool:
148 for person in Person:
149 if person is not None:
150 loc = self.where_is_person_now(person)
153 if location == location.CABIN and self.weird_mac_at_cabin:
157 def where_is_person_now(self, name: Person) -> Location:
159 logger.debug(f'Looking for {name}...')
161 if name is Person.UNKNOWN:
162 if self.weird_mac_at_cabin:
163 return Location.CABIN
165 return Location.UNKNOWN
166 votes: Dict[Location, int] = {}
167 tiebreaks: Dict[Location, datetime.datetime] = {}
169 for mac in self.devices_by_person[name]:
170 if mac not in self.names_by_mac:
172 mac_name = self.names_by_mac[mac]
173 logger.debug(f'Looking for {name}... check for mac {mac} ({mac_name})')
174 for location in self.location_ts_by_mac:
175 if mac in self.location_ts_by_mac[location]:
176 ts = (self.location_ts_by_mac[location])[mac]
177 logger.debug(f'Seen {mac} ({mac_name}) at {location} since {ts}')
178 tiebreaks[location] = ts
180 (most_recent_location, first_seen_ts) = dict_utils.item_with_max_value(tiebreaks)
182 v = votes.get(most_recent_location, 0)
183 votes[most_recent_location] = v + bonus
184 logger.debug(f'{name}: {location} gets {bonus} votes.')
187 ) # Note: list most important devices first
191 (location, value) = dict_utils.item_with_max_value(votes)
194 return Location.UNKNOWN
197 @bootstrap.initialize
199 p = PresenceDetection()
200 for person in Person:
201 print(f'{person} => {p.where_is_person_now(person)}')
203 for location in Location:
204 print(f'{location} => {p.is_anyone_in_location_now(location)}')
207 if __name__ == '__main__':