def determine_interval(self, devicename, latitude, longitude, battery): """Calculate new interval.""" distancefromhome = None zone_state = self.hass.states.get('zone.home') zone_state_lat = zone_state.attributes['latitude'] zone_state_long = zone_state.attributes['longitude'] distancefromhome = distance( latitude, longitude, zone_state_lat, zone_state_long) distancefromhome = round(distancefromhome / 1000, 1) currentzone = active_zone(self.hass, latitude, longitude) if ((currentzone is not None and currentzone == self._overridestates.get(devicename)) or (currentzone is None and self._overridestates.get(devicename) == 'away')): return self._overridestates[devicename] = None if currentzone is not None: self._intervals[devicename] = 30 return if distancefromhome is None: return if distancefromhome > 25: self._intervals[devicename] = round(distancefromhome / 2, 0) elif distancefromhome > 10: self._intervals[devicename] = 5 else: self._intervals[devicename] = 1 if battery is not None and battery <= 33 and distancefromhome > 3: self._intervals[devicename] = self._intervals[devicename] * 2
def determine_interval(self, devicename, latitude, longitude, battery): """Calculate new interval.""" currentzone = active_zone(self.hass, latitude, longitude) if ((currentzone is not None and currentzone == self._overridestates.get(devicename)) or (currentzone is None and self._overridestates.get(devicename) == 'away')): return zones = (self.hass.states.get(entity_id) for entity_id in sorted(self.hass.states.entity_ids('zone'))) distances = [] for zone_state in zones: zone_state_lat = zone_state.attributes['latitude'] zone_state_long = zone_state.attributes['longitude'] zone_distance = distance(latitude, longitude, zone_state_lat, zone_state_long) distances.append(round(zone_distance / 1000, 1)) if distances: mindistance = min(distances) else: mindistance = None self._overridestates[devicename] = None if currentzone is not None: self._intervals[devicename] = 30 return if mindistance is None: return # Calculate out how long it would take for the device to drive to the # nearest zone at 120 km/h: interval = round(mindistance / 2, 0) # Never poll more than once per minute interval = max(interval, 1) if interval > 180: # Three hour drive? This is far enough that they might be flying # home - check every half hour interval = 30 if battery is not None and battery <= 33 and mindistance > 3: # Low battery - let's check half as often interval = interval * 2 self._intervals[devicename] = interval
def determine_interval(self, devicename, latitude, longitude, battery): """Calculate new interval.""" currentzone = active_zone(self.hass, latitude, longitude) if ((currentzone is not None and currentzone == self._overridestates.get(devicename)) or (currentzone is None and self._overridestates.get(devicename) == 'away')): return zones = (self.hass.states.get(entity_id) for entity_id in sorted(self.hass.states.entity_ids('zone'))) distances = [] for zone_state in zones: zone_state_lat = zone_state.attributes['latitude'] zone_state_long = zone_state.attributes['longitude'] zone_distance = distance( latitude, longitude, zone_state_lat, zone_state_long) distances.append(round(zone_distance / 1000, 1)) if distances: mindistance = min(distances) else: mindistance = None self._overridestates[devicename] = None if currentzone is not None: self._intervals[devicename] = self._max_interval return if mindistance is None: return # Calculate out how long it would take for the device to drive to the # nearest zone at 120 km/h: interval = round(mindistance / 2, 0) # Never poll more than once per minute interval = max(interval, 1) if interval > 180: # Three hour drive? This is far enough that they might be flying interval = 30 if battery is not None and battery <= 33 and mindistance > 3: # Low battery - let's check half as often interval = interval * 2 self._intervals[devicename] = interval
def setinterval(self, interval=None, devicename=None): """Set the interval of the given devices.""" devs = [devicename] if devicename else self.devices for device in devs: devid = '{}.{}'.format(DOMAIN, device) devicestate = self.hass.states.get(devid) if interval is not None: if devicestate is not None: self._overridestates[device] = active_zone( self.hass, float(devicestate.attributes.get('latitude', 0)), float(devicestate.attributes.get('longitude', 0))) if self._overridestates[device] is None: self._overridestates[device] = 'away' self._intervals[device] = interval else: self._overridestates[device] = None self.update_device(device)
def _update_member(self, m): f = m['firstName'] l = m['lastName'] #_LOGGER.debug('Checking "{}, {}"'.format(f, l)) m_name = ('_'.join([f, l]) if f and l else f or l).replace('-', '_') dev_id = util.slugify(self._prefix + m_name) prev_update, reported = self._dev_data.get(dev_id, (None, False)) loc = m.get('location') last_update = None if not loc else utc_from_ts(loc['timestamp']) if self._max_update_wait: update = last_update or prev_update or self._started overdue = util.dt.utcnow() - update > self._max_update_wait if overdue and not reported: self._hass.bus.fire( 'device_tracker.life360_update_overdue', {'entity_id': ENTITY_ID_FORMAT.format(dev_id)}) reported = True elif not overdue and reported: self._hass.bus.fire( 'device_tracker.life360_update_restored', { 'entity_id': ENTITY_ID_FORMAT.format(dev_id), 'wait': str(last_update - (prev_update or self._started)).split('.')[0] }) reported = False if not loc: err_msg = m['issues']['title'] if err_msg: if m['issues']['dialog']: err_msg += ': ' + m['issues']['dialog'] else: err_msg = 'Location information missing' _LOGGER.error('{}: {}'.format(dev_id, err_msg)) elif prev_update is None or last_update > prev_update: msg = 'Updating {}'.format(dev_id) if prev_update is not None: msg += '; Time since last update: {}'.format(last_update - prev_update) _LOGGER.debug(msg) attrs = { ATTR_LAST_UPDATE: dt_attr_from_utc(last_update), ATTR_AT_LOC_SINCE: dt_attr_from_ts(loc['since']), ATTR_MOVING: bool_attr_from_int(loc['inTransit']), ATTR_CHARGING: bool_attr_from_int(loc['charge']), ATTR_WIFI_ON: bool_attr_from_int(loc['wifiState']), ATTR_DRIVING: bool_attr_from_int(loc['isDriving']) } lat = float(loc['latitude']) lon = float(loc['longitude']) gps_accuracy = round(float(loc['accuracy'])) # Does user want location name to be shown as state? loc_name = loc[ 'name'] if ATTR_PLACES in self._show_as_state else None # Make sure Home is always seen as exactly as home, # which is the special device_tracker state for home. if loc_name is not None and loc_name.lower() == 'home': loc_name = 'home' # If we don't have a location name yet and user wants driving or moving # to be shown as state, and current location is not in a HA zone, # then update location name accordingly. if not loc_name and not active_zone(self._hass, lat, lon, gps_accuracy): if ATTR_DRIVING in self._show_as_state and attrs[ ATTR_DRIVING] is True: loc_name = ATTR_DRIVING.capitalize() elif ATTR_MOVING in self._show_as_state and attrs[ ATTR_MOVING] is True: loc_name = ATTR_MOVING.capitalize() self._see(dev_id=dev_id, location_name=loc_name, gps=(lat, lon), gps_accuracy=gps_accuracy, battery=round(float(loc['battery'])), attributes=attrs) self._dev_data[dev_id] = last_update or prev_update, reported
def _update_member(self, m, name): name = name.replace(',', '_').replace('-', '_') dev_id = slugify(self._prefix + name) prev_seen, reported = self._dev_data.get(dev_id, (None, False)) loc = m.get('location') try: last_seen = utc_from_ts(loc.get('timestamp')) except AttributeError: last_seen = None if self._max_update_wait: update = last_seen or prev_seen or self._started overdue = dt_util.utcnow() - update > self._max_update_wait if overdue and not reported: self._hass.bus.fire( 'life360_update_overdue', {'entity_id': DT_ENTITY_ID_FORMAT.format(dev_id)}) reported = True elif not overdue and reported: self._hass.bus.fire( 'life360_update_restored', { 'entity_id': DT_ENTITY_ID_FORMAT.format(dev_id), 'wait': str(last_seen - (prev_seen or self._started)).split('.')[0] }) reported = False self._dev_data[dev_id] = last_seen or prev_seen, reported if not loc: err_msg = m['issues']['title'] if err_msg: if m['issues']['dialog']: err_msg += ': ' + m['issues']['dialog'] else: err_msg = 'Location information missing' self._err(dev_id, err_msg) return if last_seen and (not prev_seen or last_seen > prev_seen): lat = loc.get('latitude') lon = loc.get('longitude') gps_accuracy = loc.get('accuracy') try: lat = float(lat) lon = float(lon) # Life360 reports accuracy in feet, but Device Tracker expects # gps_accuracy in meters. gps_accuracy = round( convert(float(gps_accuracy), LENGTH_FEET, LENGTH_METERS)) except (TypeError, ValueError): self._err( dev_id, 'GPS data invalid: {}, {}, {}'.format( lat, lon, gps_accuracy)) return self._ok(dev_id) msg = 'Updating {}'.format(dev_id) if prev_seen: msg += '; Time since last update: {}'.format(last_seen - prev_seen) _LOGGER.debug(msg) if (self._max_gps_accuracy is not None and gps_accuracy > self._max_gps_accuracy): _LOGGER.info('{}: Ignoring update because expected GPS ' 'accuracy {} is not met: {}'.format( dev_id, gps_accuracy, self._max_gps_accuracy)) return place_name = loc.get('name') or None # Does user want location name to be shown as state? if SHOW_PLACES in self._show_as_state: loc_name = place_name # Make sure Home Place is always seen exactly as home, # which is the special device_tracker state for home. if loc_name and loc_name.lower() == self._home_place: loc_name = STATE_HOME else: loc_name = None # If a place name is given, then address will just be a copy of # it, so don't bother with address. Otherwise, piece address # lines together, depending on which are present. if place_name: address = None else: address1 = loc.get('address1') or None address2 = loc.get('address2') or None if address1 and address2: address = ', '.join([address1, address2]) else: address = address1 or address2 raw_speed = loc.get('speed') try: speed = float(raw_speed) * SPEED_FACTOR_MPH if self._hass.config.units.is_metric: speed = convert(speed, LENGTH_MILES, LENGTH_KILOMETERS) speed = max(0, round(speed)) except (TypeError, ValueError): speed = STATE_UNKNOWN driving = bool_attr_from_int(loc.get('isDriving')) if (driving in (STATE_UNKNOWN, False) and self._driving_speed is not None and speed != STATE_UNKNOWN): driving = speed >= self._driving_speed moving = bool_attr_from_int(loc.get('inTransit')) if self._time_as in [TZ_DEVICE_UTC, TZ_DEVICE_LOCAL]: # timezone_at will return a string or None. tzname = self._tf.timezone_at(lng=lon, lat=lat) # get_time_zone will return a tzinfo or None. tz = dt_util.get_time_zone(tzname) attrs = {ATTR_TIME_ZONE: tzname or STATE_UNKNOWN} else: tz = None attrs = {} attrs.update({ ATTR_ADDRESS: address, ATTR_AT_LOC_SINCE: self._dt_attr_from_ts(loc.get('since'), tz), ATTR_BATTERY_CHARGING: bool_attr_from_int(loc.get('charge')), ATTR_DRIVING: driving, ATTR_LAST_SEEN: self._dt_attr_from_utc(last_seen, tz), ATTR_MOVING: moving, ATTR_RAW_SPEED: raw_speed, ATTR_SPEED: speed, ATTR_WIFI_ON: bool_attr_from_int(loc.get('wifiState')), }) # If we don't have a location name yet and user wants driving or moving # to be shown as state, and current location is not in a HA zone, # then update location name accordingly. if not loc_name and not active_zone(self._hass, lat, lon, gps_accuracy): if SHOW_DRIVING in self._show_as_state and driving is True: loc_name = SHOW_DRIVING.capitalize() elif SHOW_MOVING in self._show_as_state and moving is True: loc_name = SHOW_MOVING.capitalize() try: battery = int(float(loc.get('battery'))) except (TypeError, ValueError): battery = None self._see(dev_id=dev_id, location_name=loc_name, gps=(lat, lon), gps_accuracy=gps_accuracy, battery=battery, attributes=attrs, picture=m.get('avatar'))
def _update_info(self, entity_id, old_state, new_state, init=False): if new_state is None: return with self._lock: # Get time device was last seen, which is the entity's last_seen # attribute, or if that doesn't exist, then last_updated from the # new state object. Make sure last_seen is timezone aware in UTC. # Note that dt_util.as_utc assumes naive datetime is in local # timezone. last_seen = new_state.attributes.get(ATTR_LAST_SEEN) if isinstance(last_seen, datetime): last_seen = dt_util.as_utc(last_seen) else: try: last_seen = dt_util.utc_from_timestamp(float(last_seen)) except (TypeError, ValueError): last_seen = new_state.last_updated # Is this newer info than last update? if self._prev_seen and last_seen <= self._prev_seen: _LOGGER.debug( 'For {} skipping update from {}: ' 'last_seen not newer than previous update ({} <= {})'. format(self._entity_id, entity_id, last_seen, self._prev_seen)) return # Try to get GPS and battery data. try: gps = (new_state.attributes[ATTR_LATITUDE], new_state.attributes[ATTR_LONGITUDE]) except KeyError: gps = None gps_accuracy = new_state.attributes.get(ATTR_GPS_ACCURACY) battery = new_state.attributes.get( ATTR_BATTERY, new_state.attributes.get(ATTR_BATTERY_LEVEL)) charging = new_state.attributes.get( ATTR_BATTERY_CHARGING, new_state.attributes.get(ATTR_CHARGING)) # Don't use location_name unless we have to. location_name = None # What type of tracker is this? if new_state.domain == BS_DOMAIN: source_type = SOURCE_TYPE_BINARY_SENSOR else: source_type = new_state.attributes.get(ATTR_SOURCE_TYPE) state = new_state.state if source_type == SOURCE_TYPE_GPS: # GPS coordinates and accuracy are required. if gps is None: self._bad_entity(entity_id, 'missing gps attributes', init) return if gps_accuracy is None: self._bad_entity(entity_id, 'missing gps_accuracy attribute', init) return self._good_entity(entity_id, SOURCE_TYPE_GPS, state) elif source_type in SOURCE_TYPE_NON_GPS: # Convert 'on'/'off' state of binary_sensor # to 'home'/'not_home'. if source_type == SOURCE_TYPE_BINARY_SENSOR: if state == STATE_BINARY_SENSOR_HOME: state = STATE_HOME else: state = STATE_NOT_HOME self._good_entity(entity_id, source_type, state) if not self._use_non_gps_data(state): return # Don't use new GPS data if it's not complete. if gps is None or gps_accuracy is None: gps = gps_accuracy = None # Get current GPS data, if any, and determine if it is in # 'zone.home'. cur_state = self._hass.states.get(self._entity_id) try: cur_lat = cur_state.attributes[ATTR_LATITUDE] cur_lon = cur_state.attributes[ATTR_LONGITUDE] cur_acc = cur_state.attributes[ATTR_GPS_ACCURACY] cur_gps_is_home = (active_zone( self._hass, cur_lat, cur_lon, cur_acc).entity_id == ENTITY_ID_HOME) except (AttributeError, KeyError): cur_gps_is_home = False # It's important, for this composite tracker, to avoid the # component level code's "stale processing." This can be done # one of two ways: 1) provide GPS data w/ source_type of gps, # or 2) provide a location_name (that will be used as the new # state.) # If router entity's state is 'home' and current GPS data from # composite entity is available and is in 'zone.home', # use it and make source_type gps. if state == STATE_HOME and cur_gps_is_home: gps = cur_lat, cur_lon gps_accuracy = cur_acc source_type = SOURCE_TYPE_GPS # Otherwise, if new GPS data is valid (which is unlikely if # new state is not 'home'), # use it and make source_type gps. elif gps: source_type = SOURCE_TYPE_GPS # Otherwise, don't use any GPS data, but set location_name to # new state. else: location_name = state else: self._bad_entity( entity_id, 'unsupported source_type: {}'.format(source_type), init) return tz = None if self._time_as in [TZ_DEVICE_UTC, TZ_DEVICE_LOCAL]: tzname = None if gps: # timezone_at will return a string or None. tzname = self._tf.timezone_at(lng=gps[1], lat=gps[0]) # get_time_zone will return a tzinfo or None. tz = dt_util.get_time_zone(tzname) attrs = {ATTR_TIME_ZONE: tzname or STATE_UNKNOWN} else: attrs = {} attrs.update({ ATTR_ENTITY_ID: tuple(entity_id for entity_id, entity in self._entities.items() if entity[ATTR_SOURCE_TYPE] is not None), ATTR_LAST_ENTITY_ID: entity_id, ATTR_LAST_SEEN: self._dt_attr_from_utc(last_seen.replace(microsecond=0), tz) }) if charging is not None: attrs[ATTR_BATTERY_CHARGING] = charging self._see(dev_id=self._dev_id, location_name=location_name, gps=gps, gps_accuracy=gps_accuracy, battery=battery, attributes=attrs, source_type=source_type) self._prev_seen = last_seen
def _update_member(self, m, name): name = name.replace(',', '_').replace('-', '_') dev_id = util.slugify(self._prefix + name) prev_seen, reported = self._dev_data.get(dev_id, (None, False)) loc = m.get('location') try: last_seen = utc_from_ts(loc.get('timestamp')) except AttributeError: last_seen = None if self._max_update_wait: update = last_seen or prev_seen or self._started overdue = util.dt.utcnow() - update > self._max_update_wait if overdue and not reported: self._hass.bus.fire( 'device_tracker.life360_update_overdue', {'entity_id': ENTITY_ID_FORMAT.format(dev_id)}) reported = True elif not overdue and reported: self._hass.bus.fire( 'device_tracker.life360_update_restored', { 'entity_id': ENTITY_ID_FORMAT.format(dev_id), 'wait': str(last_seen - (prev_seen or self._started)).split('.')[0] }) reported = False self._dev_data[dev_id] = last_seen or prev_seen, reported if not loc: err_msg = m['issues']['title'] if err_msg: if m['issues']['dialog']: err_msg += ': ' + m['issues']['dialog'] else: err_msg = 'Location information missing' self._err(dev_id, err_msg) return if last_seen and (not prev_seen or last_seen > prev_seen): lat = loc.get('latitude') lon = loc.get('longitude') gps_accuracy = loc.get('accuracy') try: lat = float(lat) lon = float(lon) # Life360 reports accuracy in feet, but Device Tracker expects # gps_accuracy in meters. gps_accuracy = round(float(gps_accuracy) * 0.3048) except (TypeError, ValueError): self._err( dev_id, 'GPS data invalid: {}, {}, {}'.format( lat, lon, gps_accuracy)) return self._ok(dev_id) msg = 'Updating {}'.format(dev_id) if prev_seen: msg += '; Time since last update: {}'.format(last_seen - prev_seen) _LOGGER.debug(msg) if (self._max_gps_accuracy is not None and gps_accuracy > self._max_gps_accuracy): _LOGGER.info('{}: Ignoring update because expected GPS ' 'accuracy {} is not met: {}'.format( dev_id, gps_accuracy, self._max_gps_accuracy)) return place_name = loc.get('name') or None # Does user want location name to be shown as state? if ATTR_PLACES in self._show_as_state: loc_name = place_name # Make sure Home is always seen as exactly as home, # which is the special device_tracker state for home. if loc_name and loc_name.lower() == 'home': loc_name = 'home' else: loc_name = None # If a place name is given, then address will just be a copy of # it, so don't bother with address. Otherwise, piece address # lines together, depending on which are present. if place_name: address = None else: address1 = loc.get('address1') or None address2 = loc.get('address2') or None if address1 and address2: address = ', '.join([address1, address2]) else: address = address1 or address2 attrs = { ATTR_LAST_SEEN: last_seen, ATTR_AT_LOC_SINCE: utc_attr_from_ts(loc.get('since')), ATTR_MOVING: bool_attr_from_int(loc.get('inTransit')), ATTR_CHARGING: bool_attr_from_int(loc.get('charge')), ATTR_WIFI_ON: bool_attr_from_int(loc.get('wifiState')), ATTR_DRIVING: bool_attr_from_int(loc.get('isDriving')), ATTR_ADDRESS: address } # If we don't have a location name yet and user wants driving or moving # to be shown as state, and current location is not in a HA zone, # then update location name accordingly. if not loc_name and not active_zone(self._hass, lat, lon, gps_accuracy): if ATTR_DRIVING in self._show_as_state and attrs[ ATTR_DRIVING] is True: loc_name = ATTR_DRIVING.capitalize() elif ATTR_MOVING in self._show_as_state and attrs[ ATTR_MOVING] is True: loc_name = ATTR_MOVING.capitalize() try: battery = float(loc.get('battery')) except (TypeError, ValueError): battery = None self._see(dev_id=dev_id, location_name=loc_name, gps=(lat, lon), gps_accuracy=gps_accuracy, battery=battery, attributes=attrs, picture=m.get('avatar'))