3 """This is a module dealing with trying to guess a person's location
4 based on the location of certain devices (e.g. phones, laptops)
5 belonging to that person. It works with networks I run that log
6 device MAC addresses active."""
12 from collections import defaultdict
13 from typing import Dict, List, Optional, Set
15 # Note: this module is fairly early loaded. Be aware of dependencies.
20 from type.locations import Location
21 from type.people import Person
23 logger = logging.getLogger(__name__)
25 cfg = config.add_commandline_args(
26 f"Presence Detection ({__file__})",
27 "Args related to detection of human beings in locations.",
30 "--presence_macs_file",
31 type=argparse_utils.valid_filename,
32 default="/home/scott/cron/persisted_mac_addresses.txt",
34 help="The location of persisted_mac_addresses.txt to use.",
37 '--presence_tolerable_staleness_seconds',
38 type=argparse_utils.valid_duration,
39 default=datetime.timedelta(seconds=60 * 5),
41 help='Max acceptable age of location data before auto-refreshing',
45 class PresenceDetection(object):
46 """See above. This is a base class for determining a person's
47 location on networks I administer."""
49 def __init__(self) -> None:
50 # Note: list most important devices first.
51 self.devices_by_person: Dict[Person, List[str]] = {
53 "DC:E5:5B:0F:03:3D", # pixel6
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.run_location = site_config.get_location()
78 logger.debug("base_presence run_location is %s", self.run_location)
79 self.weird_mac_at_cabin = False
80 self.location_ts_by_mac: Dict[Location, Dict[str, datetime.datetime]] = defaultdict(dict)
81 self.names_by_mac: Dict[str, str] = {}
82 self.dark_locations: Set[Location] = set()
83 self.last_update: Optional[datetime.datetime] = None
85 def maybe_update(self) -> None:
86 if self.last_update is None:
89 now = datetime.datetime.now()
90 delta = now - self.last_update
93 > config.config['presence_tolerable_staleness_seconds'].total_seconds()
96 "It's been %ss since last update; refreshing now.", delta.total_seconds()
100 def update(self) -> None:
101 self.dark_locations = set()
102 if self.run_location is Location.HOUSE:
103 self.update_from_house()
104 elif self.run_location is Location.CABIN:
105 self.update_from_cabin()
107 raise Exception("Where the hell is this running?!")
108 self.last_update = datetime.datetime.now()
110 def update_from_house(self) -> None:
111 from exec_utils import cmd
114 persisted_macs = config.config['presence_macs_file']
116 persisted_macs = '/home/scott/cron/persisted_mac_addresses.txt'
117 self.read_persisted_macs_file(persisted_macs, Location.HOUSE)
121 timeout_seconds=10.0,
123 self.parse_raw_macs_file(raw, Location.CABIN)
124 except Exception as e:
126 msg = "Can't see the cabin right now; presence detection impared."
128 logger.warning(msg, stacklevel=2)
129 self.dark_locations.add(Location.CABIN)
131 def update_from_cabin(self) -> None:
132 from exec_utils import cmd
135 persisted_macs = config.config['presence_macs_file']
137 persisted_macs = '/home/scott/cron/persisted_mac_addresses.txt'
138 self.read_persisted_macs_file(persisted_macs, Location.CABIN)
142 timeout_seconds=10.0,
144 self.parse_raw_macs_file(raw, Location.HOUSE)
145 except Exception as e:
147 msg = "Can't see the house right now; presence detection impared."
149 warnings.warn(msg, stacklevel=2)
150 self.dark_locations.add(Location.HOUSE)
152 def read_persisted_macs_file(self, filename: str, location: Location) -> None:
153 if location is Location.UNKNOWN:
155 with open(filename, "r") as rf:
157 self.parse_raw_macs_file(lines, location)
159 def parse_raw_macs_file(self, raw: str, location: Location) -> None:
160 lines = raw.split("\n")
162 # CC:F4:11:D7:FA:EE, 2240, 10.0.0.22 (side_deck_high_home), Google, 1611681990
168 logger.debug('%s> %s', location, line)
171 if location == Location.CABIN:
172 logger.debug('Cabin count: %d', cabin_count)
175 (mac, _, ip_name, _, ts) = line.split(",") # type: ignore
176 except Exception as e:
178 logger.error('SKIPPED BAD LINE> %s', line)
181 (self.location_ts_by_mac[location])[mac] = datetime.datetime.fromtimestamp(
184 ip_name = ip_name.strip()
185 match = re.match(r"(\d+\.\d+\.\d+\.\d+) +\(([^\)]+)\)", ip_name)
186 if match is not None:
187 name = match.group(2)
188 self.names_by_mac[mac] = name
190 logger.debug('Weird MAC at the cabin')
191 self.weird_mac_at_cabin = True
193 def is_anyone_in_location_now(self, location: Location) -> bool:
195 if location in self.dark_locations:
196 raise Exception(f"Can't see {location} right now; answer undefined.")
197 for person in Person:
198 if person is not None:
199 loc = self.where_is_person_now(person)
202 if location == location.CABIN and self.weird_mac_at_cabin:
206 def where_is_person_now(self, name: Person) -> Location:
208 if len(self.dark_locations) > 0:
209 msg = f"Can't see {self.dark_locations} right now; answer confidence impacted"
211 warnings.warn(msg, stacklevel=2)
212 logger.debug('Looking for %s...', name)
214 if name is Person.UNKNOWN:
215 if self.weird_mac_at_cabin:
216 return Location.CABIN
218 return Location.UNKNOWN
222 votes: Dict[Location, int] = {}
223 tiebreaks: Dict[Location, datetime.datetime] = {}
226 for mac in self.devices_by_person[name]:
227 if mac not in self.names_by_mac:
229 mac_name = self.names_by_mac[mac]
230 logger.debug('Looking for %s... check for mac %s (%s)', name, mac, mac_name)
231 for location in self.location_ts_by_mac:
232 if mac in self.location_ts_by_mac[location]:
233 ts = (self.location_ts_by_mac[location])[mac]
234 logger.debug('Seen %s (%s) at %s since %s', mac, mac_name, location, ts)
235 tiebreaks[location] = ts
238 most_recent_location,
240 ) = dict_utils.item_with_max_value(tiebreaks)
242 v = votes.get(most_recent_location, 0)
243 votes[most_recent_location] = v + bonus
244 logger.debug('%s: %s gets %d votes.', name, most_recent_location, bonus)
245 credit = int(credit * 0.2) # Note: list most important devices first
249 (location, value) = dict_utils.item_with_max_value(votes)
253 return Location.UNKNOWN
256 @bootstrap.initialize
258 p = PresenceDetection()
259 for person in Person:
260 print(f'{person} => {p.where_is_person_now(person)}')
262 for location in Location:
263 print(f'{location} => {p.is_anyone_in_location_now(location)}')
266 if __name__ == '__main__':