4 from collections import defaultdict
7 from typing import Dict, List, Set
10 # Note: this module is fairly early loaded. Be aware of dependencies.
14 from type.locations import Location
15 from type.people import Person
19 logger = logging.getLogger(__name__)
21 cfg = config.add_commandline_args(
22 f"Presence Detection ({__file__})",
23 "Args related to detection of human beings in locations.",
26 "--presence_macs_file",
27 type=argparse_utils.valid_filename,
28 default="/home/scott/cron/persisted_mac_addresses.txt",
30 help="The location of persisted_mac_addresses.txt to use.",
33 '--presence_tolerable_staleness_seconds',
34 type=argparse_utils.valid_duration,
35 default=datetime.timedelta(seconds=60 * 5),
37 help='Max acceptable age of location data before auto-refreshing',
41 class PresenceDetection(object):
42 def __init__(self) -> None:
43 # Note: list most important devices first.
44 self.devices_by_person: Dict[Person, List[str]] = {
46 "DC:E5:5B:0F:03:3D", # pixel6
47 "6C:40:08:AE:DC:2E", # laptop
50 "08:CC:27:63:26:14", # motog7
51 "B8:31:B5:9A:4F:19", # laptop
54 "0C:CB:85:0C:8B:AE", # phone
55 "D0:C6:37:E3:36:9A", # laptop
57 Person.AARON_AND_DANA: [
70 self.run_location = site_config.get_location()
71 logger.debug(f"run_location is {self.run_location}")
72 self.weird_mac_at_cabin = False
73 self.location_ts_by_mac: Dict[
74 Location, Dict[str, datetime.datetime]
76 self.names_by_mac: Dict[str, str] = {}
77 self.dark_locations: Set[Location] = set()
78 self.last_update = None
80 def maybe_update(self) -> None:
81 if self.last_update is None:
84 now = datetime.datetime.now()
85 delta = now - self.last_update
88 > config.config['presence_tolerable_staleness_seconds'].total_seconds()
91 f"It's been {delta.total_seconds()}s since last update; refreshing now."
95 def update(self) -> None:
96 self.dark_locations = set()
97 if self.run_location is Location.HOUSE:
98 self.update_from_house()
99 elif self.run_location is Location.CABIN:
100 self.update_from_cabin()
102 raise Exception("Where the hell is this running?!")
103 self.last_update = datetime.datetime.now()
105 def update_from_house(self) -> None:
106 from exec_utils import cmd
109 persisted_macs = config.config['presence_macs_file']
111 persisted_macs = '/home/scott/cron/persisted_mac_addresses.txt'
112 self.read_persisted_macs_file(persisted_macs, Location.HOUSE)
116 timeout_seconds=10.0,
118 self.parse_raw_macs_file(raw, Location.CABIN)
119 except Exception as e:
121 msg = "Can't see the cabin right now; presence detection impared."
123 logger.warning(msg, stacklevel=2)
124 self.dark_locations.add(Location.CABIN)
126 def update_from_cabin(self) -> None:
127 from exec_utils import cmd
130 persisted_macs = config.config['presence_macs_file']
132 persisted_macs = '/home/scott/cron/persisted_mac_addresses.txt'
133 self.read_persisted_macs_file(persisted_macs, Location.CABIN)
137 timeout_seconds=10.0,
139 self.parse_raw_macs_file(raw, Location.HOUSE)
140 except Exception as e:
142 msg = "Can't see the house right now; presence detection impared."
144 warnings.warn(msg, stacklevel=2)
145 self.dark_locations.add(Location.HOUSE)
147 def read_persisted_macs_file(self, filename: str, location: Location) -> None:
148 if location is Location.UNKNOWN:
150 with open(filename, "r") as rf:
152 self.parse_raw_macs_file(lines, location)
154 def parse_raw_macs_file(self, raw: str, location: Location) -> None:
155 lines = raw.split("\n")
157 # CC:F4:11:D7:FA:EE, 2240, 10.0.0.22 (side_deck_high_home), Google, 1611681990
163 logger.debug(f'{location}> {line}')
166 if location == Location.CABIN:
167 logger.debug(f'Cabin count: {cabin_count}')
170 (mac, count, ip_name, mfg, ts) = line.split(",")
171 except Exception as e:
172 logger.error(f'SKIPPED BAD LINE> {line}')
176 (self.location_ts_by_mac[location])[mac] = datetime.datetime.fromtimestamp(
179 ip_name = ip_name.strip()
180 match = re.match(r"(\d+\.\d+\.\d+\.\d+) +\(([^\)]+)\)", ip_name)
181 if match is not None:
182 name = match.group(2)
183 self.names_by_mac[mac] = name
185 logger.debug('Weird MAC at the cabin')
186 self.weird_mac_at_cabin = True
188 def is_anyone_in_location_now(self, location: Location) -> bool:
190 if location in self.dark_locations:
191 raise Exception(f"Can't see {location} right now; answer undefined.")
192 for person in Person:
193 if person is not None:
194 loc = self.where_is_person_now(person)
197 if location == location.CABIN and self.weird_mac_at_cabin:
201 def where_is_person_now(self, name: Person) -> Location:
203 if len(self.dark_locations) > 0:
205 f"Can't see {self.dark_locations} right now; answer confidence impacted"
208 warnings.warn(msg, stacklevel=2)
209 logger.debug(f'Looking for {name}...')
211 if name is Person.UNKNOWN:
212 if self.weird_mac_at_cabin:
213 return Location.CABIN
215 return Location.UNKNOWN
219 votes: Dict[Location, int] = {}
220 tiebreaks: Dict[Location, datetime.datetime] = {}
222 for mac in self.devices_by_person[name]:
223 if mac not in self.names_by_mac:
225 mac_name = self.names_by_mac[mac]
226 logger.debug(f'Looking for {name}... check for mac {mac} ({mac_name})')
227 for location in self.location_ts_by_mac:
228 if mac in self.location_ts_by_mac[location]:
229 ts = (self.location_ts_by_mac[location])[mac]
230 logger.debug(f'Seen {mac} ({mac_name}) at {location} since {ts}')
231 tiebreaks[location] = ts
233 (most_recent_location, first_seen_ts) = dict_utils.item_with_max_value(
237 v = votes.get(most_recent_location, 0)
238 votes[most_recent_location] = v + bonus
239 logger.debug(f'{name}: {location} gets {bonus} votes.')
240 credit = int(credit * 0.2) # Note: list most important devices first
244 (location, value) = dict_utils.item_with_max_value(votes)
247 return Location.UNKNOWN
250 @bootstrap.initialize
252 p = PresenceDetection()
253 for person in Person:
254 print(f'{person} => {p.where_is_person_now(person)}')
258 # for location in Location:
259 # print(f'{location} => {p.is_anyone_in_location_now(location)}')
262 if __name__ == '__main__':