diff --git a/custom_components/icloud3/__init__.py b/custom_components/icloud3/__init__.py index d8c2ac7..6aa6c4f 100644 --- a/custom_components/icloud3/__init__.py +++ b/custom_components/icloud3/__init__.py @@ -1 +1 @@ -""" iCloud3 Device Tracker """ +"""iCloud3 Device Tracker""" diff --git a/custom_components/icloud3/device_tracker.py b/custom_components/icloud3/device_tracker.py index 8fb6926..6947acb 100644 --- a/custom_components/icloud3/device_tracker.py +++ b/custom_components/icloud3/device_tracker.py @@ -22,7 +22,7 @@ #pylint: disable=unused-argument, unused-variable #pylint: disable=too-many-instance-attributes, too-many-lines -VERSION = '2.2.0' +VERSION = '2.2.1' #Symbols = •▶¦▶ ●►◄ ▬ ▲▼◀▶ oPhone=►▶► @@ -95,13 +95,15 @@ CONF_DEVICENAME = 'device_name' CONF_NAME = 'name' CONF_TRACKING_METHOD = 'tracking_method' -CONF_IOSAPP_LOCATE_REQUEST_MAX_CNT = 'iosapp_locate_request_max_cnt' +CONF_IOSAPP_REQUEST_LOC_MAX_CNT = 'iosapp_request_loc_max_cnt' CONF_TRACK_DEVICES = 'track_devices' CONF_TRACK_DEVICE = 'track_device' CONF_UNIT_OF_MEASUREMENT = 'unit_of_measurement' +CONF_TIME_FORMAT = 'time_format' CONF_INTERVAL = 'interval' CONF_BASE_ZONE = 'base_zone' CONF_INZONE_INTERVAL = 'inzone_interval' +CONF_DISPLAY_ZONE_FNAME = 'display_zone_fname' CONF_CENTER_IN_ZONE = 'center_in_zone' CONF_STATIONARY_STILL_TIME = 'stationary_still_time' CONF_STATIONARY_INZONE_INTERVAL = 'stationary_inzone_interval' @@ -187,11 +189,21 @@ ATTR_EVENT_LOG = 'event_log' ATTR_PICTURE = 'entity_picture' - +#General constants +HOME = 'home' +NOT_HOME = 'not_home' +NOT_SET = 'not_set' +STATIONARY = 'stationary' +AWAY_FROM = 'AwayFrom' +AWAY = 'Away' +PAUSED = 'Paused' +PAUSED_CAPS = 'PAUSED' +UNKNOWN = 'Unknown' +NEVER = 'Never' +ERROR = 'Error' TIMESTAMP_ZERO = '0000-00-00 00:00:00' HHMMSS_ZERO = '00:00:00' HIGH_INTEGER = 9999999999 -TIME_24H = True UTC_TIME = True LOCAL_TIME = False NUMERIC = True @@ -218,8 +230,8 @@ ATTR_NAME: '', ATTR_DEVICE_CLASS: 'iPhone', ATTR_BATTERY_LEVEL: 0, - ATTR_BATTERY_STATUS: 'Unknown', - ATTR_DEVICE_STATUS: '', + ATTR_BATTERY_STATUS: UNKNOWN, + ATTR_DEVICE_STATUS: UNKNOWN, ATTR_LOW_POWER_MODE: False, ATTR_TIMESTAMP: 0, ATTR_TIMESTAMP_TIME: HHMMSS_ZERO, @@ -349,9 +361,9 @@ SENSOR_ATTR_ICON = { 'zone': 'mdi:cellphone-iphone', - 'last_zone': 'mdi:cellphone-iphone', - 'base_zone': 'mdi:cellphone-iphone', - 'zone_timestamp': 'mdi:restore-clock', + 'last_zone': 'mdi:map-clock-outline', + 'base_zone': 'mdi:map-clock', + 'zone_timestamp': 'mdi:clock-in', 'zone_distance': 'mdi:map-marker-distance', 'calc_distance': 'mdi:map-marker-distance', 'waze_distance': 'mdi:map-marker-distance', @@ -359,14 +371,14 @@ 'dir_of_travel': 'mdi:compass-outline', 'interval': 'mdi:clock-start', 'info': 'mdi:information-outline', - 'last_located': 'mdi:restore-clock', - 'last_update': 'mdi:restore-clock', + 'last_located': 'mdi:history', + 'last_update': 'mdi:history', 'next_update': 'mdi:update', 'poll_count': 'mdi:counter', 'travel_distance': 'mdi:map-marker-distance', 'trigger': 'mdi:flash-outline', - 'battery': 'mdi:battery', - 'battery_status': 'mdi:battery', + 'battery': 'mdi:battery-outline', + 'battery_status': 'mdi:battery-outline', 'gps_accuracy': 'mdi:map-marker-radius', 'altitude': 'mdi:image-filter-hdr', 'vertical_accuracy': 'mdi:map-marker-radius', @@ -408,32 +420,48 @@ 'name': 'name', } - -ATTR_TIMESTAMP_FORMAT = '%Y-%m-%d %H:%M:%S.%f' -APPLE_DEVICE_TYPES = ['iphone', 'ipad', 'ipod', 'watch', 'iwatch', 'icloud', - 'iPhone', 'iPad', 'iPod', 'Watch', 'iWatch', 'iCloud'] +ATTR_TIMESTAMP_FORMAT = '%Y-%m-%d %H:%M:%S.%f' +APPLE_DEVICE_TYPES = ['iphone', 'ipad', 'ipod', 'watch', 'iwatch', 'icloud', + 'iPhone', 'iPad', 'iPod', 'Watch', 'iWatch', 'iCloud'] FMF_FAMSHR_LOCATION_FIELDS = ['altitude', 'latitude', 'longitude', 'timestamp', 'horizontalAccuracy', 'verticalAccuracy', ATTR_ICLOUD_BATTERY_STATUS] + +#Convert zone/state value to display value +ZONE_TO_DISPLAY_BASE = { + None: "not_home", + "not_home": "Away", + "not_set": "NotSet", + "away": "Away", + "stationary": "Stationary", + "nearzone": "NearZone", + "near_zone": "NearZone", + } +#Convert state non-fname value to internal zone/state value +STATE_TO_ZONE_BASE = { + "NotSet": "not_set", + "Away": "not_home", + "away": "not_home", + "NotHome": "not_home", + "nothome": "not_home", + "Stationary": "stationary", + "stationary": "stationary", + "NearZone": "nearzone", + "NearZone": "near_zone", + } + #icloud_update commands CMD_ERROR = 1 CMD_INTERVAL = 2 CMD_PAUSE = 3 CMD_RESUME = 4 CMD_WAZE = 5 +CMD_LOCATION = 6 #Other constants IOSAPP_DT_ENTITY = True ICLOUD_DT_ENTITY = False ICLOUD_LOCATION_DATA_ERROR = False -#General constants -HOME = 'home' -NOT_HOME = 'not_home' -NOT_SET = 'not_set' -STATIONARY = 'stationary' -AWAY_FROM = 'AwayFrom' -AWAY = 'Away' -PAUSED = 'Paused' STATIONARY_LAT_90 = 90 STATIONARY_LONG_180 = 180 STAT_ZONE_NEW_LOCATION = True @@ -446,7 +474,6 @@ ICLOUD3_ERROR_MSG = "ICLOUD3 ERROR-SEE EVENT LOG" #Devicename config parameter file extraction - DI_DEVICENAME = 0 DI_DEVICE_TYPE = 1 DI_NAME = 2 @@ -456,7 +483,6 @@ DI_IOSAPP_SUFFIX = 6 DI_ZONES = 7 - #Waze status codes WAZE_REGIONS = ['US', 'NA', 'EU', 'IL', 'AU'] WAZE_USED = 0 @@ -465,6 +491,16 @@ WAZE_OUT_OF_RANGE = 3 WAZE_NO_DATA = 4 +#Interval range table used for setting the interval based on a retry count +#The key is starting retry count range, the value is the interval (in minutes) +#poor_location_gps cnt, icloud_authentication cnt (default) +POOR_LOC_GPS_CNT = 1.1 +AUTH_ERROR_CNT = 1.2 +RETRY_INTERVAL_RANGE_1 = {0:.25, 4:1, 8:5, 12:30, 16:60, 20:120, 24:240} +#request iosapp location retry cnt +IOSAPP_REQUEST_LOC_CNT = 2.1 +RETRY_INTERVAL_RANGE_2 = {0:.5, 4:2, 8:30, 12:60, 14:120, 16:240, 18:480} + #Used by the 'update_method' in the polling_5_sec loop IOSAPP_UPDATE = "IOSAPP" ICLOUD_UPDATE = "ICLOUD" @@ -604,7 +640,7 @@ vol.Optional(CONF_PASSWORD, default=''): cv.string, vol.Optional(CONF_GROUP, default='group'): cv.slugify, vol.Optional(CONF_TRACKING_METHOD, default=FMF): cv.slugify, - vol.Optional(CONF_IOSAPP_LOCATE_REQUEST_MAX_CNT, default=100): cv.string, + vol.Optional(CONF_IOSAPP_REQUEST_LOC_MAX_CNT, default=HIGH_INTEGER): cv.string, vol.Optional(CONF_ENTITY_REGISTRY_FILE): cv.string, vol.Optional(CONF_CONFIG_IC3_FILE_NAME, default=''): cv.string, vol.Optional(CONF_EVENT_LOG_CARD_DIRECTORY, default='www/custom_cards'): cv.string, @@ -613,7 +649,9 @@ #-----►►General Attributes ---------- vol.Optional(CONF_UNIT_OF_MEASUREMENT, default='mi'): cv.slugify, + vol.Optional(CONF_TIME_FORMAT, default=0): cv.string, vol.Optional(CONF_INZONE_INTERVAL, default='2 hrs'): cv.string, + vol.Optional(CONF_DISPLAY_ZONE_FNAME, default=False): cv.boolean, vol.Optional(CONF_CENTER_IN_ZONE, default=False): cv.boolean, vol.Optional(CONF_MAX_INTERVAL, default='4 hrs'): cv.string, vol.Optional(CONF_TRAVEL_TIME_FACTOR, default=.60): cv.string, @@ -622,7 +660,7 @@ vol.Optional(CONF_IGNORE_GPS_ACC_INZONE, default=True): cv.boolean, vol.Optional(CONF_HIDE_GPS_COORDINATES, default=False): cv.boolean, vol.Optional(CONF_LOG_LEVEL, default=''): cv.string, - vol.Optional(CONF_DEVICE_STATUS, default='online'): cv.string, + vol.Optional(CONF_DEVICE_STATUS, default='online, pending'): cv.string, #-----►►Filter, Include, Exclude Devices ---------- vol.Optional(CONF_TRACK_DEVICES, default=[]): vol.All(cv.ensure_list, [cv.string]), @@ -646,7 +684,9 @@ DEFAULT_CONFIG_VALUES = { CONF_UNIT_OF_MEASUREMENT: 'mi', + CONF_TIME_FORMAT: 0, CONF_INZONE_INTERVAL: '2 hrs', + CONF_DISPLAY_ZONE_FNAME: False, CONF_CENTER_IN_ZONE: False, CONF_MAX_INTERVAL: '4 hrs', CONF_TRAVEL_TIME_FACTOR: .60, @@ -655,7 +695,7 @@ CONF_IGNORE_GPS_ACC_INZONE: True, CONF_HIDE_GPS_COORDINATES: False, CONF_LOG_LEVEL: '', - CONF_DEVICE_STATUS: 'online', + CONF_DEVICE_STATUS: 'online, pending', CONF_TRACK_DEVICES: [], CONF_TRACK_DEVICE: [], CONF_DISTANCE_METHOD: 'waze', @@ -736,7 +776,7 @@ def format_gps(latitude, longitude, accuracy, latitude_to=None, longitude_to=Non '''Format the GPS string for logs & messages''' accuracy_text = (f"/{accuracy}m)") if accuracy > 0 else "" - gps_to_text = (f" to [{round(latitude_to, 6)}, {round(longitude_to, 6)}]") if latitude_to else "" + gps_to_text = (f" to ({round(latitude_to, 6)}, {round(longitude_to, 6)})") if latitude_to else "" gps_text = f"({round(latitude, 6)}, {round(longitude, 6)}){accuracy_text}{gps_to_text}" return gps_text #============================================================================== @@ -758,7 +798,7 @@ def setup_scanner(hass, config: dict, see, discovery_info=None): entity_registry_file = config.get(CONF_ENTITY_REGISTRY_FILE) config_ic3_file_name = config.get(CONF_CONFIG_IC3_FILE_NAME) event_log_card_directory = config.get(CONF_EVENT_LOG_CARD_DIRECTORY) - iosapp_locate_request_max_cnt = int(config.get(CONF_IOSAPP_LOCATE_REQUEST_MAX_CNT)) + iosapp_request_location_max_cnt = int(config.get(CONF_IOSAPP_REQUEST_LOC_MAX_CNT)) legacy_mode = config.get(CONF_LEGACY_MODE) display_text_as = config.get(CONF_DISPLAY_TEXT_AS) @@ -793,12 +833,14 @@ def setup_scanner(hass, config: dict, see, discovery_info=None): inzone_interval_str = config.get(CONF_INZONE_INTERVAL) max_interval_str = config.get(CONF_MAX_INTERVAL) + display_zone_fname = config.get(CONF_DISPLAY_ZONE_FNAME) center_in_zone_flag = config.get(CONF_CENTER_IN_ZONE) gps_accuracy_threshold = config.get(CONF_GPS_ACCURACY_THRESHOLD) old_location_threshold_str = config.get(CONF_OLD_LOCATION_THRESHOLD) ignore_gps_accuracy_inzone_flag = config.get(CONF_IGNORE_GPS_ACC_INZONE) hide_gps_coordinates = config.get(CONF_HIDE_GPS_COORDINATES) unit_of_measurement = config.get(CONF_UNIT_OF_MEASUREMENT) + time_format = config.get(CONF_TIME_FORMAT) stationary_inzone_interval_str = config.get(CONF_STATIONARY_INZONE_INTERVAL) stationary_still_time_str = config.get(CONF_STATIONARY_STILL_TIME) @@ -828,14 +870,15 @@ def setup_scanner(hass, config: dict, see, discovery_info=None): ICLOUD3_GROUP_OBJS[group] = Icloud3( hass, see, username, password, group, base_zone, tracking_method, track_devices, - iosapp_locate_request_max_cnt, inzone_interval_str, - max_interval_str, center_in_zone_flag, + iosapp_request_location_max_cnt, inzone_interval_str, + max_interval_str, display_zone_fname, center_in_zone_flag, gps_accuracy_threshold, old_location_threshold_str, stationary_inzone_interval_str, stationary_still_time_str, stationary_zone_offset, ignore_gps_accuracy_inzone_flag, hide_gps_coordinates, sensor_ids, exclude_sensor_ids, - unit_of_measurement, travel_time_factor, distance_method, + unit_of_measurement, time_format, + travel_time_factor, distance_method, waze_region, waze_realtime, waze_max_distance, waze_min_distance, log_level, device_status, display_text_as, entity_registry_file, config_ic3_file_name, event_log_card_directory @@ -892,8 +935,9 @@ def _service_callback_setinterval(call): def _service_callback_lost_iphone(call): """Call the lost iPhone function if the device is found.""" - groups = call.data.get(CONF_GROUP, ICLOUD3_GROUP_OBJS) + groups = call.data.get(CONF_GROUP, ICLOUD3_GROUP_OBJS) devicename = call.data.get(CONF_DEVICENAME) + for group in groups: if group in ICLOUD3_GROUP_OBJS: ICLOUD3_GROUP_OBJS[group]._service_handler_lost_iphone( @@ -913,14 +957,15 @@ class Icloud3:#(DeviceScanner): def __init__(self, hass, see, username, password, group, base_zone, tracking_method, track_devices, - iosapp_locate_request_max_cnt, inzone_interval_str, - max_interval_str, center_in_zone_flag, + iosapp_request_location_max_cnt, inzone_interval_str, + max_interval_str, display_zone_fname, center_in_zone_flag, gps_accuracy_threshold, old_location_threshold_str, stationary_inzone_interval_str, stationary_still_time_str, stationary_zone_offset, ignore_gps_accuracy_inzone_flag, hide_gps_coordinates, sensor_ids, exclude_sensor_ids, - unit_of_measurement, travel_time_factor, distance_method, + unit_of_measurement, time_format, + travel_time_factor, distance_method, waze_region, waze_realtime, waze_max_distance, waze_min_distance, log_level, device_status, display_text_as, entity_registry_file, config_ic3_file_name, event_log_card_directory @@ -950,19 +995,21 @@ def __init__(self, self.trusted_devices = None self.tracking_method_config = tracking_method - self.iosapp_locate_request_max_cnt= iosapp_locate_request_max_cnt + self.iosapp_request_loc_max_cnt= iosapp_request_location_max_cnt self.start_icloud3_request_flag = False self.start_icloud3_inprocess_flag = False self.authenticated_time = 0 self.log_level = log_level self.log_level_eventlog_flag = False - self.device_status_online = device_status + self.device_status_online = list(device_status.replace(" ","").split(",")) + self.device_status_online.append('') self.attributes_initialized_flag = False self.track_devices = track_devices self.distance_method_waze_flag = (distance_method.lower() == 'waze') self.inzone_interval_secs = self._time_str_to_secs(inzone_interval_str) self.max_interval_secs = self._time_str_to_secs(max_interval_str) + self.display_zone_fname_flag = display_zone_fname self.center_in_zone_flag = center_in_zone_flag self.gps_accuracy_threshold = int(gps_accuracy_threshold) self.old_location_threshold = self._time_str_to_secs(old_location_threshold_str) @@ -972,6 +1019,7 @@ def __init__(self, self.sensor_ids = sensor_ids self.exclude_sensor_ids = exclude_sensor_ids self.unit_of_measurement = unit_of_measurement + self.time_format = int(time_format) self.travel_time_factor = float(travel_time_factor) self.e_seconds_local_offset_secs = 0 self.waze_region = waze_region @@ -1019,10 +1067,10 @@ def _start_icloud3(self): self.startup_log_msgs_prefix = '' devicename = '' - self._initialize_um_formats(self.unit_of_measurement) self._define_device_fields() self._define_device_status_fields() self._define_device_tracking_fields() + self._define_zone_fields() self._define_device_zone_fields() self._define_tracking_control_fields() self._define_sensor_fields(self.start_icloud3_initial_load_flag) @@ -1035,6 +1083,7 @@ def _start_icloud3(self): self.startup_log_msgs_prefix = NEW_LINE self._check_config_ic3_yaml_parameter_file() self._check_ic3_event_log_file_version() + self._initialize_um_formats(self.unit_of_measurement) for item in self.display_text_as: from_to_text = item.split(">") @@ -1327,22 +1376,22 @@ def _polling_loop_5_sec_device(self, now): return self.this_update_secs = self._time_now_secs() - this_update_hhmmss = dt_util.now().strftime('%H:%M:%S') + self.this_update_time = dt_util.now().strftime('%H:%M:%S') this_minute = int(dt_util.now().strftime('%M')) this_5sec_loop_second = int(dt_util.now().strftime('%S')) #Reset counts on new day, check for daylight saving time new offset - if this_update_hhmmss.endswith(':00:00'): + if self.this_update_time.endswith(':00:00'): self._timer_tasks_every_hour() - if this_update_hhmmss == HHMMSS_ZERO: + if self.this_update_time == HHMMSS_ZERO: self._timer_tasks_midnight() - elif this_update_hhmmss == '01:00:00': + elif self.this_update_time == '01:00:00': self._timer_tasks_1am() #Test code to check ios monitor, display it every minute - #if this_update_hhmmss.endswith(':00'): + #if self.this_update_time.endswith(':00'): # self.last_iosapp_msg['gary_iphone'] = "" try: @@ -1372,12 +1421,14 @@ def _polling_loop_5_sec_device(self, now): ic3dev_state = self._get_state(ic3_entity_id) #Will be not_set with a last_poll value if the iosapp has not be set up - if ic3dev_state == NOT_SET and self.state_last_poll.get(devicename) != NOT_SET: - self._request_iosapp_location_update(devicename) + if (ic3dev_state == NOT_SET + and self.state_last_poll.get(devicename) != NOT_SET): + event_msg = "iOSApp state will be updated after iOSApp starts" + self._save_event(devicename,event_msg) continue - ic3dev_attrs = self._get_device_attributes(ic3_entity_id) #Extract only attrs needed to update the device + ic3dev_attrs = self._get_device_attributes(ic3_entity_id) ic3dev_attrs_avail = {k: v for k, v in ic3dev_attrs.items() if k in DEVICE_ATTRS_BASE} ic3dev_data = {**DEVICE_ATTRS_BASE, **ic3dev_attrs_avail} @@ -1393,7 +1444,7 @@ def _polling_loop_5_sec_device(self, now): ATTR_GPS_ACCURACY: ic3dev_gps_accuracy, ATTR_BATTERY_LEVEL: ic3dev_battery} - #iosapp v2 uses the device_tracker._# entity for + #iosapp uses the device_tracker._# entity for #location info and sensor._last_update_trigger entity #for trigger info. Get location data and trigger. #Use the trigger/timestamp if timestamp is newer than current @@ -1402,6 +1453,7 @@ def _polling_loop_5_sec_device(self, now): update_reason = "" ios_update_reason = "" update_via_iosapp_flag = False + last_located_secs_plus_5 = self.last_located_secs.get(devicename) + 5 if self.iosapp_monitor_dev_trk_flag.get(devicename): iosapp_state, iosapp_dev_attrs, iosapp_data_flag = \ @@ -1426,7 +1478,7 @@ def _polling_loop_5_sec_device(self, now): iosapp_msg = (f"iOSApp Monitor {iosapp_data_msg}> " f"Trigger-{iosapp_trigger}@{iosapp_trigger_changed_time} (%tage ago), " f"State-{iosapp_state}@{iosapp_state_changed_time} (%sage ago), " - f"GPS-{format_gps(iosapp_dev_attrs[ATTR_LATITUDE], iosapp_dev_attrs[ATTR_LONGITUDE], ic3dev_gps_accuracy)}, " + f"GPS-{format_gps(iosapp_dev_attrs[ATTR_LATITUDE], iosapp_dev_attrs[ATTR_LONGITUDE], iosapp_dev_attrs[ATTR_GPS_ACCURACY])}, " f"LastiC3UpdtTime-{self.last_update_time.get(devicename_zone)}, ") #Initialize if first time through @@ -1446,6 +1498,11 @@ def _polling_loop_5_sec_device(self, now): update_via_iosapp_flag = False ios_update_reason = "No data received from the iOS App, using iC3 data" + elif (iosapp_state == NOT_SET + and self.iosapp_request_loc_retry_cnt.get(devicename) == 0): + update_via_iosapp_flag = True + ios_update_reason = "Reinitialize iOSApp location" + elif (instr(iosapp_state, STATIONARY) and iosapp_dev_attrs[ATTR_LATITUDE] == self.stat_zone_base_lat and iosapp_dev_attrs[ATTR_LONGITUDE] == self.stat_zone_base_long): @@ -1457,12 +1514,14 @@ def _polling_loop_5_sec_device(self, now): ios_update_reason = (f"State Change-{iosapp_state}") #trigger time is after last locate - elif iosapp_trigger_changed_secs > (self.last_located_secs.get(devicename) + 5): + #elif iosapp_trigger_changed_secs > (self.last_located_secs.get(devicename) + 5): + elif iosapp_trigger_changed_secs > last_located_secs_plus_5: update_via_iosapp_flag = True ios_update_reason = (f"Trigger Change-{iosapp_trigger}") #State changed more than 5-secs after last locate - elif iosapp_state_changed_secs > (self.last_located_secs.get(devicename) + 5): + #elif iosapp_state_changed_secs > (self.last_located_secs.get(devicename) + 5): + elif iosapp_state_changed_secs > last_located_secs_plus_5: update_via_iosapp_flag = True iosapp_trigger = "iOSApp Loc Update" iosapp_trigger_changed_secs = iosapp_state_changed_secs @@ -1471,7 +1530,8 @@ def _polling_loop_5_sec_device(self, now): #Prevent duplicate update if State & Trigger changed at the same time #and state change was handled on last cycle elif (iosapp_trigger_changed_secs == iosapp_state_changed_secs - or iosapp_trigger_changed_secs <= (self.last_located_secs.get(devicename) + 5)): + or iosapp_trigger_changed_secs <= last_located_secs_plus_5): + # or iosapp_trigger_changed_secs <= (self.last_located_secs.get(devicename) + 5)): self.last_iosapp_trigger[devicename] = iosapp_trigger ios_update_reason = "Already Processed" @@ -1484,7 +1544,8 @@ def _polling_loop_5_sec_device(self, now): elif instr(iosapp_trigger, '@'): ios_update_reason = "Trigger Already Processed" - elif iosapp_trigger_changed_secs <= (self.last_located_secs.get(devicename) + 5): + #elif iosapp_trigger_changed_secs <= (self.last_located_secs.get(devicename) + 5): + elif iosapp_trigger_changed_secs <= last_located_secs_plus_5: ios_update_reason = "Trigger Before Last Locate" else: @@ -1493,7 +1554,7 @@ def _polling_loop_5_sec_device(self, now): iosapp_msg += (f"WillUpdate-{update_via_iosapp_flag}") #Show iOS App monitor every half hour - if this_update_hhmmss.endswith(':00:00') or this_update_hhmmss.endswith(':30:00'): + if self.this_update_time.endswith(':00:00') or self.this_update_time.endswith(':30:00'): self.last_iosapp_msg[devicename] = "" if (iosapp_msg != self.last_iosapp_msg.get(devicename)): @@ -1518,7 +1579,8 @@ def _polling_loop_5_sec_device(self, now): and self.in_stationary_zone_flag.get(devicename) == False): event_msg = (f"Stationary Zone Entered > iOS App used another device's " - f"Stationary Zone, changed {iosapp_state} to {self._format_zone_name(devicename, STATIONARY)}") + f"Stationary Zone, changed {iosapp_state} to " + f"{self._format_zone_name(devicename, STATIONARY)}") self._save_event(devicename, event_msg) latitude = self.zone_lat.get(iosapp_state) @@ -1528,7 +1590,7 @@ def _polling_loop_5_sec_device(self, now): devicename, latitude, longitude, - STAT_ZONE_NEW_LOCATION, 'poll 5-1442') + STAT_ZONE_NEW_LOCATION, 'poll 5-EnterTrigger') iosapp_state = self._format_zone_name(devicename, STATIONARY) @@ -1538,11 +1600,11 @@ def _polling_loop_5_sec_device(self, now): devicename, self.stat_zone_base_lat, self.stat_zone_base_long, - STAT_ZONE_MOVE_TO_BASE, 'poll 5-1470') + STAT_ZONE_MOVE_TO_BASE, 'poll 5-ExitTrigger') #Discard another devices Stationary Zone triggers - if instr(iosapp_state, STATIONARY) and instr(iosapp_state, devicename) == False: - continue + #if instr(iosapp_state, STATIONARY) and instr(iosapp_state, devicename) == False: + # continue if instr(iosapp_state, STATIONARY): iosapp_state = STATIONARY @@ -1550,6 +1612,7 @@ def _polling_loop_5_sec_device(self, now): #---------------------------------------------------------------------------- ic3dev_battery = self._get_attr(iosapp_dev_attrs, ATTR_BATTERY_LEVEL, NUMERIC) self.last_battery[devicename] = ic3dev_battery + if update_via_iosapp_flag: iosapp_trigger_age_secs = self._secs_since(iosapp_trigger_changed_secs) age = iosapp_trigger_changed_secs - self.this_update_secs @@ -1576,13 +1639,13 @@ def _polling_loop_5_sec_device(self, now): #Check ios app for activity every 6-hours #Issue ios app Location update 15-min before 6-hour alert - elif (this_update_hhmmss in ['23:45:00', '05:45:00', '11:45:00', '17:45:00'] + elif (self.this_update_time in ['23:45:00', '05:45:00', '11:45:00', '17:45:00'] and iosapp_state_age_secs > 20700 and iosapp_trigger_age_secs > 20700): - self._request_iosapp_location_update(devicename) + self._iosapp_request_loc_update(devicename) #No activity, display Alert msg in Event Log - elif (this_update_hhmmss in ['00:00:00', '06:00:00', '12:00:00', '18:00:00'] + elif (self.this_update_time in ['00:00:00', '06:00:00', '12:00:00', '18:00:00'] and iosapp_state_age_secs > 21600 and iosapp_trigger_age_secs > 21600): event_msg = (f"{EVLOG_ALERT}iOS App Alert > No iOS App updates for more than 6 hours > " @@ -1594,7 +1657,6 @@ def _polling_loop_5_sec_device(self, now): f"—{iosapp_trigger_age_str} ago") self._display_info_status_msg(devicename, event_msg) - zone = self._format_zone_name(devicename, ic3dev_state) event_msg = "" update_reason = "" @@ -1616,7 +1678,6 @@ def _polling_loop_5_sec_device(self, now): self.zone_radius_m.get(HOME)) zone_radius_accuracy_m = zone_radius_m + self.gps_accuracy_threshold - if (self.TRK_METHOD_IOSAPP and self.zone_current.get(devicename) == ''): update_method = IOSAPP_UPDATE update_reason = "Initial Locate" @@ -1625,8 +1686,12 @@ def _polling_loop_5_sec_device(self, now): #latitude and longitude. Reset via icloud update. elif ic3dev_latitude == 0: update_method = ICLOUD_UPDATE - update_reason = (f"GPS data = 0 {self.state_last_poll.get(devicename)}-{ic3dev_state}") + update_reason = (f"GPS=(0, 0) {self.state_last_poll.get(devicename)}/{ic3dev_state}") ic3dev_trigger = "RefreshLocation" + device_offline_msg = (f"May be Offline, No Location " + f"(#{self.poor_location_gps_cnt.get(devicename)})") + self._display_info_status_msg(devicename, device_offline_msg) + self._save_event(devicename,device_offline_msg) #Update the device if it wasn't completed last time. elif self.state_last_poll.get(devicename) == NOT_SET: @@ -1648,7 +1713,7 @@ def _polling_loop_5_sec_device(self, now): elif (self.stat_zone_timer.get(devicename, 0) > 0 and self.this_update_secs >= self.stat_zone_timer.get(devicename) - and self.old_loc_poor_gps_cnt.get(devicename) == 0): + and self.poor_location_gps_cnt.get(devicename) == 0): event_msg = (f"Move into Stationary Zone Timer reached > {devicename}, " f"Expired-{self._secs_to_time(self.stat_zone_timer.get(devicename, -1))}") self._save_event(devicename, event_msg) @@ -1665,7 +1730,7 @@ def _polling_loop_5_sec_device(self, now): #changed without a trigger being posted and will be picked #up here anyway. elif (ic3dev_state != self.state_last_poll.get(devicename) - and ic3dev_timestamp_secs > (self.last_located_secs.get(devicename) + 5)): + and ic3dev_timestamp_secs > last_located_secs_plus_5): self.count_state_changed[devicename] += 1 self.state_change_flag[devicename] = True update_method = IOSAPP_UPDATE @@ -1680,20 +1745,29 @@ def _polling_loop_5_sec_device(self, now): and iosapp_dev_attrs[ATTR_LONGITUDE] == self.stat_zone_base_long): update_method = ICLOUD_UPDATE update_reason = "Verify Location" - event_msg = (f"Discarded > Can not set current location to Stationary Base Zone") + event_msg = (f"Discarded > Entering Stationary Base Zone") self._save_event(devicename, event_msg) elif (ic3dev_trigger != self.trigger.get(devicename) - and ic3dev_timestamp_secs > (self.last_located_secs.get(devicename) + 5)): + and ic3dev_timestamp_secs > last_located_secs_plus_5): update_method = IOSAPP_UPDATE self.count_trigger_changed[devicename] += 1 update_reason = "Trigger Change" event_msg = (f"iOSApp Trigger Change detected > {ic3dev_trigger}") self._save_event(devicename, event_msg) + #If iOS App tracking and next update time reached and message not sent, request location. iOS App should respond within 20-seconds and create a Location Request + #trigger. Do this 4-times and then display message and wait. + elif (self.TRK_METHOD_IOSAPP + and self._check_next_update_time_reached_devicename(devicename)): + self._iosapp_request_loc_update(devicename) + else: update_reason = f"OlderTrigger-{ic3dev_trigger}" + if (self.TRK_METHOD_IOSAPP + and update_method == ICLOUD_UPDATE): + update_method = IOSAPP_UPDATE #Update because of state or trigger change. #Accept the location data as it was sent by ios if the trigger @@ -1703,19 +1777,20 @@ def _polling_loop_5_sec_device(self, now): #If the trigger was sometning else (Significant Location Change, #Background Fetch, etc, check to make sure it is not old or #has poor gps info. - if update_method == IOSAPP_UPDATE: + if (update_method == IOSAPP_UPDATE + or update_method == ICLOUD_UPDATE and self.TRK_METHOD_IOSAPP): + self.iosapp_request_loc_sent_flag[devicename] = False + #If exit trigger flag is not set, set it now if Exiting zone #If already set, leave it alone and reset when enter Zone (v2.1x) if self.got_exit_trigger_flag.get(devicename) == False: self.got_exit_trigger_flag[devicename] = (ic3dev_trigger in IOS_TRIGGERS_EXIT) - #self._trace_device_attributes(devicename, '5sPOLL', update_reason, ic3dev_attrs) - if ic3dev_trigger in IOS_TRIGGERS_ENTER: if (zone in self.zone_lat and dist_from_zone_m > self.zone_radius_m.get(zone)*2 and dist_from_zone_m < HIGH_INTEGER): - event_msg = (f"Conflicting enter zone trigger, Moving into zone > " + event_msg = (f"Enter Zone Trigger Conflict Moving into Zone > " f"Zone-{zone}, Distance-{dist_from_zone_m}m, " f"ZoneVerifyDist-{self.zone_radius_m.get(zone)*2}m, " f"GPS-{format_gps(ic3dev_latitude, ic3dev_longitude, ic3dev_gps_accuracy)}") @@ -1728,7 +1803,7 @@ def _polling_loop_5_sec_device(self, now): #RegionExit trigger overrules old location, gps accuracy and other checks elif (ic3dev_trigger in IOS_TRIGGERS_EXIT - and ic3dev_timestamp_secs > (self.last_located_secs.get(devicename) + 5)): + and ic3dev_timestamp_secs > last_located_secs_plus_5): update_method = IOSAPP_UPDATE update_reason = "Region Exit" @@ -1737,18 +1812,18 @@ def _polling_loop_5_sec_device(self, now): #elif (ic3dev_trigger in IOS_TRIGGERS_VERIFY_LOCATION): #If not an enter/exit trigger, verify the location elif (ic3dev_trigger not in IOS_TRIGGERS_ENTER_EXIT): - old_loc_poor_gps_flag, discard_reason = self._check_old_loc_poor_gps( + poor_location_gps_flag, discard_reason = self._check_poor_location_gps( devicename, ic3dev_timestamp_secs, ic3dev_gps_accuracy) #If old location, discard - if old_loc_poor_gps_flag: + if poor_location_gps_flag: location_age = self._secs_since(ic3dev_timestamp_secs) - event_msg = (f"Update via iCloud > Old location or poor GPS " - f"(#{self.old_loc_poor_gps_cnt.get(devicename)}), " + event_msg = (f"Old Location or Poor GPS " + f"(#{self.poor_location_gps_cnt.get(devicename)}) > " f"Located-{self._secs_to_time(ic3dev_timestamp_secs)} " - f"({self._secs_to_time_str(location_age)} ago), " + f"({self._format_age(location_age)}), " f"GPS-{format_gps(ic3dev_latitude, ic3dev_longitude, ic3dev_gps_accuracy)}, " f"OldLocThreshold-{self._secs_to_time_str(self.old_location_secs.get(devicename))}") @@ -1790,7 +1865,7 @@ def _polling_loop_5_sec_device(self, now): #by treating it as poor GPS if self._is_inzone_zonename(zone): outside_no_exit_trigger_flag, info_msg = \ - self._check_outside_zone_no_exit(devicename, zone, + self._check_outside_zone_no_exit(devicename, zone, ic3dev_trigger, ic3dev_latitude, ic3dev_longitude) if outside_no_exit_trigger_flag: update_method = None @@ -1800,7 +1875,7 @@ def _polling_loop_5_sec_device(self, now): #update via icloud to verify location if less than home_radius*10 elif (dist_from_zone_m <= zone_radius_m * 10 and self.TRK_METHOD_FMF_FAMSHR): - event_msg = (f"Update via iCloud > Verify location needed > " + event_msg = (f"Verify Location Needed > " f"Zone-{zone}, " f"Distance-{self._format_dist_m(dist_from_zone_m)}m, " f"ZoneVerifyDist-{self._format_dist_m(zone_radius_m*10)}m, " @@ -1808,6 +1883,10 @@ def _polling_loop_5_sec_device(self, now): self._save_event_halog_info(devicename, event_msg) update_method = ICLOUD_UPDATE update_reason = "Verify Location" + else: + pass + else: + pass if (ic3dev_data[ATTR_LATITUDE] is None or ic3dev_data[ATTR_LONGITUDE] is None): update_method = ICLOUD_UPDATE @@ -1827,19 +1906,36 @@ def _polling_loop_5_sec_device(self, now): self._evlog_debug_msg(devicename, device_monitor_msg) self.last_device_monitor_msg[devicename] = device_monitor_msg + if (self._device_online(devicename) == False + or self.state_this_poll == NOT_SET): + device_offline_msg = (f"May be Offline, Never Located " + f"(#{self.poor_location_gps_cnt.get(devicename)})") + self._display_info_status_msg(devicename, device_offline_msg) + #Save trigger and time for cycle even if trigger was discarded. self.trigger[devicename] = ic3dev_trigger self.last_located_secs[devicename] = ic3dev_timestamp_secs + if update_method == ICLOUD_UPDATE: + if self.TRK_METHOD_FMF_FAMSHR: + self._update_device_icloud(update_reason, devicename) + + elif self.TRK_METHOD_IOSAPP: + update_method = IOSAPP_UPDATE + self.iosapp_request_loc_sent_flag[devicename] = False + if update_method == IOSAPP_UPDATE: self.state_this_poll[devicename] = ic3dev_state self.iosapp_update_flag[devicename] = True update_method = self._update_device_iosapp(devicename, update_reason, ic3dev_data) - self.any_device_being_updated_flag = False - if update_method == ICLOUD_UPDATE and self.TRK_METHOD_FMF_FAMSHR: - self._update_device_icloud(update_reason, devicename) + #Retry with iCloud of an error or no data + if (update_method == ICLOUD_UPDATE + and self.TRK_METHOD_FMF_FAMSHR): + self._update_device_icloud(update_reason, devicename) + + self.any_device_being_updated_flag = False #If less than 90 secs to the next update for any devicename:zone, display time to #the next update in the NextUpdt time field, e.g, 1m05s or 0m15s. @@ -1848,8 +1944,10 @@ def _polling_loop_5_sec_device(self, now): devicename_zone = self._format_devicename_zone(devicename, zone) if devicename_zone in self.next_update_secs: age_secs = self._secs_to(self.next_update_secs.get(devicename_zone)) - if (age_secs <= 90 and age_secs >= -15): - self._display_time_till_update_info_msg(devicename_zone, age_secs) + #if (age_secs <= 90 and age_secs >= -15): + # self._display_time_till_update_info_msg(devicename_zone, age_secs) + self._display_time_till_update_info_msg(devicename_zone, age_secs) + if update_method is not None: self.device_being_updated_flag[devicename] = False @@ -1864,14 +1962,14 @@ def _polling_loop_5_sec_device(self, now): log_msg = (f"Device Update Error, Error-{ValueError}") self._log_error_msg(log_msg) - self.update_in_process_flag = False + self.update_in_process_flag = False self._log_debug_msgs_trace_flag = False #Cycle thru all devices and check to see if devices next update time #will occur in 5-secs. If so, request a location update now so it #it might be current on the next update. - if ((this_5sec_loop_second % 15) == 10): - self._polling_loop_10_sec_fmf_loc_prefetch(now) + if ((this_5sec_loop_second % 15) == 10) and self.TRK_METHOD_FMF_FAMSHR: + self._polling_loop_10_sec_loc_prefetch(now) #Cycle thru all devices and check to see if devices need to be #updated via every 15 seconds @@ -1909,6 +2007,47 @@ def _retry_update(self, devicename): self._update_device_icloud(update_reason, devicename) +######################################################### +# +# This function is called every 10 seconds. Cycle through all +# of the devices to see if any of the ones being tracked will +# be updated on the 15-sec polling loop in 5-secs. If so, request a +# location update now so it might be current when the device +# is updated. +# +######################################################### + def _polling_loop_10_sec_loc_prefetch(self, now): + + try: + if self.next_update_secs is None: + return + + for devicename_zone in self.next_update_secs: + devicename = devicename_zone.split(':')[0] + if self.state_this_poll.get(devicename) == NOT_SET: + continue + + time_till_update = self.next_update_secs.get(devicename_zone) - \ + self.this_update_secs + location_data = self.location_data.get(devicename) + + if time_till_update <= 10: + location_data = self.location_data.get(devicename) + location_age = location_data[ATTR_AGE] + + if location_age > 15: + if self.TRK_METHOD_FMF_FAMSHR: + self._refresh_pyicloud_devices_location_data(location_age, devicename) + + elif self.TRK_METHOD_IOSAPP: + self._iosapp_request_loc_update(devicename) + break + + except Exception as err: + _LOGGER.exception(err) + + return + ######################################################### # # Update the device on a state or trigger change was recieved from the ios app @@ -1916,7 +2055,7 @@ def _retry_update(self, devicename): ######################################################### def _update_device_iosapp(self, devicename, update_reason, ic3dev_data): """ - + Update the devices location using data from the iOS App """ if self.start_icloud3_inprocess_flag: @@ -1927,14 +2066,21 @@ def _update_device_iosapp(self, devicename, update_reason, ic3dev_data): self.any_device_being_updated_flag = True return_code = IOSAPP_UPDATE + self.iosapp_request_loc_retry_cnt[devicename] = 0 + self.iosapp_request_loc_sent_secs[devicename] = 0 + self.iosapp_request_loc_sent_flag[devicename] = False + try: devicename_zone = self._format_devicename_zone(devicename, HOME) if self.next_update_time.get(devicename_zone) == PAUSED: + self._save_event(devicename,"2047 update_iosapp, paused") return elif ATTR_LATITUDE not in ic3dev_data or ATTR_LONGITUDE not in ic3dev_data: + self._save_event(devicename,f"2050 update_iosapp, ic3_dev_data={ic3dev_data}") return elif ic3dev_data[ATTR_LATITUDE] is None or ic3dev_data[ATTR_LONGITUDE] is None: + self._save_event(devicename,f"2053 update_iosapp, lat=None, ic3_dev_data={ic3dev_data}") return self._log_start_finish_update_banner('▼▼▼', devicename, "iOSApp", update_reason) @@ -1949,7 +2095,7 @@ def _update_device_iosapp(self, devicename, update_reason, ic3dev_data): latitude = ic3dev_data[ATTR_LATITUDE] longitude = ic3dev_data[ATTR_LONGITUDE] timestamp = self._timestamp_to_time(ic3dev_data[ATTR_TIMESTAMP]) - timestamp = self._secs_to_time(self.this_update_secs) if timestamp == HHMMSS_ZERO else timestamp + timestamp = self.this_update_time if timestamp == HHMMSS_ZERO else timestamp gps_accuracy = ic3dev_data[ATTR_GPS_ACCURACY] battery = ic3dev_data[ATTR_BATTERY_LEVEL] battery_status = ic3dev_data[ATTR_BATTERY_STATUS] @@ -1959,9 +2105,12 @@ def _update_device_iosapp(self, devicename, update_reason, ic3dev_data): vertical_accuracy = self._get_attr(ic3dev_data, ATTR_VERT_ACCURACY, NUMERIC) location_isold_attr = False - old_loc_poor_gps_flag = False - self.old_loc_poor_gps_cnt[devicename] = 0 - self.old_loc_poor_gps_msg[devicename] = False + poor_location_gps_flag = False + self.poor_location_gps_cnt[devicename] = 0 + self.poor_location_gps_msg[devicename] = False + self.poor_gps_flag[devicename] = False #v2.2.1 + self.device_status[devicename] = device_status + attrs = {} #-------------------------------------------------------- @@ -1991,7 +2140,8 @@ def _update_device_iosapp(self, devicename, update_reason, ic3dev_data): #discard trigger if outsize zone with no exit trigger if self._is_inzone_zonename(zone): discard_flag, discard_msg = \ - self._check_outside_zone_no_exit(devicename, zone, latitude, longitude) + self._check_outside_zone_no_exit(devicename, zone, '', + latitude, longitude) if discard_flag: self._save_event(devicename, discard_msg) @@ -2006,7 +2156,7 @@ def _update_device_iosapp(self, devicename, update_reason, ic3dev_data): longitude, battery, gps_accuracy, - old_loc_poor_gps_flag, + poor_location_gps_flag, self.last_located_secs.get(devicename), timestamp, "iOSApp") @@ -2026,7 +2176,7 @@ def _update_device_iosapp(self, devicename, update_reason, ic3dev_data): #device_being_update_flag so an icloud update will be done. if attrs == {} and self.TRK_METHOD_FMF_FAMSHR: self.any_device_being_updated_flag = False - self.iosapp_locate_update_secs[devicename] = 0 + self.iosapp_request_loc_sent_secs[devicename] = 0 event_msg = ("iOS update was not completed, " f"will retry with {self.trk_method_short_name}") @@ -2048,7 +2198,13 @@ def _update_device_iosapp(self, devicename, update_reason, ic3dev_data): #If location is empty or trying to set to the Stationary Base Zone Location, #discard the update and try again in 15-sec - if self._update_last_latitude_longitude(devicename, latitude, longitude, (f"iOSApp-{update_reason}")) == False: + check_gps = self._update_last_latitude_longitude( + devicename, + latitude, + longitude, + (f"iOSApp-{update_reason}")) + + if check_gps == False: self.any_device_being_updated_flag = False return ICLOUD_UPDATE @@ -2061,7 +2217,7 @@ def _update_device_iosapp(self, devicename, update_reason, ic3dev_data): altitude = 0 attrs[ATTR_LAST_LOCATED] = self._time_to_12hrtime(timestamp) - attrs[ATTR_DEVICE_STATUS] = device_status + attrs[ATTR_DEVICE_STATUS] = self.device_status.get(devicename) attrs[ATTR_LOW_POWER_MODE] = low_power_mode attrs[ATTR_BATTERY] = battery attrs[ATTR_BATTERY_STATUS] = battery_status @@ -2118,43 +2274,72 @@ def _update_device_iosapp(self, devicename, update_reason, ic3dev_data): return_code = ICLOUD_UPDATE self.any_device_being_updated_flag = False - self.iosapp_locate_update_secs[devicename] = 0 + #self.iosapp_request_loc_sent_secs[devicename] = 0 return return_code ######################################################### # -# This function is called every 10 seconds. Cycle through all -# of the devices to see if any of the ones being tracked will -# be updated on the 15-sec polling loop in 5-secs. If so, request a -# location update now so it might be current when the device -# is updated. +# Using the iosapp tracking method or iCloud is disabled +# so trigger the iosapp to send a +# location transaction # ######################################################### - def _polling_loop_10_sec_fmf_loc_prefetch(self, now): + def _iosapp_request_loc_update(self, devicename, reissue_msg=""): + ''' + Send location request to phone. Check to see if one has been sent but not responded to + and, if true, set interval based on the retry count. + ''' try: - if self.next_update_secs is None: - return - elif self.TRK_METHOD_IOSAPP: - return + age = self._secs_since(self.iosapp_request_loc_sent_secs.get(devicename)) + event_msg = "Requested iOSApp Loc" + + #Save initial sent time if not sent before, otherwise increase retry cnt and + #set new interval time + if self.iosapp_request_loc_sent_flag.get(devicename) == False: + self.iosapp_request_loc_sent_secs[devicename] = self.this_update_secs + self.iosapp_request_loc_retry_cnt[devicename] = 0 + event_msg += (f"@{self.this_update_time}") + else: + self.iosapp_request_loc_retry_cnt[devicename] += 1 + event_msg += (f"@{self._secs_to_time(self.iosapp_request_loc_sent_secs.get(devicename))}, " + f"({self._format_age(age)}), " + f"#{self.iosapp_request_loc_retry_cnt.get(devicename)}") - for devicename_zone in self.next_update_secs: - time_till_update = self.next_update_secs.get(devicename_zone) - \ - self.this_update_secs - if time_till_update <= 10: - devicename = devicename_zone.split(':')[0] - location_data = self.location_data.get(devicename) - age = location_data[ATTR_AGE] + if self.iosapp_request_loc_retry_cnt.get(devicename) > 10: + event_msg += ", May be offline/asleep" - if age > 15: - if self.TRK_METHOD_FMF_FAMSHR: - self._refresh_pyicloud_devices_location_data(age, devicename) - break + self._determine_interval_after_error( + devicename, + event_msg, + counter=IOSAPP_REQUEST_LOC_CNT) + + self.iosapp_request_loc_sent_flag[devicename] = True + self.iosapp_request_loc_cnt[devicename] += 1 + + message = {"message": "request_location_update"} + return_code = self._send_message_to_device(devicename, message) + + #self.hass.async_create_task( + # self.hass.services.async_call('notify', entity_id, service_data)) + + self._save_event_halog_info(devicename, event_msg) + + if return_code: + attrs = {} + attrs[ATTR_POLL_COUNT] = self._format_poll_count(devicename) + attrs[ATTR_INFO] = event_msg + self._update_device_sensors(devicename, attrs) + else: + event_msg = f"{EVA_NOTICE}{event_msg} > Failed to send message" + self._save_event_halog_info(devicename, event_msg) except Exception as err: _LOGGER.exception(err) + error_msg = (f"iCloud3 Error > An error occurred sending a location request > " + f"Device-{self.notify_iosapp_entity.get(devicename)}, Error-{err}") + self._save_event_halog_error(devicename, error_msg) - return ######################################################### # @@ -2186,6 +2371,9 @@ def _polling_loop_15_sec_icloud(self, now): if (self.tracking_device_flag.get(devicename) is False or self.next_update_time.get(devicename_zone) == PAUSED): continue + elif (self.state_this_poll.get(devicename) == NOT_SET + and self.next_update_secs.get(devicename_zone) > self.this_update_secs): + continue self.iosapp_update_flag[devicename] = False update_method = None @@ -2210,7 +2398,7 @@ def _polling_loop_15_sec_icloud(self, now): if 'nearzone' in state: state = 'near_zone' - self.state_this_poll[devicename] = state + self.state_this_poll[devicename] = state self.next_update_secs[devicename_zone] = 0 attrs = {} @@ -2229,6 +2417,7 @@ def _polling_loop_15_sec_icloud(self, now): log_msg = (f"{self._format_fname_devtype(devicename)} Cancelled update retry") self._log_info_msg(log_msg) + update_via_other_devicename = None if self._check_in_zone_and_before_next_update(devicename): continue @@ -2250,16 +2439,24 @@ def _polling_loop_15_sec_icloud(self, now): else: update_via_other_devicename = self._check_next_update_time_reached() - if update_via_other_devicename is not None: + #TODO. Pia update from other device flag into update routine so it won't update of old loc and from another def and next update time not reached + if (update_via_other_devicename != devicename + and self.poor_location_gps_cnt.get(devicename) > 0 + and self.next_update_secs.get(devicename_zone) > self.this_update_secs): + pass + + elif update_via_other_devicename is not None: self._log_debug_msgs_trace_flag = False + retry_suffix = "" if self.poor_location_gps_cnt.get(devicename) == 0 else " (Retry)" update_method = ICLOUD_UPDATE - update_reason = "Next Update Time" - self.trigger[devicename] = 'NextUpdateTime' - event_msg = (f"NextUpdateTime reached > {update_via_other_devicename}") + update_reason = f"Next Update Time reached{retry_suffix}" + self.trigger[devicename] = f"NextUpdateTime{retry_suffix}" + event_msg = (f"{update_reason} > {update_via_other_devicename}") self._save_event(devicename, event_msg) elif update_method == ICLOUD_UPDATE: - event_msg = (f"NextUpdateTime reached > {devicename}") + retry_suffix = "" if self.poor_location_gps_cnt.get(devicename) == 0 else " (Retry)" + event_msg = (f"Next Update Time reached{retry_suffix} > {devicename}") self._save_event(devicename, event_msg) if update_method == ICLOUD_UPDATE: @@ -2272,7 +2469,7 @@ def _polling_loop_15_sec_icloud(self, now): self.update_in_process_flag = False return - self.info_notification = (f"THE ICLOUD 2SA CODE IS NEEDED TO VERIFY " + self.info_notification = (f"THE ICLOUD 2FA CODE IS NEEDED TO VERIFY " f"THE ACCOUNT FOR {self.username}") for devicename in self.tracked_devices: self._display_info_status_msg(devicename, self.info_notification) @@ -2287,7 +2484,7 @@ def _polling_loop_15_sec_icloud(self, now): self._icloud_show_trusted_device_request_form() return - self._update_device_icloud(update_reason) + self._update_device_icloud(update_reason, update_via_other_devicename) self.update_in_process_flag = False @@ -2298,7 +2495,7 @@ def _polling_loop_15_sec_icloud(self, now): self._log_error_msg(log_msg) self.api.authenticate() #Reset iCloud self.authenticated_time = time.time() - self._update_device_icloud('iCloud/FmF Reauth') #Retry update devices + self._update_device_icloud('iCloud/FmF Reauth', update_via_other_devicename) #Retry update devices self.update_in_process_flag = False self._log_debug_msgs_trace_flag = False @@ -2311,10 +2508,22 @@ def _polling_loop_15_sec_icloud(self, now): # ●►●◄►●▬▲▼◀►►●◀ oPhone=►▶ ######################################################### def _update_device_icloud(self, update_reason='Check iCloud', - arg_devicename=None): + arg_devicename=None, arg_via_other_devicename=None): + """ Request device information from iCloud (if needed) and update device_tracker information. + + arg_devicename - + None = Update all devices + Not None = Update specified device + arg_other-devicename - + None = Update all devices + Not None = One device in the list reached the next update time. + Do not update another device that now has poor location + gps after all the results have been determined if + their update time has not been reached. + """ if self.TRK_METHOD_IOSAPP: @@ -2331,13 +2540,15 @@ def _update_device_icloud(self, update_reason='Check iCloud', try: for devicename in self.tracked_devices: zone = self.zone_current.get(devicename) - devicename_zone = self._format_devicename_zone(devicename) + devicename_home_zone = self._format_devicename_zone(devicename) if arg_devicename and devicename != arg_devicename: continue - elif self.next_update_time.get(devicename_zone) == PAUSED: + elif self.next_update_time.get(devicename_home_zone) == PAUSED: + continue + elif (self.state_this_poll.get(devicename) == NOT_SET + and self.next_update_secs.get(devicename_home_zone) > self.this_update_secs): continue - #If the device is in a zone, and was in the same zone on the #last poll of another device on the account and this device @@ -2358,7 +2569,7 @@ def _update_device_icloud(self, update_reason='Check iCloud', self.trk_method_short_name, update_reason) self.update_timer[devicename] = time.time() - self.iosapp_locate_update_secs[devicename] = 0 + self.iosapp_request_loc_sent_secs[devicename] = 0 do_not_update_flag = False location_time = 0 @@ -2374,11 +2585,10 @@ def _update_device_icloud(self, update_reason='Check iCloud', #if ic3dev_data[0] is False: if valid_data_flag == ICLOUD_LOCATION_DATA_ERROR: self.icloud_acct_auth_error_cnt += 1 - self._determine_interval_retry_after_error( + self._determine_interval_after_error( devicename, - self.icloud_acct_auth_error_cnt, - "offline", - "iCloud Offline (Authentication or Location Error)") + "iCloud Offline (Authentication or Location Error)", + counter=AUTH_ERROR_CNT) if (self.interval_seconds.get(devicename) != 15 and self.icloud_acct_auth_error_cnt > 2): @@ -2407,24 +2617,10 @@ def _update_device_icloud(self, update_reason='Check iCloud', longitude = location_data[ATTR_LONGITUDE] gps_accuracy = 0 - #Discard if no location coordinates - if latitude == 0 or longitude == 0: - location_time = 'Unknown' - location_age = None - info_msg = (f"No location data returned from iCloud Location Svcs, " - f"GPS-({latitude}, {longitude})") - - self._determine_interval_retry_after_error( - devicename, - self.old_loc_poor_gps_cnt.get(devicename), - "", - info_msg) - do_not_update_flag = True - - else: + if latitude != 0 and longitude != 0: timestamp = location_data[ATTR_TIMESTAMP] location_isold_attr = location_data[ATTR_ISOLD] - location_time_secs = location_data[ATTR_TIMESTAMP] + last_located_secs = location_data[ATTR_TIMESTAMP] location_time = location_data[ATTR_TIMESTAMP_TIME] battery = location_data[ATTR_BATTERY_LEVEL] battery_status = location_data[ATTR_BATTERY_STATUS] @@ -2436,67 +2632,94 @@ def _update_device_icloud(self, update_reason='Check iCloud', location_age = self._secs_since(location_data.get(ATTR_TIMESTAMP)) location_data[ATTR_AGE] = location_age - old_loc_poor_gps_flag, discard_reason = self._check_old_loc_poor_gps( - devicename, - location_time_secs, - gps_accuracy) self.location_data[devicename][ATTR_BATTERY_LEVEL] = battery - self.last_located_secs[devicename] = location_time_secs + self.last_located_secs[devicename] = last_located_secs + self.device_status[devicename] = device_status + + poor_location_gps_flag, discard_reason = self._check_poor_location_gps( + devicename, + last_located_secs, + gps_accuracy) + + #Discard if no location coordinates + if latitude == 0 or longitude == 0: + location_time = NEVER + location_age = HIGH_INTEGER + self.poor_location_gps_cnt[devicename] += 1 + self.device_status[devicename] = UNKNOWN + discard_reason = (f"No location data " + f"(#{self.poor_location_gps_cnt.get(devicename)})") + device_offline_msg = (f"May be Offline, No Location " + f"(#{self.poor_location_gps_cnt.get(devicename)})") + info_msg = discard_reason + self._determine_interval_after_error( + devicename, + device_offline_msg) + do_not_update_flag = True #Check to see if currently in a zone. If so, check the zone distance. #If new location is outside of the zone and inside radius*4, discard #by treating it as poor GPS - if (self._isnot_inzone_zonename(zone) or self.state_this_poll.get(devicename) == NOT_SET): + elif (self._isnot_inzone_zonename(zone) + or self.state_this_poll.get(devicename) == NOT_SET): outside_no_exit_trigger_flag = False info_msg= '' else: outside_no_exit_trigger_flag, info_msg = \ - self._check_outside_zone_no_exit(devicename, zone, latitude, longitude) + self._check_outside_zone_no_exit(devicename, zone, '', + latitude, longitude) - #If not authorized or no data, don't check old or accuracy errors if self.icloud_acct_auth_error_cnt > 0: pass #If initializing, nothing is set yet - elif self.state_this_poll.get(devicename) == NOT_SET: - pass + #elif (self.state_this_poll.get(devicename) == NOT_SET + # and location_age < 300): + # pass #If no location data elif do_not_update_flag: pass - elif device_status not in ["online", "pending", ""]: + #Ignore old location when in a zone, let normal next time update + #check process + elif (poor_location_gps_flag + and self.this_update_secs < self.next_update_secs.get(devicename_home_zone) + and (self._is_inzone(devicename) + or devicename != arg_via_other_devicename)): + self.poor_location_gps_cnt[devicename] -= 1 + pass + + #elif device_status not in ["online", "pending", ""]: + elif self._device_online(devicename) == False: do_not_update_flag = True - info_msg = "DEVICE OFFLINE" - self._determine_interval_retry_after_error( + info_msg = "Device Offline" + self._determine_interval_after_error( devicename, - self.old_loc_poor_gps_cnt.get(devicename), - device_status, info_msg) - event_msg = (f"{EVLOG_ALERT}iCloud Alert > {devicename} is Offline > Tracking is delayed, Status-{device_status}, " + event_msg = (f"{EVLOG_ALERT}iCloud Alert > {devicename} is Offline > Tracking is delayed, " + f"Status-{self.device_status.get(devicename)}, " f"OnlineStatus-{self.device_status_online}") self._save_event(devicename, event_msg) + #elif self.state_this_poll.get(devicename) == NOT_SET: + # pass + #Outside zone, no exit trigger check elif outside_no_exit_trigger_flag: - self.poor_gps_accuracy_flag[devicename] = True - self.old_loc_poor_gps_cnt[devicename] += 1 + self.poor_gps_flag[devicename] = True + self.poor_location_gps_cnt[devicename] += 1 do_not_update_flag = True - self._determine_interval_retry_after_error( + self._determine_interval_after_error( devicename, - self.old_loc_poor_gps_cnt.get(devicename), - device_status, info_msg) #Discard if location is old or poor gps - elif old_loc_poor_gps_flag: + elif poor_location_gps_flag: info_msg = (f"{discard_reason}") - do_not_update_flag = True - self._determine_interval_retry_after_error( + self._determine_interval_after_error( devicename, - self.old_loc_poor_gps_cnt.get(devicename), - device_status, info_msg) #discard if outside home zone and less than zone_radius+self.gps_accuracy_threshold due to gps errors @@ -2504,10 +2727,14 @@ def _update_device_icloud(self, update_reason='Check iCloud', self.zone_home_lat, self.zone_home_long) if do_not_update_flag: - event_msg = (f"Discarding > {info_msg} > GPS-{format_gps(latitude, longitude, gps_accuracy)}, " - f"Located-{location_time} " - f"({self._secs_to_time_str(location_age)} ago), " + location_age_str = "" if location_time == NEVER else (f" ({self._format_age(location_age)})") + event_msg = (f"Discarded > {info_msg} > " + f"GPS-{format_gps(latitude, longitude, gps_accuracy)}, " + f"Located-{location_time}{location_age_str}, " + f"NextUpdate-{self.next_update_time.get(self._format_devicename_zone(devicename))}, " f"OldLocThreshold-{self._secs_to_time_str(self.old_location_secs.get(devicename))}") + if self._device_online(devicename) == False: + event_msg += (f", DeviceStatus-{self.device_status.get(devicename)}") self._save_event(devicename, event_msg) self._log_start_finish_update_banner('▲▲▲', devicename, @@ -2522,7 +2749,7 @@ def _update_device_icloud(self, update_reason='Check iCloud', else: info_msg = "Updating" event_msg = (f"Updating Device > GPS-{format_gps(latitude, longitude, gps_accuracy)}, " - f"Located-{location_time} ({self._secs_to_time_str(location_age)} ago)") + f"Located-{location_time} ({self._format_age(location_age)})") info_msg = f"{info_msg} {self.fname.get(devicename)}" self._display_info_status_msg(devicename, info_msg) self._save_event(devicename, event_msg) @@ -2551,8 +2778,8 @@ def _update_device_icloud(self, update_reason='Check iCloud', longitude, battery, gps_accuracy, - old_loc_poor_gps_flag, - location_time_secs, + poor_location_gps_flag, + last_located_secs, location_time, "icld") if attrs != {}: @@ -2573,18 +2800,22 @@ def _update_device_icloud(self, update_reason='Check iCloud', #location goes to 'See' as a "(latitude, longitude)" pair. #'See' converts them to ATTR_LATITUDE and ATTR_LONGITUDE #and discards the 'gps' item. - log_msg = (f"LOCATION ATTRIBUTES, State-{self.state_last_poll.get(devicename)}, " - f"Attrs-{attrs}") + log_msg = (f"LOCATION ATTRIBUTES, " + f"State-{self.state_last_poll.get(devicename)}, " + f"Attrs-{attrs}") self._log_debug_msg(devicename, log_msg) self.count_update_icloud[devicename] += 1 - if not old_loc_poor_gps_flag: - self._update_last_latitude_longitude(devicename, latitude, longitude, (f"iCloud-{update_reason}")) + if not poor_location_gps_flag: + self._update_last_latitude_longitude( + devicename, latitude, longitude, + (f"iCloud-{update_reason}")) if altitude is None: altitude = -2 - attrs[ATTR_DEVICE_STATUS] = device_status + #attrs[ATTR_DEVICE_STATUS] = device_status + attrs[ATTR_DEVICE_STATUS] = self.device_status.get(devicename) attrs[ATTR_LOW_POWER_MODE] = low_power_mode attrs[ATTR_BATTERY] = battery attrs[ATTR_BATTERY_STATUS] = battery_status @@ -2689,10 +2920,10 @@ def _get_fmf_data(self, devicename): log_msg = (f"LOCATION DATA-{location_data})") self._log_debug_msg(devicename, log_msg) - age = location_data[ATTR_AGE] + location_age = location_data[ATTR_AGE] - if age > self.old_location_secs.get(devicename): - if self._refresh_pyicloud_devices_location_data(age, devicename): + if location_age > self.old_location_secs.get(devicename): + if self._refresh_pyicloud_devices_location_data(location_age, devicename): self._display_info_status_msg(devicename, "Location Data Old, Refreshing") location_data = self.location_data.get(devicename) @@ -2704,7 +2935,10 @@ def _get_fmf_data(self, devicename): self._log_error_msg(f"iCloud3 Error > No Location Data " f"Returned for {devicename}") return ICLOUD_LOCATION_DATA_ERROR - self._display_info_status_msg(devicename, "iCloud Location Data Available") + + if self._device_online(devicename): + self._display_info_status_msg(devicename, "iCloud Location Data Available") + return True except Exception as err: @@ -2742,10 +2976,10 @@ def _get_famshr_data(self, devicename): log_msg = (f"LOCATION DATA-{location_data})") self._log_debug_msg(devicename, log_msg) - age = location_data[ATTR_AGE] + location_age = location_data[ATTR_AGE] - if age > self.old_location_secs.get(devicename): - if self._refresh_pyicloud_devices_location_data(age, devicename): + if location_age > self.old_location_secs.get(devicename): + if self._refresh_pyicloud_devices_location_data(location_age, devicename): self._display_info_status_msg(devicename, "Location Data Old, Refreshing") location_data = self.location_data.get(devicename) @@ -2766,7 +3000,7 @@ def _get_famshr_data(self, devicename): return ICLOUD_LOCATION_DATA_ERROR #---------------------------------------------------------------------------- - def _refresh_pyicloud_devices_location_data(self, age, arg_devicename): + def _refresh_pyicloud_devices_location_data(self, location_age, arg_devicename): ''' Authenticate pyicloud & refresh device & location data. This calls the function to update 'self.location_data' for each device being tracked. @@ -2776,12 +3010,12 @@ def _refresh_pyicloud_devices_location_data(self, age, arg_devicename): ''' try: - event_msg=(f"Sending location request to iCloud > Last Updated") - if age == HIGH_INTEGER: - event_msg += (f": Never (Initial Locate)") + event_msg=(f"Sending location request to iCloud > Last Updated-") + if location_age == HIGH_INTEGER: + event_msg += (f"Never (Initial Locate)") else: - event_msg += (f" {self.location_data.get(arg_devicename)[ATTR_TIMESTAMP_TIME]} " - f"({self._secs_to_time_str(age)} ago)") + event_msg += (f"{self.location_data.get(arg_devicename)[ATTR_TIMESTAMP_TIME]} " + f"({self._format_age(location_age)})") self._save_event_halog_info(arg_devicename, event_msg) exit_get_data_loop = False @@ -2875,9 +3109,9 @@ def _update_location_data(self, devicename, device_data): timestamp = device_data[ATTR_LOCATION][timestamp_field] / 1000 if timestamp == self.location_data.get(devicename)[ATTR_TIMESTAMP]: - age = self.location_data.get(devicename)[ATTR_AGE] + location_age = self.location_data.get(devicename)[ATTR_AGE] debug_msg = (f"DEVICE NOT UPDATED > Will Refresh, Located-{self._secs_to_time(timestamp)} " - f"({self._secs_to_time_str(age)} ago)") + f"({self._format_age(location_age)})") self._log_debug_msg(devicename, debug_msg) return @@ -2911,7 +3145,7 @@ def _update_location_data(self, devicename, device_data): self.location_data[devicename] = location_data debug_msg = (f"UPDATE LOCATION > Located-{location_data[ATTR_TIMESTAMP_TIME]} " - f"({self._secs_to_time_str(location_data[ATTR_AGE])} ago)") + f"({self._format_age(location_data[ATTR_AGE])})") self._log_debug_msg(devicename, debug_msg) self._log_debug_msg(devicename, location_data) @@ -2922,52 +3156,6 @@ def _update_location_data(self, devicename, device_data): return False -######################################################### -# -# iCloud is disabled so trigger the iosapp to send a -# Background Fetch location transaction -# -######################################################### - def _request_iosapp_location_update(self, devicename): - '''Send location request to phone''' - - if (self.iosapp_locate_request_cnt.get(devicename) > self.iosapp_locate_request_max_cnt): - return - - request_msg_suffix = '' - - try: - if self.iosapp_locate_update_secs.get(devicename, 0) > 0: - age = self._secs_since(self.iosapp_locate_update_secs.get(devicename)) - request_msg_suffix = (f" {self._secs_to_time_str(age)} ago") - - else: - self.iosapp_locate_update_secs[devicename] = self.this_update_secs - self.iosapp_locate_request_cnt[devicename] += 1 - - message = {"message": "request_location_update"} - return_code = self._send_message_to_device(devicename, message) - - #self.hass.async_create_task( - # self.hass.services.async_call('notify', entity_id, service_data)) - if return_code: - event_msg = (f"Requested iOS App Location (#{self.iosapp_locate_request_cnt.get(devicename)})") - - attrs = {} - attrs[ATTR_POLL_COUNT] = self._format_poll_count(devicename) - attrs[ATTR_INFO] = (f"● Requested iOS App Location " - f"(#{self.iosapp_locate_request_cnt.get(devicename)})" - f"{request_msg_suffix} ●") - self._update_device_sensors(devicename, attrs) - self._save_event(devicename, event_msg) - - except Exception as err: - _LOGGER.exception(err) - error_msg = (f"iCloud3 Error > An error occurred sending a location request > " - f"Device-{self.notify_iosapp_entity.get(devicename)}, Error-{err}") - self._save_event_halog_error(devicename, error_msg) - - ######################################################### # # Calculate polling interval based on zone, distance from home and @@ -2975,8 +3163,8 @@ def _request_iosapp_location_update(self, devicename): # ######################################################### def _determine_interval(self, devicename, latitude, longitude, - battery, gps_accuracy, old_loc_poor_gps_flag, - location_time_secs, location_time, + battery, gps_accuracy, poor_location_gps_flag, + last_located_secs, location_time, ios_icld = ''): """Calculate new interval. Return location based attributes""" @@ -2991,13 +3179,13 @@ def _determine_interval(self, devicename, latitude, longitude, latitude, longitude, gps_accuracy, - old_loc_poor_gps_flag) + poor_location_gps_flag) log_msg = (f"Location_data-{location_data}") self._log_debug_interval_msg(devicename, log_msg) #Abort and Retry if Internal Error - if (location_data[0] == 'ERROR'): + if (location_data[0] == ERROR): return location_data[1] #(attrs) self._display_info_status_msg(devicename, "● Calculating Tracking Info ●") @@ -3019,6 +3207,7 @@ def _determine_interval(self, devicename, latitude, longitude, dir_of_trav_msg = location_data[14] timestamp = location_data[15] + last_located_secs = self.last_located_secs.get(devicename) except Exception as err: attrs_msg = self._internal_error_msg(fct_name, err, 'SetLocation') @@ -3063,9 +3252,9 @@ def _determine_interval(self, devicename, latitude, longitude, f"NZ-{near_zone_flag}") self._log_debug_interval_msg(devicename, log_msg) - log_method = '' + interval_method = '' log_msg = '' - log_method_im = '' + interval_method_im = '' old_location_secs_msg = '' except Exception as err: @@ -3084,102 +3273,98 @@ def _determine_interval(self, devicename, latitude, longitude, #updating the device_tracker state so it will not trigger a state chng if self.state_change_flag.get(devicename): if inzone_flag: - - if (STATIONARY in zone): interval = self.stat_zone_inzone_interval - log_method = "1sz-Stationary" + interval_method = "1sz-Stationary" log_msg = f"Zone-{zone}" #inzone & old location - elif old_loc_poor_gps_flag: - interval = self._get_interval_for_error_retry_cnt( - self.old_loc_poor_gps_cnt.get(devicename)) - log_method = '1iz-OldLocPoorGPS' + elif poor_location_gps_flag: + interval = self._get_interval_for_error_retry_cnt(devicename, POOR_LOC_GPS_CNT) + #self.poor_location_gps_cnt.get(devicename)) + interval_method = '1iz-OldLocPoorGPS' else: interval = self.inzone_interval_secs - log_method="1ez-EnterZone" + interval_method="1ez-EnterZone" #entered 'near_zone' zone if close to HOME and last is NOT_HOME elif (near_zone_flag and wasnot_inzone_flag and calc_dist_from_zone_km < 2): interval = 15 dir_of_travel = 'NearZone' - log_method="1nz-EnterHomeNearZone" + interval_method="1nzniz-EnterNearZone" #entered 'near_zone' zone if close to HOME and last is NOT_HOME elif (near_zone_flag and was_inzone_flag and calc_dist_from_zone_km < 2): interval = 15 dir_of_travel = 'NearZone' - log_method="1nhz-EnterNearHomeZone" + interval_method="1nziz-EnterNearZone" #exited HOME zone elif (not_inzone_flag and was_inzone_home_flag): interval = 240 dir_of_travel = AWAY_FROM - log_method="1ehz-ExitHomeZone" + interval_method="1ehz-ExitHomeZone" #exited 'other' zone elif (not_inzone_flag and was_inzone_flag): interval = 120 dir_of_travel = 'left_zone' - log_method="1ez-ExitZone" + interval_method="1ez-ExitZone" #entered 'other' zone else: interval = 240 - log_method="1zc-ZoneChanged" + interval_method="1zc-ZoneChanged" log_msg = (f"Zone-{zone}, Last-{self.state_last_poll.get(devicename)}, " f"This-{self.state_this_poll.get(devicename)}") self._log_debug_interval_msg(devicename, log_msg) #inzone & poor gps & check gps accuracy when inzone - elif (self.poor_gps_accuracy_flag.get(devicename) + elif (self.poor_gps_flag.get(devicename) and inzone_flag and self.check_gps_accuracy_inzone_flag): interval = 300 #poor accuracy, try again in 5 minutes - log_method = '2iz-PoorGPS' + interval_method = '2pgpsiz-PoorGPSinZone' - elif self.poor_gps_accuracy_flag.get(devicename): - interval = self._get_interval_for_error_retry_cnt( - self.old_loc_poor_gps_cnt.get(devicename)) - log_method = '2niz-PoorGPS' + elif self.poor_gps_flag.get(devicename): + interval = self._get_interval_for_error_retry_cnt(devicename, POOR_LOC_GPS_CNT) + interval_method = '2pgps-PoorGPS' - elif self.overrideinterval_seconds.get(devicename) > 0: - interval = self.overrideinterval_seconds.get(devicename) - log_method = '3-Override' + elif self.override_interval_seconds.get(devicename) > 0: + interval = self.override_interval_seconds.get(devicename) + interval_method = '3ior-Override' elif (STATIONARY in zone): interval = self.stat_zone_inzone_interval - log_method = "4sz-Stationary" + interval_method = "4sz-Stationary" log_msg = f"Zone-{zone}" - elif old_loc_poor_gps_flag: - interval = self._get_interval_for_error_retry_cnt( - self.old_loc_poor_gps_cnt.get(devicename)) - log_method = '4-OldLocPoorGPS' - log_msg = f"Cnt-{self.old_loc_poor_gps_cnt.get(devicename)}" + elif poor_location_gps_flag: + interval = self._get_interval_for_error_retry_cnt(devicename, POOR_LOC_GPS_CNT) + interval_method = '4old-OldLocPoorGPS' + log_msg = f"Cnt-{self.poor_location_gps_cnt.get(devicename)}" elif (inzone_home_flag or (dist_from_zone_km < .05 and dir_of_travel == 'towards')): interval = self.inzone_interval_secs - log_method = '4iz-InZone' + interval_method = '4ihz-InHomeZone' log_msg = f"Zone-{zone}" elif zone == 'near_zone': interval = 15 - log_method = '4nz-NearZone' + interval_method = '4nz-NearZone' log_msg = f"Zone-{zone}, Dir-{dir_of_travel}" #in another zone and inzone time > travel time elif (inzone_flag and self.inzone_interval_secs > waze_interval): interval = self.inzone_interval_secs - log_method = '4iz-InZone' + interval_method = '4iz-InZone' log_msg = f"Zone-{zone}" elif dir_of_travel in ('left_zone', NOT_SET): @@ -3188,51 +3373,50 @@ def _determine_interval(self, devicename, latitude, longitude, dir_of_travel = AWAY_FROM else: dir_of_travel = NOT_SET - log_method = '5-NeedInfo' + interval_method = '5ni-NeedInfo' log_msg = f"ZoneLeft-{zone}" - elif dist_from_zone_km < 2.5 and self.went_3km.get(devicename): interval = 15 #1.5 mi=real close and driving - log_method = '10a-Dist < 2.5km(1.5mi)' + interval_method = '10a-<2.5km' elif dist_from_zone_km < 3.5: #2 mi=30 sec interval = 30 - log_method = '10b-Dist < 3.5km(2mi)' + interval_method = '10b-<3.5km' elif waze_time_from_zone > 5 and waze_interval > 0: interval = waze_interval - log_method = '10c-WazeTime' + interval_method = '10c-WazeTime' log_msg = f"TimeFmHome-{waze_time_from_zone}" elif dist_from_zone_km < 5: #3 mi=1 min interval = 60 - log_method = '10d-Dist < 5km(3mi)' + interval_method = '10d-<5km' elif dist_from_zone_km < 8: #5 mi=2 min interval = 120 - log_method = '10e-Dist < 8km(5mi)' + interval_method = '10e-<8km' elif dist_from_zone_km < 12: #7.5 mi=3 min interval = 180 - log_method = '10f-Dist < 12km(7mi)' + interval_method = '10f-<12km' elif dist_from_zone_km < 20: #12 mi=10 min interval = 600 - log_method = '10g-Dist < 20km(12mi)' + interval_method = '10g-<20km' elif dist_from_zone_km < 40: #25 mi=15 min interval = 900 - log_method = '10h-Dist < 40km(25mi)' + interval_method = '10h-<40km' elif dist_from_zone_km > 150: #90 mi=1 hr interval = 3600 - log_method = '10i-Dist > 150km(90mi)' + interval_method = '10i->150km' else: interval = calc_interval - log_method = '20-Calculated' + interval_method = '20calc-Calculated' log_msg = f"Value-{self._km_to_mi(dist_from_zone_km)}/1.5" except Exception as err: @@ -3243,7 +3427,7 @@ def _determine_interval(self, devicename, latitude, longitude, #determined in get_dist_data with dir_of_travel if dir_of_travel == STATIONARY: interval = self.stat_zone_inzone_interval - log_method = "21-Stationary" + interval_method = "21stat-Stationary" if self.in_stationary_zone_flag.get(devicename) is False: rtn_code = self._update_stationary_zone( @@ -3256,25 +3440,32 @@ def _determine_interval(self, devicename, latitude, longitude, if rtn_code: self.zone_current[devicename] = self._format_zone_name(devicename, STATIONARY) self.zone_timestamp[devicename] = dt_util.now().strftime(self.um_date_time_strfmt) - log_method_im = "●Set.Stationary.Zone" + interval_method_im = "●Set.Stationary.Zone" zone = STATIONARY dir_of_travel = 'in_zone' inzone_flag = True not_inzone_flag = False else: dir_of_travel = NOT_SET + if (dir_of_travel in ('', AWAY_FROM) + and interval < 180 + and interval > 0): + interval_method += ',xx30dot-Away(<3min)' - if dir_of_travel in ('', AWAY_FROM) and interval < 180: + if (dir_of_travel in ('', AWAY_FROM) + and interval < 180 + and interval > 30): interval = 180 - log_method_im = '30-Away(<3min)' + interval_method += ',30dot-Away(<3min)' elif (dir_of_travel == AWAY_FROM and not self.distance_method_waze_flag): interval_multiplier = 2 #calc-increase timer - log_method_im = '30-Away(Calc)' - - elif (dir_of_travel == NOT_SET and interval > 180): + interval_method += ',30dot-Away(Calc)' + elif (dir_of_travel == NOT_SET + and interval > 180): interval = 180 + interval_method += ',301dor->180s' #15-sec interval (close to zone) and may be going into a stationary zone, #increase the interval @@ -3282,7 +3473,7 @@ def _determine_interval(self, devicename, latitude, longitude, and devicename in self.stat_zone_timer and self.this_update_secs >= self.stat_zone_timer.get(devicename)+45): interval = 30 - log_method_im = '31-StatTimer+45' + interval_method += ',31st-StatTimer+45' except Exception as err: attrs_msg = self._internal_error_msg(fct_name, err, 'SetStatZone') @@ -3293,28 +3484,31 @@ def _determine_interval(self, devicename, latitude, longitude, #Turn off waze close to zone flag to use waze after leaving zone if inzone_flag: self.waze_close_to_zone_pause_flag = False - + if (self.iosapp_update_flag.get(devicename) + and interval < 180 + and self.override_interval_seconds.get(devicename) == 0): + interval_method += ',xx33ios-iosAppTrigger' #if triggered by ios app (Zone Enter/Exit, Manual, Fetch, etc.) #and interval < 3 min, set to 3 min. Leave alone if > 3 min. if (self.iosapp_update_flag.get(devicename) and interval < 180 - and self.overrideinterval_seconds.get(devicename) == 0): + and interval > 30 + and self.override_interval_seconds.get(devicename) == 0): interval = 180 - log_method = '0-iosAppTrigger' + interval_method += ',33ios-iosAppTrigger' #if changed zones on this poll reset multiplier if self.state_change_flag.get(devicename): interval_multiplier = 1 #Check accuracy again to make sure nothing changed, update counter - if self.poor_gps_accuracy_flag.get(devicename): + if self.poor_gps_flag.get(devicename): interval_multiplier = 1 except Exception as err: attrs_msg = self._internal_error_msg(fct_name, err, 'ResetStatZone') return attrs_msg - try: #Real close, final check to make sure interval is not adjusted if (interval <= 60 @@ -3329,21 +3523,22 @@ def _determine_interval(self, devicename, latitude, longitude, if interval > self.max_interval_secs and not_inzone_flag: interval_str = (f"{self._secs_to_time_str(self.max_interval_secs)}({self._secs_to_time_str(interval)})") interval = self.max_interval_secs - log_method = (f"40-MaxIntervalOverride {interval_str}") + interval_method += (f",40-Max") else: interval_str = self._secs_to_time_str(interval) - interval_debug_msg = (f"●Interval-{interval_str} ({log_method}, {log_msg}), " + interval_debug_msg = (f"●Interval-{interval_str} ({interval_method}, {log_msg}), " f"●DirOfTrav-{dir_of_trav_msg}, " f"●State-{self.state_last_poll.get(devicename)}->, " f"{self.state_this_poll.get(devicename)}, " f"Zone-{zone}") - event_msg = (f"Interval basis: {log_method}, {log_msg}, Direction {dir_of_travel}") + event_msg = (f"Interval basis: {interval_method}, {log_msg}, Direction {dir_of_travel}") #self._save_event(devicename, event_msg) - if interval_multiplier != 1: - interval_debug_msg = (f"{interval_debug_msg}, " - f"Multiplier-{interval_multiplier}({log_method_im})") + if interval_multiplier > 1: + interval_method += (f"x{interval_multiplier}") + interval_debug_msg = (f"{interval_debug_msg}, " + f"Multiplier-{interval_multiplier} ({interval_method})") #check if next update is past midnight (next day), if so, adjust it next_poll = round((self.this_update_secs + interval)/15, 0) * 15 @@ -3354,7 +3549,7 @@ def _determine_interval(self, devicename, latitude, longitude, self.interval_seconds[devicename_zone] = interval self.interval_str[devicename_zone] = interval_str self.last_update_secs[devicename_zone] = self.this_update_secs - self.last_update_time[devicename_zone] = self._secs_to_time(self.this_update_secs) + self.last_update_time[devicename_zone] = self._time_to_12hrtime(self.this_update_time) #-------------------------------------------------------------------------------- #Calculate the old_location age check based on the direction and if there are @@ -3365,7 +3560,7 @@ def _determine_interval(self, devicename, latitude, longitude, self.old_location_secs[devicename] = HIGH_INTEGER ic3dev_old_location_secs = self.old_location_secs.get(devicename) - new_old_location_secs = self._determine_old_location_secs(zone, interval) + new_old_location_secs = self._determine_old_location_secs(zone, interval) select='' if inzone_flag: select='inzone' @@ -3401,14 +3596,15 @@ def _determine_interval(self, devicename, latitude, longitude, if self.log_level_intervalcalc_flag == False: interval_debug_msg = '' - log_msg = (f"DETERMINE INTERVAL , " - f"This poll: {self._secs_to_time(self.this_update_secs)}({self.this_update_secs}), " - f"Last Update: {self.last_update_time.get(devicename_zone)}({self.last_update_secs.get(devicename_zone)}), " - f"Next Update: {self.next_update_time.get(devicename_zone)}({self.next_update_secs.get(devicename_zone)}), " - f"Interval: {self.interval_str.get(devicename_zone)}*{interval_multiplier}, " - f"OverrideInterval-{self.overrideinterval_seconds.get(devicename)}, " - f"DistTraveled-{dist_last_poll_moved_km}, CurrZone-{zone}") - self._log_debug_interval_msg(devicename, log_msg) + event_msg = (f"{EVLOG_DEBUG}Interval Results > " + f"Interval-{interval_str} ({interval_method}), " + f"LastUpdate-{self.last_update_time.get(devicename_zone)}, " + f"NextUpdate-{self.next_update_time.get(devicename_zone)}, " + f"DistTraveled-{self._format_dist(calc_dist_last_poll_moved_km)}, " + f"CurrZone-{zone}") + if self.override_interval_seconds.get(devicename) > 0: + event_msg += (f", OverrideInterval-{self._secs_to_time_str(self.override_interval_seconds.get(devicename))}") + self._save_event_halog_info(devicename, event_msg, log_title="") except Exception as err: attrs_msg = self._internal_error_msg(fct_name, err, 'ShowMsgs') @@ -3419,15 +3615,18 @@ def _determine_interval(self, devicename, latitude, longitude, if near_zone_flag: zone = NOT_HOME - log_msg = (f"DIR OF TRAVEL ATTRS, Direction-{dir_of_travel}, LastDir-{last_dir_of_travel}, " - f"Dist-{dist_from_zone_km}, LastDist-{last_dist_from_zone_km}, " - f"SelfDist-{self.zone_dist.get(devicename_zone)}, Moved-{dist_from_zone_moved_km}," + log_msg = (f"DIR OF TRAVEL ATTRS, Direction-{dir_of_travel}, " + f"LastDir-{last_dir_of_travel}, " + f"Dist-{dist_from_zone_km}, " + f"LastDist-{last_dist_from_zone_km}, " + f"SelfDist-{self.zone_dist.get(devicename_zone)}, " + f"Moved-{dist_from_zone_moved_km}," f"WazeMoved-{waze_dist_from_zone_moved_km}") self._log_debug_interval_msg(devicename, log_msg) #if poor gps and moved less than 1km, redisplay last distances if (self.state_change_flag.get(devicename) == False - and self.poor_gps_accuracy_flag.get(devicename) + and self.poor_gps_flag.get(devicename) and dist_last_poll_moved_km < 1): dist_from_zone_km = self.zone_dist.get(devicename_zone) waze_dist_from_zone_km = self.waze_dist.get(devicename_zone) @@ -3451,36 +3650,43 @@ def _determine_interval(self, devicename, latitude, longitude, #Save last and new state, set attributes #If first time thru, set the last state to the current state #so a zone change will not be triggered next time + if self.state_last_poll.get(devicename) == NOT_SET: - self.state_last_poll[devicename] = zone + last_state = zone #When put into stationary zone, also set last_poll so it #won't trigger again on next cycle as a state change elif (instr(zone, STATIONARY) or instr(self.state_this_poll.get(devicename), STATIONARY)): zone = STATIONARY - self.state_last_poll[devicename] = STATIONARY + last_state = STATIONARY + #elif self.state_this_poll.get(devicename) == AWAY: + # self.state_last_poll[devicename] = NOT_HOME else: - self.state_last_poll[devicename] = self.state_this_poll.get(devicename) + last_state = self.state_this_poll.get(devicename) + + #Make sure the new 'last state' value is the internal value for + #the state (e.g., Away-->not_home) to reduce state change triggers later. + last_state = STATE_TO_ZONE_BASE.get(last_state, last_state) + self.state_last_poll[devicename] = last_state self.state_this_poll[devicename] = zone self.last_located_time[devicename] = self._time_to_12hrtime(location_time) - location_age = self._secs_since(location_time_secs) - location_age_str = self._secs_to_time_str(location_age) - if (old_loc_poor_gps_flag and self.poor_gps_accuracy_flag.get(devicename) == False): + location_age = self._secs_since(last_located_secs) + location_age_str = self._format_age(location_age) + if (poor_location_gps_flag and self.poor_gps_flag.get(devicename) == False): location_age_str = (f"Old-{location_age_str}") log_msg = (f"LOCATION TIME-{devicename} location_time-{location_time}, " - f"loc_time_secs-{self._secs_to_time(location_time_secs)}({location_time_secs}), " - f"age-{location_age_str}") + f"loc_time_secs-{self._secs_to_time(last_located_secs)} ({location_age_str})") self._log_debug_msg(devicename, log_msg) attrs = {} attrs[ATTR_ZONE] = self.zone_current.get(devicename) attrs[ATTR_ZONE_TIMESTAMP] = str(self.zone_timestamp.get(devicename)) attrs[ATTR_LAST_ZONE] = self.zone_last.get(devicename) - attrs[ATTR_LAST_UPDATE_TIME] = self._secs_to_time(self.this_update_secs) + attrs[ATTR_LAST_UPDATE_TIME] = self._time_to_12hrtime(self.this_update_time) attrs[ATTR_LAST_LOCATED] = self._time_to_12hrtime(location_time) attrs[ATTR_INTERVAL] = interval_str @@ -3521,8 +3727,7 @@ def _determine_interval(self, devicename, latitude, longitude, battery, gps_accuracy, dist_last_poll_moved_km, - zone, - old_loc_poor_gps_flag, location_time_secs) + zone) attrs[ATTR_INFO] = interval_debug_msg + info_msg @@ -3532,18 +3737,21 @@ def _determine_interval(self, devicename, latitude, longitude, self.last_distance_str[devicename_zone] = (f"{self._km_to_mi(dist_from_zone_km)} {self.unit_of_measurement}") self._trace_device_attributes(devicename, 'RESULTS', fct_name, attrs) - event_msg = (f"Results: {self.zone_fname.get(self.base_zone)} > " - f"CurrZone-{self.zone_fname.get(self.zone_current.get(devicename), AWAY)}, " - f"GPS-{format_gps(latitude, longitude, gps_accuracy)}, " - f"Interval-{interval_str}, " - f"Dist-{self._km_to_mi(dist_from_zone_km)} {self.unit_of_measurement}, " + zone = self.zone_current.get(devicename) + + event_msg = (f"Results: From-{self.zone_to_display.get(self.base_zone)} > CurrZone-" + f"{self.zone_to_display.get(zone)}, ") + event_msg +=(f"GPS-{format_gps(latitude, longitude, gps_accuracy)}, " + f"Interval-{interval_str}") + event_msg +=(f" ({interval_method}), ") if self.log_level_debug_flag else ", " + event_msg +=(f"Dist-{self._km_to_mi(dist_from_zone_km)} {self.unit_of_measurement}, " f"TravTime-{waze_time_msg} ({dir_of_travel}), " f"NextUpdt-{self._secs_to_time(next_poll)}, " - f"Located-{self._time_to_12hrtime(location_time)} ({location_age_str} ago), " + f"Located-{self._time_to_12hrtime(location_time)} ({location_age_str}), " f"OldLocThreshold-{old_location_secs_msg}") if self.stat_zone_timer.get(devicename) > 0: - event_msg += (f", WillMoveIntoStatZoneAfter-{self._secs_to_time(self.stat_zone_timer.get(devicename))}" - f"({self.stat_zone_moved_total.get(devicename)*100}m)") + event_msg += (f", WillMoveIntoStatZoneAfter-{self._secs_to_time(self.stat_zone_timer.get(devicename))} " + f"({self._format_dist(self.stat_zone_moved_total.get(devicename))})") self._save_event_halog_info(devicename, event_msg, log_title="") return attrs @@ -3560,7 +3768,7 @@ def _determine_interval(self, devicename, latitude, longitude, # retry intervals based on current retry count. # ######################################################### - def _determine_interval_retry_after_error(self, devicename, retry_cnt, device_status, info_msg): + def _determine_interval_after_error(self, devicename, info_msg, counter=POOR_LOC_GPS_CNT): ''' Handle errors where the device can not be or should not be updated with the current data. The update will be retried 4 times on a 15 sec interval. @@ -3579,16 +3787,13 @@ def _determine_interval_retry_after_error(self, devicename, retry_cnt, device_st - Poor GPS Acuracy ''' - fct_name = "_determine_interval_retry_after_error" + fct_name = "_determine_interval_after_error" base_zone_home_flag = (self.base_zone == HOME) devicename_zone = self._format_devicename_zone(devicename) try: - if device_status in ["online", "pending", ""]: - interval = self._get_interval_for_error_retry_cnt(retry_cnt) - else: - interval = 900 + interval = self._get_interval_for_error_retry_cnt(devicename, counter) #check if next update is past midnight (next day), if so, adjust it next_poll = round((self.this_update_secs + interval)/15, 0) * 15 @@ -3596,22 +3801,29 @@ def _determine_interval_retry_after_error(self, devicename, retry_cnt, device_st # Update all dates and other fields interval_str = self._secs_to_time_str(interval) next_updt_str = self._secs_to_time(next_poll) - last_updt_str = self._secs_to_time(self.this_update_secs) self.interval_seconds[devicename_zone] = interval self.last_update_secs[devicename_zone] = self.this_update_secs + self.last_update_time[devicename_zone] = self._time_to_12hrtime(self.this_update_time) self.next_update_secs[devicename_zone] = next_poll - self.last_update_time[devicename_zone] = last_updt_str self.next_update_time[devicename_zone] = next_updt_str self.interval_str[devicename_zone] = interval_str self.count_update_ignore[devicename] += 1 attrs = {} - attrs[ATTR_LAST_UPDATE_TIME] = last_updt_str + attrs[ATTR_LAST_UPDATE_TIME] = self._time_to_12hrtime(self.this_update_time) attrs[ATTR_INTERVAL] = interval_str attrs[ATTR_NEXT_UPDATE_TIME] = next_updt_str attrs[ATTR_POLL_COUNT] = self._format_poll_count(devicename) - attrs[ATTR_INFO] = (f"●● {info_msg} ●●") + + #If located more than 12 hrs ago, use dhms ago instead of time + location_age = self._secs_since(self.last_located_secs.get(devicename)) + if location_age > 42300: + attrs[ATTR_LAST_LOCATED] = f"{self.format_age(location_age)}" + info_msg = f"May be Offline, {info_msg}, LastLocated-{self.format_age(location_age)}" + self._save_event(devicename,info_msg) + + attrs[ATTR_INFO] = (f"●● {info_msg} ●●") this_zone = self.state_this_poll.get(devicename) this_zone = self._format_zone_name(devicename, this_zone) @@ -3650,12 +3862,20 @@ def _determine_interval_retry_after_error(self, devicename, retry_cnt, device_st self.device_being_updated_flag[devicename] = False - log_msg = (f"DETERMINE INTERVAL ERROR RETRY, CurrZone-{this_zone}, " - f"LastZone-{last_zone}, GPS-{format_gps(latitude,longitude, 0)}") - self._log_debug_interval_msg(devicename, log_msg) - log_msg = (f"DETERMINE INTERVAL ERROR RETRY, Interval-{interval_str}, " - f"LastUpdt-{last_updt_str}, NextUpdt-{next_updt_str}, Info-{info_msg}") - self._log_debug_interval_msg(devicename, log_msg) + #Set the lat/long for the Error Msg if not_set + if this_zone == NOT_SET: + latitude = 0 + longitude = 0 + + event_msg = (f"{EVLOG_DEBUG}Discarded Results: {self.zone_to_display.get(self.base_zone)} > " + f"CurrZone-{this_zone}, " + f"GPS-{format_gps(latitude, longitude, 0)}, " + f"Interval-{interval_str}, " + f"NextUpdt-{next_updt_str}, " + f"OldLocPoorGpsCnt-#{self.poor_location_gps_cnt.get(devicename)}, " + f"UpdateErrorCnt-#{self.count_update_ignore.get(devicename)}, " + f"InfoMsg-{info_msg}") + self._save_event(devicename, event_msg) except Exception as err: _LOGGER.exception(err) @@ -3666,7 +3886,7 @@ def _determine_interval_retry_after_error(self, devicename, retry_cnt, device_st # ######################################################### def _get_distance_data(self, devicename, latitude, longitude, - gps_accuracy, old_loc_poor_gps_flag): + gps_accuracy, poor_location_gps_flag): """ Determine the location of the device. Returns: - zone (current zone from lat & long) @@ -3682,7 +3902,7 @@ def _get_distance_data(self, devicename, latitude, longitude, try: if latitude is None or longitude is None: attrs = self._internal_error_msg(fct_name, 'lat/long=None', 'NoLocation') - return ('ERROR', attrs) + return (ERROR, attrs) base_zone_home_flag = (self.base_zone == HOME) devicename_zone = self._format_devicename_zone(devicename) @@ -3713,7 +3933,7 @@ def _get_distance_data(self, devicename, latitude, longitude, _LOGGER.exception(err) error_msg = (f"Entity-{entity_id}, Err-{err}") attrs = self._internal_error_msg(fct_name, error_msg, 'GetAttrs') - return ('ERROR', attrs) + return (ERROR, attrs) try: #Not available if first time after reset @@ -3745,7 +3965,7 @@ def _get_distance_data(self, devicename, latitude, longitude, except Exception as err: _LOGGER.exception(err) attrs = self._internal_error_msg(fct_name, err, 'SetupLocation') - return ('ERROR', attrs) + return (ERROR, attrs) try: zone = self._get_zone(devicename, this_lat, this_long) @@ -3759,7 +3979,7 @@ def _get_distance_data(self, devicename, latitude, longitude, except Exception as err: _LOGGER.exception(err) attrs = self._internal_error_msg(fct_name, err, 'GetCurrZone') - return ('ERROR', attrs) + return (ERROR, attrs) try: # Get Waze distance & time @@ -3832,7 +4052,7 @@ def _get_distance_data(self, devicename, latitude, longitude, except Exception as err: _LOGGER.exception(err) attrs = self._internal_error_msg(fct_name, err, 'InitializeDist') - return ('ERROR', attrs) + return (ERROR, attrs) try: if self.waze_status == WAZE_USED: @@ -3869,7 +4089,7 @@ def _get_distance_data(self, devicename, latitude, longitude, #device. if (gps_accuracy <= self.gps_accuracy_threshold and waze_dist_from_zone_km > 0 - and old_loc_poor_gps_flag is False): + and poor_location_gps_flag is False): self.waze_distance_history[devicename_zone] = \ [self._time_now_secs(), this_lat, @@ -3943,7 +4163,7 @@ def _get_distance_data(self, devicename, latitude, longitude, except Exception as err: _LOGGER.exception(err) attrs = self._internal_error_msg(fct_name, err, 'CalcDist') - return ('ERROR', attrs) + return (ERROR, attrs) try: section = "dir_of_trav" @@ -3965,7 +4185,7 @@ def _get_distance_data(self, devicename, latitude, longitude, dir_of_travel = AWAY_FROM dir_of_trav_msg = (f"Dist-{self._format_dist(dist_from_zone_moved_km)}") - elif self.poor_gps_accuracy_flag.get(devicename): + elif self.poor_gps_flag.get(devicename): dir_of_travel = 'Poor.GPS' dir_of_trav_msg = ("Poor.GPS-{gps_accuracy}") @@ -4090,7 +4310,7 @@ def _get_distance_data(self, devicename, latitude, longitude, except Exception as err: _LOGGER.exception(err) attrs = self._internal_error_msg(fct_name+section, err, 'Finalize') - return ('ERROR', attrs) + return (ERROR, attrs) #-------------------------------------------------------------------------------- def _determine_old_location_secs(self, zone, interval): @@ -4101,19 +4321,19 @@ def _determine_old_location_secs(self, zone, interval): if self.old_location_threshold > 0: return self.old_location_threshold - old_location_secs = 14 + old_location_secs = 60 if self._is_inzone_zonename(zone): old_location_secs = interval * .025 #inzone interval --> 2.5% if old_location_secs < 90: old_location_secs = 90 elif interval < 90: - old_location_secs = 30 #30 secs if < 1.5 min + old_location_secs = 60 #60 secs if < 1.5 min else: old_location_secs = interval * .125 #12.5% of the interval - if old_location_secs < 15: - old_location_secs = 15 + if old_location_secs < 61: + old_location_secs = 61 elif old_location_secs > 600: old_location_secs = 600 @@ -4131,19 +4351,14 @@ def _determine_old_location_secs(self, zone, interval): def _get_state(self, entity_id): """ Get current state of the device_tracker entity - (home, away, other state) + (zone's name, actual state (home, away) or zone's + friendly name) and return it's zone name """ try: - device_state = self.hass.states.get(entity_id).state + entity_state = self.hass.states.get(entity_id).state - if device_state: - if device_state.lower() == 'not set': - state = NOT_SET - else: - state = device_state - else: - state = NOT_HOME + state = self.state_to_zone.get(entity_state, entity_state.lower()) except Exception as err: #When starting iCloud3, the device_tracker for the iosapp might @@ -4151,7 +4366,7 @@ def _get_state(self, entity_id): #_LOGGER.exception(err) state = NOT_SET - return state.lower() + return state #-------------------------------------------------------------------- def _set_state(self, entity_id, state_value, attrs_value): """ @@ -4183,7 +4398,7 @@ def _get_entity_last_changed_time(self, entity_id, devicename): hhmmss = self._secs_to_time(secs) timestamp = self._secs_to_timestamp(secs) age_secs = self.this_update_secs - secs - dhms_age_str = self._secs_to_minsec_str(age_secs) + dhms_age_str = self._secs_to_dhms_str(age_secs) return hhmmss, secs, timestamp, age_secs, dhms_age_str @@ -4230,7 +4445,7 @@ def _get_attr(attributes, attribute_name, numeric = False): #-------------------------------------------------------------------- def _update_device_attributes(self, devicename, kwargs: str = None, - attrs: str = None, fct_name: str = 'Unknown'): + attrs: str = None, fct_name: str = UNKNOWN): """ Update the device and attributes with new information On Entry, kwargs = {} or contains the base attributes. @@ -4270,9 +4485,9 @@ def _update_device_attributes(self, devicename, kwargs: str = None, 'entity_picture': '/local/gary-caller_id.png'} """ + zone = self.zone_current.get(devicename) ic3dev_state = self.state_this_poll.get(devicename) - zone = self.zone_current.get(devicename) - + ic3dev_state_fname = ic3dev_state ####################################################################### #The current zone is based on location of the device after it is looked @@ -4293,28 +4508,21 @@ def _update_device_attributes(self, devicename, kwargs: str = None, #current zone that was based on the device location. #If the state is in a zone but not the current zone, change the state #to the current zone that was based on the device location. - elif ((ic3dev_state == STATIONARY and self._is_inzone(zone)) or - (self._is_inzone(ic3dev_state) and self._is_inzone(zone) and - ic3dev_state != zone)): - event_msg = (f"State/Zone mismatch > Resetting iC3 State ({ic3dev_state}) " - f"to ({zone})") - self._save_event(devicename, event_msg) - ic3dev_state = zone + elif ((ic3dev_state == STATIONARY + and self._is_inzone(zone)) + or (self._is_inzone(ic3dev_state) + and self._is_inzone(zone) + and ic3dev_state != zone)): + if self._check_overlapping_zone(ic3dev_state, zone) == False: + event_msg = (f"State/Zone mismatch > Resetting iC3 State ({ic3dev_state}) " + f"to ({zone})") + self._save_event(devicename, event_msg) + ic3dev_state = zone elif ic3dev_state == HOME: self.waze_distance_history = {} - #Get friendly name or capitalize and reformat ic3dev_state, reset waze history - if self._is_inzone_zonename(ic3dev_state): - if self.zone_fname.get(ic3dev_state): - ic3dev_state = self.zone_fname.get(ic3dev_state) - - else: - ic3dev_state = ic3dev_state.replace('_', ' ') - ic3dev_state = ic3dev_state.title() - - if ic3dev_state == 'Home': - ic3dev_state = HOME + ic3dev_state_fname = self.zone_to_display.get(ic3dev_state, ic3dev_state) #Update the device timestamp if not attrs: @@ -4343,7 +4551,7 @@ def _update_device_attributes(self, devicename, kwargs: str = None, self.trigger[devicename] = new_trigger attrs[ATTR_TRIGGER] = new_trigger - #Update sensor._last_update_trigger if IOS App v2 detected + #Update sensor._last_update_trigger if IOS App detected #and iCloud3 has been running for at least 10 secs to let HA & #mobile_app start up to avoid error if iC3 loads before the mobile_app @@ -4357,7 +4565,7 @@ def _update_device_attributes(self, devicename, kwargs: str = None, kwargs['dev_id'] = devicename kwargs['host_name'] = self.fname.get(devicename) - kwargs['location_name'] = ic3dev_state + kwargs['location_name'] = ic3dev_state_fname kwargs['source_type'] = 'gps' kwargs[ATTR_ATTRIBUTES] = attrs self.see(**kwargs) @@ -4446,7 +4654,7 @@ def _setup_base_kwargs(self, devicename, latitude, longitude, and zone_dist <= self.zone_radius_m.get(zone_name, 100) and (latitude != zone_lat or longitude != zone_long)): event_msg = (f"Moving to zone center > {zone_name}, " - f"GPS-{format_gps(latitude, longitude, zone_lat, zone_long, 0)}, " + f"GPS-{format_gps(latitude, longitude, gps_accuracy, zone_lat, zone_long)}, " f"Distance-{self._format_dist_m(zone_dist)}") self._save_event(devicename, event_msg) self._log_debug_msg(devicename, event_msg) @@ -4484,7 +4692,7 @@ def _format_fname_devicename(self, devicename): #-------------------------------------------------------------------- def _format_fname_zone(self, zone): - return (f"{self.zone_fname.get(zone, zone.title())}") + return (f"{self.zone_to_display.get(zone, zone.title())}") #-------------------------------------------------------------------- def _format_devicename_zone(self, devicename, zone = None): @@ -4498,6 +4706,9 @@ def _format_list(self, arg_list): formatted_list = formatted_list.replace("{", "").replace("}", "") formatted_list = formatted_list.replace("'", "").replace(",", "CRLF• ") return (f"CRLF• {formatted_list}") +#-------------------------------------------------------------------- + def _format_age(self, secs): + return (f"{self._secs_to_time_str(secs)} ago") #-------------------------------------------------------------------- def _trace_device_attributes(self, devicename, description, fct_name, attrs): @@ -4568,9 +4779,13 @@ def _send_message_to_device(self, devicename, service_data): "Trigger was not received"}} ''' try: - evlog_msg = (f"{EVLOG_NOTICE}Sending Message to Device > " - f"Message-{service_data.get('message')}") - self._save_event_halog_info(devicename, evlog_msg) + if self.notify_iosapp_entity.get(devicename, None) == None: + return + + if service_data.get('message') != "request_location_update": + evlog_msg = (f"{EVLOG_NOTICE}Sending Message to Device > " + f"Message-{service_data.get('message')}") + self._save_event_halog_info(devicename, evlog_msg) for notify_devicename in self.notify_iosapp_entity.get(devicename): entity_id = (f"mobile_app_{notify_devicename}") @@ -4607,6 +4822,12 @@ def _get_iosapp_device_tracker_state_attributes(self, devicename, ic3_state, ic3 iosapp_state = self._get_state(entity_id) iosapp_dev_attrs = self._get_device_attributes(entity_id) + #iosapp state is the friendly name of the zone, ic3 keeps the state + #by zone name, not the friendly name. Convert iosapp state back to zone + #entity name to match ic3 state_this_poll and state_last_poll, + #state-zone name mismatch errors and state change detected trigger + #when it really didn't + if ATTR_LATITUDE in iosapp_dev_attrs: self.iosapp_monitor_error_cnt[devicename] = 0 @@ -4678,7 +4899,7 @@ def _get_zone(self, devicename, latitude, longitude): ''' zone_selected_dist = HIGH_INTEGER zone_selected = None - log_msg = f"Select Zone > " + zones_msg = "" iosapp_zone_msg = "" zone_iosapp = self.state_this_poll.get(devicename) if self._is_inzone_zonename(self.state_this_poll.get(devicename)) else None @@ -4710,17 +4931,12 @@ def _get_zone(self, devicename, latitude, longitude): zone_selected = zone iosapp_zone_msg = " (Using iOSApp State)" - log_msg += (f"{self.zone_fname.get(zone)}-" - f"{self._format_dist(zone_dist)}/r" - f"{round(self.zone_radius_m.get(zone))}, ") - - event_msg = (f"{log_msg[:-2]}") - event_msg += (f" > Selected-{self.zone_fname.get(zone_selected, AWAY)}{iosapp_zone_msg}") - - self._save_event(devicename, event_msg) - log_msg = f"GET ZONE {event_msg}" - self._log_debug_msg(devicename, log_msg) - + if (instr(zone, STATIONARY)): + zones_msg += self.zone_to_display.get(STATIONARY) + else: + zones_msg += self.zone_to_display.get(zone) + zones_msg += (f"-{self._format_dist(zone_dist)}" + f"/r{round(self.zone_radius_m.get(zone))}, ") if zone_selected is None: zone_selected = NOT_HOME @@ -4737,6 +4953,21 @@ def _get_zone(self, devicename, latitude, longitude): elif instr(zone,'nearzone'): zone_selected = 'near_zone' + event_msg = (f"Selected Zone > ") + + if self.display_zone_fname_flag: + event_msg += ZONE_TO_DISPLAY_BASE.get(zone_selected, zone_selected) + else: + event_msg += self.zone_to_display.get(zone_selected, NOT_HOME) + + event_msg += (f"{iosapp_zone_msg} > {zones_msg[:-2]}") + + self._save_event(devicename, event_msg) + self._log_debug_msg(devicename, event_msg) + + #Get distance between zone selected and current zone to see if they overlap + if self._check_overlapping_zone(self.zone_current.get(devicename), zone_selected): + self.zone_current[devicename] = zone_selected #If the zone changed from a previous poll, save it and set the new one if (self.zone_current.get(devicename) != zone_selected): @@ -4759,6 +4990,25 @@ def _get_zone(self, devicename, latitude, longitude): return zone_selected +#-------------------------------------------------------------------- + def _check_overlapping_zone(self, zone1, zone2): + ''' + zone1 and zone2 overlap if their distance between centers is less than 2m + ''' + try: + if zone1 == zone2: + return True + + if zone1 == "": zone1 = HOME + zone_dist = self._calc_distance_m( + self.zone_lat.get(zone1), self.zone_long.get(zone1), + self.zone_lat.get(zone2), self.zone_long.get(zone2)) + + return (zone_dist <= 2) + + except: + return False + #-------------------------------------------------------------------- @staticmethod def _get_zone_names(zone_name): @@ -4774,9 +5024,9 @@ def _get_zone_names(zone_name): office__bldg_1 --> Office Bldg1 """ if zone_name: - if STATIONARY in zone_name: + if instr(zone_name, STATIONARY): name1 = STATIONARY - elif NOT_HOME in zone_name: + elif instr(zone_name, NOT_HOME): name1 = AWAY else: name1 = zone_name.title() @@ -4784,8 +5034,8 @@ def _get_zone_names(zone_name): if zone_name == ATTR_ZONE: badge_state = name1 - name2 = zone_name.title().replace('_', ' ', 99) - name3 = zone_name.title().replace('_', '', 99) + name2 = zone_name.title().replace('_', ' ') + name3 = zone_name.title().replace('_', '') else: name1 = NOT_SET name2 = 'Not Set' @@ -4808,7 +5058,7 @@ def _set_base_zone_name_lat_long_radius(self, zone): Set the base_zone's name, lat, long & radius ''' self.base_zone = zone - self.base_zone_name = self.zone_fname.get(zone) + self.base_zone_name = self.zone_to_display.get(zone) self.base_zone_lat = self.zone_lat.get(zone) self.base_zone_long = self.zone_long.get(zone) self.base_zone_radius_km = float(self.zone_radius_km.get(zone)) @@ -4925,9 +5175,9 @@ def _update_stationary_zone(self, devicename, latitude, longitude, enter_exit_fl if latitude is None or longitude is None: return + stat_zone_dist = self._calc_distance_m(latitude, longitude, self.zone_lat.get(stat_zone_name), self.zone_long.get(stat_zone_name)) - stat_home_dist = self._calc_distance_m(latitude, longitude, self.zone_home_lat, self.zone_home_long,) @@ -4973,6 +5223,11 @@ def _update_stationary_zone(self, devicename, latitude, longitude, enter_exit_fl f"DistFromHome-{self._format_dist_m(stat_home_dist)}") self._save_event(devicename, event_msg) + else: + #self.zone_by_fname[stat_zone_name] = stat_zone_name + self.zone_to_display[stat_zone_name] = 'Stationary' + self.state_to_zone[stat_zone_name] = stat_zone_name + return True #Set Stationary Zone at new location @@ -5081,25 +5336,23 @@ def _update_device_sensors(self, arg_devicename, attrs:dict): sensor_attrs = {} if attr_name in SENSOR_ATTR_FORMAT: format_type = SENSOR_ATTR_FORMAT.get(attr_name) - if format_type == "dist": - sensor_attrs['unit_of_measurement'] = \ - self.unit_of_measurement + if format_type == 'dist': + sensor_attrs[CONF_UNIT_OF_MEASUREMENT] = self.unit_of_measurement - elif format_type == "diststr": + elif format_type == 'diststr': try: x = (state_value / 2) - sensor_attrs['unit_of_measurement'] = \ - self.unit_of_measurement + sensor_attrs[CONF_UNIT_OF_MEASUREMENT] = self.unit_of_measurement except: - sensor_attrs['unit_of_measurement'] = '' - elif format_type == "%": - sensor_attrs['unit_of_measurment'] = '%' + sensor_attrs[CONF_UNIT_OF_MEASUREMENT] = '' + elif format_type == '%': + sensor_attrs[CONF_UNIT_OF_MEASUREMENT] = '%' elif format_type == 'title': state_value = state_value.title().replace('_', ' ') elif format_type == 'kph-mph': - sensor_attrs['unit_of_measurement'] = self.um_kph_mph + sensor_attrs[CONF_UNIT_OF_MEASUREMENT] = self.um_kph_mph elif format_type == 'm-ft': - sensor_attrs['unit_of_measurement'] = self.um_m_ft + sensor_attrs[CONF_UNIT_OF_MEASUREMENT] = self.um_m_ft if attr_name in SENSOR_ATTR_ICON: sensor_attrs['icon'] = SENSOR_ATTR_ICON.get(attr_name) @@ -5170,7 +5423,7 @@ def _update_device_sensors_hass(self, devicename, base_entity, attr_name, #-------------------------------------------------------------------- def _format_info_attr(self, devicename, battery, gps_accuracy, dist_last_poll_moved_km, - zone, old_loc_poor_gps_flag, location_time_secs): #location_time): + zone): """ Initialize info attribute @@ -5189,7 +5442,7 @@ def _format_info_attr(self, devicename, battery, and self.tracking_method_config != IOSAPP): info_msg += (f" • Track.Method: {self.trk_method_short_name}") - if self.overrideinterval_seconds.get(devicename) > 0: + if self.override_interval_seconds.get(devicename) > 0: info_msg += " • Overriding.Interval" if zone == 'near_zone': @@ -5200,20 +5453,20 @@ def _format_info_attr(self, devicename, battery, if gps_accuracy > self.gps_accuracy_threshold: info_msg += (f" • Poor.GPS.Accuracy, Dist-{self._format_dist(gps_accuracy)}") - if self.old_loc_poor_gps_cnt.get(devicename) > 0: - info_msg += (f" (#{self.old_loc_poor_gps_cnt.get(devicename)})") + if self.poor_location_gps_cnt.get(devicename) > 0: + info_msg += (f" (#{self.poor_location_gps_cnt.get(devicename)})") if (self._is_inzone_zonename(zone) and self.ignore_gps_accuracy_inzone_flag): info_msg += " - Discarded" - isold_cnt = self.old_loc_poor_gps_cnt.get(devicename) - - if isold_cnt > 0: - age = self._secs_since(self.last_located_secs.get(devicename)) - info_msg += (f" • Old.Location, Age-{self._secs_to_time_str(age)} (#{isold_cnt})") + old_cnt = self.poor_location_gps_cnt.get(devicename) + if old_cnt > 16: + location_age = self._secs_since(self.last_located_secs.get(devicename)) + info_msg += (f" • May Be Offline, Located-{self._format_age(location_age)}, " + f"OldCnt-#{old_cnt}") if self.stat_zone_timer.get(devicename) > 0: - info_msg += (f" • Into.Stationary.Zone@{self._secs_to_time(self.stat_zone_timer.get(devicename))}") + info_msg += (f" • MoveIntoStatZone@{self._secs_to_time(self.stat_zone_timer.get(devicename))}") if self.waze_data_copied_from.get(devicename) is not None: copied_from = self.waze_data_copied_from.get(devicename) @@ -5305,7 +5558,7 @@ def _display_usage_counts(self, devicename, force_display=False): self.count_update_ignore.get(devicename) + \ self.count_state_changed.get(devicename) + \ self.count_trigger_changed.get(devicename) + \ - self.iosapp_locate_request_cnt.get(devicename) + self.iosapp_request_loc_cnt.get(devicename) pyi_avg_time_per_call = self.time_pyicloud_calls / \ @@ -5341,7 +5594,7 @@ def _display_usage_counts(self, devicename, force_display=False): f"«LT-iOS App Updates¦LC-{self.count_update_iosapp.get(devicename)}¦RT-Time/Locate (secs)¦RC-{round(pyi_avg_time_per_call, 2)}»") else: count_msg += (f"«HS¦LH-Device Counts¦RH-iOS App Counts»HE" - f"«LT-State/Triggers Chgs¦LC-{state_trig_count}¦RT-iOS Locate Rqsts¦RC-{self.iosapp_locate_request_cnt.get(devicename)}»" + f"«LT-State/Triggers Chgs¦LC-{state_trig_count}¦RT-iOS Locate Requests¦RC-{self.iosapp_request_loc_cnt.get(devicename)}»" f"«LT-iCloud Updates¦LC-{self.count_update_icloud.get(devicename)}¦RT-iOS App Updates¦RC-{self.count_update_iosapp.get(devicename)}»") count_msg += (f"«LT-Discarded¦LC-{self.count_update_ignore.get(devicename)}¦RT-Waze Routes¦RC-{self.count_waze_locates.get(devicename)}»" @@ -5461,6 +5714,7 @@ def _define_device_fields(self): self.api_device_devicename = {} #icloud.api.device obj for each devicename self.data_source = {} self.device_type = {} + self.device_status = {} self.devicename_iosapp_entity = {} self.devicename_iosapp_suffix = {} self.notify_iosapp_entity = {} @@ -5485,29 +5739,73 @@ def _define_device_status_fields(self): self.zone_timestamp = {} self.state_change_flag = {} self.location_data = {} - self.overrideinterval_seconds = {} self.last_located_time = {} self.last_located_secs = {} #device timestamp in seconds self.went_3km = {} #>3 km/mi, probably driving +#-------------------------------------------------------------------- + def _initialize_device_status_fields(self, devicename): + ''' + Make domain name entity ids for the device_tracker and + sensors for each device so we don't have to do it all the + time. Then check to see if 'sensor.geocode_location' + exists. If it does, then using iosapp version 2. + ''' + entity_id = (f"device_tracker.{devicename}") + self.device_tracker_entity_ic3[devicename] = entity_id + self.state_this_poll[devicename] = self._get_state(entity_id) + self.state_last_poll[devicename] = NOT_SET + self.device_status[devicename] = UNKNOWN + self.zone_last[devicename] = '' + self.zone_current[devicename] = '' + self.zone_timestamp[devicename] = '' + self.state_change_flag[devicename] = False + self.location_data[devicename] = INITIAL_LOCATION_DATA + self.last_located_time[devicename] = HHMMSS_ZERO + self.last_located_secs[devicename] = 0 + self.went_3km[devicename] = False + + self.trigger[devicename] = 'iCloud3' + self.got_exit_trigger_flag[devicename] = False + self.seen_this_device_flag[devicename] = False + self.device_being_updated_flag[devicename] = False + self.device_being_updated_retry_cnt[devicename] = 0 + + self.iosapp_update_flag[devicename] = False + + #iosapp v2 entity info + self.last_iosapp_state[devicename] = '' + self.last_iosapp_state_changed_time[devicename] = '' + self.last_iosapp_state_changed_secs[devicename] = 0 + self.last_iosapp_trigger[devicename] = '' + self.last_iosapp_trigger_changed_time[devicename] = '' + self.last_iosapp_trigger_changed_secs[devicename] = 0 + self.iosapp_monitor_error_cnt[devicename] = 0 + + #-------------------------------------------------------------------- def _initialize_um_formats(self, unit_of_measurement): #Define variables, lists & tables if unit_of_measurement == 'mi': - self.um_time_strfmt = '%I:%M:%S' - self.um_time_strfmt_ampm = '%I:%M:%S%P' - self.um_date_time_strfmt = '%Y-%m-%d %I:%M:%S' + if self.time_format != 24: self.time_format = 12 self.um_km_mi_factor = 0.62137 self.um_m_ft = 'ft' self.um_kph_mph = 'mph' else: - self.um_time_strfmt = '%H:%M:%S' - self.um_time_strfmt_ampm = '%H:%M:%S' - self.um_date_time_strfmt = '%Y-%m-%d %H:%M:%S' + if self.time_format != 12: self.time_format = 24 self.um_km_mi_factor = 1 self.um_m_ft = 'm' self.um_kph_mph = 'kph' + if self.time_format == 12: + self.um_time_strfmt = '%I:%M:%S' + self.um_time_strfmt_ampm = '%I:%M:%S%P' + self.um_date_time_strfmt = '%Y-%m-%d %I:%M:%S' + else: + self.um_time_strfmt = '%H:%M:%S' + self.um_time_strfmt_ampm = '%H:%M:%S' + self.um_date_time_strfmt = '%Y-%m-%d %H:%M:%S' + #-------------------------------------------------------------------- def _setup_tracking_method(self, tracking_method): ''' @@ -5555,76 +5853,38 @@ def _setup_iosapp_tracking_method(self): self.TRK_METHOD_FAMSHR = False self.TRK_METHOD_FMF_FAMSHR = False -#-------------------------------------------------------------------- - def _initialize_device_status_fields(self, devicename): - ''' - Make domain name entity ids for the device_tracker and - sensors for each device so we don't have to do it all the - time. Then check to see if 'sensor.geocode_location' - exists. If it does, then using iosapp version 2. - ''' - entity_id = self.device_tracker_entity_ic3.get(devicename) - self.state_this_poll[devicename] = self._get_state(entity_id) - self.state_last_poll[devicename] = NOT_SET - self.zone_last[devicename] = '' - self.zone_current[devicename] = '' - self.zone_timestamp[devicename] = '' - self.state_change_flag[devicename] = False - self.trigger[devicename] = 'iCloud3' - self.got_exit_trigger_flag[devicename] = False - self.last_located_time[devicename] = HHMMSS_ZERO - self.last_located_secs[devicename] = 0 - self.location_data[devicename] = INITIAL_LOCATION_DATA - self.went_3km[devicename] = False - self.seen_this_device_flag[devicename] = False - self.device_being_updated_flag[devicename] = False - self.device_being_updated_retry_cnt[devicename] = 0 - - self.iosapp_update_flag[devicename] = False - - #iosapp v2 entity info - self.last_iosapp_state[devicename] = '' - self.last_iosapp_state_changed_time[devicename] = '' - self.last_iosapp_state_changed_secs[devicename] = 0 - self.last_iosapp_trigger[devicename] = '' - self.last_iosapp_trigger_changed_time[devicename] = '' - self.last_iosapp_trigger_changed_secs[devicename] = 0 - self.iosapp_monitor_error_cnt[devicename] = 0 - - #-------------------------------------------------------------------- def _define_device_tracking_fields(self): #times, flags - self.update_timer = {} - self.overrideinterval_seconds = {} + self.update_timer = {} + self.override_interval_seconds = {} self.dist_from_zone_km_small_move_total = {} - self.this_update_secs = 0 + self.this_update_secs = 0 #location, gps - self.old_loc_poor_gps_cnt = {} # override interval while < 4 - self.old_loc_poor_gps_msg = {} + self.poor_location_gps_cnt = {} # override interval while < 4 + self.poor_location_gps_msg = {} self.old_location_secs = {} - - self.poor_gps_accuracy_flag = {} + self.poor_gps_flag = {} + self.last_lat = {} self.last_long = {} self.last_battery = {} #used to detect iosapp v2 change - self.last_lat = {} self.last_gps_accuracy = {} #used to detect iosapp v2 change #-------------------------------------------------------------------- def _initialize_device_tracking_fields(self, devicename): #times, flags - self.update_timer[devicename] = time.time() - self.overrideinterval_seconds[devicename] = 0 + self.update_timer[devicename] = time.time() + self.override_interval_seconds[devicename] = 0 self.dist_from_zone_km_small_move_total[devicename] = 0 #location, gps - self.old_loc_poor_gps_cnt[devicename] = 0 - self.old_loc_poor_gps_msg[devicename] = False + self.poor_location_gps_cnt[devicename] = 0 + self.poor_location_gps_msg[devicename] = False self.old_location_secs[devicename] = 90 #Timer (secs) before a location is old + self.poor_gps_flag[devicename] = False self.last_lat[devicename] = self.zone_home_lat self.last_long[devicename] = self.zone_home_long - self.poor_gps_accuracy_flag[devicename] = False self.last_battery[devicename] = 0 self.last_gps_accuracy[devicename] = 0 self.stat_zone_timer[devicename] = 0 @@ -5664,13 +5924,17 @@ def _initialize_usage_counters(self, devicename, clear_counters=True): self.time_waze_calls[devicename] = 0.0 #-------------------------------------------------------------------- def _define_iosapp_message_fields(self): - self.iosapp_locate_update_secs = {} - self.iosapp_locate_request_cnt = {} + self.iosapp_request_loc_sent_flag = {} + self.iosapp_request_loc_sent_secs = {} + self.iosapp_request_loc_cnt = {} + self.iosapp_request_loc_retry_cnt = {} #-------------------------------------------------------------------- def _initialize_iosapp_message_fields(self, devicename): - self.iosapp_locate_update_secs[devicename] = 0 - self.iosapp_locate_request_cnt[devicename] = 0 + self.iosapp_request_loc_sent_flag[devicename] = False + self.iosapp_request_loc_sent_secs[devicename] = 0 + self.iosapp_request_loc_cnt[devicename] = 0 + self.iosapp_request_loc_retry_cnt[devicename] = 0 #-------------------------------------------------------------------- def _initialize_next_update_time(self, devicename): @@ -5691,6 +5955,20 @@ def _define_sensor_fields(self, initial_load_flag): self.sensor_prefix_name = {} self.sensor_attr_fname_prefix = {} +#-------------------------------------------------------------------- + def _define_zone_fields(self): + ''' + Dictionary fields for zone friendly names + ''' + self.zones = [] + self.zone_to_display= dict(ZONE_TO_DISPLAY_BASE) + self.state_to_zone = dict(STATE_TO_ZONE_BASE) + self.zone_lat = {} + self.zone_long = {} + self.zone_radius_km = {} + self.zone_radius_m = {} + self.zone_passive = {} + #-------------------------------------------------------------------- def _define_device_zone_fields(self): ''' @@ -5759,7 +6037,7 @@ def _initialize_device_zone_fields(self, devicename): self.stat_zone_devicename_icon[icon_name] = devicename stat_zone_name = self._format_zone_name(devicename, STATIONARY) - self.zone_fname[stat_zone_name] = "Stationary" + self.zone_to_display[stat_zone_name] = "Stationary" except Exception as err: _LOGGER.exception(err) @@ -5823,11 +6101,11 @@ def _initialize_attrs(self, devicename): attrs[ATTR_TIMESTAMP] = dt_util.utcnow().isoformat()[0:19] attrs[ATTR_AUTHENTICATED] = '' attrs[ATTR_BATTERY] = 0 - attrs[ATTR_BATTERY_STATUS] = '' + attrs[ATTR_BATTERY_STATUS] = UNKNOWN attrs[ATTR_INFO] = "● HA is initializing dev_trk attributes ●" attrs[ATTR_ALTITUDE] = 0 attrs[ATTR_VERT_ACCURACY] = 0 - attrs[ATTR_DEVICE_STATUS] = '' + attrs[ATTR_DEVICE_STATUS] = UNKNOWN attrs[ATTR_LOW_POWER_MODE] = '' attrs[CONF_GROUP] = self.group attrs[ATTR_PICTURE] = self.badge_picture.get(devicename) @@ -5841,13 +6119,6 @@ def _initialize_zone_tables(self): ''' Get friendly name of all zones to set the device_tracker state ''' - self.zones = [] - self.zone_fname = {"not_home": "Away", "near_zone": "NearZone"} - self.zone_lat = {} - self.zone_long = {} - self.zone_radius_km = {} - self.zone_radius_m = {} - self.zone_passive = {} try: if self.start_icloud3_initial_load_flag == False: @@ -5870,7 +6141,7 @@ def _initialize_zone_tables(self): self._log_debug_msg("*",f"zone-{zone_name}, data-{zone_data}") if instr(zone_name.lower(), STATIONARY): - self.zone_fname[zone_name] = 'Stationary' + self.zone_to_display[zone_name] = 'Stationary' if ATTR_LATITUDE in zone_data: self.zone_lat[zone_name] = zone_data.get(ATTR_LATITUDE, 0) @@ -5878,7 +6149,16 @@ def _initialize_zone_tables(self): self.zone_passive[zone_name] = zone_data.get('passive', True) self.zone_radius_m[zone_name] = int(zone_data.get(ATTR_RADIUS, 100)) self.zone_radius_km[zone_name] = round(self.zone_radius_m[zone_name]/1000, 4) - self.zone_fname[zone_name] = zone_data.get(ATTR_FRIENDLY_NAME, zone_name.title()) + + zone_fname = zone_data.get(ATTR_FRIENDLY_NAME, zone_name) + if self.display_zone_fname_flag: + self.zone_to_display[zone_name] = zone_fname + self.state_to_zone[zone_fname] = zone_name + else: + zone_name_title = zone_name.replace('_',' ').title().replace(' ', '') + self.zone_to_display[zone_name] = zone_name_title + self.state_to_zone[zone_fname] = zone_name + self.state_to_zone[zone_name_title] = zone_name else: log_msg = (f"Error loading zone {zone_name} > No data was returned from HA. " @@ -5892,7 +6172,7 @@ def _initialize_zone_tables(self): except Exception as err: _LOGGER.exception(err) - zone_msg = (f"{zone_msg}{zone_name}/{self.zone_fname.get(zone_name)} " + zone_msg = (f"{zone_msg}{zone_name}/{self.zone_to_display.get(zone_name)} " f"(r{self.zone_radius_m[zone_name]}m), ") log_msg = (f"Set up Zones > {zone_msg[:-2]}") @@ -5904,7 +6184,7 @@ def _initialize_zone_tables(self): self.zone_home_radius_m = self.zone_radius_m.get(HOME) self.base_zone = HOME - self.base_zone_name = self.zone_fname.get(HOME) + self.base_zone_name = self.zone_to_display.get(HOME) self.base_zone_lat = self.zone_lat.get(HOME) self.base_zone_long = self.zone_long.get(HOME) self.base_zone_radius_km = float(self.zone_radius_km.get(HOME)) @@ -6396,7 +6676,6 @@ def _verify_tracked_devices_for_famshr(self): self.api_device_devicename[device_content_name] = devicename self.api_device_devicename[devicename] = device_content_name - devicename_list_tracked += (f"CRLF• {devicename} ({device_content_name}/{device_type})") else: @@ -6485,7 +6764,7 @@ def _setup_tracked_devices_config_parm(self, config_parameter): self.device_type[devicename] = di[DI_DEVICE_TYPE] self.fname[devicename] = di[DI_NAME] self.badge_picture[devicename] = di[DI_BADGE_PICTURE] - self.devicename_iosapp_entity[devicename] = di[DI_IOSAPP_ENTITY] + self.devicename_iosapp_entity[devicename] = di[DI_IOSAPP_ENTITY] self.devicename_iosapp_suffix[devicename] = di[DI_IOSAPP_SUFFIX] self.track_from_zone[devicename] = di[DI_ZONES] @@ -6579,7 +6858,7 @@ def _decode_track_device_config_parms(self, track_device_line): items = parameters.split(',') for itemx in items: - item_entered = itemx.strip().replace(' ', '_', 99) + item_entered = itemx.strip().replace(' ', '_') item = item_entered.lower() if item == '': @@ -6588,7 +6867,7 @@ def _decode_track_device_config_parms(self, track_device_line): email = item elif instr(item, 'png') or instr(item, 'jpg'): badge_picture = item - elif item == 'iosappv1': + elif item in ['iosappv1', 'noiosapp']: iosapp_monitor_flag = False elif item.startswith("_"): dev_trk_iosapp_suffix = item @@ -6639,7 +6918,7 @@ def _setup_monitored_iosapp_entities(self, devicename, iosapp_entities, notify_d #and the sensor.xxxx_last_update_trigger entity for that device. - self.device_tracker_entity_ic3[devicename] = (f"device_tracker.{devicename}") + #self.device_tracker_entity_ic3[devicename] = (f"device_tracker.{devicename}") if (self.iosapp_monitor_dev_trk_flag.get(devicename) == False): self.device_tracker_entity_iosapp[devicename] = (f"device_tracker.{devicename}") self.notify_iosapp_entity[devicename] = (f"ios_{devicename}") @@ -6863,8 +7142,10 @@ def _setup_sensor_base_attrs(self, devicename): attr_prefix_fname = attr_prefix_fname.replace('Ip','-iP') attr_prefix_fname = attr_prefix_fname.replace('Iw','-iW') attr_prefix_fname = attr_prefix_fname.replace('--','-') + attr_prefix_fname = attr_prefix_fname.replace('-De-', '-de-') + if attr_prefix_fname.startswith('-'): attr_prefix_fname = attr_prefix_fname[1:] - self.sensor_attr_fname_prefix[devicename] = (f"{attr_prefix_fname}-") + self.sensor_attr_fname_prefix[devicename] = (f"{attr_prefix_fname} ") badge_attrs = {} badge_attrs['entity_picture'] = self.badge_picture.get(devicename) @@ -6923,7 +7204,15 @@ def _setup_sensors_custom_list(self, initial_load_flag): # DEVICE STATUS SUPPORT FUNCTIONS FOR GPS ACCURACY, OLD LOC DATA, ETC # ######################################################### - def _check_old_loc_poor_gps(self, devicename, timestamp_secs, gps_accuracy): + def _check_poor_location_gps_only(self, devicename, timestamp_secs, gps_accuracy): + poor_location_gps_flag, discard_reason = self._check_poor_location_gps( + devicename, + last_located_secs, + gps_accuracy, + checkOnly=True) + return poor_location_gps_flag + + def _check_poor_location_gps(self, devicename, timestamp_secs, gps_accuracy, checkOnly=False): """ If this is checked in the icloud location cycle, check if the location isold flag. Then check to see if @@ -6934,48 +7223,58 @@ def _check_old_loc_poor_gps(self, devicename, timestamp_secs, gps_accuracy): already updated the lat/long so you don't want to discard the record just because it is old. If in a zone, use the trigger but check the distance from the - zone when updating the device. If the distance from the zone = 0, - then reset the lat/long to the center of the zone. + zone when updating the device. + + Update the old_location_poor_gps_cnt if just_check=False """ try: - discard_reason = "" - age = int(self._secs_since(timestamp_secs)) - age_str = self._secs_to_time_str(age) - location_isold_flag = (age > self.old_location_secs.get(devicename)) - poor_gps_flag = (gps_accuracy > self.gps_accuracy_threshold) - - if location_isold_flag and poor_gps_flag: - discard_reason = (f"Old.Location-{age_str}, GPSAccuracy-{gps_accuracy}m") - elif location_isold_flag: - discard_reason = (f"Old.Location-{age_str}") + discard_reason = "" + location_age = int(self._secs_since(timestamp_secs)) + location_age_str = (f"{self._format_age(location_age)}") + old_location_flag = (location_age > self.old_location_secs.get(devicename)) + poor_gps_flag = (gps_accuracy > self.gps_accuracy_threshold) + + if self._is_inzone(devicename): + old_location_flag = False + poor_gps_flag = (poor_gps_flag \ + and self.ignore_gps_accuracy_inzone_flag == False) + + if old_location_flag and poor_gps_flag: + discard_reason = (f"OldLocation-{location_age_str}, GPSAccuracy-{gps_accuracy}m") + elif old_location_flag: + discard_reason = (f"OldLocation-{location_age_str}") elif poor_gps_flag: discard_reason = (f"GPSAccuracy-{gps_accuracy}m") - if location_isold_flag or poor_gps_flag: - self.old_loc_poor_gps_cnt[devicename] += 1 - discard_reason += (f" (#{self.old_loc_poor_gps_cnt.get(devicename)})") - else: - self.old_loc_poor_gps_cnt[devicename] = 0 + #Do not update status and count if just checking poor loc gps status + if checkOnly: + return (old_location_flag or poor_gps_flag) - self.poor_gps_accuracy_flag[devicename] = (location_isold_flag or poor_gps_flag) + if old_location_flag or poor_gps_flag: + self.poor_gps_flag[devicename] = True + self.poor_location_gps_cnt[devicename] += 1 + discard_reason += (f" (#{self.poor_location_gps_cnt.get(devicename)})") + else: + self.poor_gps_flag[devicename] = False + self.poor_location_gps_cnt[devicename] = 0 log_msg = (f"CHECK ISOLD/GPS ACCURACY, Time-{self._secs_to_time(timestamp_secs)}, " - f"isOldFlag-{location_isold_flag}, Age-{age_str}, " + f"isOldFlag-{old_location_flag}, Age-{location_age_str}, " f"GPSAccuracy-{gps_accuracy}m, GPSAccuracyFlag-{poor_gps_flag}", - f"Results-{self.poor_gps_accuracy_flag.get(devicename)}, " + f"Results-{self.poor_gps_flag.get(devicename)}, " f"DiscardReason-{discard_reason}") self._log_debug_msg(devicename, log_msg) except Exception as err: _LOGGER.exception(err) - self.poor_gps_accuracy_flag[devicename] = False - self.old_loc_poor_gps_cnt[devicename] = 0 + self.poor_gps_flag[devicename] = False + self.poor_location_gps_cnt[devicename] = 0 log_msg = ("►INTERNAL ERROR (ChkOldLocPoorGPS)") self._log_error_msg(log_msg) - return (self.poor_gps_accuracy_flag.get(devicename), discard_reason) + return (self.poor_gps_flag.get(devicename), discard_reason) #-------------------------------------------------------------------- def _check_next_update_time_reached(self, devicename=None): @@ -6983,6 +7282,9 @@ def _check_next_update_time_reached(self, devicename=None): Cycle through the next_update_secs for all devices and determine if one of them is earlier than the current time. If so, the devices need to be updated. + + Return None - Next update time has not been reached on any devicename:zone + devicename - devicename of phone that needs to be updated ''' try: if self.next_update_secs is None: @@ -7004,6 +7306,32 @@ def _check_next_update_time_reached(self, devicename=None): return None +#-------------------------------------------------------------------- + def _check_next_update_time_reached_devicename(self, devicename): + ''' + Cycle through the next_update_secs for this devicename and + determine if one of them is earlier than the current time. + If so, the devicename need to be updated. + + Return True - Reached next_update_secs, update devicename + False - Do not update devicename + ''' + try: + if self.next_update_secs is None: + return False + + for devicename_zone in self.next_update_secs: + if devicename_zone.startswith(devicename): + time_till_update = self.next_update_secs.get(devicename_zone) - \ + self.this_update_secs + + if time_till_update <= 5: + return True + + except Exception as err: + _LOGGER.exception(err) + + return False #-------------------------------------------------------------------- def _check_in_zone_and_before_next_update(self, devicename): ''' @@ -7024,12 +7352,16 @@ def _check_in_zone_and_before_next_update(self, devicename): return False #-------------------------------------------------------------------- - def _check_outside_zone_no_exit(self,devicename, zone, latitude, longitude): + def _check_outside_zone_no_exit(self,devicename, zone, trigger, latitude, longitude): ''' If the device is outside of the zone and less than the zone radius + gps_acuracy_threshold and no Geographic Zone Exit trigger was received, it has probably wandered due to GPS errors. If so, discard the poll and try again later ''' + trigger = self.trigger.get(devicename) if trigger == '' else trigger + if trigger in IOS_TRIGGERS_ENTER: + return False, '' + dist_from_zone_m = self._zone_distance_m( devicename, zone, @@ -7046,7 +7378,7 @@ def _check_outside_zone_no_exit(self,devicename, zone, latitude, longitude): and self.got_exit_trigger_flag.get(devicename) == False and instr(zone, STATIONARY) == False): if dist_from_zone_m < zone_radius_accuracy_m: - self.poor_gps_accuracy_flag[devicename] = True + self.poor_gps_flag[devicename] = True msg = ("Outside Zone and No Exit Zone trigger, " f"Keeping in zone > Zone-{zone}, " @@ -7061,30 +7393,59 @@ def _check_outside_zone_no_exit(self,devicename, zone, latitude, longitude): return False, '' #-------------------------------------------------------------------- - #@staticmethod - def _get_interval_for_error_retry_cnt(self, retry_cnt): - cycle, cycle_cnt = divmod(retry_cnt, 4) + def _get_interval_for_error_retry_cnt(self, devicename, counter=POOR_LOC_GPS_CNT): + ''' + Get the interval time based on the retry_cnt. + retry_cnt = -1 - Use the poor_location_gps count for devicename + = iosapp_request_loc_sent_retry_cnt + = retry pyicloud authorization count - if cycle == 0: - interval = 15 - elif cycle == 1: - interval = 60 #1 min - elif cycle == 2: - interval = 300 #5 min - elif cycle == 3: - interval = 900 #15 min + Interval range table - key = retry_cnt, value = time in minutes + - poor_location_gps cnt, icloud_authentication cnt (default): + interval_range_1 = {0:.25, 4:1, 8:5, 12:30, 16:60, 20:120, 24:240} + - request iosapp location retry cnt: + interval_range_2 = {0:.5, 4:2, 8:30, 12:60, 16:120} + + ''' + if counter == POOR_LOC_GPS_CNT: + retry_cnt = self.poor_location_gps_cnt.get(devicename, 0) + range_tbl = RETRY_INTERVAL_RANGE_1 + + elif counter == AUTH_ERROR_CNT: + retry_cnt = self.icloud_acct_auth_error_cnt + range_tbl = RETRY_INTERVAL_RANGE_1 + + elif counter == IOSAPP_REQUEST_LOC_CNT: + retry_cnt = self.iosapp_request_loc_retry_cnt.get(devicename) + range_tbl = RETRY_INTERVAL_RANGE_2 else: - interval = 1800 #30 min + return 60 + + interval = .25 + for k, v in range_tbl.items(): + if k <= retry_cnt: + interval = v + + interval = interval * 60 return interval #-------------------------------------------------------------------- def _display_time_till_update_info_msg(self, devicename_zone, age_secs): - info_msg = (f"● {self._secs_to_minsec_str(age_secs)} ●") + ''' + Display the secs until the next update in the next update time field. + if between 90s to -90s. if between -90s and -120s, resisplay time + without the age to make sure it goes away. + ''' - attrs = {} - attrs[ATTR_NEXT_UPDATE_TIME] = info_msg + info_msg=(f"{self.next_update_time.get(devicename_zone)} ") + if age_secs <= 90 and age_secs >= -90: + info_msg += (f"({age_secs}s)") - self._update_device_sensors(devicename_zone, attrs) + if age_secs <= 90 and age_secs > -120: + attrs = {} + attrs[ATTR_NEXT_UPDATE_TIME] = info_msg + + self._update_device_sensors(devicename_zone, attrs) #-------------------------------------------------------------------- def _log_device_status_attrubutes(self, status): @@ -7180,6 +7541,8 @@ def _setup_event_log_base_attrs(self, initial_load_flag): if len(self.tracked_devices) > 0: self.log_table_max_items = EVLOG_RECDS_PER_DEVICE * len(self.tracked_devices) + if len(self.track_from_zone.get(devicename)) > 1: + self.log_table_max_items = .25 * self.log_table_max_items * len(self.track_from_zone.get(devicename)) base_attrs["names"] = name_attrs @@ -7228,18 +7591,24 @@ def _save_event(self, devicename, event_text): else: iosapp_state= self.last_iosapp_state.get(devicename, '') - zone_names = self._get_zone_names(self.zone_current.get(devicename, '')) - zone = zone_names[1][:12] if zone_names != '' else '' + zone = self.zone_current.get(devicename, AWAY) interval = self.interval_str.get(devicename_zone, '').split("(")[0] travel_time = self.last_tavel_time.get(devicename_zone, '') distance = self.last_distance_str.get(devicename_zone, '') if (instr(type(event_text), 'dict') or instr(type(event_text), 'list')): event_text = str(event_text) - if instr(iosapp_state, STATIONARY): iosapp_state = STATIONARY + if instr(zone, STATIONARY): zone = STATIONARY - if len(event_text) == 0: event_text = 'Info Message' + if instr(iosapp_state, STATIONARY): iosapp_state = STATIONARY + iosapp_state = self.zone_to_display.get(iosapp_state, iosapp_state.title()) + zone = self.zone_to_display.get(zone, zone.title()) + + if iosapp_state == None: iosapp_state = '' + if zone == None: zone = '' + + if len(event_text) == 0: event_text = 'Info Message' if event_text.startswith('__'): event_text = event_text[2:] event_text = event_text.replace('"', '`') event_text = event_text.replace("'", "`") @@ -7260,7 +7629,7 @@ def _save_event(self, devicename, event_text): if event_text.startswith('*'): color_symbol = '*' if event_text.startswith('**'): color_symbol = '**' if event_text.startswith('***'): color_symbol = '***' - if instr(event_text, 'Error'): color_symbol = '!' + if instr(event_text, ERROR): color_symbol = '!' char_per_line = 2000 #Break the event_text string into chunks of 250 characters each and @@ -7520,7 +7889,7 @@ def _get_waze_data(self, devicename, self._log_error_msg(log_msg) waze_time_msg = self._format_waze_time_msg(waze_time_from_zone) - event_msg = (f"Waze Route Info: {self.zone_fname.get(self.base_zone)} > " + event_msg = (f"Waze Route Info: {self.zone_to_display.get(self.base_zone)} > " f"Dist-{waze_dist_from_zone_km}km, " f"TravTime-{waze_time_msg}, " f"DistMovedSinceLastUpdate-{waze_dist_last_poll}km") @@ -7530,7 +7899,8 @@ def _get_waze_data(self, devicename, f"Status-{waze_status}, DistFromHome-{waze_dist_from_zone_km}, " f"TimeFromHome-{waze_time_from_zone}, " f"DistLastPoll-{waze_dist_last_poll}, " - f"WazeFromHome-{waze_from_zone}, WazeFromLastPoll-{waze_from_last_poll}") + f"WazeFromHome-{waze_from_zone}, " + f"WazeFromLastPoll-{waze_from_last_poll}") self._log_debug_interval_msg(devicename, log_msg) return (waze_status, waze_dist_from_zone_km, waze_time_from_zone, @@ -7673,7 +8043,7 @@ def _get_waze_from_data_history(self, devicename, #Return the waze history data for the other closest device if used_data_from_devicename_zone is not None: used_devicename = used_data_from_devicename_zone.split(':')[0] - event_msg = (f"Waze Route History Used: {self.zone_fname.get(self.base_zone)} > " + event_msg = (f"Waze Route History Used: {self.zone_to_display.get(self.base_zone)} > " f"Dist-{other_closest_device_data[1]}km, " f"TravTime-{round(other_closest_device_data[2], 0)} min, " f"UsedInfoFrom-{self._format_fname_devicename(used_devicename)}, " @@ -7799,11 +8169,16 @@ def _check_config_ic3_yaml_parameter_file(self): and os.path.exists(self.config_ic3_file_name)): config_filename = self.config_ic3_file_name + elif os.path.exists(f"/config/{self.config_ic3_file_name}"): + config_filename = (f"/config/{self.config_ic3_file_name}") + elif os.path.exists(f"{ic3_directory}/{self.config_ic3_file_name}"): config_filename = (f"{ic3_directory}/{self.config_ic3_file_name}") - elif os.path.exists(f"/config/{self.config_ic3_file_name}"): - config_filename = (f"/config/{self.config_ic3_file_name}") + alert_msg = (f"{EVLOG_ALERT}iCloud3 Alert > The `config_ic3.yaml` " + f"configuration file should moved to the `/config` " + f"directory so it is not deleted when HACS updates iCloud3") + self._save_event("*", alert_msg) else: event_msg += "Error-File Not Found" @@ -7912,21 +8287,25 @@ def _set_parameter_item(self, parameter_name, parameter_value): return ("", "") - log_msg = (f"config_ic3 Updating parameter-{parameter_name}: {parameter_value}") - self._log_debug_msg("*", log_msg) + log_msg = (f"{EVLOG_DEBUG}config_ic3 Parameter > {parameter_name}: {parameter_value}") + self._save_event("*", log_msg) if parameter_name in [CONF_TRACK_DEVICES, CONF_TRACK_DEVICE]: self.track_devices = parameter_value - elif parameter_name == CONF_IOSAPP_LOCATE_REQUEST_MAX_CNT: - self.iosapp_locate_request_max_cnt = int(parameter_value) + elif parameter_name == CONF_IOSAPP_REQUEST_LOC_MAX_CNT: + self.iosapp_request_loc_max_cnt = int(parameter_value) elif parameter_name == CONF_UNIT_OF_MEASUREMENT: self.unit_of_measurement = parameter_value + elif parameter_name == CONF_TIME_FORMAT: + self.time_format = int(parameter_value) elif parameter_name == CONF_BASE_ZONE: self.base_zone = parameter_value elif parameter_name == CONF_INZONE_INTERVAL: self.inzone_interval_secs = self._time_str_to_secs(parameter_value) elif parameter_name == CONF_MAX_INTERVAL: self.max_interval_secs = self._time_str_to_secs(parameter_value) + elif parameter_name == CONF_DISPLAY_ZONE_FNAME: + self.display_zone_fname_flag = (parameter_value == 'true') elif parameter_name == CONF_CENTER_IN_ZONE: self.center_in_zone_flag = (parameter_value == 'true') elif parameter_name == CONF_STATIONARY_STILL_TIME: @@ -7959,7 +8338,8 @@ def _set_parameter_item(self, parameter_name, parameter_value): elif parameter_name == CONF_EVENT_LOG_CARD_DIRECTORY: self.event_log_card_directory = parameter_value elif parameter_name == CONF_DEVICE_STATUS: - self.device_status_online = parameter_value + self.device_status_online = list(parameter_value.replace(" ","").split(",")) + self.device_status_online.append('') elif parameter_name == CONF_DISPLAY_TEXT_AS: self.display_text_as = parameter_value else: @@ -8013,7 +8393,7 @@ def _check_ic3_event_log_file_version(self): www_version, www_version_text = self._read_event_log_card_js_file(www_evlog_filename) else: www_version = 0 - www_version_text = "Unknown" + www_version_text = UNKNOWN try: os.mkdir(www_directory) except FileExistsError: @@ -8069,7 +8449,7 @@ def _read_event_log_card_js_file(self, evlog_filename): ''' try: #Cycle thru the file looking for the Version - evlog_version_text = "Unknown" + evlog_version_text = UNKNOWN evlog_version_no = 0 evlog_file = open(evlog_filename) evlog_version_parts = [0, 0, 0] @@ -8101,7 +8481,7 @@ def _read_event_log_card_js_file(self, evlog_filename): except FileNotFoundError: evlog_version_no = 0 - evlog_version_text = "Unknown" + evlog_version_text = UNKNOWN return (evlog_version_no, evlog_version_text) except Exception as err: @@ -8223,11 +8603,11 @@ def _log_debug_msg2(self, log_msg): _LOGGER.debug(log_msg) #-------------------------------------- - @staticmethod - def _internal_error_msg(function_name, err_text: str='', + def _internal_error_msg(self, function_name, err_text: str='', section_name: str=''): log_msg = (f"►INTERNAL ERROR-RETRYING ({function_name}:{section_name}-{err_text})") _LOGGER.error(log_msg) + self._save_event("*", log_msg) attrs = {} attrs[ATTR_INTERVAL] = '0 sec' @@ -8246,18 +8626,16 @@ def _time_now_secs(): ''' Return the epoch seconds in utc time ''' return int(time.time()) + #-------------------------------------------------------------------- - def _secs_to_time(self, e_seconds, time_24h = False): + def _secs_to_time(self, e_seconds): """ Convert seconds to hh:mm:ss """ if e_seconds == 0 or e_seconds == HIGH_INTEGER: return HHMMSS_ZERO else: t_struct = time.localtime(e_seconds + self.e_seconds_local_offset_secs) - if time_24h: - return time.strftime("%H:%M:%S", t_struct).lstrip('0') - else: - return time.strftime(self.um_time_strfmt, t_struct).lstrip('0') + return time.strftime(self.um_time_strfmt, t_struct).lstrip('0') #-------------------------------------------------------------------- @staticmethod @@ -8265,7 +8643,9 @@ def _secs_to_time_str(secs): """ Create the time string from seconds """ try: - if secs < 60: + if secs >= 86400: + time_str = self._secs_to_dhms_str(secs) + elif secs < 60: time_str = str(round(secs, 0)) + " sec" elif secs < 3600: time_str = str(round(secs/60, 1)) + " min" @@ -8283,19 +8663,20 @@ def _secs_to_time_str(secs): return time_str #-------------------------------------------------------------------- @staticmethod - def _secs_to_minsec_str(secs): + def _secs_to_dhms_str(secs): """ Create the time 0d0h0m0s time string from seconds """ try: secs_dhms = float(secs) dhms_str = "" - if (secs > 86400): dhms_str += f"{secs_dhms // 86400}d" + if (secs >= 86400): dhms_str += f"{secs_dhms // 86400}d" secs_dhms = secs_dhms % 86400 - if (secs > 3600): dhms_str += f"{secs_dhms // 3600}h" + if (secs >= 3600): dhms_str += f"{secs_dhms // 3600}h" secs_dhms %= 3600 - if (secs > 60): dhms_str += f"{secs_dhms // 60}m" + if (secs >= 60): dhms_str += f"{secs_dhms // 60}m" secs_dhms %= 60 dhms_str += f"{secs_dhms}s" + dhms_str = dhms_str.replace('.0', '') except: @@ -8323,10 +8704,11 @@ def _time_to_secs(hhmmss): return secs #-------------------------------------------------------------------- - def _time_to_12hrtime(self, hhmmss, time_24h=False, ampm=False): + def _time_to_12hrtime(self, hhmmss, ampm=False): try: - if self.unit_of_measurement == 'mi' and time_24h is False: + #if self.unit_of_measurement == 'mi' and time_24h is False: + if self.time_format == 12: hh_mm_ss = hhmmss.split(':') hhmmss_hh = int(hh_mm_ss[0]) @@ -8391,12 +8773,11 @@ def _timestamp_to_time_utcsecs(self, utc_timestamp) -> int: return hhmmss #-------------------------------------------------------------------- - def _timestamp_to_time(self, timestamp, time_24h = False): + def _timestamp_to_time(self, timestamp): """ Extract the time from the device timeStamp attribute updated by the IOS app. Format is --'timestamp': '2019-02-02 12:12:38.358-0500' - Return as a 24hour time if time_24h = True """ try: @@ -8509,24 +8890,23 @@ def _km_to_mi(self, arg_distance): """ try: - arg_distance = arg_distance * self.um_km_mi_factor + mi = arg_distance * self.um_km_mi_factor - if arg_distance == 0: + if mi == 0: mi = 0 - elif arg_distance <= 10: - mi = round(arg_distance, 2) - elif arg_distance <= 100: - mi = round(arg_distance, 1) + elif mi <= 10: + mi = round(mi, 2) + elif mi <= 100: + mi = round(mi, 1) else: - mi = round(arg_distance) + mi = round(mi) except: mi = 0 - return mi def _mi_to_km(self, arg_distance): - return round(float(arg_distance) / self.um_km_mi_factor, 2) + return round(float(arg_distance) / self.um_km_mi_factor, 2) #-------------------------------------------------------------------- @staticmethod @@ -8580,7 +8960,6 @@ def _isnumber(string): return False #-------------------------------------------------------------------- - def _extract_name_device_type(self, devicename): '''Extract the name and device type from the devicename''' @@ -8601,6 +8980,14 @@ def _extract_name_device_type(self, devicename): return (fname, "iCloud") +#-------------------------------------------------------------------- + def _device_online(self, devicename): + ''' Returns True/False if the device is online based on the device_status ''' + if self.TRK_METHOD_IOSAPP: + return True + else: + return (self.device_status.get(devicename) in self.device_status_online) #["online", "pending", ""]) + ######################################################### # # These functions handle notification and entry of the @@ -8610,6 +8997,9 @@ def _extract_name_device_type(self, devicename): def _icloud_show_trusted_device_request_form(self): """We need a trusted device.""" + if self._icloud_valid_api() == False: + return + self._service_handler_icloud_update(self.group, arg_command='pause') configurator = self.hass.components.configurator @@ -8662,13 +9052,17 @@ def _icloud_handle_trusted_device_entry(self, callback_data): {'deviceType': 'SMS', 'areaCode': '', 'phoneNumber': '********66', 'deviceId': '2'}] """ + + if self._icloud_valid_api() == False: + return + device_id_entered = str(callback_data.get('trusted_device')) if device_id_entered in self.trusted_device_list: self.trusted_device = self.trusted_device_list.get(device_id_entered) phone_number = self.trusted_device.get('phoneNumber') event_msg = (f"Verify Trusted Device Id > Device Id Entered-{device_id_entered}, " - f"Phone Number-{phone_number}") + f"Phone Number-{phone_number}") self._save_event("*", event_msg) if self.username not in self.hass_configurator_request_id: @@ -8719,6 +9113,9 @@ def _icloud_show_verification_code_entry_form(self, invalid_code_msg=""): def _icloud_handle_verification_code_entry(self, callback_data): """Handle the chosen trusted device.""" + if self._icloud_valid_api() == False: + return + from .pyicloud_ic3 import PyiCloudException self.verification_code = callback_data.get('code') event_msg = (f"Submit Verification Code > Code-{callback_data}") @@ -8735,6 +9132,7 @@ def _icloud_handle_verification_code_entry(self, callback_data): self._save_event("*", event_msg) except PyiCloudException as error: + # Reset to the initial 2FA state to allow the user to retry event_msg = (f"Failed to verify account > Error-{error}") self._save_event_halog_error("*", event_msg) @@ -8752,38 +9150,39 @@ def _icloud_handle_verification_code_entry(self, callback_data): configurator.request_done(request_id) self._setup_tracking_method(self.tracking_method_config) - event_msg = (f"{EVLOG_ALERT}iCloud Alert > iCloud Account Verification completed, {self.tracking_method_config}" - f"{self.trk_method_short_name} will be used.") + event_msg = (f"{EVLOG_ALERT}iCloud Alert > iCloud Account Verification completed, " + f"{self.trk_method_short_name} ({self.tracking_method_config}) will be used.") self._save_event("*", event_msg) - self._service_handler_icloud_update(self.group, arg_command='resume') + self._start_icloud3() + #self._service_handler_icloud_update(self.group, arg_command='resume') + +#-------------------------------------------------------------------- + def _icloud_valid_api(self): + ''' + Make sure the pyicloud_ic3 api is valid + ''' + + if self.api == None: + event_msg = (f"{EVLOG_ERROR}iCloud3 Error > There was an error logging into the " + f"Apple/iCloud Account when iCloud3 was started. Verification can not " + f"be completed. Review the iCloud3 Event Log for more information.") + self._save_event_halog_error('*', event_msg) + return False + return True ######################################################### # # ICLOUD ROUTINES # ######################################################### - def _service_handler_lost_iphone(self, group, arg_devicename): + def _service_handler_lost_iphone(self, group, devicename): """Call the lost iPhone function if the device is found.""" - if self.TRK_METHOD_FAMSHR is False: - log_msg = ("Lost Phone Alert Error: Alerts can only be sent " - "when using tracking_method FamShr") - self._log_warning_msg(log_msg) - self.info_notification = log_msg - self._display_status_info_msg(arg_devicename, log_msg) - return - - valid_devicename = self._service_multi_acct_devicename_check( - "Lost iPhone Service", group, arg_devicename) - if valid_devicename is False: - return - - device = self.tracked_devices.get(arg_devicename) - device.play_sound() - - log_msg = (f"iCloud Lost iPhone Alert, Device {arg_devicename}") - self._log_info_msg(log_msg) - self._display_status_info_msg(arg_devicename, "Lost Phone Alert sent") + lost_message = ("This phone has been identified as lost. " + "Please contact the owner with it's location.") + message = {"title": "Lost Phone Notification", + "message": lost_message} + self._send_message_to_device(devicename, message) #-------------------------------------------------------------------- def _service_handler_icloud_update(self, group, arg_devicename=None, @@ -8817,13 +9216,6 @@ def _service_handler_icloud_update(self, group, arg_devicename=None, log_msg = (f"iCLOUD3 COMMAND, Device: `{arg_devicename}`, Command: `{arg_command}`") self._log_debug_msg("*", log_msg) - if (arg_devicename and arg_devicename != "startup_log"): - if (arg_devicename != 'restart'): - valid_devicename = self._service_multi_acct_devicename_check( - "Update iCloud Service", group, arg_devicename) - if valid_devicename is False: - return - self._evlog_debug_msg(arg_devicename, (f"Service Call Command Received > `{arg_command}`")) arg_command = (f"{arg_command} ") @@ -8946,7 +9338,7 @@ def _service_handler_icloud_update(self, group, arg_devicename=None, attrs = {} self._wait_if_update_in_process(arg_devicename) - self.overrideinterval_seconds[arg_devicename] = 0 + self.override_interval_seconds[arg_devicename] = 0 self.update_in_process_flag = False self._initialize_next_update_time(arg_devicename) @@ -8976,13 +9368,13 @@ def _service_handler_icloud_update(self, group, arg_devicename=None, cmd_type = CMD_PAUSE self.next_update_secs[devicename_zone] = HIGH_INTEGER self.next_update_time[devicename_zone] = PAUSED - self._display_info_status_msg(devicename, 'PAUSED') + self._display_info_status_msg(devicename, PAUSED_CAPS) elif arg_command_cmd == 'resume': cmd_type = CMD_RESUME self.next_update_time[devicename_zone] = HHMMSS_ZERO self.next_update_secs[devicename_zone] = 0 - self.overrideinterval_seconds[devicename] = 0 + self.override_interval_seconds[devicename] = 0 self._display_info_status_msg(devicename, 'RESUMING') self._update_device_icloud('Resuming', devicename) @@ -8993,7 +9385,7 @@ def _service_handler_icloud_update(self, group, arg_devicename=None, self.next_update_secs[devicename_zone] = 0 attrs[ATTR_NEXT_UPDATE_TIME] = HHMMSS_ZERO attrs[ATTR_WAZE_DISTANCE] = 'Resuming' - self.overrideinterval_seconds[devicename] = 0 + self.override_interval_seconds[devicename] = 0 self._update_device_sensors(devicename, attrs) attrs = {} @@ -9002,8 +9394,16 @@ def _service_handler_icloud_update(self, group, arg_devicename=None, attrs[ATTR_WAZE_DISTANCE] = PAUSED attrs[ATTR_WAZE_TIME] = '' - elif arg_command_cmd == ATTR_LOCATION: - self._request_iosapp_location_update(devicename) + elif arg_command_cmd == 'location': + cmd_type = CMD_LOCATION + self._display_info_status_msg(devicename, 'locating') + if self.iosapp_monitor_dev_trk_flag.get(devicename): + self._iosapp_request_loc_update(devicename) + else: + self.next_update_time[devicename_zone] = HHMMSS_ZERO + self.next_update_secs[devicename_zone] = 0 + self.override_interval_seconds[devicename] = 0 + self._update_device_icloud('Locating', devicename) self._update_sensor_ic3_event_log(devicename) else: @@ -9040,19 +9440,13 @@ def _service_handler_icloud_setinterval(self, group, arg_interval=None, #device. if arg_devicename and self.TRK_METHOD_IOSAPP: - if self.iosapp_locate_request_cnt.get(arg_devicename) > self.iosapp_locate_request_max_cnt: + if self.iosapp_request_loc_cnt.get(arg_devicename) > self.iosapp_request_loc_max_cnt: event_msg = (f"Can not Set Interval, location request cnt " - f"exceeded ({self.iosapp_locate_request_cnt.get(arg_devicename)} " - f"of { self.iosapp_locate_request_max_cnt})") + f"exceeded ({self.iosapp_request_location_cnt.get(arg_devicename)} " + f"of {self.iosapp_request_loc_max_cnt})") self._save_event(arg_devicename, event_msg) return - elif arg_devicename: - valid_devicename = self._service_multi_acct_devicename_check( - "Update Interval Service", group, arg_devicename) - if valid_devicename is False: - return - if arg_interval is None: if arg_devicename is not None: self._save_event(arg_devicename, "Set Interval Command Error, " @@ -9085,7 +9479,7 @@ def _service_handler_icloud_setinterval(self, group, arg_interval=None, self.next_update_time[devicename_zone] = HHMMSS_ZERO self.next_update_secs[devicename_zone] = 0 self.interval_str[devicename_zone] = new_interval - self.overrideinterval_seconds[devicename] = self._time_str_to_secs(new_interval) + self.override_interval_seconds[devicename] = self._time_str_to_secs(new_interval) now_seconds = self._time_to_secs(dt_util.now().strftime('%X')) x, update_in_secs = divmod(now_seconds, 15) @@ -9096,22 +9490,5 @@ def _service_handler_icloud_setinterval(self, group, arg_interval=None, log_msg = (f"SET INTERVAL COMMAND END {devicename}") self._log_debug_msg(devicename, log_msg) -#-------------------------------------------------------------------- - def _service_multi_acct_devicename_check(self, svc_call_name, - group, arg_devicename): - if arg_devicename is None: - log_msg = (f"{svc_call_name} Error, no devicename specified") - self._log_error_msg(log_msg) - return False - - info_msg = (f"Checking {svc_call_name} for {group}") - - if (arg_devicename not in self.track_devicename_list): - event_msg = (f"{info_msg}, {arg_devicename} not in this group") - self._log_info_msg(event_msg) - return False - - event_msg = (f"{info_msg}-{arg_devicename} Processed") - return True #-------------------------------------------------------------------- diff --git a/custom_components/icloud3/icloud3-event-log-card.js b/custom_components/icloud3/icloud3-event-log-card.js index 1f976da..3acebd7 100644 --- a/custom_components/icloud3/icloud3-event-log-card.js +++ b/custom_components/icloud3/icloud3-event-log-card.js @@ -12,247 +12,293 @@ // If they do not match, the one in the 'custom_components\icloud3' is copied // to the 'www\custom_cards' directory. // -// Version=2.2.0.10 (10/4/2020) +// Version=2.2.1.02 (11/01/2020) // ///////////////////////////////////////////////////////////////////////////// class iCloud3EventLogCard extends HTMLElement { constructor() { - super(); - this.attachShadow({ mode: 'open' }); + super() + this.attachShadow({ mode: 'open' }) } //--------------------------------------------------------------------------- setConfig(config) { - const version = "2.2.0.10" + const version = "2.2.1.02" const cardTitle = "iCloud3 Event Log" - const root = this.shadowRoot; - const hass = this._hass; + const root = this.shadowRoot + const hass = this._hass // Create card elements - const card = document.createElement('ha-card'); - const background = document.createElement('div'); - background.id = "background"; + const card = document.createElement('ha-card') + const background = document.createElement('div') + background.id = "background" // Title Bar - const titleBar = document.createElement("div"); - titleBar.id = "titleBar"; - const title = document.createElement("div"); - title.id = "title"; + const titleBar = document.createElement("div") + titleBar.id = "titleBar" + const title = document.createElement("div") + title.id = "title" title.textContent = cardTitle - const utilityBar = document.createElement("div"); - utilityBar.id = "utilityBar"; - const thisButtonId = document.createElement("div"); - thisButtonId.id = "thisButtonId"; - thisButtonId.classList.add("themeTextColor"); - thisButtonId.innerText = "setup"; - const logRecdCnt = document.createElement("div"); - logRecdCnt.id = "logRecdCnt"; - logRecdCnt.innerText = "-1"; - const devType = document.createElement("div"); - devType.id = "devType"; - devType.innerText = ""; - const hdrCellWidth = document.createElement("div"); - hdrCellWidth.id = "hdrCellWidth"; - hdrCellWidth.innerText = "0,66.7px,97.8px,94.4px,80px,70px,66.7px"; - const versionText = document.createElement("div"); - versionText.id = "versionText"; - versionText.style.setProperty('visibility', 'hidden'); - versionText.textContent = 'v' + version + //Utility base contains hidden variables + const utilityBar = document.createElement("div") + utilityBar.id = "utilityBar" + const thisButtonId = document.createElement("div") + thisButtonId.id = "thisButtonId" + thisButtonId.classList.add("themeTextColor") + thisButtonId.innerText = "setup" + const logRecdCnt = document.createElement("div") + logRecdCnt.id = "logRecdCnt" + logRecdCnt.innerText = "-1" + const devType = document.createElement("div") + devType.id = "devType" + devType.innerText = "" + const hdrCellWidth = document.createElement("div") + hdrCellWidth.id = "hdrCellWidth" + hdrCellWidth.innerText = "0,66.7px,97.8px,94.4px,80px,70px,66.7px" + const versionText = document.createElement("div") + versionText.id = "versionText" + versionText.innerText = version + + const infoText = document.createElement("div") + infoText.id = "infoText" + infoText.innerText = '' // Button Bar - const buttonBar = document.createElement("div"); - buttonBar.id = "buttonBar"; - buttonBar.class = "buttonBar"; + const buttonBar = document.createElement("div") + buttonBar.id = "buttonBar" + buttonBar.class = "buttonBar" // Name Buttons - const btnName0 = document.createElement('btnName'); - btnName0.id = "btnName0"; - btnName0.classList.add("btnBaseFormat"); - btnName0.style.setProperty('visibility', 'visible'); - btnName0.innerText = "Setup"; - const btnName1 = document.createElement('btnName'); - btnName1.id = "btnName1"; - btnName1.classList.add("btnBaseFormat"); - btnName1.classList.add("btnHidden"); - const btnName2 = document.createElement('btnName'); - btnName2.id = "btnName2"; - btnName2.classList.add("btnBaseFormat"); - btnName2.classList.add("btnHidden"); - const btnName3 = document.createElement('btnName'); - btnName3.id = "btnName3"; - btnName3.classList.add("btnBaseFormat"); - btnName3.classList.add("btnHidden"); - const btnName4 = document.createElement('btnName'); - btnName4.id = "btnName4"; - btnName4.classList.add("btnBaseFormat"); - btnName4.classList.add("btnHidden"); - const btnName5 = document.createElement('btnName'); - btnName5.id = "btnName5"; - btnName5.classList.add("btnBaseFormat"); - btnName5.classList.add("btnHidden"); - const btnName6 = document.createElement('btnName'); - btnName6.id = "btnName6"; - btnName6.classList.add("btnBaseFormat"); - btnName6.classList.add("btnHidden"); - const btnName7 = document.createElement('btnName'); - btnName7.id = "btnName7"; - btnName7.classList.add("btnBaseFormat"); - btnName7.classList.add("btnHidden"); - const btnName8 = document.createElement('btnName'); - btnName8.id = "btnName8"; - btnName8.classList.add("btnBaseFormat"); - btnName8.classList.add("btnHidden"); - const btnName9 = document.createElement('btnName'); - btnName9.id = "btnName9"; - btnName9.classList.add("btnBaseFormat"); - btnName9.classList.add("btnHidden"); + const btnName0 = document.createElement('btnName') + btnName0.id = "btnName0" + btnName0.classList.add("btnBaseFormat") + btnName0.style.setProperty('visibility', 'visible') + btnName0.innerText = "Setup" + const btnName1 = document.createElement('btnName') + btnName1.id = "btnName1" + btnName1.classList.add("btnBaseFormat") + btnName1.classList.add("btnHidden") + const btnName2 = document.createElement('btnName') + btnName2.id = "btnName2" + btnName2.classList.add("btnBaseFormat") + btnName2.classList.add("btnHidden") + const btnName3 = document.createElement('btnName') + btnName3.id = "btnName3" + btnName3.classList.add("btnBaseFormat") + btnName3.classList.add("btnHidden") + const btnName4 = document.createElement('btnName') + btnName4.id = "btnName4" + btnName4.classList.add("btnBaseFormat") + btnName4.classList.add("btnHidden") + const btnName5 = document.createElement('btnName') + btnName5.id = "btnName5" + btnName5.classList.add("btnBaseFormat") + btnName5.classList.add("btnHidden") + const btnName6 = document.createElement('btnName') + btnName6.id = "btnName6" + btnName6.classList.add("btnBaseFormat") + btnName6.classList.add("btnHidden") + const btnName7 = document.createElement('btnName') + btnName7.id = "btnName7" + btnName7.classList.add("btnBaseFormat") + btnName7.classList.add("btnHidden") + const btnName8 = document.createElement('btnName') + btnName8.id = "btnName8" + btnName8.classList.add("btnBaseFormat") + btnName8.classList.add("btnHidden") + const btnName9 = document.createElement('btnName') + btnName9.id = "btnName9" + btnName9.classList.add("btnBaseFormat") + btnName9.classList.add("btnHidden") /* Action Select Box */ - const btnAction = document.createElement('select'); - btnAction.id = "btnAction"; - btnAction.style.setProperty('visibility', 'visible'); - btnAction.setDefault; - btnAction.classList.add("btnBaseFormat"); - btnAction.classList.add("btnAction"); - - var btnActionOptA = document.createElement("option"); - var btnActionOptATxt = document.createTextNode("Actions"); - btnActionOptA.setAttribute("value", "action"); - btnActionOptA.setAttribute("id", "optAction"); - btnActionOptA.classList.add("btnActionOptionTransparent"); - btnActionOptA.appendChild(btnActionOptATxt); - btnAction.appendChild(btnActionOptA); - - var btnActionOptG = document.createElement("optGroup"); - btnActionOptG.setAttribute("label", "———— Global Actions ————"); - btnActionOptG.classList.add("btnActionOptionGroup"); - btnAction.appendChild(btnActionOptG); - - var btnActionOptG1 = document.createElement("option"); - var btnActionOptG1Txt = document.createTextNode("Restart iCloud3"); - btnActionOptG1.setAttribute("value", "restart"); - btnActionOptG1.classList.add("btnActionOption"); - btnActionOptG1.appendChild(btnActionOptG1Txt); - btnAction.appendChild(btnActionOptG1); - - var btnActionOptG2 = document.createElement("option"); - var btnActionOptG2Txt = document.createTextNode("Pause Polling"); - btnActionOptG2.setAttribute("value", "pause"); - btnActionOptG2.classList.add("btnActionOption"); - btnActionOptG2.appendChild(btnActionOptG2Txt); - btnAction.appendChild(btnActionOptG2); - - var btnActionOptG3 = document.createElement("option"); - var btnActionOptG3Txt = document.createTextNode("Resume Polling"); - btnActionOptG3.setAttribute("value", "resume"); - btnActionOptG3.classList.add("btnActionOption"); - btnActionOptG3.appendChild(btnActionOptG3Txt); - btnAction.appendChild(btnActionOptG3); - - var btnActionOptG7 = document.createElement("option"); - var btnActionOptG7Txt = document.createTextNode("Request iOS App Locations"); - btnActionOptG7.setAttribute("value", "location"); - btnActionOptG7.classList.add("btnActionOption"); - btnActionOptG7.appendChild(btnActionOptG7Txt); - btnAction.appendChild(btnActionOptG7); - - var btnActionOptG4 = document.createElement("option"); - var btnActionOptG4Txt = document.createTextNode("Show Tracking Monitors"); - btnActionOptG4.setAttribute("value", "dev-log_level: eventlog"); - btnActionOptG4.setAttribute("id", "optEvlog"); - btnActionOptG4.classList.add("btnActionOption"); - btnActionOptG4.appendChild(btnActionOptG4Txt); - btnAction.appendChild(btnActionOptG4); - - var btnActionOptG8 = document.createElement("option"); - var btnActionOptG8Txt = document.createTextNode("Show Startup Log, Errors & Alerts"); - btnActionOptG8.setAttribute("value", "dev-refresh_event_log"); - btnActionOptG8.setAttribute("id", "optStartuplog"); - btnActionOptG8.classList.add("btnActionOption"); - btnActionOptG8.appendChild(btnActionOptG8Txt); - btnAction.appendChild(btnActionOptG8); - - var btnActionOptG5 = document.createElement("option"); - var btnActionOptG5Txt = document.createTextNode("Export Event Log"); - btnActionOptG5.setAttribute("value", "dev-export_event_log"); - btnActionOptG5.classList.add("btnActionOption"); - btnActionOptG5.appendChild(btnActionOptG5Txt); - btnAction.appendChild(btnActionOptG5); - - var btnActionOptG6 = document.createElement("option"); - var btnActionOptG6Txt = document.createTextNode("Start HA Debug Logging"); - btnActionOptG6.setAttribute("value", "dev-log_level: debug"); - btnActionOptG6.setAttribute("id", "optHalog"); - btnActionOptG6.classList.add("btnActionOption"); - btnActionOptG6.appendChild(btnActionOptG6Txt); - btnAction.appendChild(btnActionOptG6); + const btnAction = document.createElement('select') + btnAction.id = "btnAction" + btnAction.style.setProperty('visibility', 'visible') + btnAction.setDefault + btnAction.classList.add("btnBaseFormat") + btnAction.classList.add("btnAction") + + var btnActionOptA = document.createElement("option") + var btnActionOptATxt = document.createTextNode("Actions") + btnActionOptA.setAttribute("value", "action") + btnActionOptA.setAttribute("id", "optAction") + btnActionOptA.classList.add("btnActionOptionTransparent") + btnActionOptA.appendChild(btnActionOptATxt) + btnAction.appendChild(btnActionOptA) + + var btnActionOptG = document.createElement("optGroup") + btnActionOptG.setAttribute("label", "———— Global Actions ————") + btnActionOptG.classList.add("btnActionOptionGroup") + btnAction.appendChild(btnActionOptG) + + var btnActionOptG1 = document.createElement("option") + var btnActionOptG1Txt = document.createTextNode("Restart iCloud3") + btnActionOptG1.setAttribute("value", "restart") + btnActionOptG1.classList.add("btnActionOption") + btnActionOptG1.appendChild(btnActionOptG1Txt) + btnAction.appendChild(btnActionOptG1) + + var btnActionOptG2 = document.createElement("option") + var btnActionOptG2Txt = document.createTextNode("Pause Polling") + btnActionOptG2.setAttribute("value", "pause") + btnActionOptG2.classList.add("btnActionOption") + btnActionOptG2.appendChild(btnActionOptG2Txt) + btnAction.appendChild(btnActionOptG2) + + var btnActionOptG3 = document.createElement("option") + var btnActionOptG3Txt = document.createTextNode("Resume Polling") + btnActionOptG3.setAttribute("value", "resume") + btnActionOptG3.classList.add("btnActionOption") + btnActionOptG3.appendChild(btnActionOptG3Txt) + btnAction.appendChild(btnActionOptG3) + + var btnActionOptG7 = document.createElement("option") + var btnActionOptG7Txt = document.createTextNode("Update All Locations") + btnActionOptG7.setAttribute("value", "location") + btnActionOptG7.classList.add("btnActionOption") + btnActionOptG7.appendChild(btnActionOptG7Txt) + btnAction.appendChild(btnActionOptG7) + + var btnActionOptG4 = document.createElement("option") + var btnActionOptG4Txt = document.createTextNode("Show Tracking Monitors") + btnActionOptG4.setAttribute("value", "dev-log_level: eventlog") + btnActionOptG4.setAttribute("id", "optEvlog") + btnActionOptG4.classList.add("btnActionOption") + btnActionOptG4.appendChild(btnActionOptG4Txt) + btnAction.appendChild(btnActionOptG4) + + var btnActionOptG8 = document.createElement("option") + var btnActionOptG8Txt = document.createTextNode("Show Startup Log, Errors & Alerts") + btnActionOptG8.setAttribute("value", "dev-refresh_event_log") + btnActionOptG8.setAttribute("id", "optStartuplog") + btnActionOptG8.classList.add("btnActionOption") + btnActionOptG8.appendChild(btnActionOptG8Txt) + btnAction.appendChild(btnActionOptG8) + + var btnActionOptG5 = document.createElement("option") + var btnActionOptG5Txt = document.createTextNode("Export Event Log") + btnActionOptG5.setAttribute("value", "dev-export_event_log") + btnActionOptG5.classList.add("btnActionOption") + btnActionOptG5.appendChild(btnActionOptG5Txt) + btnAction.appendChild(btnActionOptG5) + + var btnActionOptG6 = document.createElement("option") + var btnActionOptG6Txt = document.createTextNode("Start HA Debug Logging") + btnActionOptG6.setAttribute("value", "dev-log_level: debug") + btnActionOptG6.setAttribute("id", "optHalog") + btnActionOptG6.classList.add("btnActionOption") + btnActionOptG6.appendChild(btnActionOptG6Txt) + btnAction.appendChild(btnActionOptG6) //--------------------------------------------------------- - var btnActionOptD = document.createElement("optGroup"); - btnActionOptD.setAttribute("label", "———— Device Actions ————"); - btnActionOptD.classList.add("btnActionOptionGroup"); - btnAction.appendChild(btnActionOptD); - - var btnActionOptD1 = document.createElement("option"); - var btnActionOptD1Txt = document.createTextNode("Pause Polling"); - btnActionOptD1.setAttribute("value", "dev-pause"); - btnActionOptD1.classList.add("btnActionOption"); - btnActionOptD1.appendChild(btnActionOptD1Txt); - btnAction.appendChild(btnActionOptD1); - - var btnActionOptD2 = document.createElement("option"); - var btnActionOptD2Txt = document.createTextNode("Resume Polling"); - btnActionOptD2.setAttribute("value", "dev-resume"); - btnActionOptD2.classList.add("btnActionOption"); - btnActionOptD2.appendChild(btnActionOptD2Txt); - btnAction.appendChild(btnActionOptD2); - - var btnActionOptD3 = document.createElement("option"); - var btnActionOptD3Txt = document.createTextNode("Request iOS App Location"); - btnActionOptD3.setAttribute("value", "dev-location"); - btnActionOptD3.classList.add("btnActionOption"); - btnActionOptD3.appendChild(btnActionOptD3Txt); - btnAction.appendChild(btnActionOptD3); - - var btnActionOptBL = document.createElement("option"); - var btnActionOptBLTxt = document.createTextNode(""); - btnActionOptBL.classList.add("btnActionOption"); + var btnActionOptD = document.createElement("optGroup") + btnActionOptD.setAttribute("label", "———— Selected Phone ————") + btnActionOptD.classList.add("btnActionOptionGroup") + btnAction.appendChild(btnActionOptD) + + var btnActionOptD1 = document.createElement("option") + var btnActionOptD1Txt = document.createTextNode("Pause Polling") + btnActionOptD1.setAttribute("value", "dev-pause") + btnActionOptD1.classList.add("btnActionOption") + btnActionOptD1.appendChild(btnActionOptD1Txt) + btnAction.appendChild(btnActionOptD1) + + var btnActionOptD2 = document.createElement("option") + var btnActionOptD2Txt = document.createTextNode("Resume Polling") + btnActionOptD2.setAttribute("value", "dev-resume") + btnActionOptD2.classList.add("btnActionOption") + btnActionOptD2.appendChild(btnActionOptD2Txt) + btnAction.appendChild(btnActionOptD2) + + var btnActionOptD3 = document.createElement("option") + var btnActionOptD3Txt = document.createTextNode("Update Phone's Location") + btnActionOptD3.setAttribute("value", "dev-location") + btnActionOptD3.classList.add("btnActionOption") + btnActionOptD3.appendChild(btnActionOptD3Txt) + btnAction.appendChild(btnActionOptD3) + + var btnActionOptBL = document.createElement("option") + var btnActionOptBLTxt = document.createTextNode("") + btnActionOptBL.classList.add("btnActionOption") btnActionOptBL.appendChild(btnActionOptBLTxt) - btnAction.appendChild(btnActionOptBL); - var btnActionOptV = document.createElement("optGroup"); - btnActionOptV.setAttribute("label", "—— Event Log v"+version+" ———"); - btnActionOptV.classList.add("btnActionOptionGroup"); - btnAction.appendChild(btnActionOptV); + btnAction.appendChild(btnActionOptBL) + var btnActionOptV = document.createElement("optGroup") + btnActionOptV.setAttribute("label", "—— Event Log v"+version+" ———") + btnActionOptV.classList.add("btnActionOptionGroup") + btnAction.appendChild(btnActionOptV) //------------------------------------------------------------- - const btnRefresh = document.createElement('btnName'); - btnRefresh.id = "btnRefresh"; - btnRefresh.classList.add("btnRefresh"); - btnRefresh.style.setProperty('visibility', 'visible'); - btnRefresh.innerHTML=`` + var btnHelpIcon24 = document.createElement('IMG') + btnHelpIcon24.id = "btnHelpIcon24" + btnHelpIcon24.setAttribute("alt", "iCloud3 Documentation") + //btnHelpIcon24.style.setProperty('visibility', 'visible') + btnHelpIcon24.setAttribute("src", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAYCAYAAADkgu3FAAAEEElEQVRIS72WfUzUZRzAP7zccefB8fY7DhDwmIgY/2S2dC1QBDFXbNp8bxlGNl9oDUyjmvhS4ZhQKIQvCVe4Nhthjj9glQqVscbmJNecJAZXdLyI3h0HCNzBtYN+7Afd8dJaz7/fl8/z/T7fl8eD/+l4zMRJB4VcQUi4D7HJamKDZfj9YcdU30tz3xD3Gh7RdQNsM/lxC1oF3k+peeJAKBmCjNUOB5pBsNjALhtFrvTEF+g0DFN7sgP9R/38AjjcAV2C3lCh3aMlZ7GKHW1D3HkwxLUOGzd+tdPaPkh/lBx1vDcLgxU8Od+HZK2MqIY+SivNFBWZMbuC/QP0ui+P5UeiV3oh1Js5ntXOl024NnY6TFcR+koQ2xICeNNq49bRTnYXmjFMhU0CHVQSkbeAS22j2Mq72Zdnpkk0KAokaqvABpuDeBk0numk+kgf3aL8vIbEjRo+ljkw5LaTXmilRwqbAK0CRfkiTkbIWPmhkS05Zn4WFd8PYMGrApdH4HEvD4btDuTAtdIOtuf10yXqVWpJ3hjC51etnE1p4xgwIsomQIUCSdmhVH3zkD1rjXwhKqwDn/IY8kYh2zxCldHGdzo565WerPaC/LAWcqQ3/0FHzjN+HDjaTtIRE7cmgV4CVdliyv4cJTD6LuuAUVFhOWirYjDIPbjbOETi879jqtOhW+LNdRuoI1tQS0Gv+SF8EMHVIRtXdrXwTi0MOeVjEW3xYeHFWL5vsnJiaRtFUsPrkYQvUXDxvp36uFZynbK6+UTEKWmwg19kC4FTH745moLYeaTtMJBw4e93HAOdEUh7Wcun+h6e29vFT5NuCLKAeWjMA/SfA0uFFlWiL+e9PdjqKnVO29owNqQGo9/ZSmJF/3j6xkBN0WTqFBxMMrDi5gDG6brcGEOBA/aPOCg5YeLd4of0TtUvEFi2T0tN6QN27u+kZs6gc8GkrA+iCgc/Hr7Pi6ctmFxdSgTpu9i1t4fqCdB0qZM6qgknc5mK4h47m+NbqXQX+UTqfiOpYoCbsyoGqbPb0RyKlHPseCepeRa+dQdyWwzTlbfU2TY58WsCSLzcz6VqSaPOurydiu4aVuok1581qWoyL5h4+2wft11FNG3DOg2mG0GiQ71A9qZgCgs7ePZwL19PBc1qBDmNpEP1s24y3zOPP6R4PtGQsCmI7cWdFByycE8qKxdY+UIIJTMOVdFoYk14oKm3UnjKROVXkik9NYocBbq0EDY/7U+W1UbTrNaE6MS5+HZreStORUbHMM3GR1zpsNM4dfEJSpbH+LDWz5uwhl5KKnvnsPhEmHOVr1CzNEtLRoiMFAcILlZ5l2GQmtPdlOWPF8fcVrk0PeLnRPBhUYI/MZGe+BtHsdT1cuc/+ZxMN+/+jewvN+q9KPbla94AAAAASUVORK5CYII=") + + var btnHelpIcon24Hover = document.createElement('IMG') + btnHelpIcon24Hover.id = "btnHelpIcon24Hover" + btnHelpIcon24Hover.setAttribute("alt", "iCloud3 Documentation") + btnHelpIcon24Hover.classList.add("btnHidden") + btnHelpIcon24Hover.setAttribute("src", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAYCAYAAADkgu3FAAAELUlEQVRIS72Wf0zUdRjHXwRc3kiUeSASB5RGKIv5a0FNjt8YphsYqNA08AdThBmQRhqgaMgJVxCIiMApyq8IcdSOmT+gNNZoyMWckxxLlvHDNCB1kw6OdrA77vjN1vr++zzv5/V9ns/zeZ6PEf/TZzQtxzN8DmKBFfNtHHnLxxHzBXPp/L2HW/WtqJ620dzQTVOTaro4k4M8PU1wenMlW/fvYJ7Im6EhS/qf9zGgGsDEVIBQ+BLQRVd7LRVZcvK/uA0MTQacGLRz30I27knA9vVtdN2/S9/j6/R1NnHv19949OAZYjtzXnVejNmC1Vi+7IPFQjtaGnK5UpnJ2czeiWDjQRExy4iRyjEVilDWH0cW+zVK5YTi4YAh4dYEbg/lDfePeP6khdNHdlMoax8LMwTFHLAlMvUiD+6r+KZoL7mpSp0gOdMO3y1BqFTOmJg2UppXQ97hhzp7WoEESfBJBKbt5CeFky97pA8bBXl6zuFQURYiWw/KP9+MNOEXnWP8MXsCd15CPbicF4z/YXBAAFynOjeMrNRunV9OpQ+S4BIar51mp28KMKi1jYIOyrwIjavi5+/2sH1thU4cEPAiB4tSUavjeNpbxcOO77F2CEQo9MbYWIr7ogSDMl24kYDLmv0UHvEi63CLIch/qxnphYV0/2GB/ysBgFondnVdiLSqHYHgHspGCVHreyirc8B26U0GVOZ4ic0NQKGRIqI+u8Zg/1Wkuw5SW9uvsY9kFLh5MSnlP9CmTCdoRaaBsOymDfZLy+n9s551TknDtgt1ttg7NTAwMBcvscW4LlO0ZmDnuIHEbe5Unx8+xxHQsbwNrPvgLAr5u3wa9ZOBMDLSFMF8S7p7n1GZ30d6sRkrJQUYm2zByFiKx5jSacTnaoNY7i8nLUJCWfFw+UZA1cporB0OEO7lRmtzx5S3/EZHBuqheNSDORSkH6Ik++9x/gkZqwjeq6AiN4L0eMXsQUfzffEOrMKIH8lJfp/SUz0T/pQWVCvfRWJUzcxKpx+pQBGN06pseh9tYr1z5aSZa0uXEuFFVXHzzJpBP5riTiJW4hTkx/05mXplUtCkzTBVe+tHey/UGVc/CTcvXaSmZvSi6vtM2d4ax8kurH6QfUl+uPlH8+35Tyg5fWfCjKa8sBrFVCNIGzFNHodfiIxS2TvIki+PA81oBGlU+kNVcS6a7KPDB6n7Us+44xcSxlfZGaQnthnYThR5sGZjzvRDVavSrgmB0JJb9TKqv6ykunp0So9N48MEB1Zv2ITL27E8f6Kc2ZrQBtEsvqDdHyN22sHjzlb+6rhKT2fj+MUnckW8ZC3CuYu43ZDD5dksPi1Ms8qXua0gLHYHFla+qIdEE6zybrraFZSfKuSMVNMcs1zl+uXRPk7MRa/h4r4EG/E8ujv6aKq7+988TqYceLM3/gvZOcgoRP8sgAAAAABJRU5ErkJggg==") + + const btnHelp = document.createElement('A') + btnHelp.id = "btnHelp" + btnHelp.classList.add("btnHelp") + btnHelp.style.setProperty('visibility', 'visible') + btnHelp.setAttribute('href', 'https://gcobb321.github.io/icloud3/#/') + btnHelp.setAttribute('target', '_blank') + btnHelp.appendChild(btnHelpIcon24) + btnHelp.appendChild(btnHelpIcon24Hover) + + //btnHelp.innerHTML=`` + + //------------------------------------------------------------- + var btnRefreshIcon24 = document.createElement('IMG') + btnRefreshIcon24.id = "btnRefreshIcon24" + btnRefreshIcon24.setAttribute("alt", "Refresh") + //btnRefreshIcon24.style.setProperty('visibility', 'visible') + btnRefreshIcon24.setAttribute("src", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAYCAYAAADkgu3FAAADLUlEQVRIS72WbWhTVxjHf6lJkxCT+HKTW7W6ltoXt0+V4UR0Wis4cf2gyMQPumJRdFNGfS37sFnHFHHRKr5ssLZuIijx5YusbLRaFcoQirGINE63RGvS1rrG3lSbJubKrU1Im5Q0Ejzf7jnPc37n+Z/nPs9R8Z6GKhmnHHSZOqzTtRSUmiiYqsH4JERvcx9Of4BHLa/oaoVgsn3GBC0B9TwTc3dnUSFoWCrLWAbgRRBCmjCZ+gwmAp3uQRqOeak/2s89QB4LmBD0jQFxq0hVoYENrgDtzwNc8wZpfRDiv44B+mdlYvpITd5UHR/P0FIqapjV4ueU3UdNjQ9fIlgcaPtEPjw0k3r9BIRmHwcrO7joILGzsmG5gayNU1i3aBK7pCBtpnZWKPP+OVxXqbhpuM/3yvcI0B492Qc+4LIrTLCum68P+HAk0z6y/quFT9dYOKmRcXtDTBfVSBkyhw3tXB0BWgK6unyOZWtYfMTD2iofd8cLidjZRUo/m8KfKngEeFQytjiQTaBkRxaX/vqfrcs9XEgVMiyXc1glJSniQevBUFtI7dMwk3P/GdI4nCpImsMNVYyfDBlx0q3Vkne+gJsOicPFLmpShSj2/UV8PtqvM4Q57yHnonf0s0DZlyJn6ntY+VUXf78LKJnPUNY5ctmWo2NPiZv5d17iSeY0nvVnhRgVO4sTKRpRukFHstEXq5H/9aOp6IkBpVu6hmmsmmzOvHzq8eDc319yJxpROpIhVk5nLj9NMqh37nKFxLN+uqOgdKR3BLTZiPBjNk2BII2bHvJtAwRGVIZ0/LDKhrdyqFpoZHd1ByX7emmLHCBa69JVgtZYOdck8csyF/uB13EgZSK2qP7WzbYffG8vcjyjTmDxaisnlKL6XQflNomeWL+x24QKS7OE7Xgv9ivDF5oIWKUjp8zKFwvMVEpBHNWdbLH5cI+2HbPxbRHZW2SgwjuI0/OKRm+I26Mbn6Dnk9lalhvVTGvp44S9L4XGFzmJ0srnmyiuFKmwalgmg5CglXe5B/jjdDe1h/zcT7mVx4YdeZwIWvIXmZk9MwOzJ8yL6320p+VxMp4ESMXmDVKARSiFsInBAAAAAElFTkSuQmCC") + + var btnRefreshIcon24Hover = document.createElement('IMG') + btnRefreshIcon24Hover.id = "btnRefreshIcon24Hover" + btnRefreshIcon24Hover.setAttribute("alt", "Refresh") + btnRefreshIcon24Hover.classList.add("btnHidden") + //btnRefreshIcon24Hover.style.setProperty('visibility', 'hidden') + btnRefreshIcon24Hover.setAttribute("src", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAYCAYAAADkgu3FAAADLklEQVRIS72Wa0iTYRTHf6+50Vhq4swyF5XdKBIssQtmMyO7QkYXDCrLim5SdpWKSruarbTMypp2BcNsHwqli2kXJIzlkohWWEnlptlFVqBpLbZYm22ii9Hz7X3ec87vPec57/k/Av9pCR1yFPFdkYt70D1wEGOiB+Ht54X+7Wcel+lo+VpNZXkdGk1LR3HaBykUngwJH8GCTQn4yCZgMvnT3NRIa0srniIxEkk3wIChppjLmXnkHHkKmNoDOgctXRvArJXJBA1eiOHNcxo/3qFRr+Hli9c0vPuGvI83/YcFI/ULw793NL4Bfagqz+ZWQQZnM744gzmCFicOJTEtD5FEhrZsP8qkK2i1Tp0tAefE92TmkjiGj9tIk7GKcO8plv1HX0sRhHuESXeaH9uCEjcHsXzfVd69aeFa7mqy92k7qv2f9wfORBI5+zhiUQ0f9IH4BRjp4pHOSOn1tiCFoivbcjORBY0n//A80pKfdBpiNcwqiCZ88g0EoRqoxUNQOoK2KqOIW1/Io5srWRJz2WXI73LpEBAwWZrCCWjSAinpKhV1732Z1M9c458ugyqMdxEEm5/J5OFYupnzgknNv0e1Np3Y0AyXIWYHzbfpDn4NBh9igi/ZzmjPyRlMXXSWorxpbF/18J9AHTj97jq1dg09+24mPmo0uspat4AefPCyxInwN9oycjco6bCEkFAT9a9EbEmwA7m7dOeKY8Ui36vfC7NHUHi+0paRO5rBvt5FukOe0u4bWjM2BqC+UG8DuaO9raC45TJW7S3hR/Nt0pZtpbi4ue1kcMcPa4548X4yIRGbUKVEkbmrysq3zTp3jaDI2ZeoKDnF0ompwA9HkHnHfqgWnVvDsd2Wg+zUOpg7nohZWZahmrMjnhxlg71f+zIhlvjzuEyJ+mgBarXlQJ2udcl9CZsxl5CxSTQZtZxKWYFKWfO3bfvCF7tiC/IhCXzU6/hUe5vP+gpH4ZONQj4gBolXL56WZ3HDFeGzfopZyoeODmV+UgK+PSby0yRzIuV1GGqKyD+h4nTaM9el3D5v6+XEWzaQkHEDCJT7UFfbiKb0uXsuJ53qgM4b/QIdc0go4VmAXgAAAABJRU5ErkJggg==") + + const btnRefresh = document.createElement('btnName') + btnRefresh.id = "btnRefresh" + btnRefresh.classList.add("btnRefresh") + btnRefresh.style.setProperty('visibility', 'visible') + btnRefresh.appendChild(btnRefreshIcon24) + btnRefresh.appendChild(btnRefreshIcon24Hover) + + //btnRefresh.innerHTML=`` + // Message Bar - const eltInfoBar = document.createElement("div"); - eltInfoBar.id = "eltInfoBar"; - - const eltInfoName = document.createElement("div"); - eltInfoName.id = "eltInfoName"; - eltInfoName.innerText = "Select Person"; - eltInfoName.style.color = "firebrick" - - const eltInfoTime = document.createElement("div"); - eltInfoTime.id = "eltInfoTime"; - eltInfoTime.innerText = "setup"; - eltInfoTime.style.color = "firebrick" - - const eltInfoMsgPopup = document.createElement("div"); - eltInfoMsgPopup.id = "eltInfoMsgPopup"; - eltInfoMsgPopup.classList.add("eltInfoMsgPopup"); - eltInfoMsgPopup.classList.add("eltInfoMsgPopupHidden"); - eltInfoMsgPopup.style.setProperty('zIndex', '9999'); - - const tblEvlogContainer = document.createElement("div"); + const statusBar = document.createElement("div") + statusBar.id = "statusBar" + + const statusName = document.createElement("div") + statusName.id = "statusName" + statusName.innerText = "Select Person" + statusName.style.color = "firebrick" + + const statusTime = document.createElement("div") + statusTime.id = "statusTime" + statusTime.innerText = "setup" + statusTime.style.color = "firebrick" + + const statusMsgPopup = document.createElement("div") + statusMsgPopup.id = "statusMsgPopup" + statusMsgPopup.classList.add("statusMsgPopup") + statusMsgPopup.classList.add("statusMsgPopupHidden") + statusMsgPopup.style.setProperty('zIndex', '9999') + + //Event Table + const tblEvlogContainer = document.createElement("div") tblEvlogContainer.id = "tblEvlogContainer" const tblEvlog = document.createElement("TABLE") @@ -268,7 +314,7 @@ class iCloud3EventLogCard extends HTMLElement { tblEvlogBody.classList.add("tblEvlogBody") // Style - const cssStyle = document.createElement('style'); + const cssStyle = document.createElement('style') cssStyle.textContent = ` /* Text special colors */ .blue {color: blue;} @@ -365,16 +411,15 @@ class iCloud3EventLogCard extends HTMLElement { width: 100%; /*border: 1px solid dodgerblue;*/ } - #thisButtonId, #logRecdCnt, #devType, #hdrCellWidth { + #thisButtonId, #logRecdCnt, #devType, #hdrCellWidth, #versionText { /*font-size: 2px;*/ color: transparent; - width: 25px; + width: 5px; float: left; /*border: 1px solid green;*/ } - - #versionText { - color: silver; + #infoText { + color: dodgerblue; float: right; } @@ -385,12 +430,12 @@ class iCloud3EventLogCard extends HTMLElement { } /* Message Bar setup */ - #eltInfoBar { + #statusBar { position: relative; width: 100%; /*border: 1px solid dodgerblue;*/ } - #eltInfoName { + #statusName { width: 40%; color: firebrick; float: left; @@ -399,7 +444,7 @@ class iCloud3EventLogCard extends HTMLElement { margin: 2px 0px 4px 0px; /*border: 1px solid var(--label-badge-red);*/ } - #eltInfoTime { + #statusTime { margin: 2px 2px 4px 0px; color: firebrick; float: right; @@ -407,7 +452,7 @@ class iCloud3EventLogCard extends HTMLElement { font-weight: 400; /*border: 1px solid green;*/ } - .eltInfoMsgPopup { + .statusMsgPopup { position: relative; width: 85%; margin-left: auto; @@ -422,7 +467,7 @@ class iCloud3EventLogCard extends HTMLElement { -moz-box-shadow: 5px 5px 23px 3px rgba(0,0,0,0.75); box-shadow: 3px 3px 20px 3px rgba(0,0,0,0.75); } - .eltInfoMsgPopupHidden { + .statusMsgPopupHidden { height: 0px; width: 0px; visibility: hidden; @@ -561,17 +606,35 @@ class iCloud3EventLogCard extends HTMLElement { } .btnHover {border: 1px solid var(--primary-color);} + /* Helph Select Button */ + #btnHelp { + display: inline-block; + visibility: visible; + color: var(--primary-text-color); + background-color: transparent; + /*height: 28px;*/ + /*width: 30px;*/ + margin: 0px 0px 0px 4px; + float: right; + } + .btnHelp { + border: 0px solid transparent; + background-color: transparent; + box-shadow: transparent; + } + /* Refresh Select Button */ #btnRefresh { display: inline-block; visibility: visible; color: var(--primary-text-color); background-color: transparent; - height: 24px; - margin: -4px 2px; + /*height: 28px;*/ + /*width: 30px;*/ + margin: 0px 0px 0px 4px; float: right; - box-sizing: border-box; } + .btnRefresh { border: 0px solid transparent; background-color: transparent; @@ -655,37 +718,39 @@ class iCloud3EventLogCard extends HTMLElement { ::-webkit-scrollbar {width: 1px;} ::-webkit-scrollbar-thumb {background: rgba(var(--rgb-accent-color), 0.7);} } - */ + */ - `; + ` // Build title - titleBar.appendChild(title); - titleBar.appendChild(btnRefresh); + titleBar.appendChild(title) + titleBar.appendChild(btnHelp) + titleBar.appendChild(btnRefresh) - utilityBar.appendChild(thisButtonId); - utilityBar.appendChild(logRecdCnt); - utilityBar.appendChild(devType); - utilityBar.appendChild(hdrCellWidth); - utilityBar.appendChild(versionText); + utilityBar.appendChild(thisButtonId) + utilityBar.appendChild(logRecdCnt) + utilityBar.appendChild(devType) + utilityBar.appendChild(hdrCellWidth) + utilityBar.appendChild(versionText) + utilityBar.appendChild(infoText) // Create Buttons - buttonBar.appendChild(btnName0); - buttonBar.appendChild(btnName1); - buttonBar.appendChild(btnName2); - buttonBar.appendChild(btnName3); - buttonBar.appendChild(btnName4); - buttonBar.appendChild(btnName5); - buttonBar.appendChild(btnAction); - buttonBar.appendChild(btnName6); - buttonBar.appendChild(btnName7); - buttonBar.appendChild(btnName8); - buttonBar.appendChild(btnName9); + buttonBar.appendChild(btnName0) + buttonBar.appendChild(btnName1) + buttonBar.appendChild(btnName2) + buttonBar.appendChild(btnName3) + buttonBar.appendChild(btnName4) + buttonBar.appendChild(btnName5) + buttonBar.appendChild(btnAction) + buttonBar.appendChild(btnName6) + buttonBar.appendChild(btnName7) + buttonBar.appendChild(btnName8) + buttonBar.appendChild(btnName9) // Build Message Bar - eltInfoBar.appendChild(eltInfoName); - eltInfoBar.appendChild(eltInfoTime); - eltInfoBar.appendChild(eltInfoMsgPopup) + statusBar.appendChild(statusName) + statusBar.appendChild(statusTime) + statusBar.appendChild(statusMsgPopup) tblEvlog.appendChild(tblEvlogHdr) tblEvlog.appendChild(tblEvlogBody) @@ -695,33 +760,37 @@ class iCloud3EventLogCard extends HTMLElement { background.appendChild(titleBar) background.appendChild(utilityBar) background.appendChild(buttonBar) - background.appendChild(eltInfoBar) + background.appendChild(statusBar) background.appendChild(tblEvlogContainer) - background.appendChild(cssStyle); + background.appendChild(cssStyle) - card.appendChild(background); - root.appendChild(card); + card.appendChild(background) + root.appendChild(card) // Click & Mouse Events for (let i = 0; i <= 9; i++) { let buttonId = 'btnName' + i let button = root.getElementById(buttonId) - button.addEventListener("mousedown", event => { this._nameButtonPress(buttonId); }); - button.addEventListener("mouseover", event => { this._btnClassMouseOver(buttonId); }); - button.addEventListener("mouseout", event => { this._btnClassMouseOut(buttonId); }); + button.addEventListener("mousedown", event => { this._nameButtonPress(buttonId); }) + button.addEventListener("mouseover", event => { this._btnClassMouseOver(buttonId); }) + button.addEventListener("mouseout", event => { this._btnClassMouseOut(buttonId); }) } - btnAction.addEventListener("change", event => { this._commandButtonPress("btnAction"); }); - //btnAction.addEventListener("mouseover", event => { this._btnClassMouseOver("btnAction"); }); - //btnAction.addEventListener("mouseout", event => { this._btnClassMouseOut("btnAction"); }); + btnAction.addEventListener("change", event => { this._commandButtonPress("btnAction"); }) + //btnAction.addEventListener("mouseover", event => { this._btnClassMouseOver("btnAction"); }) + //btnAction.addEventListener("mouseout", event => { this._btnClassMouseOut("btnAction"); }) - btnRefresh.addEventListener("mousedown", event => { this._commandButtonPress("btnRefresh"); }); - btnRefresh.addEventListener("mouseover", event => { this._btnClassMouseOver("btnRefresh"); }); - btnRefresh.addEventListener("mouseout", event => { this._btnClassMouseOut("btnRefresh"); }); + //btnHelp.addEventListener("mousedown", event => { this._commandButtonPress("btnHelp"); }) + btnHelp.addEventListener("mouseover", event => { this._btnClassMouseOver("btnHelp"); }) + btnHelp.addEventListener("mouseout", event => { this._btnClassMouseOut("btnHelp"); }) + + btnRefresh.addEventListener("mousedown", event => { this._commandButtonPress("btnRefresh"); }) + btnRefresh.addEventListener("mouseover", event => { this._btnClassMouseOver("btnRefresh"); }) + btnRefresh.addEventListener("mouseout", event => { this._btnClassMouseOut("btnRefresh"); }) // Add to root - this._config = config; + this._config = config } // Create card. @@ -733,8 +802,8 @@ class iCloud3EventLogCard extends HTMLElement { const root = this.shadowRoot this._hass = hass const thisButtonId = root.getElementById("thisButtonId") - const eltInfoTime = root.getElementById("eltInfoTime") - const eltInfoMsgPopup = root.getElementById("eltInfoMsgPopup") + const statusTime = root.getElementById("statusTime") + const statusMsgPopup = root.getElementById("statusMsgPopup") try { const updateTimeAttr = hass.states['sensor.icloud3_event_log'].attributes['update_time'] @@ -744,17 +813,17 @@ class iCloud3EventLogCard extends HTMLElement { this._nameButtonPress(this._currentButtonId()) } - //this._displayNameMsgL('/'+eltInfoTime.innerText + '/'+updateTimeAttr+'/') - if (eltInfoTime.innerText.indexOf(updateTimeAttr) == -1) { + //this._displayNameMsgL('/'+statusTime.innerText + '/'+updateTimeAttr+'/') + if (statusTime.innerText.indexOf(updateTimeAttr) == -1) { this._setupEventLogTable('hass') } - eltInfoMsgPopup.classList.add('eltInfoMsgPopupHidden') + statusMsgPopup.classList.add('statusMsgPopupHidden') } catch(err) { - const eltInfoMsgPopup = root.getElementById("eltInfoMsgPopup") - const eltInfoTime = root.getElementById("eltInfoTime") + const statusMsgPopup = root.getElementById("statusMsgPopup") + const statusTime = root.getElementById("statusTime") - if (eltInfoMsgPopup.classList.contains('eltInfoMsgPopupHidden') == false) { + if (statusMsgPopup.classList.contains('statusMsgPopupHidden') == false) { return } const msgRestarting = '

iCloud3 is restarting

' @@ -762,13 +831,13 @@ class iCloud3EventLogCard extends HTMLElement { if (err.name == 'TypeError') { if (err.message.indexOf('attributes') > -1) { - //if (eltInfoTime.innerText == 'setup') { + //if (statusTime.innerText == 'setup') { if (thisButtonId.innerText == "setup") { - eltInfoMsgPopup.innerHTML = msgNotRunning + statusMsgPopup.innerHTML = msgNotRunning } else { - eltInfoMsgPopup.innerHTML = msgRestarting + statusMsgPopup.innerHTML = msgRestarting } - eltInfoMsgPopup.classList.remove('eltInfoMsgPopupHidden') + statusMsgPopup.classList.remove('statusMsgPopupHidden') } else if (err.message.indexOf('undefined') == -1) { alert(err) } @@ -783,8 +852,8 @@ class iCloud3EventLogCard extends HTMLElement { /* Cycle through the sensor.icloud3_event_log attributes and build the names on the buttons, and make them visible. */ - const root = this.shadowRoot; - const hass = this._hass; + const root = this.shadowRoot + const hass = this._hass const thisButtonId = root.getElementById("thisButtonId") const btnName0 = root.getElementById("btnName0") const filtername = hass.states['sensor.icloud3_event_log'].attributes['filtername'] @@ -806,13 +875,13 @@ class iCloud3EventLogCard extends HTMLElement { if (i < names.length) { button.innerText = names[i] - button.style.setProperty('visibility', 'visible'); + button.style.setProperty('visibility', 'visible') button.classList.remove('btnHidden') button.classList.add('btnNotSelected') //} else { // button.innerText = "Device-"+i - // button.style.setProperty('visibility', 'visible'); + // button.style.setProperty('visibility', 'visible') // button.classList.remove('btnHidden') } } @@ -824,10 +893,10 @@ class iCloud3EventLogCard extends HTMLElement { build the event log table */ - const root = this.shadowRoot; - const hass = this._hass; + const root = this.shadowRoot + const hass = this._hass const tblEvlog = root.getElementById("tblEvlog") - const eltInfoTime = root.getElementById("eltInfoTime") + const statusTime = root.getElementById("statusTime") const hdrCellWidth = root.getElementById("hdrCellWidth") const logRecdCnt = root.getElementById("logRecdCnt") const devType = root.getElementById("devType") @@ -966,6 +1035,8 @@ class iCloud3EventLogCard extends HTMLElement { maxStatZoneLength = 9 if (tStat == 'stationary') {tStat = 'stationry'} if (tZone == 'stationary') {tZone = 'stationry'} + if (tStat == 'Stationary') {tStat = 'Stationry'} + if (tZone == 'Stationary') {tZone = 'Stationry'} } if (tStat.length > maxStatZoneLength) { tStat = tStat.substr(0, maxStatZoneLength) + "
" + tStat.substr(maxStatZoneLength, tStat.length) @@ -1091,7 +1162,7 @@ class iCloud3EventLogCard extends HTMLElement { && tText.indexOf("Complete") == -1) { initializationRecdFound = true } - if (tText.indexOf("Error") >= 0) { + if (tText.indexOf(" Error ") >= 0) { classErrorMsg = ' errorMsg' if (initializationRecdFound == false) { alertErrorMsg = "iCloud3 Error Msg at "+tTime @@ -1270,7 +1341,7 @@ class iCloud3EventLogCard extends HTMLElement { //--------------------------------------------------------------------------- _resize_header_width() { - const root = this.shadowRoot; + const root = this.shadowRoot const tblEvlog = root.getElementById("tblEvlog") const devType = root.getElementById("devType") var rowCnt = tblEvlog.rows.length @@ -1298,7 +1369,7 @@ class iCloud3EventLogCard extends HTMLElement { } //--------------------------------------------------------------------------- _setupDevType() { - const root = this.shadowRoot; + const root = this.shadowRoot const devType = root.getElementById("devType") //iPhone (portrait) width=375, ,height=768 @@ -1335,8 +1406,8 @@ class iCloud3EventLogCard extends HTMLElement { and then the Event Log was displayed in another, the Log revs are for the selected device but the name highlighter will be for the precious device selected. */ - const root = this.shadowRoot; - const hass = this._hass; + const root = this.shadowRoot + const hass = this._hass this.namesAttr = hass.states['sensor.icloud3_event_log'].attributes['names'] var filtername = hass.states['sensor.icloud3_event_log'].attributes['filtername'] const namesAttr = this.namesAttr @@ -1375,8 +1446,8 @@ class iCloud3EventLogCard extends HTMLElement { /* Handle the button press events. Get the devicename, do an 'icloud3_update' event_log devicename' service call to have the event_log attribute populated. */ - const root = this.shadowRoot; - const hass = this._hass; + const root = this.shadowRoot + const hass = this._hass this.namesAttr = hass.states['sensor.icloud3_event_log'].attributes['names'] const namesAttr = this.namesAttr const names = Object.values(namesAttr) @@ -1388,9 +1459,9 @@ class iCloud3EventLogCard extends HTMLElement { var lastButtonId = this._currentButtonId() var lastButtonPressed = root.getElementById(lastButtonId) var buttonPressX = buttonPressId.substr(-1) - var eltInfoName = names[buttonPressX]+" ("+devicenames[buttonPressX]+")" + var statusName = names[buttonPressX]+" ("+devicenames[buttonPressX]+")" - this._displayNameMsgL(eltInfoName) + this._displayNameMsgL(statusName) thisButtonId.innerText = buttonPressId lastButtonPressed.classList.remove('btnSelected') @@ -1409,8 +1480,8 @@ class iCloud3EventLogCard extends HTMLElement { /* Handle the button press events. Get the devicename, do an 'icloud3_update' event_log devicename' service call to have the event_log attribute populated. */ - const root = this.shadowRoot; - const hass = this._hass; + const root = this.shadowRoot + const hass = this._hass this.namesAttr = hass.states['sensor.icloud3_event_log'].attributes['names'] const namesAttr = this.namesAttr const devicenames = Object.keys(namesAttr) @@ -1465,15 +1536,27 @@ class iCloud3EventLogCard extends HTMLElement { //--------------------------------------------------------------------------- _btnClassMouseOver(buttonId) { - const root = this.shadowRoot; + const root = this.shadowRoot const button = root.getElementById(buttonId) - const thisButtonId = root.getElementById("thisButtonId") + const btnHelp = root.getElementById("bthHelp") + const btnHelpIcon24 = root.getElementById("btnHelpIcon24") + const btnHelpIcon24Hover = root.getElementById("btnHelpIcon24Hover") + const btnRefreshIcon24 = root.getElementById("btnRefreshIcon24") + const btnRefreshIcon24Hover = root.getElementById("btnRefreshIcon24Hover") const versionText = root.getElementById("versionText") + const infoText = root.getElementById("infoText") const devType = root.getElementById("devType") - if (buttonId == "btnRefresh") { - this._displayTimeMsgR("Refresh Event Log") - versionText.style.setProperty('visibility', 'visible'); + if (buttonId == "btnHelp") { + btnHelpIcon24Hover.classList.remove('btnHidden') + btnHelpIcon24.classList.add('btnHidden') + this._displayInfoText("iCloud3 User Maual") + this._displayTimeMsgR("Version "+versionText.textContent) + + } else if (buttonId == "btnRefresh") { + btnRefreshIcon24Hover.classList.remove('btnHidden') + btnRefreshIcon24.classList.add('btnHidden') + this._displayInfoText("Refresh Event Log") } else if (buttonId == "btnAction") { this._displayTimeMsgR("Show Action Command List") @@ -1484,16 +1567,29 @@ class iCloud3EventLogCard extends HTMLElement { //--------------------------------------------------------------------------- _btnClassMouseOut(buttonId) { - const root = this.shadowRoot; - const hass = this._hass; + const root = this.shadowRoot + const hass = this._hass this.logLevelDebug = hass.states['sensor.icloud3_event_log'].attributes['log_level_debug'] const button = root.getElementById(buttonId) + const btnHelp = root.getElementById("bthHelp") + const btnHelpIcon24 = root.getElementById("btnHelpIcon24") + const btnHelpIcon24Hover = root.getElementById("btnHelpIcon24Hover") + const btnRefreshIcon24 = root.getElementById("btnRefreshIcon24") + const btnRefreshIcon24Hover = root.getElementById("btnRefreshIcon24Hover") const versionText = root.getElementById('versionText') + const infoText = root.getElementById("infoText") const devType = root.getElementById("devType") const thisButtonId = root.getElementById("thisButtonId") - if (buttonId == 'btnRefresh') { - versionText.style.setProperty('visibility', 'hidden') + if (buttonId == 'btnHelp') { + btnHelpIcon24.classList.remove('btnHidden') + btnHelpIcon24Hover.classList.add('btnHidden') + this._displayInfoText('') + + } else if (buttonId == 'btnRefresh') { + btnRefreshIcon24.classList.remove('btnHidden') + btnRefreshIcon24Hover.classList.add('btnHidden') + this._displayInfoText('') } if (devType.innerText == "") {button.classList.remove("btnHover")} @@ -1501,42 +1597,50 @@ class iCloud3EventLogCard extends HTMLElement { } //--------------------------------------------------------------------------- _currentButtonId() { - const root = this.shadowRoot; + const root = this.shadowRoot const thisButtonId = root.getElementById("thisButtonId") return thisButtonId.innerText } //--------------------------------------------------------------------------- _displayTimeMsgR(msg) { - // Display message before time field - const root = this.shadowRoot; - const hass = this._hass; - const eltInfoTime = root.getElementById("eltInfoTime") + // Display text below action button + const root = this.shadowRoot + const hass = this._hass + const statusTime = root.getElementById("statusTime") const updateTimeAttr = hass.states['sensor.icloud3_event_log'].attributes['update_time'] - //if (eltInfoTime.innerText.startsWith("●●")) { + //if (statusTime.innerText.startsWith("●●")) { //pass if (msg == "") { - eltInfoTime.innerHTML = "Refreshed: " + updateTimeAttr + statusTime.innerHTML = "Refreshed: " + updateTimeAttr } else { - eltInfoTime.innerHTML = msg + statusTime.innerHTML = msg } } //--------------------------------------------------------------------------- _displayNameMsgL(msg) { - /* Display test messages */ - const root = this.shadowRoot; - const eltInfoName = root.getElementById("eltInfoName") - eltInfoName.innerHTML = msg + /* Display text below name button */ + const root = this.shadowRoot + const statusName = root.getElementById("statusName") + statusName.innerHTML = msg + } + + //--------------------------------------------------------------------------- + _displayInfoText(msg) { + /* Display text in area below refresh & help buttons */ + const root = this.shadowRoot + const infoText = root.getElementById("infoText") + infoText.innerText = msg } //--------------------------------------------------------------------------- getCardSize() { - return 1; + return 1 } } -customElements.define('icloud3-event-log-card', iCloud3EventLogCard); +customElements.define('icloud3-event-log-card', iCloud3EventLogCard) diff --git a/custom_components/icloud3/pyicloud_ic3.py b/custom_components/icloud3/pyicloud_ic3.py index a63eb64..4edea47 100644 --- a/custom_components/icloud3/pyicloud_ic3.py +++ b/custom_components/icloud3/pyicloud_ic3.py @@ -24,7 +24,7 @@ to generate a Authentication error code rather than generating it's own 2SA Needed Exception """ -from six import PY2, string_types +from six import PY2, string_types, text_type from uuid import uuid1 import inspect import json @@ -103,22 +103,34 @@ def request(self, method, url, **kwargs): # pylint: disable=arguments-differ if self.service.password_filter not in request_logger.filters: request_logger.addFilter(self.service.password_filter) - request_logger.debug(f"{method}, {url}, {kwargs.get('data', '')}") + request_logger.debug(f"106 REQUEST -- {25*'-'}") + request_logger.debug(f"106 REQUEST -- {method}, {url}, {kwargs.get('data', '')}") #request_logger.info(f"{method}, {url}, {kwargs.get("data", "")}"") kwargs_retry_flag = kwargs.get("retried", None) kwargs.pop("retried", None) + response = super(PyiCloudSession, self).request(method, url, **kwargs) + request_logger.debug(f"115 RESPONSE -- {response}, StatusCode-{response.status_code}, okStatus-{response.ok}") + request_logger.debug(f"110 RESPONSE -- {25*'-'}") + content_type = response.headers.get("Content-Type", "").split(";")[0] json_mimetypes = ["application/json", "text/json"] kwargs_retry_flag = True if not response.ok and content_type not in json_mimetypes: + try: + data = response.json() + request_logger.debug(f"120 RESPONSE ERROR DATA -- {data}") + except: + pass + if (kwargs_retry_flag is None and (response.status_code == AUTHENTICATION_REQUIRED or response.status_code == DEVICE_STATUS_ERROR)): message = (f"Reauthentication Required for Account: {self.service.user['apple_id']}") + request_logger.debug(f"133 MESSAGE -- {message}") api_error = PyiCloudAPIResponseException( message, response.status_code, retry=True @@ -139,7 +151,7 @@ def request(self, method, url, **kwargs): # pylint: disable=arguments-differ request_logger.warning("Failed to parse response with JSON mimetype") return response - request_logger.debug(data) + #request_logger.debug(f"150 RESPONSE DATA -- {data}") #request_logger.info(data) reason = data.get("errorMessage") diff --git a/custom_components/icloud3/services.yaml b/custom_components/icloud3/services.yaml index 5f41292..9be5441 100644 --- a/custom_components/icloud3/services.yaml +++ b/custom_components/icloud3/services.yaml @@ -1,3 +1,6 @@ +# yamllint disable rule:document-start +# yamllint disable rule:line-length + icloud3_update: description: This service allows you to change the way iCloud3 operates. fields: @@ -24,7 +27,7 @@ icloud3_restart: account_name: description: account_name of the iCloud3 custom component specified in the Configuration Variables section described at the beginning of this document. (Required) example: gary_icloud - + icloud3_lost_iphone: description: This service will play the Lost iPhone sound on a specific device. fields: diff --git a/development area - v2.2.1/change log.txt b/development area - v2.2.1/change log.txt deleted file mode 100644 index 30e3193..0000000 --- a/development area - v2.2.1/change log.txt +++ /dev/null @@ -1,49 +0,0 @@ -v2.2.1f (10/29/2020) -------- -1. Bug fix - Fixed an error introduced in v2.2.1e dealing with authentication error checking. -2. Parameter change - Changed 'display_zone_name:' to 'display_zone_fname' to match what iCloud3 was doing before v2.2.1e. -3. If the zone name is displayed, it will be reformatted before it is displayed. For example, 'the_shores' will be displayed as 'TheShores'. - -v2.2.1e (10/28/2020) -------- -1. Enhancement - Updated the iOS App tracking method to request the phone's location when the Next Update Time is reached in the same manner as the iCloud tracking methods. Using the tracking method 'iosapp' eliminates all iCloud account polling, relies only on the data provided by the iOS app and provides a reliable tracking method when access to the iCloud accounts is limited due to 2fa authentication/verification issues. At night, the iOS App usually shuts down when the phone is asleep. When the phone becomes inactive and is not responding to location requests, a message is displayed in the Event Log and on the iCloud3 information screen, the interval is increased until the phone wakes up and the iOS App becomes active again. When iOS App wakes up and begins responding to the location request, polling will automatically resume. Note: If the iOS App is running in the background, it still may not wake up and respond to the location requests. In that case, the iOS App must be restarted. iCloud3 will detect the 'launch' trigger issued by the iOS App and begin polling as normal. -2. Bug fix - The iOS App device_tracker entity contained the zone's friendly name on enter/exit events while iCloud3 used the zone name for it's device_tracker entity. This led to extra zone triggers zone mismatch errors when the names were different. This has been fixed. -3. Updated - Changed the way zones are handled to better support overlapping zones, particularilly when you have two zones with a center at the same location with different sizes. For example, your Home zone has a radius of 100m and you have a second zone at the Home zone's location with a radius of 500m. The larger zone will help wake up the iOS App before you reach the Home zone. Another example is having a city size zone to display the city's name instead of Away in the Zone and State entities on the Event Log and iCloud3 information screen. -4. New parameter - 'display_zone_name: True/False', Default: False. iCloud3 (and the iOS App) displays the zone's friendly name in the Zone and iOSApp state fields on the Event Log and the iCloud3 information screen. If the friendly name is too long to be displayed, it will be truncated. With this parameter, the zone's name rather than it's friendly name, is displayed. -5. New parameter - 'time_format: 12/24', Default depends on the unit_of_measurement (mi=12, km=24). This parameter overrides the unit_of_measurement time format. -6. Enhancement - Added error handling to the iCloud authentication/verification process. - - -v2.2.1c (10/20/2020) -------- -1. Bug fix - The iOS App reports the device_tracker state with the zone's friendly_name. iCloud3 was handling zones by the zone name. This caused problems handling zone change detection and, at times created a iOS App/iCloud3 state mismatch error. -2. Bug fix - If (1) the phone was turned off and not available when HA restarted or (2) became unreachable for an extended period of time while HA/iCloud3 was running (cell service down, turned off, airplane mode, etc.), the phone would be in a not_set state or the location would become older and older. This would hang up iCloud3 in a 5-second update loop, polling iCloud for location data when none was available. It will now retry the data request 4-times at a 15-second interval. The interval will increase to 1, 5, 15, 30, 1 hr and then the max_interval (4-hrs) and remain there until the phone comes back online. If the phone is then turned on, it will be picked up on the next successful location data request and returned and then tracked as normal. -3. Bug fix - When old location messages were added to the Event Log if the last located time is old and the phone is in a zone. -4. Bug fix - If the unit_of_measurement not being set to 'km' if the parameter was in the config_ic3.yaml file. It was being set correctly if it was in the HA configuration.file. -5. Bug fix - Fixed 'Lost Pnone' notification. It will now work with all tracking methods using the iOS App Notifications platform. -6. If the phone's name started with iPhone (or iPad), the first character of the sensor.xxx friendly_name attribute would be a '-'. The '-' was removed. Also removed the '-' between the phone's name and the attribute name to match the iOS App friendly_name formatting. -7. New configuration parameter - 'display_zone_name: True/False(default)' The 'device_tracker.[devicename]' entity displays the zone's friendly_ name, which is then displayed on the lovelace card. The name is truncated if it is longer than 10-12 letters. This option, if True, will display the zone name itself instead of the friendly_name. -8. Added some logger debug statements to 'pyicloud_ic3.py' to capture icloud request/response events that might help pinpoint what is happening when iCloud needs to do an account verification. -To turn this on, add the following to your configuration.yaml file: -logger: - default: info - logs: - custom_components.icloud3.pyicloud_ic3: debug - - - -v2.2.1b (10/14/2020) --------------------- -1. Fixes a Region Entered trigger being discarded when the distance to the center of the zone is between the zone's radius and 100m when the radius is less than 100m. The iOS App issues the Region Enter trigger when the distance is less than 100m, regardless of the zone size. iCloud3 looks at the zone size and not the 100m prezone size like the iOS App. -2. A location will not be considered old if it's age is less than 1-minute to reduce the number of location upates that are discarded. -3. Updated sensor icons. - -v2.2.1a (10/13/2020) --------------------- -1. Display an Alert message in the Event Log if the config_ic3.yaml file is found in the icloud3 directory. -2. Restart iCloud3 to reinitialize location information when the iCloud account is verified with the 6-digit authentication code. Previously, iCloud3 was resuming and, in some cases, would not receive location information from iCloud Location Services on the next poll. -3. Fixed the iOS App monitor so it would show the iOS App gps accuracy rather than the last iCloud value. -4. Fixed a determining the polling interval if the last poll was from iCloud data and it was discarded due to poor gps accuracy and the next poll was from the iOS App with good gps accuracy. -5. Added the 'noiosapp' value to the track_devices parameter that indicates the devicename does not have the iOS App installed on it. Example ' - gary_iphone > gary-456@email.com, gary.png, noiosapp' -6. Added the results of the interval calculation to the Event Log Tracking Monitor display. -7. Changed Event Log > Actions > Request iOS App Location to 'Update Location' to issue an iOS App Locate Reuest if the iOS App is installed or an iCloud Location request if it is not installed. \ No newline at end of file diff --git a/development area - v2.2.1/device_tracker.py b/development area - v2.2.1/device_tracker.py deleted file mode 100644 index 73ddc75..0000000 --- a/development area - v2.2.1/device_tracker.py +++ /dev/null @@ -1,9541 +0,0 @@ -""" -Platform that supports scanning iCloud. -For more details about this platform, please refer to the documentation at -https://home-assistant.io/components/device_tracker.icloud/ - - -Special Note: I want to thank Walt Howd, (iCloud2 fame) who inspired me to - tackle this project. I also want to give a shout out to Kovács Bálint, - Budapest, Hungary who wrote the Python WazeRouteCalculator and some - awesome HA guys (Petro31, scop, tsvi, troykellt, balloob, Myrddyn1, - mountainsandcode, diraimondo, fabaff, squirtbrnr, and mhhbob) who - gave me the idea of using Waze in iCloud3. - ...Gary Cobb aka GeeksterGary, Vero Beach, Florida, USA - -Thanks to all -""" - -#pylint: disable=bad-whitespace, bad-indentation -#pylint: disable=bad-continuation, import-error, invalid-name, bare-except -#pylint: disable=too-many-arguments, too-many-statements, too-many-branches -#pylint: disable=too-many-locals, too-many-return-statements -#pylint: disable=unused-argument, unused-variable -#pylint: disable=too-many-instance-attributes, too-many-lines - -VERSION = '2.2.1f' - -''' -v2.2.1f -------- -1. Bug fix - Fixed an error introduced in v2.2.1e dealing with authentication error checking. -2. Parameter change - Changed 'dislay_zone_name:' to 'display_zone_fname' to match what iCloud3 was doing before v2.2.1e. -3. If the zone name is displayed, it will be reformatted before it is displayed. For example, 'the_shores' will be displayed as 'TheShores'. - -v2.2.1e -------- -1. Enhancement - Updated the iOS App tracking method to request the phone's location when the Next Update Time is reached in the same manner as the iCloud tracking methods. Using the tracking method 'iosapp' eliminates all iCloud account polling, relies only on the data provided by the ios app and provides a reliable tracking method when access to the iCloud accounts is limited due to 2fa authentication/verification issues. At night, the iOS App usually shuts down when the phone is asleep. When it becomes inactive, a message is displayed in the Event Log and on the iCloud3 information screen, the interval is increased until the phone wakes up and the iOS App becomes active. Polling will be resumed when the phone wakes up, the iOS App wakes up and begins responding to the location request. Note: If the iOS App is running in the background, it may not wake up and respond to the location requests. In that case, the iOS App must be restarted. Then, iCloud3 will detect the 'launch' trigger and begin polling the phone on a regular basis. -2. Updated - Changed the way zones are handled to better support overlapping zones, particularilly when you have two zones with a center at the same location with different sizes. For example, your Home zone with a radius of 100m and you have a second zone with the Home zone's location with a radius of 500m. The larger zone will help wake up the iOS App before you reach the Home zone. Another example is having a city size zone that will then display the city's name instead of Away. -3. New parameter - 'display_zone_name: True/False', Default: False. iCloud3 (and the iOS App) displays the zone's friendly name in the Zone (and device_tracker state) field on the Event Log and the iCloud3 information screen. If the friendly name is too long to be displayed, it will be truncated. With this parameter, the zone's name rather than it's friendly name, is displayed. -4. New parameter - 'time_format: 12/24', Default depends on the unit_of_measurement (mi=12, km=24). This parameter overrides the unit_of_measurement time format. - -v2.2.1c -------- -1. Bug fix - The iOS App reports the device_tracker state with the zone's friendly_name. iCloud3 was handling zones by the zone name. This caused problems handling zone change detection and, at times created a iOS App/iCloud3 state mismatch error. -2. Bug fix - If (1) the phone was turned off and not available when HA restarted or (2) became unreachable for an extended period of time while HA/iCloud3 was running (cell service down, turned off, airplane mode, etc.), the phone would be in a not_set state or the location would become older and older. This would hang up iCloud3 in a 5-second update loop, polling iCloud for location data when none was available. It will now retry the data request 4-times at a 15-second interval. The interval will increase to 1, 5, 15, 30, 1 hr and then the max_interval (4-hrs) and remain there until the phone comes back online. If the phone is then turned on, it will be picked up on the next successful location data request and returned and then tracked as normal. -3. Bug fix - When old location messages were added to the Event Log if the last located time is old and the phone is in a zone. -4. Bug fix - If the unit_of_measurement not being set to 'km' if the parameter was in the config_ic3.yaml file. It was being set correctly if it was in the HA configuration.file. -5. Bug fix - Fixed 'Lost Pnone' notification. It will now work with all tracking methods using the iOS App Notifications platform. -6. If the phone's name started with iPhone (or iPad), the first character of the sensor.xxx friendly_name attribute would be a '-'. The '-' was removed. Also removed the '-' between the phone's name and the attribute name to match the iOS App friendly_name formatting. -7. New configuration parameter - 'display_zone_name: True/False(default)' The 'device_tracker.[devicename]' entity displays the zone's friendly_ name, which is then displayed on the lovelace card. The name is truncated if it is longer than 10-12 letters. This option, if True, will display the zone name itself instead of the friendly_name. -8. Added some logger debug statements to 'pyicloud_ic3.py' to capture icloud request/response events that might help pinpoint what is happening when iCloud needs to do an account verification. -To turn this on, add the following to your configuration.yaml file: -logger: - default: info - logs: - custom_components.icloud3.pyicloud_ic3: debug - - -v2.2.1b -------- -1. Fixes a Region Entered trigger being discarded when the distance to the center of the zone is between the zone's radius and 100m when the radius is less than 100m. The iOS App issues the Region Enter trigger when the distance is less than 100m, regardless of the zone size. iCloud3 looks at the zone size and not the 100m prezone size like the iOS App. -2. A location will not be considered old if it's age is less than 1-minute to reduce the number of location upates that are discarded. -3. Updated sensor icons. - -v2.2.1a -------- -1. Display an Alert message in the Event Log if the config_ic3.yaml file is found in the icloud3 directory. -2. Restart iCloud3 to reinitialize location information when the iCloud account is verified with the 6-digit authentication code. Previously, iCloud3 was resuming and, in some cases, would not receive location information from iCloud Location Services on the next poll. -3. Fixed the iOS App monitor so it would show the iOS App gps accuracy rather than the last iCloud value. -4. Fixed a determining the polling interval if the last poll was from iCloud data and it was discarded due to poor gps accuracy and the next poll was from the iOS App with good gps accuracy. -5. Added the 'noiosapp' value to the track_devices parameter that indicates the devicename does not have the iOS App installed on it. -6. Added the results of the interval calculation to the Event Log Tracking Monitor display. -7. Changed Event Log > Actions > Request iOS App Location to 'Update Location' to issue an iOS App Locate Request if the iOS App is installed or an iCloud Location request if it is not installed. -''' -#Symbols = •▶¦▶ ●►◄ ▬ ▲▼◀▶ oPhone=►▶► - -import logging -import os -import sys -import shutil -import time -import datetime -import json -import voluptuous as vol - -from homeassistant.const import CONF_USERNAME, CONF_PASSWORD -from homeassistant.helpers.event import track_utc_time_change -import homeassistant.helpers.config_validation as cv -from homeassistant.util import slugify -import homeassistant.util.dt as dt_util -from homeassistant.util.location import distance -from homeassistant.components.device_tracker import ( - PLATFORM_SCHEMA, DOMAIN, ATTR_ATTRIBUTES) -#from homeassistant.components.device_tracker import DeviceScanner - -_LOGGER = logging.getLogger(__name__) - -#Changes in device_tracker entities are not supported in HA v0.94 and -#legacy code is being used for the DeviceScanner. Try to import from the -#.legacy directory and retry from the normal directory if the .legacy -#directory does not exist. -#try: -# from homeassistant.components.device_tracker.legacy import DeviceScanner -# HA_DEVICE_TRACKER_LEGACY_MODE = True -#except ImportError: -# from homeassistant.components.device_tracker import DeviceScanner - -HA_DEVICE_TRACKER_LEGACY_MODE = False - -#Vailidate that Waze is available and can be used -try: - import WazeRouteCalculator - WAZE_IMPORT_SUCCESSFUL = True -except ImportError: - WAZE_IMPORT_SUCCESSFUL = False - pass - -try: - from .pyicloud_ic3 import PyiCloudService - from .pyicloud_ic3 import ( - PyiCloudFailedLoginException, - PyiCloudNoDevicesException, - PyiCloudServiceNotActivatedException, - PyiCloudAPIResponseException, - PyiCloud2SARequiredException, - ) - PYICLOUD_IC3_IMPORT_SUCCESSFUL = True -except ImportError: - PYICLOUD_IC3_IMPORT_SUCCESSFUL = False - pass - -DEBUG_TRACE_CONTROL_FLAG = False - -HA_ENTITY_REGISTRY_FILE_NAME ='/config/.storage/core.entity_registry' -ENTITY_REGISTRY_FILE_KEY = 'core.entity_registry' -STORAGE_KEY_ICLOUD = 'icloud' -STORAGE_KEY_ENTITY_REGISTRY = 'core.entity_registry' -STORAGE_VERSION = 1 -STORAGE_DIR = ".storage" - -CONF_ACCOUNT_NAME = 'account_name' -CONF_GROUP = 'group' -CONF_DEVICENAME = 'device_name' -CONF_NAME = 'name' -CONF_TRACKING_METHOD = 'tracking_method' -CONF_IOSAPP_REQUEST_LOC_MAX_CNT = 'iosapp_request_loc_max_cnt' -CONF_TRACK_DEVICES = 'track_devices' -CONF_TRACK_DEVICE = 'track_device' -CONF_UNIT_OF_MEASUREMENT = 'unit_of_measurement' -CONF_TIME_FORMAT = 'time_format' -CONF_INTERVAL = 'interval' -CONF_BASE_ZONE = 'base_zone' -CONF_INZONE_INTERVAL = 'inzone_interval' -CONF_DISPLAY_ZONE_FNAME = 'display_zone_fname' -CONF_CENTER_IN_ZONE = 'center_in_zone' -CONF_STATIONARY_STILL_TIME = 'stationary_still_time' -CONF_STATIONARY_INZONE_INTERVAL = 'stationary_inzone_interval' -CONF_STATIONARY_ZONE_OFFSET = 'stationary_zone_offset' -CONF_MAX_INTERVAL = 'max_interval' -CONF_TRAVEL_TIME_FACTOR = 'travel_time_factor' -CONF_GPS_ACCURACY_THRESHOLD = 'gps_accuracy_threshold' -CONF_OLD_LOCATION_THRESHOLD = 'old_location_threshold' -CONF_IGNORE_GPS_ACC_INZONE = 'ignore_gps_accuracy_inzone' -CONF_HIDE_GPS_COORDINATES = 'hide_gps_coordinates' -CONF_WAZE_REGION = 'waze_region' -CONF_WAZE_MAX_DISTANCE = 'waze_max_distance' -CONF_WAZE_MIN_DISTANCE = 'waze_min_distance' -CONF_WAZE_REALTIME = 'waze_realtime' -CONF_DISTANCE_METHOD = 'distance_method' -CONF_COMMAND = 'command' -CONF_CREATE_SENSORS = 'create_sensors' -CONF_EXCLUDE_SENSORS = 'exclude_sensors' -CONF_ENTITY_REGISTRY_FILE = 'entity_registry_file_name' -CONF_LOG_LEVEL = 'log_level' -CONF_CONFIG_IC3_FILE_NAME = 'config_ic3_file_name' -CONF_LEGACY_MODE = 'legacy_mode' -CONF_EVENT_LOG_CARD_DIRECTORY = 'event_log_card_directory' -CONF_DEVICE_STATUS = 'device_status' -CONF_DISPLAY_TEXT_AS = 'display_text_as' - -# entity attributes (iCloud FmF & FamShr) -ATTR_ICLOUD_TIMESTAMP = 'timeStamp' -ATTR_ICLOUD_HORIZONTAL_ACCURACY = 'horizontalAccuracy' -ATTR_ICLOUD_VERTICAL_ACCURACY = 'verticalAccuracy' -ATTR_ICLOUD_BATTERY_STATUS = 'batteryStatus' -ATTR_ICLOUD_BATTERY_LEVEL = 'batteryLevel' -ATTR_ICLOUD_DEVICE_CLASS = 'deviceClass' -ATTR_ICLOUD_DEVICE_STATUS = 'deviceStatus' -ATTR_ICLOUD_LOW_POWER_MODE = 'lowPowerMode' - -# device data attributes -ATTR_LOCATION = 'location' -ATTR_ATTRIBUTES = 'attributes' -ATTR_RADIUS = 'radius' -ATTR_FRIENDLY_NAME = 'friendly_name' -ATTR_NAME = 'name' -ATTR_ISOLD = 'isOld' -ATTR_DEVICE_CLASS = 'device_class' - -# entity attributes -ATTR_ZONE = 'zone' -ATTR_ZONE_TIMESTAMP = 'zone_timestamp' -ATTR_LAST_ZONE = 'last_zone' -ATTR_GROUP = 'group' -ATTR_TIMESTAMP = 'timestamp' -ATTR_TIMESTAMP_TIME = 'timestamp_time' -ATTR_AGE = 'age' -ATTR_TRIGGER = 'trigger' -ATTR_BATTERY = 'battery' -ATTR_BATTERY_LEVEL = 'battery_level' -ATTR_BATTERY_STATUS = 'battery_status' -ATTR_INTERVAL = 'interval' -ATTR_ZONE_DISTANCE = 'zone_distance' -ATTR_CALC_DISTANCE = 'calc_distance' -ATTR_WAZE_DISTANCE = 'waze_distance' -ATTR_WAZE_TIME = 'travel_time' -ATTR_DIR_OF_TRAVEL = 'dir_of_travel' -ATTR_TRAVEL_DISTANCE = 'travel_distance' -ATTR_DEVICE_STATUS = 'device_status' -ATTR_LOW_POWER_MODE = 'low_power_mode' -ATTR_TRACKING = 'tracking' -ATTR_DEVICENAME_IOSAPP = 'iosapp_device' -ATTR_AUTHENTICATED = 'authenticated' -ATTR_LAST_UPDATE_TIME = 'last_update' -ATTR_NEXT_UPDATE_TIME = 'next_update' -ATTR_LAST_LOCATED = 'last_located' -ATTR_INFO = 'info' -ATTR_GPS_ACCURACY = 'gps_accuracy' -ATTR_GPS = 'gps' -ATTR_LATITUDE = 'latitude' -ATTR_LONGITUDE = 'longitude' -ATTR_POLL_COUNT = 'poll_count' -ATTR_ICLOUD3_VERSION = 'icloud3_version' -ATTR_VERT_ACCURACY = 'vertical_accuracy' -ATTR_ALTITUDE = 'altitude' -ATTR_BADGE = 'badge' -ATTR_EVENT_LOG = 'event_log' -ATTR_PICTURE = 'entity_picture' - -#General constants -HOME = 'home' -NOT_HOME = 'not_home' -NOT_SET = 'not_set' -STATIONARY = 'stationary' -AWAY_FROM = 'AwayFrom' -AWAY = 'Away' -PAUSED = 'Paused' -PAUSED_CAPS = 'PAUSED' -UNKNOWN = 'Unknown' -NEVER = 'Never' -ERROR = 'Error' -TIMESTAMP_ZERO = '0000-00-00 00:00:00' -HHMMSS_ZERO = '00:00:00' -HIGH_INTEGER = 9999999999 -UTC_TIME = True -LOCAL_TIME = False -NUMERIC = True -NEW_LINE = '\n' - -SENSOR_EVENT_LOG_ENTITY = 'sensor.icloud3_event_log' - -DEVICE_ATTRS_BASE = { - ATTR_LATITUDE: 0, - ATTR_LONGITUDE: 0, - ATTR_BATTERY: 0, - ATTR_BATTERY_LEVEL: 0, - ATTR_BATTERY_STATUS: '', - ATTR_GPS_ACCURACY: 0, - ATTR_VERT_ACCURACY: 0, - ATTR_TIMESTAMP: TIMESTAMP_ZERO, - ATTR_ICLOUD_TIMESTAMP: HHMMSS_ZERO, - ATTR_TRIGGER: '', - ATTR_DEVICE_STATUS: '', - ATTR_LOW_POWER_MODE: '', - } - -INITIAL_LOCATION_DATA = { - ATTR_NAME: '', - ATTR_DEVICE_CLASS: 'iPhone', - ATTR_BATTERY_LEVEL: 0, - ATTR_BATTERY_STATUS: UNKNOWN, - ATTR_DEVICE_STATUS: UNKNOWN, - ATTR_LOW_POWER_MODE: False, - ATTR_TIMESTAMP: 0, - ATTR_TIMESTAMP_TIME: HHMMSS_ZERO, - ATTR_AGE: HIGH_INTEGER, - ATTR_LATITUDE: 0.0, - ATTR_LONGITUDE: 0.0, - ATTR_ALTITUDE: 0.0, - ATTR_ISOLD: False, - ATTR_GPS_ACCURACY: 0, - ATTR_VERT_ACCURACY: 0, - } - -TRACE_ATTRS_BASE = { - ATTR_NAME: '', - ATTR_ZONE: '', - ATTR_LAST_ZONE: '', - ATTR_ZONE_TIMESTAMP: '', - ATTR_LATITUDE: 0, - ATTR_LONGITUDE: 0, - ATTR_TRIGGER: '', - ATTR_TIMESTAMP: TIMESTAMP_ZERO, - ATTR_ZONE_DISTANCE: 0, - ATTR_INTERVAL: 0, - ATTR_DIR_OF_TRAVEL: '', - ATTR_TRAVEL_DISTANCE: 0, - ATTR_WAZE_DISTANCE: '', - ATTR_CALC_DISTANCE: 0, - ATTR_LAST_LOCATED: '', - ATTR_LAST_UPDATE_TIME: '', - ATTR_NEXT_UPDATE_TIME: '', - ATTR_POLL_COUNT: '', - ATTR_INFO: '', - ATTR_BATTERY: 0, - ATTR_BATTERY_LEVEL: 0, - ATTR_GPS: 0, - ATTR_GPS_ACCURACY: 0, - ATTR_VERT_ACCURACY: 0, - } - -TRACE_ICLOUD_ATTRS_BASE = { - CONF_NAME: '', - ATTR_ICLOUD_DEVICE_STATUS: '', - ATTR_ISOLD: False, - ATTR_LATITUDE: 0, - ATTR_LONGITUDE: 0, - ATTR_ICLOUD_TIMESTAMP: 0, - ATTR_ICLOUD_HORIZONTAL_ACCURACY: 0, - ATTR_ICLOUD_VERTICAL_ACCURACY: 0, - 'positionType': 'Wifi', - } - -SENSOR_DEVICE_ATTRS = [ - 'zone', - 'zone_name1', - 'zone_name2', - 'zone_name3', - 'last_zone', - 'last_zone_name1', - 'last_zone_name2', - 'last_zone_name3', - 'zone_timestamp', - 'base_zone', - 'zone_distance', - 'calc_distance', - 'waze_distance', - 'travel_time', - 'dir_of_travel', - 'interval', - 'info', - 'last_located', - 'last_update', - 'next_update', - 'poll_count', - 'travel_distance', - 'trigger', - 'battery', - 'battery_status', - 'gps_accuracy', - 'vertical accuracy', - 'badge', - 'name', - ] - -SENSOR_ATTR_FORMAT = { - 'zone_distance': 'dist', - 'calc_distance': 'dist', - 'waze_distance': 'diststr', - 'travel_distance': 'dist', - 'battery': '%', - 'dir_of_travel': 'title', - 'altitude': 'm-ft', - 'badge': 'badge', - } - -#---- iPhone Device Tracker Attribute Templates ----- -SENSOR_ATTR_FNAME = { - 'zone': 'Zone', - 'zone_name1': 'Zone1', - 'zone_name2': 'Zone2', - 'zone_name3': 'Zone3', - 'last_zone': 'Last Zone', - 'last_zone_name1': 'Last Zone1', - 'last_zone_name2': 'Last Zone2', - 'last_zone_name3': 'Last Zone3', - 'zone_timestamp': 'Zone Timestamp', - 'base_zone': 'Base Zone', - 'zone_distance': 'Zone Distance', - 'calc_distance': 'Calc Dist', - 'waze_distance': 'Waze Dist', - 'travel_time': 'Travel Time', - 'dir_of_travel': 'Direction', - 'interval': 'Interval', - 'info': 'Info', - 'last_located': 'Last Located', - 'last_update': 'Last Update', - 'next_update': 'Next Update', - 'poll_count': 'Poll Count', - 'travel_distance': 'Travel Dist', - 'trigger': 'Trigger', - 'battery': 'Battery', - 'battery_status': 'Battery Status', - 'gps_accuracy': 'GPS Accuracy', - 'vertical_accuracy': 'Vertical Accuracy', - 'badge': 'Badge', - 'name': 'Name', - } - -SENSOR_ATTR_ICON = { - 'zone': 'mdi:cellphone-iphone', - 'last_zone': 'mdi:map-clock-outline', - 'base_zone': 'mdi:map-clock', - 'zone_timestamp': 'mdi:clock-in', - 'zone_distance': 'mdi:map-marker-distance', - 'calc_distance': 'mdi:map-marker-distance', - 'waze_distance': 'mdi:map-marker-distance', - 'travel_time': 'mdi:clock-outline', - 'dir_of_travel': 'mdi:compass-outline', - 'interval': 'mdi:clock-start', - 'info': 'mdi:information-outline', - 'last_located': 'mdi:history', - 'last_update': 'mdi:history', - 'next_update': 'mdi:update', - 'poll_count': 'mdi:counter', - 'travel_distance': 'mdi:map-marker-distance', - 'trigger': 'mdi:flash-outline', - 'battery': 'mdi:battery-outline', - 'battery_status': 'mdi:battery-outline', - 'gps_accuracy': 'mdi:map-marker-radius', - 'altitude': 'mdi:image-filter-hdr', - 'vertical_accuracy': 'mdi:map-marker-radius', - 'badge': 'mdi:shield-account', - 'name': 'mdi:account', - 'entity_log': 'mdi:format-list-checkbox', - } - -SENSOR_ID_NAME_LIST = { - 'zon': 'zone', - 'zon1': 'zone_name1', - 'zon2': 'zone_name2', - 'zon3': 'zone_name3', - 'bzon': 'base_zone', - 'lzon': 'last_zone', - 'lzon1': 'last_zone_name1', - 'lzon2': 'last_zone_name2', - 'lzon3': 'last_zone_name3', - 'zonts': 'zone_timestamp', - 'zdis': 'zone_distance', - 'cdis': 'calc_distance', - 'wdis': 'waze_distance', - 'tdis': 'travel_distance', - 'ttim': 'travel_time', - 'dir': 'dir_of_travel', - 'intvl': 'interval', - 'lloc': 'last_located', - 'lupdt': 'last_update', - 'nupdt': 'next_update', - 'cnt': 'poll_count', - 'info': 'info', - 'trig': 'trigger', - 'bat': 'battery', - 'batstat': 'battery_status', - 'alt': 'altitude', - 'gpsacc': 'gps_accuracy', - 'vacc': 'vertical_accuracy', - 'badge': 'badge', - 'name': 'name', - } - -ATTR_TIMESTAMP_FORMAT = '%Y-%m-%d %H:%M:%S.%f' -APPLE_DEVICE_TYPES = ['iphone', 'ipad', 'ipod', 'watch', 'iwatch', 'icloud', - 'iPhone', 'iPad', 'iPod', 'Watch', 'iWatch', 'iCloud'] -FMF_FAMSHR_LOCATION_FIELDS = ['altitude', 'latitude', 'longitude', 'timestamp', - 'horizontalAccuracy', 'verticalAccuracy', ATTR_ICLOUD_BATTERY_STATUS] - -#Convert zone/state value to display value -ZONE_TO_DISPLAY_BASE = { - None: "not_home", - "not_home": "Away", - "not_set": "NotSet", - "away": "Away", - "stationary": "Stationary", - "nearzone": "NearZone", - "near_zone": "NearZone", - } -#Convert state non-fname value to internal zone/state value -STATE_TO_ZONE_BASE = { - "NotSet": "not_set", - "Away": "not_home", - "away": "not_home", - "NotHome": "not_home", - "nothome": "not_home", - "Stationary": "stationary", - "stationary": "stationary", - "NearZone": "nearzone", - "NearZone": "near_zone", - } - -#icloud_update commands -CMD_ERROR = 1 -CMD_INTERVAL = 2 -CMD_PAUSE = 3 -CMD_RESUME = 4 -CMD_WAZE = 5 -CMD_LOCATION = 6 - -#Other constants -IOSAPP_DT_ENTITY = True -ICLOUD_DT_ENTITY = False -ICLOUD_LOCATION_DATA_ERROR = False - -STATIONARY_LAT_90 = 90 -STATIONARY_LONG_180 = 180 -STAT_ZONE_NEW_LOCATION = True -STAT_ZONE_MOVE_TO_BASE = False -STATIONARY_ZONE_1KM_LAT = 0.008983 #Subtract/add from home zone latitude to make stat zone location -STATIONARY_ZONE_1KM_LONG= 0.010094 -EVLOG_RECDS_PER_DEVICE = 1000 #Used to calculate the max recds to store -EVENT_LOG_CLEAR_SECS = 600 #Clear event log data interval -EVENT_LOG_CLEAR_CNT = 15 #Number of recds to display when clearing event log -ICLOUD3_ERROR_MSG = "ICLOUD3 ERROR-SEE EVENT LOG" - -#Devicename config parameter file extraction -DI_DEVICENAME = 0 -DI_DEVICE_TYPE = 1 -DI_NAME = 2 -DI_EMAIL = 3 -DI_BADGE_PICTURE = 4 -DI_IOSAPP_ENTITY = 5 -DI_IOSAPP_SUFFIX = 6 -DI_ZONES = 7 - -#Waze status codes -WAZE_REGIONS = ['US', 'NA', 'EU', 'IL', 'AU'] -WAZE_USED = 0 -WAZE_NOT_USED = 1 -WAZE_PAUSED = 2 -WAZE_OUT_OF_RANGE = 3 -WAZE_NO_DATA = 4 - -#Interval range table used for setting the interval based on a retry count -#The key is starting retry count range, the value is the interval (in minutes) -#poor_location_gps cnt, icloud_authentication cnt (default) -POOR_LOC_GPS_CNT = 1.1 -AUTH_ERROR_CNT = 1.2 -RETRY_INTERVAL_RANGE_1 = {0:.25, 4:1, 8:5, 12:30, 16:60, 20:120, 24:240} -#request iosapp location retry cnt -IOSAPP_REQUEST_LOC_CNT = 2.1 -RETRY_INTERVAL_RANGE_2 = {0:.5, 4:2, 8:30, 12:60, 14:120, 16:240, 18:480} - -#Used by the 'update_method' in the polling_5_sec loop -IOSAPP_UPDATE = "IOSAPP" -ICLOUD_UPDATE = "ICLOUD" - -#The event_log lovelace card will display the event in a special color if -#the text starts with a special character: -# $ - SeaGreen * - Purple -# $$ - DodgerBlue ** - BlueViolet -# $$$ - Blue *** - OrangeRed -EVLOG_DEBUG = "$$" -EVLOG_ALERT = "***" -EVLOG_NOTICE = "**" - -#tracking_method config parameter being used -FMF = 'fmf' #Find My Friends -FAMSHR = 'famshr' #icloud Family-Sharing -IOSAPP = 'iosapp' #HA IOS App v1.5x or v2.x -IOSAPP1 = 'iosapp1' #HA IOS App v1.5x only -FMF_FAMSHR = [FMF, FAMSHR] -IOSAPP_IOSAPP1 = [IOSAPP, IOSAPP1] - -TRK_METHOD_NAME = { - FMF: 'Find My Friends', - FAMSHR: 'Family Sharing', - IOSAPP: 'IOS App', - IOSAPP1: 'IOS App v1', - } -TRK_METHOD_SHORT_NAME = { - FMF: 'FmF', - FAMSHR: 'FamShr', - IOSAPP: 'IOSApp', - IOSAPP1: 'IOSApp1', - } -DEVICE_TYPE_FNAME = { - 'iphone': 'iPhone', - 'phone': 'iPhone', - 'ipad': 'iPad', - 'iwatch': 'iWatch', - 'watch': 'iWatch', - 'ipod': 'iPod', - } - -#iOS App Triggers defined in \iOS/Shared/Location/LocatioTrigger.swift -BACKGROUND_FETCH = 'Background Fetch' -BKGND_FETCH = 'Bkgnd Fetch' -GEOGRAPHIC_REGION_ENTERED = 'Geographic Region Entered' -GEOGRAPHIC_REGION_EXITED = 'Geographic Region Exited' -IBEACON_REGION_ENTERED = 'iBeacon Region Entered' -IBEACON_REGION_EXITED = 'iBeacon Region Exited' -REGION_ENTERED = 'Region Entered' -REGION_EXITED = 'Region Exited' -INITIAL = 'Initial' -MANUAL = 'Manual' -LAUNCH = "Launch", -SIGNIFICANT_LOC_CHANGE = 'Significant Location Change' -SIGNIFICANT_LOC_UPDATE = 'Significant Location Update' -SIG_LOC_CHANGE = 'Sig Loc Change' -PUSH_NOTIFICATION = 'Push Notification' -REQUEST_IOSAPP_LOC = 'Request iOSApp Loc' -IOSAPP_LOC_CHANGE = "iOSApp Loc Change" - -#Trigger is converted to abbreviation after getting last_update_trigger -IOS_TRIGGER_ABBREVIATIONS = { - GEOGRAPHIC_REGION_ENTERED: REGION_ENTERED, - GEOGRAPHIC_REGION_EXITED: REGION_EXITED, - IBEACON_REGION_ENTERED: REGION_ENTERED, - IBEACON_REGION_EXITED: REGION_EXITED, - SIGNIFICANT_LOC_CHANGE: SIG_LOC_CHANGE, - SIGNIFICANT_LOC_UPDATE: SIG_LOC_CHANGE, - PUSH_NOTIFICATION: REQUEST_IOSAPP_LOC, - BACKGROUND_FETCH: BKGND_FETCH, - } -IOS_TRIGGERS_VERIFY_LOCATION = [ - INITIAL, - LAUNCH, - MANUAL, - IOSAPP_LOC_CHANGE, - BKGND_FETCH, - SIG_LOC_CHANGE, - REQUEST_IOSAPP_LOC, - ] -IOS_TRIGGERS_ENTER = [ - REGION_ENTERED, - 'Test Entered', - ] -IOS_TRIGGERS_EXIT = [ - REGION_EXITED, - 'Test Exited' - ] -IOS_TRIGGERS_ENTER_EXIT = [ - REGION_ENTERED, - REGION_EXITED, - ] - -#Lists to hold the group names, group objects and iCloud device configuration -#The ICLOUD3_GROUPS is filled in on each platform load, the GROUP_OBJS is -#filled in after the polling timer is setup. -ICLOUD3_GROUPS = [] -ICLOUD3_GROUP_OBJS = {} -ICLOUD3_TRACKED_DEVICES = {} -''' -DEVICE_STATUS_SET = [ - 'deviceModel', 'rawDeviceModel', 'deviceStatus', - 'batteryStatus', 'batteryLevel', 'id', 'lowPowerMode', - 'deviceDisplayName', 'name', 'fmlyShare', - 'location', - 'locationCapable', 'locationEnabled', 'isLocating', - 'remoteLock', 'activationLocked', 'lockedTimestamp', - 'lostModeCapable', 'lostModeEnabled', 'locFoundEnabled', - 'lostDevice', 'lostTimestamp', - 'remoteWipe', 'wipeInProgress', 'wipedTimestamp', - 'isMac'] -''' -#Default values are ["batteryLevel", "deviceDisplayName", "deviceStatus", "name"] -DEVICE_STATUS_SET = [ - ATTR_ICLOUD_DEVICE_CLASS, - ATTR_ICLOUD_BATTERY_STATUS, - ATTR_ICLOUD_LOW_POWER_MODE, - ATTR_LOCATION - ] -DEVICE_STATUS_CODES = { - '200': 'online', - '201': 'offline', - '203': 'pending', - '204': 'unregistered', - '0': '' - } -SERVICE_SCHEMA = vol.Schema({ - vol.Optional(CONF_GROUP): cv.slugify, - vol.Optional(CONF_DEVICENAME): cv.slugify, - vol.Optional(CONF_INTERVAL): cv.slugify, - vol.Optional(CONF_COMMAND): cv.string - }) - -PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ - vol.Required(CONF_USERNAME): cv.string, - vol.Optional(CONF_PASSWORD, default=''): cv.string, - vol.Optional(CONF_GROUP, default='group'): cv.slugify, - vol.Optional(CONF_TRACKING_METHOD, default=FMF): cv.slugify, - vol.Optional(CONF_IOSAPP_REQUEST_LOC_MAX_CNT, default=HIGH_INTEGER): cv.string, - vol.Optional(CONF_ENTITY_REGISTRY_FILE): cv.string, - vol.Optional(CONF_CONFIG_IC3_FILE_NAME, default=''): cv.string, - vol.Optional(CONF_EVENT_LOG_CARD_DIRECTORY, default='www/custom_cards'): cv.string, - vol.Optional(CONF_LEGACY_MODE, default=False): cv.boolean, - vol.Optional(CONF_DISPLAY_TEXT_AS, default=[]): vol.All(cv.ensure_list, [cv.string]), - - #-----►►General Attributes ---------- - vol.Optional(CONF_UNIT_OF_MEASUREMENT, default='mi'): cv.slugify, - vol.Optional(CONF_TIME_FORMAT, default=0): cv.string, - vol.Optional(CONF_INZONE_INTERVAL, default='2 hrs'): cv.string, - vol.Optional(CONF_DISPLAY_ZONE_FNAME, default=False): cv.boolean, - vol.Optional(CONF_CENTER_IN_ZONE, default=False): cv.boolean, - vol.Optional(CONF_MAX_INTERVAL, default='4 hrs'): cv.string, - vol.Optional(CONF_TRAVEL_TIME_FACTOR, default=.60): cv.string, - vol.Optional(CONF_GPS_ACCURACY_THRESHOLD, default=100): cv.string, - vol.Optional(CONF_OLD_LOCATION_THRESHOLD, default='-1 min'): cv.string, - vol.Optional(CONF_IGNORE_GPS_ACC_INZONE, default=True): cv.boolean, - vol.Optional(CONF_HIDE_GPS_COORDINATES, default=False): cv.boolean, - vol.Optional(CONF_LOG_LEVEL, default=''): cv.string, - vol.Optional(CONF_DEVICE_STATUS, default='online, pending'): cv.string, - - #-----►►Filter, Include, Exclude Devices ---------- - vol.Optional(CONF_TRACK_DEVICES, default=[]): vol.All(cv.ensure_list, [cv.string]), - vol.Optional(CONF_TRACK_DEVICE, default=[]): vol.All(cv.ensure_list, [cv.string]), - - #-----►►Waze Attributes ---------- - vol.Optional(CONF_DISTANCE_METHOD, default='waze'): cv.string, - vol.Optional(CONF_WAZE_REGION, default='US'): cv.string, - vol.Optional(CONF_WAZE_MAX_DISTANCE, default=1000): cv.string, - vol.Optional(CONF_WAZE_MIN_DISTANCE, default=1): cv.string, - vol.Optional(CONF_WAZE_REALTIME, default=False): cv.boolean, - - #-----►►Other Attributes ---------- - vol.Optional(CONF_STATIONARY_INZONE_INTERVAL, default='30 min'): cv.string, - vol.Optional(CONF_STATIONARY_STILL_TIME, default='8 min'): cv.string, - vol.Optional(CONF_STATIONARY_ZONE_OFFSET, default='1,0'): cv.string, - vol.Optional(CONF_CREATE_SENSORS, default=[]): vol.All(cv.ensure_list, [cv.string]), - vol.Optional(CONF_EXCLUDE_SENSORS, default=[]): vol.All(cv.ensure_list, [cv.string]), - vol.Optional(CONF_COMMAND): cv.string, - }) - -DEFAULT_CONFIG_VALUES = { - CONF_UNIT_OF_MEASUREMENT: 'mi', - CONF_TIME_FORMAT: 0, - CONF_INZONE_INTERVAL: '2 hrs', - CONF_DISPLAY_ZONE_FNAME: False, - CONF_CENTER_IN_ZONE: False, - CONF_MAX_INTERVAL: '4 hrs', - CONF_TRAVEL_TIME_FACTOR: .60, - CONF_GPS_ACCURACY_THRESHOLD: 100, - CONF_OLD_LOCATION_THRESHOLD: '-1 min', - CONF_IGNORE_GPS_ACC_INZONE: True, - CONF_HIDE_GPS_COORDINATES: False, - CONF_LOG_LEVEL: '', - CONF_DEVICE_STATUS: 'online, pending', - CONF_TRACK_DEVICES: [], - CONF_TRACK_DEVICE: [], - CONF_DISTANCE_METHOD: 'waze', - CONF_LEGACY_MODE: False, - CONF_WAZE_REGION: 'US', - CONF_WAZE_MAX_DISTANCE: 1000, - CONF_WAZE_MIN_DISTANCE: 1, - CONF_WAZE_REALTIME: False, - CONF_STATIONARY_INZONE_INTERVAL: '30 min', - CONF_STATIONARY_STILL_TIME: '8 min', - CONF_STATIONARY_ZONE_OFFSET: '1, 0', - CONF_EVENT_LOG_CARD_DIRECTORY: 'www/custom_cards', - CONF_DISPLAY_TEXT_AS: [], - } - -#============================================================================== -# -# SYSTEM LEVEL FUNCTIONS -# -#============================================================================== -def _combine_lists(parm_lists): - ''' - Take a list of lists and return a single list of all of the items. - [['a,b,c'],['d,e,f']] --> ['a','b','c','d','e','f'] - ''' - new_list = [] - for lists in parm_lists: - lists_items = lists.split(',') - for lists_item in lists_items: - new_list.append(lists_item) - - return new_list - -#-------------------------------------------------------------------- -def _test(parm1, parm2): - return f"{parm1}-{parm2}" - -#-------------------------------------------------------------------- -def TRACE(desc, v1='+++', v2='', v3='', v4='', v5=''): - ''' - Display a message or variable in the HA log file - ''' - if desc != '': - if v1 == '+++': - value_str = f"►TRACE►► {desc}" - else: - value_str = (f"►TRACE►► {desc} = |{v1}|-|{v2}|-" - f"|{v3}|-|{v4}|-|{v5}|") - _LOGGER.info(value_str) - -#-------------------------------------------------------------------- -def instr(string, find_string): - if find_string is None: - return False - else: - return str(string).find(find_string) >= 0 - -#-------------------------------------------------------------------- -def isnumber(string): - - try: - test_number = float(string) - - return True - except: - return False - -#-------------------------------------------------------------------- -def inlist(string, list_items): - for item in list_items: - if str(string).find(item) >= 0: - return True - - return False - -#-------------------------------------------------------------------- -def format_gps(latitude, longitude, accuracy, latitude_to=None, longitude_to=None): - '''Format the GPS string for logs & messages''' - - accuracy_text = (f"/{accuracy}m)") if accuracy > 0 else "" - gps_to_text = (f" to ({round(latitude_to, 6)}, {round(longitude_to, 6)})") if latitude_to else "" - gps_text = f"({round(latitude, 6)}, {round(longitude, 6)}){accuracy_text}{gps_to_text}" - return gps_text -#============================================================================== -# -# CREATE THE ICLOUD3 DEVICE TRACKER PLATFORM -# -#============================================================================== -def setup_scanner(hass, config: dict, see, discovery_info=None): - """Set up the iCloud3 Device Tracker""" - username = config.get(CONF_USERNAME) - password = config.get(CONF_PASSWORD) - group = config.get(CONF_GROUP) - base_zone = config.get(CONF_BASE_ZONE) - tracking_method = config.get(CONF_TRACKING_METHOD) - track_devices = config.get(CONF_TRACK_DEVICES) - track_devices.extend(config.get(CONF_TRACK_DEVICE)) - log_level = config.get(CONF_LOG_LEVEL) - device_status = config.get(CONF_DEVICE_STATUS) - entity_registry_file = config.get(CONF_ENTITY_REGISTRY_FILE) - config_ic3_file_name = config.get(CONF_CONFIG_IC3_FILE_NAME) - event_log_card_directory = config.get(CONF_EVENT_LOG_CARD_DIRECTORY) - iosapp_request_location_max_cnt = int(config.get(CONF_IOSAPP_REQUEST_LOC_MAX_CNT)) - legacy_mode = config.get(CONF_LEGACY_MODE) - display_text_as = config.get(CONF_DISPLAY_TEXT_AS) - - #make sure the same group is not specified in more than one platform. If so, - #append with a number - if group in ICLOUD3_GROUPS or group == 'group': - group = f"{group}{len(ICLOUD3_GROUPS)+1}" - ICLOUD3_GROUPS.append(group) - ICLOUD3_TRACKED_DEVICES[group] = track_devices - - #Changes in device_tracker entities are not supported in HA v0.94 and - #legacy code is being used for the DeviceScanner. Try to import from the - #.legacy directory and retry from the normal directory if the .legacy - #directory does not exist. - #try: - # if legacy_mode: - # from homeassistant.components.device_tracker.legacy import DeviceScanner - # else: - # from homeassistant.components.device_tracker import DeviceScanner - - # HA_DEVICE_TRACKER_LEGACY_MODE = legacy_mode - - #except ImportError: - # from homeassistant.components.device_tracker import DeviceScanner - # HA_DEVICE_TRACKER_LEGACY_MODE = False - - log_msg =(f"Setting up iCloud3 v{VERSION} device tracker for User: {username}, " - f"Group: {group}") - if HA_DEVICE_TRACKER_LEGACY_MODE: - log_msg = (f"{log_msg}, using device_tracker.legacy code") - _LOGGER.info(log_msg) - - inzone_interval_str = config.get(CONF_INZONE_INTERVAL) - max_interval_str = config.get(CONF_MAX_INTERVAL) - display_zone_fname = config.get(CONF_DISPLAY_ZONE_FNAME) - center_in_zone_flag = config.get(CONF_CENTER_IN_ZONE) - gps_accuracy_threshold = config.get(CONF_GPS_ACCURACY_THRESHOLD) - old_location_threshold_str = config.get(CONF_OLD_LOCATION_THRESHOLD) - ignore_gps_accuracy_inzone_flag = config.get(CONF_IGNORE_GPS_ACC_INZONE) - hide_gps_coordinates = config.get(CONF_HIDE_GPS_COORDINATES) - unit_of_measurement = config.get(CONF_UNIT_OF_MEASUREMENT) - time_format = config.get(CONF_TIME_FORMAT) - - stationary_inzone_interval_str = config.get(CONF_STATIONARY_INZONE_INTERVAL) - stationary_still_time_str = config.get(CONF_STATIONARY_STILL_TIME) - stationary_zone_offset = config.get(CONF_STATIONARY_ZONE_OFFSET) - - sensor_ids = _combine_lists(config.get(CONF_CREATE_SENSORS)) - exclude_sensor_ids = _combine_lists(config.get(CONF_EXCLUDE_SENSORS)) - - travel_time_factor = config.get(CONF_TRAVEL_TIME_FACTOR) - waze_realtime = config.get(CONF_WAZE_REALTIME) - distance_method = config.get(CONF_DISTANCE_METHOD).lower() - waze_region = config.get(CONF_WAZE_REGION) - waze_region = waze_region.upper() - waze_max_distance = config.get(CONF_WAZE_MAX_DISTANCE) - waze_min_distance = config.get(CONF_WAZE_MIN_DISTANCE) - - if waze_region not in WAZE_REGIONS: - log_msg = (f"Invalid Waze Region ({waze_region}). Valid Values are: " - "NA=US or North America, EU=Europe, IL=Isreal, AU=Australia") - _LOGGER.error(log_msg) - - waze_region = 'US' - waze_max_distance = 0 - waze_min_distance = 0 - -#--------------------------------------------- - ICLOUD3_GROUP_OBJS[group] = Icloud3( - hass, see, username, password, group, base_zone, - tracking_method, track_devices, - iosapp_request_location_max_cnt, inzone_interval_str, - max_interval_str, display_zone_fname, center_in_zone_flag, - gps_accuracy_threshold, old_location_threshold_str, - stationary_inzone_interval_str, stationary_still_time_str, - stationary_zone_offset, - ignore_gps_accuracy_inzone_flag, hide_gps_coordinates, - sensor_ids, exclude_sensor_ids, - unit_of_measurement, time_format, - travel_time_factor, distance_method, - waze_region, waze_realtime, waze_max_distance, waze_min_distance, - log_level, device_status, display_text_as, - entity_registry_file, config_ic3_file_name, event_log_card_directory - ) - - -#-------------------------------------------------------------------- - - def _service_callback_update_icloud(call): - """Call the update function of an iCloud group.""" - - groups = call.data.get(CONF_GROUP, ICLOUD3_GROUP_OBJS) - devicename = call.data.get(CONF_DEVICENAME) - command = call.data.get(CONF_COMMAND) - - for group in groups: - if group in ICLOUD3_GROUP_OBJS: - ICLOUD3_GROUP_OBJS[group]._service_handler_icloud_update( - group, devicename, command) - - hass.services.register(DOMAIN, 'icloud3_update', - _service_callback_update_icloud, schema=SERVICE_SCHEMA) - - -#-------------------------------------------------------------------- - def _service_callback__start_icloud3(call): - """Reset an iCloud group.""" - - groups = call.data.get(CONF_GROUP, ICLOUD3_GROUP_OBJS) - for group in groups: - if group in ICLOUD3_GROUP_OBJS: - ICLOUD3_GROUP_OBJS[group]._start_icloud3() - - hass.services.register(DOMAIN, 'icloud3_restart', - _service_callback__start_icloud3, schema=SERVICE_SCHEMA) - -#-------------------------------------------------------------------- - def _service_callback_setinterval(call): - """Call the setinterval function of an iCloud group.""" - - groups = call.data.get(CONF_GROUP, ICLOUD3_GROUP_OBJS) - interval = call.data.get(CONF_INTERVAL) - devicename = call.data.get(CONF_DEVICENAME) - - for group in groups: - if group in ICLOUD3_GROUP_OBJS: - ICLOUD3_GROUP_OBJS[group]._service_handler_icloud_setinterval( - group, interval, devicename) - - hass.services.register(DOMAIN, 'icloud3_set_interval', - _service_callback_setinterval, schema=SERVICE_SCHEMA) - -#-------------------------------------------------------------------- - def _service_callback_lost_iphone(call): - """Call the lost iPhone function if the device is found.""" - - groups = call.data.get(CONF_GROUP, ICLOUD3_GROUP_OBJS) - devicename = call.data.get(CONF_DEVICENAME) - - for group in groups: - if group in ICLOUD3_GROUP_OBJS: - ICLOUD3_GROUP_OBJS[group]._service_handler_lost_iphone( - group, devicename) - - hass.services.register(DOMAIN, 'icloud3_lost_iphone', - _service_callback_lost_iphone, schema=SERVICE_SCHEMA) - - # Tells the bootstrapper that the component was successfully initialized - return True - - -#==================================================================== -class Icloud3:#(DeviceScanner): - """Representation of an iCloud3 platform""" - - def __init__(self, - hass, see, username, password, group, base_zone, - tracking_method, track_devices, - iosapp_request_location_max_cnt, inzone_interval_str, - max_interval_str, display_zone_fname, center_in_zone_flag, - gps_accuracy_threshold, old_location_threshold_str, - stationary_inzone_interval_str, stationary_still_time_str, - stationary_zone_offset, - ignore_gps_accuracy_inzone_flag, hide_gps_coordinates, - sensor_ids, exclude_sensor_ids, - unit_of_measurement, time_format, - travel_time_factor, distance_method, - waze_region, waze_realtime, waze_max_distance, waze_min_distance, - log_level, device_status, display_text_as, - entity_registry_file, config_ic3_file_name, event_log_card_directory - ): - - - """Initialize the iCloud3 device tracker.""" - self.hass_configurator_request_id = {} - - self.hass = hass - self.see = see - self.username = username - self.username_base = username.split('@')[0] - self.password = password - - self.polling_5_sec_loop_running = False - self.api = None - self.entity_registry_file = entity_registry_file - self.config_ic3_file_name = config_ic3_file_name - self.event_log_card_directory = event_log_card_directory - self.group = group - self.base_zone = HOME - self.verification_inprocess_flag = False - self.verification_code = None - self.trusted_device = None - self.trusted_device_id = None - self.trusted_devices = None - self.tracking_method_config = tracking_method - - self.iosapp_request_loc_max_cnt= iosapp_request_location_max_cnt - self.start_icloud3_request_flag = False - self.start_icloud3_inprocess_flag = False - self.authenticated_time = 0 - self.log_level = log_level - self.log_level_eventlog_flag = False - self.device_status_online = list(device_status.replace(" ","").split(",")) - self.device_status_online.append('') - - self.attributes_initialized_flag = False - self.track_devices = track_devices - self.distance_method_waze_flag = (distance_method.lower() == 'waze') - self.inzone_interval_secs = self._time_str_to_secs(inzone_interval_str) - self.max_interval_secs = self._time_str_to_secs(max_interval_str) - self.display_zone_fname_flag = display_zone_fname - self.center_in_zone_flag = center_in_zone_flag - self.gps_accuracy_threshold = int(gps_accuracy_threshold) - self.old_location_threshold = self._time_str_to_secs(old_location_threshold_str) - self.ignore_gps_accuracy_inzone_flag = ignore_gps_accuracy_inzone_flag - self.check_gps_accuracy_inzone_flag = not self.ignore_gps_accuracy_inzone_flag - self.hide_gps_coordinates = hide_gps_coordinates - self.sensor_ids = sensor_ids - self.exclude_sensor_ids = exclude_sensor_ids - self.unit_of_measurement = unit_of_measurement - self.time_format = int(time_format) - self.travel_time_factor = float(travel_time_factor) - self.e_seconds_local_offset_secs = 0 - self.waze_region = waze_region - self.waze_min_distance = waze_min_distance - self.waze_max_distance = waze_max_distance - self.waze_realtime = waze_realtime - self.stationary_inzone_interval_str = stationary_inzone_interval_str - self.stationary_still_time_str = stationary_still_time_str - self.stationary_zone_offset = stationary_zone_offset - - self.display_text_as = display_text_as - self.display_text_as_list = {} - - - #define & initialize fields to carry across icloud3 restarts - self._define_event_log_fields() - self._define_usage_counters() - self._define_iosapp_message_fields() - - #add HA event that will call the _polling_loop_5_sec_icloud function - #on a 5-second interval. The interval is offset by 1-second for each - #group to avoid update conflicts. - self.start_icloud3_initial_load_flag = True - self._start_icloud3() - - self.start_icloud3_initial_load_flag = False -#-------------------------------------------------------------------- - def _start_icloud3(self): - """ - Start iCloud3, Define all variables & tables, Initialize devices - """ - - #check to see if restart is in process - if self.start_icloud3_inprocess_flag: - return - - try: - self.start_timer = time.time() - self._initialize_debug_control(self.log_level) - - self.start_icloud3_inprocess_flag = True - self.start_icloud3_request_flag = False - self.initial_locate_complete_flag = False - self.startup_log_msgs = '' - self.startup_log_msgs_prefix = '' - devicename = '' - - self._define_device_fields() - self._define_device_status_fields() - self._define_device_tracking_fields() - self._define_zone_fields() - self._define_device_zone_fields() - self._define_tracking_control_fields() - self._define_sensor_fields(self.start_icloud3_initial_load_flag) - self._setup_tracking_method(self.tracking_method_config) - - event_msg = (f"^^^ Initializing iCloud3 v{VERSION} > " - f"{dt_util.now().strftime('%A, %b %d')}") - self._save_event_halog_info("*", event_msg) - - self.startup_log_msgs_prefix = NEW_LINE - self._check_config_ic3_yaml_parameter_file() - self._check_ic3_event_log_file_version() - self._initialize_um_formats(self.unit_of_measurement) - - for item in self.display_text_as: - from_to_text = item.split(">") - self.display_text_as_list[from_to_text[0].strip()] = from_to_text[1].strip() - - event_msg = (f"Stage 1 > Prepare iCloud3 for {self.username}") - self._save_event_halog_info("*", event_msg) - - self._display_info_status_msg("", "Loading conf_ic3.yaml") - - self._display_info_status_msg("", "Loading Zones") - self._initialize_zone_tables() - self._define_stationary_zone_fields(self.stationary_inzone_interval_str, - self.stationary_still_time_str) - - self._display_info_status_msg("", "Initializing Waze Route Tracker") - self._initialize_waze_fields(self.waze_region, self.waze_min_distance, - self.waze_max_distance, self.waze_realtime) - - for devicename_cnt in self.count_update_iosapp: - self._display_usage_counts(devicename_cnt) - - except Exception as err: - _LOGGER.exception(err) - - try: - self.startup_log_msgs_prefix = NEW_LINE - self._update_sensor_ic3_event_log("") - event_msg = (f"Stage 2 > Set up tracking method & identify devices") - self._save_event_halog_info("*", event_msg) - - event_msg = (f"Preparing Tracking Method > {self.trk_method_name}") - self._save_event_halog_info("*", event_msg) - - self._display_info_status_msg("", "Setting up Tracked Devices") - self._setup_tracked_devices_config_parm(self.track_devices) - - self.this_update_secs = self._time_now_secs() - self.icloud3_started_secs = self.this_update_secs - - if self.CONF_TRK_METHOD_FMF_FAMSHR: - event_msg = (f"Stage 2a > Authenticating iCloud Account, Extract devices") - self._save_event_halog_info("*", event_msg) - self._display_info_status_msg("", "Authenticating iCloud Account") - self._pyicloud_initialize_device_api() - - if self.api: - if self.TRK_METHOD_FMF: - self._setup_tracked_devices_for_fmf() - - elif self.TRK_METHOD_FAMSHR: - self._setup_tracked_devices_for_famshr() - - elif self.CONF_TRK_METHOD_FMF_FAMSHR: - event_msg = (f"iCloud3 Error > iCloud Account Authentication needed > " - f"Will use iOS App Tracking Method until the iCloud " - f"account is authentication is complete. See the HA " - f"Notification area to continue. iCloud3 will then be restarted.") - self._save_event_halog_info("*", event_msg) - - if self.TRK_METHOD_IOSAPP: - if self.CONF_TRK_METHOD_FMF_FAMSHR: - event_msg = (f"{EVLOG_ALERT}iCloud Alert > FmF or FamShr Tracking Method is disabled until " - f"Verification has been completed. iOS App Trackimg Method " - f"wil be used.") - self._save_event_halog_info("*", event_msg) - event_msg = (f"Stage 2b > Setup iOS App Tracking Method") - self._save_event_halog_info("*", event_msg) - self._setup_tracked_devices_for_iosapp() - - except Exception as err: - _LOGGER.exception(err) - - try: - self.startup_log_msgs_prefix = NEW_LINE - self._update_sensor_ic3_event_log("") - event_msg = (f"Stage 3 > Identify iOS App entities, Verify tracked devices") - self._save_event_halog_info("*", event_msg) - - iosapp_entities = self._get_entity_registry_entities('mobile_app') - notify_devicenames = self._get_mobile_app_notify_devicenames() - - self.track_devicename_list == '' - for devicename in self.devicename_verified: - error_log_msg = None - self._display_info_status_msg(devicename, "Verifing Device") - - #Devicename config parameter is OK, now check to make sure the - #entity for device name has been setup by iosapp correctly. - #If the devicename is valid, it will be tracked - self._initialize_iosapp_message_fields(devicename) - if self.devicename_verified.get(devicename): - self.tracking_device_flag[devicename] = True - self.tracked_devices.append(devicename) - - self.track_devicename_list = (f"{self.track_devicename_list}, {devicename}") - if self.iosapp_monitor_dev_trk_flag.get(devicename): - self._setup_monitored_iosapp_entities(devicename, iosapp_entities, - notify_devicenames, self.devicename_iosapp_suffix.get(devicename)) - - self.track_devicename_list = (f"{self.track_devicename_list} " - f"({self.devicename_iosapp_entity.get(devicename).replace(devicename, ' ... ')})") - - event_msg = (f"Verified Device > {self._format_fname_devicename(devicename)}") - self._save_event_halog_info("*", event_msg) - self._display_info_status_msg(devicename, "Verified Device") - - if self.iosapp_monitor_dev_trk_flag.get(devicename): - event_msg = (f"iOS App monitoring > {self._format_fname_devicename(devicename)} > " - f"CRLF• device_tracker.{self.devicename_iosapp_entity.get(devicename)}, " - f"CRLF• sensor.{self.iosapp_last_trigger_entity.get(devicename)}") - self._save_event_halog_info("*", event_msg) - - event_msg = (f"iOS App location requests sent to > {self._format_fname_devicename(devicename)} > " - f"{self._format_list(self.notify_iosapp_entity.get(devicename))}") - self._save_event_halog_info("*", event_msg) - - #Send a message to all devices during startup - if self.broadcast_msg != '': - self._send_message_to_device(devicename, self.broadcast_msg) - else: - event_msg = (f"iOS App monitoring > device_tracker.{devicename}") - self._save_event_halog_info("*", event_msg) - - #If the devicename is not valid & verified, it will not be tracked - else: - if self.TRK_METHOD_FAMSHR: - event_msg = (f"iCloud3 Error for {self._format_fname_devicename(devicename)}/{devicename} > " - f"The iCloud Account for {self.username} did not return any " - f"device information for this device when setting up " - f"{self.trk_method_name}." - f"CRLF{'-'*25}" - f"CRLF 1. Restart iCloud3 on the Event_log " - f"screen or restart HA." - f"CRLF 2. Verify the devicename on the track_devices " - f"parameter if the error persists." - f"CRLF 3. Refresh the Event Log in your " - f"browser to refresh the list of devices.") - self._save_event_halog_error("*", event_msg) - - event_msg = (f"Not Tracking Device > " - f"{self._format_fname_devicename(devicename)}") - self._save_event_halog_info("*", event_msg) - - #Reset msg sent to all devices during startup - self.broadcast_msg = '' - - #Now that the devices have been set up, finish setting up - #the Event Log Sensor - self._setup_event_log_base_attrs(self.start_icloud3_initial_load_flag) - self._setup_sensors_custom_list(self.start_icloud3_initial_load_flag) - self._display_info_status_msg(devicename, "Define Sensors") - - #nothing to do if no devices to track - if self.track_devicename_list == '': - event_msg = (f"iCloud3 Error for {self.username} > No devices to track. " - f"Setup aborted. Check `track_devices` parameter and verify the " - f"device name matches the iPhone Name on the `Settings>General>About` " - f"screen on the devices to be tracked.") - self._save_event_halog_error("*", event_msg) - - self._update_sensor_ic3_event_log("*") - self.start_icloud3_inprocess_flag = False - return False - - self.track_devicename_list = (f"{self.track_devicename_list[1:]}") - event_msg = (f"Tracking Devices > " - f"CRLF• {self.track_devicename_list.replace(', ','CRLF• ')}") - self._save_event_halog_info("*", event_msg) - - self.startup_log_msgs_prefix = NEW_LINE - self._update_sensor_ic3_event_log("*") - event_msg = (f"Stage 4 > Configure tracked devices") - self._save_event_halog_info("*", event_msg) - - for devicename in self.tracked_devices: - event_msg = (f"Configuring Device > {self._format_fname_devicename(devicename)}") - - if len(self.track_from_zone.get(devicename)) > 1: - w = str(self.track_from_zone.get(devicename)) - w = w.replace("[", "") - w = w.replace("]", "") - w = w.replace("'", "") - event_msg += (f"CRLF• Track from zones > {w}") - - event_msg += self._display_info_status_msg(devicename, "Initialize Tracking Fields") - self._initialize_device_status_fields(devicename) - self._initialize_device_tracking_fields(devicename) - self._initialize_usage_counters(devicename, self.start_icloud3_initial_load_flag) - event_msg += self._display_info_status_msg(devicename, "Initialize Zones") - self._initialize_device_zone_fields(devicename) - event_msg += self._display_info_status_msg(devicename, - f"Initialize Stationary Zone > {self._format_zone_name(devicename, STATIONARY)}") - self._update_stationary_zone( - devicename, - self.stat_zone_base_lat, - self.stat_zone_base_long, - STAT_ZONE_MOVE_TO_BASE) - - #Initialize the new attributes - event_msg += self._display_info_status_msg(devicename, "Update HA Device Entities") - - iosapp_data_flag = False - if self.iosapp_monitor_dev_trk_flag.get(devicename): - iosapp_state, iosapp_dev_attrs, iosapp_data_flag = \ - self._get_iosapp_device_tracker_state_attributes( - devicename, HOME, {}) - - if iosapp_data_flag: - initial_lat = iosapp_dev_attrs[ATTR_LATITUDE] - initial_long = iosapp_dev_attrs[ATTR_LONGITUDE] - else: - initial_lat = self.zone_home_lat - initial_long = self.zone_home_long - - kwargs = self._setup_base_kwargs( - devicename, - initial_lat, - initial_long, - 0, 0) - - attrs = self._initialize_attrs(devicename) - self._update_device_attributes(devicename, kwargs, attrs, '_start_icloud3') - - if devicename not in self.sensor_prefix_name: - event_msg += self._setup_sensor_base_attrs(devicename) - - event_msg += self._display_info_status_msg(devicename, "Initialize Sensor Fields") - self._update_device_sensors(devicename, kwargs) - self._update_device_sensors(devicename, attrs) - - self._save_event_halog_info("*", event_msg) - - self._display_info_status_msg(devicename, "Initialize Event Log") - self._save_event_halog_info("*", "Initialize Event Log Sensor") - - except Exception as err: - _LOGGER.exception(err) - - for devicename in self.tracked_devices: - if self.log_level_debug_flag or self.log_level_eventlog_flag: - self._display_usage_counts(devicename, force_display=(not self.start_icloud3_initial_load_flag)) - - self.startup_log_msgs_prefix = NEW_LINE - self._update_sensor_ic3_event_log("*") - event_msg = (f"^^^ Initializing iCloud3 v{VERSION} > Complete, " - f"Took {round(time.time()-self.start_timer, 2)} sec") - self._save_event_halog_info("*", event_msg) - self._display_info_status_msg(devicename, "Setup Complete, Locating Devices") - self._update_sensor_ic3_event_log("*") - - self.start_icloud3_inprocess_flag = False - - if self.log_level_debug_flag == False: - self.startup_log_msgs = (NEW_LINE + '-'*55 + - self.startup_log_msgs.replace("CRLF", NEW_LINE) + - NEW_LINE + '-'*55) - _LOGGER.info(self.startup_log_msgs) - self.startup_log_msgs = '' - - if self.polling_5_sec_loop_running == False: - self.polling_5_sec_loop_running = True - track_utc_time_change(self.hass, self._polling_loop_5_sec_device, - second=[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55]) - - return True - -######################################################### -# -# This function is called every 5 seconds by HA. Cycle through all -# of the iCloud devices to see if any of the ones being tracked need -# to be updated. If so, we might as well update the information for -# all of the devices being tracked since PyiCloud gets data for -# every device in the account -# -######################################################### - def _polling_loop_5_sec_device(self, now): - try: - fct_name = "_polling_loop_5_sec_device" - - if self.start_icloud3_request_flag: #via service call - self._start_icloud3() - - if (self.any_device_being_updated_flag - or self.start_icloud3_inprocess_flag): - return - - except Exception as err: - _LOGGER.exception(err) - return - - self.this_update_secs = self._time_now_secs() - self.this_update_time = dt_util.now().strftime('%H:%M:%S') - this_minute = int(dt_util.now().strftime('%M')) - this_5sec_loop_second = int(dt_util.now().strftime('%S')) - - #Reset counts on new day, check for daylight saving time new offset - if self.this_update_time.endswith(':00:00'): - self._timer_tasks_every_hour() - - if self.this_update_time == HHMMSS_ZERO: - self._timer_tasks_midnight() - - elif self.this_update_time == '01:00:00': - self._timer_tasks_1am() - - #Test code to check ios monitor, display it every minute - #if self.this_update_time.endswith(':00'): - # self.last_iosapp_msg['gary_iphone'] = "" - - try: - if self.this_update_secs >= self.event_log_clear_secs and \ - self.log_level_debug_flag == False: - self._update_sensor_ic3_event_log('clear_log_items') - - if self.this_update_secs >= self.authentication_error_retry_secs: - self._pyicloud_authenticate_account() - - for devicename in self.tracked_devices: - devicename_zone = self._format_devicename_zone(devicename, HOME) - - if (self.tracking_device_flag.get(devicename) is False - or self.next_update_time.get(devicename_zone) == PAUSED): - continue - - update_method = None - self.state_change_flag[devicename] = False - - if self.state_last_poll.get(devicename) == NOT_SET: - self._display_info_status_msg(devicename, "Getting Initial Device State/Triggers") - - #get tracked_device (device_tracker.) state & attributes - #icloud & ios app v1 use this entity - ic3_entity_id = self.device_tracker_entity_ic3.get(devicename) - ic3dev_state = self._get_state(ic3_entity_id) - - #Will be not_set with a last_poll value if the iosapp has not be set up - if (ic3dev_state == NOT_SET - and self.state_last_poll.get(devicename) != NOT_SET): - event_msg = "iOSApp state will be updated after iOSApp starts" - self._save_event(devicename,event_msg) - continue - - #Extract only attrs needed to update the device - ic3dev_attrs = self._get_device_attributes(ic3_entity_id) - ic3dev_attrs_avail = {k: v for k, v in ic3dev_attrs.items() if k in DEVICE_ATTRS_BASE} - ic3dev_data = {**DEVICE_ATTRS_BASE, **ic3dev_attrs_avail} - - ic3dev_latitude = ic3dev_data[ATTR_LATITUDE] - ic3dev_longitude = ic3dev_data[ATTR_LONGITUDE] - ic3dev_gps_accuracy = ic3dev_data[ATTR_GPS_ACCURACY] - ic3dev_battery = ic3dev_data[ATTR_BATTERY_LEVEL] - ic3dev_trigger = ic3dev_data[ATTR_TRIGGER] - ic3dev_timestamp_secs = self._timestamp_to_secs(ic3dev_data[ATTR_TIMESTAMP]) - iosapp_state = ic3dev_state - iosapp_dev_attrs = {ATTR_LATITUDE: ic3dev_latitude, - ATTR_LONGITUDE: ic3dev_longitude, - ATTR_GPS_ACCURACY: ic3dev_gps_accuracy, - ATTR_BATTERY_LEVEL: ic3dev_battery} - - #iosapp uses the device_tracker._# entity for - #location info and sensor._last_update_trigger entity - #for trigger info. Get location data and trigger. - #Use the trigger/timestamp if timestamp is newer than current - #location timestamp. - - update_reason = "" - ios_update_reason = "" - update_via_iosapp_flag = False - last_located_secs_plus_5 = self.last_located_secs.get(devicename) + 5 - - if self.iosapp_monitor_dev_trk_flag.get(devicename): - iosapp_state, iosapp_dev_attrs, iosapp_data_flag = \ - self._get_iosapp_device_tracker_state_attributes( - devicename, iosapp_state, iosapp_dev_attrs) - - if iosapp_data_flag == False and self.iosapp_monitor_error_cnt.get(devicename) > 120: - self.iosapp_monitor_error_cnt[devicename] = 0 - event_msg = (f"iOS App data not available, iCloud data used") - self._save_event(devicename, event_msg) - - entity_id = self.device_tracker_entity_iosapp.get(devicename) - iosapp_state_changed_time, iosapp_state_changed_secs, iosapp_state_changed_timestamp, \ - iosapp_state_age_secs, iosapp_state_age_str = \ - self._get_entity_last_changed_time(entity_id, devicename) - - iosapp_trigger, iosapp_trigger_changed_time, iosapp_trigger_changed_secs, \ - iosapp_trigger_age_secs, iosapp_trigger_age_str = \ - self._get_iosapp_device_sensor_trigger(devicename) - - iosapp_data_msg = "" if iosapp_data_flag else "(Using iC3 data) " - iosapp_msg = (f"iOSApp Monitor {iosapp_data_msg}> " - f"Trigger-{iosapp_trigger}@{iosapp_trigger_changed_time} (%tage ago), " - f"State-{iosapp_state}@{iosapp_state_changed_time} (%sage ago), " - f"GPS-{format_gps(iosapp_dev_attrs[ATTR_LATITUDE], iosapp_dev_attrs[ATTR_LONGITUDE], iosapp_dev_attrs[ATTR_GPS_ACCURACY])}, " - f"LastiC3UpdtTime-{self.last_update_time.get(devicename_zone)}, ") - - #Initialize if first time through - if self.last_iosapp_trigger.get(devicename) == '': - self.last_iosapp_state[devicename] = iosapp_state - self.last_iosapp_state_changed_time[devicename] = iosapp_state_changed_time - self.last_iosapp_state_changed_secs[devicename] = iosapp_state_changed_secs - self.last_iosapp_trigger[devicename] = iosapp_trigger - self.last_iosapp_trigger_changed_time[devicename] = iosapp_trigger_changed_time - self.last_iosapp_trigger_changed_secs[devicename] = iosapp_trigger_changed_secs - - if self.TRK_METHOD_IOSAPP: - update_via_iosapp_flag = True - ios_update_reason = "Initial Locate" - - if iosapp_data_flag == False: - update_via_iosapp_flag = False - ios_update_reason = "No data received from the iOS App, using iC3 data" - - elif (iosapp_state == NOT_SET - and self.iosapp_request_loc_retry_cnt.get(devicename) == 0): - update_via_iosapp_flag = True - ios_update_reason = "Reinitialize iOSApp location" - - elif (instr(iosapp_state, STATIONARY) - and iosapp_dev_attrs[ATTR_LATITUDE] == self.stat_zone_base_lat - and iosapp_dev_attrs[ATTR_LONGITUDE] == self.stat_zone_base_long): - ios_update_reason = "Stat Zone Base Locatioon" - - #State changed - elif iosapp_state != self.last_iosapp_state.get(devicename): - update_via_iosapp_flag = True - ios_update_reason = (f"State Change-{iosapp_state}") - - #trigger time is after last locate - #elif iosapp_trigger_changed_secs > (self.last_located_secs.get(devicename) + 5): - elif iosapp_trigger_changed_secs > last_located_secs_plus_5: - update_via_iosapp_flag = True - ios_update_reason = (f"Trigger Change-{iosapp_trigger}") - - #State changed more than 5-secs after last locate - #elif iosapp_state_changed_secs > (self.last_located_secs.get(devicename) + 5): - elif iosapp_state_changed_secs > last_located_secs_plus_5: - update_via_iosapp_flag = True - iosapp_trigger = "iOSApp Loc Update" - iosapp_trigger_changed_secs = iosapp_state_changed_secs - ios_update_reason = (f"iOSApp Loc Update@{iosapp_state_changed_time}") - - #Prevent duplicate update if State & Trigger changed at the same time - #and state change was handled on last cycle - elif (iosapp_trigger_changed_secs == iosapp_state_changed_secs - or iosapp_trigger_changed_secs <= last_located_secs_plus_5): - # or iosapp_trigger_changed_secs <= (self.last_located_secs.get(devicename) + 5)): - self.last_iosapp_trigger[devicename] = iosapp_trigger - ios_update_reason = "Already Processed" - - #Trigger changed more than 5-secs after last trigger - elif (iosapp_trigger_changed_secs > (self.last_iosapp_trigger_changed_secs.get(devicename) + 5)): - update_via_iosapp_flag = True - ios_update_reason = (f"Trigger Time@{self._secs_to_time(iosapp_trigger_changed_secs)}") - - #Bypass if trigger contains ic3 date stamp suffix (@hhmmss) - elif instr(iosapp_trigger, '@'): - ios_update_reason = "Trigger Already Processed" - - #elif iosapp_trigger_changed_secs <= (self.last_located_secs.get(devicename) + 5): - elif iosapp_trigger_changed_secs <= last_located_secs_plus_5: - ios_update_reason = "Trigger Before Last Locate" - - else: - ios_update_reason = "Failed Update Tests" - - iosapp_msg += (f"WillUpdate-{update_via_iosapp_flag}") - - #Show iOS App monitor every half hour - if self.this_update_time.endswith(':00:00') or self.this_update_time.endswith(':30:00'): - self.last_iosapp_msg[devicename] = "" - - if (iosapp_msg != self.last_iosapp_msg.get(devicename)): - self.last_iosapp_msg[devicename] = iosapp_msg - - iosapp_msg = iosapp_msg.replace("%tage", iosapp_trigger_age_str) - iosapp_msg = iosapp_msg.replace("%sage", iosapp_state_age_str) - iosapp_msg += (f", {ios_update_reason}") - self._log_debug_msg(devicename, iosapp_msg) - self._evlog_debug_msg(devicename, iosapp_msg) - - #This devicename is entering a zone also assigned to another device. The ios app - #will move issue a Region Entered trigger and the state is the other devicename's - #stat zone name. Create this device's stat zone at the current location to get the - #zone tables in sync. Must do this before processing the state/trigger change or - #this devicename will use this trigger to start a timer rather than moving it ineo - #the stat zone. - if update_via_iosapp_flag: - if (iosapp_trigger in IOS_TRIGGERS_ENTER): - if (instr(iosapp_state, STATIONARY) - and instr(iosapp_state, devicename) == False - and self.in_stationary_zone_flag.get(devicename) == False): - - event_msg = (f"Stationary Zone Entered > iOS App used another device's " - f"Stationary Zone, changed {iosapp_state} to " - f"{self._format_zone_name(devicename, STATIONARY)}") - self._save_event(devicename, event_msg) - - latitude = self.zone_lat.get(iosapp_state) - longitude = self.zone_long.get(iosapp_state) - - self._update_stationary_zone( - devicename, - latitude, - longitude, - STAT_ZONE_NEW_LOCATION, 'poll 5-EnterTrigger') - - iosapp_state = self._format_zone_name(devicename, STATIONARY) - - elif (iosapp_trigger in IOS_TRIGGERS_EXIT): - if (self.in_stationary_zone_flag.get(devicename)): - self._update_stationary_zone( - devicename, - self.stat_zone_base_lat, - self.stat_zone_base_long, - STAT_ZONE_MOVE_TO_BASE, 'poll 5-ExitTrigger') - - #Discard another devices Stationary Zone triggers - #if instr(iosapp_state, STATIONARY) and instr(iosapp_state, devicename) == False: - # continue - - if instr(iosapp_state, STATIONARY): - iosapp_state = STATIONARY - - #---------------------------------------------------------------------------- - ic3dev_battery = self._get_attr(iosapp_dev_attrs, ATTR_BATTERY_LEVEL, NUMERIC) - self.last_battery[devicename] = ic3dev_battery - - if update_via_iosapp_flag: - iosapp_trigger_age_secs = self._secs_since(iosapp_trigger_changed_secs) - age = iosapp_trigger_changed_secs - self.this_update_secs - ic3dev_state = iosapp_state - ic3dev_latitude = iosapp_dev_attrs[ATTR_LATITUDE] - ic3dev_longitude = iosapp_dev_attrs[ATTR_LONGITUDE] - ic3dev_gps_accuracy = iosapp_dev_attrs[ATTR_GPS_ACCURACY] - ic3dev_trigger = iosapp_trigger - ic3dev_timestamp_secs = iosapp_trigger_changed_secs - ic3dev_data[ATTR_LATITUDE] = ic3dev_latitude - ic3dev_data[ATTR_LONGITUDE] = ic3dev_longitude - ic3dev_data[ATTR_TIMESTAMP] = iosapp_state_changed_timestamp - ic3dev_data[ATTR_GPS_ACCURACY] = ic3dev_gps_accuracy - ic3dev_data[ATTR_BATTERY_LEVEL] = ic3dev_battery - ic3dev_data[ATTR_ALTITUDE] = self._get_attr(iosapp_dev_attrs, ATTR_ALTITUDE, NUMERIC) - ic3dev_data[ATTR_VERT_ACCURACY] = self._get_attr(iosapp_dev_attrs, ATTR_VERT_ACCURACY, NUMERIC) - - self.last_iosapp_state[devicename] = iosapp_state - self.last_iosapp_state_changed_time[devicename] = iosapp_state_changed_time - self.last_iosapp_state_changed_secs[devicename] = iosapp_state_changed_secs - self.last_iosapp_trigger[devicename] = iosapp_trigger - self.last_iosapp_trigger_changed_time[devicename] = iosapp_trigger_changed_time - self.last_iosapp_trigger_changed_secs[devicename] = iosapp_trigger_changed_secs - - #Check ios app for activity every 6-hours - #Issue ios app Location update 15-min before 6-hour alert - elif (self.this_update_time in ['23:45:00', '05:45:00', '11:45:00', '17:45:00'] - and iosapp_state_age_secs > 20700 - and iosapp_trigger_age_secs > 20700): - self._iosapp_request_loc_update(devicename) - - #No activity, display Alert msg in Event Log - elif (self.this_update_time in ['00:00:00', '06:00:00', '12:00:00', '18:00:00'] - and iosapp_state_age_secs > 21600 - and iosapp_trigger_age_secs > 21600): - event_msg = (f"{EVLOG_ALERT}iOS App Alert > No iOS App updates for more than 6 hours > " - f"Device-{self.device_tracker_entity_iosapp.get(devicename)}, " - f"LastTrigger-{iosapp_trigger}@{iosapp_trigger_changed_time} ({iosapp_trigger_age_str}), " - f"LastState-{iosapp_state}@{iosapp_state_changed_time} ({iosapp_state_age_str})") - self._save_event_halog_info(devicename, event_msg) - event_msg = (f"Last iOS App update from {self.device_tracker_entity_iosapp.get(devicename)}" - f"—{iosapp_trigger_age_str} ago") - self._display_info_status_msg(devicename, event_msg) - - zone = self._format_zone_name(devicename, ic3dev_state) - event_msg = "" - update_reason = "" - - dist_from_zone_m = self._zone_distance_m( - devicename, - zone, - ic3dev_latitude, - ic3dev_longitude) - - dist_from_home_m = self._zone_distance_m( - devicename, - HOME, - ic3dev_latitude, - ic3dev_longitude) - - zone_radius_m = self.zone_radius_m.get( - zone, - self.zone_radius_m.get(HOME)) - zone_radius_accuracy_m = zone_radius_m + self.gps_accuracy_threshold - - if (self.TRK_METHOD_IOSAPP and self.zone_current.get(devicename) == ''): - update_method = IOSAPP_UPDATE - update_reason = "Initial Locate" - - #device_tracker.see svc call from automation wipes out - #latitude and longitude. Reset via icloud update. - elif ic3dev_latitude == 0: - update_method = ICLOUD_UPDATE - update_reason = (f"GPS=(0, 0) {self.state_last_poll.get(devicename)}/{ic3dev_state}") - ic3dev_trigger = "RefreshLocation" - device_offline_msg = (f"May be Offline, No Location " - f"(#{self.poor_location_gps_cnt.get(devicename)})") - self._display_info_status_msg(devicename, device_offline_msg) - self._save_event(devicename,device_offline_msg) - - #Update the device if it wasn't completed last time. - elif self.state_last_poll.get(devicename) == NOT_SET: - update_method = ICLOUD_UPDATE - ic3dev_trigger = update_reason = "Initial Locate" - self._display_info_status_msg(devicename, "Locating Device via iCloud") - - #If the state changed since last time and it was a trigger - #related to another Stationary Zone, discard it. - elif (ic3dev_state != self.state_last_poll.get(devicename) - and ic3dev_state != STATIONARY - and instr(ic3dev_state, STATIONARY) - and instr(ic3dev_state, devicename) == False): - update_method = None - update_reason = "Other Device StatZone" - event_msg = (f"Discarded > Another device's Stationary Zone trigger detected, " - f"Zone-{ic3dev_state}") - self._save_event(devicename, event_msg) - - elif (self.stat_zone_timer.get(devicename, 0) > 0 - and self.this_update_secs >= self.stat_zone_timer.get(devicename) - and self.poor_location_gps_cnt.get(devicename) == 0): - event_msg = (f"Move into Stationary Zone Timer reached > {devicename}, " - f"Expired-{self._secs_to_time(self.stat_zone_timer.get(devicename, -1))}") - self._save_event(devicename, event_msg) - - update_method = ICLOUD_UPDATE - ic3dev_trigger = "MoveIntoStatZone" - update_reason = "Move into Stat Zone " - - #The state can be changed via device_tracker.see service call - #with a different location_name in an automation or by an - #ios app notification that a zone is entered or exited. If - #by the ios app, the trigger is 'Geographic Region Exited' or - #'Geographic Region Entered'. In iosapp 2.0, the state is - #changed without a trigger being posted and will be picked - #up here anyway. - elif (ic3dev_state != self.state_last_poll.get(devicename) - and ic3dev_timestamp_secs > last_located_secs_plus_5): - self.count_state_changed[devicename] += 1 - self.state_change_flag[devicename] = True - update_method = IOSAPP_UPDATE - update_reason = "State Change" - event_msg = (f"iOSApp State Change detected > " - f"{self.state_last_poll.get(devicename)} to {ic3dev_state}") - self._save_event(devicename, event_msg) - - elif (ic3dev_trigger != self.trigger.get(devicename) - and instr(iosapp_state, STATIONARY) - and iosapp_dev_attrs[ATTR_LATITUDE] == self.stat_zone_base_lat - and iosapp_dev_attrs[ATTR_LONGITUDE] == self.stat_zone_base_long): - update_method = ICLOUD_UPDATE - update_reason = "Verify Location" - event_msg = (f"Discarded > Entering Stationary Base Zone") - self._save_event(devicename, event_msg) - - elif (ic3dev_trigger != self.trigger.get(devicename) - and ic3dev_timestamp_secs > last_located_secs_plus_5): - update_method = IOSAPP_UPDATE - self.count_trigger_changed[devicename] += 1 - update_reason = "Trigger Change" - event_msg = (f"iOSApp Trigger Change detected > {ic3dev_trigger}") - self._save_event(devicename, event_msg) - - #If iOS App tracking and next update time reached and message not sent, request location. iOS App should respond within 20-seconds and create a Location Request - #trigger. Do this 4-times and then display message and wait. - elif (self.TRK_METHOD_IOSAPP - and self._check_next_update_time_reached_devicename(devicename)): - self._iosapp_request_loc_update(devicename) - - else: - update_reason = f"OlderTrigger-{ic3dev_trigger}" - - if (self.TRK_METHOD_IOSAPP - and update_method == ICLOUD_UPDATE): - update_method = IOSAPP_UPDATE - - #Update because of state or trigger change. - #Accept the location data as it was sent by ios if the trigger - #is for zone enter, exit, manual or push notification, - #or if the last trigger was already handled by ic3 ( an '@hhmmss' - #was added to it. - #If the trigger was sometning else (Significant Location Change, - #Background Fetch, etc, check to make sure it is not old or - #has poor gps info. - if (update_method == IOSAPP_UPDATE - or update_method == ICLOUD_UPDATE and self.TRK_METHOD_IOSAPP): - self.iosapp_request_loc_sent_flag[devicename] = False - - #If exit trigger flag is not set, set it now if Exiting zone - #If already set, leave it alone and reset when enter Zone (v2.1x) - if self.got_exit_trigger_flag.get(devicename) == False: - self.got_exit_trigger_flag[devicename] = (ic3dev_trigger in IOS_TRIGGERS_EXIT) - - if ic3dev_trigger in IOS_TRIGGERS_ENTER: - if (zone in self.zone_lat - and dist_from_zone_m > self.zone_radius_m.get(zone)*2 - and dist_from_zone_m < HIGH_INTEGER): - event_msg = (f"Enter Zone Trigger Conflict Moving into Zone > " - f"Zone-{zone}, Distance-{dist_from_zone_m}m, " - f"ZoneVerifyDist-{self.zone_radius_m.get(zone)*2}m, " - f"GPS-{format_gps(ic3dev_latitude, ic3dev_longitude, ic3dev_gps_accuracy)}") - self._save_event_halog_info(devicename, event_msg) - - ic3dev_latitude = self.zone_lat.get(zone) - ic3dev_longitude = self.zone_long.get(zone) - ic3dev_data[ATTR_LATITUDE] = ic3dev_latitude - ic3dev_data[ATTR_LONGITUDE] = ic3dev_longitude - - #RegionExit trigger overrules old location, gps accuracy and other checks - elif (ic3dev_trigger in IOS_TRIGGERS_EXIT - and ic3dev_timestamp_secs > last_located_secs_plus_5): - update_method = IOSAPP_UPDATE - update_reason = "Region Exit" - - #Check info if Background Fetch, Significant Location Update, - #Push, Manual, Initial - #elif (ic3dev_trigger in IOS_TRIGGERS_VERIFY_LOCATION): - #If not an enter/exit trigger, verify the location - elif (ic3dev_trigger not in IOS_TRIGGERS_ENTER_EXIT): - poor_location_gps_flag, discard_reason = self._check_poor_location_gps( - devicename, - ic3dev_timestamp_secs, - ic3dev_gps_accuracy) - - #If old location, discard - if poor_location_gps_flag: - location_age = self._secs_since(ic3dev_timestamp_secs) - event_msg = (f"Old Location or Poor GPS " - f"(#{self.poor_location_gps_cnt.get(devicename)}) > " - f"Located-{self._secs_to_time(ic3dev_timestamp_secs)} " - f"({self._format_age(location_age)}), " - f"GPS-{format_gps(ic3dev_latitude, ic3dev_longitude, ic3dev_gps_accuracy)}, " - f"OldLocThreshold-{self._secs_to_time_str(self.old_location_secs.get(devicename))}") - - self._save_event(devicename, event_msg) - update_method = ICLOUD_UPDATE - update_reason = "OldLoc PoorGPS" - - #If got these triggers and not old location check a few - #other things - else: - update_reason = (f"{ic3dev_trigger}") - self.last_iosapp_trigger[devicename] = ic3dev_trigger - - #if the zone is a stationary zone and no exit trigger, - #the zones in the ios app may not be current. - if (dist_from_zone_m >= zone_radius_m * 2 - and instr(zone, STATIONARY) - and instr(self.zone_last.get(devicename), STATIONARY)): - event_msg = ("Outside Stationary Zone without " - "Exit Trigger > iOS App Zone info may need to be reloaded. " - "Check `iOS App Configuration > Location` screen for stat zones. " - "Force close iOS App and reload if necessary. " - f"Zone-{zone}, " - f"Distance-{self._format_dist_m(dist_from_zone_m)}, " - f"StatZoneTestDist-{zone_radius_m * 2}m") - #self._save_event_halog_info(devicename, event_msg) - - self.iosapp_stat_zone_action_msg_cnt[devicename] += 1 - if self.iosapp_stat_zone_action_msg_cnt.get(devicename) < 5: - message = { - "title": "iCloud3/iOSApp Zone Action Needed", - "message": event_msg, - "data": {"subtitle": "Stationary Zone Exit "\ - "Trigger was not recieved"}} - self._send_message_to_device(devicename, message) - - #Check to see if currently in a zone. If so, check the zone distance. - #If new location is outside of the zone and inside radius*4, discard - #by treating it as poor GPS - if self._is_inzone_zonename(zone): - outside_no_exit_trigger_flag, info_msg = \ - self._check_outside_zone_no_exit(devicename, zone, ic3dev_trigger, - ic3dev_latitude, ic3dev_longitude) - if outside_no_exit_trigger_flag: - update_method = None - ios_update_reason = None - self._save_event_halog_info(devicename, info_msg) - - #update via icloud to verify location if less than home_radius*10 - elif (dist_from_zone_m <= zone_radius_m * 10 - and self.TRK_METHOD_FMF_FAMSHR): - event_msg = (f"Verify Location Needed > " - f"Zone-{zone}, " - f"Distance-{self._format_dist_m(dist_from_zone_m)}m, " - f"ZoneVerifyDist-{self._format_dist_m(zone_radius_m*10)}m, " - f"GPS-{format_gps(ic3dev_latitude, ic3dev_longitude, ic3dev_gps_accuracy)}") - self._save_event_halog_info(devicename, event_msg) - update_method = ICLOUD_UPDATE - update_reason = "Verify Location" - else: - pass - else: - pass - - if (ic3dev_data[ATTR_LATITUDE] is None or ic3dev_data[ATTR_LONGITUDE] is None): - update_method = ICLOUD_UPDATE - - device_monitor_msg = (f"Device Monitor > UpdateMethod-{update_method}, " - f"UpdateReason-{update_reason}, " - f"State-{ic3dev_state}, " - f"Trigger-{ic3dev_trigger}, " - f"LastLoc-{self._secs_to_time(ic3dev_timestamp_secs)}, " - f"Zone-{zone}, " - f"HomeDist-{self._format_dist_m(dist_from_home_m)}, " - f"inZone-{self._is_inzone_zonename(zone)}, " - f"GPS-{format_gps(ic3dev_latitude, ic3dev_longitude, ic3dev_gps_accuracy)}, " - f"StateThisPoll-{ic3dev_state}, " - f"StateLastPoll-{self.state_last_poll.get(devicename)}") - if self.last_device_monitor_msg.get(devicename) != device_monitor_msg: - self._evlog_debug_msg(devicename, device_monitor_msg) - self.last_device_monitor_msg[devicename] = device_monitor_msg - - if (self._device_online(devicename) == False - or self.state_this_poll == NOT_SET): - device_offline_msg = (f"May be Offline, Never Located " - f"(#{self.poor_location_gps_cnt.get(devicename)})") - self._display_info_status_msg(devicename, device_offline_msg) - - #Save trigger and time for cycle even if trigger was discarded. - self.trigger[devicename] = ic3dev_trigger - self.last_located_secs[devicename] = ic3dev_timestamp_secs - - if update_method == ICLOUD_UPDATE: - if self.TRK_METHOD_FMF_FAMSHR: - self._update_device_icloud(update_reason, devicename) - - elif self.TRK_METHOD_IOSAPP: - update_method = IOSAPP_UPDATE - self.iosapp_request_loc_sent_flag[devicename] = False - - if update_method == IOSAPP_UPDATE: - self.state_this_poll[devicename] = ic3dev_state - self.iosapp_update_flag[devicename] = True - - update_method = self._update_device_iosapp(devicename, update_reason, ic3dev_data) - - #Retry with iCloud of an error or no data - if (update_method == ICLOUD_UPDATE - and self.TRK_METHOD_FMF_FAMSHR): - self._update_device_icloud(update_reason, devicename) - - self.any_device_being_updated_flag = False - - #If less than 90 secs to the next update for any devicename:zone, display time to - #the next update in the NextUpdt time field, e.g, 1m05s or 0m15s. - if devicename in self.track_from_zone: - for zone in self.track_from_zone.get(devicename): - devicename_zone = self._format_devicename_zone(devicename, zone) - if devicename_zone in self.next_update_secs: - age_secs = self._secs_to(self.next_update_secs.get(devicename_zone)) - #if (age_secs <= 90 and age_secs >= -15): - # self._display_time_till_update_info_msg(devicename_zone, age_secs) - self._display_time_till_update_info_msg(devicename_zone, age_secs) - - - if update_method is not None: - self.device_being_updated_flag[devicename] = False - self.state_change_flag[devicename] = False - self._log_debug_msgs_trace_flag = False - self.update_in_process_flag = False - - #End devicename in self.tracked_devices loop - - except Exception as err: - _LOGGER.exception(err) - log_msg = (f"Device Update Error, Error-{ValueError}") - self._log_error_msg(log_msg) - - self.update_in_process_flag = False - self._log_debug_msgs_trace_flag = False - - #Cycle thru all devices and check to see if devices next update time - #will occur in 5-secs. If so, request a location update now so it - #it might be current on the next update. - if ((this_5sec_loop_second % 15) == 10) and self.TRK_METHOD_FMF_FAMSHR: - self._polling_loop_10_sec_loc_prefetch(now) - - #Cycle thru all devices and check to see if devices need to be - #updated via every 15 seconds - if ((this_5sec_loop_second % 15) == 0) and self.TRK_METHOD_FMF_FAMSHR: - self._polling_loop_15_sec_icloud(now) - - #Refresh the Event Log after completing the first locate, display info - #for the first devicename - if self.tracked_devices: - devicename = self.tracked_devices[0] - if (self.initial_locate_complete_flag == False - and self.state_this_poll.get(devicename, NOT_SET) != NOT_SET): - self.initial_locate_complete_flag = True - self._update_sensor_ic3_event_log(devicename) - -#-------------------------------------------------------------------- - def _retry_update(self, devicename): - #This flag will be 'true' if the last update for this device - #was not completed. Do another update now. - self.device_being_updated_retry_cnt[devicename] = 0 - while (self.device_being_updated_flag.get(devicename) - and self.device_being_updated_retry_cnt.get(devicename) < 4): - self.device_being_updated_retry_cnt[devicename] += 1 - - log_msg = (f"{self._format_fname_devtype(devicename)} " - f"Retrying Update, Update was not completed in last cycle, " - f"Retry #{self.device_being_updated_retry_cnt.get(devicename)}") - self._save_event_halog_info(devicename, log_msg) - - self.device_being_updated_flag[devicename] = True - self._log_debug_msgs_trace_flag = True - - self._wait_if_update_in_process() - update_reason = (f"Retry Update #{self.device_being_updated_retry_cnt.get(devicename)}") - - self._update_device_icloud(update_reason, devicename) - -######################################################### -# -# This function is called every 10 seconds. Cycle through all -# of the devices to see if any of the ones being tracked will -# be updated on the 15-sec polling loop in 5-secs. If so, request a -# location update now so it might be current when the device -# is updated. -# -######################################################### - def _polling_loop_10_sec_loc_prefetch(self, now): - - try: - if self.next_update_secs is None: - return - - for devicename_zone in self.next_update_secs: - devicename = devicename_zone.split(':')[0] - if self.state_this_poll.get(devicename) == NOT_SET: - continue - - time_till_update = self.next_update_secs.get(devicename_zone) - \ - self.this_update_secs - location_data = self.location_data.get(devicename) - - if time_till_update <= 10: - location_data = self.location_data.get(devicename) - location_age = location_data[ATTR_AGE] - - if location_age > 15: - if self.TRK_METHOD_FMF_FAMSHR: - self._refresh_pyicloud_devices_location_data(location_age, devicename) - - elif self.TRK_METHOD_IOSAPP: - self._iosapp_request_loc_update(devicename) - break - - except Exception as err: - _LOGGER.exception(err) - - return - -######################################################### -# -# Update the device on a state or trigger change was recieved from the ios app -# ●►●◄►●▬▲▼◀►►●◀ oPhone=►▶ -######################################################### - def _update_device_iosapp(self, devicename, update_reason, ic3dev_data): - """ - Update the devices location using data from the iOS App - """ - - if self.start_icloud3_inprocess_flag: - return - - fct_name = "_update_device_ios_trigger" - - self.any_device_being_updated_flag = True - return_code = IOSAPP_UPDATE - - self.iosapp_request_loc_retry_cnt[devicename] = 0 - self.iosapp_request_loc_sent_secs[devicename] = 0 - self.iosapp_request_loc_sent_flag[devicename] = False - - try: - devicename_zone = self._format_devicename_zone(devicename, HOME) - - if self.next_update_time.get(devicename_zone) == PAUSED: - self._save_event(devicename,"2047 update_iosapp, paused") - return - elif ATTR_LATITUDE not in ic3dev_data or ATTR_LONGITUDE not in ic3dev_data: - self._save_event(devicename,f"2050 update_iosapp, ic3_dev_data={ic3dev_data}") - return - elif ic3dev_data[ATTR_LATITUDE] is None or ic3dev_data[ATTR_LONGITUDE] is None: - self._save_event(devicename,f"2053 update_iosapp, lat=None, ic3_dev_data={ic3dev_data}") - return - - self._log_start_finish_update_banner('▼▼▼', devicename, "iOSApp", update_reason) - self._trace_device_attributes(devicename, 'IC3DEV_DATA', fct_name, ic3dev_data) - event_msg = (f"iOS App update started ({update_reason.split('@')[0]})") - self._save_event(devicename, event_msg) - - self.update_timer[devicename] = time.time() - - entity_id = self.device_tracker_entity_ic3.get(devicename) - state = self._get_state(entity_id) - latitude = ic3dev_data[ATTR_LATITUDE] - longitude = ic3dev_data[ATTR_LONGITUDE] - timestamp = self._timestamp_to_time(ic3dev_data[ATTR_TIMESTAMP]) - timestamp = self.this_update_time if timestamp == HHMMSS_ZERO else timestamp - gps_accuracy = ic3dev_data[ATTR_GPS_ACCURACY] - battery = ic3dev_data[ATTR_BATTERY_LEVEL] - battery_status = ic3dev_data[ATTR_BATTERY_STATUS] - device_status = ic3dev_data[ATTR_DEVICE_STATUS] - low_power_mode = ic3dev_data[ATTR_LOW_POWER_MODE] - altitude = self._get_attr(ic3dev_data, ATTR_ALTITUDE, NUMERIC) - vertical_accuracy = self._get_attr(ic3dev_data, ATTR_VERT_ACCURACY, NUMERIC) - - location_isold_attr = False - poor_location_gps_flag = False - self.poor_location_gps_cnt[devicename] = 0 - self.poor_location_gps_msg[devicename] = False - self.poor_gps_flag[devicename] = False #v2.2.1 - self.device_status[devicename] = device_status - - attrs = {} - - #-------------------------------------------------------- - try: - if self.device_being_updated_flag.get(devicename): - info_msg = "Last update not completed, retrying" - else: - info_msg = "Updating" - info_msg = (f"{info_msg} {self.fname.get(devicename)}") - - self._display_info_status_msg(devicename, info_msg) - self.device_being_updated_flag[devicename] = True - - except Exception as err: - _LOGGER.exception(err) - attrs = self._internal_error_msg(fct_name, err, 'UpdateAttrs1') - - try: - for zone in self.track_from_zone.get(devicename): - #If the state changed, only process the zone that changed - #to avoid delays caused calculating travel time by other zones - if (self.state_change_flag.get(devicename) - and self.state_this_poll.get(devicename) != zone - and zone != HOME): - continue - - #discard trigger if outsize zone with no exit trigger - if self._is_inzone_zonename(zone): - discard_flag, discard_msg = \ - self._check_outside_zone_no_exit(devicename, zone, '', - latitude, longitude) - - if discard_flag: - self._save_event(devicename, discard_msg) - continue - - self._set_base_zone_name_lat_long_radius(zone) - self._log_start_finish_update_banner('▼-▼', devicename, "iOSApp", zone) - - attrs = self._determine_interval( - devicename, - latitude, - longitude, - battery, - gps_accuracy, - poor_location_gps_flag, - self.last_located_secs.get(devicename), - timestamp, - "iOSApp") - - if attrs != {}: - self._update_device_sensors(devicename, attrs) - self._log_start_finish_update_banner('▲-▲', devicename, "iOSApp", zone) - - except Exception as err: - attrs = self._internal_error_msg(fct_name, err, 'DetInterval') - self.any_device_being_updated_flag = False - return ICLOUD_UPDATE - - try: - #attrs should not be empty, but catch it and do an icloud update - #if it is and no data is available. Exit without resetting - #device_being_update_flag so an icloud update will be done. - if attrs == {} and self.TRK_METHOD_FMF_FAMSHR: - self.any_device_being_updated_flag = False - self.iosapp_request_loc_sent_secs[devicename] = 0 - - event_msg = ("iOS update was not completed, " - f"will retry with {self.trk_method_short_name}") - self._save_event_halog_debug(devicename, event_msg) - - return ICLOUD_UPDATE - - #Note: Final prep and update device attributes via - #device_tracker.see. The gps location, battery, and - #gps accuracy are not part of the attrs variable and are - #reformatted into device attributes by 'See'. The gps - #location goes to 'See' as a "(latitude, longitude)" pair. - #'See' converts them to ATTR_LATITUDE and ATTR_LONGITUDE - #and discards the 'gps' item. - - log_msg = (f"LOCATION ATTRIBUTES, State-{self.state_last_poll.get(devicename)}, " - f"Attrs-{attrs}") - self._log_debug_msg(devicename, log_msg) - - #If location is empty or trying to set to the Stationary Base Zone Location, - #discard the update and try again in 15-sec - check_gps = self._update_last_latitude_longitude( - devicename, - latitude, - longitude, - (f"iOSApp-{update_reason}")) - - if check_gps == False: - self.any_device_being_updated_flag = False - return ICLOUD_UPDATE - - self.count_update_iosapp[devicename] += 1 - self.last_battery[devicename] = battery - self.last_gps_accuracy[devicename] = gps_accuracy - self.last_located_time[devicename] = self._time_to_12hrtime(timestamp) - - if altitude is None: - altitude = 0 - - attrs[ATTR_LAST_LOCATED] = self._time_to_12hrtime(timestamp) - attrs[ATTR_DEVICE_STATUS] = self.device_status.get(devicename) - attrs[ATTR_LOW_POWER_MODE] = low_power_mode - attrs[ATTR_BATTERY] = battery - attrs[ATTR_BATTERY_STATUS] = battery_status - attrs[ATTR_ALTITUDE] = round(altitude, 2) - attrs[ATTR_VERT_ACCURACY] = vertical_accuracy - attrs[ATTR_POLL_COUNT] = self._format_poll_count(devicename) - - except Exception as err: - _LOGGER.exception(err) - - try: - kwargs = self._setup_base_kwargs( - devicename, - latitude, - longitude, - battery, - gps_accuracy) - - self._update_device_attributes(devicename, kwargs, attrs, 'Final Update') - self._update_device_sensors(devicename, kwargs) - self._update_device_sensors(devicename, attrs) - self._update_stationary_zone_location(devicename) - - self.seen_this_device_flag[devicename] = True - self.device_being_updated_flag[devicename] = False - - except Exception as err: - _LOGGER.exception(err) - log_msg = (f"{self._format_fname_devtype(devicename)} " - f"Error Updating Device, {err}") - self._log_error_msg(log_msg) - return_code = ICLOUD_UPDATE - - try: - event_msg = (f"IOS App update complete") - self._save_event(devicename, event_msg) - - self._log_start_finish_update_banner('▲▲▲', devicename, "iOSApp", update_reason) - - entity_id = self.device_tracker_entity_ic3.get(devicename) - ic3dev_attrs = self._get_device_attributes(entity_id) - #self._trace_device_attributes(devicename, 'AFTER.FINAL', fct_name, ic3dev_attrs) - - return_code = IOSAPP_UPDATE - - except KeyError as err: - self._internal_error_msg(fct_name, err, 'iosUpdateMsg') - return_code = ICLOUD_UPDATE - - except Exception as err: - _LOGGER.exception(err) - self._internal_error_msg(fct_name, err, 'OverallUpdate') - self.device_being_updated_flag[devicename] = False - return_code = ICLOUD_UPDATE - - self.any_device_being_updated_flag = False - #self.iosapp_request_loc_sent_secs[devicename] = 0 - return return_code - -######################################################### -# -# Using the iosapp tracking method or iCloud is disabled -# so trigger the iosapp to send a -# location transaction -# -######################################################### - def _iosapp_request_loc_update(self, devicename, reissue_msg=""): - ''' - Send location request to phone. Check to see if one has been sent but not responded to - and, if true, set interval based on the retry count. - ''' - - try: - age = self._secs_since(self.iosapp_request_loc_sent_secs.get(devicename)) - event_msg = "Requested iOSApp Loc" - - #Save initial sent time if not sent before, otherwise increase retry cnt and - #set new interval time - if self.iosapp_request_loc_sent_flag.get(devicename) == False: - self.iosapp_request_loc_sent_secs[devicename] = self.this_update_secs - self.iosapp_request_loc_retry_cnt[devicename] = 0 - event_msg += (f"@{self.this_update_time}") - else: - self.iosapp_request_loc_retry_cnt[devicename] += 1 - event_msg += (f"@{self._secs_to_time(self.iosapp_request_loc_sent_secs.get(devicename))}, " - f"({self._format_age(age)}), " - f"#{self.iosapp_request_loc_retry_cnt.get(devicename)}") - - if self.iosapp_request_loc_retry_cnt.get(devicename) > 10: - event_msg += ", May be offline/asleep" - - self._determine_interval_after_error( - devicename, - event_msg, - counter=IOSAPP_REQUEST_LOC_CNT) - - self.iosapp_request_loc_sent_flag[devicename] = True - self.iosapp_request_loc_cnt[devicename] += 1 - - message = {"message": "request_location_update"} - return_code = self._send_message_to_device(devicename, message) - - #self.hass.async_create_task( - # self.hass.services.async_call('notify', entity_id, service_data)) - - self._save_event_halog_info(devicename, event_msg) - - if return_code: - attrs = {} - attrs[ATTR_POLL_COUNT] = self._format_poll_count(devicename) - attrs[ATTR_INFO] = event_msg - self._update_device_sensors(devicename, attrs) - else: - event_msg = f"{EVA_NOTICE}{event_msg} > Failed to send message" - self._save_event_halog_info(devicename, event_msg) - - except Exception as err: - _LOGGER.exception(err) - error_msg = (f"iCloud3 Error > An error occurred sending a location request > " - f"Device-{self.notify_iosapp_entity.get(devicename)}, Error-{err}") - self._save_event_halog_error(devicename, error_msg) - - -######################################################### -# -# This function is called every 15 seconds. Cycle through all -# of the iCloud devices to see if any of the ones being tracked need -# to be updated. If so, we might as well update the information for -# all of the devices being tracked since PyiCloud gets data for -# every device in the account. -# -######################################################### - def _polling_loop_15_sec_icloud(self, now): - """Called every 15-sec to check iCloud update""" - - if self.any_device_being_updated_flag: - return - elif self.TRK_METHOD_IOSAPP: - return - - fct_name = "_polling_loop_15_sec_icloud" - - self.this_update_secs = self._time_now_secs() - this_update_time = dt_util.now().strftime(self.um_time_strfmt) - - try: - for devicename in self.tracked_devices: - update_reason = "Location Update" - devicename_zone = self._format_devicename_zone(devicename, HOME) - - if (self.tracking_device_flag.get(devicename) is False - or self.next_update_time.get(devicename_zone) == PAUSED): - continue - elif (self.state_this_poll.get(devicename) == NOT_SET - and self.next_update_secs.get(devicename_zone) > self.this_update_secs): - continue - - self.iosapp_update_flag[devicename] = False - update_method = None - event_msg = "" - - # If the state changed since last poll, force an update - # This can be done via device_tracker.see service call - # with a different location_name in an automation or - # from entering a zone via the IOS App. - entity_id = self.device_tracker_entity_ic3.get(devicename) - state = self._get_state(entity_id) - - if state != self.state_last_poll.get(devicename): - update_method = ICLOUD_UPDATE - update_reason = "State Change" - event_msg = (f"State Change detected for {devicename} > " - f"{self.state_last_poll.get(devicename)} to " - f"{state}") - self._save_event_halog_info(devicename, event_msg) - - if update_method == ICLOUD_UPDATE: - if 'nearzone' in state: - state = 'near_zone' - - self.state_this_poll[devicename] = state - self.next_update_secs[devicename_zone] = 0 - - attrs = {} - attrs[ATTR_INTERVAL] = '0 sec' - attrs[ATTR_NEXT_UPDATE_TIME] = HHMMSS_ZERO - self._update_device_sensors(devicename, attrs) - - #This flag will be 'true' if the last update for this device - #was not completed. Do another update now. - if (self.device_being_updated_flag.get(devicename) - and self.device_being_updated_retry_cnt.get(devicename) > 4): - self.device_being_updated_flag[devicename] = False - self.device_being_updated_retry_cnt[devicename] = 0 - self._log_debug_msgs_trace_flag = False - - log_msg = (f"{self._format_fname_devtype(devicename)} Cancelled update retry") - self._log_info_msg(log_msg) - - update_via_other_devicename = None - if self._check_in_zone_and_before_next_update(devicename): - continue - - elif self.device_being_updated_flag.get(devicename): - update_method = ICLOUD_UPDATE - self._log_debug_msgs_trace_flag = True - self.device_being_updated_retry_cnt[devicename] += 1 - - update_reason = "Retry Last Update" - event_msg = (f"{self.trk_method_short_name} update not completed, retrying") - self._save_event_halog_info(devicename, event_msg) - - elif self.next_update_secs.get(devicename_zone) == 0: - update_method = ICLOUD_UPDATE - self._log_debug_msgs_trace_flag = False - update_reason = "State Change/Resume" - event_msg = "State Change or Resume Polling Requested" - self._save_event(devicename, event_msg) - - else: - update_via_other_devicename = self._check_next_update_time_reached() - #TODO. Pia update from other device flag into update routine so it won't update of old loc and from another def and next update time not reached - if (update_via_other_devicename != devicename - and self.poor_location_gps_cnt.get(devicename) > 0 - and self.next_update_secs.get(devicename_zone) > self.this_update_secs): - pass - - elif update_via_other_devicename is not None: - self._log_debug_msgs_trace_flag = False - retry_suffix = "" if self.poor_location_gps_cnt.get(devicename) == 0 else " (Retry)" - update_method = ICLOUD_UPDATE - update_reason = f"Next Update Time reached{retry_suffix}" - self.trigger[devicename] = f"NextUpdateTime{retry_suffix}" - event_msg = (f"{update_reason} > {update_via_other_devicename}") - self._save_event(devicename, event_msg) - - elif update_method == ICLOUD_UPDATE: - retry_suffix = "" if self.poor_location_gps_cnt.get(devicename) == 0 else " (Retry)" - event_msg = (f"Next Update Time reached{retry_suffix} > {devicename}") - self._save_event(devicename, event_msg) - - if update_method == ICLOUD_UPDATE: - self._wait_if_update_in_process() - self.update_in_process_flag = True - - if self._check_authentication_2sa_code_needed(): - #Only display error once - if instr(self.info_notification, "ICLOUD"): - self.update_in_process_flag = False - return - - self.info_notification = (f"THE ICLOUD 2FA CODE IS NEEDED TO VERIFY " - f"THE ACCOUNT FOR {self.username}") - for devicename in self.tracked_devices: - self._display_info_status_msg(devicename, self.info_notification) - - log_msg = (f"iCloud3 Error > The iCloud 2fa code for account " - f"{self.username} needs to be verified. Use the HA " - f"Notifications area on the HA Sidebar at the bottom " - f"the HA main screen.") - self._save_event_halog_error(devicename, log_msg) - - # Trigger the next step immediately - self._icloud_show_trusted_device_request_form() - return - - self._update_device_icloud(update_reason, update_via_other_devicename) - - self.update_in_process_flag = False - - except Exception as err: #ValueError: - _LOGGER.exception(err) - - log_msg = (f"iCloud/FmF API Error, Error-{ValueError}") - self._log_error_msg(log_msg) - self.api.authenticate() #Reset iCloud - self.authenticated_time = time.time() - self._update_device_icloud('iCloud/FmF Reauth', update_via_other_devicename) #Retry update devices - - self.update_in_process_flag = False - self._log_debug_msgs_trace_flag = False - - -######################################################### -# -# Cycle through all iCloud devices and update the information for the devices -# being tracked -# ●►●◄►●▬▲▼◀►►●◀ oPhone=►▶ -######################################################### - def _update_device_icloud(self, update_reason='Check iCloud', - arg_devicename=None, arg_via_other_devicename=None): - - """ - Request device information from iCloud (if needed) and update - device_tracker information. - - arg_devicename - - None = Update all devices - Not None = Update specified device - arg_other-devicename - - None = Update all devices - Not None = One device in the list reached the next update time. - Do not update another device that now has poor location - gps after all the results have been determined if - their update time has not been reached. - - """ - - if self.TRK_METHOD_IOSAPP: - return - elif (self.start_icloud3_inprocess_flag and update_reason != 'Initial Locate'): - return - elif self.any_device_being_updated_flag: - return - fct_name = "_update_device_icloud" - - self.any_device_being_updated_flag = True - self.base_zone = HOME - - try: - for devicename in self.tracked_devices: - zone = self.zone_current.get(devicename) - devicename_home_zone = self._format_devicename_zone(devicename) - - if arg_devicename and devicename != arg_devicename: - continue - elif self.next_update_time.get(devicename_home_zone) == PAUSED: - continue - elif (self.state_this_poll.get(devicename) == NOT_SET - and self.next_update_secs.get(devicename_home_zone) > self.this_update_secs): - continue - - #If the device is in a zone, and was in the same zone on the - #last poll of another device on the account and this device - #update time has not been reached, do not update device - #information. Do this in case this device currently has bad gps - #and really doesn't need to be polled at this time anyway. - #If the iOS App triggered the update and it was not done by the - #iosapp_update routine, do one now anyway. - if (self._check_in_zone_and_before_next_update(devicename) - and arg_devicename is None): - continue - - event_msg = (f"{self.trk_method_short_name} update started " - f"({update_reason.split('@')[0]})") - self._save_event_halog_debug(devicename, event_msg) - - self._log_start_finish_update_banner('▼▼▼', devicename, - self.trk_method_short_name, update_reason) - - self.update_timer[devicename] = time.time() - self.iosapp_request_loc_sent_secs[devicename] = 0 - do_not_update_flag = False - location_time = 0 - - #Updating device info. Get data from FmF or FamShr and update - if self.TRK_METHOD_FMF: - valid_data_flag = self._get_fmf_data(devicename) - - elif self.TRK_METHOD_FAMSHR: - valid_data_flag = self._get_famshr_data(devicename) - - #An error ocurred accessing the iCloud account. This can be a - #Authentication error or an error retrieving the loction dataevligale - #if ic3dev_data[0] is False: - if valid_data_flag == ICLOUD_LOCATION_DATA_ERROR: - self.icloud_acct_auth_error_cnt += 1 - self._determine_interval_after_error( - devicename, - "iCloud Offline (Authentication or Location Error)", - counter=AUTH_ERROR_CNT) - - if (self.interval_seconds.get(devicename) != 15 - and self.icloud_acct_auth_error_cnt > 2): - log_msg = ("iCloud3 Error > An error occurred accessing " - f"the iCloud account {self.username} for {devicename}. This can be an account " - "authentication issue or no location data is " - "available. Retrying at next update time. " - "Retry #{self.icloud_acct_auth_error_cnt}") - self._save_event_halog_error("*", log_msg) - - if self.icloud_acct_auth_error_cnt > 20: - self._setup_tracking_method(IOSAPP) - log_msg = ("iCloud3 Error > More than 20 iCloud Authentication " - "errors. Resetting to use tracking_method . " - "Restart iCloud3 at a later time to see if iCloud " - "Loction Services is available.") - self._save_event_halog_error("*", log_msg) - - break - else: - self.icloud_acct_auth_error_cnt = 0 - - #icloud data overrules device data which may be stale - location_data = self.location_data.get(devicename) - latitude = location_data[ATTR_LATITUDE] - longitude = location_data[ATTR_LONGITUDE] - gps_accuracy = 0 - - if latitude != 0 and longitude != 0: - timestamp = location_data[ATTR_TIMESTAMP] - location_isold_attr = location_data[ATTR_ISOLD] - last_located_secs = location_data[ATTR_TIMESTAMP] - location_time = location_data[ATTR_TIMESTAMP_TIME] - battery = location_data[ATTR_BATTERY_LEVEL] - battery_status = location_data[ATTR_BATTERY_STATUS] - device_status = location_data[ATTR_DEVICE_STATUS] - low_power_mode = location_data[ATTR_LOW_POWER_MODE] - altitude = location_data[ATTR_ALTITUDE] - gps_accuracy = location_data[ATTR_GPS_ACCURACY] - vertical_accuracy = location_data[ATTR_VERT_ACCURACY] - - location_age = self._secs_since(location_data.get(ATTR_TIMESTAMP)) - location_data[ATTR_AGE] = location_age - self.location_data[devicename][ATTR_BATTERY_LEVEL] = battery - self.last_located_secs[devicename] = last_located_secs - self.device_status[devicename] = device_status - - poor_location_gps_flag, discard_reason = self._check_poor_location_gps( - devicename, - last_located_secs, - gps_accuracy) - - #Discard if no location coordinates - if latitude == 0 or longitude == 0: - location_time = NEVER - location_age = HIGH_INTEGER - self.poor_location_gps_cnt[devicename] += 1 - self.device_status[devicename] = UNKNOWN - discard_reason = (f"No location data " - f"(#{self.poor_location_gps_cnt.get(devicename)})") - device_offline_msg = (f"May be Offline, No Location " - f"(#{self.poor_location_gps_cnt.get(devicename)})") - info_msg = discard_reason - self._determine_interval_after_error( - devicename, - device_offline_msg) - do_not_update_flag = True - - #Check to see if currently in a zone. If so, check the zone distance. - #If new location is outside of the zone and inside radius*4, discard - #by treating it as poor GPS - elif (self._isnot_inzone_zonename(zone) - or self.state_this_poll.get(devicename) == NOT_SET): - outside_no_exit_trigger_flag = False - info_msg= '' - else: - outside_no_exit_trigger_flag, info_msg = \ - self._check_outside_zone_no_exit(devicename, zone, '', - latitude, longitude) - - if self.icloud_acct_auth_error_cnt > 0: - pass - - #If initializing, nothing is set yet - #elif (self.state_this_poll.get(devicename) == NOT_SET - # and location_age < 300): - # pass - - #If no location data - elif do_not_update_flag: - pass - - #Ignore old location when in a zone, let normal next time update - #check process - elif (poor_location_gps_flag - and self.this_update_secs < self.next_update_secs.get(devicename_home_zone) - and (self._is_inzone(devicename) - or devicename != arg_via_other_devicename)): - self.poor_location_gps_cnt[devicename] -= 1 - pass - - #elif device_status not in ["online", "pending", ""]: - elif self._device_online(devicename) == False: - do_not_update_flag = True - info_msg = "Device Offline" - self._determine_interval_after_error( - devicename, - info_msg) - event_msg = (f"{EVLOG_ALERT}iCloud Alert > {devicename} is Offline > Tracking is delayed, " - f"Status-{self.device_status.get(devicename)}, " - f"OnlineStatus-{self.device_status_online}") - self._save_event(devicename, event_msg) - - #elif self.state_this_poll.get(devicename) == NOT_SET: - # pass - - #Outside zone, no exit trigger check - elif outside_no_exit_trigger_flag: - self.poor_gps_flag[devicename] = True - self.poor_location_gps_cnt[devicename] += 1 - do_not_update_flag = True - self._determine_interval_after_error( - devicename, - info_msg) - - #Discard if location is old or poor gps - elif poor_location_gps_flag: - info_msg = (f"{discard_reason}") - do_not_update_flag = True - self._determine_interval_after_error( - devicename, - info_msg) - - #discard if outside home zone and less than zone_radius+self.gps_accuracy_threshold due to gps errors - dist_from_home_m = self._calc_distance_m(latitude, longitude, - self.zone_home_lat, self.zone_home_long) - - if do_not_update_flag: - location_age_str = "" if location_time == NEVER else (f" ({self._format_age(location_age)})") - event_msg = (f"Discarded > {info_msg} > " - f"GPS-{format_gps(latitude, longitude, gps_accuracy)}, " - f"Located-{location_time}{location_age_str}, " - f"NextUpdate-{self.next_update_time.get(self._format_devicename_zone(devicename))}, " - f"OldLocThreshold-{self._secs_to_time_str(self.old_location_secs.get(devicename))}") - if self._device_online(devicename) == False: - event_msg += (f", DeviceStatus-{self.device_status.get(devicename)}") - self._save_event(devicename, event_msg) - - self._log_start_finish_update_banner('▲▲▲', devicename, - self.trk_method_short_name, update_reason) - continue - - #-------------------------------------------------------- - try: - if self.device_being_updated_flag.get(devicename): - info_msg = "Retrying > Last update not completed" - event_msg = info_msg - else: - info_msg = "Updating" - event_msg = (f"Updating Device > GPS-{format_gps(latitude, longitude, gps_accuracy)}, " - f"Located-{location_time} ({self._format_age(location_age)})") - info_msg = f"{info_msg} {self.fname.get(devicename)}" - self._display_info_status_msg(devicename, info_msg) - self._save_event(devicename, event_msg) - - #set device being updated flag. This is checked in the - #'_polling_loop_15_sec_icloud' loop to make sure the last update - #completed successfully (Waze has a compile error bug that will - #kill update and everything will sit there until the next poll. - #if this is still set in '_polling_loop_15_sec_icloud', repoll - #immediately!!! - self.device_being_updated_flag[devicename] = True - - except Exception as err: - attrs = self._internal_error_msg(fct_name, err, 'UpdateAttrs1') - - try: - for zone in self.track_from_zone.get(devicename): - self._set_base_zone_name_lat_long_radius(zone) - - self._log_start_finish_update_banner('▼-▼', devicename, - self.trk_method_short_name, zone) - self.location_data[devicename][ATTR_BATTERY_LEVEL] = battery - attrs = self._determine_interval( - devicename, - latitude, - longitude, - battery, - gps_accuracy, - poor_location_gps_flag, - last_located_secs, - location_time, - "icld") - if attrs != {}: - self._update_device_sensors(devicename, attrs) - - self._log_start_finish_update_banner('▲-▲', devicename, - self.trk_method_short_name,zone) - - except Exception as err: - attrs = self._internal_error_msg(fct_name, err, 'DetInterval') - continue - - try: - #Note: Final prep and update device attributes via - #device_tracker.see. The gps location, battery, and - #gps accuracy are not part of the attrs variable and are - #reformatted into device attributes by 'See'. The gps - #location goes to 'See' as a "(latitude, longitude)" pair. - #'See' converts them to ATTR_LATITUDE and ATTR_LONGITUDE - #and discards the 'gps' item. - log_msg = (f"LOCATION ATTRIBUTES, " - f"State-{self.state_last_poll.get(devicename)}, " - f"Attrs-{attrs}") - self._log_debug_msg(devicename, log_msg) - - self.count_update_icloud[devicename] += 1 - if not poor_location_gps_flag: - self._update_last_latitude_longitude( - devicename, latitude, longitude, - (f"iCloud-{update_reason}")) - - if altitude is None: - altitude = -2 - - #attrs[ATTR_DEVICE_STATUS] = device_status - attrs[ATTR_DEVICE_STATUS] = self.device_status.get(devicename) - attrs[ATTR_LOW_POWER_MODE] = low_power_mode - attrs[ATTR_BATTERY] = battery - attrs[ATTR_BATTERY_STATUS] = battery_status - attrs[ATTR_ALTITUDE] = round(altitude, 2) - attrs[ATTR_VERT_ACCURACY] = vertical_accuracy - attrs[ATTR_POLL_COUNT] = self._format_poll_count(devicename) - attrs[ATTR_AUTHENTICATED] = self._secs_to_timestamp(self.authenticated_time) - - except Exception as err: - attrs = self._internal_error_msg(fct_name, err, 'SetAttrs') - - try: - kwargs = self._setup_base_kwargs(devicename, - latitude, longitude, battery, gps_accuracy) - - self._update_device_attributes(devicename, kwargs, attrs, 'Final Update') - self._update_device_sensors(devicename, kwargs) - self._update_device_sensors(devicename, attrs) - self._update_stationary_zone_location(devicename) - - self.seen_this_device_flag[devicename] = True - self.device_being_updated_flag[devicename] = False - - except Exception as err: - log_msg = (f"{self._format_fname_devtype(devicename)} Error Updating Device, {err}") - self._log_error_msg(log_msg) - - _LOGGER.exception(err) - - try: - event_msg = (f"{self.trk_method_short_name} update completed") - self._save_event(devicename, event_msg) - - self._log_start_finish_update_banner('▲▲▲', devicename, - self.trk_method_short_name, update_reason) - - except KeyError as err: - self._internal_error_msg(fct_name, err, 'icloudUpdateMsg') - - except Exception as err: - _LOGGER.exception(err) - self._internal_error_msg(fct_name, err, 'OverallUpdate') - self.device_being_updated_flag[devicename] = False - - self.any_device_being_updated_flag = False - -######################################################### -# -# Get iCloud device & location info when using the -# FmF (Find-my-Friends / Find Me) tracking method. -# -######################################################### - def _get_fmf_data(self, devicename): - ''' - Get the location data from Find My Friends. - - location_data-{ - 'locationStatus': None, - 'location': { - 'isInaccurate': False, - 'altitude': 0.0, - 'address': {'formattedAddressLines': ['123 Main St', - 'Your City, NY', 'United States'], - 'country': 'United States', - 'streetName': 'Main St, - 'streetAddress': '123 Main St', - 'countryCode': 'US', - 'locality': 'Your City', - 'stateCode': 'NY', - 'administrativeArea': 'New York'}, - 'locSource': None, - 'latitude': 12.34567890, - 'floorLevel': 0, - 'horizontalAccuracy': 65.0, - 'labels': [{'id': '79f8e34c-d577-46b4-a6d43a7b891eca843', - 'latitude': 12.34567890, - 'longitude': -45.67890123, - 'info': None, - 'label': '_$!!$_', - 'type': 'friend'}], - 'tempLangForAddrAndPremises': None, - 'verticalAccuracy': 0.0, - ATTR_ICLOUD_BATTERY_STATUS: None, - 'locationId': 'a6b0ee1d-be34-578a-0d45-5432c5753d3f', - 'locationTimestamp': 0, - 'longitude': -45.67890123, - 'timestamp': 1562512615222}, - 'id': 'NDM0NTU2NzE3', - 'status': None} - ''' - - fct_name = "_get_fmf_data" - from .pyicloud_ic3 import PyiCloudNoDevicesException - - log_msg = (f"= = = Prep Data From FmF = = = (Now-{self.this_update_secs})") - self._log_debug_msg(devicename, log_msg) - - try: - self._display_info_status_msg(devicename, "Getting iCloud Location") - location_data = self.location_data.get(devicename) - - log_msg = (f"LOCATION DATA-{location_data})") - self._log_debug_msg(devicename, log_msg) - - location_age = location_data[ATTR_AGE] - - if location_age > self.old_location_secs.get(devicename): - if self._refresh_pyicloud_devices_location_data(location_age, devicename): - self._display_info_status_msg(devicename, "Location Data Old, Refreshing") - location_data = self.location_data.get(devicename) - - evlog_msg = (f"Refreshed FmF iCloud location data") - self._evlog_debug_msg(devicename, evlog_msg) - else: - self._display_info_status_msg(devicename, "No iCloud Location Available") - if self.icloud_acct_auth_error_cnt > 3: - self._log_error_msg(f"iCloud3 Error > No Location Data " - f"Returned for {devicename}") - return ICLOUD_LOCATION_DATA_ERROR - - if self._device_online(devicename): - self._display_info_status_msg(devicename, "iCloud Location Data Available") - - return True - - except Exception as err: - _LOGGER.exception(err) - self._log_error_msg("General iCloud Location Data Error") - return ICLOUD_LOCATION_DATA_ERROR - -######################################################### -# -# Get iCloud device & location info when using the -# FamShr (Family Sharing) tracking method. -# -######################################################### - def _get_famshr_data(self, devicename): - ''' - Extract the data needed to determine location, direction, interval, - etc. from the iCloud data set. - - Sample data set is: - {'isOld': False, 'isInaccurate': False, 'altitude': 0.0, 'positionType': 'Wifi', - 'latitude': 27.72690098883266, 'floorLevel': 0, 'horizontalAccuracy': 65.0, - 'locationType': '', 'timeStamp': 1587306847548, 'locationFinished': True, - 'verticalAccuracy': 0.0, 'longitude': -80.3905776599289} - ''' - - fct_name = "_get_famshr_data" - - log_msg = (f"= = = Prep Data From FamShr = = = (Now-{self.this_update_secs})") - self._log_debug_msg(devicename, log_msg) - - try: - self._display_info_status_msg(devicename, "Getting iCloud Location") - location_data = self.location_data.get(devicename) - - log_msg = (f"LOCATION DATA-{location_data})") - self._log_debug_msg(devicename, log_msg) - - location_age = location_data[ATTR_AGE] - - if location_age > self.old_location_secs.get(devicename): - if self._refresh_pyicloud_devices_location_data(location_age, devicename): - self._display_info_status_msg(devicename, "Location Data Old, Refreshing") - location_data = self.location_data.get(devicename) - - evlog_msg = (f"Refreshed FamShr iCloud location data") - self._evlog_debug_msg(devicename, evlog_msg) - else: - self._display_info_status_msg(devicename, "No iCloud Location Available") - if self.icloud_acct_auth_error_cnt > 3: - self._log_error_msg(f"iCloud3 Error > No Location Data " - f"Returned for {devicename}") - return ICLOUD_LOCATION_DATA_ERROR - self._display_info_status_msg(devicename, "iCloud Location Data Available") - return True - - except Exception as err: - _LOGGER.exception(err) - self._log_error_msg("General iCloud FamShr Location Data Error") - return ICLOUD_LOCATION_DATA_ERROR - -#---------------------------------------------------------------------------- - def _refresh_pyicloud_devices_location_data(self, location_age, arg_devicename): - ''' - Authenticate pyicloud & refresh device & location data. This calls the - function to update 'self.location_data' for each device being tracked. - - Return: True if device data was updated successfully - False if api error or no device data returned - ''' - - try: - event_msg=(f"Sending location request to iCloud > Last Updated-") - if location_age == HIGH_INTEGER: - event_msg += (f"Never (Initial Locate)") - else: - event_msg += (f"{self.location_data.get(arg_devicename)[ATTR_TIMESTAMP_TIME]} " - f"({self._format_age(location_age)})") - self._save_event_halog_info(arg_devicename, event_msg) - - exit_get_data_loop = False - authenticated_pyicloud_flag = False - self.count_pyicloud_location_update += 1 - pyicloud_start_call_time = time.time() - - while exit_get_data_loop == False: - try: - if self.api is None: - return False - - if self.TRK_METHOD_FMF: - self.api.friends.refresh_client() - devices = self.api.friends - locations = devices.locations - - for location in locations: - if ATTR_LOCATION in location: - contact_id = location['id'] - if contact_id in self.fmf_id: - devicename = self.fmf_id[contact_id] - self._update_location_data(devicename, location) - - elif self.TRK_METHOD_FAMSHR: - api_devices = {} - api_devices = self.api.devices - api_device_data = api_devices.response["content"] - - for device in api_device_data: - if device: - device_data_name = device[ATTR_NAME] - if device_data_name in self.api_device_devicename: - devicename = self.api_device_devicename.get(device_data_name) - if devicename in self.tracked_devices: - self._update_location_data(devicename, device) - - except PyiCloud2SARequiredException as err: - if authenticated_pyicloud_flag: - return False - - authenticated_pyicloud_flag = True - self._check_authentication_2sa_code_needed() - if self.api is not None: - self._pyicloud_authenticate_account(devicename=arg_devicename) - - except PyiCloudAPIResponseException as err: - if authenticated_pyicloud_flag: - return False - - authenticated_pyicloud_flag = True - self._pyicloud_authenticate_account(devicename=arg_devicename) - - except Exception as err: - _LOGGER.exception(err) - - else: - exit_get_data_loop = True - - update_took_time = time.time() - pyicloud_start_call_time - self.time_pyicloud_calls += update_took_time - - return True - - except Exception as err: - _LOGGER.exception(err) - - return False - -#---------------------------------------------------------------------------- - def _update_location_data(self, devicename, device_data): - ''' - Extract the location_data dictionary table from the device - data returned from pyicloud for the devicename device. This data is used to - determine the update interval, accuracy, location, etc. - ''' - try: - if device_data is None: - return False - elif ATTR_LOCATION not in device_data: - return False - elif device_data[ATTR_LOCATION] == {}: - return - elif device_data[ATTR_LOCATION] is None: - return - - self._log_level_debug_rawdata("update_location_data (device_data)", device_data) - - try: - timestamp_field = ATTR_TIMESTAMP if self.TRK_METHOD_FMF else ATTR_ICLOUD_TIMESTAMP - timestamp = device_data[ATTR_LOCATION][timestamp_field] / 1000 - - if timestamp == self.location_data.get(devicename)[ATTR_TIMESTAMP]: - location_age = self.location_data.get(devicename)[ATTR_AGE] - debug_msg = (f"DEVICE NOT UPDATED > Will Refresh, Located-{self._secs_to_time(timestamp)} " - f"({self._format_age(location_age)})") - self._log_debug_msg(devicename, debug_msg) - return - - except: - return - - iosapp_battery = self.last_battery.get(devicename, -1) - icloud_battery = int(device_data.get(ATTR_ICLOUD_BATTERY_LEVEL, 0) * 100) - - location_data = {} - location_data[ATTR_NAME] = device_data.get(ATTR_NAME, "") - location_data[ATTR_DEVICE_CLASS] = device_data.get(ATTR_ICLOUD_DEVICE_CLASS, "") - location_data[ATTR_BATTERY_LEVEL] = icloud_battery if icloud_battery > 0 else iosapp_battery - location_data[ATTR_BATTERY_STATUS] = device_data.get(ATTR_ICLOUD_BATTERY_STATUS, "") - - device_status_code = device_data.get(ATTR_ICLOUD_DEVICE_STATUS, 0) - location_data[ATTR_DEVICE_STATUS] = DEVICE_STATUS_CODES.get(device_status_code, "") - location_data[ATTR_LOW_POWER_MODE] = device_data.get(ATTR_ICLOUD_LOW_POWER_MODE, "") - - location = device_data[ATTR_LOCATION] - location_data[ATTR_TIMESTAMP] = timestamp - location_data[ATTR_TIMESTAMP_TIME] = self._secs_to_time(timestamp) - location_data[ATTR_AGE] = self._secs_since(timestamp) - location_data[ATTR_LATITUDE] = location.get(ATTR_LATITUDE, 0) - location_data[ATTR_LONGITUDE] = location.get(ATTR_LONGITUDE, 0) - location_data[ATTR_ALTITUDE] = round(location.get(ATTR_ALTITUDE, 0), 1) - location_data[ATTR_ISOLD] = location.get(ATTR_ISOLD, False) - location_data[ATTR_GPS_ACCURACY] = int(round(location.get(ATTR_ICLOUD_HORIZONTAL_ACCURACY, 0), 0)) - location_data[ATTR_VERT_ACCURACY] = int(round(location.get(ATTR_ICLOUD_VERTICAL_ACCURACY, 0), 0)) - - self.location_data[devicename] = location_data - - debug_msg = (f"UPDATE LOCATION > Located-{location_data[ATTR_TIMESTAMP_TIME]} " - f"({self._format_age(location_data[ATTR_AGE])})") - self._log_debug_msg(devicename, debug_msg) - self._log_debug_msg(devicename, location_data) - - return True - - except Exception as err: - _LOGGER.exception(err) - - return False - -######################################################### -# -# Calculate polling interval based on zone, distance from home and -# battery level. Setup triggers for next poll -# -######################################################### - def _determine_interval(self, devicename, latitude, longitude, - battery, gps_accuracy, poor_location_gps_flag, - last_located_secs, location_time, - ios_icld = ''): - """Calculate new interval. Return location based attributes""" - - fct_name = "_determine_interval" - - base_zone_home_flag = (self.base_zone == HOME) - devicename_zone = self._format_devicename_zone(devicename) - - try: - location_data = self._get_distance_data( - devicename, - latitude, - longitude, - gps_accuracy, - poor_location_gps_flag) - - log_msg = (f"Location_data-{location_data}") - self._log_debug_interval_msg(devicename, log_msg) - - #Abort and Retry if Internal Error - if (location_data[0] == ERROR): - return location_data[1] #(attrs) - - self._display_info_status_msg(devicename, "● Calculating Tracking Info ●") - - zone = location_data[0] - dir_of_travel = location_data[1] - dist_from_zone_km = location_data[2] - dist_from_zone_moved_km = location_data[3] - dist_last_poll_moved_km = location_data[4] - waze_dist_from_zone_km = location_data[5] - calc_dist_from_zone_km = location_data[6] - waze_dist_from_zone_moved_km = location_data[7] - calc_dist_from_zone_moved_km = location_data[8] - waze_dist_last_poll_moved_km = location_data[9] - calc_dist_last_poll_moved_km = location_data[10] - waze_time_from_zone = location_data[11] - last_dist_from_zone_km = location_data[12] - last_dir_of_travel = location_data[13] - dir_of_trav_msg = location_data[14] - timestamp = location_data[15] - - last_located_secs = self.last_located_secs.get(devicename) - - except Exception as err: - attrs_msg = self._internal_error_msg(fct_name, err, 'SetLocation') - return attrs_msg - - try: - log_msg = (f"DETERMINE INTERVAL Entered, " - "location_data-{location_data}") - self._log_debug_interval_msg(devicename, log_msg) - - # The following checks the distance from home and assigns a - # polling interval in minutes. It assumes a varying speed and - # is generally set so it will poll one or twice for each distance - # group. When it gets real close to home, it switches to once - # each 15 seconds so the distance from home will be calculated - # more often and can then be used for triggering automations - # when you are real close to home. When home is reached, - # the distance will be 0. - - waze_time_msg = "" - calc_interval = round(self._km_to_mi(dist_from_zone_km) / 1.5) * 60 - if self.waze_status == WAZE_USED: - waze_interval = round(waze_time_from_zone * 60 * self.travel_time_factor , 0) - else: - waze_interval = 0 - interval = 15 - interval_multiplier = 1 - interval_str = '' - - inzone_flag = (self._is_inzone_zonename(zone)) - not_inzone_flag = (self._isnot_inzone_zonename(zone)) - was_inzone_flag = (self._was_inzone(devicename)) - wasnot_inzone_flag = (self._wasnot_inzone(devicename)) - inzone_home_flag = (zone == self.base_zone) #HOME) - was_inzone_home_flag = \ - (self.state_last_poll.get(devicename) == self.base_zone) #HOME) - near_zone_flag = (zone == 'near_zone') - - log_msg = (f"Zone-{zone} ,IZ-{inzone_flag}, NIZ-{not_inzone_flag}, " - f"WIZ-{was_inzone_flag}, WNIZ-{wasnot_inzone_flag}, " - f"IZH-{inzone_home_flag}, WIZH-{was_inzone_home_flag}, " - f"NZ-{near_zone_flag}") - self._log_debug_interval_msg(devicename, log_msg) - - interval_method = '' - log_msg = '' - interval_method_im = '' - old_location_secs_msg = '' - - except Exception as err: - attrs_msg = self._internal_error_msg(fct_name, err, 'SetupZone') - return attrs_msg - - try: - if inzone_flag: - #Reset got zone exit trigger since now in a zone for next - #exit distance check. Also reset Stat Zone timer and dist moved. - self.got_exit_trigger_flag[devicename] = False - self.stat_zone_timer[devicename] = 0 - self.stat_zone_moved_total[devicename] = 0 - - #Note: If state is 'near_zone', it is reset to NOT_HOME when - #updating the device_tracker state so it will not trigger a state chng - if self.state_change_flag.get(devicename): - if inzone_flag: - if (STATIONARY in zone): - interval = self.stat_zone_inzone_interval - interval_method = "1sz-Stationary" - log_msg = f"Zone-{zone}" - - #inzone & old location - elif poor_location_gps_flag: - interval = self._get_interval_for_error_retry_cnt(devicename, POOR_LOC_GPS_CNT) - #self.poor_location_gps_cnt.get(devicename)) - interval_method = '1iz-OldLocPoorGPS' - - else: - interval = self.inzone_interval_secs - interval_method="1ez-EnterZone" - - #entered 'near_zone' zone if close to HOME and last is NOT_HOME - elif (near_zone_flag and wasnot_inzone_flag and - calc_dist_from_zone_km < 2): - interval = 15 - dir_of_travel = 'NearZone' - interval_method="1nzniz-EnterNearZone" - - #entered 'near_zone' zone if close to HOME and last is NOT_HOME - elif (near_zone_flag and was_inzone_flag - and calc_dist_from_zone_km < 2): - interval = 15 - dir_of_travel = 'NearZone' - interval_method="1nziz-EnterNearZone" - - #exited HOME zone - elif (not_inzone_flag and was_inzone_home_flag): - interval = 240 - dir_of_travel = AWAY_FROM - interval_method="1ehz-ExitHomeZone" - - #exited 'other' zone - elif (not_inzone_flag and was_inzone_flag): - interval = 120 - dir_of_travel = 'left_zone' - interval_method="1ez-ExitZone" - - #entered 'other' zone - else: - interval = 240 - interval_method="1zc-ZoneChanged" - - log_msg = (f"Zone-{zone}, Last-{self.state_last_poll.get(devicename)}, " - f"This-{self.state_this_poll.get(devicename)}") - self._log_debug_interval_msg(devicename, log_msg) - - #inzone & poor gps & check gps accuracy when inzone - elif (self.poor_gps_flag.get(devicename) - and inzone_flag - and self.check_gps_accuracy_inzone_flag): - interval = 300 #poor accuracy, try again in 5 minutes - interval_method = '2pgpsiz-PoorGPSinZone' - - elif self.poor_gps_flag.get(devicename): - interval = self._get_interval_for_error_retry_cnt(devicename, POOR_LOC_GPS_CNT) - interval_method = '2pgps-PoorGPS' - - elif self.override_interval_seconds.get(devicename) > 0: - interval = self.override_interval_seconds.get(devicename) - interval_method = '3ior-Override' - - elif (STATIONARY in zone): - interval = self.stat_zone_inzone_interval - interval_method = "4sz-Stationary" - log_msg = f"Zone-{zone}" - - elif poor_location_gps_flag: - interval = self._get_interval_for_error_retry_cnt(devicename, POOR_LOC_GPS_CNT) - interval_method = '4old-OldLocPoorGPS' - log_msg = f"Cnt-{self.poor_location_gps_cnt.get(devicename)}" - - elif (inzone_home_flag - or (dist_from_zone_km < .05 - and dir_of_travel == 'towards')): - interval = self.inzone_interval_secs - interval_method = '4ihz-InHomeZone' - log_msg = f"Zone-{zone}" - - elif zone == 'near_zone': - interval = 15 - interval_method = '4nz-NearZone' - log_msg = f"Zone-{zone}, Dir-{dir_of_travel}" - - #in another zone and inzone time > travel time - elif (inzone_flag - and self.inzone_interval_secs > waze_interval): - interval = self.inzone_interval_secs - interval_method = '4iz-InZone' - log_msg = f"Zone-{zone}" - - elif dir_of_travel in ('left_zone', NOT_SET): - interval = 150 - if inzone_home_flag: - dir_of_travel = AWAY_FROM - else: - dir_of_travel = NOT_SET - interval_method = '5ni-NeedInfo' - log_msg = f"ZoneLeft-{zone}" - - elif dist_from_zone_km < 2.5 and self.went_3km.get(devicename): - interval = 15 #1.5 mi=real close and driving - interval_method = '10a-<2.5km' - - elif dist_from_zone_km < 3.5: #2 mi=30 sec - interval = 30 - interval_method = '10b-<3.5km' - - elif waze_time_from_zone > 5 and waze_interval > 0: - interval = waze_interval - interval_method = '10c-WazeTime' - log_msg = f"TimeFmHome-{waze_time_from_zone}" - - elif dist_from_zone_km < 5: #3 mi=1 min - interval = 60 - interval_method = '10d-<5km' - - elif dist_from_zone_km < 8: #5 mi=2 min - interval = 120 - interval_method = '10e-<8km' - - elif dist_from_zone_km < 12: #7.5 mi=3 min - interval = 180 - interval_method = '10f-<12km' - - - elif dist_from_zone_km < 20: #12 mi=10 min - interval = 600 - interval_method = '10g-<20km' - - elif dist_from_zone_km < 40: #25 mi=15 min - interval = 900 - interval_method = '10h-<40km' - - elif dist_from_zone_km > 150: #90 mi=1 hr - interval = 3600 - interval_method = '10i->150km' - - else: - interval = calc_interval - interval_method = '20calc-Calculated' - log_msg = f"Value-{self._km_to_mi(dist_from_zone_km)}/1.5" - - except Exception as err: - attrs_msg = self._internal_error_msg(fct_name, err, 'SetInterval') - - try: - #if haven't moved far for X minutes, put in stationary zone - #determined in get_dist_data with dir_of_travel - if dir_of_travel == STATIONARY: - interval = self.stat_zone_inzone_interval - interval_method = "21stat-Stationary" - - if self.in_stationary_zone_flag.get(devicename) is False: - rtn_code = self._update_stationary_zone( - devicename, - latitude, - longitude, - STAT_ZONE_NEW_LOCATION, '21-Stationary') - - self.in_stationary_zone_flag[devicename] = rtn_code - if rtn_code: - self.zone_current[devicename] = self._format_zone_name(devicename, STATIONARY) - self.zone_timestamp[devicename] = dt_util.now().strftime(self.um_date_time_strfmt) - interval_method_im = "●Set.Stationary.Zone" - zone = STATIONARY - dir_of_travel = 'in_zone' - inzone_flag = True - not_inzone_flag = False - else: - dir_of_travel = NOT_SET - if (dir_of_travel in ('', AWAY_FROM) - and interval < 180 - and interval > 0): - interval_method += ',xx30dot-Away(<3min)' - - if (dir_of_travel in ('', AWAY_FROM) - and interval < 180 - and interval > 30): - interval = 180 - interval_method += ',30dot-Away(<3min)' - - elif (dir_of_travel == AWAY_FROM - and not self.distance_method_waze_flag): - interval_multiplier = 2 #calc-increase timer - interval_method += ',30dot-Away(Calc)' - elif (dir_of_travel == NOT_SET - and interval > 180): - interval = 180 - interval_method += ',301dor->180s' - - #15-sec interval (close to zone) and may be going into a stationary zone, - #increase the interval - elif (interval == 15 - and devicename in self.stat_zone_timer - and self.this_update_secs >= self.stat_zone_timer.get(devicename)+45): - interval = 30 - interval_method += ',31st-StatTimer+45' - - except Exception as err: - attrs_msg = self._internal_error_msg(fct_name, err, 'SetStatZone') - _LOGGER.exception(err) - - - try: - #Turn off waze close to zone flag to use waze after leaving zone - if inzone_flag: - self.waze_close_to_zone_pause_flag = False - if (self.iosapp_update_flag.get(devicename) - and interval < 180 - and self.override_interval_seconds.get(devicename) == 0): - interval_method += ',xx33ios-iosAppTrigger' - #if triggered by ios app (Zone Enter/Exit, Manual, Fetch, etc.) - #and interval < 3 min, set to 3 min. Leave alone if > 3 min. - if (self.iosapp_update_flag.get(devicename) - and interval < 180 - and interval > 30 - and self.override_interval_seconds.get(devicename) == 0): - interval = 180 - interval_method += ',33ios-iosAppTrigger' - - #if changed zones on this poll reset multiplier - if self.state_change_flag.get(devicename): - interval_multiplier = 1 - - #Check accuracy again to make sure nothing changed, update counter - if self.poor_gps_flag.get(devicename): - interval_multiplier = 1 - - except Exception as err: - attrs_msg = self._internal_error_msg(fct_name, err, 'ResetStatZone') - return attrs_msg - - try: - #Real close, final check to make sure interval is not adjusted - if (interval <= 60 - or (battery > 0 and battery <= 33 and interval >= 120)): - interval_multiplier = 1 - - interval = interval * interval_multiplier - interval, x = divmod(interval, 15) - interval = interval * 15 - - #check for max interval - if interval > self.max_interval_secs and not_inzone_flag: - interval_str = (f"{self._secs_to_time_str(self.max_interval_secs)}({self._secs_to_time_str(interval)})") - interval = self.max_interval_secs - interval_method += (f",40-Max") - else: - interval_str = self._secs_to_time_str(interval) - - interval_debug_msg = (f"●Interval-{interval_str} ({interval_method}, {log_msg}), " - f"●DirOfTrav-{dir_of_trav_msg}, " - f"●State-{self.state_last_poll.get(devicename)}->, " - f"{self.state_this_poll.get(devicename)}, " - f"Zone-{zone}") - event_msg = (f"Interval basis: {interval_method}, {log_msg}, Direction {dir_of_travel}") - #self._save_event(devicename, event_msg) - - if interval_multiplier > 1: - interval_method += (f"x{interval_multiplier}") - interval_debug_msg = (f"{interval_debug_msg}, " - f"Multiplier-{interval_multiplier} ({interval_method})") - - #check if next update is past midnight (next day), if so, adjust it - next_poll = round((self.this_update_secs + interval)/15, 0) * 15 - - # Update all dates and other fields - self.next_update_secs[devicename_zone] = next_poll - self.next_update_time[devicename_zone] = self._secs_to_time(next_poll) - self.interval_seconds[devicename_zone] = interval - self.interval_str[devicename_zone] = interval_str - self.last_update_secs[devicename_zone] = self.this_update_secs - self.last_update_time[devicename_zone] = self._time_to_12hrtime(self.this_update_time) - - #-------------------------------------------------------------------------------- - #Calculate the old_location age check based on the direction and if there are - #multiple zones being tracked from - - zi=self.track_from_zone.get(devicename).index(self.base_zone) - if zi == 0: - self.old_location_secs[devicename] = HIGH_INTEGER - - ic3dev_old_location_secs = self.old_location_secs.get(devicename) - new_old_location_secs = self._determine_old_location_secs(zone, interval) - select='' - if inzone_flag: - select='inzone' - ic3dev_old_location_secs = new_old_location_secs - - #Other base_zones are calculated before home zone, use smallest value - elif new_old_location_secs < ic3dev_old_location_secs: - select='ols < self.ols' - ic3dev_old_location_secs = new_old_location_secs - - elif base_zone_home_flag and ic3dev_old_location_secs == HIGH_INTEGER: - select='zone-home & HIGH_INTEGER' - ic3dev_old_location_secs = new_old_location_secs - - self.old_location_secs[devicename] = ic3dev_old_location_secs - old_location_secs_msg = self._secs_to_time_str(self.old_location_secs.get(devicename)) - - #-------------------------------------------------------------------------------- - #if more than 3km(1.8mi) then assume driving, used later above - if dist_from_zone_km > 3: # 1.8 mi - self.went_3km[devicename] = True - elif dist_from_zone_km < .03: # home, reset flag - self.went_3km[devicename] = False - - except Exception as err: - attrs_msg = self._internal_error_msg(fct_name, err, 'SetTimes') - - #-------------------------------------------------------------------------------- - try: - log_msg = (f"►INTERVAL FORMULA, {interval_debug_msg}") - self._log_debug_interval_msg(devicename, log_msg) - - if self.log_level_intervalcalc_flag == False: - interval_debug_msg = '' - - event_msg = (f"{EVLOG_DEBUG}Interval Results > " - f"Interval-{interval_str} ({interval_method}), " - f"LastUpdate-{self.last_update_time.get(devicename_zone)}, " - f"NextUpdate-{self.next_update_time.get(devicename_zone)}, " - f"DistTraveled-{self._format_dist(calc_dist_last_poll_moved_km)}, " - f"CurrZone-{zone}") - if self.override_interval_seconds.get(devicename) > 0: - event_msg += (f", OverrideInterval-{self._secs_to_time_str(self.override_interval_seconds.get(devicename))}") - self._save_event_halog_info(devicename, event_msg, log_title="") - - except Exception as err: - attrs_msg = self._internal_error_msg(fct_name, err, 'ShowMsgs') - - - try: - #if 'NearZone' zone, do not change the state - if near_zone_flag: - zone = NOT_HOME - - log_msg = (f"DIR OF TRAVEL ATTRS, Direction-{dir_of_travel}, " - f"LastDir-{last_dir_of_travel}, " - f"Dist-{dist_from_zone_km}, " - f"LastDist-{last_dist_from_zone_km}, " - f"SelfDist-{self.zone_dist.get(devicename_zone)}, " - f"Moved-{dist_from_zone_moved_km}," - f"WazeMoved-{waze_dist_from_zone_moved_km}") - self._log_debug_interval_msg(devicename, log_msg) - - #if poor gps and moved less than 1km, redisplay last distances - if (self.state_change_flag.get(devicename) == False - and self.poor_gps_flag.get(devicename) - and dist_last_poll_moved_km < 1): - dist_from_zone_km = self.zone_dist.get(devicename_zone) - waze_dist_from_zone_km = self.waze_dist.get(devicename_zone) - calc_dist_from_zone_km = self.calc_dist.get(devicename_zone) - waze_time_msg = self.waze_time.get(devicename_zone) - - else: - waze_time_msg = self._format_waze_time_msg(waze_time_from_zone) - - #save for next poll if poor gps - self.zone_dist[devicename_zone] = dist_from_zone_km - self.waze_dist[devicename_zone] = waze_dist_from_zone_km - self.waze_time[devicename_zone] = waze_time_msg - self.calc_dist[devicename_zone] = calc_dist_from_zone_km - - except Exception as err: - attrs_msg = self._internal_error_msg(fct_name, err, 'SetDistDir') - - #-------------------------------------------------------------------------------- - try: - #Save last and new state, set attributes - #If first time thru, set the last state to the current state - #so a zone change will not be triggered next time - - if self.state_last_poll.get(devicename) == NOT_SET: - last_state = zone - - #When put into stationary zone, also set last_poll so it - #won't trigger again on next cycle as a state change - elif (instr(zone, STATIONARY) - or instr(self.state_this_poll.get(devicename), STATIONARY)): - zone = STATIONARY - last_state = STATIONARY - - #elif self.state_this_poll.get(devicename) == AWAY: - # self.state_last_poll[devicename] = NOT_HOME - else: - last_state = self.state_this_poll.get(devicename) - - #Make sure the new 'last state' value is the internal value for - #the state (e.g., Away-->not_home) to reduce state change triggers later. - last_state = STATE_TO_ZONE_BASE.get(last_state, last_state) - self.state_last_poll[devicename] = last_state - - self.state_this_poll[devicename] = zone - self.last_located_time[devicename] = self._time_to_12hrtime(location_time) - location_age = self._secs_since(last_located_secs) - location_age_str = self._format_age(location_age) - if (poor_location_gps_flag and self.poor_gps_flag.get(devicename) == False): - location_age_str = (f"Old-{location_age_str}") - - log_msg = (f"LOCATION TIME-{devicename} location_time-{location_time}, " - f"loc_time_secs-{self._secs_to_time(last_located_secs)} ({location_age_str})") - self._log_debug_msg(devicename, log_msg) - - attrs = {} - attrs[ATTR_ZONE] = self.zone_current.get(devicename) - attrs[ATTR_ZONE_TIMESTAMP] = str(self.zone_timestamp.get(devicename)) - attrs[ATTR_LAST_ZONE] = self.zone_last.get(devicename) - attrs[ATTR_LAST_UPDATE_TIME] = self._time_to_12hrtime(self.this_update_time) - attrs[ATTR_LAST_LOCATED] = self._time_to_12hrtime(location_time) - - attrs[ATTR_INTERVAL] = interval_str - attrs[ATTR_NEXT_UPDATE_TIME] = self._secs_to_time(next_poll) - - attrs[ATTR_WAZE_TIME] = '' - if self.waze_status == WAZE_USED: - attrs[ATTR_WAZE_TIME] = waze_time_msg - attrs[ATTR_WAZE_DISTANCE] = self._km_to_mi(waze_dist_from_zone_km) - elif self.waze_status == WAZE_NOT_USED: - attrs[ATTR_WAZE_DISTANCE] = 'NotUsed' - elif self.waze_status == WAZE_NO_DATA: - attrs[ATTR_WAZE_DISTANCE] = 'NoData' - elif self.waze_status == WAZE_OUT_OF_RANGE: - if waze_dist_from_zone_km < 1: - attrs[ATTR_WAZE_DISTANCE] = '' - elif waze_dist_from_zone_km < self.waze_min_distance: - attrs[ATTR_WAZE_DISTANCE] = 'DistLow' - else: - attrs[ATTR_WAZE_DISTANCE] = 'DistHigh' - elif dir_of_travel == 'in_zone': - attrs[ATTR_WAZE_DISTANCE] = '' - elif self.waze_status == WAZE_PAUSED: - attrs[ATTR_WAZE_DISTANCE] = PAUSED - elif waze_dist_from_zone_km > 0: - attrs[ATTR_WAZE_TIME] = waze_time_msg - attrs[ATTR_WAZE_DISTANCE] = self._km_to_mi(waze_dist_from_zone_km) - else: - attrs[ATTR_WAZE_DISTANCE] = '' - - attrs[ATTR_ZONE_DISTANCE] = self._km_to_mi(dist_from_zone_km) - attrs[ATTR_CALC_DISTANCE] = self._km_to_mi(calc_dist_from_zone_km) - attrs[ATTR_DIR_OF_TRAVEL] = dir_of_travel - attrs[ATTR_TRAVEL_DISTANCE] = self._km_to_mi(dist_last_poll_moved_km) - - info_msg = self._format_info_attr( - devicename, - battery, - gps_accuracy, - dist_last_poll_moved_km, - zone) - - attrs[ATTR_INFO] = interval_debug_msg + info_msg - - #save for event log - if type(waze_time_msg) != str: waze_time_msg = '' - self.last_tavel_time[devicename_zone] = waze_time_msg - self.last_distance_str[devicename_zone] = (f"{self._km_to_mi(dist_from_zone_km)} {self.unit_of_measurement}") - self._trace_device_attributes(devicename, 'RESULTS', fct_name, attrs) - - zone = self.zone_current.get(devicename) - - event_msg = (f"Results: From-{self.zone_to_display.get(self.base_zone)} > CurrZone-" - f"{self.zone_to_display.get(zone)}, ") - event_msg +=(f"GPS-{format_gps(latitude, longitude, gps_accuracy)}, " - f"Interval-{interval_str}") - event_msg +=(f" ({interval_method}), ") if self.log_level_debug_flag else ", " - event_msg +=(f"Dist-{self._km_to_mi(dist_from_zone_km)} {self.unit_of_measurement}, " - f"TravTime-{waze_time_msg} ({dir_of_travel}), " - f"NextUpdt-{self._secs_to_time(next_poll)}, " - f"Located-{self._time_to_12hrtime(location_time)} ({location_age_str}), " - f"OldLocThreshold-{old_location_secs_msg}") - if self.stat_zone_timer.get(devicename) > 0: - event_msg += (f", WillMoveIntoStatZoneAfter-{self._secs_to_time(self.stat_zone_timer.get(devicename))} " - f"({self._format_dist(self.stat_zone_moved_total.get(devicename))})") - self._save_event_halog_info(devicename, event_msg, log_title="") - - return attrs - - except Exception as err: - attrs_msg = self._internal_error_msg(fct_name, err, 'SetAttrs') - _LOGGER.exception(err) - return attrs_msg - -######################################################### -# -# iCloud FmF or FamShr authentication returned an error or no location -# data is available. Update counter and device attributes and set -# retry intervals based on current retry count. -# -######################################################### - def _determine_interval_after_error(self, devicename, info_msg, counter=POOR_LOC_GPS_CNT): - ''' - Handle errors where the device can not be or should not be updated with - the current data. The update will be retried 4 times on a 15 sec interval. - If the error continues, the interval will increased based on the retry - count using the following cycles: - 1-4 - 15 sec - 5-8 - 1 min - 9-12 - 5min - 13-16 - 15min - >16 - 30min - - The following errors use this routine: - - iCloud Authentication errors - - FmF location data not available - - Old location - - Poor GPS Acuracy - ''' - - fct_name = "_determine_interval_after_error" - - base_zone_home_flag = (self.base_zone == HOME) - devicename_zone = self._format_devicename_zone(devicename) - - try: - interval = self._get_interval_for_error_retry_cnt(devicename, counter) - - #check if next update is past midnight (next day), if so, adjust it - next_poll = round((self.this_update_secs + interval)/15, 0) * 15 - - # Update all dates and other fields - interval_str = self._secs_to_time_str(interval) - next_updt_str = self._secs_to_time(next_poll) - - self.interval_seconds[devicename_zone] = interval - self.last_update_secs[devicename_zone] = self.this_update_secs - self.last_update_time[devicename_zone] = self._time_to_12hrtime(self.this_update_time) - self.next_update_secs[devicename_zone] = next_poll - self.next_update_time[devicename_zone] = next_updt_str - self.interval_str[devicename_zone] = interval_str - self.count_update_ignore[devicename] += 1 - - attrs = {} - attrs[ATTR_LAST_UPDATE_TIME] = self._time_to_12hrtime(self.this_update_time) - attrs[ATTR_INTERVAL] = interval_str - attrs[ATTR_NEXT_UPDATE_TIME] = next_updt_str - attrs[ATTR_POLL_COUNT] = self._format_poll_count(devicename) - - #If located more than 12 hrs ago, use dhms ago instead of time - location_age = self._secs_since(self.last_located_secs.get(devicename)) - if location_age > 42300: - attrs[ATTR_LAST_LOCATED] = f"{self.format_age(location_age)}" - info_msg = f"May be Offline, {info_msg}, LastLocated-{self.format_age(location_age)}" - self._save_event(devicename,info_msg) - - attrs[ATTR_INFO] = (f"●● {info_msg} ●●") - - this_zone = self.state_this_poll.get(devicename) - this_zone = self._format_zone_name(devicename, this_zone) - last_zone = self.state_last_poll.get(devicename) - last_zone = self._format_zone_name(devicename, last_zone) - - if self._is_inzone(devicename): - latitude = self.zone_lat.get(this_zone) - longitude = self.zone_long.get(this_zone) - - elif self._was_inzone(devicename): - latitude = self.zone_lat.get(last_zone) - longitude = self.zone_long.get(last_zone) - else: - latitude = self.last_lat.get(devicename) - longitude = self.last_long.get(devicename) - - if latitude is None or longitude is None: - latitude = self.last_lat.get(devicename) - longitude = self.last_long.get(devicename) - if latitude is None or longitude is None: - latitude = self.zone_lat.get(last_zone) - longitude = self.zone_long.get(last_zone) - if latitude is None or longitude is None: - event_msg = "Aborting update, no location data" - self._save_event_halog_error(devicename,event_msg) - return - - kwargs = self._setup_base_kwargs(devicename, - latitude, longitude, 0, 0) - - self._update_device_attributes(devicename, kwargs, attrs, 'DetIntlErrorRetry') - self._update_device_sensors(devicename, kwargs) - self._update_device_sensors(devicename, attrs) - self._update_stationary_zone_location(devicename) - - self.device_being_updated_flag[devicename] = False - - #Set the lat/long for the Error Msg if not_set - if this_zone == NOT_SET: - latitude = 0 - longitude = 0 - - event_msg = (f"{EVLOG_DEBUG}Discarded Results: {self.zone_to_display.get(self.base_zone)} > " - f"CurrZone-{this_zone}, " - f"GPS-{format_gps(latitude, longitude, 0)}, " - f"Interval-{interval_str}, " - f"NextUpdt-{next_updt_str}, " - f"OldLocPoorGpsCnt-#{self.poor_location_gps_cnt.get(devicename)}, " - f"UpdateErrorCnt-#{self.count_update_ignore.get(devicename)}, " - f"InfoMsg-{info_msg}") - self._save_event(devicename, event_msg) - - except Exception as err: - _LOGGER.exception(err) - -######################################################### -# -# UPDATE DEVICE LOCATION & INFORMATION ATTRIBUTE FUNCTIONS -# -######################################################### - def _get_distance_data(self, devicename, latitude, longitude, - gps_accuracy, poor_location_gps_flag): - """ Determine the location of the device. - Returns: - - zone (current zone from lat & long) - set to HOME if distance < home zone radius - - dist_from_zone_km (mi or km) - - dist_traveled (since last poll) - - dir_of_travel (towards, away_from, stationary, in_zone, - left_zone, near_home) - """ - - fct_name = '_get_distance_data' - - try: - if latitude is None or longitude is None: - attrs = self._internal_error_msg(fct_name, 'lat/long=None', 'NoLocation') - return (ERROR, attrs) - - base_zone_home_flag = (self.base_zone == HOME) - devicename_zone = self._format_devicename_zone(devicename) - - log_msg = ("GET DEVICE DISTANCE DATA Entered") - self._log_debug_interval_msg(devicename, log_msg) - - last_dir_of_travel = NOT_SET - last_dist_from_zone_km = 0 - last_waze_time = 0 - last_lat = self.base_zone_lat - last_long = self.base_zone_long - ic3dev_timestamp_secs = 0 - - zone = self.base_zone - calc_dist_from_zone_km = 0 - calc_dist_last_poll_moved_km = 0 - calc_dist_from_zone_moved_km = 0 - - - #Get the devicename's icloud3 attributes - entity_id = self.device_tracker_entity_ic3.get(devicename) - attrs = self._get_device_attributes(entity_id) - - self._trace_device_attributes(devicename, 'READ', fct_name, attrs) - - except Exception as err: - _LOGGER.exception(err) - error_msg = (f"Entity-{entity_id}, Err-{err}") - attrs = self._internal_error_msg(fct_name, error_msg, 'GetAttrs') - return (ERROR, attrs) - - try: - #Not available if first time after reset - if self.state_last_poll.get(devicename) != NOT_SET: - log_msg = ("Distance info available") - if ATTR_TIMESTAMP in attrs: - ic3dev_timestamp_secs = attrs[ATTR_TIMESTAMP] - ic3dev_timestamp_secs = self._timestamp_to_time(ic3dev_timestamp_secs) - else: - ic3dev_timestamp_secs = 0 - - last_dist_from_zone_km_s = self._get_attr(attrs, ATTR_ZONE_DISTANCE, NUMERIC) - last_dist_from_zone_km = last_dist_from_zone_km_s - - last_waze_time = self._get_attr(attrs, ATTR_WAZE_TIME) - last_dir_of_travel = self._get_attr(attrs, ATTR_DIR_OF_TRAVEL) - last_dir_of_travel = last_dir_of_travel.replace('*', '', 99) - last_dir_of_travel = last_dir_of_travel.replace('?', '', 99) - last_lat = self.last_lat.get(devicename) - last_long = self.last_long.get(devicename) - - #get last interval - interval_str = self.interval_str.get(devicename_zone) - interval = self._time_str_to_secs(interval_str) - - this_lat = latitude - this_long = longitude - - except Exception as err: - _LOGGER.exception(err) - attrs = self._internal_error_msg(fct_name, err, 'SetupLocation') - return (ERROR, attrs) - - try: - zone = self._get_zone(devicename, this_lat, this_long) - - log_msg = (f"LAT-LONG GPS INITIALIZED {zone}, LastDirOfTrav-{last_dir_of_travel}, " - f"LastGPS=({last_lat}, {last_long}), ThisGPS=({this_lat}, {this_long}), " - f"UsingGPS=({latitude}, {longitude}), GPS.Accur-{gps_accuracy}, " - f"GPS.Threshold-{self.gps_accuracy_threshold}") - self._log_debug_interval_msg(devicename, log_msg) - - except Exception as err: - _LOGGER.exception(err) - attrs = self._internal_error_msg(fct_name, err, 'GetCurrZone') - return (ERROR, attrs) - - try: - # Get Waze distance & time - # Will return [error, 0, 0, 0] if error - # [out_of_range, dist, time, info] if - # last_dist_from_zone_km > - # last distance from home - # [ok, 0, 0, 0] if zone=home - # [ok, distFmHome, timeFmHome, info] if OK - - calc_dist_from_zone_km = self._calc_distance_km(this_lat, this_long, - self.base_zone_lat, self.base_zone_long) - calc_dist_last_poll_moved_km = self._calc_distance_km(last_lat, last_long, - this_lat, this_long) - calc_dist_from_zone_moved_km= (calc_dist_from_zone_km - last_dist_from_zone_km) - calc_dist_from_zone_km = self._round_to_zero(calc_dist_from_zone_km) - calc_dist_last_poll_moved_km = self._round_to_zero(calc_dist_last_poll_moved_km) - calc_dist_from_zone_moved_km= self._round_to_zero(calc_dist_from_zone_moved_km) - - if self.distance_method_waze_flag: - #If waze paused via icloud_command or close to a zone, default to pause - if self.waze_manual_pause_flag or self.waze_close_to_zone_pause_flag: - self.waze_status = WAZE_PAUSED - else: - self.waze_status = WAZE_USED - else: - self.waze_status = WAZE_NOT_USED - - log_msg = (f"Zone-{devicename_zone}, wStatus-{self.waze_status}, " - f"calc_dist-{calc_dist_from_zone_km}, wManualPauseFlag-{self.waze_manual_pause_flag}, " - f"CloseToZoneFlag-{self.waze_close_to_zone_pause_flag}") - self._log_debug_interval_msg(devicename, log_msg) - - #Make sure distance and zone are correct for HOME, initialize - if calc_dist_from_zone_km <= .05 or zone == self.base_zone: - zone = self.base_zone - calc_dist_from_zone_km = 0 - calc_dist_last_poll_moved_km = 0 - calc_dist_from_zone_moved_km = 0 - self.waze_status = WAZE_PAUSED - - #Near zone & towards or in near_zone - elif (calc_dist_from_zone_km < 1 - and last_dir_of_travel in ('towards', 'near_zone')): - self.waze_status = WAZE_PAUSED - self.waze_close_to_zone_pause_flag = True - - log_msg = "Using Calc Method (near Home & towards or Waze off)" - self._log_debug_interval_msg(devicename, log_msg) - - #Determine if Waze should be used based on calculated distance - elif (calc_dist_from_zone_km > self.waze_max_distance - or calc_dist_from_zone_km < self.waze_min_distance): - self.waze_status = WAZE_OUT_OF_RANGE - - #Initialize Waze default fields - waze_dist_from_zone_km = calc_dist_from_zone_km - waze_time_from_zone = 0 - waze_dist_last_poll_moved_km = calc_dist_last_poll_moved_km - waze_dist_from_zone_moved_km = calc_dist_from_zone_moved_km - self.waze_history_data_used_flag[devicename_zone] = False - - #Use Calc if close to home, Waze not accurate when close - log_msg = (f"Zone-{devicename_zone}, Status-{self.waze_status}, " - f"calc_dist-{calc_dist_from_zone_km}, " - f"ManualPauseFlag-{self.waze_manual_pause_flag}," - f"CloseToZoneFlag-{self.waze_close_to_zone_pause_flag}") - self._log_debug_interval_msg(devicename, log_msg) - - except Exception as err: - _LOGGER.exception(err) - attrs = self._internal_error_msg(fct_name, err, 'InitializeDist') - return (ERROR, attrs) - - try: - if self.waze_status == WAZE_USED: - try: - #See if another device is close with valid Waze data. - #If so, use it instead of calling Waze again. event_msg will have - #msg for log file if history was used - - waze_dist_time_info = self._get_waze_from_data_history( - devicename, - calc_dist_from_zone_km, - this_lat, - this_long) - - #No Waze data from close device. Get it from Waze - if waze_dist_time_info is None: - waze_dist_time_info = self._get_waze_data( - devicename, - this_lat, this_long, - last_lat, last_long, - zone, - last_dist_from_zone_km) - - self.waze_status = waze_dist_time_info[0] - - if self.waze_status == WAZE_USED: - waze_dist_from_zone_km = waze_dist_time_info[1] - waze_time_from_zone = waze_dist_time_info[2] - waze_dist_last_poll_moved_km = waze_dist_time_info[3] - waze_dist_from_zone_moved_km= round(waze_dist_from_zone_km - last_dist_from_zone_km, 2) - waze_time_msg = self._format_waze_time_msg(waze_time_from_zone) - - #Save new Waze data or retimestamp data from another - #device. - if (gps_accuracy <= self.gps_accuracy_threshold - and waze_dist_from_zone_km > 0 - and poor_location_gps_flag is False): - self.waze_distance_history[devicename_zone] = \ - [self._time_now_secs(), - this_lat, - this_long, - waze_dist_time_info] - - else: - self.waze_distance_history[devicename_zone] = [] - - except Exception as err: - _LOGGER.exception(err) - self.waze_status = WAZE_NO_DATA - - except Exception as err: - attrs = self._internal_error_msg(fct_name, err, 'WazeNoData') - self.waze_status = WAZE_NO_DATA - - try: - #don't reset data if poor gps, use the best we have - if zone == self.base_zone: - distance_method = 'Home/Calc' - dist_from_zone_km = 0 - dist_last_poll_moved_km = 0 - dist_from_zone_moved_km = 0 - elif self.waze_status == WAZE_USED: - distance_method = 'Waze' - dist_from_zone_km = waze_dist_from_zone_km - dist_last_poll_moved_km = waze_dist_last_poll_moved_km - dist_from_zone_moved_km = waze_dist_from_zone_moved_km - else: - distance_method = 'Calc' - dist_from_zone_km = calc_dist_from_zone_km - dist_last_poll_moved_km = calc_dist_last_poll_moved_km - dist_from_zone_moved_km = calc_dist_from_zone_moved_km - - if dist_from_zone_km > 99: dist_from_zone_km = int(dist_from_zone_km) - if dist_last_poll_moved_km > 99: dist_last_poll_moved_km = int(dist_last_poll_moved_km) - if dist_from_zone_moved_km> 99: dist_from_zone_moved_km= int(dist_from_zone_moved_km) - - dist_from_zone_moved_km= self._round_to_zero(dist_from_zone_moved_km) - - log_msg = (f"DISTANCES CALCULATED, " - f"Zone-{zone}, Method-{distance_method}, " - f"LastDistFmHome-{self._format_dist(last_dist_from_zone_km)}, " - f"WazeStatus-{self.waze_status}") - self._log_debug_interval_msg(devicename, log_msg) - log_msg = (f"DISTANCES ...Waze, " - f"Dist-{self._format_dist(waze_dist_from_zone_km)}, " - f"LastPollMoved-{self._format_dist(waze_dist_last_poll_moved_km)}, " - f"FmHomeMoved-{self._format_dist(waze_dist_from_zone_moved_km)}, " - f"Time-{waze_time_from_zone}, " - f"Status-{self.waze_status}") - self._log_debug_interval_msg(devicename, log_msg) - log_msg = (f"DISTANCES ...Calc, " - f"Dist-{self._format_dist(calc_dist_from_zone_km)}, " - f"LastPollMoved-{self._format_dist(calc_dist_last_poll_moved_km)}, " - f"FmHomeMoved-{self._format_dist(calc_dist_from_zone_moved_km)}") - self._log_debug_interval_msg(devicename, log_msg) - - #if didn't move far enough to determine towards or away_from, - #keep the current distance and add it to the distance on the next - #poll - if (dist_from_zone_moved_km> -.3 and dist_from_zone_moved_km< .3): - dist_from_zone_moved_km+= \ - self.dist_from_zone_km_small_move_total.get(devicename) - self.dist_from_zone_km_small_move_total[devicename] = \ - dist_from_zone_moved_km - else: - self.dist_from_zone_km_small_move_total[devicename] = 0 - - except Exception as err: - _LOGGER.exception(err) - attrs = self._internal_error_msg(fct_name, err, 'CalcDist') - return (ERROR, attrs) - - try: - section = "dir_of_trav" - dir_of_travel = '' - dir_of_trav_msg = '' - if zone not in (NOT_HOME, 'near_zone'): - dir_of_travel = 'in_zone' - dir_of_trav_msg = (f"Zone-{zone}") - - elif last_dir_of_travel == "in_zone": - dir_of_travel = 'left_zone' - dir_of_trav_msg = (f"LastZone-{last_dir_of_travel}") - - elif dist_from_zone_moved_km<= -.3: #.18 mi - dir_of_travel = 'towards' - dir_of_trav_msg = (f"Dist-{self._format_dist(dist_from_zone_moved_km)}") - - elif dist_from_zone_moved_km>= .3: #.18 mi - dir_of_travel = AWAY_FROM - dir_of_trav_msg = (f"Dist-{self._format_dist(dist_from_zone_moved_km)}") - - elif self.poor_gps_flag.get(devicename): - dir_of_travel = 'Poor.GPS' - dir_of_trav_msg = ("Poor.GPS-{gps_accuracy}") - - else: - #didn't move far enough to tell current direction - dir_of_travel = (f"{last_dir_of_travel}?") - dir_of_trav_msg = (f"Moved-{self._format_dist(dist_last_poll_moved_km)}") - - #If moved more than stationary zone limit (~.06km(200ft)), - #reset check StatZone still timer and check again next poll - #Use calc distance rather than waze for better accuracy - section = "test if home" - - if (calc_dist_from_zone_km > self.stat_min_dist_from_zone_km - and zone == NOT_HOME): - - section = "test moved" - #Reset stationary zone timer - if (calc_dist_last_poll_moved_km > self.stat_dist_move_limit - or devicename not in self.stat_zone_moved_total - or self.this_update_secs > self.stat_zone_timer.get(devicename)+120): - section = "test moved-reset stat zone " - - event_msg = (f"Stat Zone > Reset Timer, ") - if calc_dist_last_poll_moved_km > self.stat_dist_move_limit: - event_msg += (f"MovedOverLimit-{(calc_dist_last_poll_moved_km > self.stat_dist_move_limit)}, ") - if devicename not in self.stat_zone_moved_total: - event_msg += "Initial Setup, " - if (self.this_update_secs > self.stat_zone_timer.get(devicename)+120): - event_msg += (f"ResetTimer-{(self.this_update_secs > self.stat_zone_timer.get(devicename)+120)}, ") - - event_msg += (f"Moved-{self._format_dist(calc_dist_last_poll_moved_km)}, " - f"Timer-{self._secs_to_time(self.stat_zone_timer.get(devicename))}, ") - - self.stat_zone_moved_total[devicename] = 0 - self.stat_zone_timer[devicename] = self.this_update_secs + self.stat_zone_still_time - - event_msg += (f" to {self._secs_to_time(self.stat_zone_timer.get(devicename))}") - self._evlog_debug_msg(devicename, event_msg) - - #If moved less than the stationary zone limit, update the - #distance moved and check to see if now in a stationary zone - elif devicename in self.stat_zone_moved_total: - section = "StatZonePrep" - self.stat_zone_moved_total[devicename] += calc_dist_last_poll_moved_km - if self.stat_zone_timer.get(devicename) > 0: - stat_zone_timer_left = self.stat_zone_timer.get(devicename) - self.this_update_secs - else: - stat_zone_timer_left = HIGH_INTEGER - - log_msg = (f"Stat Zone Movement > " - f"TotalMoved-{self._format_dist(self.stat_zone_moved_total.get(devicename))}, " - f"Timer-{self._secs_to_time(self.stat_zone_timer.get(devicename))}, " - f"TimerLeft- {stat_zone_timer_left} secs, " - f"TimerExpired-{stat_zone_timer_left <= 0}" - f"UnderMoveLimit-{self.stat_zone_moved_total.get(devicename) <= self.stat_dist_move_limit}, " - f"DistFmZone-{self._format_dist(dist_from_zone_km)}") - self._evlog_debug_msg(devicename, log_msg) - self._log_debug_msg(devicename, log_msg) - section = "CheckNowinzone_stationary" - - #See if moved less than the stationary zone movement limit - #If updating via the ios app and the current state is stationary, - #make sure it is kept in the stationary zone - if (self.stat_zone_moved_total.get(devicename) <= self.stat_dist_move_limit - and stat_zone_timer_left <= 0): - dir_of_travel = STATIONARY - dir_of_trav_msg = (f"Age-{self._secs_to(self.stat_zone_timer.get(devicename))}s, " - f"Moved-{self.stat_zone_moved_total.get(devicename)}") - else: - self.stat_zone_moved_total[devicename] = 0 - - section = "Finalize" - dir_of_trav_msg = (f"{dir_of_travel}({dir_of_trav_msg})") - log_msg = (f"DIR OF TRAVEL DETERMINED, {dir_of_trav_msg}") - self._log_debug_interval_msg(devicename, log_msg) - - dist_from_zone_km = self._round_to_zero(dist_from_zone_km) - dist_from_zone_moved_km = self._round_to_zero(dist_from_zone_moved_km) - dist_last_poll_moved_km = self._round_to_zero(dist_last_poll_moved_km) - waze_dist_from_zone_km = self._round_to_zero(waze_dist_from_zone_km) - calc_dist_from_zone_moved_km = self._round_to_zero(calc_dist_from_zone_moved_km) - waze_dist_last_poll_moved_km = self._round_to_zero(waze_dist_last_poll_moved_km) - calc_dist_last_poll_moved_km = self._round_to_zero(calc_dist_last_poll_moved_km) - last_dist_from_zone_km = self._round_to_zero(last_dist_from_zone_km) - - log_msg = (f"GET DEVICE DISTANCE DATA Complete, " - f"CurrentZone-{zone}, DistFmHome-{dist_from_zone_km}, " - f"DistFmHomeMoved-{dist_from_zone_moved_km}, " - f"DistLastPollMoved-{dist_last_poll_moved_km}") - self._log_debug_interval_msg(devicename, log_msg) - - distance_data = (zone, - dir_of_travel, - dist_from_zone_km, - dist_from_zone_moved_km, - dist_last_poll_moved_km, - waze_dist_from_zone_km, - calc_dist_from_zone_km, - waze_dist_from_zone_moved_km, - calc_dist_from_zone_moved_km, - waze_dist_last_poll_moved_km, - calc_dist_last_poll_moved_km, - waze_time_from_zone, - last_dist_from_zone_km, - last_dir_of_travel, - dir_of_trav_msg, - ic3dev_timestamp_secs) - - log_msg = (f"DISTANCE DATA-{devicename}-{distance_data}") - self._log_debug_msg(devicename, log_msg) - evlog_msg = (f"Distance Data > DirOfTrav-{dir_of_travel}, " - f"LastDirOfTrav-{last_dir_of_travel}, " - f"DistFmZone-{self._format_dist(dist_from_zone_km)}, " - f"LastDistFmZone-{self._format_dist(last_dist_from_zone_km)}, " - f"DistFmZoneMoved-{self._format_dist(dist_from_zone_moved_km)}, " - f"DistFmLastPollMoved-{self._format_dist(dist_last_poll_moved_km)}") - self._evlog_debug_msg(devicename, evlog_msg) - - return distance_data - - except Exception as err: - _LOGGER.exception(err) - attrs = self._internal_error_msg(fct_name+section, err, 'Finalize') - return (ERROR, attrs) - -#-------------------------------------------------------------------------------- - def _determine_old_location_secs(self, zone, interval): - """ - Calculate the time between the location timestamp and now (age) a - location record must be before it is considered old - """ - if self.old_location_threshold > 0: - return self.old_location_threshold - - old_location_secs = 60 - if self._is_inzone_zonename(zone): - old_location_secs = interval * .025 #inzone interval --> 2.5% - if old_location_secs < 90: old_location_secs = 90 - - elif interval < 90: - old_location_secs = 60 #60 secs if < 1.5 min - - else: - old_location_secs = interval * .125 #12.5% of the interval - - if old_location_secs < 61: - old_location_secs = 61 - elif old_location_secs > 600: - old_location_secs = 600 - - #IOS App old location time minimum is 3 min - if self.TRK_METHOD_IOSAPP and old_location_secs < 180: - old_location_secs == 180 - - return old_location_secs - -######################################################### -# -# DEVICE ATTRIBUTES ROUTINES -# -######################################################### - def _get_state(self, entity_id): - """ - Get current state of the device_tracker entity - (zone's name, actual state (home, away) or zone's - friendly name) and return it's zone name - """ - - try: - entity_state = self.hass.states.get(entity_id).state - - state = self.state_to_zone.get(entity_state, entity_state.lower()) - - except Exception as err: - #When starting iCloud3, the device_tracker for the iosapp might - #not have been set up yet. Catch the entity_id error here. - #_LOGGER.exception(err) - state = NOT_SET - - return state -#-------------------------------------------------------------------- - def _set_state(self, entity_id, state_value, attrs_value): - """ - General routine for setting the state and attributes of an entity_id - """ - - try: - self.hass.states.set(entity_id, state_value, attrs_value) - - except Exception as err: - log_msg = (f"Error updating entity > {entity_id}, StateValue-{state_value}, " - f"AttrsValue-{attrs_value}") - self._log_error_msg(log_msg) - _LOGGER.exception(err) - -#-------------------------------------------------------------------- - def _get_entity_last_changed_time(self, entity_id, devicename): - """ - Get entity's last changed time attribute - Last changed time format '2019-09-09 14:02:45.12345+00:00' (utc value) - Return time, seconds, timestamp - """ - - try: - timestamp_utc = str(self.hass.states.get(entity_id).last_changed) - - timestamp_utc = timestamp_utc.split(".")[0] - secs = self._timestamp_to_secs(timestamp_utc, UTC_TIME) - hhmmss = self._secs_to_time(secs) - timestamp = self._secs_to_timestamp(secs) - age_secs = self.this_update_secs - secs - dhms_age_str = self._secs_to_dhms_str(age_secs) - - return hhmmss, secs, timestamp, age_secs, dhms_age_str - - except Exception as err: - #_LOGGER.exception(err) - return '', 0, TIMESTAMP_ZERO, 0, '' -#-------------------------------------------------------------------- - def _get_device_attributes(self, entity_id): - """ Get attributes of the device """ - - try: - ic3dev_data = self.hass.states.get(entity_id) - ic3dev_attrs = ic3dev_data.attributes - - retry_cnt = 0 - while retry_cnt < 10: - if ic3dev_attrs: - break - retry_cnt += 1 - log_msg = (f"No attribute data returned for {entity_id}. Retrying #{retry_cnt}") - self._log_debug_msg('*', log_msg) - - except (KeyError, AttributeError): - ic3dev_attrs = {} - pass - - except Exception as err: - _LOGGER.exception(err) - ic3dev_attrs = {} - ic3dev_attrs[ATTR_TRIGGER] = (f"Error {err}") - - return dict(ic3dev_attrs) - -#-------------------------------------------------------------------- - @staticmethod - def _get_attr(attributes, attribute_name, numeric = False): - ''' Get an attribute out of the attrs attributes if it exists''' - if attribute_name in attributes: - return attributes[attribute_name] - elif numeric: - return 0 - else: - return '' - -#-------------------------------------------------------------------- - def _update_device_attributes(self, devicename, kwargs: str = None, - attrs: str = None, fct_name: str = UNKNOWN): - """ - Update the device and attributes with new information - On Entry, kwargs = {} or contains the base attributes. - - Trace the interesting attributes if debugging. - - Full set of attributes is: - 'gps': (27.726639, -80.3904565), 'battery': 61, 'gps_accuracy': 65.0 - 'dev_id': 'lillian_iphone', 'host_name': 'Lillian', - 'location_name': HOME, 'source_type': 'gps', - 'attributes': {'interval': '2 hrs', 'last_update': '10:55:17', - 'next_update': '12:55:15', 'travel_time': '', 'distance': 0, - 'calc_distance': 0, 'waze_distance': 0, 'dir_of_travel': 'in_zone', - 'travel_distance': 0, 'info': ' ●Battery-61%', - 'group': 'gary_icloud', 'authenticated': '02/22/19 10:55:10', - 'last_located': '10:55:15', 'device_status': 'online', - ATTR_LOW_POWER_MODE: False, 'battery_status': 'Charging', - 'tracked_devices': 'gary_icloud/gary_iphone, - gary_icloud/lillian_iphone', 'trigger': 'iCloud', - 'timestamp': '2019-02-22T10:55:17.543', 'poll_count': '1:0:1'} - - {'source_type': 'gps', 'latitude': 27.726639, 'longitude': -80.3904565, - 'gps_accuracy': 65.0, 'battery': 93, 'zone': HOME, - 'last_zone': HOME, 'zone_timestamp': '03/13/19, 9:47:35', - 'trigger': 'iCloud', 'timestamp': '2019-03-13T09:47:35.405', - 'interval': '2 hrs', 'travel_time': '', 'distance': 0, - 'calc_distance': 0, 'waze_distance': '', 'last_located': '9:47:34', - 'last_update': '9:47:35', 'next_update': '11:47:30', - 'poll_count': '1:0:2', 'dir_of_travel': 'in_zone', - 'travel_distance': 0, 'info': ' ●Battery-93%', - 'battery_status': 'NotCharging', 'device_status': - 'online', ATTR_LOW_POWER_MODE: False, - 'authenticated': '03/13/19, 9:47:26', - 'tracked_devices': 'gary_icloud/gary_iphone, gary_icloud/lillian_iphone', - 'group': 'gary_icloud', 'friendly_name': 'Gary', - 'icon': 'mdi:cellphone-iphone', - 'entity_picture': '/local/gary-caller_id.png'} - """ - - zone = self.zone_current.get(devicename) - ic3dev_state = self.state_this_poll.get(devicename) - ic3dev_state_fname = ic3dev_state - - ####################################################################### - #The current zone is based on location of the device after it is looked - #up in the zone tables. - #The ic3dev_state is from the original trigger value when the poll started. - #If the device went from one zone to another zone, an enter/exit trigger - #may not have been issued. If the trigger was the next update time - #reached, the ic3dev_state and zone many now not match. (v2.0.2) - - if ic3dev_state == NOT_SET or zone == NOT_SET or zone == '': - pass - - #If ic3dev_state is 'stationary' and in a stationary zone, nothing to do - elif ic3dev_state == STATIONARY and instr(zone, STATIONARY): - pass - - #If state is 'stationary' and in another zone, reset the state to the - #current zone that was based on the device location. - #If the state is in a zone but not the current zone, change the state - #to the current zone that was based on the device location. - elif ((ic3dev_state == STATIONARY - and self._is_inzone(zone)) - or (self._is_inzone(ic3dev_state) - and self._is_inzone(zone) - and ic3dev_state != zone)): - if self._check_overlapping_zone(ic3dev_state, zone) == False: - event_msg = (f"State/Zone mismatch > Resetting iC3 State ({ic3dev_state}) " - f"to ({zone})") - self._save_event(devicename, event_msg) - ic3dev_state = zone - - elif ic3dev_state == HOME: - self.waze_distance_history = {} - - ic3dev_state_fname = self.zone_to_display.get(ic3dev_state, ic3dev_state) - - #Update the device timestamp - if not attrs: - attrs = {} - if ATTR_TIMESTAMP in attrs: - timestamp = attrs[ATTR_TIMESTAMP] - else: - timestamp = dt_util.now().strftime(ATTR_TIMESTAMP_FORMAT)[0:19] - attrs[ATTR_TIMESTAMP] = timestamp - - #Calculate and display how long the update took - update_took_time = round(time.time() - self.update_timer.get(devicename), 2) - if update_took_time > 3 and ATTR_INFO in attrs: - attrs[ATTR_INFO] = f"{attrs[ATTR_INFO]} • Took {update_took_time}s" - - attrs[ATTR_NAME] = self.fname.get(devicename) - attrs[ATTR_GROUP] = self.group - attrs[ATTR_TRACKING] = (f"{self.track_devicename_list} ({self.trk_method_short_name})") - attrs[ATTR_ICLOUD3_VERSION] = VERSION - - #Add update time to trigger to be able to detect trigger change by iOS App - #and by iC3. - new_trigger = (f"{self.trigger.get(devicename)}@").split('@')[0] - new_trigger = (f"{new_trigger}@{self.last_located_time.get(devicename)}") - - self.trigger[devicename] = new_trigger - attrs[ATTR_TRIGGER] = new_trigger - - #Update sensor._last_update_trigger if IOS App detected - #and iCloud3 has been running for at least 10 secs to let HA & - #mobile_app start up to avoid error if iC3 loads before the mobile_app - - #Set the gps attribute and update the attributes via self.see - if kwargs == {} or not kwargs: - kwargs = self._setup_base_kwargs( - devicename, - self.last_lat.get(devicename), - self.last_long.get(devicename), - 0, 0) - - kwargs['dev_id'] = devicename - kwargs['host_name'] = self.fname.get(devicename) - kwargs['location_name'] = ic3dev_state_fname - kwargs['source_type'] = 'gps' - kwargs[ATTR_ATTRIBUTES] = attrs - self.see(**kwargs) - - if ic3dev_state == "Not Set": - ic3dev_state = "not_set" - - self.state_this_poll[devicename] = ic3dev_state.lower() - - self._trace_device_attributes(devicename, 'WRITE', fct_name, kwargs) - - if timestamp == '': #Bypass if not initializing - return - - retry_cnt = 1 - timestamp = timestamp[10:] #Strip off date - - #Quite often, the attribute update has not actually taken - #before other code is executed and errors occur. - #Reread the attributes of the ones just updated to make sure they - #were updated corectly. Verify by comparing the timestamps. If - #differet, retry the attribute update. HA runs in multiple threads. - try: - entity_id = self.device_tracker_entity_ic3.get(devicename) - while retry_cnt < 99: - chk_see_attrs = self._get_device_attributes(entity_id) - chk_timestamp = str(chk_see_attrs.get(ATTR_TIMESTAMP)) - chk_timestamp = chk_timestamp[10:] - - if timestamp == chk_timestamp: - break - - if (retry_cnt % 10) == 0: - time.sleep(1) - retry_cnt += 1 - - self.see(**kwargs) - - except Exception as err: - _LOGGER.exception(err) - - return - -#-------------------------------------------------------------------- - def _setup_base_kwargs(self, devicename, latitude, longitude, - battery, gps_accuracy): - - #check to see if device set up yet - ic3dev_state = self.state_this_poll.get(devicename) - zone_name = None - - if latitude == self.zone_home_lat: - pass - elif ic3dev_state == NOT_SET: - zone_name = self.base_zone - - #if in zone, replace lat/long with zone center lat/long - elif self._is_inzone_zonename(ic3dev_state): - zone_name = self._format_zone_name(devicename, ic3dev_state) - - debug_msg=(f"SETUP BASE KWARGS zone_name-{zone_name}, inzone-state-{self._is_inzone_zonename(ic3dev_state)}") - self._log_debug_msg(devicename, debug_msg) - - if zone_name and self._is_inzone_zonename(ic3dev_state): - zone_lat = self.zone_lat.get(zone_name) - zone_long = self.zone_long.get(zone_name) - zone_dist = self._calc_distance_m(latitude, longitude, zone_lat, zone_long) - - debug_msg=(f"zone_lat/long=({zone_lat}, {zone_long}), " - f"lat-long=({latitude}, {longitude}), zone_dist-{zone_dist}, " - f"zone-radius-{self.zone_radius_km.get(zone_name, 100)}") - self._log_debug_msg(devicename, debug_msg) - - #Move center of stationary zone to new location if more than 10m from old loc - if (instr(zone_name, STATIONARY) - and self.in_stationary_zone_flag.get(devicename) - and zone_dist > 10): - self._update_stationary_zone( - devicename, - latitude, - longitude, - STAT_ZONE_NEW_LOCATION,'_setup_base_kwargs') - - #inside zone, move to center - elif (self.center_in_zone_flag - and zone_dist <= self.zone_radius_m.get(zone_name, 100) - and (latitude != zone_lat or longitude != zone_long)): - event_msg = (f"Moving to zone center > {zone_name}, " - f"GPS-{format_gps(latitude, longitude, gps_accuracy, zone_lat, zone_long)}, " - f"Distance-{self._format_dist_m(zone_dist)}") - self._save_event(devicename, event_msg) - self._log_debug_msg(devicename, event_msg) - - latitude = zone_lat - longitude = zone_long - self.last_lat[devicename] = zone_lat - self.last_long[devicename] = zone_long - - gps_lat_long = (latitude, longitude) - kwargs = {} - kwargs['gps'] = gps_lat_long - kwargs[ATTR_BATTERY] = int(battery) - kwargs[ATTR_GPS_ACCURACY] = gps_accuracy - - return kwargs - -#-------------------------------------------------------------------- - def _format_entity_id(self, devicename): - return (f"{DOMAIN}.{devicename}") - -#-------------------------------------------------------------------- - def _format_fname_devtype(self, devicename): - if devicename == "*": - return "" - else: - return (f"{self.fname.get(devicename, '')} ({self.device_type.get(devicename, '')})") - -#-------------------------------------------------------------------- - def _format_fname_devicename(self, devicename): - if devicename == "*": - return "" - else: - return (f"{self.fname.get(devicename, '')} ({devicename})") - -#-------------------------------------------------------------------- - def _format_fname_zone(self, zone): - return (f"{self.zone_to_display.get(zone, zone.title())}") - -#-------------------------------------------------------------------- - def _format_devicename_zone(self, devicename, zone = None): - if zone is None: - zone = self.base_zone - return (f"{devicename}:{zone}") -#-------------------------------------------------------------------- - def _format_list(self, arg_list): - formatted_list = str(arg_list) - formatted_list = formatted_list.replace("[", "").replace("]", "") - formatted_list = formatted_list.replace("{", "").replace("}", "") - formatted_list = formatted_list.replace("'", "").replace(",", "CRLF• ") - return (f"CRLF• {formatted_list}") -#-------------------------------------------------------------------- - def _format_age(self, secs): - return (f"{self._secs_to_time_str(secs)} ago") -#-------------------------------------------------------------------- - def _trace_device_attributes(self, devicename, description, - fct_name, attrs): - - try: - #Extract only attrs needed to update the device - if attrs is None: - return - - attrs_in_attrs = {} - if (instr(description, "iCloud") or instr(description, "FamShr")): - attrs_base_elements = TRACE_ICLOUD_ATTRS_BASE - if ATTR_LOCATION in attrs: - attrs_in_attrs = attrs[ATTR_LOCATION] - elif 'Zone' in description: - attrs_base_elements = attrs - else: - attrs_base_elements = TRACE_ATTRS_BASE - if ATTR_ATTRIBUTES in attrs: - attrs_in_attrs = attrs[ATTR_ATTRIBUTES] - - trace_attrs = {k: v for k, v in attrs.items() \ - if k in attrs_base_elements} - - trace_attrs_in_attrs = {k: v for k, v in attrs_in_attrs.items() \ - if k in attrs_base_elements} - - #trace_attrs = attrs - - ls = self.state_last_poll.get(devicename) - cs = self.state_this_poll.get(devicename) - log_msg = (f"{description} Attrs ___ ({fct_name})") - self._log_debug_msg(devicename, log_msg) - - log_msg = (f"{description} Last State-{ls}, This State-{cs}") - self._log_debug_msg(devicename, log_msg) - - log_msg = (f"{description} Attrs-{trace_attrs}{trace_attrs_in_attrs}") - self._log_debug_msg(devicename, log_msg) - - - except Exception as err: - pass - #_LOGGER.exception(err) - - return - -#-------------------------------------------------------------------- - def _broadcast_message(self, service_data): - '''Send a message to all devices ''' - - for devicename in self.tracked_devices: - self._send_message_to_device(devicename, service_data) - -#-------------------------------------------------------------------- - def _send_message_to_device(self, devicename, service_data): - ''' - Send a message to the device. An example message is: - service_data = { - "title": "iCloud3/iOSApp Zone Action Needed", - "message": "The iCloud3 Stationary Zone may "\ - "not be loaded in the iOSApp. Force close "\ - "the iOSApp from the iOS App Switcher. "\ - "Then restart the iOSApp to reload the HA zones. "\ - f"Distance-{dist_from_zone_m} m, " - f"StatZoneTestDist-{zone_radius_m * 2} m", - "data": {"subtitle": "Stationary Zone Exit "\ - "Trigger was not received"}} - ''' - try: - if self.notify_iosapp_entity.get(devicename, None) == None: - return - - if service_data.get('message') != "request_location_update": - evlog_msg = (f"{EVLOG_NOTICE}Sending Message to Device > " - f"Message-{service_data.get('message')}") - self._save_event_halog_info(devicename, evlog_msg) - - for notify_devicename in self.notify_iosapp_entity.get(devicename): - entity_id = (f"mobile_app_{notify_devicename}") - self.hass.services.call("notify", entity_id, service_data) - - #self.hass.async_create_task( - # self.hass.services.async_call('notify', entity_id, service_data)) - - return True - - except Exception as err: - event_msg = (f"iCloud3 Error > An error occurred sending a message to device " - f"{notify_devicename} via notify.{entity_id} service. " - f"CRLF• Message-{str(service_data)}") - if instr(err, "notify/none"): - event_msg += "CRLF• The devicename can not be found." - devicename = "*" - else: - event_msg += f"CRLF• Error-{err}" - self._save_event_halog_error(devicename, event_msg) - - return False - -#-------------------------------------------------------------------- - def _get_iosapp_device_tracker_state_attributes(self, devicename, ic3_state, ic3_dev_attrs): - ''' - Return the state and attributes of the ios app device tracker. - The ic3 device tracker state and attributes are returned if - the ios app data is not available or an error occurs. - ''' - try: - entity_id = self.device_tracker_entity_iosapp.get(devicename, None) - if entity_id: - iosapp_state = self._get_state(entity_id) - iosapp_dev_attrs = self._get_device_attributes(entity_id) - - #iosapp state is the friendly name of the zone, ic3 keeps the state - #by zone name, not the friendly name. Convert iosapp state back to zone - #entity name to match ic3 state_this_poll and state_last_poll, - #state-zone name mismatch errors and state change detected trigger - #when it really didn't - - if ATTR_LATITUDE in iosapp_dev_attrs: - self.iosapp_monitor_error_cnt[devicename] = 0 - - return iosapp_state, iosapp_dev_attrs, True - - except Exception as err: - self.iosapp_monitor_error_cnt[devicename] += 1 - #_LOGGER.exception(err) - - return ic3_state, ic3_dev_attrs, False - - -#-------------------------------------------------------------------- - def _get_iosapp_device_sensor_trigger(self, devicename): - - entity_id = (f"sensor.{self.iosapp_last_trigger_entity.get(devicename)}") - - try: - if self.iosapp_monitor_dev_trk_flag.get(devicename): - trigger = self.hass.states.get(entity_id).state - - trigger_time, trigger_time_secs, trigger_timestamp, \ - trigger_age_secs, trigger_age_str = \ - self._get_entity_last_changed_time(entity_id, devicename) - - trigger_abbrev = IOS_TRIGGER_ABBREVIATIONS.get(trigger, trigger) - - return (trigger_abbrev, trigger_time, trigger_time_secs, - trigger_age_secs, trigger_age_str) - - else: - return '', TIMESTAMP_ZERO, 0, 0, '' - - except Exception as err: - #_LOGGER.exception(err) - return '', TIMESTAMP_ZERO, 0, 0, '' - -#-------------------------------------------------------------------- - def _get_iosapp_device_sensor_battery_level(self, devicename) -> int: - return -1 - - entity_id = (f"sensor.{self.iosapp_battery_level_entity.get(devicename)}") - - try: - if self.iosapp_monitor_dev_trk_flag.get(devicename): - battery_level = self.hass.states.get(entity_id).state - return int(battery_level) - - else: - return 0 - - except Exception as err: - #_LOGGER.exception(err) - return 0 - -######################################################### -# -# DEVICE ZONE ROUTINES -# -######################################################### - def _get_zone(self, devicename, latitude, longitude): - - ''' - Get current zone of the device based on the location """ - - This is the same code as (active_zone/async_active_zone) in zone.py - but inserted here to use zone table loaded at startup rather than - calling hass on all polls - ''' - zone_selected_dist = HIGH_INTEGER - zone_selected = None - zones_msg = "" - iosapp_zone_msg = "" - - zone_iosapp = self.state_this_poll.get(devicename) if self._is_inzone_zonename(self.state_this_poll.get(devicename)) else None - - for zone in self.zone_lat: - #Skip another device's stationary zone or if at base location - if (instr(zone, STATIONARY) and instr(zone, devicename) == False): - continue - - zone_dist = self._calc_distance_km(latitude, longitude, - self.zone_lat.get(zone), self.zone_long.get(zone)) - - #Do not check Stat Zone if radius=1 (at base loc) but include in log_msg - if self.zone_radius_m.get(zone) > 1: - in_zone_flag = zone_dist < self.zone_radius_km.get(zone) - closer_zone_flag = zone_selected is None or zone_dist < zone_selected_dist - smaller_zone_flag = (zone_dist == zone_selected_dist - and self.zone_radius_km.get(zone) <= self.zone_radius_km.get(zone_selected)) - - if in_zone_flag and (closer_zone_flag or smaller_zone_flag): - zone_selected_dist = zone_dist - zone_selected = zone - iosapp_zone_msg = "" - - #If closer than 200m, keep zone name for ios app state override f - #ios app is in a Zone but dist is still outside a zone's radius - elif (zone_iosapp and zone == zone_iosapp and zone_dist < .2): - zone_selected_dist = zone_dist - zone_selected = zone - iosapp_zone_msg = " (Using iOSApp State)" - - if (instr(zone, STATIONARY)): - zones_msg += self.zone_to_display.get(STATIONARY) - else: - zones_msg += self.zone_to_display.get(zone) - zones_msg += (f"-{self._format_dist(zone_dist)}" - f"/r{round(self.zone_radius_m.get(zone))}, ") - - if zone_selected is None: - zone_selected = NOT_HOME - zone_selected_dist = 0 - - #If not in a zone and was in a Stationary Zone, Exit the zone and reset everything - if self.in_stationary_zone_flag.get(devicename): - self._update_stationary_zone( - devicename, - self.stat_zone_base_lat, - self.stat_zone_base_long, - STAT_ZONE_MOVE_TO_BASE, '_get_zone') - - elif instr(zone,'nearzone'): - zone_selected = 'near_zone' - - event_msg = (f"Selected Zone > ") - - if self.display_zone_fname_flag: - event_msg += ZONE_TO_DISPLAY_BASE.get(zone_selected, zone_selected) - else: - event_msg += self.zone_to_display.get(zone_selected, NOT_HOME) - - event_msg += (f"{iosapp_zone_msg} > {zones_msg[:-2]}") - - self._save_event(devicename, event_msg) - self._log_debug_msg(devicename, event_msg) - - #Get distance between zone selected and current zone to see if they overlap - if self._check_overlapping_zone(self.zone_current.get(devicename), zone_selected): - self.zone_current[devicename] = zone_selected - - #If the zone changed from a previous poll, save it and set the new one - if (self.zone_current.get(devicename) != zone_selected): - self.zone_last[devicename] = self.zone_current.get(devicename) - - #First time thru, initialize zone_last - if (self.zone_last.get(devicename) == ''): - self.zone_last[devicename] = zone_selected - - self.zone_current[devicename] = zone_selected - self.zone_timestamp[devicename] = \ - dt_util.now().strftime(self.um_date_time_strfmt) - - log_msg = (f"GET ZONE RESULTS, Zone-{zone_selected}, " - f"{format_gps(latitude, longitude, 0)}, " - f"StateThisPoll-{self.state_this_poll.get(devicename)}, " - f"LastZone-{self.zone_last.get(devicename)}, " - f"ThisZone-{self.zone_current.get(devicename)}") - self._log_debug_msg(devicename, log_msg) - - return zone_selected - -#-------------------------------------------------------------------- - def _check_overlapping_zone(self, zone1, zone2): - ''' - zone1 and zone2 overlap if their distance between centers is less than 2m - ''' - try: - if zone1 == zone2: - return True - - if zone1 == "": zone1 = HOME - zone_dist = self._calc_distance_m( - self.zone_lat.get(zone1), self.zone_long.get(zone1), - self.zone_lat.get(zone2), self.zone_long.get(zone2)) - - return (zone_dist <= 2) - - except: - return False - -#-------------------------------------------------------------------- - @staticmethod - def _get_zone_names(zone_name): - """ - Make zone_names 1, 2, & 3 out of the zone_name value for sensors - - name1 = home --> Home - not_home --> Away - gary_iphone_stationary --> Stationary - name2 = gary_iphone_stationary --> Gary Iphone Stationary - office_bldg_1 --> Office Bldg 1 - name3 = gary_iphone_stationary --> GaryIphoneStationary - office__bldg_1 --> Office Bldg1 - """ - if zone_name: - if instr(zone_name, STATIONARY): - name1 = STATIONARY - elif instr(zone_name, NOT_HOME): - name1 = AWAY - else: - name1 = zone_name.title() - - if zone_name == ATTR_ZONE: - badge_state = name1 - - name2 = zone_name.title().replace('_', ' ') - name3 = zone_name.title().replace('_', '') - else: - name1 = NOT_SET - name2 = 'Not Set' - name3 = 'NotSet' - - return [zone_name, name1, name2, name3] - -#-------------------------------------------------------------------- - @staticmethod - def _format_zone_name(devicename, zone): - ''' - The Stationary zone info is kept by 'devicename_stationary'. Other zones - are kept as 'zone'. Format the name based on the zone. - ''' - return f"{devicename}_stationary" if zone == STATIONARY else zone - -#-------------------------------------------------------------------- - def _set_base_zone_name_lat_long_radius(self, zone): - ''' - Set the base_zone's name, lat, long & radius - ''' - self.base_zone = zone - self.base_zone_name = self.zone_to_display.get(zone) - self.base_zone_lat = self.zone_lat.get(zone) - self.base_zone_long = self.zone_long.get(zone) - self.base_zone_radius_km = float(self.zone_radius_km.get(zone)) - - return - -#-------------------------------------------------------------------- - def _zone_distance_m(self, devicename, zone, latitude, longitude): - ''' - Get the distance from zone `zone` - ''' - - zone_dist = HIGH_INTEGER - - if self.zone_lat.get(zone): - zone_name = self._format_zone_name(devicename, zone) - - zone_dist = self._calc_distance_m( - latitude, - longitude, - self.zone_lat.get(zone_name), - self.zone_long.get(zone_name)) - - log_msg = (f"ZONE DIST {devicename}, Zone-{zone_name}, " - f"CurrGPS-{format_gps(latitude, longitude, 0)}, " - f"ZoneGPS-{format_gps(self.zone_lat.get(zone_name), self.zone_long.get(zone_name), 0)}, " - f"Dist-{zone_dist}m") - #self._log_debug_msg(devicename, log_msg) - - return zone_dist - -#-------------------------------------------------------------------- - def _is_inzone(self, devicename): - return (self.state_this_poll.get(devicename) != NOT_HOME) - - def _isnot_inzone(self, devicename): - return (self.state_this_poll.get(devicename) == NOT_HOME) - - def _was_inzone(self, devicename): - return (self.state_last_poll.get(devicename) != NOT_HOME) - - def _wasnot_inzone(self, devicename): - return (self.state_last_poll.get(devicename) == NOT_HOME) - - def _is_inzone_stationary(self, devicename): - return (instr(self.state_this_poll.get(devicename), STATIONARY)) - - def _isnot_inzone_stationary(self, devicename): - return (instr(self.state_this_poll.get(devicename), STATIONARY) == False) - - def _was_inzone_stationary(self, devicename): - return (instr(self.state_last_poll.get(devicename), STATIONARY)) - - def _wasnot_inzone_stationary(self, devicename): - return (instr(self.state_last_poll.get(devicename), STATIONARY) == False) - - @staticmethod - def _is_inzone_zonename(zone): - return (zone != NOT_HOME) - - @staticmethod - def _isnot_inzone_zonename(zone): - #_LOGGER.warning("_isnot_inzone_zonename = %s",(zone == NOT_HOME)) - return (zone == NOT_HOME) -#-------------------------------------------------------------------- - def _wait_if_update_in_process(self, devicename=None): - #An update is in process, must wait until done - wait_cnt = 0 - while self.update_in_process_flag: - wait_cnt += 1 - if devicename: - attrs = {} - attrs[ATTR_INTERVAL] = (f"WAIT-{wait_cnt}") - - self._update_device_sensors(devicename, attrs) - - time.sleep(2) - -#-------------------------------------------------------------------- - def _update_last_latitude_longitude(self, devicename, latitude, longitude, called_from=""): - #Make sure that the last latitude/longitude is not set to the - #base stationary one before updating. If it is, do not save them - - if latitude is None or longitude is None: - error_msg = (f"Discarded > Undefined GPS Coordinates, " - f"UpdateRequestedBy-{called_from}") - - elif latitude == self.stat_zone_base_lat and longitude == self.stat_zone_base_long: - error_msg = (f"Discarded > Can not set current location to Stationary " - f"Base Zone location {format_gps(latitude, longitude, 0)}, " - f"UpdateRequestedBy-{called_from}") - else: - self.last_lat[devicename] = latitude - self.last_long[devicename] = longitude - return True - - self._save_event_halog_info(devicename, error_msg) - return False - -#-------------------------------------------------------------------- - @staticmethod - def _latitude_longitude_none(latitude, longitude): - return (latitude is None or longitude is None) - -#-------------------------------------------------------------------- - def _update_stationary_zone(self, devicename, latitude, longitude, enter_exit_flag, calledfrom=''): - """ Set, Enter, Exit, Move stationary zone """ - - try: - - event_log_devicename = "*" if self.start_icloud3_inprocess_flag else devicename - stat_zone_name = self._format_zone_name(devicename, STATIONARY) - self.stat_zone_update_location[stat_zone_name] = "" #clear update location - - if latitude is None or longitude is None: - return - - stat_zone_dist = self._calc_distance_m(latitude, longitude, - self.zone_lat.get(stat_zone_name), self.zone_long.get(stat_zone_name)) - stat_home_dist = self._calc_distance_m(latitude, longitude, - self.zone_home_lat, self.zone_home_long,) - - #Make sure stationary zone is not being moved to another zone's location unless it a - #Stationary Zone - for zone in self.zone_lat: - if instr(zone, STATIONARY) == False: - zone_dist = self._calc_distance_m(latitude, longitude, self.zone_lat.get(zone), self.zone_long.get(zone)) - if zone_dist < self.zone_radius_m.get(zone): - event_msg = (f"Move into stationary zone cancelled > Too close to zone-{zone}, Dist-{zone_dist}m") - self._save_event(devicename, event_msg) - self.stat_zone_timer[devicename] = self.this_update_secs + self.stat_zone_still_time - - return False - - self.zone_lat[stat_zone_name] = latitude - self.zone_long[stat_zone_name] = longitude - self.zone_passive[stat_zone_name] = not enter_exit_flag - self.stat_zone_moved_total[devicename] = 0 - - attrs = {} - attrs[CONF_NAME] = stat_zone_name - attrs[ATTR_LATITUDE] = latitude - attrs[ATTR_LONGITUDE] = longitude - attrs['icon'] = (f"mdi:{self.stat_zone_devicename_icon.get(devicename)}") - attrs[ATTR_FRIENDLY_NAME] = stat_zone_name - - #If Stationary zone is exited, move it back to it's base location - #and reduce it's size - if enter_exit_flag == STAT_ZONE_MOVE_TO_BASE: - attrs['passive'] = True - attrs[ATTR_RADIUS] = 1 - self.zone_radius_m[stat_zone_name] = 1 - self.zone_radius_km[stat_zone_name] = .1 - self.stat_zone_timer[devicename] = 0 - self.in_stationary_zone_flag[devicename] = False - - self.stat_zone_update_location[stat_zone_name] = attrs - - if self.start_icloud3_inprocess_flag == False: - event_msg = (f"Reset Stationary Zone Location > {stat_zone_name}, " - f"Moved to Base Location-{format_gps(latitude, longitude, 0)}, " - f"DistFromHome-{self._format_dist_m(stat_home_dist)}") - self._save_event(devicename, event_msg) - - else: - #self.zone_by_fname[stat_zone_name] = stat_zone_name - self.zone_to_display[stat_zone_name] = 'Stationary' - self.state_to_zone[stat_zone_name] = stat_zone_name - - return True - - #Set Stationary Zone at new location - attrs['passive'] = False - attrs[ATTR_RADIUS] = self.stat_zone_radius_m - self.zone_radius_m[stat_zone_name] = self.stat_zone_radius_m - self.zone_radius_km[stat_zone_name] = self.stat_zone_radius_km - self.in_stationary_zone_flag[devicename] = True - - self.stat_zone_update_location[stat_zone_name] = attrs - - self._trace_device_attributes(stat_zone_name, "SET.STAT.ZONE", "SetStatZone", attrs) - - if stat_zone_dist > self.stat_zone_radius_m: - event_msg = (f"Moving Into Stationary Zone >") - else: - event_msg = (f"Moving Stationary Zone Location >") - event_msg += (f" {stat_zone_name}, " - f"GPS-{format_gps(latitude, longitude, 0)}, " - f"DistFromHome-{self._format_dist_m(stat_home_dist)}") - if stat_zone_dist <= self.stat_zone_radius_m: - event_msg += (f", DistFromLastLoc-{stat_zone_dist}m") - if self.stat_zone_timer.get(devicename) > 0: - event_msg += (f", StationarySince-{self._secs_to_time(self.stat_zone_timer.get(devicename) - self.stat_zone_still_time)}") - self._save_event_halog_info(event_log_devicename, event_msg) - - self.stat_zone_timer[devicename] = 0 - - return True - - except Exception as err: - _LOGGER.exception(err) - log_msg = (f"►INTERNAL ERROR (UpdtStatZone-{err})") - self._log_error_msg(log_msg) - - return False - -#-------------------------------------------------------------------- - def _update_stationary_zone_location(self, devicename): - ''' move the stationary zone to it's new location if necessary ''' - - try: - stat_zone_name = self._format_zone_name(devicename, STATIONARY) - - attrs = self.stat_zone_update_location.get(stat_zone_name, '') - if attrs != '': - self._set_state("zone." + stat_zone_name, "zoning", attrs) - - - except Exception as err: - _LOGGER.exception(err) - pass - -#-------------------------------------------------------------------- - def _reset_stat_zone_time(self): - ''' returns the initial value of the stationary zone timer ''' - return self.this_update_secs + self.stat_zone_still_time - -#-------------------------------------------------------------------- - def _update_device_sensors(self, arg_devicename, attrs:dict): - ''' - Update/Create sensor for the device attributes - - sensor_device_attrs = ['distance', 'calc_distance', 'waze_distance', - 'travel_time', 'dir_of_travel', 'interval', 'info', - 'last_located', 'last_update', 'next_update', - 'poll_count', 'trigger', 'battery', 'battery_state', - 'gps_accuracy', 'zone', 'last_zone', 'travel_distance'] - - sensor_attrs_format = {'distance': 'dist', 'calc_distance': 'dist', - 'travel_distance': 'dist', 'battery': '%', - 'dir_of_travel': 'title'} - ''' - try: - if not attrs: - return - - #check to see if arg_devicename is really devicename_zone - if instr(arg_devicename, ":") == False: - devicename = arg_devicename - prefix_zone = self.base_zone - else: - devicename = arg_devicename.split(':')[0] - prefix_zone = arg_devicename.split(':')[1] - - badge_state = None - badge_zone = None - badge_dist = None - base_entity = self.sensor_prefix_name.get(devicename, devicename) - - if prefix_zone == HOME: - base_entity = (f"sensor.{self.sensor_prefix_name.get(devicename, devicename)}") - attr_fname_prefix = self.sensor_attr_fname_prefix.get(devicename) - else: - base_entity = (f"sensor.{prefix_zone}_{self.sensor_prefix_name.get(devicename, devicename)}") - attr_fname_prefix = (f"{prefix_zone.replace('_', ' ', 99).title()}_" - f"{self.sensor_attr_fname_prefix.get(devicename)}") - - for attr_name in SENSOR_DEVICE_ATTRS: - sensor_entity = (f"{base_entity}_{attr_name}") - if attr_name in attrs: - state_value = attrs.get(attr_name) - else: - continue - - sensor_attrs = {} - if attr_name in SENSOR_ATTR_FORMAT: - format_type = SENSOR_ATTR_FORMAT.get(attr_name) - if format_type == 'dist': - sensor_attrs[CONF_UNIT_OF_MEASUREMENT] = self.unit_of_measurement - - elif format_type == 'diststr': - try: - x = (state_value / 2) - sensor_attrs[CONF_UNIT_OF_MEASUREMENT] = self.unit_of_measurement - except: - sensor_attrs[CONF_UNIT_OF_MEASUREMENT] = '' - elif format_type == '%': - sensor_attrs[CONF_UNIT_OF_MEASUREMENT] = '%' - elif format_type == 'title': - state_value = state_value.title().replace('_', ' ') - elif format_type == 'kph-mph': - sensor_attrs[CONF_UNIT_OF_MEASUREMENT] = self.um_kph_mph - elif format_type == 'm-ft': - sensor_attrs[CONF_UNIT_OF_MEASUREMENT] = self.um_m_ft - - if attr_name in SENSOR_ATTR_ICON: - sensor_attrs['icon'] = SENSOR_ATTR_ICON.get(attr_name) - - if attr_name in SENSOR_ATTR_FNAME: - sensor_attrs[ATTR_FRIENDLY_NAME] = (f"{attr_fname_prefix}{SENSOR_ATTR_FNAME.get(attr_name)}") - - self._update_device_sensors_hass(devicename, base_entity, attr_name, - state_value, sensor_attrs) - - if attr_name == 'zone': - zone_names = self._get_zone_names(state_value) - if badge_state is None: - badge_state = zone_names[1] - self._update_device_sensors_hass(devicename, base_entity, - "zone_name1", zone_names[1], sensor_attrs) - - self._update_device_sensors_hass(devicename, base_entity, - "zone_name2", zone_names[2], sensor_attrs) - - self._update_device_sensors_hass(devicename, base_entity, - "zone_name3", zone_names[3], sensor_attrs) - - elif attr_name == 'last_zone': - zone_names = self._get_zone_names(state_value) - - self._update_device_sensors_hass(devicename, base_entity, - "last_zone_name1", zone_names[1], sensor_attrs) - - self._update_device_sensors_hass(devicename, base_entity, - "last_zone_name2", zone_names[2], sensor_attrs) - - self._update_device_sensors_hass(devicename, base_entity, - "last_zone_name3", zone_names[3], sensor_attrs) - - elif attr_name == 'zone_distance': - if state_value and float(state_value) > 0: - badge_state = (f"{state_value} {self.unit_of_measurement}") - - if badge_state: - self._update_device_sensors_hass(devicename, - base_entity, - "badge", - badge_state, - self.sensor_badge_attrs.get(devicename)) - return True - - except Exception as err: - _LOGGER.exception(err) - log_msg = (f"►INTERNAL ERROR (UpdtSensorUpdate-{err})") - self._log_error_msg(log_msg) - - return False -#-------------------------------------------------------------------- - def _update_device_sensors_hass(self, devicename, base_entity, attr_name, - state_value, sensor_attrs): - - try: - state_value = state_value[0:250] - except: - pass - - if attr_name in self.sensors_custom_list: - sensor_entity = (f"{base_entity}_{attr_name}") - - self._set_state(sensor_entity, state_value, sensor_attrs) - -#-------------------------------------------------------------------- - def _format_info_attr(self, devicename, battery, - gps_accuracy, dist_last_poll_moved_km, - zone): - - """ - Initialize info attribute - """ - devicename_zone = self._format_devicename_zone(devicename) - try: - info_msg = '' - if self.info_notification != '': - info_msg = f"●●{self.info_notification}●●" - self.info_notification = '' - - if self.base_zone != HOME: - info_msg += (f" • Base.Zone: {self.base_zone_name}") - - if (self.TRK_METHOD_IOSAPP - and self.tracking_method_config != IOSAPP): - info_msg += (f" • Track.Method: {self.trk_method_short_name}") - - if self.override_interval_seconds.get(devicename) > 0: - info_msg += " • Overriding.Interval" - - if zone == 'near_zone': - info_msg += " • NearZone" - - if battery > 0: - info_msg += f" • Battery-{battery}%" - - if gps_accuracy > self.gps_accuracy_threshold: - info_msg += (f" • Poor.GPS.Accuracy, Dist-{self._format_dist(gps_accuracy)}") - if self.poor_location_gps_cnt.get(devicename) > 0: - info_msg += (f" (#{self.poor_location_gps_cnt.get(devicename)})") - if (self._is_inzone_zonename(zone) - and self.ignore_gps_accuracy_inzone_flag): - info_msg += " - Discarded" - - old_cnt = self.poor_location_gps_cnt.get(devicename) - if old_cnt > 16: - location_age = self._secs_since(self.last_located_secs.get(devicename)) - info_msg += (f" • May Be Offline, Located-{self._format_age(location_age)}, " - f"OldCnt-#{old_cnt}") - - if self.stat_zone_timer.get(devicename) > 0: - info_msg += (f" • MoveIntoStatZone@{self._secs_to_time(self.stat_zone_timer.get(devicename))}") - - if self.waze_data_copied_from.get(devicename) is not None: - copied_from = self.waze_data_copied_from.get(devicename) - if devicename != copied_from: - info_msg += (f" • Using Waze data from {self.fname.get(copied_from)}") - - except Exception as err: - _LOGGER.exception(err) - info_msg += (f"Error setting up info attribute-{err}") - self._log_error_msg(info_msg) - - return info_msg - -#-------------------------------------------------------------------- - def _display_info_status_msg(self, devicename_zone, info_msg, start_icloud3_initial_load_flag=False): - ''' - Display a status message in the info sensor. If the devicename_zone - parameter contains the base zone (devicename:zone), display only for that - devicename_zone, otherwise (devicename), display for all zones for - the devicename. - ''' - try: - if start_icloud3_initial_load_flag: - return - - save_base_zone = self.base_zone - - if devicename_zone == '': - if self.tracked_devices: - devicename = self.tracked_devices[0] - devicename_zone_list = self.track_from_zone.get(devicename) - else: - devicename = self.track_devices[0].split('>')[0].strip() - devicename_zone_list = [self.base_zone] - - elif instr(devicename_zone, ':'): - devicename = devicename_zone.split(':')[0] - devicename_zone_list = [devicename_zone.split(':')[1]] - else: - devicename = devicename_zone - devicename_zone_list = self.track_from_zone.get(devicename) - - elapsed_time = '' - - for zone in devicename_zone_list: - self.base_zone = zone - attrs = {} - attrs[ATTR_INFO] = f"●● {info_msg}{elapsed_time} ●●" - self._update_device_sensors(devicename, attrs) - - except Exception as err: - _LOGGER.exception(err) - pass - - self.base_zone = save_base_zone - - #return formatted msg for event log - return (f"CRLF• {info_msg}") - -#-------------------------------------------------------------------- - def _update_count_update_ignore_attribute(self, devicename, info = None): - self.count_update_ignore[devicename] += 1 - - try: - attrs = {} - attrs[ATTR_POLL_COUNT] = self._format_poll_count(devicename) - - self._update_device_sensors(devicename, attrs) - - except: - pass -#-------------------------------------------------------------------- - def _format_poll_count(self, devicename): - - return (f"{self.count_update_icloud.get(devicename)}:" - f"{self.count_update_iosapp.get(devicename)}:" - f"{self.count_update_ignore.get(devicename)}") - -#-------------------------------------------------------------------- - def _display_usage_counts(self, devicename, force_display=False): - - - try: - if devicename not in self.count_update_icloud: - self._initialize_usage_counters(devicename, True) - - total_count = self.count_update_icloud.get(devicename) + \ - self.count_update_iosapp.get(devicename) + \ - self.count_update_ignore.get(devicename) + \ - self.count_state_changed.get(devicename) + \ - self.count_trigger_changed.get(devicename) + \ - self.iosapp_request_loc_cnt.get(devicename) - - - pyi_avg_time_per_call = self.time_pyicloud_calls / \ - (self.count_pyicloud_authentications + self.count_pyicloud_location_update) \ - if self.count_pyicloud_location_update > 0 else 0 - #If updating the devicename's info_msg, only add to the event log - #and info_msg if the counter total is divisible by 5. - total_count = 1 - hour = int(dt_util.now().strftime('%H')) - if force_display: - pass - elif (hour % 3) != 0: - return (None, 0) - elif total_count == 0: - return (None, 0) - - # ¤s= Table start, Row start - # ¤e=
Row end, Table end - # §= Row end, next row start - # » = - # «LT- = Col start, 40% width - # ¦LC-= Col end, next col start-width 40% - # ¦RT-= Col end, next col start-width 10% - # ¦RC-= Col end, next col start-width 40% - - count_msg = (f"¤s") - state_trig_count = self.count_state_changed.get(devicename) + self.count_trigger_changed.get(devicename) - - if self.TRK_METHOD_FMF_FAMSHR: - count_msg += (f"«HS¦LH-Device Counts¦RH-iCloud Counts»HE" - f"«LT-State/Trigger Chgs¦LC-{state_trig_count}¦RT-Authentications¦RC-{self.count_pyicloud_authentications}»" - f"«LT-iCloud Updates¦LC-{self.count_update_icloud.get(devicename)}¦RT-Total iCloud Loc Rqsts¦RC-{self.count_pyicloud_location_update}»" - f"«LT-iOS App Updates¦LC-{self.count_update_iosapp.get(devicename)}¦RT-Time/Locate (secs)¦RC-{round(pyi_avg_time_per_call, 2)}»") - else: - count_msg += (f"«HS¦LH-Device Counts¦RH-iOS App Counts»HE" - f"«LT-State/Triggers Chgs¦LC-{state_trig_count}¦RT-iOS Locate Requests¦RC-{self.iosapp_request_loc_cnt.get(devicename)}»" - f"«LT-iCloud Updates¦LC-{self.count_update_icloud.get(devicename)}¦RT-iOS App Updates¦RC-{self.count_update_iosapp.get(devicename)}»") - - count_msg += (f"«LT-Discarded¦LC-{self.count_update_ignore.get(devicename)}¦RT-Waze Routes¦RC-{self.count_waze_locates.get(devicename)}»" - f"¤e") - - self._save_event(devicename, f"{count_msg}") - - except Exception as err: - _LOGGER.exception(err) - - return (None, 0) - -######################################################### -# -# Perform tasks on a regular time schedule -# -######################################################### - def _timer_tasks_every_hour(self): - for devicename in self.tracked_devices: - self._display_usage_counts(devicename) - -#-------------------------------------------------------------------- - def _timer_tasks_midnight(self): - for devicename in self.tracked_devices: - devicename_zone = self._format_devicename_zone(devicename, HOME) - - event_msg = (f"^^^ iCloud3 v{VERSION} Daily Summary > " - f"{dt_util.now().strftime('%A, %b %d')}") - self._save_event_halog_info(devicename, event_msg) - - event_msg = (f"Tracking Devices > {self.track_devicename_list}") - self._save_event_halog_info(devicename, event_msg) - - if self.iosapp_monitor_dev_trk_flag.get(devicename): - event_msg = (f"iOS App monitoring > {self._format_fname_devicename(devicename)} > " - f"CRLF• device_tracker.{self.devicename_iosapp_entity.get(devicename)}, " - f"CRLF• sensor.{self.iosapp_last_trigger_entity.get(devicename)}") - self._save_event_halog_info(devicename, event_msg) - else: - event_msg = (f"iOS App monitoring > device_tracker.{devicename}") - self._save_event_halog_info(devicename, event_msg) - - self.count_pyicloud_authentications = 0 - self.count_pyicloud_location_update = 0 - self.time_pyicloud_calls = 0.0 - self._initialize_usage_counters(devicename, True) - - for devicename_zone in self.waze_distance_history: - self.waze_distance_history[devicename_zone] = '' - - self._check_authentication_2sa_code_needed() - -#-------------------------------------------------------------------- - def _timer_tasks_1am(self): - self._calculate_time_zone_offset() - -######################################################### -# -# VARIABLE DEFINITION & INITIALIZATION FUNCTIONS -# -######################################################### - def _define_tracking_control_fields(self): - self.icloud3_started_secs = 0 - self.icloud_acct_auth_error_cnt = 0 - self.immediate_retry_flag = False - self.time_zone_offset_seconds = self._calculate_time_zone_offset() - self.setinterval_cmd_devicename = None - self.update_in_process_flag = False - self.track_devicename_list = '' - self.any_device_being_updated_flag = False - self.tracked_devices_config_parm = {} #config file item for devicename - self.tracked_devices = [] - - self.trigger = {} #device update trigger - self.last_iosapp_trigger = {} #last trigger issued by iosapp - self.got_exit_trigger_flag = {} #iosapp issued exit trigger leaving zone - self.device_being_updated_flag = {} - self.device_being_updated_retry_cnt = {} - self.last_iosapp_state = {} - self.last_iosapp_state_changed_time = {} - self.last_iosapp_state_changed_secs = {} - self.last_iosapp_trigger = {} - self.last_iosapp_trigger_changed_time= {} - self.last_iosapp_trigger_changed_secs= {} - - self.iosapp_update_flag = {} - self.iosapp_monitor_dev_trk_flag = {} - self.iosapp_monitor_error_cnt = {} - self.iosapp_last_trigger_entity = {} #sensor entity extracted from entity_registry - self.iosapp_battery_level_entity = {} #sensor entity extracted from entity_registry - - self.iosapp_stat_zone_action_msg_cnt = {} - self.authenticated_time = 0 - self.authentication_error_cnt = 0 - self.authentication_error_retry_secs = HIGH_INTEGER - self.info_notification = '' - self.broadcast_msg = '' - - this_update_time = dt_util.now().strftime('%H:%M:%S') -#-------------------------------------------------------------------- - def _define_event_log_fields(self): - self.event_log_table = [] - self.event_log_base_attrs = '' - self.log_table_max_items = 999 - self.event_log_clear_secs = HIGH_INTEGER - self.event_log_sensor_state = '' - self.event_log_last_devicename = '*' - -#-------------------------------------------------------------------- - def _define_device_fields(self): - ''' - Dictionary fields for each devicename - ''' - self.fname = {} #name made from status[CONF_NAME] - self.badge_picture = {} #devicename picture from badge setup - self.api_devices = None #icloud.api.devices obj - self.api_device_devicename = {} #icloud.api.device obj for each devicename - self.data_source = {} - self.device_type = {} - self.device_status = {} - self.devicename_iosapp_entity = {} - self.devicename_iosapp_suffix = {} - self.notify_iosapp_entity = {} - self.devicename_verified = {} #Set to True in mode setup fcts - self.fmf_id = {} - self.fmf_devicename_email = {} - self.seen_this_device_flag = {} - self.device_tracker_entity_ic3 = {} - self.device_tracker_entity_iosapp = {} - self.track_from_zone = {} #Track device from other zone - -#-------------------------------------------------------------------- - def _define_device_status_fields(self): - ''' - Dictionary fields for each devicename - ''' - self.tracking_device_flag = {} - self.state_this_poll = {} - self.state_last_poll = {} - self.zone_last = {} - self.zone_current = {} - self.zone_timestamp = {} - self.state_change_flag = {} - self.location_data = {} - self.last_located_time = {} - self.last_located_secs = {} #device timestamp in seconds - self.went_3km = {} #>3 km/mi, probably driving - -#-------------------------------------------------------------------- - def _initialize_device_status_fields(self, devicename): - ''' - Make domain name entity ids for the device_tracker and - sensors for each device so we don't have to do it all the - time. Then check to see if 'sensor.geocode_location' - exists. If it does, then using iosapp version 2. - ''' - entity_id = (f"device_tracker.{devicename}") - self.device_tracker_entity_ic3[devicename] = entity_id - self.state_this_poll[devicename] = self._get_state(entity_id) - self.state_last_poll[devicename] = NOT_SET - self.device_status[devicename] = UNKNOWN - self.zone_last[devicename] = '' - self.zone_current[devicename] = '' - self.zone_timestamp[devicename] = '' - self.state_change_flag[devicename] = False - self.location_data[devicename] = INITIAL_LOCATION_DATA - self.last_located_time[devicename] = HHMMSS_ZERO - self.last_located_secs[devicename] = 0 - self.went_3km[devicename] = False - - self.trigger[devicename] = 'iCloud3' - self.got_exit_trigger_flag[devicename] = False - self.seen_this_device_flag[devicename] = False - self.device_being_updated_flag[devicename] = False - self.device_being_updated_retry_cnt[devicename] = 0 - - self.iosapp_update_flag[devicename] = False - - #iosapp v2 entity info - self.last_iosapp_state[devicename] = '' - self.last_iosapp_state_changed_time[devicename] = '' - self.last_iosapp_state_changed_secs[devicename] = 0 - self.last_iosapp_trigger[devicename] = '' - self.last_iosapp_trigger_changed_time[devicename] = '' - self.last_iosapp_trigger_changed_secs[devicename] = 0 - self.iosapp_monitor_error_cnt[devicename] = 0 - - -#-------------------------------------------------------------------- - def _initialize_um_formats(self, unit_of_measurement): - #Define variables, lists & tables - if unit_of_measurement == 'mi': - if self.time_format != 24: self.time_format = 12 - self.um_km_mi_factor = 0.62137 - self.um_m_ft = 'ft' - self.um_kph_mph = 'mph' - else: - if self.time_format != 12: self.time_format = 24 - self.um_km_mi_factor = 1 - self.um_m_ft = 'm' - self.um_kph_mph = 'kph' - - if self.time_format == 12: - self.um_time_strfmt = '%I:%M:%S' - self.um_time_strfmt_ampm = '%I:%M:%S%P' - self.um_date_time_strfmt = '%Y-%m-%d %I:%M:%S' - else: - self.um_time_strfmt = '%H:%M:%S' - self.um_time_strfmt_ampm = '%H:%M:%S' - self.um_date_time_strfmt = '%Y-%m-%d %H:%M:%S' - -#-------------------------------------------------------------------- - def _setup_tracking_method(self, tracking_method): - ''' - tracking_method: method - tracking_method: method, iosapp1 - - tracking_method can have a secondary option to use iosappv1 even if iosv2 is - on the devices - ''' - - trk_method_split = (f"{tracking_method}_").split('_') - trk_method_primary = trk_method_split[0] - trk_method_secondary = trk_method_split[1] - - self.TRK_METHOD_FMF = (trk_method_primary == FMF) - self.TRK_METHOD_FAMSHR = (trk_method_primary == FAMSHR) - self.TRK_METHOD_FMF_FAMSHR = (trk_method_primary in FMF_FAMSHR) - self.CONF_TRK_METHOD_FMF_FAMSHR = (trk_method_primary in FMF_FAMSHR) - if (self.TRK_METHOD_FMF_FAMSHR and PYICLOUD_IC3_IMPORT_SUCCESSFUL is False): - trk_method_primary = IOSAPP - - self.TRK_METHOD_IOSAPP = (trk_method_primary in IOSAPP_IOSAPP1) - - self.trk_method_config = trk_method_primary - self.trk_method = trk_method_primary - self.trk_method_name = TRK_METHOD_NAME.get(trk_method_primary) - self.trk_method_short_name = TRK_METHOD_SHORT_NAME.get(trk_method_primary) - - if self.TRK_METHOD_FMF_FAMSHR and self.password == '': - event_msg = ("iCloud3 Error > The password is required for the " - f"{self.trk_method_short_name} tracking method. The " - f"iOS App tracking_method will be used.") - self._save_event_halog_error("*", event_msg) - - self._setup_iosapp_tracking_method() -#-------------------------------------------------------------------- - def _setup_iosapp_tracking_method(self): - """ Change tracking method to IOSAPP if FMF or FAMSHR error """ - self.trk_method_short_name = TRK_METHOD_SHORT_NAME.get(IOSAPP) - self.trk_method_config = IOSAPP - self.trk_method = IOSAPP - self.trk_method_name = TRK_METHOD_NAME.get(IOSAPP) - self.TRK_METHOD_IOSAPP = True - self.TRK_METHOD_FMF = False - self.TRK_METHOD_FAMSHR = False - self.TRK_METHOD_FMF_FAMSHR = False - -#-------------------------------------------------------------------- - def _define_device_tracking_fields(self): - #times, flags - self.update_timer = {} - self.override_interval_seconds = {} - self.dist_from_zone_km_small_move_total = {} - self.this_update_secs = 0 - - #location, gps - self.poor_location_gps_cnt = {} # override interval while < 4 - self.poor_location_gps_msg = {} - self.old_location_secs = {} - self.poor_gps_flag = {} - self.last_lat = {} - self.last_long = {} - self.last_battery = {} #used to detect iosapp v2 change - self.last_gps_accuracy = {} #used to detect iosapp v2 change - -#-------------------------------------------------------------------- - def _initialize_device_tracking_fields(self, devicename): - #times, flags - self.update_timer[devicename] = time.time() - self.override_interval_seconds[devicename] = 0 - self.dist_from_zone_km_small_move_total[devicename] = 0 - - #location, gps - self.poor_location_gps_cnt[devicename] = 0 - self.poor_location_gps_msg[devicename] = False - self.old_location_secs[devicename] = 90 #Timer (secs) before a location is old - self.poor_gps_flag[devicename] = False - self.last_lat[devicename] = self.zone_home_lat - self.last_long[devicename] = self.zone_home_long - self.last_battery[devicename] = 0 - self.last_gps_accuracy[devicename] = 0 - self.stat_zone_timer[devicename] = 0 - self.stat_zone_moved_total[devicename] = 0 - - stat_zone_name = self._format_zone_name(devicename, STATIONARY) - self.stat_zone_update_location[stat_zone_name] = '' - - #Other items - self.data_source[devicename] = '' - self.last_iosapp_msg[devicename] = '' - self.last_device_monitor_msg[devicename] = '' - self.iosapp_stat_zone_action_msg_cnt[devicename]= 0 - -#-------------------------------------------------------------------- - def _define_usage_counters(self): - self.count_update_icloud = {} - self.count_update_iosapp = {} - self.count_update_ignore = {} - self.count_state_changed = {} - self.count_trigger_changed = {} - self.count_waze_locates = {} - self.time_waze_calls = {} - self.count_pyicloud_authentications = 0 - self.count_pyicloud_location_update = 0 - self.time_pyicloud_calls = 0.0 - -#-------------------------------------------------------------------- - def _initialize_usage_counters(self, devicename, clear_counters=True): - if devicename not in self.count_update_icloud or clear_counters: - self.count_update_icloud[devicename] = 0 - self.count_update_iosapp[devicename] = 0 - self.count_update_ignore[devicename] = 0 - self.count_state_changed[devicename] = 0 - self.count_trigger_changed[devicename] = 0 - self.count_waze_locates[devicename] = 0 - self.time_waze_calls[devicename] = 0.0 -#-------------------------------------------------------------------- - def _define_iosapp_message_fields(self): - self.iosapp_request_loc_sent_flag = {} - self.iosapp_request_loc_sent_secs = {} - self.iosapp_request_loc_cnt = {} - self.iosapp_request_loc_retry_cnt = {} - -#-------------------------------------------------------------------- - def _initialize_iosapp_message_fields(self, devicename): - self.iosapp_request_loc_sent_flag[devicename] = False - self.iosapp_request_loc_sent_secs[devicename] = 0 - self.iosapp_request_loc_cnt[devicename] = 0 - self.iosapp_request_loc_retry_cnt[devicename] = 0 - -#-------------------------------------------------------------------- - def _initialize_next_update_time(self, devicename): - for zone in self.track_from_zone.get(devicename): - devicename_zone = self._format_devicename_zone(devicename, zone) - - self.next_update_time[devicename_zone] = HHMMSS_ZERO - self.next_update_secs[devicename_zone] = 0 - -#-------------------------------------------------------------------- - def _define_sensor_fields(self, initial_load_flag): - #Prepare sensors and base attributes - - if initial_load_flag: - self.sensor_devicenames = [] - self.sensors_custom_list = [] - self.sensor_badge_attrs = {} - self.sensor_prefix_name = {} - self.sensor_attr_fname_prefix = {} - -#-------------------------------------------------------------------- - def _define_zone_fields(self): - ''' - Dictionary fields for zone friendly names - ''' - self.zones = [] - self.zone_to_display= dict(ZONE_TO_DISPLAY_BASE) - self.state_to_zone = dict(STATE_TO_ZONE_BASE) - self.zone_lat = {} - self.zone_long = {} - self.zone_radius_km = {} - self.zone_radius_m = {} - self.zone_passive = {} - -#-------------------------------------------------------------------- - def _define_device_zone_fields(self): - ''' - Dictionary fields for each devicename_zone - ''' - self.last_tavel_time = {} - self.interval_seconds = {} - self.interval_str = {} - self.last_distance_str = {} - self.last_update_time = {} - self.last_update_secs = {} - self.next_update_secs = {} - self.next_update_time = {} - self.next_update_in_secs = {} - self.next_update_devicenames= [] - - #used to calculate distance traveled since last poll - self.waze_time = {} - self.waze_dist = {} - self.calc_dist = {} - self.zone_dist = {} - - self.last_ic3dev_timestamp_ses = {} - -#-------------------------------------------------------------------- - def _initialize_device_zone_fields(self, devicename): - #interval, distances, times - - for zone in self.track_from_zone.get(devicename): - devicename_zone = self._format_devicename_zone(devicename, zone) - - self.last_tavel_time[devicename_zone] = '' - self.interval_seconds[devicename_zone] = 0 - self.interval_str[devicename_zone] = '0 sec' - self.last_distance_str[devicename_zone] = '' - self.last_update_time[devicename_zone] = HHMMSS_ZERO - self.last_update_secs[devicename_zone] = 0 - self.next_update_time[devicename_zone] = HHMMSS_ZERO - self.next_update_secs[devicename_zone] = 0 - self.next_update_in_secs[devicename_zone] = 0 - - self.waze_history_data_used_flag[devicename_zone] = False - self.waze_time[devicename_zone] = 0 - self.waze_dist[devicename_zone] = 0 - self.calc_dist[devicename_zone] = 0 - self.zone_dist[devicename_zone] = 0 - - try: - #set up stationary zone icon for devicename - first_initial = self.fname.get(devicename)[0].lower() - - if devicename in self.stat_zone_devicename_icon: - icon = self.stat_zone_devicename_icon.get(devicename) - elif (f"alpha-{first_initial}-box") not in self.stat_zone_devicename_icon: - icon_name = (f"alpha-{first_initial}-box") - elif (f"alpha-{first_initial}-circle") not in self.stat_zone_devicename_icon: - icon_name = (f"alpha-{first_initial}-circle") - elif (f"alpha-{first_initial}-box-outline") not in self.stat_zone_devicename_icon: - icon_name = (f"alpha-{first_initial}-box-outline") - elif (f"alpha-{first_initial}-circle-outline") not in self.stat_zone_devicename_icon: - icon_name = (f"alpha-{first_initial}-circle-outline") - else: - icon_name = (f"alpha-{first_initial}") - - self.stat_zone_devicename_icon[devicename] = icon_name - self.stat_zone_devicename_icon[icon_name] = devicename - - stat_zone_name = self._format_zone_name(devicename, STATIONARY) - self.zone_to_display[stat_zone_name] = "Stationary" - - except Exception as err: - _LOGGER.exception(err) - self.stat_zone_devicename_icon[devicename] = 'account' - -#-------------------------------------------------------------------- - def _initialize_waze_fields(self, waze_region, waze_min_distance, - waze_max_distance, waze_realtime): - #Keep distance data to be used by another device if nearby. Also keep - #source of copied data so that device won't reclone from the device - #using it. - self.waze_region = waze_region.upper() - self.waze_realtime = waze_realtime - - min_dist_msg = (f"{waze_min_distance} {self.unit_of_measurement}") - max_dist_msg = (f"{waze_max_distance} {self.unit_of_measurement}") - - if self.unit_of_measurement == 'mi': - self.waze_min_distance = self._mi_to_km(waze_min_distance) - self.waze_max_distance = self._mi_to_km(waze_max_distance) - min_dist_msg += (f" ({self.waze_min_distance}km)") - max_dist_msg += (f" ({self.waze_max_distance}km)") - else: - self.waze_min_distance = float(waze_min_distance) - self.waze_max_distance = float(waze_max_distance) - - self.waze_distance_history = {} - self.waze_data_copied_from = {} - self.waze_history_data_used_flag = {} - - self.waze_manual_pause_flag = False #If Paused vid iCloud command - self.waze_close_to_zone_pause_flag = False #pause if dist from zone < 1 flag - - if self.distance_method_waze_flag: - log_msg = (f"Set Up Waze > Region-{self.waze_region}, " - f"MinDist-{min_dist_msg}, " - f"MaxDist-{max_dist_msg}, " - f"Realtime-{self.waze_realtime}") - self._log_info_msg(log_msg) - self._save_event("*", log_msg) - -#-------------------------------------------------------------------- - def _initialize_attrs(self, devicename): - attrs = {} - attrs[ATTR_NAME] = '' - attrs[ATTR_ZONE] = NOT_SET - attrs[ATTR_LAST_ZONE] = NOT_SET - attrs[ATTR_ZONE_TIMESTAMP] = '' - attrs[ATTR_INTERVAL] = '' - attrs[ATTR_WAZE_TIME] = '' - attrs[ATTR_ZONE_DISTANCE] = 0 - attrs[ATTR_CALC_DISTANCE] = 0 - attrs[ATTR_WAZE_DISTANCE] = 0 - attrs[ATTR_LAST_LOCATED] = HHMMSS_ZERO - attrs[ATTR_LAST_UPDATE_TIME] = HHMMSS_ZERO - attrs[ATTR_NEXT_UPDATE_TIME] = HHMMSS_ZERO - attrs[ATTR_POLL_COUNT] = '0:0:0' - attrs[ATTR_DIR_OF_TRAVEL] = '' - attrs[ATTR_TRAVEL_DISTANCE] = 0 - attrs[ATTR_TRIGGER] = '' - attrs[ATTR_TIMESTAMP] = dt_util.utcnow().isoformat()[0:19] - attrs[ATTR_AUTHENTICATED] = '' - attrs[ATTR_BATTERY] = 0 - attrs[ATTR_BATTERY_STATUS] = UNKNOWN - attrs[ATTR_INFO] = "● HA is initializing dev_trk attributes ●" - attrs[ATTR_ALTITUDE] = 0 - attrs[ATTR_VERT_ACCURACY] = 0 - attrs[ATTR_DEVICE_STATUS] = UNKNOWN - attrs[ATTR_LOW_POWER_MODE] = '' - attrs[CONF_GROUP] = self.group - attrs[ATTR_PICTURE] = self.badge_picture.get(devicename) - attrs[ATTR_TRACKING] = (f"{self.track_devicename_list} ({self.trk_method_short_name})") - attrs[ATTR_ICLOUD3_VERSION] = VERSION - - return attrs - -#-------------------------------------------------------------------- - def _initialize_zone_tables(self): - ''' - Get friendly name of all zones to set the device_tracker state - ''' - - try: - if self.start_icloud3_initial_load_flag == False: - self.hass.services.call(ATTR_ZONE, "reload") - except: - pass - - log_msg = (f"Reloading Zone.yaml config file") - self._log_debug_msg("*", log_msg) - - zones = self.hass.states.entity_ids(ATTR_ZONE) - zone_msg = '' - - for zone in zones: - zone_name = zone.split(".")[1] #zone='zone.'+zone_name - - try: - self.zones.append(zone_name.lower()) - zone_data = self.hass.states.get(zone).attributes - self._log_debug_msg("*",f"zone-{zone_name}, data-{zone_data}") - - if instr(zone_name.lower(), STATIONARY): - self.zone_to_display[zone_name] = 'Stationary' - - if ATTR_LATITUDE in zone_data: - self.zone_lat[zone_name] = zone_data.get(ATTR_LATITUDE, 0) - self.zone_long[zone_name] = zone_data.get(ATTR_LONGITUDE, 0) - self.zone_passive[zone_name] = zone_data.get('passive', True) - self.zone_radius_m[zone_name] = int(zone_data.get(ATTR_RADIUS, 100)) - self.zone_radius_km[zone_name] = round(self.zone_radius_m[zone_name]/1000, 4) - - zone_fname = zone_data.get(ATTR_FRIENDLY_NAME, zone_name) - if self.display_zone_fname_flag: - self.zone_to_display[zone_name] = zone_fname - self.state_to_zone[zone_fname] = zone_name - else: - zone_name_title = zone_name.replace('_',' ').title().replace(' ', '') - self.zone_to_display[zone_name] = zone_name_title - self.state_to_zone[zone_fname] = zone_name - self.state_to_zone[zone_name_title] = zone_name - - else: - log_msg = (f"Error loading zone {zone_name} > No data was returned from HA. " - f"Zone data returned is `{zone_data}`") - self._log_error_msg(log_msg) - self._save_event("*", log_msg) - - except KeyError: - self.zone_passive[zone_name] = False - - except Exception as err: - _LOGGER.exception(err) - - zone_msg = (f"{zone_msg}{zone_name}/{self.zone_to_display.get(zone_name)} " - f"(r{self.zone_radius_m[zone_name]}m), ") - - log_msg = (f"Set up Zones > {zone_msg[:-2]}") - self._save_event_halog_info("*", log_msg) - - self.zone_home_lat = self.zone_lat.get(HOME) - self.zone_home_long = self.zone_long.get(HOME) - self.zone_home_radius_km = float(self.zone_radius_km.get(HOME)) - self.zone_home_radius_m = self.zone_radius_m.get(HOME) - - self.base_zone = HOME - self.base_zone_name = self.zone_to_display.get(HOME) - self.base_zone_lat = self.zone_lat.get(HOME) - self.base_zone_long = self.zone_long.get(HOME) - self.base_zone_radius_km = float(self.zone_radius_km.get(HOME)) - - return - -#-------------------------------------------------------------------- - def _define_stationary_zone_fields(self, stationary_inzone_interval_str, - stationary_still_time_str): - #create dynamic zone used by ios app when stationary - self.stat_zone_inzone_interval = self._time_str_to_secs(stationary_inzone_interval_str) - self.stat_zone_still_time = self._time_str_to_secs(stationary_still_time_str) - self.stat_zone_half_still_time = self.stat_zone_still_time / 2 - self.in_stationary_zone_flag = {} - self.stat_zone_devicename_icon = {} #icon to be used for a devicename - self.stat_zone_moved_total = {} #Total of small distances - self.stat_zone_timer = {} #Time when distance set to 0 - self.stat_zone_update_location = {} #zonename/attrs to be updated after track results - self.stat_min_dist_from_zone_km = round(self.zone_home_radius_km * 2.5, 2) - self.stat_dist_move_limit = round(self.zone_home_radius_km * 1.5, 2) - self.stat_zone_radius_km = round(self.zone_home_radius_km * 2, 2) - self.stat_zone_radius_m = self.zone_home_radius_m * 2 - if self.stat_zone_radius_km > .1: self.stat_zone_radius_km = .1 - if self.stat_zone_radius_m > 100: self.stat_zone_radius_m = 100 - - #Offset the stat zone from the Home zone based on the stationary_zone_offset parameter - self.stat_zone_base_long = self.zone_home_long - if instr(self.stationary_zone_offset, "("): - szo = self.stationary_zone_offset.replace("(", "").replace(")", "") - self.stat_zone_base_lat = float(szo.split(',')[0]) - self.stat_zone_base_long = float(szo.split(',')[1]) - else: - offset_lat = float(self.stationary_zone_offset.split(',')[0]) * STATIONARY_ZONE_1KM_LAT - offset_long = float(self.stationary_zone_offset.split(',')[1]) * STATIONARY_ZONE_1KM_LONG - self.stat_zone_base_lat = self.zone_home_lat + offset_lat - self.stat_zone_base_long = self.zone_home_long + offset_long - - dist = self._calc_distance_km(self.zone_home_lat, self.zone_home_long, - self.stat_zone_base_lat, self.stat_zone_base_long) - - log_msg = (f"Set Initial Stationary Zone Location > " - f"GPS-{format_gps(self.stat_zone_base_lat, self.stat_zone_base_long, 0)}, " - f"Radius-{self.stat_zone_radius_m}m, DistFromHome-{dist}km") - self._log_debug_msg("*", log_msg) - self._save_event("*", log_msg) - -#-------------------------------------------------------------------- - def _initialize_debug_control(self, log_level): - #string set using the update_icloud command to pass debug commands - #into icloud3 to monitor operations or to set test variables - # interval - toggle display of interval calulation method in info fld - # debug - log 'debug' messages to the log file under the 'info' type - # debug_rawdata - log data read from records to the log file - # eventlog - Add debug items to ic3 event log - # debug+eventlog - Add debug items to HA log file and ic3 event log - - self.log_level_debug_flag = (instr(log_level, 'debug') or DEBUG_TRACE_CONTROL_FLAG) - self.log_level_debug_rawdata_flag = (instr(log_level, 'rawdata') and self.log_level_debug_flag) - self._log_debug_msgs_trace_flag = self.log_level_debug_flag - - self.log_level_intervalcalc_flag = DEBUG_TRACE_CONTROL_FLAG or instr(log_level, 'intervalcalc') - self.log_level_eventlog_flag = self.log_level_eventlog_flag or instr(log_level, 'eventlog') - - self.debug_counter = 0 - self.last_iosapp_msg = {} #can be used to compare changes in debug msgs - self.last_device_monitor_msg = {} - -######################################################### -# -# INITIALIZE PYICLOUD DEVICE API -# DEVICE SETUP SUPPORT FUNCTIONS FOR MODES FMF, FAMSHR, IOSAPP -# -######################################################### - def _pyicloud_initialize_device_api(self): - #See if pyicloud_ic3 is available - if (PYICLOUD_IC3_IMPORT_SUCCESSFUL == False and self.CONF_TRK_METHOD_FMF_FAMSHR): - event_msg = ("iCloud3 Error > An error was encountered setting up the `pyicloud_ic3.py` " - f"module. Either the module was not found or there was an error loading it." - f"The {self.trk_method_short_name} Location Service is disabled and the " - f"iOS App tracking_method will be used.") - self._save_event_halog_error("*", event_msg) - - self._setup_iosapp_tracking_method() - - else: - #Set up pyicloud cookies directory & file names - try: - self.icloud_cookies_dir = self.hass.config.path(STORAGE_DIR, STORAGE_KEY_ICLOUD) - self.icloud_cookies_file = (f"{self.icloud_cookies_dir}/" - f"{self.username.replace('@','').replace('.','')}") - if not os.path.exists(self.icloud_cookies_dir): - os.makedirs(self.icloud_cookies_dir) - - except Exception as err: - _LOGGER.exception(err) - - if self.TRK_METHOD_IOSAPP: - self.api = None - - elif self.CONF_TRK_METHOD_FMF_FAMSHR: - event_msg = ("iCloud Web Services interface (pyicloud_ic3.py) > Verified") - self._save_event_halog_info("*", event_msg) - - self._pyicloud_authenticate_account(initial_setup=True) - if self.api is not None: - self._check_authentication_2sa_code_needed(initial_setup=True) - -#-------------------------------------------------------------------- - def _pyicloud_authenticate_account(self, devicename="", initial_setup=False): - ''' - Authenticate the iCloud Acount via pyicloud - If successful - self.api to the api of the pyicloudservice for the username - If not - set self.api = None - ''' - try: - self.count_pyicloud_authentications += 1 - self.authenticated_time = time.time() - - self.api = PyiCloudService(self.username, self.password, - cookie_directory=self.icloud_cookies_dir, - verify=True) - self.time_pyicloud_calls += (time.time() - self.authenticated_time) - - if self.authentication_error_retry_secs != HIGH_INTEGER: - self.authentication_error_cnt = 0 - self.authentication_error_retry_secs = HIGH_INTEGER - self._setup_tracking_method(self.tracking_method_config) - - event_msg = (f"iCloud Account Authentication Successful > {self.username}") - self._save_event_halog_info("*", event_msg) - - except (PyiCloudFailedLoginException, PyiCloudNoDevicesException, - PyiCloudAPIResponseException) as err: - - self._authentication_error() - return - - except (PyiCloud2SARequiredException) as err: - self._check_authentication_2sa_code_neede() - return - - def _authentication_error(self): - #Set up for retry in X minutes - self.authentication_error_cnt += 1 - if self.authentication_error_cnt >= 8: - retry_secs = 3600 #1 hours - elif self.authentication_error_cnt >= 4: - retry_secs = 1800 #30 minutes - else: - retry_secs = 900 #15 minutes - - self.authentication_error_retry_secs = time.time() + retry_secs - auth_retry_time = self._secs_to_time(self.authentication_error_retry_secs) - - event_msg = (f"iCloud3 Error > An error occurred authenticating " - f"CRLFThe iCloud Web Services may be down or the Username/Password" - f" may be invalid. The {self.trk_method_short_name} tracking method " - f"is disabled and the iOS App tracking method will be used. " - f"CRLFThe authentication will be retried in " - f"{self._secs_to_time_str(retry_secs)} at {auth_retry_time}.") - self._save_event_halog_error("*", event_msg) - - self._setup_iosapp_tracking_method() - self.api = None - -#-------------------------------------------------------------------- - def _check_authentication_2sa_code_needed(self, initial_setup=False): - ''' - Make sure iCloud is still available and doesn't need to be authenticationd - in 15-second polling loop - - Returns True if Authentication is needed. - Returns False if Authentication succeeded - ''' - if self.CONF_TRK_METHOD_FMF_FAMSHR == False: - return - elif initial_setup: - pass - elif self.start_icloud3_inprocess_flag: - return False - - fct_name = "icloud_authenticate_account" - - from .pyicloud_ic3 import PyiCloudService - - try: - if initial_setup == False: - if self.api is None: - event_msg = ("iCloud/FmF API Error, No device API information " - "for devices. Resetting iCloud") - self._save_event_halog_error(event_msg) - - self._start_icloud3() - - elif self.start_icloud3_request_flag: #via service call - event_msg = ("iCloud Restarting, Reset command issued") - self._save_event_halog_error(event_msg) - self._start_icloud3() - - if self.api is None: - event_msg = ("iCloud reset failed, no device API information " - "after reset") - self._save_event_halog_error(event_msg) - - return True #Authentication needed - - if self.api.requires_2sa: - from .pyicloud_ic3 import PyiCloudException - try: - if self.trusted_device is None: - self._icloud_show_trusted_device_request_form() - return True #Authentication needed - - if self.verification_code is None: - self._icloud_show_verification_code_entry_form() - - devicename = list(self.tracked_devices.keys())[0] - self._display_info_status_msg(devicename, '') - return True #Authentication needed - - self.api.authenticate() - self.authenticated_time = time.time() - - event_msg = (f"iCloud/FmF Authentication, Devices-{self.api.devices}") - self._save_event_halog_info("*", event_msg) - - if self.api.requires_2sa: - raise Exception('Unknown failure') - - self.trusted_device = None - self.verification_code = None - - except PyiCloudException as error: - event_msg = (f"iCloud3 Error > Setting up 2FA: {error}") - self._save_event_halog_error(event_msg) - - return True #Authentication needed, Authentication Failed - - return False #Authentication not needed, (Authenticationed OK) - - except Exception as err: - _LOGGER.exception(err) - x = self._internal_error_msg(fct_name, err, 'AuthiCloud') - return True - -#-------------------------------------------------------------------- - def _setup_tracked_devices_for_fmf(self): - ''' - Cycle thru the Find My Friends contact data. Extract the name, id & - email address. Scan fmf_email config parameter to tie the fmf_id in - the location record to the devicename. - - email --> devicename <--fmf_id - ''' - ''' - contact-{ - 'emails': ['gary678tw@', 'gary_2fa_acct@email.com'], - 'firstName': 'Gary', - 'lastName': '', - 'photoUrl': 'PHOTO;X-ABCROP-RECTANGLE=ABClipRect_1&64&42&1228&1228& - //mOVw+4cc3VJSJmspjUWg==; - VALUE=uri:https://p58-contacts.icloud.com:443/186297810/wbs/ - 0123efg8a51b906789fece - 'contactId': '8590AE02-7D39-42C1-A2E8-ACCFB9A5E406',60110127e5cb19d1daea', - 'phones': ['(222)\xa0m456-7899'], - 'middleName': '', - 'id': 'ABC0DEFGH2NzE3'} - - cycle thru config>track_devices devicename/email parameter - looking for a match with the fmf contact record emails item - fmf_devicename_email: - 'gary_iphone' = 'gary_2fa_acct@email.com' - 'gary_2fa_acct@email.com' = 'gary_iphone@' - - or - - 'gary_iphone' = 'gary678@' - 'gary678@' = 'gary_iphone@gmail' - - emails: - ['gary456tw@', 'gary_2fa_acct@email.com] - - When complete, erase fmf_devicename_email and replace it with full - email list - ''' - try: - if self.api is not None: - api_friends = self.api.friends - - except (PyiCloudServiceNotActivatedException, PyiCloudNoDevicesException): - self.api = None - - if self.api is None: - if self._pyicloud_authenticate_account(initial_setup=True): - event_msg = (f"iCloud3 Error for {self.username} > " - f"No information was returned from the iCloud Location Services. " - f"iCloud {self.trk_method_short_name} Location Service is disabled. " - f"iCloud3 will use the IOS App tracking_method until your account is atuthenticated.") - self._save_event_halog_error("*", event_msg) - self._setup_iosapp_tracking_method() - return - - try: - if api_friends is None: - event_msg = (f"iCloud3 Error for {self.username} > " - f"No FmF data was returned from Apple Web Services. " - f"CRLF{'-'*25}" - f"CRLF 1. Verify that the tracked devices have been added " - f"to the Contacts list for this iCloud account." - f"CRLF 2. Verify that the tracked devices have been set up in the " - f"FindMe App and they can be located. " - f"CRLF 3. See the iCloud3 Documentation, `Setting Up your iCloud " - f"Account/Find-my-Friends Tracking Method`." - f"CRLFThe {self.trk_method_short_name} Location Service " - f"is disabled and the IOS App tracking_method will be used.") - self._save_event_halog_error("*", event_msg) - - self._setup_iosapp_tracking_method() - return - - self._log_level_debug_rawdata("iCloud FmF Raw Data - (api_friends.data)", api_friends.data) - - #cycle thru al contacts in fmf recd - devicename_contact_emails = {} - contacts_valid_emails = '' - - #Get contacts data from non-2fa account. If there are no contacts - #in the fmf data, use the following data in the fmf data - for contact in api_friends.following: - contact_emails = contact.get('invitationAcceptedHandles') - contact_id = contact.get('id') - - self._log_level_debug_rawdata("iCloud FmF Raw Data - (api_friends.following) 5715", contact) - - #cycle thru the emails on the tracked_devices config parameter - for parm_email in self.fmf_devicename_email: - if instr(parm_email, '@') == False: - continue - - #cycle thru the contacts emails - matched_friend = False - devicename = self.fmf_devicename_email.get(parm_email) - - for contact_email in contact_emails: - if instr(contacts_valid_emails, contact_email) == False: - contacts_valid_emails += "CRLF• " + contact_email - - if contact_email.startswith(parm_email): - #update temp list with full email from contact recd - matched_friend = True - devicename_contact_emails[contact_email] = devicename - devicename_contact_emails[devicename] = contact_email - - self.fmf_id[contact_id] = devicename - self.fmf_id[devicename] = contact_id - self.devicename_verified[devicename] = True - - log_msg = (f"Matched FmF Contact > " - f"{self._format_fname_devicename(devicename)} " - f"with {contact_email}, Id: {contact_id}") - self._log_info_msg(log_msg) - break - - log_msg = (f"FmF contact list email addresses found in the FindMy app for {self.username} > " - f"{contacts_valid_emails}") - self._save_event_halog_info("*", log_msg) - - for devicename in self.devicename_verified: - if self.devicename_verified.get(devicename) is False: - parm_email = self.fmf_devicename_email.get(devicename) - devicename_contact_emails[devicename] = parm_email - log_msg = (f"iCloud3 Error for {self._format_fname_devicename(devicename)} > " - f"The email address `{parm_email}` is invalid " - f"or is not in the FmF contact list and will not be tracked." - f"CRLF{'-'*25}" - f"CRLF 1. Open the FindMy App. Select People." - f"CRLF 2. Verify that the person associated with this email address " - f"is listed. The list must include the person associated with the " - f"iCloud account being used. " - f"CRLF 3. Press `Share My Location` and follow the steps to add the " - f"person/email address to track, or" - f"CRLF 4. Press the person's name, then press Contact to verify their " - f"email address." - f"CRLF 5. Restart Home Assistant.") - self._save_event_halog_error("*", log_msg) - - self.fmf_devicename_email = {} - self.fmf_devicename_email.update(devicename_contact_emails) - - except Exception as err: - self._setup_iosapp_tracking_method() - _LOGGER.exception(err) - -#-------------------------------------------------------------------- - def _setup_tracked_devices_for_famshr(self): - ''' - Verify that the devicenames in the track_devices list are valid - and set it's the verified flag. Retry once if any are not verified. - ''' - try: - devicename_list_tracked, devicename_list_not_tracked = \ - self._verify_tracked_devices_for_famshr() - unverified_devicenames = [k for k in self.devicename_verified if self.devicename_verified.get(k) == False] - - #Refresh & retry if an unverfied devicename - if unverified_devicenames != []: - event_msg = (f"{EVLOG_ALERT}iCloud Alert > iCloud did not return device data for any tracked devices > " - f"{self._format_list(unverified_devicenames)}, Authentication & Verification will be retried") - self._save_event_halog_info("*", event_msg) - - self._pyicloud_authenticate_account(initial_setup=True) - - devicename_list_tracked, devicename_list_not_tracked = \ - self._verify_tracked_devices_for_famshr() - unverified_devicenames = [k for k in self.devicename_verified if self.devicename_verified.get(k) == False] - - if unverified_devicenames == []: - event_msg = (f"{EVLOG_ALERT}iCloud Alert > Authentication & Verification Retry Successful") - else: - event_msg = (f"Verification not successful for devices > " - f"{self._format_list(unverified_devicenames)}") - self._save_event_halog_info("*", event_msg) - - if devicename_list_not_tracked != '': - event_msg = (f"Not Tracking Devices >{devicename_list_not_tracked}") - if devicename_list_tracked != '': - self._save_event_halog_info("*", event_msg) - else: - event_msg = (f"iCloud3 Error > {event_msg}") - self._save_event_halog_error("*", event_msg) - - if devicename_list_tracked != '': - event_msg = (f"Tracking Devices >{devicename_list_tracked}") - self._save_event_halog_info("*", event_msg) - - return - - except Exception as err: - _LOGGER.exception(err) - - event_msg = (f"iCloud3 Error for {self.username} > " - "Error Authenticating account or no data was returned from " - "iCloud Web Services. Web Services may be down or the " - "Username/Password may be invalid.") - self._save_event_halog_error("*", event_msg) - return False - -#-------------------------------------------------------------------- - def _verify_tracked_devices_for_famshr(self): - ''' - Get the device info from iCloud Web Svcs via pyicloud. Then cycle through - the iCloud devices and for each device, see if it is in the list of devicenames - to be tracked. If in the list, set it's verified flag to True. - - Returns the devices being tracked and the devices in the iCloud list that are - not being tracked. - ''' - try: - devicename_list_tracked = "" - devicename_list_not_tracked = "" - - if self.api is not None: - api_devices = self.api.devices - - api_device_content = api_devices.response["content"] - - except (PyiCloudServiceNotActivatedException, PyiCloudNoDevicesException): - self.api = None - - if self.api is None: - event_msg = (f"iCloud3 Error for {self.username} > " - f"No devices were returned from the iCloud Location Services. " - f"iCloud {self.trk_method_short_name} Location Service is disabled. " - f"iCloud3 will use the IOS App tracking_method until your account is authenticated.") - self._save_event_halog_error("*", event_msg) - self._setup_iosapp_tracking_method() - return "", "" - - try: - self._log_level_debug_rawdata("FamShr iCloud Data - (devices) 5826", api_device_content) - - for device in api_device_content: - device_content_name = device[ATTR_NAME] - devicename = slugify(device_content_name) - device_type = device[ATTR_ICLOUD_DEVICE_CLASS] - self._log_level_debug_rawdata((f"FamShr iCloud Data - {devicename}"), - device, log_rawdata=self.log_level_debug_flag) - - if devicename in self.devicename_verified: - self.devicename_verified[devicename] = True - - self.api_device_devicename[device_content_name] = devicename - self.api_device_devicename[devicename] = device_content_name - devicename_list_tracked += (f"CRLF• {devicename} ({device_content_name}/{device_type})") - - else: - devicename_list_not_tracked += (f"CRLF• {devicename} ({device_content_name}/{device_type})") - - return devicename_list_tracked, devicename_list_not_tracked - - except Exception as err: - _LOGGER.exception(err) - - event_msg = (f"iCloud3 Error for {self.username} > " - "Error Authenticating account or no data was returned from " - "iCloud Web Services. Web Services may be down or the " - "Username/Password may be invalid.") - self._save_event_halog_error("*", event_msg) - - return "", "" - -#-------------------------------------------------------------------- - def _setup_tracked_devices_for_iosapp(self): - ''' - The devices to be tracked are in the track_devices or the - include_devices config parameters. - ''' - for devicename in self.devicename_verified: - self.devicename_verified[devicename] = True - - event_msg = (f"Verified Device for iOS App Tracking > " - f"{self._format_list(self.devicename_verified)}") - self._save_event_halog_info("*", event_msg) - return - - #-------------------------------------------------------------------- - def _setup_tracked_devices_config_parm(self, config_parameter): - ''' - Set up the devices to be tracked and it's associated information - for the configuration line entry. This will fill in the following - fields based on the extracted devicename: - device_type - friendly_name - fmf email address - sensor.picture name - device tracking flags - tracked_devices list - These fields may be overridden by the routines associated with the - operating mode (fmf, icloud, iosapp) - ''' - - if config_parameter is None: - return - - try: - for track_device_line in config_parameter: - di = self._decode_track_device_config_parms(track_device_line) - - if di is None: - return - - devicename = di[DI_DEVICENAME] - if self._check_devicename_in_another_thread(devicename): - continue - - elif (self.iosapp_monitor_dev_trk_flag.get(devicename) - and devicename == di[DI_IOSAPP_ENTITY]): - event_msg = (f"iCloud3 Error > iCloud3 not tracking {devicename}. " - f"The iCloud3 tracked_device is already assigned to " - f"the IOS App v2 and duplicate names are not allowed for HA " - f"Integration entities. You must change the IOS App v2 " - f"entity name on the HA `Sidebar>Configuration>Integrations` " - f"screen. Then do the following: " - f"CRLF{'-'*25}" - f"CRLF 1. Select the Mobile_App entry for `{devicename}`." - f"CRLF 2. Scroll to the `device_tracker.{devicename}` statement." - f"CRLF 3. Select it." - f"CRLF 4. Click the Settings icon." - f"CRLF 5. Add or change the suffix of the " - f"`device_tracker.{devicename}` Entity ID to another value " - f"(e.g., _2, _10, _iosappv2)." - f"CRLF 6. Restart HA.") - self._save_event_halog_error("*", event_msg) - continue - - email = di[DI_EMAIL] - self.fmf_devicename_email[email] = devicename - self.fmf_devicename_email[devicename] = email - self.device_type[devicename] = di[DI_DEVICE_TYPE] - self.fname[devicename] = di[DI_NAME] - self.badge_picture[devicename] = di[DI_BADGE_PICTURE] - self.devicename_iosapp_entity[devicename] = di[DI_IOSAPP_ENTITY] - self.devicename_iosapp_suffix[devicename] = di[DI_IOSAPP_SUFFIX] - self.track_from_zone[devicename] = di[DI_ZONES] - - self.devicename_verified[devicename] = False - - except Exception as err: - _LOGGER.exception(err) - -#-------------------------------------------------------------------- - def _decode_track_device_config_parms(self, track_device_line): - ''' - This will decode the device's parameter in the configuration file for - the include_devices, sensor_name_prefix, track_devices items in the - format of: - - devicename > email, picture, iosapp, sensornameprefix - - If the item cotains '@', it is an email item, - If the item contains .png or .jpg, it is a picture item. - Otherwise, it is the prefix name item for sensors - - The device_type and friendly names are also returned in the - following order as a list item: - devicename, device_type, friendlyname, email, picture, sensor name - - Various formats: - - Find my Friends: - ---------------- - devicename > email_address - devicename > email_address, badge_picture_name - devicename > email_address, badge_picture_name, iosapp_id, name - devicename > email_address, iosapp_id - devicename > email_address, iosapp_id, name - devicename > email_address, badge_picture_name, name - devicename > email_address, name - - Find my Phone: - -------------- - devicename - devicename > badge_picture_name - devicename > badge_picture_name, name - devicename > iosapp_id - devicename > iosapp_id, name - devicename > name - - - IOS App Version 1: - ------------------ - devicename - devicename > badge_picture_name - devicename > badge_picture_name, name - - IOS App Version 2: - ------------------ - devicename - devicename > iosapp_id - devicename > badge_picture_name, iosapp_id - devicename > badge_picture_name, iosapp_id, name - ''' - - try: - badge_picture = "" - email = "" - fname = "" - device_type = "" - zones = [] - dev_trk_entity_id = "" - dev_trk_iosapp_suffix = "" - dev_trk_device_id = "" - iosapp_monitor_flag = True - - #devicename_parameters = track_device_line.lower().split('>') - devicename_parameters = track_device_line.split('>') - devicename = slugify(devicename_parameters[0].replace(' ', '', 99).lower()) - log_msg = (f"Decoding > {track_device_line}") - self._save_event_halog_info("*", log_msg) - - #If tracking method is IOSAPP or FAMSHR, try to make a friendly - #name from the devicename. If FMF, it will be retrieved from the - #contacts data. If it is specified on the config parms, it will be - #overridden with the specified name later. - - fname, device_type = self._extract_name_device_type(devicename) - self.tracked_devices_config_parm[devicename] = track_device_line - - if len(devicename_parameters) > 1: - parameters = devicename_parameters[1].strip() - parameters = parameters + ',,,,,,' - else: - parameters = '' - - items = parameters.split(',') - for itemx in items: - item_entered = itemx.strip().replace(' ', '_') - item = item_entered.lower() - - if item == '': - continue - elif instr(item, '@'): - email = item - elif instr(item, 'png') or instr(item, 'jpg'): - badge_picture = item - elif item in ['iosappv1', 'noiosapp']: - iosapp_monitor_flag = False - elif item.startswith("_"): - dev_trk_iosapp_suffix = item - dev_trk_entity_id = devicename + dev_trk_iosapp_suffix - elif instr(item, "_"): - dev_trk_entity_id = item - dev_trk_iosapp_suffix = dev_trk_entity_id.replace(devicename, "") - elif item in self.zones: - if item != HOME: - if zones == []: - zones = [item] - else: - zones.append(item) - else: - fname = item_entered - - zones.append(HOME) - if badge_picture and instr(badge_picture, '/') == False: - badge_picture = '/local/' + badge_picture - - event_msg = (f"Results > FriendlyName-{fname}, Email-{email}, " - f"Picture-{badge_picture}, DeviceType-{device_type}") - if zones != []: - event_msg += f", TrackFromZone-{zones}" - - if dev_trk_entity_id != "": - event_msg += (f", iOSAppDevTrkEntity-{dev_trk_entity_id}") - self._save_event("*", event_msg) - - self.iosapp_monitor_dev_trk_flag[devicename] = iosapp_monitor_flag - device_info = [devicename, device_type, fname, email, badge_picture, - dev_trk_entity_id, dev_trk_iosapp_suffix, zones] - - log_msg = (f"Extract Trk_Dev Parm, ic3dev_info-{device_info}") - self._log_debug_msg("*", log_msg) - - except Exception as err: - _LOGGER.exception(err) - - return device_info - - #-------------------------------------------------------------------- - def _setup_monitored_iosapp_entities(self, devicename, iosapp_entities, notify_devicenames, dev_trk_iosapp_suffix): - - #Cycle through the mobile_app 'core.entity_registry' items and see - #if this 'device_tracker.devicename' exists. If so, it is using - #the iosapp v2 component. Return the devicename with the device suffix (_#) - #and the sensor.xxxx_last_update_trigger entity for that device. - - - #self.device_tracker_entity_ic3[devicename] = (f"device_tracker.{devicename}") - if (self.iosapp_monitor_dev_trk_flag.get(devicename) == False): - self.device_tracker_entity_iosapp[devicename] = (f"device_tracker.{devicename}") - self.notify_iosapp_entity[devicename] = (f"ios_{devicename}") - return ("", "", "", "") - - dev_trk_iosapp_suffix = "" if dev_trk_iosapp_suffix == None else dev_trk_iosapp_suffix - dev_trk_entity_id = devicename + dev_trk_iosapp_suffix if dev_trk_iosapp_suffix != "" else "" - sensor_last_trigger_entity = "" - sensor_battery_level_entity = "" - dev_trk_list = "" - dev_trk_device_id = "" - - #Cycle through iosapp_entities in - #.storage/core.entity_registry (mobile_app pltform) and get the - #names of the iosapp device_tracker and sensor.last_update_trigger - #names for this devicename. If iosapp_id suffix or device tracker entity name - # is specified, look for the device_tracker with that number. - dev_trk_entity_cnt = 0 - - log_msg = (f"Scanning {self.entity_registry_file} Entity Registry for " - f"iOS App device_tracker {devicename}") - if dev_trk_entity_id != "": - log_msg += (f", Specified Entity-({dev_trk_entity_id})") - self._log_info_msg(log_msg) - - #Get the entity for the devicename entity specified on the track_devices parameter - if dev_trk_entity_id != "": - device_tracker_entities = [x for x in iosapp_entities \ - if (x['entity_id'] == f"device_tracker.{dev_trk_entity_id}")] - dev_trk_entity_cnt = len(device_tracker_entities) - - #If the entity specified was not found, get all entities for the device - if dev_trk_entity_cnt == 0: - device_tracker_entities = [x for x in iosapp_entities \ - if (x['entity_id'].startswith("device_tracker.") and instr(x['entity_id'], devicename))] - dev_trk_entity_cnt = len(device_tracker_entities) - - #Extract the device_id for each entity found. If more than 1 was found, display an - #error message about duplicate entities and select the last one. - for entity in device_tracker_entities: - entity_id = entity['entity_id'] - dev_trk_entity_id = entity_id.replace("device_tracker.", "") - dev_trk_iosapp_suffix = dev_trk_entity_id.replace(devicename, "") - dev_trk_device_id = entity['device_id'] - dev_trk_list += (f"CRLF• {dev_trk_entity_id} ({dev_trk_iosapp_suffix})") - - log_msg = (f"SCAN ENTITY REG, device_trackers found-[{dev_trk_list}]") - self._log_debug_msg(devicename, log_msg) - - self.iosapp_monitor_dev_trk_flag[devicename] = (dev_trk_entity_cnt > 0) - - if dev_trk_entity_cnt > 1: - self.info_notification = (f"iOS App Device Tracker not specified for " - f"{self._format_fname_devicename(devicename)}. See Event Log for more information.") - dev_trk_list += " ← ← Will be monitored" - event_msg = (f"iCloud3 Setup Error > There are {dev_trk_entity_cnt} iOS App " - f"device_tracker entities for {devicename}, iCloud3 can only monitor one." - f"CRLF{'-'*25}CRLFDo one of the following:" - f"CRLF● Delete the incorrect device_tracker from the Entity Registry, or" - f"CRLF● Add the full entity name or the suffix of the device_tracker entity that " - f"should be monitored to the `{devicename}` track_devices parameter, or" - f"CRLF● Change the device_tracker entity's name of the one that should not be monitored " - f"so it does not start with `{devicename}`." - f"CRLF{'-'*25}CRLFDevice_tracker entities (suffixes) found:" - f"{dev_trk_list}") - self._save_event_halog_error("*", event_msg) - - #Get the sensor.last_update_trigger for deviceID - if dev_trk_device_id: - sensor_last_trigger_entity = \ - self._get_entity_registry_item(devicename, iosapp_entities, dev_trk_device_id, '_last_update_trigger') - sensor_battery_level_entity = '' - - if self.iosapp_monitor_dev_trk_flag.get(devicename) == False: - event_msg = (f"iCloud3 Setup Error > {dev_trk_entity_id} > " - f"The iOS App device_tracker entity was not found in the " - f"Entity Registry." - f"CRLFDevice_tracker entities (suffixes) found -" - f"{dev_trk_list}") - self._save_event_halog_error("*", event_msg) - self.info_notification = ICLOUD3_ERROR_MSG - - dev_trk_entity_id = devicename - dev_trk_iosapp_suffix = '' - sensor_last_trigger_entity = '' - sensor_battery_level_entity = '' - - self.devicename_iosapp_entity[devicename] = dev_trk_entity_id - self.devicename_iosapp_suffix[devicename] = dev_trk_iosapp_suffix - self.iosapp_last_trigger_entity[devicename] = sensor_last_trigger_entity - self.iosapp_battery_level_entity[devicename] = sensor_battery_level_entity - self.device_tracker_entity_iosapp[devicename] = (f"device_tracker.{dev_trk_entity_id}") - - #Extract all notify entitity id's with this devicename in them from hass notify services notify list - notify_devicename_list = [] - for notify_devicename in notify_devicenames: - if instr(notify_devicename, devicename): - notify_devicename_list.append(notify_devicename.replace("mobile_app_", "")) - - self.notify_iosapp_entity[devicename] = notify_devicename_list - - return - -#-------------------------------------------------------------------- - def _get_entity_registry_entities(self, platform): - ''' - Read the /config/.storage/core.entity_registry file and return - the entities for platform ('mobile_app', 'ios', etc) - ''' - - try: - if self.entity_registry_file is None: - self.entity_registry_file = self.hass.config.path( - STORAGE_DIR, STORAGE_KEY_ENTITY_REGISTRY) - - entities = [] - entity_reg_file = open(self.entity_registry_file) - entity_reg_str = entity_reg_file.read() - entity_reg_data = json.loads(entity_reg_str) - entity_reg_entities = entity_reg_data['data']['entities'] - entity_reg_file.close() - - entity_devicename_list = "" - for entity in entity_reg_entities: - if (entity['platform'] == platform): - entities.append(entity) - if entity['entity_id'].startswith("device_tracker."): - entity_devicename_list += (f"CRLF• {entity['entity_id'].replace('device_tracker.', '')} " - f"({entity['original_name']})") - - event_msg = (f"Entity Registry mobile_app device_tracker entities found >{entity_devicename_list}") - self._save_event("*", event_msg) - - except Exception as err: - _LOGGER.exception(err) - pass - - return entities -#-------------------------------------------------------------------- - def _get_mobile_app_notify_devicenames(self): - ''' - Extract notify services devicenames from hass - ''' - try: - notify_devicenames = [] - services = self.hass.services - notify_services = dict(services.__dict__)['_services']['notify'] - - for notify_service in notify_services: - if notify_service.startswith("mobile_app_"): - notify_devicenames.append(notify_service) - except: - pass - - return notify_devicenames -#-------------------------------------------------------------------- - def _get_entity_registry_item(self, devicename, iosapp_entities, device_id, desired_entity_name): - ''' - Scan through the iosapp entities and get the actual ios app entity_id for - the desired entity - ''' - for entity in (x for x in iosapp_entities \ - if x['unique_id'].endswith(desired_entity_name)): - - if (entity['device_id'] == device_id): - real_entity = entity['entity_id'].replace('sensor.', '') - log_msg = (f"Matched iOS App {entity['entity_id']} with " - f"iCloud3 tracked_device {devicename}") - self._log_info_msg(log_msg) - - return real_entity - - return '' - -#-------------------------------------------------------------------- - def _check_valid_ha_device_tracker(self, devicename): - ''' - Validate the 'device_tracker.devicename' entity during the iCloud3 - Stage 2 initialization. If it does not exist, then it has not been set - up in known_devices.yaml (and/or the iosapp) and can not be used ty - the 'see' function thatupdates the location information. - ''' - try: - retry_cnt = 0 - entity_id = self._format_entity_id(devicename) - - while retry_cnt < 10: - ic3dev_data = self.hass.states.get(entity_id) - - if ic3dev_data: - ic3dev_attrs = ic3dev_data.attributes - - if ic3dev_attrs: - return True - retry_cnt += 1 - - #except (KeyError, AttributeError): - # pass - - except Exception as err: - _LOGGER.exception(err) - - return False - -######################################################### -# -# DEVICE SENSOR SETUP ROUTINES -# -######################################################### - def _setup_sensor_base_attrs(self, devicename): - ''' - The sensor name prefix can be the devicename or a name specified on - the track_device configuration parameter ''' - - self.sensor_prefix_name[devicename] = devicename - - attr_prefix_fname = self.sensor_prefix_name.get(devicename) - - #Format sensor['friendly_name'] attribute prefix - attr_prefix_fname = attr_prefix_fname.replace('_','-').title() - attr_prefix_fname = attr_prefix_fname.replace('Ip','-iP') - attr_prefix_fname = attr_prefix_fname.replace('Iw','-iW') - attr_prefix_fname = attr_prefix_fname.replace('--','-') - attr_prefix_fname = attr_prefix_fname.replace('-De-', '-de-') - if attr_prefix_fname.startswith('-'): attr_prefix_fname = attr_prefix_fname[1:] - - self.sensor_attr_fname_prefix[devicename] = (f"{attr_prefix_fname} ") - - badge_attrs = {} - badge_attrs['entity_picture'] = self.badge_picture.get(devicename) - badge_attrs[ATTR_FRIENDLY_NAME] = self.fname.get(devicename) - badge_attrs['icon'] = SENSOR_ATTR_ICON.get('badge') - self.sensor_badge_attrs[devicename] = badge_attrs - - event_msg = "" - for zone in self.track_from_zone.get(devicename): - if zone == 'home': - zone_prefix = '' - else: - zone_prefix = zone + '_' - event_msg = (f"CRLF• Sensor entity prefix > sensor.{zone_prefix}" - f"{self.sensor_prefix_name.get(devicename)}") - - log_msg = (f"Set up sensor name for device, devicename-{devicename}, " - f"entity_base-{self.sensor_prefix_name.get(devicename)}") - self._log_debug_msg(devicename, log_msg) - - #Return text for the event msg during startup - return event_msg - -#-------------------------------------------------------------------- - def _setup_sensors_custom_list(self, initial_load_flag): - ''' - This will process the 'sensors' and 'exclude_sensors' config - parameters if 'sensors' exists, only those sensors wil be displayed. - if 'exclude_sensors' eists, those sensors will not be displayed. - 'sensors' takes ppresidence over 'exclude_sensors'. - ''' - - if initial_load_flag == False: - return - - if self.sensor_ids != []: - self.sensors_custom_list = [] - for sensor_id in self.sensor_ids: - id = sensor_id.lower().strip() - if id in SENSOR_ID_NAME_LIST: - self.sensors_custom_list.append(SENSOR_ID_NAME_LIST.get(id)) - - elif self.exclude_sensor_ids != []: - self.sensors_custom_list.extend(SENSOR_DEVICE_ATTRS) - for sensor_id in self.exclude_sensor_ids: - id = sensor_id.lower().strip() - if id in SENSOR_ID_NAME_LIST: - if SENSOR_ID_NAME_LIST.get(id) in self.sensors_custom_list: - self.sensors_custom_list.remove(SENSOR_ID_NAME_LIST.get(id)) - else: - self.sensors_custom_list.extend(SENSOR_DEVICE_ATTRS) - - -######################################################### -# -# DEVICE STATUS SUPPORT FUNCTIONS FOR GPS ACCURACY, OLD LOC DATA, ETC -# -######################################################### - def _check_poor_location_gps_only(self, devicename, timestamp_secs, gps_accuracy): - poor_location_gps_flag, discard_reason = self._check_poor_location_gps( - devicename, - last_located_secs, - gps_accuracy, - checkOnly=True) - return poor_location_gps_flag - - def _check_poor_location_gps(self, devicename, timestamp_secs, gps_accuracy, checkOnly=False): - """ - If this is checked in the icloud location cycle, - check if the location isold flag. Then check to see if - the current timestamp is the same as the timestamp on the previous - poll. - - If this is checked in the iosapp cycle, the trigger transaction has - already updated the lat/long so - you don't want to discard the record just because it is old. - If in a zone, use the trigger but check the distance from the - zone when updating the device. - - Update the old_location_poor_gps_cnt if just_check=False - """ - - try: - discard_reason = "" - location_age = int(self._secs_since(timestamp_secs)) - location_age_str = (f"{self._format_age(location_age)}") - old_location_flag = (location_age > self.old_location_secs.get(devicename)) - poor_gps_flag = (gps_accuracy > self.gps_accuracy_threshold) - - if self._is_inzone(devicename): - old_location_flag = False - poor_gps_flag = (poor_gps_flag \ - and self.ignore_gps_accuracy_inzone_flag == False) - - if old_location_flag and poor_gps_flag: - discard_reason = (f"OldLocation-{location_age_str}, GPSAccuracy-{gps_accuracy}m") - elif old_location_flag: - discard_reason = (f"OldLocation-{location_age_str}") - elif poor_gps_flag: - discard_reason = (f"GPSAccuracy-{gps_accuracy}m") - - #Do not update status and count if just checking poor loc gps status - if checkOnly: - return (old_location_flag or poor_gps_flag) - - if old_location_flag or poor_gps_flag: - self.poor_gps_flag[devicename] = True - self.poor_location_gps_cnt[devicename] += 1 - discard_reason += (f" (#{self.poor_location_gps_cnt.get(devicename)})") - else: - self.poor_gps_flag[devicename] = False - self.poor_location_gps_cnt[devicename] = 0 - - log_msg = (f"CHECK ISOLD/GPS ACCURACY, Time-{self._secs_to_time(timestamp_secs)}, " - f"isOldFlag-{old_location_flag}, Age-{location_age_str}, " - f"GPSAccuracy-{gps_accuracy}m, GPSAccuracyFlag-{poor_gps_flag}", - f"Results-{self.poor_gps_flag.get(devicename)}, " - f"DiscardReason-{discard_reason}") - self._log_debug_msg(devicename, log_msg) - - except Exception as err: - _LOGGER.exception(err) - self.poor_gps_flag[devicename] = False - self.poor_location_gps_cnt[devicename] = 0 - - log_msg = ("►INTERNAL ERROR (ChkOldLocPoorGPS)") - self._log_error_msg(log_msg) - - return (self.poor_gps_flag.get(devicename), discard_reason) - -#-------------------------------------------------------------------- - def _check_next_update_time_reached(self, devicename=None): - ''' - Cycle through the next_update_secs for all devices and - determine if one of them is earlier than the current time. - If so, the devices need to be updated. - - Return None - Next update time has not been reached on any devicename:zone - devicename - devicename of phone that needs to be updated - ''' - try: - if self.next_update_secs is None: - return None - - self.next_update_devicenames = [] - for devicename_zone in self.next_update_secs: - if (devicename is None or devicename_zone.startswith(devicename)): - time_till_update = self.next_update_secs.get(devicename_zone) - \ - self.this_update_secs - - if time_till_update <= 5: - self.next_update_devicenames.append(devicename_zone.split(':')[0]) - - return (f"{devicename_zone.split(':')[0]}") - - except Exception as err: - _LOGGER.exception(err) - - return None - -#-------------------------------------------------------------------- - def _check_next_update_time_reached_devicename(self, devicename): - ''' - Cycle through the next_update_secs for this devicename and - determine if one of them is earlier than the current time. - If so, the devicename need to be updated. - - Return True - Reached next_update_secs, update devicename - False - Do not update devicename - ''' - try: - if self.next_update_secs is None: - return False - - for devicename_zone in self.next_update_secs: - if devicename_zone.startswith(devicename): - time_till_update = self.next_update_secs.get(devicename_zone) - \ - self.this_update_secs - - if time_till_update <= 5: - return True - - except Exception as err: - _LOGGER.exception(err) - - return False -#-------------------------------------------------------------------- - def _check_in_zone_and_before_next_update(self, devicename): - ''' - If updated because another device was updated and this device is - in a zone and it's next time has not been reached, do not update now - ''' - try: - if (self.state_this_poll.get(devicename) != NOT_SET - and self._is_inzone(devicename) - and self._was_inzone(devicename) - and self._check_next_update_time_reached(devicename) is None): - - return True - - except Exception as err: - _LOGGER.exception(err) - - return False - -#-------------------------------------------------------------------- - def _check_outside_zone_no_exit(self,devicename, zone, trigger, latitude, longitude): - ''' - If the device is outside of the zone and less than the zone radius + gps_acuracy_threshold - and no Geographic Zone Exit trigger was received, it has probably wandered due to - GPS errors. If so, discard the poll and try again later - ''' - trigger = self.trigger.get(devicename) if trigger == '' else trigger - if trigger in IOS_TRIGGERS_ENTER: - return False, '' - - dist_from_zone_m = self._zone_distance_m( - devicename, - zone, - latitude, - longitude) - - zone_radius_m = self.zone_radius_m.get( - zone, - self.zone_radius_m.get(HOME)) - zone_radius_accuracy_m = zone_radius_m + self.gps_accuracy_threshold - - msg = '' - if (dist_from_zone_m > zone_radius_m - and self.got_exit_trigger_flag.get(devicename) == False - and instr(zone, STATIONARY) == False): - if dist_from_zone_m < zone_radius_accuracy_m: - self.poor_gps_flag[devicename] = True - - msg = ("Outside Zone and No Exit Zone trigger, " - f"Keeping in zone > Zone-{zone}, " - f"Distance-{dist_from_zone_m}m, " - f"DiscardDist-{zone_radius_m}m to {zone_radius_accuracy_m}m ") - return True, msg - else: - msg = ("Outside Zone and No Exit Zone trigger but outside threshold, " - f"Exiting zone > Zone-{zone}, " - f"Distance-{dist_from_zone_m}m, " - f"DiscardDist-{zone_radius_m}m to {zone_radius_accuracy_m}m ") - - return False, '' -#-------------------------------------------------------------------- - def _get_interval_for_error_retry_cnt(self, devicename, counter=POOR_LOC_GPS_CNT): - ''' - Get the interval time based on the retry_cnt. - retry_cnt = -1 - Use the poor_location_gps count for devicename - = iosapp_request_loc_sent_retry_cnt - = retry pyicloud authorization count - - Interval range table - key = retry_cnt, value = time in minutes - - poor_location_gps cnt, icloud_authentication cnt (default): - interval_range_1 = {0:.25, 4:1, 8:5, 12:30, 16:60, 20:120, 24:240} - - request iosapp location retry cnt: - interval_range_2 = {0:.5, 4:2, 8:30, 12:60, 16:120} - - ''' - if counter == POOR_LOC_GPS_CNT: - retry_cnt = self.poor_location_gps_cnt.get(devicename, 0) - range_tbl = RETRY_INTERVAL_RANGE_1 - - elif counter == AUTH_ERROR_CNT: - retry_cnt = self.icloud_acct_auth_error_cnt - range_tbl = RETRY_INTERVAL_RANGE_1 - - elif counter == IOSAPP_REQUEST_LOC_CNT: - retry_cnt = self.iosapp_request_loc_retry_cnt.get(devicename) - range_tbl = RETRY_INTERVAL_RANGE_2 - else: - return 60 - - interval = .25 - for k, v in range_tbl.items(): - if k <= retry_cnt: - interval = v - - interval = interval * 60 - - return interval -#-------------------------------------------------------------------- - def _display_time_till_update_info_msg(self, devicename_zone, age_secs): - ''' - Display the secs until the next update in the next update time field. - if between 90s to -90s. if between -90s and -120s, resisplay time - without the age to make sure it goes away. - ''' - - info_msg=(f"{self.next_update_time.get(devicename_zone)} ") - if age_secs <= 90 and age_secs >= -90: - info_msg += (f"({age_secs}s)") - - if age_secs <= 90 and age_secs > -120: - attrs = {} - attrs[ATTR_NEXT_UPDATE_TIME] = info_msg - - self._update_device_sensors(devicename_zone, attrs) - -#-------------------------------------------------------------------- - def _log_device_status_attrubutes(self, status): - - """ - Status-{'batteryLevel': 1.0, 'deviceDisplayName': 'iPhone X', - ATTR_ICLOUD_DEVICE_STATUS: '200', CONF_NAME: 'Gary-iPhone', - 'deviceModel': 'iphoneX-1-2-0', 'rawDeviceModel': 'iPhone10,6', - ATTR_ICLOUD_DEVICE_CLASS: 'iPhone', - 'id':'qyXlfsz1BIOGxcqDxDleX63Mr63NqBxvJcajuZT3y05RyahM3/OMpuHYVN - SUzmWV', 'lowPowerMode': False, 'batteryStatus': 'NotCharging', - 'fmlyShare': False, 'location': {'isOld': False, - 'isInaccurate': False, 'altitude': 0.0, 'positionType': 'GPS' - 'latitude': 27.726843548976, 'floorLevel': 0, - 'horizontalAccuracy': 48.00000000000001, - 'locationType': '', 'timeStamp': 1539662398966, - 'locationFinished': False, 'verticalAccuracy': 0.0, - 'longitude': -80.39036092533418}, 'locationCapable': True, - 'locationEnabled': True, 'isLocating': True, 'remoteLock': None, - 'activationLocked': True, 'lockedTimestamp': None, - 'lostModeCapable': True, 'lostModeEnabled': False, - 'locFoundEnabled': False, 'lostDevice': None, - 'lostTimestamp': '', 'remoteWipe': None, - 'wipeInProgress': False, 'wipedTimestamp': None, 'isMac': False} - """ - - log_msg = (f"ICLOUD DATA, DEVICE ID-{status}, ▶deviceDisplayName-{status['deviceDisplayName']}") - self._log_debug_msg('*', log_msg) - - location = status[ATTR_LOCATION] - - log_msg = (f"ICLOUD DEVICE STATUS/LOCATION, " - f"●deviceDisplayName-{status['deviceDisplayName']}, " - f"●deviceStatus-{status[ATTR_ICLOUD_DEVICE_STATUS]}, " - f"●name-{status[CONF_NAME]}, " - f"●deviceClass-{status[ATTR_ICLOUD_DEVICE_CLASS]}, " - f"●batteryLevel-{status[ATTR_ICLOUD_BATTERY_LEVEL]}, " - f"●batteryStatus-{status[ATTR_ICLOUD_BATTERY_STATUS]}, " - f"●isOld-{location[ATTR_ISOLD]}, " - f"●positionType-{location['positionType']}, " - f"●latitude-{location[ATTR_LATITUDE]}, " - f"●longitude-{location[ATTR_LONGITUDE]}, " - f"●horizontalAccuracy-{location[ATTR_ICLOUD_HORIZONTAL_ACCURACY]}, " - f"●timeStamp-{location[ATTR_ICLOUD_TIMESTAMP]}" - f"({self._timestamp_to_time_utcsecs(location[ATTR_ICLOUD_TIMESTAMP])})") - self._log_debug_msg('*', log_msg) - return True - -#-------------------------------------------------------------------- - def _log_start_finish_update_banner(self, start_finish_symbol, devicename, - method, update_reason): - ''' - Display a banner in the log file at the start and finish of a - device update cycle - ''' - - log_msg = (f"^ {method} ^ {devicename}-{self.group}-{self.base_zone} ^^ " - f"State-{self.state_this_poll.get(devicename)} ^^ {update_reason} ^") - - log_msg2 = log_msg.replace('^', start_finish_symbol, 99).replace(" ",".").upper() - self._log_debug_msg(devicename, log_msg2) - -######################################################### -# -# EVENT LOG ROUTINES -# -######################################################### - def _setup_event_log_base_attrs(self, initial_load_flag): - ''' - Set up the name, picture and devicename attributes in the Event Log - sensor. Read the sensor attributes first to see if it was set up by - another instance of iCloud3 for a different iCloud acount. - ''' - try: - curr_base_attrs = self.hass.states.get(SENSOR_EVENT_LOG_ENTITY).attributes - - base_attrs = {k: v for k, v in curr_base_attrs.items()} - - except (KeyError, AttributeError): - base_attrs = {} - base_attrs["logs"] = "" - - except Exception as err: - _LOGGER.exception(err) - - try: - name_attrs = {} - if self.tracked_devices: - for devicename in self.tracked_devices: - name_attrs[devicename] = self.fname.get(devicename) - else: - name_attrs = {'No Tracked Devices Error'} - - if len(self.tracked_devices) > 0: - self.log_table_max_items = EVLOG_RECDS_PER_DEVICE * len(self.tracked_devices) - if len(self.track_from_zone.get(devicename)) > 1: - self.log_table_max_items = .25 * self.log_table_max_items * len(self.track_from_zone.get(devicename)) - - base_attrs["names"] = name_attrs - - self._set_state(SENSOR_EVENT_LOG_ENTITY, "Initialized", base_attrs) - - self.event_log_base_attrs = {k: v for k, v in base_attrs.items() if k != "logs"} - self.event_log_base_attrs["logs"] = "" - - except Exception as err: - _LOGGER.exception(err) - - return - -#------------------------------------------------------ - def _save_event(self, devicename, event_text): - ''' - Add records to the Event Log table the devicename. If the devicename="*", - the event_text is added to all devicesnames table. - - The event_text can consist of pseudo codes that display a 2-column table (see - _display_usage_counts function for an example and details) - - The event_log lovelace card will display the event in a special color if - the text starts with a special character: - ''' - try: - if (instr(event_text, "▼") or instr(event_text, "▲") - or len(event_text) == 0 - or instr(event_text, "event_log")): - return - - devicename_zone = self._format_devicename_zone(devicename, HOME) - this_update_time = dt_util.now().strftime('%H:%M:%S') - this_update_time = self._time_to_12hrtime(this_update_time, ampm=True) - - if devicename is None: devicename = '*' - - if ((self.start_icloud3_inprocess_flag and self.state_this_poll.get(devicename) == '') - or devicename == "*"): - iosapp_state= '' - zone_names = '' - zone = '' - interval = '' - travel_time = '' - distance = '' - - else: - iosapp_state= self.last_iosapp_state.get(devicename, '') - zone = self.zone_current.get(devicename, AWAY) - interval = self.interval_str.get(devicename_zone, '').split("(")[0] - travel_time = self.last_tavel_time.get(devicename_zone, '') - distance = self.last_distance_str.get(devicename_zone, '') - - if (instr(type(event_text), 'dict') or instr(type(event_text), 'list')): - event_text = str(event_text) - - if instr(zone, STATIONARY): zone = STATIONARY - if instr(iosapp_state, STATIONARY): iosapp_state = STATIONARY - - iosapp_state = self.zone_to_display.get(iosapp_state, iosapp_state.title()) - zone = self.zone_to_display.get(zone, zone.title()) - - if iosapp_state == None: iosapp_state = '' - if zone == None: zone = '' - - if len(event_text) == 0: event_text = 'Info Message' - if event_text.startswith('__'): event_text = event_text[2:] - event_text = event_text.replace('"', '`') - event_text = event_text.replace("'", "`") - event_text = event_text.replace('~','--') - event_text = event_text.replace('Background','Bkgnd') - event_text = event_text.replace('Geographic','Geo') - event_text = event_text.replace('Significant','Sig') - - for from_text in self.display_text_as_list: - event_text = event_text.replace(from_text, self.display_text_as_list.get(from_text)) - - #Keep track of special colors so it will continue on the - #next text chunk - color_symbol = '' - if event_text.startswith('$'): color_symbol = '$' - if event_text.startswith('$$'): color_symbol = '$$' - if event_text.startswith('$$$'): color_symbol = '$$$' - if event_text.startswith('*'): color_symbol = '*' - if event_text.startswith('**'): color_symbol = '**' - if event_text.startswith('***'): color_symbol = '***' - if instr(event_text, ERROR): color_symbol = '!' - char_per_line = 2000 - - #Break the event_text string into chunks of 250 characters each and - #create an event_log recd for each chunk - if len(event_text) < char_per_line: - event_recd = [devicename, this_update_time, - iosapp_state, zone, interval, travel_time, - distance, event_text] - self._insert_event_log_recd(event_recd) - - else: - line_no = int(len(event_text)/char_per_line + .5) - char_per_line = int(len(event_text) / line_no) - event_text+=f" ({len(event_text)}-{line_no}-{char_per_line})" - - if event_text.find("CRLF") > 0: - split_str = "CRLF" - else: - split_str = " " - split_str_end_len = -1 * len(split_str) - word_chunk = event_text.split(split_str) - - line_no = len(word_chunk)-1 - event_chunk = '' - while line_no >= 0: - if len(event_chunk) + len(word_chunk[line_no]) + len(split_str) > char_per_line: - event_recd = [devicename, '', '', '', '', '', '', - (f"{color_symbol}{event_chunk[:split_str_end_len]} ({event_chunk[:split_str_end_len]})")] - self._insert_event_log_recd(event_recd) - - event_chunk = '' - - if len(word_chunk[line_no]) > 0: - event_chunk = word_chunk[line_no] + split_str + event_chunk - - line_no-=1 - - event_recd = [devicename, this_update_time, - iosapp_state, zone, interval, travel_time, - distance, (f"{event_chunk[:split_str_end_len]} ({event_chunk[:split_str_end_len]})")] - self._insert_event_log_recd(event_recd) - - except Exception as err: - _LOGGER.exception(err) - -#------------------------------------------------------- - def _insert_event_log_recd(self, event_recd): - """Add the event recd into the event table""" - - if self.event_log_table is None: - self.event_log_table = [] - - while len(self.event_log_table) >= self.log_table_max_items: - self.event_log_table.pop() - - self.event_log_table.insert(0, event_recd) - -#------------------------------------------------------ - def _update_sensor_ic3_event_log(self, devicename): - """Display the event log""" - - try: - log_attrs = self.event_log_base_attrs.copy() if self.event_log_base_attrs else {} - - attr_recd = {} - attr_event = {} - log_attr_text = "" - if self.log_level_eventlog_flag: log_attr_text += "evlog," - if self.log_level_debug_flag: log_attr_text += "halog" - log_attrs["log_level_debug"] = log_attr_text - - if devicename is None: - return - elif devicename == "clear_log_items": - log_attrs["filtername"] = "ClearLogItems" - elif devicename == "*" : - log_attrs["filtername"] = "Initialize" - else: - log_attrs["filtername"] = self.fname.get(devicename) - - if devicename == 'clear_log_items': - max_recds = EVENT_LOG_CLEAR_CNT - self.event_log_clear_secs = HIGH_INTEGER - devicename = self.event_log_last_devicename - else: - max_recds = HIGH_INTEGER - self.event_log_clear_secs = self.this_update_secs + EVENT_LOG_CLEAR_SECS - self.event_log_last_devicename = devicename - - #The state must change for the recds to be refreshed on the - #Lovelace card. If the state does not change, the new information - #is not displayed. Add the update time to make it unique. - log_update_time = (f"{dt_util.now().strftime('%a, %m/%d')}, " - f"{dt_util.now().strftime(self.um_time_strfmt)}") - log_attrs["update_time"] = log_update_time - self.event_log_sensor_state = (f"{devicename}:{log_update_time}") - - attr_recd = self._update_sensor_ic3_event_log_recds(devicename, max_recds) - log_attrs["logs"] = attr_recd - - self._set_state(SENSOR_EVENT_LOG_ENTITY, self.event_log_sensor_state, log_attrs) - - except Exception as err: - _LOGGER.exception(err) -#------------------------------------------------------ - def _update_sensor_ic3_event_log_recds(self, devicename, max_recds=HIGH_INTEGER): - ''' - Build the event items attribute for the event log sensor. Each item record - is [devicename, time, state, zone, interval, travTime, dist, textMsg] - Select the items for the devicename or '*' and return the string of - the resulting list to be passed to the Event Log - ''' - if devicename == "startup_log": - devicename = "*" - - el_devicename_check=['*', devicename] - - if self.log_level_eventlog_flag: - attr_recd = [el_recd[1:8] for el_recd in self.event_log_table \ - if el_recd[0] in el_devicename_check] - elif devicename == "*": - attr_recd = [el_recd[1:8] for el_recd in self.event_log_table \ - if ((el_recd[0] in el_devicename_check - or el_recd[7].startswith(EVLOG_ALERT)) - and (el_recd[7].startswith(EVLOG_DEBUG) == False))] - else: - attr_recd = [el_recd[1:8] for el_recd in self.event_log_table \ - if (el_recd[0] in el_devicename_check - and el_recd[7].startswith(EVLOG_DEBUG) == False)] - - if max_recds == EVENT_LOG_CLEAR_CNT: - recd_cnt = len(attr_recd) - attr_recd = attr_recd[0:max_recds] - control_recd = ['',' ',' ',' ',' ',' ',f'^^^ Click `Refresh` to display \ - all records ({max_recds} of {recd_cnt} displayed) ^^^'] - attr_recd.insert(0, control_recd) - - control_recd = [HHMMSS_ZERO,'','','','','','Last Record'] - attr_recd.append(control_recd) - - return str(attr_recd) - -#------------------------------------------------------ - def _export_ic3_event_log(self): - ''' Export Event Log to 'config/icloud_event_log.log' ''' - - try: - log_update_time = (f"{dt_util.now().strftime('%a, %m/%d')}, " - f"{dt_util.now().strftime(self.um_time_strfmt)}") - hdr_recd ="devicename\tTime\tiOSApp State\tiC3 Zone\tInterval\tTravel Time\tDistance\tText" - export_recd = (f"{hdr_recd}\n" - f"Tracked Devices: { self.tracked_devices:}\n" - f"Log Update Time: {log_update_time}\n") - - #Prepare Global '*' records. Reverse the list elements using [::-1] and make a string of the results - el_recds = [el_recd for el_recd in self.event_log_table if (el_recd[0] == "*")] - dev_recds = str(el_recds[::-1]) - export_recd += self._export_ic3_event_log_reformat_recds(dev_recds) - - #Prepare recds for each devicename - for devicename in self.tracked_devices: - el_devicename_check=[devicename] - el_recds = [el_recd for el_recd in self.event_log_table \ - if (el_recd[0] == devicename and el_recd[3] != "Device.Cnts")] - dev_recds = str(el_recds[::-1]) - export_recd += self._export_ic3_event_log_reformat_recds(dev_recds) - - ic3_directory = os.path.abspath(os.path.dirname(__file__)) - export_filename = (f"{ic3_directory.split('custom_components')[0]}/icloud3-event-log.log") - export_filename = export_filename.replace("//", "/") - - export_file = open(export_filename, "w") - export_file.write(export_recd) - export_file.close() - - event_msg = (f"iCloud3 Event Log Exported > File {export_filename}") - self._save_event_halog_info("*", event_msg) - - except Exception as err: - _LOGGER.exception(err) - -#-------------------------------------------------------------------- - def _export_ic3_event_log_reformat_recds(self, recd_str): - recd_str = recd_str.replace("[[", "").replace("]]","").replace("], [", "\n") - recd_str = recd_str.replace("''", "'-'").replace("', '","\t") - recd_str = recd_str.replace("'", "").replace("CRLF", ", ") - recd_str = recd_str.replace("*", "-- sys event --") - - for from_text in self.display_text_as_list: - recd_str = recd_str.replace(from_text, self.display_text_as_list.get(from_text)) - - recd_str += "\n\n" - return recd_str - -######################################################### -# -# WAZE ROUTINES -# -######################################################### - def _get_waze_data(self, devicename, - this_lat, this_long, last_lat, - last_long, zone, last_dist_from_zone_km): - - try: - if not self.distance_method_waze_flag: - return (WAZE_NOT_USED, 0, 0, 0) - elif zone == self.base_zone: - return (WAZE_USED, 0, 0, 0) - elif self.waze_status == WAZE_PAUSED: - return (WAZE_PAUSED, 0, 0, 0) - - try: - log_msg = (f"Request Waze Info, CurrentLoc to {self.base_zone}") - self._log_info_msg(log_msg) - waze_from_zone = self._get_waze_distance(devicename, - this_lat, this_long, - self.base_zone_lat, self.base_zone_long) - - waze_status = waze_from_zone[0] - if waze_status == WAZE_NO_DATA: - event_msg = (f"Waze Route Failure > No Response from Waze Servers, " - f"Calc distance will be used") - self._save_event_halog_info(devicename, event_msg) - - return (WAZE_NO_DATA, 0, 0, 0) - - log_msg = (f"Request Waze Info, CurrentLoc to LastLoc") - self._log_info_msg(log_msg) - waze_from_last_poll = self._get_waze_distance(devicename, - last_lat, last_long, this_lat, this_long) - - except Exception as err: - _LOGGER.exception(err) - - if err == "Name 'WazeRouteCalculator' is not defined": - self.distance_method_waze_flag = False - return (WAZE_NOT_USED, 0, 0, 0) - - return (WAZE_NO_DATA, 0, 0, 0) - - try: - waze_dist_from_zone_km = self._round_to_zero(waze_from_zone[1]) - waze_time_from_zone = self._round_to_zero(waze_from_zone[2]) - waze_dist_last_poll = self._round_to_zero(waze_from_last_poll[1]) - - if waze_dist_from_zone_km == 0: - waze_time_from_zone = 0 - else: - waze_time_from_zone = self._round_to_zero(waze_from_zone[2]) - - if ((waze_dist_from_zone_km > self.waze_max_distance) - or (waze_dist_from_zone_km < self.waze_min_distance)): - waze_status = WAZE_OUT_OF_RANGE - - except Exception as err: - log_msg = (f"►INTERNAL ERROR (ProcWazeData)-{err})") - self._log_error_msg(log_msg) - - waze_time_msg = self._format_waze_time_msg(waze_time_from_zone) - event_msg = (f"Waze Route Info: {self.zone_to_display.get(self.base_zone)} > " - f"Dist-{waze_dist_from_zone_km}km, " - f"TravTime-{waze_time_msg}, " - f"DistMovedSinceLastUpdate-{waze_dist_last_poll}km") - self._save_event(devicename, event_msg) - - log_msg = (f"WAZE DISTANCES CALCULATED>, " - f"Status-{waze_status}, DistFromHome-{waze_dist_from_zone_km}, " - f"TimeFromHome-{waze_time_from_zone}, " - f"DistLastPoll-{waze_dist_last_poll}, " - f"WazeFromHome-{waze_from_zone}, " - f"WazeFromLastPoll-{waze_from_last_poll}") - self._log_debug_interval_msg(devicename, log_msg) - - return (waze_status, waze_dist_from_zone_km, waze_time_from_zone, - waze_dist_last_poll) - - except Exception as err: - self._set_waze_not_available_error(err) - - return (WAZE_NO_DATA, 0, 0, 0) - -#-------------------------------------------------------------------- - def _get_waze_distance(self, devicename, from_lat, from_long, to_lat, - to_long): - """ - Example output: - Time 72.42 minutes, distance 121.33 km. - (72.41666666666667, 121.325) - - See https://github.com/home-assistant/home-assistant/blob - /master/homeassistant/components/sensor/waze_travel_time.py - See https://github.com/kovacsbalu/WazeRouteCalculator - """ - - try: - from_loc = f"{from_lat},{from_long}" - to_loc = f"{to_lat},{to_long}" - - retry_cnt = 0 - while retry_cnt < 3: - try: - self.count_waze_locates[devicename] += 1 - waze_call_start_time = time.time() - route = WazeRouteCalculator.WazeRouteCalculator( - from_loc, to_loc, self.waze_region) - - route_time, route_distance = \ - route.calc_route_info(self.waze_realtime) - - self.time_waze_calls[devicename] += (time.time() - waze_call_start_time) - - route_time = round(route_time, 0) - route_distance = round(route_distance, 2) - - return (WAZE_USED, route_distance, route_time) - - except WazeRouteCalculator.WRCError as err: - retry_cnt += 1 - log_msg = (f"Waze Server Error (#{retry_cnt}), Retrying, Type-{err}") - self._log_info_msg(log_msg) - - except Exception as err: - self._set_waze_not_available_error(err) - - return (WAZE_NO_DATA, 0, 0) - -#-------------------------------------------------------------------- - def _set_waze_not_available_error(self, err): - ''' Turn Waze off if connection error ''' - if (instr(err, "www.waze.com") - and instr(err, "HTTPSConnectionPool") - and instr(err, "Max retries exceeded") - and instr(err, "TIMEOUT")): - self.waze_status = WAZE_NOT_USED - event_msg = ("!Waze Server Error > Connection error accessing www.waze.com, " - "Waze is not available, Will use `distance_method: calc`") - self._save_event_halog_error_msg(devicename, event_msg) - else: - log_msg = (f"►INTERNAL ERROR (GetWazeDist-{err})") - self._log_info_msg(log_msg) - -#-------------------------------------------------------------------- - def _get_waze_from_data_history(self, devicename, - curr_dist_from_zone_km, this_lat, this_long): - ''' - Before getting Waze data, look at all other devices to see - if there are any really close. If so, don't call waze but use their - distance & time instead if the data it passes distance and age - tests. - - The other device's distance from home and distance from last - poll might not be the same as this devices current location - but it should be close enough. - - last_waze_data is a list in the following format: - [timestamp, latitudeWhenCalculated, longitudeWhenCalculated, - [distance, time, distMoved]] - - Returns: [ Waze History Data] - ''' - - devicename_zone = self._format_devicename_zone(devicename) - if not self.distance_method_waze_flag: - return None - elif self.waze_status == WAZE_PAUSED: - return None - - #Delete Waze history if entered/exited zone - #v2.2.0rc7 - elif self.trigger.get(devicename) in IOS_TRIGGERS_ENTER_EXIT: - self.waze_distance_history[devicename_zone] = [] - self.waze_history_data_used_flag[devicename_zone] = False - return None - - #Calculate how far the old data can be from the new data before the - #data will be refreshed. - test_distance = curr_dist_from_zone_km * .05 - if test_distance > 5: - test_distance = 5 - - try: - #other_closest_device_data = None - used_data_from_devicename_zone = None - for near_devicename_zone in self.waze_distance_history: - self.waze_history_data_used_flag[devicename_zone] = False - waze_data_other_device = self.waze_distance_history.get(near_devicename_zone) - #Skip if this device doesn't have any Waze data saved or it's for - #another base_zone. - if len(waze_data_other_device) == 0: - continue - elif len(waze_data_other_device[3]) == 0: - continue - elif near_devicename_zone.endswith(':'+self.base_zone) == False: - continue - - waze_data_timestamp = waze_data_other_device[0] - waze_data_latitude = waze_data_other_device[1] - waze_data_longitude = waze_data_other_device[2] - - dist_from_other_waze_data = self._calc_distance_km( - this_lat, this_long, - waze_data_latitude, waze_data_longitude) - - #Find device's waze data closest to my current location - #If close enough, use it regardless of whose it is - if dist_from_other_waze_data < test_distance: - used_data_from_devicename_zone = near_devicename_zone - other_closest_device_data = waze_data_other_device[3] - test_distance = dist_from_other_waze_data - - #Return the waze history data for the other closest device - if used_data_from_devicename_zone is not None: - used_devicename = used_data_from_devicename_zone.split(':')[0] - event_msg = (f"Waze Route History Used: {self.zone_to_display.get(self.base_zone)} > " - f"Dist-{other_closest_device_data[1]}km, " - f"TravTime-{round(other_closest_device_data[2], 0)} min, " - f"UsedInfoFrom-{self._format_fname_devicename(used_devicename)}, " - f"({test_distance}m AwayFromMyLoc)") - self._save_event_halog_info(devicename, event_msg) - - #Return Waze data (Status, distance, time, dist_moved) - self.waze_history_data_used_flag[used_data_from_devicename_zone] = True - self.waze_data_copied_from[devicename_zone] = used_data_from_devicename_zone - return other_closest_device_data - - except Exception as err: - _LOGGER.exception(err) - - return None - -#-------------------------------------------------------------------- - def _format_waze_time_msg(self, waze_time_from_zone): - ''' - Return the message displayed in the waze time field ►► - ''' - - #Display time to the nearest minute if more than 3 min away - if self.waze_status == WAZE_USED: - t = waze_time_from_zone * 60 - r = 0 - if t > 180: - t, r = divmod(t, 60) - t = t + 1 if r > 30 else t - t = t * 60 - - waze_time_msg = self._secs_to_time_str(t) - - else: - waze_time_msg = '' - - return waze_time_msg -#-------------------------------------------------------------------- - def _verify_waze_installation(self): - ''' - Report on Waze Route alculator service availability - ''' - - self._log_info_msg("Verifying Waze Route Service component") - - if (WAZE_IMPORT_SUCCESSFUL and self.distance_method_waze_flag): - self.waze_status = WAZE_USED - else: - self.waze_status = WAZE_NOT_USED - self.distance_method_waze_flag = False - self._log_info_msg("Waze Route Service not available") -######################################################### -# -# MULTIPLE PLATFORM/GROUP ROUTINES -# -######################################################### - def _check_devicename_in_another_thread(self, devicename): - ''' - Cycle through all instances of the ICLOUD3_TRACKED_DEVICES and check - to see if this devicename is also in another the tracked_devices - for group/instance/thread/platform. - If so, return True to reject this devicename and generate an error msg. - - ICLOUD3_TRACKED_DEVICES = { - 'work': ['gary_iphone > gcobb321@gmail.com, gary.png'], - 'group2': ['gary_iphone > gcobb321@gmail.com, gary.png, whse', - 'lillian_iphone > lilliancobb321@gmail.com, lillian.png']} - ''' - try: - for group in ICLOUD3_GROUPS: - if group != self.group and ICLOUD3_GROUPS.index(group) > 0: - tracked_devices = ICLOUD3_TRACKED_DEVICES.get(group) - for tracked_device in tracked_devices: - tracked_devicename = tracked_device.split('>')[0].strip() - if devicename == tracked_devicename: - log_msg = (f"Error: A device can only be tracked in " - f"one platform/group {ICLOUD3_GROUPS}. '{devicename}' was defined multiple " - f"groups and will not be tracked in '{self.group}'.") - self._save_event_halog_error('*', log_msg) - return True - - except Exception as err: - _LOGGER.exception(err) - - return False - -####################################################################### -# -# EXTRACT ICLOUD3 PARAMETERS FROM THE CONFIG_IC3.YAML PARAMETER FILE. -# -# The ic3 parameters are specified in the HA configuration.yaml file and -# processed when HA starts. The 'config_ic3.yaml' file lets you specify -# parameters at HA startup time or when iCloud3 is restarted using the -# Restart-iC3 command on the Event Log screen. When iC3 is restarted, -# the parameters will override those specified at HA startup time. -# -# 1. You can, for example, add new tracked devices without restarting HA. -# 2. You can specify the username, password and tracking method in this -# file but these items are onlyu processed when iC3 initially loads. -# A restart will discard these items -# -# Default file is config/custom_components/icloud3/config-ic3.yaml -# if no '/' on the config_ic3_file_name parameter: -# check the default directory -# if not found, check the /config directory -# -# -####################################################################### - def _check_config_ic3_yaml_parameter_file(self): - - try: - ic3_directory = os.path.abspath(os.path.dirname(__file__)) - self._save_event("*", f"iCloud3 Directory > {ic3_directory}") - - if self.config_ic3_file_name == "": - return - - event_msg = (f"iCloud3 Configuration File > " - f"Specified-{self.config_ic3_file_name}, ") - - #fully qualified name specified ('/' in filename) - if (instr(self.config_ic3_file_name, "/") - and os.path.exists(self.config_ic3_file_name)): - config_filename = self.config_ic3_file_name - - elif os.path.exists(f"/config/{self.config_ic3_file_name}"): - config_filename = (f"/config/{self.config_ic3_file_name}") - - elif os.path.exists(f"{ic3_directory}/{self.config_ic3_file_name}"): - config_filename = (f"{ic3_directory}/{self.config_ic3_file_name}") - - alert_msg = (f"{EVLOG_ALERT}iCloud3 Alert > The `config_ic3.yaml` " - f"configuration file should moved to the `/config` " - f"directory so it is not deleted when HACS updates iCloud3") - self._save_event("*", alert_msg) - - else: - event_msg += "Error-File Not Found" - self._save_event("*", event_msg) - return - - config_filename = config_filename.replace("//", "/") - - event_msg += (f"Found-{config_filename}") - self._save_event("*", event_msg) - - config_ic3_file = open(config_filename) - - except (FileNotFoundError, IOError): - event_msg = (f"iCloud3 Error Opening {config_filename} > File not Found") - self._save_event_halog_error("*", event_msg) - self.info_notification = event_msg - return - - except Exception as err: - _LOGGER.exception(err) - return - - try: - if self.start_icloud3_initial_load_flag: - self.last_config_ic3_items = [] - - #reset any changed items in config_ic3 from the last ic3 reset back to it's default value - for last_config_ic3_item in self.last_config_ic3_items: - self._set_parameter_item(last_config_ic3_item, DEFAULT_CONFIG_VALUES.get(last_config_ic3_item)) - - self.last_config_ic3_items = [] - - parameter_list = [] - parameter_list_name = "" - log_success_msg = "" - log_error_msg = "" - success_msg = "" - error_msg = "" - for config_ic3_recd in config_ic3_file: - parm_recd_flag = True - recd = config_ic3_recd.strip() - if len(recd) < 2 or recd.startswith('#'): - continue - - #Last recd started with a '-' (list item), Add this one to the list being built - if recd.startswith('-'): - parameter_value = recd[1:].strip() - parameter_list.append(parameter_value) - continue - - #Not a list recd but a list exists, update it's parameter value, then process this recd - elif parameter_list != []: - success_msg, error_msg = self._set_parameter_item(parameter_list_name, parameter_list) - log_success_msg += success_msg - log_error_msg += error_msg - parameter_list_name = "" - parameter_list = [] - - #Decode and process the config recd - recd_fields = recd.split(":") - parameter_name = recd_fields[0].strip().lower() - parameter_value = recd_fields[1].replace("'","").strip().lower() - - #Check to see if the parameter is a list parameter. If so start building a list - if parameter_name in [CONF_TRACK_DEVICE, CONF_TRACK_DEVICES, - CONF_CREATE_SENSORS, CONF_EXCLUDE_SENSORS, - CONF_DISPLAY_TEXT_AS]: - parameter_list_name = parameter_name - else: - success_msg, error_msg = self._set_parameter_item(parameter_name, parameter_value) - if success_msg != "": - self.last_config_ic3_items.append(parameter_name) - - log_success_msg += success_msg - log_error_msg += error_msg - - if parameter_list != []: - success_msg, error_msg = self._set_parameter_item(parameter_list_name, parameter_list) - log_success_msg += success_msg - log_error_msg += error_msg - - except Exception as err: - _LOGGER.exception(err) - pass - - config_ic3_file.close() - - if log_error_msg != "": - event_msg = (f"iCloud3 Error decoding '{config_filename}` parameters > " - f"The following parameters can not be handled:CRLF{log_error_msg}") - self._save_event_halog_info("*", event_msg) - - return - -#------------------------------------------------------------------------- - def _set_parameter_item(self, parameter_name, parameter_value): - try: - success_msg = "" - error_msg = "" - #These parameters can not be changed - if parameter_name in [CONF_GROUP, CONF_USERNAME, CONF_PASSWORD, - CONF_TRACKING_METHOD, - CONF_CREATE_SENSORS, CONF_EXCLUDE_SENSORS, - CONF_ENTITY_REGISTRY_FILE, CONF_CONFIG_IC3_FILE_NAME]: - return ("", "") - - - log_msg = (f"{EVLOG_DEBUG}config_ic3 Parameter > {parameter_name}: {parameter_value}") - self._save_event("*", log_msg) - - if parameter_name in [CONF_TRACK_DEVICES, CONF_TRACK_DEVICE]: - self.track_devices = parameter_value - elif parameter_name == CONF_IOSAPP_REQUEST_LOC_MAX_CNT: - self.iosapp_request_loc_max_cnt = int(parameter_value) - elif parameter_name == CONF_UNIT_OF_MEASUREMENT: - self.unit_of_measurement = parameter_value - elif parameter_name == CONF_TIME_FORMAT: - self.time_format = int(parameter_value) - elif parameter_name == CONF_BASE_ZONE: - self.base_zone = parameter_value - elif parameter_name == CONF_INZONE_INTERVAL: - self.inzone_interval_secs = self._time_str_to_secs(parameter_value) - elif parameter_name == CONF_MAX_INTERVAL: - self.max_interval_secs = self._time_str_to_secs(parameter_value) - elif parameter_name == CONF_DISPLAY_ZONE_FNAME: - self.display_zone_fname_flag = (parameter_value == 'true') - elif parameter_name == CONF_CENTER_IN_ZONE: - self.center_in_zone_flag = (parameter_value == 'true') - elif parameter_name == CONF_STATIONARY_STILL_TIME: - self.stationary_still_time_str = parameter_value - elif parameter_name == CONF_STATIONARY_INZONE_INTERVAL: - self.stationary_inzone_interval_str = parameter_value - elif parameter_name == CONF_STATIONARY_ZONE_OFFSET: - self.stationary_zone_offset = parameter_value - elif parameter_name == CONF_TRAVEL_TIME_FACTOR: - self.travel_time_factor = float(parameter_value) - elif parameter_name == CONF_GPS_ACCURACY_THRESHOLD: - self.gps_accuracy_threshold = int(parameter_value) - elif parameter_name == CONF_OLD_LOCATION_THRESHOLD: - self.old_location_threshold = self._time_str_to_secs(parameter_value) - elif parameter_name == CONF_IGNORE_GPS_ACC_INZONE: - self.ignore_gps_accuracy_inzone_flag = (parameter_value == 'true') - self.check_gps_accuracy_inzone_flag = not self.ignore_gps_accuracy_inzone_flag - elif parameter_name == CONF_WAZE_REGION: - self.waze_region = parameter_value - elif parameter_name == CONF_WAZE_MAX_DISTANCE: - self.waze_max_distance = int(parameter_value) - elif parameter_name == CONF_WAZE_MIN_DISTANCE: - self.waze_min_distance = int(parameter_value) - elif parameter_name == CONF_WAZE_REALTIME: - self.waze_realtime = (parameter_value == 'true') - elif parameter_name == CONF_DISTANCE_METHOD: - self.distance_method_waze_flag = (parameter_value == 'waze') - elif parameter_name == CONF_LOG_LEVEL: - self._initialize_debug_control(parameter_value) - elif parameter_name == CONF_EVENT_LOG_CARD_DIRECTORY: - self.event_log_card_directory = parameter_value - elif parameter_name == CONF_DEVICE_STATUS: - self.device_status_online = list(parameter_value.replace(" ","").split(",")) - self.device_status_online.append('') - elif parameter_name == CONF_DISPLAY_TEXT_AS: - self.display_text_as = parameter_value - else: - error_msg = (f"{parameter_name}: {parameter_value}CRLF") - log_msg = (f"Invalid parameter-{parameter_name}: {parameter_value}") - self._log_debug_msg("*", log_msg) - - except Exception as err: - _LOGGER.exception(err) - error_msg = (f"{err}CRLF") - - if error_msg == "": - success_msg = (f"{parameter_name}: {parameter_value}CRLF") - - return (success_msg, error_msg) - -######################################################### -# -# CHECK THE IC3 EVENT LOG VERSION BEING USED -# -# Read the icloud3-event-log-card.js file in the iCloud3 directory and the -# Lovelace Custom Card directory (default=www/custom_cards) and extract -# the current version (Version=x.x.x (mm.dd.yyyy)) comment entry before -# the first 'class' statement. If the version in the ic3 directory is -# newer than the www/custom_cards directory, copy the ic3 version -# to the www/custom_cards directory. -# -# The custom_cards directory can be changed using the event_log_card_directory -# parameter. -# -######################################################### - def _check_ic3_event_log_file_version(self): - try: - ic3_directory = os.path.abspath(os.path.dirname(__file__)) - ic3_evlog_filename = (f"{ic3_directory}/icloud3-event-log-card.js") - if os.path.exists(ic3_evlog_filename) == False: - return - - www_directory = (f"{ic3_evlog_filename.split('custom_components')[0]}" - f"{self.event_log_card_directory}") - www_evlog_filename = (f"{www_directory}/icloud3-event-log-card.js") - www_evlog_file_exists_flag = os.path.exists(www_evlog_filename) - - - except Exception as err: - _LOGGER.exception(err) - - try: - ic3_version, ic3_version_text = self._read_event_log_card_js_file(ic3_evlog_filename) - if www_evlog_file_exists_flag: - www_version, www_version_text = self._read_event_log_card_js_file(www_evlog_filename) - else: - www_version = 0 - www_version_text = UNKNOWN - try: - os.mkdir(www_directory) - except FileExistsError: - pass - except Exception as err: - _LOGGER.exception(err) - pass - - if ic3_version > www_version: - shutil.copy(ic3_evlog_filename, www_evlog_filename) - event_msg = (f"{EVLOG_ALERT}" - f"EventLog Alert > Event Log was updated, " - f"CRLFOldVersion-{www_version_text}, " - f"NewVersion-v{ic3_version_text}, " - f"CRLFCopied-`{ic3_evlog_filename}` to `{www_directory}`" - f"CRLF-----" - f"CRLFThe Event Log Card was updated to v{ic3_version_text}. " - "Refresh your browser and do the following on every tracked " - "devices running the iOS App to load the new version." - "CRLF1. Select HA Sidebar > APP Configuration." - "CRLF2. Scroll to the botton of the General screen." - "CRLF3. Select Reset Frontend Cache, then select Done." - "CRLF4. Display the Event Log, then pull down to refresh the page. " - "You should see the busy spinning wheel as the new version is loaded.") - self._save_event_halog_info("*", event_msg) - self.info_notification = (f"Event Log Card updated to v{ic3_version_text}. " - "See Event Log for more info.") - title = (f"iCloud3 Event Log Card updated to v{ic3_version_text}") - message = ("Refresh the iOS App to load the new version. " - "Select HA Sidebar > APP Configuration. Scroll down. Select Refresh " - "Frontend Cache. Select Done. Pull down to refresh App.") - self.broadcast_msg = { - "title": title, - "message": message, - "data": {"subtitle": "Event Log needs to be refreshed"}} - - else: - event_msg = (f"Event Log Version Check > Current release is being used. " - f"Version-{www_version_text}, {www_directory}") - self._save_event_halog_info("*", event_msg) - - except Exception as err: - _LOGGER.exception(err) - return - -#-------------------------------------- - def _read_event_log_card_js_file(self, evlog_filename): - ''' - Read the records in the the evlog_filename up to the 'class' statement and - extract the version and date. - Return the Version number and the Version text (#.#.#.### (m/d/yyy)) - Return 0, "Unknown" if the Version number was not found - ''' - try: - #Cycle thru the file looking for the Version - evlog_version_text = UNKNOWN - evlog_version_no = 0 - evlog_file = open(evlog_filename) - evlog_version_parts = [0, 0, 0] - - for evlog_recd in evlog_file: - version_pos = evlog_recd.lower().find("version") - if version_pos > 0: - #Make sure it's 'Version=#.#.#.## (m/d/yyyy), get number & date - evlog_recd = evlog_recd.replace("("," (") - version_text = evlog_recd[version_pos:].split("=") - - if len(version_text) == 2: - #Get number portion, then get each number - evlog_version_text = version_text[1].strip() - evlog_version = evlog_version_text.split(" ")[0] - evlog_version_parts = evlog_version.split(".") - break - - #exit if find 'class' recd before 'version' recd - elif instr(evlog_recd, "class"): - break - - evlog_version_parts.append('0') - evlog_version_no = 0 - evlog_version_no += int(evlog_version_parts[0])*100000 - evlog_version_no += int(evlog_version_parts[1])*10000 - evlog_version_no += int(evlog_version_parts[2])*1000 - evlog_version_no += int(evlog_version_parts[3]) - - except FileNotFoundError: - evlog_version_no = 0 - evlog_version_text = UNKNOWN - return (evlog_version_no, evlog_version_text) - - except Exception as err: - _LOGGER.exception(err) - evlog_version_no = HIGH_INTEGER - evlog_version_text = "Error" - - evlog_file.close() - - return (evlog_version_no, evlog_version_text) - -######################################################### -# -# log_, trace_ MESSAGE ROUTINES -# -######################################################### - def _log_info_msg(self, log_msg): - ''' Always add log_msg to HA log ''' - if self.start_icloud3_inprocess_flag and not self.log_level_debug_flag: - self.startup_log_msgs += f"{self.startup_log_msgs_prefix}\n {log_msg}" - self.startup_log_msgs_prefix = "" - else: - _LOGGER.info(log_msg) - -#-------------------------------------- - def _save_event_halog_info(self, devicename, log_msg, log_title=""): - ''' Always display log_msg in Event Log; Always add log_msg to HA log ''' - self._save_event(devicename, log_msg) - - log_msg = str(log_msg).replace("CRLF", ". ") - if devicename != "*": - log_msg = (f"{log_title}{self._format_fname_devtype(devicename)} {log_msg}") - - if self.start_icloud3_inprocess_flag and not self.log_level_debug_flag: - self.startup_log_msgs += f"{self.startup_log_msgs_prefix}\n {log_msg}" - self.startup_log_msgs_prefix = "" - else: - self._log_info_msg(log_msg) - -#-------------------------------------- - def _save_event_halog_debug(self, devicename, log_msg, log_title=""): - ''' Always display log_msg in Event Log; add to HA log only when "log_level: debug" ''' - self._save_event(devicename, f"{log_msg}") - - if devicename != "*": - log_msg = (f"{log_title}{self._format_fname_devtype(devicename)} {log_msg}") - self._log_debug_msg(devicename, log_msg) - -#-------------------------------------- - def _evlog_debug_msg(self, devicename, log_msg, log_title=""): - ''' Only display log_msg in Event Log and HA log when "log_level: eventlog" ''' - self._save_event(devicename, f"{EVLOG_DEBUG}{log_msg}") - - if self.log_level_eventlog_flag: - if devicename != "*": - log_msg = (f"{self._format_fname_devtype(devicename)} {log_msg}") - self._log_debug_msg(devicename, log_msg, log_title) - -#-------------------------------------- - @staticmethod - def _log_warning_msg(log_msg): - _LOGGER.warning(log_msg) - -#-------------------------------------- - @staticmethod - def _log_error_msg(log_msg): - _LOGGER.error(log_msg) - -#-------------------------------------- - def _save_event_halog_error(self, devicename, log_msg): - ''' Always display log_msg in Event Log; always add to HA log ''' - if instr(log_msg, "iCloud3 Error"): - self.info_notification = ICLOUD3_ERROR_MSG - for td_devicename in self.tracked_devices: - self._display_info_status_msg(td_devicename, ICLOUD3_ERROR_MSG) - - self._save_event(devicename, log_msg) - log_msg = (f"{self._format_fname_devtype(devicename)} {log_msg}") - log_msg = str(log_msg).replace("CRLF", ". ") - - if self.start_icloud3_inprocess_flag and not self.log_level_debug_flag: - self.startup_log_msgs += f"{self.startup_log_msgs_prefix}\n {log_msg}" - self.startup_log_msgs_prefix = "" - - self._log_error_msg(log_msg) - -#-------------------------------------- - def _log_debug_msg(self, devicename, log_msg, log_title=""): - ''' Always add log_msg to HA log only when "log_level: debug" ''' - - log_msg = str(log_msg).replace("CRLF", ". ") - if self.log_level_debug_flag: - _LOGGER.info(f"◆{devicename}◆ {log_title}{log_msg}") - else: - _LOGGER.debug(f"◆{devicename}◆ {log_title}{log_msg}") - -#-------------------------------------- - def _log_debug_interval_msg(self, devicename, log_msg): - ''' Add log_msg to HA log only when "log_level: intervalcalc" ''' - if self.log_level_intervalcalc_flag: - _LOGGER.debug(f"◆{devicename}◆ {log_msg}") - - if self.log_level_eventlog_flag: - self._save_event(devicename, (f"{EVLOG_DEBUG}{str(log_msg).replace('►','')}")) - -#-------------------------------------- - def _log_level_debug_rawdata(self, title, data, log_rawdata=False): - ''' Add log_msg to HA log only when "log_level: rawdata" ''' - display_title = title.replace(" ",".").upper() - if self.log_level_debug_rawdata_flag or log_rawdata: - log_msg = (f"▼---------▼--{display_title}--▼---------▼") - self._log_debug_msg("*", log_msg) - log_msg = (f"{data}") - self._log_debug_msg("*", log_msg) - log_msg = (f"▲---------▲--{display_title}--▲---------▲") - self._log_debug_msg("*", log_msg) -#-------------------------------------- - def _log_debug_msg2(self, log_msg): - _LOGGER.debug(log_msg) - -#-------------------------------------- - def _internal_error_msg(self, function_name, err_text: str='', - section_name: str=''): - log_msg = (f"►INTERNAL ERROR-RETRYING ({function_name}:{section_name}-{err_text})") - _LOGGER.error(log_msg) - self._save_event("*", log_msg) - - attrs = {} - attrs[ATTR_INTERVAL] = '0 sec' - attrs[ATTR_NEXT_UPDATE_TIME] = HHMMSS_ZERO - attrs[ATTR_INFO] = log_msg - - return attrs - -######################################################### -# -# TIME & DISTANCE UTILITY ROUTINES -# -######################################################### - @staticmethod - def _time_now_secs(): - ''' Return the epoch seconds in utc time ''' - - return int(time.time()) - -#-------------------------------------------------------------------- - def _secs_to_time(self, e_seconds): - """ Convert seconds to hh:mm:ss """ - - if e_seconds == 0 or e_seconds == HIGH_INTEGER: - return HHMMSS_ZERO - else: - t_struct = time.localtime(e_seconds + self.e_seconds_local_offset_secs) - return time.strftime(self.um_time_strfmt, t_struct).lstrip('0') - -#-------------------------------------------------------------------- - @staticmethod - def _secs_to_time_str(secs): - """ Create the time string from seconds """ - - try: - if secs >= 86400: - time_str = self._secs_to_dhms_str(secs) - elif secs < 60: - time_str = str(round(secs, 0)) + " sec" - elif secs < 3600: - time_str = str(round(secs/60, 1)) + " min" - elif secs == 3600: - time_str = "1 hr" - else: - time_str = str(round(secs/3600, 1)) + " hrs" - - # xx.0 min/hr --> xx min/hr - time_str = time_str.replace('.0 ', ' ') - - except: - time_str = "" - - return time_str -#-------------------------------------------------------------------- - @staticmethod - def _secs_to_dhms_str(secs): - """ Create the time 0d0h0m0s time string from seconds """ - - try: - secs_dhms = float(secs) - dhms_str = "" - if (secs >= 86400): dhms_str += f"{secs_dhms // 86400}d" - secs_dhms = secs_dhms % 86400 - if (secs >= 3600): dhms_str += f"{secs_dhms // 3600}h" - secs_dhms %= 3600 - if (secs >= 60): dhms_str += f"{secs_dhms // 60}m" - secs_dhms %= 60 - dhms_str += f"{secs_dhms}s" - - dhms_str = dhms_str.replace('.0', '') - - except: - dhms_srt = "" - - return dhms_str - -#-------------------------------------------------------------------- - def _secs_since(self, e_secs) -> int: - return round(time.time() - e_secs) -#-------------------------------------------------------------------- - def _secs_to(self, e_secs) -> int: - return round(e_secs - time.time()) -#-------------------------------------------------------------------- - @staticmethod - def _time_to_secs(hhmmss): - """ Convert hh:mm:ss into seconds """ - try: - hh_mm_ss = hhmmss.split(":") - secs = int(hh_mm_ss[0]) * 3600 + int(hh_mm_ss[1]) * 60 + int(hh_mm_ss[2]) - - except: - secs = 0 - - return secs - -#-------------------------------------------------------------------- - def _time_to_12hrtime(self, hhmmss, ampm=False): - - try: - #if self.unit_of_measurement == 'mi' and time_24h is False: - if self.time_format == 12: - hh_mm_ss = hhmmss.split(':') - hhmmss_hh = int(hh_mm_ss[0]) - - ap = 'a' - if hhmmss_hh > 12: - hhmmss_hh -= 12 - ap = 'p' - elif hhmmss_hh == 12: - ap = 'p' - elif hhmmss_hh == 0: - hhmmss_hh = 12 - - ap = '' if ampm == False else ap - - hhmmss = f"{hhmmss_hh}:{hh_mm_ss[1]}:{hh_mm_ss[2]}{ap}" - - except: - pass - - return hhmmss -#-------------------------------------------------------------------- - @staticmethod - def _time_str_to_secs(time_str='30 min') -> int: - """ - Calculate the seconds in the time string. - The time attribute is in the form of '15 sec' ', - '2 min', '60 min', etc - """ - - if time_str == "": - return 0 - - s1 = str(time_str).replace('_', ' ') + " min" - time_part = float((s1.split(" ")[0])) - text_part = s1.split(" ")[1] - - if text_part == 'sec': - secs = time_part - elif text_part == 'min': - secs = time_part * 60 - elif text_part == 'hrs': - secs = time_part * 3600 - elif text_part in ('hr', 'hrs'): - secs = time_part * 3600 - else: - secs = 1200 #default to 20 minutes - - return secs - -#-------------------------------------------------------------------- - def _timestamp_to_time_utcsecs(self, utc_timestamp) -> int: - """ - Convert iCloud timeStamp into the local time zone and - return hh:mm:ss - """ - - ts_local = int(float(utc_timestamp)/1000) + self.time_zone_offset_seconds - hhmmss = dt_util.utc_from_timestamp(ts_local).strftime(self.um_time_strfmt) - if hhmmss[0] == "0": - hhmmss = hhmmss[1:] - - return hhmmss - -#-------------------------------------------------------------------- - def _timestamp_to_time(self, timestamp): - """ - Extract the time from the device timeStamp attribute - updated by the IOS app. - Format is --'timestamp': '2019-02-02 12:12:38.358-0500' - """ - - try: - if timestamp == TIMESTAMP_ZERO: - return HHMMSS_ZERO - - yyyymmdd_hhmmss = (f"{timestamp}.").split(' ')[1] - hhmmss = yyyymmdd_hhmmss.split('.')[0] - - except: - hhmmss = HHMMSS_ZERO - - return hhmmss - -#-------------------------------------------------------------------- - def _timestamp_to_secs_utc(self, utc_timestamp) -> int: - """ - Convert timeStamp seconds (1567604461006) into the local time zone and - return time in seconds. - """ - - try: - ts_local = int(float(utc_timestamp)/1000) + self.time_zone_offset_seconds - - hhmmss = dt_util.utc_from_timestamp(ts_local).strftime('%X') - if hhmmss[0] == "0": - hhmmss = hhmmss[1:] - - except: - hhmmss = 0 - - return self._time_to_secs(hhmmss) - -#-------------------------------------------------------------------- - @staticmethod - def _secs_to_timestamp(secs): - """ - Convert seconds to timestamp - Return timestamp (2020-05-19 09:12:30) - """ - try: - time_struct = time.localtime(secs) - timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time_struct) - - except: - timestamp = "0000-00-00 00:00:00" - - return timestamp - -#-------------------------------------------------------------------- - def _timestamp_to_secs(self, timestamp, utc_local = LOCAL_TIME) -> int: - """ - Convert the timestamp from the device timestamp attribute - updated by the IOS app. - Format is --'timestamp': '2019-02-02T12:12:38.358-0500' - Return epoch seconds - """ - try: - if timestamp is None: - secs = 0 - elif timestamp == '' or timestamp[0:19] == TIMESTAMP_ZERO: - secs = 0 - else: - timestamp = timestamp.replace("T", " ")[0:19] - secs = time.mktime(time.strptime(timestamp, "%Y-%m-%d %H:%M:%S")) - if utc_local is UTC_TIME: - secs += self.time_zone_offset_seconds - - except: - secs = 0 - - return secs -#-------------------------------------------------------------------- - def _calculate_time_zone_offset(self): - """ - Calculate time zone offset seconds - """ - try: - local_zone_offset = dt_util.now().strftime('%z') - local_zone_offset_secs = int(local_zone_offset[1:3])*3600 + \ - int(local_zone_offset[3:])*60 - if local_zone_offset[:1] == "-": - local_zone_offset_secs = -1*local_zone_offset_secs - - t_now = int(time.time()) - t_hhmmss = dt_util.now().strftime('%H%M%S') - l_now = time.localtime(t_now) - l_hhmmss = time.strftime('%H%M%S', l_now) - g_now = time.gmtime(t_now) - g_hhmmss = time.strftime('%H%M%S', g_now) - - if (l_hhmmss == g_hhmmss): - self.e_seconds_local_offset_secs = local_zone_offset_secs - - log_msg = (f"Time Zone Offset, Local Zone-{local_zone_offset} hrs, " - f"{local_zone_offset_secs} secs") - self._log_debug_msg('*', log_msg) - - except Exception as err: - _LOGGER.exception(err) - x = self._internal_error_msg(fct_name, err, 'CalcTZOffset') - local_zone_offset_secs = 0 - - return local_zone_offset_secs - -#-------------------------------------------------------------------- - def _km_to_mi(self, arg_distance): - """ - convert km to miles - """ - - try: - mi = arg_distance * self.um_km_mi_factor - - if mi == 0: - mi = 0 - elif mi <= 10: - mi = round(mi, 2) - elif mi <= 100: - mi = round(mi, 1) - else: - mi = round(mi) - - except: - mi = 0 - return mi - - def _mi_to_km(self, arg_distance): - return round(float(arg_distance) / self.um_km_mi_factor, 2) - -#-------------------------------------------------------------------- - @staticmethod - def _format_dist(dist): - return f"{dist}km" if dist > .5 else f"{round(dist*1000)}m" - - @staticmethod - def _format_dist_m(dist): - return f"{round(dist/1000, 2)}km" if dist > 500 else f"{round(dist)}m" -#-------------------------------------------------------------------- - @staticmethod - def _calc_distance_km(from_lat, from_long, to_lat, to_long): - if from_lat is None or from_long is None or to_lat is None or to_long is None: - return 0 - - d = distance(from_lat, from_long, to_lat, to_long) / 1000 - if d < .05: d = 0 - return round(d, 2) - - @staticmethod - def _calc_distance_m(from_lat, from_long, to_lat, to_long): - if from_lat is None or from_long is None or to_lat is None or to_long is None: - return 0 - - d = distance(from_lat, from_long, to_lat, to_long) - - return round(d, 2) - -#-------------------------------------------------------------------- - @staticmethod - def _round_to_zero(arg_distance): - if abs(arg_distance) < .05: arg_distance = 0 - return round(arg_distance, 2) - -#-------------------------------------------------------------------- - def _add_comma_to_str(self, text): - """ Add a comma to info if it is not an empty string """ - if text: - return f"{text}, " - return '' - -#-------------------------------------------------------------------- - @staticmethod - def _isnumber(string): - - try: - test_number = float(string) - - return True - except: - return False - -#-------------------------------------------------------------------- - def _extract_name_device_type(self, devicename): - '''Extract the name and device type from the devicename''' - - try: - fname = devicename.title() - device_type = '' - - for ic3dev_type in APPLE_DEVICE_TYPES: - if instr(devicename, ic3dev_type): - fnamew = devicename.replace(ic3dev_type, "", 99) - fname = fnamew.replace("_", "", 99) - fname = fname.replace("-", "", 99).title() - device_type = ic3dev_type - return (fname, ic3dev_type) - - except Exception as err: - _LOGGER.exception(err) - - return (fname, "iCloud") - -#-------------------------------------------------------------------- - def _device_online(self, devicename): - ''' Returns True/False if the device is online based on the device_status ''' - if self.TRK_METHOD_IOSAPP: - return True - else: - return (self.device_status.get(devicename) in self.device_status_online) #["online", "pending", ""]) - -######################################################### -# -# These functions handle notification and entry of the -# iCloud Account trusted device verification code. -# -######################################################### - def _icloud_show_trusted_device_request_form(self): - """We need a trusted device.""" - - if self._icloud_valid_api() == False: - return - - self._service_handler_icloud_update(self.group, arg_command='pause') - configurator = self.hass.components.configurator - - event_msg = (f"{EVLOG_ALERT}iCloud Alert > Apple/iCloud Account Verification Required > " - f"Open HA Notifications window to select Trusted Device and to " - f"enter the 6-digit Verification Code.") - self._save_event_halog_info('*', event_msg) - self.info_notification = "Apple/iCloud Account Verification Required, See Event Log." - - device_list = '' - self.trusted_device_list = {} - self.trusted_devices = self.api.trusted_devices - device_list += "ID      Phone Number\n" \ - "––    ––––––––––––\n" - - for trusted_device in self.trusted_devices: - phone_number = trusted_device.get('phoneNumber') - device_list += (f"{trusted_device['deviceId']}      " - f"  {phone_number}\n") - event_msg += (f"#{trusted_device['deviceId']}-{phone_number}, ") - - self.trusted_device_list[trusted_device['deviceId']] = trusted_device - - log_msg = (f"VALID TRUSTED IDs={self.trusted_device_list}") - self._log_debug_msg('*', log_msg) - - description_msg = (f"Account {self.username} needs to be verified. Enter the " - f"ID for the Trusted Device that will receive the " - f"verification code via a text message.\n\n\n{device_list}") - - self.hass_configurator_request_id[self.username] = configurator.request_config( - (f"Select Trusted Device"), - self._icloud_handle_trusted_device_entry, - description = (description_msg), - entity_picture = "/static/images/config_icloud.png", - submit_caption = 'Confirm', - fields = [{'id': 'trusted_device', \ - CONF_NAME: 'Trusted Device ID'}] - ) - -#-------------------------------------------------------------------- - def _icloud_handle_trusted_device_entry(self, callback_data): - """ - Take the device number enterd above, get the api.device info and - have pyiCloud validate the device. - - callbackData-{'trusted_device': '1'} - apiDevices=[{'deviceType': 'SMS', 'areaCode': '', 'phoneNumber': - '********65', 'deviceId': '1'}, - {'deviceType': 'SMS', 'areaCode': '', 'phoneNumber': - '********66', 'deviceId': '2'}] - """ - - if self._icloud_valid_api() == False: - return - - device_id_entered = str(callback_data.get('trusted_device')) - - if device_id_entered in self.trusted_device_list: - self.trusted_device = self.trusted_device_list.get(device_id_entered) - phone_number = self.trusted_device.get('phoneNumber') - event_msg = (f"Verify Trusted Device Id > Device Id Entered-{device_id_entered}, " - f"Phone Number-{phone_number}") - self._save_event("*", event_msg) - - if self.username not in self.hass_configurator_request_id: - request_id = self.hass_configurator_request_id.pop(self.username) - configurator = self.hass.components.configurator - configurator.request_done(request_id) - else: - #By returning, the Device ID Entry screen will remain open for a valid entry - self.trusted_device = None - event_msg = (f"Verify Trusted Device Id > Invalid Device Id Entered-{device_id_entered}") - self._save_event("*", event_msg) - return - - text_msg_send_success = self.api.send_verification_code(self.trusted_device) - if text_msg_send_success: - # Get the verification code, Trigger the next step immediately - self._icloud_show_verification_code_entry_form() - else: - #trusted_device = self.trusted_device_list[trusted_device['deviceId']] - event_msg = (f"iCloud3 Error > Failed to send text verification code to Phone ID #{device_id_entered}. " - f"Restart HA to reset everything and try again later.") - self._save_event_halog_error("*", event_msg) - - self.trusted_device = None - -#------------------------------------------------------ - def _icloud_show_verification_code_entry_form(self, invalid_code_msg=""): - """Return the verification code.""" - - self._service_handler_icloud_update(self.group, arg_command='pause') - - configurator = self.hass.components.configurator - if self.username in self.hass_configurator_request_id: - request_id = self.hass_configurator_request_id.pop(self.username) - configurator = self.hass.components.configurator - configurator.request_done(request_id) - - self.hass_configurator_request_id[self.username] = configurator.request_config( - ("Enter Apple Verification Code"), - self._icloud_handle_verification_code_entry, - description = (f"{invalid_code_msg}Enter the Verification Code sent to the Trusted Device"), - entity_picture = "/static/images/config_icloud.png", - submit_caption = 'Confirm', - fields = [{'id': 'code', CONF_NAME: 'Verification Code'}] - ) - -#-------------------------------------------------------------------- - def _icloud_handle_verification_code_entry(self, callback_data): - """Handle the chosen trusted device.""" - - if self._icloud_valid_api() == False: - return - - from .pyicloud_ic3 import PyiCloudException - self.verification_code = callback_data.get('code') - event_msg = (f"Submit Verification Code > Code-{callback_data}") - self._save_event("*", event_msg) - - try: - valid_code = self.api.validate_verification_code(self.trusted_device, self.verification_code) - if valid_code == False: - invalid_code_text = (f"The code {self.verification_code} in incorrect.\n\n") - self._icloud_show_verification_code_entry_form(invalid_code_msg=invalid_code_text) - return - - event_msg = "Apple/iCloud Account Verification Successful" - self._save_event("*", event_msg) - - except PyiCloudException as error: - - # Reset to the initial 2FA state to allow the user to retry - event_msg = (f"Failed to verify account > Error-{error}") - self._save_event_halog_error("*", event_msg) - - # Trigger the next step immediately - self._icloud_show_trusted_device_request_form() - if valid_code == False: - invalid_code_text = (f"The Verification Code {self.verification_code} in incorrect.\n\n") - - self._icloud_show_verification_code_entry_form(invalid_code_msg=invalid_code_text) - return - if self.username in self.hass_configurator_request_id: - request_id = self.hass_configurator_request_id.pop(self.username) - configurator = self.hass.components.configurator - configurator.request_done(request_id) - - self._setup_tracking_method(self.tracking_method_config) - event_msg = (f"{EVLOG_ALERT}iCloud Alert > iCloud Account Verification completed, " - f"{self.trk_method_short_name} ({self.tracking_method_config}) will be used.") - self._save_event("*", event_msg) - self._start_icloud3() - #self._service_handler_icloud_update(self.group, arg_command='resume') - -#-------------------------------------------------------------------- - def _icloud_valid_api(self): - ''' - Make sure the pyicloud_ic3 api is valid - ''' - - if self.api == None: - event_msg = (f"{EVLOG_ERROR}iCloud3 Error > There was an error logging into the " - f"Apple/iCloud Account when iCloud3 was started. Verification can not " - f"be completed. Review the iCloud3 Event Log for more information.") - self._save_event_halog_error('*', event_msg) - return False - return True - -######################################################### -# -# ICLOUD ROUTINES -# -######################################################### - def _service_handler_lost_iphone(self, group, devicename): - """Call the lost iPhone function if the device is found.""" - - lost_message = ("This phone has been identified as lost. " - "Please contact the owner with it's location.") - message = {"title": "Lost Phone Notification", - "message": lost_message} - self._send_message_to_device(devicename, message) - -#-------------------------------------------------------------------- - def _service_handler_icloud_update(self, group, arg_devicename=None, - arg_command=None): - """ - Authenticate against iCloud and scan for devices. - - - Commands: - - waze reset range = reset the min-max rnge to defaults (1-1000) - - waze toggle = toggle waze on or off - - pause = stop polling for the devicename or all devices - - resume = resume polling devicename or all devices, reset - the interval override to normal interval - calculations - - pause-resume = same as above but toggles between pause and resume - - zone xxxx = updates the devie state to xxxx and updates all - of the iloud3 attributes. This does the see - service call and then an update. - - reset = reset everything and rescans all of the devices - - debug interval = displays the interval formula being used - - debug gps = simulates bad gps accuracy - - debug old = simulates that the location informaiton is old - - info xxx = the same as 'debug' - - location = request location update from ios app - """ - - #If several iCloud groups are used, this will be called for each - #one. Exit if this instance of iCloud is not the one handling this - #device. But if devicename = 'reset', it is an event_log service cmd. - log_msg = (f"iCLOUD3 COMMAND, Device: `{arg_devicename}`, Command: `{arg_command}`") - self._log_debug_msg("*", log_msg) - - self._evlog_debug_msg(arg_devicename, (f"Service Call Command Received > `{arg_command}`")) - - arg_command = (f"{arg_command} ") - arg_command_cmd = arg_command.split(' ')[0].lower() - arg_command_parm = arg_command.split(' ')[1] #original value - arg_command_parmlow = arg_command_parm.lower() - log_level_msg = "" - msg_devicename = arg_devicename if arg_devicename else "All" - log_msg = (f"iCloud3 Command Processed > Device-{msg_devicename}, Command-{arg_command}") - - #System level commands - if arg_command_cmd == 'restart': - self._start_icloud3() - return - - if self.tracked_devices == []: - self._start_icloud3() - elif self.start_icloud3_inprocess_flag is False: - self.start_icloud3_request_flag = True - self._save_event_halog_info("*", log_msg) - return - - elif arg_command_cmd == 'export_event_log': - self._save_event("*", log_msg) - self._export_ic3_event_log() - self._update_sensor_ic3_event_log(arg_devicename) - return - - elif arg_command_cmd == 'refresh_event_log': - self.last_iosapp_msg[arg_devicename] = "" - self._update_sensor_ic3_event_log(arg_devicename) - return - - elif arg_command_cmd == 'startuplog': - self._update_sensor_ic3_event_log("*") - return - - elif arg_command_cmd == "counts": - for devicename in self.count_update_iosapp: - self._display_usage_counts(devicename, force_display=True) - return - - elif arg_command_cmd == 'trusted_device': - self._icloud_show_trusted_device_request_form() - return - - elif arg_command_cmd == 'event_log': - error_msg = ("Error > Event Log v1.0 is being used. You may need to clear your " - "browser cache and then refresh the Event Log page in your browser several times. " - "The latest Event Log version has [Refresh] [Actions] buttons at the top of the screen. " - "You may also need to clear the iOS App cache on each device. Select " - "HA Sidebar>App Configuration, then scroll down, select Reset Frontend Cache and " - "refresh your device by swiping down from the top of the screen.") - self._save_event("*", error_msg) - - self.last_iosapp_msg[arg_devicename] = "" - self._update_sensor_ic3_event_log(arg_devicename) - return - - #command preprocessor, reformat specific commands - elif instr(arg_command_cmd, 'log_level'): - if instr(arg_command_parm, 'debug'): - self.log_level_debug_flag = (not self.log_level_debug_flag) - - if instr(arg_command_parm, 'rawdata'): - self.log_level_debug_rawdata_flag = (not self.log_level_debug_rawdata_flag) - if self.log_level_debug_rawdata_flag: self.log_level_debug_flag = True - - if instr(arg_command_parm, 'intervalcalc'): - self.log_level_intervalcalc_flag = (not self.log_level_intervalcalc_flag) - - if instr(arg_command_parm, 'eventlog'): - self.log_level_eventlog_flag = (not self.log_level_eventlog_flag) - - event_msg = "" - if self.log_level_eventlog_flag: event_msg += "Event Log Details: On, " - if self.log_level_debug_flag: event_msg += "Debug: On, " - if self.log_level_debug_rawdata_flag: event_msg += "+Rawdata: On, " - if self.log_level_intervalcalc_flag: event_msg += "+IntervalCalc: On, " - event_msg = "Logging: Off" if event_msg == "" else event_msg - event_msg = (f"Log Level State > {event_msg}") - self._save_event_halog_debug("*", event_msg) - - self._update_sensor_ic3_event_log(arg_devicename) - - return - - self._save_event_halog_info("*", log_msg) - - #Location level commands - if arg_command_cmd == 'waze': - if self.waze_status == WAZE_NOT_USED: - arg_command_cmd = '' - return - elif arg_command_parmlow == 'reset_range': - self.waze_min_distance = 0 - self.waze_max_distance = HIGH_INTEGER - self.waze_manual_pause_flag = False - self.waze_status = WAZE_USED - elif arg_command_parmlow == 'toggle': - if self.waze_status == WAZE_PAUSED: - self.waze_manual_pause_flag = False - self.waze_status = WAZE_USED - else: - self.waze_manual_pause_flag = True - self.waze_status = WAZE_PAUSED - elif arg_command_parmlow == 'pause': - self.waze_manual_pause_flag = False - self.waze_status = WAZE_USED - elif arg_command_parmlow != 'pause': - self.waze_manual_pause_flag = True - self.waze_status = WAZE_PAUSED - - elif arg_command_cmd == 'zone': #parmeter is the new zone - #if HOME in arg_command_parmlow: #home/not_home is lower case - if self.base_zone in arg_command_parmlow: #home/not_home is lower case - arg_command_parm = arg_command_parmlow - - kwargs = {} - attrs = {} - - self._wait_if_update_in_process(arg_devicename) - self.override_interval_seconds[arg_devicename] = 0 - self.update_in_process_flag = False - self._initialize_next_update_time(arg_devicename) - - self._update_device_icloud('Command', arg_devicename) - - return - - #Device level commands - device_time_adj = 0 - for devicename in self.tracked_devices: - if arg_devicename and devicename != arg_devicename: - continue - - device_time_adj += 3 - devicename_zone = self._format_devicename_zone(devicename, HOME) - - now_secs_str = dt_util.now().strftime('%X') - now_seconds = self._time_to_secs(now_secs_str) - x, update_in_secs = divmod(now_seconds, 15) - update_in_secs = 15 - update_in_secs + device_time_adj - - attrs = {} - - #command processor, execute the entered command - info_msg = None - if arg_command_cmd == 'pause': - cmd_type = CMD_PAUSE - self.next_update_secs[devicename_zone] = HIGH_INTEGER - self.next_update_time[devicename_zone] = PAUSED - self._display_info_status_msg(devicename, PAUSED_CAPS) - - elif arg_command_cmd == 'resume': - cmd_type = CMD_RESUME - self.next_update_time[devicename_zone] = HHMMSS_ZERO - self.next_update_secs[devicename_zone] = 0 - self.override_interval_seconds[devicename] = 0 - self._display_info_status_msg(devicename, 'RESUMING') - self._update_device_icloud('Resuming', devicename) - - elif arg_command_cmd == 'waze': - cmd_type = CMD_WAZE - if self.waze_status == WAZE_USED: - self.next_update_time[devicename_zone] = HHMMSS_ZERO - self.next_update_secs[devicename_zone] = 0 - attrs[ATTR_NEXT_UPDATE_TIME] = HHMMSS_ZERO - attrs[ATTR_WAZE_DISTANCE] = 'Resuming' - self.override_interval_seconds[devicename] = 0 - self._update_device_sensors(devicename, attrs) - attrs = {} - - self._update_device_icloud('Resuming', devicename) - else: - attrs[ATTR_WAZE_DISTANCE] = PAUSED - attrs[ATTR_WAZE_TIME] = '' - - elif arg_command_cmd == 'location': - cmd_type = CMD_LOCATION - self._display_info_status_msg(devicename, 'locating') - if self.iosapp_monitor_dev_trk_flag.get(devicename): - self._iosapp_request_loc_update(devicename) - else: - self.next_update_time[devicename_zone] = HHMMSS_ZERO - self.next_update_secs[devicename_zone] = 0 - self.override_interval_seconds[devicename] = 0 - self._update_device_icloud('Locating', devicename) - self._update_sensor_ic3_event_log(devicename) - - else: - cmd_type = CMD_ERROR - info_msg = (f"INVALID COMMAND > {arg_command_cmd}") - self._display_info_status_msg(devicename, info_msg) - - if attrs: - self._update_device_sensors(devicename, attrs) - - #end for devicename in devs loop - -#-------------------------------------------------------------------- - def _service_handler_icloud_setinterval(self, group, arg_interval=None, - arg_devicename=None): - - """ - Set the interval or process the action command of the given devices. - 'interval' has the following options: - - 15 = 15 minutes - - 15 min = 15 minutes - - 15 sec = 15 seconds - - 5 hrs = 5 hours - - Pause = Pause polling for all devices - (or specific device if devicename - is specified) - - Resume = Resume polling for all devices - (or specific device if devicename - is specified) - - Waze = Toggle Waze on/off - """ - #If several iCloud groups are used, this will be called for each - #one. Exit if this instance of iCloud is not the one handling this - #device. - - if arg_devicename and self.TRK_METHOD_IOSAPP: - if self.iosapp_request_loc_cnt.get(arg_devicename) > self.iosapp_request_loc_max_cnt: - event_msg = (f"Can not Set Interval, location request cnt " - f"exceeded ({self.iosapp_request_location_cnt.get(arg_devicename)} " - f"of {self.iosapp_request_loc_max_cnt})") - self._save_event(arg_devicename, event_msg) - return - - if arg_interval is None: - if arg_devicename is not None: - self._save_event(arg_devicename, "Set Interval Command Error, " - "no new interval specified") - return - - cmd_type = CMD_INTERVAL - new_interval = arg_interval.lower().replace('_', ' ') - -# loop through all devices being tracked and -# update the attributes. Set various flags if pausing or resuming -# that will be processed by the next poll in '_polling_loop_15_sec_icloud' - device_time_adj = 0 - for devicename in self.tracked_devices: - if arg_devicename and devicename != arg_devicename: - continue - - device_time_adj += 3 - devicename_zone = self._format_devicename_zone(devicename, HOME) - - self._wait_if_update_in_process() - - log_msg = (f"SET INTERVAL COMMAND Start {devicename}, " - f"ArgDevname-{arg_devicename}, ArgInterval-{arg_interval}, " - f"New Interval-{new_interval}") - self._log_debug_msg(devicename, log_msg) - self._save_event(devicename, - (f"Set Interval Command handled, New interval {arg_interval}")) - - self.next_update_time[devicename_zone] = HHMMSS_ZERO - self.next_update_secs[devicename_zone] = 0 - self.interval_str[devicename_zone] = new_interval - self.override_interval_seconds[devicename] = self._time_str_to_secs(new_interval) - - now_seconds = self._time_to_secs(dt_util.now().strftime('%X')) - x, update_in_secs = divmod(now_seconds, 15) - time_suffix = 15 - update_in_secs + device_time_adj - - info_msg = 'Updating' - self._display_info_status_msg(devicename, info_msg) - - log_msg = (f"SET INTERVAL COMMAND END {devicename}") - self._log_debug_msg(devicename, log_msg) - -#-------------------------------------------------------------------- diff --git a/development area - v2.2.1/iCloud3 v2.2.1f.zip b/development area - v2.2.1/iCloud3 v2.2.1f.zip deleted file mode 100644 index 4a227c5..0000000 Binary files a/development area - v2.2.1/iCloud3 v2.2.1f.zip and /dev/null differ diff --git a/development area - v2.2.1/icloud3-event-log-card.js b/development area - v2.2.1/icloud3-event-log-card.js deleted file mode 100644 index 9068111..0000000 --- a/development area - v2.2.1/icloud3-event-log-card.js +++ /dev/null @@ -1,1544 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// ICLOUD3 EVENT LOG CARD -// -// This custom card displays Event Log records generated by the iCloud3 -// Custom Component. The event log records and control fields are stored -// in the sensor.icloud3_event_log entity. -// -// When iCloud3 starts, the version of this file, 'icloud3-event-log-card.js', -// in the 'custom_components\icloud3' directory (or the current directory of -// the icloud3 platform being run) is compared with the one in 'www/custom_cards'. -// If they do not match, the one in the 'custom_components\icloud3' is copied -// to the 'www\custom_cards' directory. -// -// Version=2.2.1.01 (10/28/2020) -// -///////////////////////////////////////////////////////////////////////////// - -class iCloud3EventLogCard extends HTMLElement { - constructor() { - super(); - this.attachShadow({ mode: 'open' }); - } - //--------------------------------------------------------------------------- - setConfig(config) { - const version = "2.2.1.01" - const cardTitle = "iCloud3 Event Log" - - const root = this.shadowRoot; - const hass = this._hass; - - // Create card elements - const card = document.createElement('ha-card'); - const background = document.createElement('div'); - background.id = "background"; - - // Title Bar - const titleBar = document.createElement("div"); - titleBar.id = "titleBar"; - const title = document.createElement("div"); - title.id = "title"; - title.textContent = cardTitle - - const utilityBar = document.createElement("div"); - utilityBar.id = "utilityBar"; - const thisButtonId = document.createElement("div"); - thisButtonId.id = "thisButtonId"; - thisButtonId.classList.add("themeTextColor"); - thisButtonId.innerText = "setup"; - const logRecdCnt = document.createElement("div"); - logRecdCnt.id = "logRecdCnt"; - logRecdCnt.innerText = "-1"; - const devType = document.createElement("div"); - devType.id = "devType"; - devType.innerText = ""; - const hdrCellWidth = document.createElement("div"); - hdrCellWidth.id = "hdrCellWidth"; - hdrCellWidth.innerText = "0,66.7px,97.8px,94.4px,80px,70px,66.7px"; - const versionText = document.createElement("div"); - versionText.id = "versionText"; - versionText.style.setProperty('visibility', 'hidden'); - versionText.textContent = 'v' + version - - // Button Bar - const buttonBar = document.createElement("div"); - buttonBar.id = "buttonBar"; - buttonBar.class = "buttonBar"; - - // Name Buttons - const btnName0 = document.createElement('btnName'); - btnName0.id = "btnName0"; - btnName0.classList.add("btnBaseFormat"); - btnName0.style.setProperty('visibility', 'visible'); - btnName0.innerText = "Setup"; - const btnName1 = document.createElement('btnName'); - btnName1.id = "btnName1"; - btnName1.classList.add("btnBaseFormat"); - btnName1.classList.add("btnHidden"); - const btnName2 = document.createElement('btnName'); - btnName2.id = "btnName2"; - btnName2.classList.add("btnBaseFormat"); - btnName2.classList.add("btnHidden"); - const btnName3 = document.createElement('btnName'); - btnName3.id = "btnName3"; - btnName3.classList.add("btnBaseFormat"); - btnName3.classList.add("btnHidden"); - const btnName4 = document.createElement('btnName'); - btnName4.id = "btnName4"; - btnName4.classList.add("btnBaseFormat"); - btnName4.classList.add("btnHidden"); - const btnName5 = document.createElement('btnName'); - btnName5.id = "btnName5"; - btnName5.classList.add("btnBaseFormat"); - btnName5.classList.add("btnHidden"); - const btnName6 = document.createElement('btnName'); - btnName6.id = "btnName6"; - btnName6.classList.add("btnBaseFormat"); - btnName6.classList.add("btnHidden"); - const btnName7 = document.createElement('btnName'); - btnName7.id = "btnName7"; - btnName7.classList.add("btnBaseFormat"); - btnName7.classList.add("btnHidden"); - const btnName8 = document.createElement('btnName'); - btnName8.id = "btnName8"; - btnName8.classList.add("btnBaseFormat"); - btnName8.classList.add("btnHidden"); - const btnName9 = document.createElement('btnName'); - btnName9.id = "btnName9"; - btnName9.classList.add("btnBaseFormat"); - btnName9.classList.add("btnHidden"); - - /* Action Select Box */ - const btnAction = document.createElement('select'); - btnAction.id = "btnAction"; - btnAction.style.setProperty('visibility', 'visible'); - btnAction.setDefault; - btnAction.classList.add("btnBaseFormat"); - btnAction.classList.add("btnAction"); - - var btnActionOptA = document.createElement("option"); - var btnActionOptATxt = document.createTextNode("Actions"); - btnActionOptA.setAttribute("value", "action"); - btnActionOptA.setAttribute("id", "optAction"); - btnActionOptA.classList.add("btnActionOptionTransparent"); - btnActionOptA.appendChild(btnActionOptATxt); - btnAction.appendChild(btnActionOptA); - - var btnActionOptG = document.createElement("optGroup"); - btnActionOptG.setAttribute("label", "———— Global Actions ————"); - btnActionOptG.classList.add("btnActionOptionGroup"); - btnAction.appendChild(btnActionOptG); - - var btnActionOptG1 = document.createElement("option"); - var btnActionOptG1Txt = document.createTextNode("Restart iCloud3"); - btnActionOptG1.setAttribute("value", "restart"); - btnActionOptG1.classList.add("btnActionOption"); - btnActionOptG1.appendChild(btnActionOptG1Txt); - btnAction.appendChild(btnActionOptG1); - - var btnActionOptG2 = document.createElement("option"); - var btnActionOptG2Txt = document.createTextNode("Pause Polling"); - btnActionOptG2.setAttribute("value", "pause"); - btnActionOptG2.classList.add("btnActionOption"); - btnActionOptG2.appendChild(btnActionOptG2Txt); - btnAction.appendChild(btnActionOptG2); - - var btnActionOptG3 = document.createElement("option"); - var btnActionOptG3Txt = document.createTextNode("Resume Polling"); - btnActionOptG3.setAttribute("value", "resume"); - btnActionOptG3.classList.add("btnActionOption"); - btnActionOptG3.appendChild(btnActionOptG3Txt); - btnAction.appendChild(btnActionOptG3); - - var btnActionOptG7 = document.createElement("option"); - var btnActionOptG7Txt = document.createTextNode("Update All Locations"); - btnActionOptG7.setAttribute("value", "location"); - btnActionOptG7.classList.add("btnActionOption"); - btnActionOptG7.appendChild(btnActionOptG7Txt); - btnAction.appendChild(btnActionOptG7); - - var btnActionOptG4 = document.createElement("option"); - var btnActionOptG4Txt = document.createTextNode("Show Tracking Monitors"); - btnActionOptG4.setAttribute("value", "dev-log_level: eventlog"); - btnActionOptG4.setAttribute("id", "optEvlog"); - btnActionOptG4.classList.add("btnActionOption"); - btnActionOptG4.appendChild(btnActionOptG4Txt); - btnAction.appendChild(btnActionOptG4); - - var btnActionOptG8 = document.createElement("option"); - var btnActionOptG8Txt = document.createTextNode("Show Startup Log, Errors & Alerts"); - btnActionOptG8.setAttribute("value", "dev-refresh_event_log"); - btnActionOptG8.setAttribute("id", "optStartuplog"); - btnActionOptG8.classList.add("btnActionOption"); - btnActionOptG8.appendChild(btnActionOptG8Txt); - btnAction.appendChild(btnActionOptG8); - - var btnActionOptG5 = document.createElement("option"); - var btnActionOptG5Txt = document.createTextNode("Export Event Log"); - btnActionOptG5.setAttribute("value", "dev-export_event_log"); - btnActionOptG5.classList.add("btnActionOption"); - btnActionOptG5.appendChild(btnActionOptG5Txt); - btnAction.appendChild(btnActionOptG5); - - var btnActionOptG6 = document.createElement("option"); - var btnActionOptG6Txt = document.createTextNode("Start HA Debug Logging"); - btnActionOptG6.setAttribute("value", "dev-log_level: debug"); - btnActionOptG6.setAttribute("id", "optHalog"); - btnActionOptG6.classList.add("btnActionOption"); - btnActionOptG6.appendChild(btnActionOptG6Txt); - btnAction.appendChild(btnActionOptG6); - - //--------------------------------------------------------- - var btnActionOptD = document.createElement("optGroup"); - btnActionOptD.setAttribute("label", "———— Selected Phone ————"); - btnActionOptD.classList.add("btnActionOptionGroup"); - btnAction.appendChild(btnActionOptD); - - var btnActionOptD1 = document.createElement("option"); - var btnActionOptD1Txt = document.createTextNode("Pause Polling"); - btnActionOptD1.setAttribute("value", "dev-pause"); - btnActionOptD1.classList.add("btnActionOption"); - btnActionOptD1.appendChild(btnActionOptD1Txt); - btnAction.appendChild(btnActionOptD1); - - var btnActionOptD2 = document.createElement("option"); - var btnActionOptD2Txt = document.createTextNode("Resume Polling"); - btnActionOptD2.setAttribute("value", "dev-resume"); - btnActionOptD2.classList.add("btnActionOption"); - btnActionOptD2.appendChild(btnActionOptD2Txt); - btnAction.appendChild(btnActionOptD2); - - var btnActionOptD3 = document.createElement("option"); - var btnActionOptD3Txt = document.createTextNode("Update Phone's Location"); - btnActionOptD3.setAttribute("value", "dev-location"); - btnActionOptD3.classList.add("btnActionOption"); - btnActionOptD3.appendChild(btnActionOptD3Txt); - btnAction.appendChild(btnActionOptD3); - - var btnActionOptBL = document.createElement("option"); - var btnActionOptBLTxt = document.createTextNode(""); - btnActionOptBL.classList.add("btnActionOption"); - btnActionOptBL.appendChild(btnActionOptBLTxt) - btnAction.appendChild(btnActionOptBL); - var btnActionOptV = document.createElement("optGroup"); - btnActionOptV.setAttribute("label", "—— Event Log v"+version+" ———"); - btnActionOptV.classList.add("btnActionOptionGroup"); - btnAction.appendChild(btnActionOptV); - //------------------------------------------------------------- - const btnRefresh = document.createElement('btnName'); - btnRefresh.id = "btnRefresh"; - btnRefresh.classList.add("btnRefresh"); - btnRefresh.style.setProperty('visibility', 'visible'); - btnRefresh.innerHTML=`` - - // Message Bar - const eltInfoBar = document.createElement("div"); - eltInfoBar.id = "eltInfoBar"; - - const eltInfoName = document.createElement("div"); - eltInfoName.id = "eltInfoName"; - eltInfoName.innerText = "Select Person"; - eltInfoName.style.color = "firebrick" - - const eltInfoTime = document.createElement("div"); - eltInfoTime.id = "eltInfoTime"; - eltInfoTime.innerText = "setup"; - eltInfoTime.style.color = "firebrick" - - const eltInfoMsgPopup = document.createElement("div"); - eltInfoMsgPopup.id = "eltInfoMsgPopup"; - eltInfoMsgPopup.classList.add("eltInfoMsgPopup"); - eltInfoMsgPopup.classList.add("eltInfoMsgPopupHidden"); - eltInfoMsgPopup.style.setProperty('zIndex', '9999'); - - const tblEvlogContainer = document.createElement("div"); - tblEvlogContainer.id = "tblEvlogContainer" - - const tblEvlog = document.createElement("TABLE") - tblEvlog.id = "tblEvlog" - tblEvlog.classList.add("tblEvlog") - - const tblEvlogHdr = document.createElement("TH") - tblEvlogHdr.id = "tblEvlogHdr" - tblEvlogHdr.classList.add("tblEvlogHeader") - - const tblEvlogBody = document.createElement("BODY") - tblEvlogBody.id = "tblEvlogBody" - tblEvlogBody.classList.add("tblEvlogBody") - - // Style - const cssStyle = document.createElement('style'); - cssStyle.textContent = ` - /* Text special colors */ - .blue {color: blue;} - .teal {color: teal;} - .darkgray {color: darkgray;} - .dimgray {color: dimgray;} - .black {color: var(--primary-text-color);} - .silver {color: silver;} - .darkred {color: darkred;} - .green {color: green;} - .red {color: var(--label-badge-red);} - .redChg {color: var(--label-badge-red);} - .redbox {border: 1px solid var(--label-badge-red); border-collapse: collapse;} - - .iosappRecd {color: teal;} - .errorMsg {color: var(--label-badge-red); border-left: 2px solid var(--label-badge-red);} - .warningMsg {color: green;} - - /* Color for special records */ - /* DarkGoldenRod, Fushia, DeepPink, OrangeRed, #e600e6 (firebrickish), MediumVioletRed */ - .star1 {color: firebrick; border-left: 2px solid firebrick;} - .star2 {color: BlueViolet; border-left: 2px solid BlueViolet;} - .star3 {color: OrangeRed; border-left: 2px solid OrangeRed;} - .dollar1 {color: SeaGreen; border-left: 2px solid SeaGreen;} - .dollar2 {color: Var(--dark-primary-color); border-left: 2px solid var(--dark-primary-color);} - .dollar3 {color: Blue; border-left: 2px solid RoyalBlue;} - - - .trigger {color: var(--primary-text-color); font-weight: 300;} - .normalText {color: var(--primary-text-color);} - .event {colspan: 5;} - - /* Solid bars for update start/complete, startup stage recds, startup date recd */ - .hdrTopBottomShadow {-moz-box-shadow: inset rgba(0, 0, 0, 0.8) 0px 14px 18px -18px, inset #000000 0px -14px 18px -18px; - -webkit-box-shadow: inset rgba(0, 0, 0, 0.8) 0px 14px 18px -18px, inset #000000 0px -14px 18px -18px; - box-shadow: inset rgba(0, 0, 0, 0.8) 0px 14px 18px -18px, inset #000000 0px -14px 18px -18px; - } - .updateRecdHdr {color: white; - background-color: rgba(var(--rgb-primary-color), 0.85); - border-top: 1px solid var(--light-primary-color); - border-bottom: 1px solid var(--light-primary-color); - font-weight: 450; - } - .updateEdgeBar {border-left: 4px solid var(--dark-primary-color);} - .stageRecdHdr {color: white; - background-color: peru; font-weight: 450; - border-top: 1px solid peru; - border-bottom: 1px solid peru; - } - .stageEdgeBar {border-left: 4px solid peru;} - .dateBarHdr {color: white; - background-color: peru; - border-top: 1px solid peru; - border-bottom: 1px solid peru; - } - .noLeftEdge {border-left: none;} - - /* Card Definition */ - ha-card { - background-color: var(--card-background-color); - padding: 10px; - } - #background { - position: relative; - height: 681px; - /*width: 473px;*/ - } - - /* Title Bar set up */ - #titleBar { - position: relative; - display: inline-block; - height: 20px; - margin: 4px 0px -6px 0px; - width: 100%; - //border: 1px solid dodgerblue; - } - #title { - height: 100%; - width: 60%; - text-align: left; - font-size: 24px; - margin: 0px 0px 0px 0px; - float: left; - vertical-align: middle; - color: var(--primary-text-color); - //border: 1px solid var(--label-badge-red); - } - - #utilityBar { - position: relative; - display: inline-block; - margin: 2px 0px -10px 0px; - width: 100%; - /*border: 1px solid dodgerblue;*/ - } - #thisButtonId, #logRecdCnt, #devType, #hdrCellWidth { - /*font-size: 2px;*/ - color: transparent; - width: 25px; - float: left; - /*border: 1px solid green;*/ - } - - #versionText { - color: silver; - float: right; - } - - /* Store the theme's primary text color in the thisButtonId field */ - .themeTextColor { - color: var(--primary-text-color);} - background-color: var(--secondary-text-color);} - } - - /* Message Bar setup */ - #eltInfoBar { - position: relative; - width: 100%; - /*border: 1px solid dodgerblue;*/ - } - #eltInfoName { - width: 40%; - color: firebrick; - float: left; - font-size: 14px; - font-weight: 400; - margin: 2px 0px 4px 0px; - /*border: 1px solid var(--label-badge-red);*/ - } - #eltInfoTime { - margin: 2px 2px 4px 0px; - color: firebrick; - float: right; - font-size: 14px; - font-weight: 400; - /*border: 1px solid green;*/ - } - .eltInfoMsgPopup { - position: relative; - width: 85%; - margin-left: auto; - margin-right: auto; - color: white; - background-color: var(--label-badge-red); - padding: 12px 12px; - font-size: 14px; - font-weight: 400; - z-index: 9999; - -webkit-box-shadow: 5px 5px 23px 3px rgba(0,0,0,0.75); - -moz-box-shadow: 5px 5px 23px 3px rgba(0,0,0,0.75); - box-shadow: 3px 3px 20px 3px rgba(0,0,0,0.75); - } - .eltInfoMsgPopupHidden { - height: 0px; - width: 0px; - visibility: hidden; - border: 0px; - } - - /* Scrollbar */ - ::-webkit-scrollbar {width: 7px;} - ::-webkit-scrollbar-track {background-color: transparent; - border-left: 1px solid rgba(var(--rgb-primary-color), 0.2);} - ::-webkit-scrollbar-thumb {background: rgba(var(--rgb-accent-color), 0.7); - border-radius: 4px;} - ::-webkit-scrollbar-thumb:hover {background: var(--accent-color);} - - /* Event Log Table */ - .txtTblStyle {color: var(--dark-primary-color);} - .txtTblHdr {border-left: 1px solid var(--dark-primary-color);} - .txtTblHdrRow {color: var(--dark-primary-color);} - .txtTblEdge {border-left: 1px solid var(--dark-primary-color);} - - .highlightResults {color: red;} - .inprocessResults {color: firebrick;} - .highlightItem {color: silver;} - .highlightItemChg {color: silver;} - - #tblEvlog { - position: relative; - margin: 0px 0px; - width: 100%; - } - - /* Event Log Table */ - .tblEvlog { - position: sticky; - display: block; - table-layout: fixed; - width: 100%; - border-collapse: collapse; - } - .tblEvlogHdr { - position: sticky; - table-layout: fixed; - display: block; - width: 100%; - height: 16px; - padding: 0px 0px 3px 0px; - border-collapse: collapse; - background-color: rgba(var(--rgb-primary-color), 0.15); - border: 1px solid rgba(var(--rgb-primary-color), 0.3); - } - .tblEvlogHdr tr { - display: block; - } - .tblEvlogBody { - display: block; - table-layout: fixed; - width: 100%; - height: 560px; - border-collapse: collapse; - border: 1px solid rgba(var(--rgb-primary-color), 0.2); - border-top: 1px solid transparent; - overflow-y: scroll; - overflow-x: hidden; - -webkit-overflow-scrolling: touch; - } - .tblEvlogBody tr { - border: 1px solid rgba(var(--rgb-primary-text-color), 0.1); - z-index: 1; - } - - .noTopBorder {border: 1px solid transparent;} - .rowBorder {border-left: 2px solid cyan;} - .tblEvlogBody tr:nth-child(even) {background-color: rgba(var(--rgb-primary-text-color), 0.05);} - .tblEvlogBody tr:nth-child(odd) {background-color: var(--primary-background-color);} - - /* Browser Text */ - .colTime {width: 66.67px; vertical-align: text-top;} - .colStat {width: 92.22px; vertical-align: text-top;} - .colZone {width: 90.00px; vertical-align: text-top;} - .colIntv {width: 76.67px; vertical-align: text-top;} - .colTrav {width: 65.56px; vertical-align: text-top;} - .colDist {width: 62.22px; vertical-align: text-top;} - .colTimeTextRow {color: rgba(var(--rgb-primary-text-color), 0.5); vertical-align: text-top;} - .colText {color: var(--primary-text-color)} - - /* Browser Header */ - .hTime {width: 64.6px; text-align: left; color: var(--primary-text-color); padding-left: 4px;} - .hStat {width: 90.2px; text-align: left; color: var(--primary-text-color);} - .hZone {width: 88.0px; text-align: left; color: var(--primary-text-color);} - .hIntv {width: 73.6px; text-align: left; color: var(--primary-text-color);} - .hTrav {width: 63.6px; text-align: left; color: var(--primary-text-color);} - .hDist {width: 59.1px; text-align: left; color: var(--primary-text-color);} - .hdrBase {text-align: left; color: var(--primary-text-color);} - - /* Buttons */ - .buttonBar { - position: relative; - margin: 8px 0px 8px 0px; - width: 100%; - border: 1px solid blue; - } - .btnBaseFormat { - display: inline-block; - visibility: visible; - font-family: Roboto,sans-serif; - font-size: 14px; - font-weight: bolder; - color: var(--primary-text-color); - /*background-color: transparent;*/ - background-color: rgba(var(--rgb-primary-text-color), 0.05); - text-decoration: none; - text-align: center; - height: 24px; - padding: 1px 4px; - margin: 4px 6px 0px 0px; - border: 1px solid #ff4d4d; - border-radius: 3px; - box-sizing: border-box; - /*border: 1px solid #0080F0;*/ - } - .btnSelected { - color: white; - background-color: darkred; - } - .btnNotSelected { - color: var(--primary-text-color); - background-color: rgba(var(--rgb-primary-text-color), 0.04); - } - .btnHidden { - height: 0px; - width: 0px; - margin: 0px; - padding: 0px; - visibility: hidden; - border: 0px; - } - .btnHover {border: 1px solid var(--primary-color);} - - /* Refresh Select Button */ - #btnRefresh { - display: inline-block; - visibility: visible; - color: var(--primary-text-color); - background-color: transparent; - height: 24px; - margin: -4px 2px; - float: right; - box-sizing: border-box; - } - .btnRefresh { - border: 0px solid transparent; - background-color: transparent; - box-shadow: transparent; - } - svg {fill: #ff4d4d;} - svg:hover {fill: var(--primary-color);} - - /* Action Select Button */ - #btnAction { - color: white; - background-color: darkred; - float: right; - margin: 4px 2px 0 0; - border: 1px solid #ff4d4d; - } - #btnAction:hover {border: 1px solid var(--primary-color);} - .btnAction { - background: darkred; - font-weight: bolder; - height: 24px; - width: 80px; - border-radius: 3px; - overflow: hidden; - -webkit-appearance: none; - -moz-appearance: none; - transition: color 0.3s ease, background-color 0.3s ease, border-bottom-color 0.3s ease; - - /* Action Button Down Arrow */ - background-image: - linear-gradient(#cc0000, #cc0000), - linear-gradient(darkred 43%, transparent 35%), - linear-gradient(-135deg, transparent 58%, darkred 50%), - linear-gradient(-225deg, white 58%, darkred 50%); - background-size: 1px 100%, 22px 26px, 22px 26px, 22px 100%; - background-repeat: no-repeat; - background-position: right 20px center, right bottom, right bottom, right bottom; - - } - .btnAction::-ms-expand { - display: none; - } - .btnActionOptionGroup { - background-color: var(--primary-background-color); - color: var(--primary-text-color); - } - .btnActionOptionTransparent { - background-color: var(--primary-background-color); - color: var(--primary-text-color); - } - .btnActionOption { - background-color: var(--primary-background-color); - color: var(--primary-text-color); - } - - /* IPHONE IPAD Mods */ - /* iPhone with smaller screen*/ - @media only screen and (max-device-width: 640px), - only screen and (max-device-width: 667px), - only screen and (max-width: 480px) { - - ha-card {padding: 4px 4px 4px 4px;} - .btnBaseFormat {margin: 0px 2px 4px 0px; padding: 1px 3px;) - .btnAction {width: 45px; height: 22px;} - .updateRecd {font-weight: 450;} - - .ic3StartupMsg {font-weight: 450;} - .tblEvlogBody tr:nth-child(even) {background-color: #EEF2F5;} - ::-webkit-scrollbar {width: 1px;} - ::-webkit-scrollbar-thumb {background: rgba(var(--rgb-accent-color), 0.7);} - } - - /* iPad ??? - @media only screen - and (min-device-width : 768px) - and (max-device-width : 1024px) { - .updateRecd {font-weight: 450;} - .updateEdgeBar {border-left-width: 3px;} - .ic3StartupMsg {font-weight: 450;} - .tblEvlogBody tr:nth-child(even) {background-color: #EEF2F5;} - ::-webkit-scrollbar {width: 1px;} - ::-webkit-scrollbar-thumb {background: rgba(var(--rgb-accent-color), 0.7);} - } - */ - - `; - - // Build title - titleBar.appendChild(title); - titleBar.appendChild(btnRefresh); - - utilityBar.appendChild(thisButtonId); - utilityBar.appendChild(logRecdCnt); - utilityBar.appendChild(devType); - utilityBar.appendChild(hdrCellWidth); - utilityBar.appendChild(versionText); - - // Create Buttons - buttonBar.appendChild(btnName0); - buttonBar.appendChild(btnName1); - buttonBar.appendChild(btnName2); - buttonBar.appendChild(btnName3); - buttonBar.appendChild(btnName4); - buttonBar.appendChild(btnName5); - buttonBar.appendChild(btnAction); - buttonBar.appendChild(btnName6); - buttonBar.appendChild(btnName7); - buttonBar.appendChild(btnName8); - buttonBar.appendChild(btnName9); - - // Build Message Bar - eltInfoBar.appendChild(eltInfoName); - eltInfoBar.appendChild(eltInfoTime); - eltInfoBar.appendChild(eltInfoMsgPopup) - - tblEvlog.appendChild(tblEvlogHdr) - tblEvlog.appendChild(tblEvlogBody) - tblEvlogContainer.appendChild(tblEvlog) - - // Create Background - background.appendChild(titleBar) - background.appendChild(utilityBar) - background.appendChild(buttonBar) - background.appendChild(eltInfoBar) - background.appendChild(tblEvlogContainer) - background.appendChild(cssStyle); - - card.appendChild(background); - root.appendChild(card); - - // Click & Mouse Events - for (let i = 0; i <= 9; i++) { - let buttonId = 'btnName' + i - let button = root.getElementById(buttonId) - - button.addEventListener("mousedown", event => { this._nameButtonPress(buttonId); }); - button.addEventListener("mouseover", event => { this._btnClassMouseOver(buttonId); }); - button.addEventListener("mouseout", event => { this._btnClassMouseOut(buttonId); }); - } - - btnAction.addEventListener("change", event => { this._commandButtonPress("btnAction"); }); - //btnAction.addEventListener("mouseover", event => { this._btnClassMouseOver("btnAction"); }); - //btnAction.addEventListener("mouseout", event => { this._btnClassMouseOut("btnAction"); }); - - btnRefresh.addEventListener("mousedown", event => { this._commandButtonPress("btnRefresh"); }); - btnRefresh.addEventListener("mouseover", event => { this._btnClassMouseOver("btnRefresh"); }); - btnRefresh.addEventListener("mouseout", event => { this._btnClassMouseOut("btnRefresh"); }); - - // Add to root - this._config = config; - } - - // Create card. - //--------------------------------------------------------------------------- - set hass(hass) { - /* Hass will do this on a regular basis. If this is the first time - through, set up the button names. otherwise, display the event table. - */ - const root = this.shadowRoot - this._hass = hass - const thisButtonId = root.getElementById("thisButtonId") - const eltInfoTime = root.getElementById("eltInfoTime") - const eltInfoMsgPopup = root.getElementById("eltInfoMsgPopup") - - try { - const updateTimeAttr = hass.states['sensor.icloud3_event_log'].attributes['update_time'] - if (thisButtonId.innerText == "setup") { - this._setupDevType() - this._setupButtonNames() - this._nameButtonPress(this._currentButtonId()) - } - - //this._displayNameMsgL('/'+eltInfoTime.innerText + '/'+updateTimeAttr+'/') - if (eltInfoTime.innerText.indexOf(updateTimeAttr) == -1) { - this._setupEventLogTable('hass') - } - eltInfoMsgPopup.classList.add('eltInfoMsgPopupHidden') - } - catch(err) { - const eltInfoMsgPopup = root.getElementById("eltInfoMsgPopup") - const eltInfoTime = root.getElementById("eltInfoTime") - - if (eltInfoMsgPopup.classList.contains('eltInfoMsgPopupHidden') == false) { - return - } - const msgRestarting = '

iCloud3 is restarting

' - const msgNotRunning = '

iCloud3 Status:
     • restarting,
     • not running,
     • not installed,
     • has not been set up or,
     • there are other errors.


Be sure you have setup the iCloud3 device_tracker platform in the HA configuration.yaml file.

Check for iCloud3 load errors in the HA Logs here:
HA Sidebar>Configuration>Logs.

Review the iCloud3 documentation for more information here:
https://gcobb321.github.io/icloud3/#/chapters/1-installing-icloud3

' - - if (err.name == 'TypeError') { - if (err.message.indexOf('attributes') > -1) { - //if (eltInfoTime.innerText == 'setup') { - if (thisButtonId.innerText == "setup") { - eltInfoMsgPopup.innerHTML = msgNotRunning - } else { - eltInfoMsgPopup.innerHTML = msgRestarting - } - eltInfoMsgPopup.classList.remove('eltInfoMsgPopupHidden') - } else if (err.message.indexOf('undefined') == -1) { - alert(err) - } - } else { - alert(err) - } - } - } - - //--------------------------------------------------------------------------- - _setupButtonNames() { - /* Cycle through the sensor.icloud3_event_log attributes and - build the names on the buttons, and make them visible. - */ - const root = this.shadowRoot; - const hass = this._hass; - const thisButtonId = root.getElementById("thisButtonId") - const btnName0 = root.getElementById("btnName0") - const filtername = hass.states['sensor.icloud3_event_log'].attributes['filtername'] - const namesAttr = hass.states['sensor.icloud3_event_log'].attributes['names'] - const names = Object.values(namesAttr) - var nameCnt = names.length - - thisButtonId.innerText = 'btnName0' - - if (nameCnt > 10) {nameCnt = 10} - for (var i = 0; i < nameCnt; i++) { - let buttonId = 'btnName' + i - var button = root.getElementById(buttonId) - - //Get button for data in current sensor.icloud3_event_log - if (filtername == names[i]) { - thisButtonId.innerText = buttonId - } - - if (i < names.length) { - button.innerText = names[i] - button.style.setProperty('visibility', 'visible'); - button.classList.remove('btnHidden') - button.classList.add('btnNotSelected') - - //} else { - // button.innerText = "Device-"+i - // button.style.setProperty('visibility', 'visible'); - // button.classList.remove('btnHidden') - } - } - } - -//--------------------------------------------------------------------------- - _setupEventLogTable(devicenameParm) { - /* Cycle through the sensor.icloud3_event_log attributes and - build the event log table - */ - - const root = this.shadowRoot; - const hass = this._hass; - const tblEvlog = root.getElementById("tblEvlog") - const eltInfoTime = root.getElementById("eltInfoTime") - const hdrCellWidth = root.getElementById("hdrCellWidth") - const logRecdCnt = root.getElementById("logRecdCnt") - const devType = root.getElementById("devType") - const thisButtonId = root.getElementById("thisButtonId") - - var logAttr = hass.states['sensor.icloud3_event_log'].attributes['logs'] - - /* - The Evlog table has been built and displayed but Hass usually calls this routine a - second time. No need to builds tblEvlog again but now go back thru and - update the header cell lengths - */ - - if (logAttr.length == logRecdCnt.innerText) { - if (hdrCellWidth.innerText.startsWith('0,')) { - this._resize_header_width() - } - //this._displayNameMsgL('Return len=/'+logAttr.length+'/'+logRecdCnt.innerText) - return - } - - this._checkNameButtonSelected() - - if (logAttr.length > 0) { - var logEntriesRaw = logAttr.slice(2,-2) - var logEntries = logEntriesRaw.split('], [',99999) - } - - logRecdCnt.innerText = logAttr.length - let row = 0 - var sameTextCnt = 0 - var infoTimeText = "" - - var iPhoneP = false - var iPhoneL = false - var iPad = false - var iPadP = false - var iPadL = false - if (devType.innerText == "phnP") {iPhoneP = true} - else if (devType.innerText == "phnL") {iPhoneL = true} - else if (devType.innerText == "padP") {iPadP = true} - else if (devType.innerText == "padL") {iPadL = true} - if (devType.innerText.startsWith("pad") > 0) {iPad = true} - - /* Field naming conventions (xTime examples appply to all cell fields): - thTime = Header text for Time column - hTime = hTime header Id & Class name - iTime = iTime data cell Id name - classTime = iTime class name - tTime = Time text for current record - nTime = Time text for next record - */ - - var cellWidth = hdrCellWidth.innerText.split(',') - var thTime = "Time" - var thStat = "iOS App" - var thZone = "iC3 Zone" - var thIntv = "Interval" - var thTrav = "Travel" - var thDist = "Distance" - if (iPhoneP) { - thIntv = "Intvl" - thTrav = "Travl" - thDist = "Dist" - } - let logTableHeadHTML = '' - logTableHeadHTML += '' - logTableHeadHTML += '' - logTableHeadHTML += ''+thTime+'' - logTableHeadHTML += ''+thStat+'' - logTableHeadHTML += ''+thZone+'' - logTableHeadHTML += ''+thIntv+'' - logTableHeadHTML += ''+thTrav+'' - logTableHeadHTML += ''+thDist+'' - - logTableHeadHTML += ' ' - logTableHeadHTML += '' - logTableHeadHTML += '' - - let logTableHTML = '' - logTableHTML += '
' - logTableHTML += '' - logTableHTML += logTableHeadHTML - logTableHTML += '' - - /* - Example of log file string: - [['10:54:45', 'home', 'Home', '0 mi', '', '2 hrs', 'Update via iCloud Completed'], - ['10:54:45', 'home', 'Home', '0 mi', '', '2 hrs', 'Interval basis: 4iz-InZone, Zone=home, Dir=in_zone'], - ['10:54:45', 'home', 'Home', '0 mi', '', '2 hrs', 'Location Data Prepared (27.72682, -80.390507)'], - ['10:54:45', 'home', 'Home', '0 mi', '', '2 hrs', 'Preparing Location Data'], ['10:54:45', 'home', 'Home', '0 mi', '', '2 hrs', 'Update via iCloud, nextUpdateTime reached'], - ['10:54:33', 'home', 'Home', '0 mi', '', '2 hrs', 'Update cancelled, Old location data, Age 18.9 min, Retry #1']] - - Data extraction steps: - 1. Drop '[[' and ']]' at each end. - 2. Split on '], ][' to create a list item for each record. - 3. Cycle through list records. Split on ', ' to create each element. - */ - if (logAttr.length == 0) { - return - } - - var completedItemHighlightNextRowFlag = false - var classEdgeBar = '' - var cancelEdgeBarFlag = false - var initializationRecdFound = false - var iosappUpdateCompleteFlag = false - var icloudUpdateCompleteFlag = false - var alertErrorMsg = "" - - for (var i = 0; i < logEntries.length-1; i++) { - var thisRecd = logEntries[i].split("', '",10) - - var tTime = thisRecd[0].slice(1) - var tStat = thisRecd[1] - var tZone = thisRecd[2] - var tIntv = thisRecd[3] - var tTrav = thisRecd[4] - var tDist = thisRecd[5] - var tText = thisRecd[6].slice(0,-1) - - var nextRecd = logEntries[i+1].split("', '",10) - var nStat = nextRecd[1] - var nZone = nextRecd[2] - var nIntv = nextRecd[3] - var nTrav = nextRecd[4] - var nDist = nextRecd[5] - var nText = nextRecd[6].slice(0,-1) - - var thisRecdTestChg = tStat + tZone + tIntv + tTrav + tDist - var nextRecdTestChg = nStat + nZone + nIntv + nTrav + nDist - - var maxStatZoneLength = 10 - if (iPhoneP) { - tText = tText.replace('/icloud3','... .../icloud3') - maxStatZoneLength = 9 - if (tStat == 'stationary') {tStat = 'stationry'} - if (tZone == 'stationary') {tZone = 'stationry'} - if (tStat == 'Stationary') {tStat = 'Stationry'} - if (tZone == 'Stationary') {tZone = 'Stationry'} - } - if (tStat.length > maxStatZoneLength) { - tStat = tStat.substr(0, maxStatZoneLength) + "
" + tStat.substr(maxStatZoneLength, tStat.length) - if (tStat.length > maxStatZoneLength*2) {tStat = tStat.substr(0, maxStatZoneLength*2 + 3) + "..."} - } - if (tZone.length > 8) { - tZone = tZone.substr(0, maxStatZoneLength) + "
" + tZone.substr(maxStatZoneLength, tZone.length) - if (tZone.length > maxStatZoneLength*2) {tZone = tZone.substr(0, maxStatZoneLength*2 + 3) + "..."} - } - if (tText == nText) { - ++sameTextCnt - if (sameTextCnt == 1) {var firstTime = tTime} - continue - } - if (sameTextCnt > 0) { - tTime = firstTime - tText += ' (+'+ sameTextCnt +' more times)' - sameTextCnt = 0 - } - - var classTime = 'colTime' - var classStat = 'colStat' - var classZone = 'colZone' - var classIntv = 'colIntv' - var classTrav = 'colTrav' - var classDist = 'colDist' - var classText = 'colText' - - var highlightResultsFlag = false - //This is set when the previous item was an update complete item - if (completedItemHighlightNextRowFlag) { - highlightResultsFlag = true - completedItemHighlightNextRowFlag = false - - //display the info in var(--label-badge-red) if starting an update - } else if (tText.indexOf("update started") >= 0) { - highlightResultsFlag = true - - //Display info in first row in var(--label-badge-red) - } else if (row == 0) { - highlightResultsFlag = true - } - if (highlightResultsFlag ) { - classTime += ' highlightResults' - classStat += ' highlightResults' - classZone += ' highlightResults' - classIntv += ' highlightResults' - classTrav += ' highlightResults' - classDist += ' highlightResults' - } else { - classTime += ' inprocessResults' - classStat += ' inprocessResults' - classZone += ' inprocessResults' - classIntv += ' inprocessResults' - classTrav += ' inprocessResults' - classDist += ' inprocessResults' - } - - //Set header recd background bar color and turn edge bar on/off - //Set Startup start/complete & stage bar colors and edge bars - var classRecdType = ' normalText' - var classHeaderBar = '' - if (tText.indexOf("update started") >= 0) { - classHeaderBar = ' updateRecdHdr' - cancelEdgeBarFlag = true - } else if (tText.indexOf("update complete") >= 0) { - if (tText.indexOf("iOS App") >=0) { - iosappUpdateCompleteFlag = true - } else { - icloudUpdateCompleteFlag = true - } - completedItemHighlightNextRowFlag = true - classHeaderBar = ' updateRecdHdr' - classEdgeBar = ' updateEdgeBar' - - } else if (tText.startsWith("^^^")) { - cancelEdgeBarFlag = (tText.indexOf("started") >= 0) - classHeaderBar = ' dateBarHdr' - classEdgeBar = ' stageEdgeBar' - tText = tText.replace("^^^", "") - tText = tText.replace("^^^", "") - } else if (tText.indexOf("Stage") >= 0) { - classHeaderBar = ' stageRecdHdr' - classEdgeBar = ' stageEdgeBar' - } else if (tText.indexOf("Warning") >= 0) { - classHeaderBar = ' warningMsg' - } - - if (classHeaderBar != "") { - classHeaderBar = " hdrTopBottomShadow" + classHeaderBar - } - - //Set text color the text starts with a special color character - var classSpecialTextColor = '' - var specialColorFlag = true - if (tText.startsWith("$$$")) { - classSpecialTextColor = ' dollar3' - tText = tText.slice(3) - } else if (tText.startsWith("$$")) { - classSpecialTextColor = ' dollar2' - tText = tText.slice(2) - } else if (tText.startsWith("$")) { - classSpecialTextColor = ' dollar1' - tText = tText.slice(1) - } else if (tText.startsWith("***")) { - classSpecialTextColor = ' star3' - tText = tText.slice(3) - } else if (tText.startsWith("**")) { - classSpecialTextColor = ' star2' - tText = tText.slice(2) - } else if (tText.startsWith("*")) { - classSpecialTextColor = ' star1' - tText = tText.slice(1) - } else if (tText.startsWith("__")) { - classSpecialTextColor = ' normalText' - } else { - specialColorFlag = false - classSpecialTextColor = '' - } - - var classErrorMsg = "" - if (tText.indexOf("Initializing iCloud3") >= 0 - && tText.indexOf("Complete") == -1) { - initializationRecdFound = true - } - if (tText.indexOf(" Error ") >= 0) { - classErrorMsg = ' errorMsg' - if (initializationRecdFound == false) { - alertErrorMsg = "iCloud3 Error Msg at "+tTime - } - } else if (tText.indexOf("iCloud Alert") >= 0) { - classErrorMsg = ' errorMsg' - if (initializationRecdFound == false - && icloudUpdateCompleteFlag == false) { - alertErrorMsg = "iCloud Alert Msg at "+tTime - } - } else if (tText.indexOf("iOS App Alert") >= 0) { - classErrorMsg = ' errorMsg' - if (initializationRecdFound == false - && iosappUpdateCompleteFlag == false) { - alertErrorMsg = "iOS App Alert Msg at "+tTime - } - } else if (tText.indexOf("Alert") >= 0) { - classErrorMsg = ' errorMsg' - if (initializationRecdFound == false) { - alertErrorMsg = "Alert Msg at "+tTime - } - } else if (tText.startsWith("!")) { - classErrorMsg = ' errorMsg' - tText = tText.slice(1) - } - - //Change CRLF in the text string to HTML >b> for a new line - while (tText.indexOf("CRLF•") >= 0) { - tText = tText.replace("CRLF•","
   •") - } - while (tText.indexOf("CRLF") >= 0) { - tText = tText.replace("CRLF", "
") - } - - //If displaying a table, the State & Interval can contain column titles - var classTable = '' - var txtTblFlag = false - if (tText.indexOf("¤s") >= 0) { - txtTblFlag = true - classTable = ' txtTblStyle' - } - - //Build the table HTML from the special characters in the recd - // ¤s=
Table start, Row start - // ¤e=
Row end, Table end - // §= Row end, next row start - // «40= Col start, 40% width - // ¦0= Col end, next col start - // ¦10= Col end, next col start-width 10% - // ¦40= - tText = tText.replace(/¤s/g, '') - tText = tText.replace(/¤e/g, '
') - - tText = tText.replace(/«HS/g, '') - tText = tText.replace(/¦LH-/g, '') - tText = tText.replace(/¦RH-/g, '') - tText = tText.replace(/»HE/g, '') - - tText = tText.replace(/«LT-/g, ' ') - tText = tText.replace(/¦LC-/g, '') - tText = tText.replace(/¦RT-/g, ' ') - tText = tText.replace(/¦RC-/g, '') - - tText = tText.replace(/»/g, '') - - //Abbreviate text if displaying on an iPhone with a smaller display - if (iPhoneP) { - tIntv = tIntv.replace(' sec','s') - tIntv = tIntv.replace(' min','m') - tIntv = tIntv.replace(' hrs','h') - tIntv = tIntv.replace(' hr','h') - - tTrav = tTrav.replace(' sec','s') - tTrav = tTrav.replace(' min','m') - tTrav = tTrav.replace(' hrs','h') - tTrav = tTrav.replace(' hr','h') - - tDist = tDist.replace(' mi','mi') - tDist = tDist.replace(' km','km') - - if (txtTblFlag) { - tText = tText.replace("App Updates", "App Updts") - tText = tText.replace("Rqsts", "") - tText = tText.replace("Trigger Chgs", "Trig Chg") - tText = tText.replace("Locate", "Loc") - } - } - - //Determine if the state/zone/dist/time line should be displayed - var displayStateZoneLineFlag = false - if (thisRecdTestChg != nextRecdTestChg) {displayStateZoneLineFlag = true} - if (classTime.indexOf("highlightResults") >= 0) {displayStateZoneLineFlag = true} - if (tStat == '' && tZone == '') {displayStateZoneLineFlag = false} - if (tText.startsWith("^^^")) {displayStateZoneLineFlag = false} - - if (row > 1) {classTime += classEdgeBar} - - //Display Info Row - if (displayStateZoneLineFlag) { - if (tIntv == '') {tIntv = ' '} - if (tTrav == '') {tTrav = ' '} - if (tDist == '') {tDist = ' '} - - ++row - logTableHTML += '' - logTableHTML += ''+tTime+'' - logTableHTML += ''+tStat+'' - logTableHTML += ''+tZone+'' - logTableHTML += ''+tIntv+'' - logTableHTML += ''+tTrav+'' - logTableHTML += ''+tDist+'' - logTableHTML += '' - } - - //continue - //Display Text Row - //tText = classTime - classTime = classTime.replace("highlightResults", "") - classTime = classTime.replace("inprocessResults", "") - classTime += classRecdType + classHeaderBar - classTime += ' colTimeTextRow' - - if (classTime.indexOf("Hdr") >= 0) { - classText += ' noLeftEdge' - tTime = '' - } - var classTextColor = classHeaderBar + classSpecialTextColor + classTable + classErrorMsg - if (classTextColor != "") { - classText = classText.replace("colText", classTextColor) - } - - ++row - logTableHTML += '' - logTableHTML += ''+tTime+'' - logTableHTML += '' - logTableHTML += ''+tText+'' - logTableHTML += '' - - if (cancelEdgeBarFlag) { - classEdgeBar = '' - cancelEdgeBarFlag = false - } - } - - logTableHTML += '' - //} - logTableHTML += '
' - tblEvlog.innerHTML = logTableHTML - - this._resize_header_width() - - const updateTimeAttr = hass.states['sensor.icloud3_event_log'].attributes['update_time'] - const logLevelDebug = hass.states['sensor.icloud3_event_log'].attributes['log_level_debug'] - const optEvlog = root.getElementById("optEvlog") - const optHalog = root.getElementById("optHalog") - const optStartuplog = root.getElementById("optStartuplog") - - if (logLevelDebug.indexOf("evlog") >= 0) { - optEvlog.text = "Hide Tracking Monitors" - } else { - optEvlog.text = "Show Tracking Monitors" - } - if (logLevelDebug.indexOf("halog") >= 0) { - optHalog.text = "Stop HA Debug Logging" - infoTimeText = "Debug Log, "+updateTimeAttr - } else { - optHalog.text = "Start HA Debug Logging" - } - - if (alertErrorMsg != "") { - infoTimeText = "●● " + alertErrorMsg - } - - this._displayTimeMsgR(infoTimeText) - } - -//--------------------------------------------------------------------------- - _resize_header_width() { - const root = this.shadowRoot; - const tblEvlog = root.getElementById("tblEvlog") - const devType = root.getElementById("devType") - var rowCnt = tblEvlog.rows.length - - //Get, reset and save header cell widths - var hdrCellWidthStr = '' - rowCnt = tblEvlog.rows.length - for (var row = 1; row < rowCnt-1; row++) { - var cellCnt = tblEvlog.rows[row].cells.length - var cellWidth = tblEvlog.rows[row].cells[1].offsetWidth - if (cellCnt > 2 && cellWidth != 0) { - for (var i = 0; i < cellCnt; i++) { - var cellBCRObj = tblEvlog.rows[row].cells[i].getBoundingClientRect() - var cellWidthBCR = cellBCRObj.width + 2 - if (i == 5 && devType.innerText == "") {cellWidthBCR -= 10} - hdrCellWidthStr += cellWidthBCR + 'px,' - tblEvlog.rows[0].cells[i].style.width = cellWidthBCR+'px' - } - //alert(hdrCellWidth.innerText = row + ',' + hdrCellWidthStr) - return - } - } - - return - } -//--------------------------------------------------------------------------- - _setupDevType() { - const root = this.shadowRoot; - const devType = root.getElementById("devType") - - //iPhone (portrait) width=375, ,height=768 - // (landscape) width=724, ,height=375 - //iPad (portrait) width=834, ,height=1092 - // (landscape) width=1112, height=814 - //Windows (portrait) width=1424, height=921 - - var deviceWidth = window.innerWidth - var deviceHeight = window.innerHeight - - const userAgentStr = navigator.userAgent - var userAgentAlamofire = userAgentStr.indexOf("Alamofire") - var userAgentHA = userAgentStr.indexOf("HomeAssistant") - var appleDevice = userAgentAlamofire + userAgentHA - if (appleDevice > 0) { - if (deviceWidth < 400 && deviceHeight < 800) { - devType.innerText = "phnP" - } else if (deviceWidth < 800 && deviceHeight < 400) { - devType.innerText = "phnL" - } else if (deviceWidth < 850 && deviceHeight > 800) { - devType.innerText = "padP" - } else if (deviceWidth > 800 && deviceHeight < 850) { - devType.innerText = "padL" - } - } - //alert('/'+devType.innerText+'/') - } - -//--------------------------------------------------------------------------- - _checkNameButtonSelected() { - /* Simulate name button press using the name returned from HA when building - the tblEvlog table. If the selected name was changed on one device and - and then the Event Log was displayed in another, the Log revs are for the - selected device but the name highlighter will be for the precious device selected. - */ - const root = this.shadowRoot; - const hass = this._hass; - this.namesAttr = hass.states['sensor.icloud3_event_log'].attributes['names'] - var filtername = hass.states['sensor.icloud3_event_log'].attributes['filtername'] - const namesAttr = this.namesAttr - const names = Object.values(namesAttr) - const btnName0 = root.getElementById("btnName0") - var lastButtonId = this._currentButtonId() - var lastButtonPressed = root.getElementById(lastButtonId) - - if (filtername == null) { - lastButtonPressed.classList.add('btnNotSelected') - lastButtonPressed.classList.remove('btnSelected') - - this._displayNameMsgL("Select Person") - return - - } else if (filtername == "Initialize") { - this._setupButtonNames() - this._nameButtonPress("btnName0") - //btnName0.classList.remove('btnNotSelected') - //btnName0.classList.add('btnSelected') - } - - for (var i = 0; i < 10; i++) { - if (names[i] == null) {break} - if (filtername == names[i]) { - let buttonId = 'btnName' + i - - if (buttonId != lastButtonId) { - this._nameButtonPress(buttonId) - } - } - } - } -//--------------------------------------------------------------------------- - _nameButtonPress(buttonPressId) { - /* Handle the button press events. Get the devicename, do an 'icloud3_update' - event_log devicename' service call to have the event_log attribute populated. - */ - const root = this.shadowRoot; - const hass = this._hass; - this.namesAttr = hass.states['sensor.icloud3_event_log'].attributes['names'] - const namesAttr = this.namesAttr - const names = Object.values(namesAttr) - const devicenames = Object.keys(namesAttr) - const logRecdCnt = root.getElementById("logRecdCnt") - const thisButtonId = root.getElementById("thisButtonId") - const thisButtonPressed = root.getElementById(buttonPressId) - - var lastButtonId = this._currentButtonId() - var lastButtonPressed = root.getElementById(lastButtonId) - var buttonPressX = buttonPressId.substr(-1) - var eltInfoName = names[buttonPressX]+" ("+devicenames[buttonPressX]+")" - - this._displayNameMsgL(eltInfoName) - thisButtonId.innerText = buttonPressId - - lastButtonPressed.classList.remove('btnSelected') - lastButtonPressed.classList.add('btnNotSelected') - thisButtonPressed.classList.remove('btnNotSelected') - thisButtonPressed.classList.add('btnSelected') - thisButtonPressed.classList.remove("btnHover") - - this._hass.callService("device_tracker", "icloud3_update", { - device_name: devicenames[buttonPressX], - command: 'refresh_event_log'}) - } - -//--------------------------------------------------------------------------- - _commandButtonPress(actionButton) { - /* Handle the button press events. Get the devicename, do an 'icloud3_update' - event_log devicename' service call to have the event_log attribute populated. - */ - const root = this.shadowRoot; - const hass = this._hass; - this.namesAttr = hass.states['sensor.icloud3_event_log'].attributes['names'] - const namesAttr = this.namesAttr - const devicenames = Object.keys(namesAttr) - const btnAction = root.getElementById('btnAction') - const logRecdCnt = root.getElementById("logRecdCnt") - const thisButtonId = root.getElementById("thisButtonId") - - const btnName0 = root.getElementById('btnName0') - var lastButtonId = this._currentButtonId() - var lastButtonPressed= root.getElementById(lastButtonId) - var buttonPressX = lastButtonId.substr(-1) - var actionDevicename = devicenames[buttonPressX] - - if (actionButton == "btnRefresh") { - this._hass.callService("device_tracker", "icloud3_update", { - device_name: actionDevicename, - command: "refresh_event_log"}) - - } else if (actionButton == "btnAction") { - var actionValue = btnAction.value - var actionIndex = btnAction.selectedIndex - btnAction.options[actionIndex].selected = false - - if (actionValue == "dev-refresh_event_log") { - actionDevicename = "startup_log" - } - - //Device Actions - if (actionValue.startsWith("dev-")) { - actionValue = actionValue.slice(4) - - this._hass.callService("device_tracker", "icloud3_update", { - device_name: actionDevicename, - command: actionValue}) - - //Global Actions - } else { - this._hass.callService("device_tracker", "icloud3_update", { - command: actionValue}) - - if (actionValue == "restart") { - thisButtonId.innerText = "setup" - logRecdCnt.innerText = "-1" - } - } - - //Lose btnAction focus to reset selected option - btnAction.blur() - } - } - -//--------------------------------------------------------------------------- - _btnClassMouseOver(buttonId) { - - const root = this.shadowRoot; - const button = root.getElementById(buttonId) - const thisButtonId = root.getElementById("thisButtonId") - const versionText = root.getElementById("versionText") - const devType = root.getElementById("devType") - - if (buttonId == "btnRefresh") { - this._displayTimeMsgR("Refresh Event Log") - versionText.style.setProperty('visibility', 'visible'); - - } else if (buttonId == "btnAction") { - this._displayTimeMsgR("Show Action Command List") - } - - if (devType.innerText == "") {button.classList.add("btnHover")} - } - //--------------------------------------------------------------------------- - _btnClassMouseOut(buttonId) { - - const root = this.shadowRoot; - const hass = this._hass; - this.logLevelDebug = hass.states['sensor.icloud3_event_log'].attributes['log_level_debug'] - const button = root.getElementById(buttonId) - const versionText = root.getElementById('versionText') - const devType = root.getElementById("devType") - const thisButtonId = root.getElementById("thisButtonId") - - if (buttonId == 'btnRefresh') { - versionText.style.setProperty('visibility', 'hidden') - } - - if (devType.innerText == "") {button.classList.remove("btnHover")} - this._displayTimeMsgR("") - } -//--------------------------------------------------------------------------- - _currentButtonId() { - const root = this.shadowRoot; - const thisButtonId = root.getElementById("thisButtonId") - - return thisButtonId.innerText - } -//--------------------------------------------------------------------------- - _displayTimeMsgR(msg) { - // Display message before time field - const root = this.shadowRoot; - const hass = this._hass; - const eltInfoTime = root.getElementById("eltInfoTime") - const updateTimeAttr = hass.states['sensor.icloud3_event_log'].attributes['update_time'] - - //if (eltInfoTime.innerText.startsWith("●●")) { - //pass - if (msg == "") { - eltInfoTime.innerHTML = "Refreshed: " + updateTimeAttr - } else { - eltInfoTime.innerHTML = msg - } - } - - //--------------------------------------------------------------------------- - _displayNameMsgL(msg) { - /* Display test messages */ - const root = this.shadowRoot; - const eltInfoName = root.getElementById("eltInfoName") - eltInfoName.innerHTML = msg - } - - //--------------------------------------------------------------------------- - getCardSize() { - return 1; - } - -} - - -customElements.define('icloud3-event-log-card', iCloud3EventLogCard); diff --git a/development area - v2.2.1/pyicloud_ic3.py b/development area - v2.2.1/pyicloud_ic3.py deleted file mode 100644 index 4edea47..0000000 --- a/development area - v2.2.1/pyicloud_ic3.py +++ /dev/null @@ -1,924 +0,0 @@ -""" -Customized version of pyicloud.py to support iCloud3 Custom Component - -Platform that supports importing data from the iCloud Location Services -and Find My Friends api routines. Modifications to pyicloud were made -by various people to include: - - Original pyicloud - picklepete & Quantame - - https://github.com/picklepete - - - Updated and maintained by - Quantame - - - Find My Friends Update - Z Zeleznick - -The piclkepete version used imports for the services, utilities and exceptions -modules. They have been modified and are now maintained by Quantame & Z Zeleznick. -These modules have been incorporated into the pyicloud_ic3.py version used by iCloud3. -""" - -VERSION = '2.2.0' - -""" -8/20/20 - - Changed the _raise_error routine to catch the '2sa needed and missing WEB Cookie' error - to generate a Authentication error code rather than generating it's own 2SA Needed Exception -""" - -from six import PY2, string_types, text_type -from uuid import uuid1 -import inspect -import json -import logging -from requests import Session -import sys -from tempfile import gettempdir -from os import path, mkdir -from re import match -import http.cookiejar as cookielib - -LOGGER = logging.getLogger(__name__) - -#Device Status Codes -DEVICE_STATUS_ONLINE = 200 -DEVICE_STATUS_OFFLINE = 201 -DEVICE_STATUS_PENDING = 203 -DEVICE_STATUS_UNREGISTERED = 204 -AUTHENTICATION_REQUIRED = 450 -DEVICE_STATUS_ERROR = 500 - -''' -#Other Device Status Codes -SEND_MESSAGE_MSG_DISPLAYED = 200 -REMOTE_WIPE_STARTED = 200 -REMOVE_DEVICE_SUCCESS = 200 -UPDATE_LOCATION_PREF_SUCCESS = 200 -LOST_MODE_SUCCESS = 200 -PLAY_SOUND_SUCCESS = 200 -PLAY_SOUND_NEEDS_SAFETY_CONFIRM = 203 -SEND_MESSAGE_MSG_SENT = 205 -REMOTE_WIPE_SENT = 205 -LOST_MODE_SENT = 205 -LOCK_SENT = 205 -PLAY_SOUND_SENT = 205 -LOCK_SERVICE_FAILURE = 500 -SEND_MESSAGE_FAILURE = 500 -PLAY_SOUND_FAILURE = 500 -REMOTE_WIPE_FAILURE = 500 -UPDATE_LOCATION_PREF_FAILURE = 500 -LOCK_SUCC_PASSCODE_SET = 2200 -LOCK_SUCC_PASSCODE_NOT_SET_PASSCD_EXISTS = 2201 -LOCK_SUCCESSFUL_2 = 2204 -LOCK_FAIL_PASSCODE_NOT_SET_CONS_FAIL = 2403 -LOCK_FAIL_NO_PASSCD_2 = 2406 -''' - -class PyiCloudPasswordFilter(logging.Filter): - """Password log hider.""" - - def __init__(self, password): - super(PyiCloudPasswordFilter, self).__init__(password) - - def filter(self, record): - message = record.getMessage() - if self.name in message: - record.msg = message.replace(self.name, "*" * 8) - record.args = [] - - return True - - -class PyiCloudSession(Session): - """iCloud session.""" - - def __init__(self, service): - self.service = service - Session.__init__(self) - - def request(self, method, url, **kwargs): # pylint: disable=arguments-differ - - # Charge logging to the right service endpoint - callee = inspect.stack()[2] - module = inspect.getmodule(callee[0]) - request_logger = logging.getLogger(module.__name__).getChild("http") - if self.service.password_filter not in request_logger.filters: - request_logger.addFilter(self.service.password_filter) - - request_logger.debug(f"106 REQUEST -- {25*'-'}") - request_logger.debug(f"106 REQUEST -- {method}, {url}, {kwargs.get('data', '')}") - #request_logger.info(f"{method}, {url}, {kwargs.get("data", "")}"") - - kwargs_retry_flag = kwargs.get("retried", None) - kwargs.pop("retried", None) - - response = super(PyiCloudSession, self).request(method, url, **kwargs) - - request_logger.debug(f"115 RESPONSE -- {response}, StatusCode-{response.status_code}, okStatus-{response.ok}") - request_logger.debug(f"110 RESPONSE -- {25*'-'}") - - content_type = response.headers.get("Content-Type", "").split(";")[0] - json_mimetypes = ["application/json", "text/json"] - - kwargs_retry_flag = True - if not response.ok and content_type not in json_mimetypes: - try: - data = response.json() - request_logger.debug(f"120 RESPONSE ERROR DATA -- {data}") - except: - pass - - if (kwargs_retry_flag is None - and (response.status_code == AUTHENTICATION_REQUIRED - or response.status_code == DEVICE_STATUS_ERROR)): - message = (f"Reauthentication Required for Account: {self.service.user['apple_id']}") - request_logger.debug(f"133 MESSAGE -- {message}") - - api_error = PyiCloudAPIResponseException( - message, response.status_code, retry=True - ) - - request_logger.info(api_error) - kwargs["retried"] = True - return self.request(method, url, **kwargs) - - self._raise_error(response.status_code, response.reason) - - if content_type not in json_mimetypes: - return response - - try: - data = response.json() - except: # pylint: disable=bare-except - request_logger.warning("Failed to parse response with JSON mimetype") - return response - - #request_logger.debug(f"150 RESPONSE DATA -- {data}") - #request_logger.info(data) - - reason = data.get("errorMessage") - reason = reason or data.get("reason") - reason = reason or data.get("errorReason") - if not reason and isinstance(data.get("error"), string_types): - reason = data.get("error") - if not reason and data.get("error"): - reason = "Unknown reason" - - code = data.get("errorCode") - if not code and data.get("serverErrorCode"): - code = data.get("serverErrorCode") - - if reason: - self._raise_error(code, reason) - - return response - - def _raise_error(self, code, reason): - if (self.service.requires_2sa - and reason == "Missing X-APPLE-WEBAUTH-TOKEN cookie"): - code = AUTHENTICATION_REQUIRED - - if code == AUTHENTICATION_REQUIRED or code == DEVICE_STATUS_ERROR: - reason = (f"Authentication Required for Account: {self.service.user['apple_id']}") - api_error = PyiCloudAPIResponseException(reason, code) - #LOGGER.info(api_error) - - raise (api_error) - - elif (self.service.requires_2sa - and reason == "Missing X-APPLE-WEBAUTH-TOKEN cookie"): - raise PyiCloud2SARequiredException(self.service.user["apple_id"]) - - - elif code in ("ZONE_NOT_FOUND", "AUTHENTICATION_FAILED"): - reason = ("Please log into https://icloud.com/ to manually " - "finish setting up your iCloud service") - api_error = PyiCloudServiceNotActivatedException(reason, code) - LOGGER.error(api_error) - - raise (api_error) - - elif code == "ACCESS_DENIED": - reason += (". Please wait a few minutes then try again." - "The remote servers might be trying to throttle requests.") - - api_error = PyiCloudAPIResponseException(reason, code) - - LOGGER.error(api_error) - raise api_error - - -class PyiCloudService(object): - """ - A base authentication class for the iCloud service. Handles the - authentication required to access iCloud services. - - Usage: - from pyicloud import PyiCloudService - pyicloud = PyiCloudService('username@apple.com', 'password') - pyicloud.iphone.location() - """ - - HOME_ENDPOINT = "https://www.icloud.com" - SETUP_ENDPOINT = "https://setup.icloud.com/setup/ws/1" - #"logout_no_services": "https://setup.icloud.com/setup/ws/1/logout", - - def __init__( - self, - apple_id, - password=None, - cookie_directory=None, - verify=True, - client_id=None, - with_family=True, - ): - if password is None: - password = get_password_from_keyring(apple_id) - - self.data = {} - self.client_id = client_id or str(uuid1()).upper() - self.with_family = with_family - self.user = {"apple_id": apple_id, "password": password} - - self.password_filter = PyiCloudPasswordFilter(password) - LOGGER.addFilter(self.password_filter) - - self._base_login_url = f"{self.SETUP_ENDPOINT}/login" - - if cookie_directory: - self._cookie_directory = path.expanduser(path.normpath(cookie_directory)) - else: - self._cookie_directory = path.join(gettempdir(), "pyicloud") - - self.session = PyiCloudSession(self) - self.session.verify = verify - self.session.headers.update( - { - "Origin": self.HOME_ENDPOINT, - "Referer": f"{self.HOME_ENDPOINT}/", - "User-Agent": "Opera/9.52 (X11; Linux i686; U; en)", - } - ) - - cookiejar_path = self._get_cookiejar_path() - self.session.cookies = cookielib.LWPCookieJar(filename=cookiejar_path) - if path.exists(cookiejar_path): - try: - self.session.cookies.load() - LOGGER.debug(f"Read cookies from {cookiejar_path}") - except: # pylint: disable=bare-except - # Most likely a pickled cookiejar from earlier versions. - # The cookiejar will get replaced with a valid one after - # successful authentication. - LOGGER.warning(f"Failed to read cookiejar {cookiejar_path}") - - self.params = { - "clientBuildNumber": "17DHotfix5", - "clientMasteringNumber": "17DHotfix5", - "ckjsBuildVersion": "17DProjectDev77", - "ckjsVersion": "2.0.5", - "clientId": self.client_id, - } - - self.authenticate() - - self._files = None - self._photos = None - - def authenticate(self): - """ - Handles authentication, and persists the X-APPLE-WEB-KB cookie so that - subsequent logins will not cause additional e-mails from Apple. - """ - - LOGGER.info(f"Authenticating as {self.user['apple_id']}") - - data = dict(self.user) - - # We authenticate every time, so "remember me" is not needed - #data.update({"extended_login": False}) - data.update({"extended_login": True}) - - try: - req = self.session.post( - self._base_login_url, params=self.params, data=json.dumps(data) - ) - except PyiCloudAPIResponseException as error: - msg = "Invalid email/password combination." - raise PyiCloudFailedLoginException(msg, error) - - self.data = req.json() - self.params.update({"dsid": self.data["dsInfo"]["dsid"]}) - self._webservices = self.data["webservices"] - - if not path.exists(self._cookie_directory): - mkdir(self._cookie_directory) - self.session.cookies.save() - LOGGER.debug(f"Cookies saved to {self._get_cookiejar_path()}") - - LOGGER.info("Authentication completed successfully") - LOGGER.debug(self.params) - - def _get_cookiejar_path(self): - """Get path for cookiejar file.""" - return path.join( - self._cookie_directory, - "".join([c for c in self.user.get("apple_id") if match(r"\w", c)]), - ) - - @property - def requires_2sa(self): - """Returns True if two-step authentication is required.""" - return ( - self.data.get("hsaChallengeRequired", False) - and self.data["dsInfo"].get("hsaVersion", 0) >= 1 - ) - # FIXME: Implement 2FA for hsaVersion == 2 # pylint: disable=fixme - - @property - def trusted_devices(self): - """Returns devices trusted for two-step authentication.""" - request = self.session.get( - f"{self.SETUP_ENDPOINT}/listDevices", params=self.params - ) - return request.json().get("devices") - - def send_verification_code(self, device): - """Requests that a verification code is sent to the given device.""" - data = json.dumps(device) - request = self.session.post( - f"{self.SETUP_ENDPOINT}/sendVerificationCode", - params=self.params, - data=data, - ) - LOGGER.info(f"Send Trusted Device ID result-{request.json()}") - return request.json().get("success", False) - - #This is called from the iCloud3 in the _icloud_handle_verification_code_entry - #code routine - def validate_verification_code(self, device, code): - """Verifies a verification code received on a trusted device.""" - #LOGGER.info(f"Verification code-{code}") - device.update({'verificationCode': code, 'trustBrowser': True}) - data = json.dumps(device) - - try: - self.session.post( - f"{self.SETUP_ENDPOINT}/validateVerificationCode", - params=self.params, - data=data, - ) - except PyiCloudAPIResponseException as error: - LOGGER.info(f"Verification Error code-{error.code}") - if error.code == -21669: - # Wrong verification code - return False - #raise - - # Re-authenticate, which will both update the HSA data, and - # ensure that we save the X-APPLE-WEBAUTH-HSA-TRUST cookie. - self.authenticate() - - return not self.requires_2sa - - def logout(self): - """ Logout from iCloud """ - try: - req = self.session.post( - f"{self.SETUP_ENDPOINT}/logout", - params=self.params, - ) - except Exception as error: - msg = f"Error Logging out of Apple Web Services - {error}" - api_error = PyiCloudAPIResponseException(msg, 1) - LOGGER.error(api_error) - raise api_error - - def close_session(self): - """ Close current Session """ - try: - req = self.session.close() - - except Exception as error: - msg = f"Error Closing Session - {error}" - api_error = PyiCloudAPIResponseException(msg, 1) - LOGGER.error(api_error) - raise api_error - - - def _get_webservice_url(self, ws_key): - """Get webservice URL, raise an exception if not exists.""" - if self._webservices.get(ws_key) is None: - raise PyiCloudServiceNotActivatedException( - "Webservice not available", ws_key - ) - return self._webservices[ws_key]["url"] - -###################################################################### - @property - def devices(self): - """Returns all devices.""" - service_root = self._get_webservice_url("findme") - return FindMyiPhoneServiceManager( - service_root, self.session, self.params, self.with_family - ) - - @property - def friends(self): - """Gets the 'Friends' service.""" - service_root = self._get_webservice_url("fmf") - return FindFriendsService(service_root, self.session, self.params) - - @property - def contacts(self): - """Gets the 'Contacts' service.""" - service_root = self._get_webservice_url("contacts") - return ContactsService(service_root, self.session, self.params) - - def __unicode__(self): - return f"iCloud API: {self.user.get('apple_id')}" - - def __str__(self): - as_unicode = self.__unicode__() - if PY2: - return as_unicode.encode("utf-8", "ignore") - return as_unicode - - def __repr__(self): - return "<{str(self)}>" -#################################################################################### -# -# Find my iPhone service -# -#################################################################################### -"""Find my iPhone service.""" -#import json -#from six import PY2, text_type -#from pyicloud.exceptions import PyiCloudNoDevicesException - -class FindMyiPhoneServiceManager(object): - """The 'Find my iPhone' iCloud service - - This connects to iCloud and return phone data including the near-realtime - latitude and longitude. - """ - - def __init__(self, service_root, session, params, with_family=False): - self.session = session - self.params = params - self.with_family = with_family - - fmip_endpoint = f"{service_root}/fmipservice/client/web" - self._fmip_refresh_url = f"{fmip_endpoint}/refreshClient" - self._fmip_sound_url = f"{fmip_endpoint}/playSound" - self._fmip_message_url = f"{fmip_endpoint}/sendMessage" - self._fmip_lost_url = f"{fmip_endpoint}/lostDevice" - - self._devices = {} - self.refresh_client() - - def refresh_client(self): - """Refreshes the FindMyiPhoneService endpoint, - - This ensures that the location data is up-to-date. - - """ - req = self.session.post( - self._fmip_refresh_url, - params=self.params, - data=json.dumps( - { - "clientContext": { - "fmly": self.with_family, - "shouldLocate": True, - "selectedDevice": "all", - "deviceListVersion": 1, - } - } - ), - ) - self.response = req.json() - - for device_info in self.response["content"]: - device_id = device_info["id"] - if device_id not in self._devices: - self._devices[device_id] = AppleDevice( - device_info, - self.session, - self.params, - manager=self, - sound_url=self._fmip_sound_url, - lost_url=self._fmip_lost_url, - message_url=self._fmip_message_url, - ) - else: - self._devices[device_id].update(device_info) - - if not self._devices: - raise PyiCloudNoDevicesException() - - def __getitem__(self, key): - if isinstance(key, int): - if PY2: - key = self.keys()[key] - else: - key = list(self.keys())[key] - return self._devices[key] - - def __getattr__(self, attr): - return getattr(self._devices, attr) - - def __unicode__(self): - return text_type(self._devices) - - def __str__(self): - as_unicode = self.__unicode__() - if PY2: - return as_unicode.encode("utf-8", "ignore") - return as_unicode - - def __repr__(self): - return text_type(self) - - -class AppleDevice(object): - """Apple device.""" - - def __init__( - self, - content, - session, - params, - manager, - sound_url=None, - lost_url=None, - message_url=None, - ): - self.content = content - self.manager = manager - self.session = session - self.params = params - - self.sound_url = sound_url - self.lost_url = lost_url - self.message_url = message_url - - def update(self, data): - """Updates the device data.""" - self.content = data - - def location(self): - """Updates the device location.""" - self.manager.refresh_client() - return self.content["location"] - - def status(self, additional=[]): # pylint: disable=dangerous-default-value - """Returns status information for device. - - This returns only a subset of possible properties. - """ - self.manager.refresh_client() - fields = ["batteryLevel", "deviceDisplayName", "deviceStatus", "name"] - fields += additional - properties = {} - for field in fields: - properties[field] = self.content.get(field) - return properties - - def play_sound(self, subject="Find My iPhone Alert"): - """Send a request to the device to play a sound. - - It's possible to pass a custom message by changing the `subject`. - """ - data = json.dumps( - { - "device": self.content["id"], - "subject": subject, - "clientContext": {"fmly": True}, - } - ) - self.session.post(self.sound_url, params=self.params, data=data) - - def display_message( - self, subject="Find My iPhone Alert", message="This is a note", sounds=False - ): - """Send a request to the device to play a sound. - - It's possible to pass a custom message by changing the `subject`. - """ - data = json.dumps( - { - "device": self.content["id"], - "subject": subject, - "sound": sounds, - "userText": True, - "text": message, - } - ) - self.session.post(self.message_url, params=self.params, data=data) - - def lost_device( - self, number, text="This iPhone has been lost. Please call me.", newpasscode="" - ): - """Send a request to the device to trigger 'lost mode'. - - The device will show the message in `text`, and if a number has - been passed, then the person holding the device can call - the number without entering the passcode. - """ - data = json.dumps( - { - "text": text, - "userText": True, - "ownerNbr": number, - "lostModeEnabled": True, - "trackingEnabled": True, - "device": self.content["id"], - "passcode": newpasscode, - } - ) - self.session.post(self.lost_url, params=self.params, data=data) - - @property - def data(self): - """Gets the device data.""" - return self.content - - def __getitem__(self, key): - return self.content[key] - - def __getattr__(self, attr): - return getattr(self.content, attr) - - def __unicode__(self): - display_name = self["deviceDisplayName"] - name = self["name"] - return f"{display_name}: {name}" - - def __str__(self): - as_unicode = self.__unicode__() - if PY2: - return as_unicode.encode("utf-8", "ignore") - return as_unicode - - def __repr__(self): - return f"" -#################################################################################### -# -# Find my Friends service -# -#################################################################################### -"""Find my Friends service.""" -#from __future__ import absolute_import -#import json - -class FindFriendsService(object): - """ - The 'Find My' (FKA 'Find My Friends') iCloud service - - This connects to iCloud and returns friend data including - latitude and longitude. - """ - - def __init__(self, service_root, session, params): - self.session = session - self.params = params - self._service_root = service_root - #self._friend_endpoint = "%s/fmipservice/client/fmfWeb/initClient" % (self._service_root,) - self._friend_endpoint = f"{self._service_root}/fmipservice/client/fmfWeb/initClient" - self.refresh_always = False - self.response = {} - - def refresh_client(self): - """ - Refreshes all data from 'Find My' endpoint, - """ - params = dict(self.params) - # This is a request payload we mock to fetch the data - mock_payload = json.dumps( - { - "clientContext": { - "appVersion": "1.0", - "contextApp": "com.icloud.web.fmf", - "mapkitAvailable": True, - "productType": "fmfWeb", - "tileServer": "Apple", - "userInactivityTimeInMS": 537, - "windowInFocus": False, - "windowVisible": True, - }, - "dataContext": None, - "serverContext": None, - } - ) - req = self.session.post(self._friend_endpoint, data=mock_payload, params=params) - self.response = req.json() - - @staticmethod - def should_refresh_client_fnc(response): - """Function to override to set custom refresh behavior""" - return not response - - def should_refresh_client(self): - """ - Customizable logic to determine whether the data should be refreshed. - - By default, this returns False. - - Consumers can set `refresh_always` to True or assign their own function - that takes a single-argument (the last reponse) and returns a boolean. - """ - return self.refresh_always or FindFriendsService.should_refresh_client_fnc( - self.response - ) - - @property - def data(self): - """ - Convenience property to return data from the 'Find My' endpoint. - - Call `refresh_client()` before property access for latest data. - """ - if not self.response or self.should_refresh_client(): - self.refresh_client() - return self.response - - def contact_id_for(self, identifier, default=None): - """ - Returns the contact id of your friend with a given identifier - """ - lookup_key = "phones" - if "@" in identifier: - lookup_key = "emails" - - def matcher(item): - """Returns True iff the identifier matches""" - hit = item.get(lookup_key) - if not isinstance(hit, list): - return hit == identifier - return any([el for el in hit if el == identifier]) - - candidates = [ - item.get("id", default) for item in self.contact_details if matcher(item) - ] - if not candidates: - return default - return candidates[0] - - def location_of(self, contact_id, default=None): - """ - Returns the location of your friend with a given contact_id - """ - candidates = [ - item.get("location", default) - for item in self.locations - if item.get("id") == contact_id - ] - if not candidates: - return default - return candidates[0] - - @property - def locations(self): - """Returns a list of your friends' locations""" - return self.data.get("locations", []) - - @property - def followers(self): - """Returns a list of friends who follow you""" - return self.data.get("followers") - - @property - def following(self): - """Returns a list of friends who you follow""" - return self.data.get("following") - - @property - def contact_details(self): - """Returns a list of your friends contact details""" - return self.data.get("contactDetails") - - -#################################################################################### -# -# Exceptions (exceptions.py) -# -#################################################################################### -"""Library exceptions.""" - - -class PyiCloudException(Exception): - """Generic iCloud exception.""" - pass - - -# API -class PyiCloudAPIResponseException(PyiCloudException): - """iCloud response exception.""" - def __init__(self, reason, code=None, retry=False): - self.reason = reason - self.code = code - message = reason or "" - if code: - message += (f" (Error Code {code})") - if retry: - message += ". Retrying ..." - - super(PyiCloudAPIResponseException, self).__init__(message) - - -class PyiCloudServiceNotActivatedException(PyiCloudAPIResponseException): - """iCloud service not activated exception.""" - pass - - -# Login -class PyiCloudFailedLoginException(PyiCloudException): - """iCloud failed login exception.""" - pass - - -class PyiCloud2SARequiredException(PyiCloudException): - """iCloud 2SA required exception.""" - def __init__(self, apple_id): - message = f"Two-Step Authentication (2SA) Required for Account {apple_id}" - super(PyiCloud2SARequiredException, self).__init__(message) - - -class PyiCloudNoStoredPasswordAvailableException(PyiCloudException): - """iCloud no stored password exception.""" - pass - - -# Webservice specific -class PyiCloudNoDevicesException(PyiCloudException): - """iCloud no device exception.""" - pass - - -#################################################################################### -# -# Utilities (utils.py) -# -#################################################################################### -"""Utils.""" -import getpass -import keyring -import sys -#from .exceptions import PyiCloudNoStoredPasswordAvailableException - -KEYRING_SYSTEM = "pyicloud://icloud-password" - - -def get_password(username, interactive=sys.stdout.isatty()): - """Get the password from a username.""" - try: - return get_password_from_keyring(username) - except PyiCloudNoStoredPasswordAvailableException: - if not interactive: - raise - - return getpass.getpass( - "Enter iCloud password for {username}: ".format(username=username,) - ) - - -def password_exists_in_keyring(username): - """Return true if the password of a username exists in the keyring.""" - try: - get_password_from_keyring(username) - except PyiCloudNoStoredPasswordAvailableException: - return False - - return True - - -def get_password_from_keyring(username): - """Get the password from a username.""" - result = keyring.get_password(KEYRING_SYSTEM, username) - if result is None: - raise PyiCloudNoStoredPasswordAvailableException( - "No pyicloud password for {username} could be found " - "in the system keychain. Use the `--store-in-keyring` " - "command-line option for storing a password for this " - "username.".format(username=username,) - ) - - return result - - -def store_password_in_keyring(username, password): - """Store the password of a username.""" - return keyring.set_password(KEYRING_SYSTEM, username, password,) - - -def delete_password_in_keyring(username): - """Delete the password of a username.""" - return keyring.delete_password(KEYRING_SYSTEM, username,) - - -def underscore_to_camelcase(word, initial_capital=False): - """Transform a word to camelCase.""" - words = [x.capitalize() or "_" for x in word.split("_")] - if not initial_capital: - words[0] = words[0].lower() - - return "".join(words) diff --git a/icloud3.zip b/icloud3.zip index 36ebb84..3bc3a74 100644 Binary files a/icloud3.zip and b/icloud3.zip differ diff --git a/www/custom_cards/icloud3-event-log-card.js b/www/custom_cards/icloud3-event-log-card.js index 1f976da..3acebd7 100644 --- a/www/custom_cards/icloud3-event-log-card.js +++ b/www/custom_cards/icloud3-event-log-card.js @@ -12,247 +12,293 @@ // If they do not match, the one in the 'custom_components\icloud3' is copied // to the 'www\custom_cards' directory. // -// Version=2.2.0.10 (10/4/2020) +// Version=2.2.1.02 (11/01/2020) // ///////////////////////////////////////////////////////////////////////////// class iCloud3EventLogCard extends HTMLElement { constructor() { - super(); - this.attachShadow({ mode: 'open' }); + super() + this.attachShadow({ mode: 'open' }) } //--------------------------------------------------------------------------- setConfig(config) { - const version = "2.2.0.10" + const version = "2.2.1.02" const cardTitle = "iCloud3 Event Log" - const root = this.shadowRoot; - const hass = this._hass; + const root = this.shadowRoot + const hass = this._hass // Create card elements - const card = document.createElement('ha-card'); - const background = document.createElement('div'); - background.id = "background"; + const card = document.createElement('ha-card') + const background = document.createElement('div') + background.id = "background" // Title Bar - const titleBar = document.createElement("div"); - titleBar.id = "titleBar"; - const title = document.createElement("div"); - title.id = "title"; + const titleBar = document.createElement("div") + titleBar.id = "titleBar" + const title = document.createElement("div") + title.id = "title" title.textContent = cardTitle - const utilityBar = document.createElement("div"); - utilityBar.id = "utilityBar"; - const thisButtonId = document.createElement("div"); - thisButtonId.id = "thisButtonId"; - thisButtonId.classList.add("themeTextColor"); - thisButtonId.innerText = "setup"; - const logRecdCnt = document.createElement("div"); - logRecdCnt.id = "logRecdCnt"; - logRecdCnt.innerText = "-1"; - const devType = document.createElement("div"); - devType.id = "devType"; - devType.innerText = ""; - const hdrCellWidth = document.createElement("div"); - hdrCellWidth.id = "hdrCellWidth"; - hdrCellWidth.innerText = "0,66.7px,97.8px,94.4px,80px,70px,66.7px"; - const versionText = document.createElement("div"); - versionText.id = "versionText"; - versionText.style.setProperty('visibility', 'hidden'); - versionText.textContent = 'v' + version + //Utility base contains hidden variables + const utilityBar = document.createElement("div") + utilityBar.id = "utilityBar" + const thisButtonId = document.createElement("div") + thisButtonId.id = "thisButtonId" + thisButtonId.classList.add("themeTextColor") + thisButtonId.innerText = "setup" + const logRecdCnt = document.createElement("div") + logRecdCnt.id = "logRecdCnt" + logRecdCnt.innerText = "-1" + const devType = document.createElement("div") + devType.id = "devType" + devType.innerText = "" + const hdrCellWidth = document.createElement("div") + hdrCellWidth.id = "hdrCellWidth" + hdrCellWidth.innerText = "0,66.7px,97.8px,94.4px,80px,70px,66.7px" + const versionText = document.createElement("div") + versionText.id = "versionText" + versionText.innerText = version + + const infoText = document.createElement("div") + infoText.id = "infoText" + infoText.innerText = '' // Button Bar - const buttonBar = document.createElement("div"); - buttonBar.id = "buttonBar"; - buttonBar.class = "buttonBar"; + const buttonBar = document.createElement("div") + buttonBar.id = "buttonBar" + buttonBar.class = "buttonBar" // Name Buttons - const btnName0 = document.createElement('btnName'); - btnName0.id = "btnName0"; - btnName0.classList.add("btnBaseFormat"); - btnName0.style.setProperty('visibility', 'visible'); - btnName0.innerText = "Setup"; - const btnName1 = document.createElement('btnName'); - btnName1.id = "btnName1"; - btnName1.classList.add("btnBaseFormat"); - btnName1.classList.add("btnHidden"); - const btnName2 = document.createElement('btnName'); - btnName2.id = "btnName2"; - btnName2.classList.add("btnBaseFormat"); - btnName2.classList.add("btnHidden"); - const btnName3 = document.createElement('btnName'); - btnName3.id = "btnName3"; - btnName3.classList.add("btnBaseFormat"); - btnName3.classList.add("btnHidden"); - const btnName4 = document.createElement('btnName'); - btnName4.id = "btnName4"; - btnName4.classList.add("btnBaseFormat"); - btnName4.classList.add("btnHidden"); - const btnName5 = document.createElement('btnName'); - btnName5.id = "btnName5"; - btnName5.classList.add("btnBaseFormat"); - btnName5.classList.add("btnHidden"); - const btnName6 = document.createElement('btnName'); - btnName6.id = "btnName6"; - btnName6.classList.add("btnBaseFormat"); - btnName6.classList.add("btnHidden"); - const btnName7 = document.createElement('btnName'); - btnName7.id = "btnName7"; - btnName7.classList.add("btnBaseFormat"); - btnName7.classList.add("btnHidden"); - const btnName8 = document.createElement('btnName'); - btnName8.id = "btnName8"; - btnName8.classList.add("btnBaseFormat"); - btnName8.classList.add("btnHidden"); - const btnName9 = document.createElement('btnName'); - btnName9.id = "btnName9"; - btnName9.classList.add("btnBaseFormat"); - btnName9.classList.add("btnHidden"); + const btnName0 = document.createElement('btnName') + btnName0.id = "btnName0" + btnName0.classList.add("btnBaseFormat") + btnName0.style.setProperty('visibility', 'visible') + btnName0.innerText = "Setup" + const btnName1 = document.createElement('btnName') + btnName1.id = "btnName1" + btnName1.classList.add("btnBaseFormat") + btnName1.classList.add("btnHidden") + const btnName2 = document.createElement('btnName') + btnName2.id = "btnName2" + btnName2.classList.add("btnBaseFormat") + btnName2.classList.add("btnHidden") + const btnName3 = document.createElement('btnName') + btnName3.id = "btnName3" + btnName3.classList.add("btnBaseFormat") + btnName3.classList.add("btnHidden") + const btnName4 = document.createElement('btnName') + btnName4.id = "btnName4" + btnName4.classList.add("btnBaseFormat") + btnName4.classList.add("btnHidden") + const btnName5 = document.createElement('btnName') + btnName5.id = "btnName5" + btnName5.classList.add("btnBaseFormat") + btnName5.classList.add("btnHidden") + const btnName6 = document.createElement('btnName') + btnName6.id = "btnName6" + btnName6.classList.add("btnBaseFormat") + btnName6.classList.add("btnHidden") + const btnName7 = document.createElement('btnName') + btnName7.id = "btnName7" + btnName7.classList.add("btnBaseFormat") + btnName7.classList.add("btnHidden") + const btnName8 = document.createElement('btnName') + btnName8.id = "btnName8" + btnName8.classList.add("btnBaseFormat") + btnName8.classList.add("btnHidden") + const btnName9 = document.createElement('btnName') + btnName9.id = "btnName9" + btnName9.classList.add("btnBaseFormat") + btnName9.classList.add("btnHidden") /* Action Select Box */ - const btnAction = document.createElement('select'); - btnAction.id = "btnAction"; - btnAction.style.setProperty('visibility', 'visible'); - btnAction.setDefault; - btnAction.classList.add("btnBaseFormat"); - btnAction.classList.add("btnAction"); - - var btnActionOptA = document.createElement("option"); - var btnActionOptATxt = document.createTextNode("Actions"); - btnActionOptA.setAttribute("value", "action"); - btnActionOptA.setAttribute("id", "optAction"); - btnActionOptA.classList.add("btnActionOptionTransparent"); - btnActionOptA.appendChild(btnActionOptATxt); - btnAction.appendChild(btnActionOptA); - - var btnActionOptG = document.createElement("optGroup"); - btnActionOptG.setAttribute("label", "———— Global Actions ————"); - btnActionOptG.classList.add("btnActionOptionGroup"); - btnAction.appendChild(btnActionOptG); - - var btnActionOptG1 = document.createElement("option"); - var btnActionOptG1Txt = document.createTextNode("Restart iCloud3"); - btnActionOptG1.setAttribute("value", "restart"); - btnActionOptG1.classList.add("btnActionOption"); - btnActionOptG1.appendChild(btnActionOptG1Txt); - btnAction.appendChild(btnActionOptG1); - - var btnActionOptG2 = document.createElement("option"); - var btnActionOptG2Txt = document.createTextNode("Pause Polling"); - btnActionOptG2.setAttribute("value", "pause"); - btnActionOptG2.classList.add("btnActionOption"); - btnActionOptG2.appendChild(btnActionOptG2Txt); - btnAction.appendChild(btnActionOptG2); - - var btnActionOptG3 = document.createElement("option"); - var btnActionOptG3Txt = document.createTextNode("Resume Polling"); - btnActionOptG3.setAttribute("value", "resume"); - btnActionOptG3.classList.add("btnActionOption"); - btnActionOptG3.appendChild(btnActionOptG3Txt); - btnAction.appendChild(btnActionOptG3); - - var btnActionOptG7 = document.createElement("option"); - var btnActionOptG7Txt = document.createTextNode("Request iOS App Locations"); - btnActionOptG7.setAttribute("value", "location"); - btnActionOptG7.classList.add("btnActionOption"); - btnActionOptG7.appendChild(btnActionOptG7Txt); - btnAction.appendChild(btnActionOptG7); - - var btnActionOptG4 = document.createElement("option"); - var btnActionOptG4Txt = document.createTextNode("Show Tracking Monitors"); - btnActionOptG4.setAttribute("value", "dev-log_level: eventlog"); - btnActionOptG4.setAttribute("id", "optEvlog"); - btnActionOptG4.classList.add("btnActionOption"); - btnActionOptG4.appendChild(btnActionOptG4Txt); - btnAction.appendChild(btnActionOptG4); - - var btnActionOptG8 = document.createElement("option"); - var btnActionOptG8Txt = document.createTextNode("Show Startup Log, Errors & Alerts"); - btnActionOptG8.setAttribute("value", "dev-refresh_event_log"); - btnActionOptG8.setAttribute("id", "optStartuplog"); - btnActionOptG8.classList.add("btnActionOption"); - btnActionOptG8.appendChild(btnActionOptG8Txt); - btnAction.appendChild(btnActionOptG8); - - var btnActionOptG5 = document.createElement("option"); - var btnActionOptG5Txt = document.createTextNode("Export Event Log"); - btnActionOptG5.setAttribute("value", "dev-export_event_log"); - btnActionOptG5.classList.add("btnActionOption"); - btnActionOptG5.appendChild(btnActionOptG5Txt); - btnAction.appendChild(btnActionOptG5); - - var btnActionOptG6 = document.createElement("option"); - var btnActionOptG6Txt = document.createTextNode("Start HA Debug Logging"); - btnActionOptG6.setAttribute("value", "dev-log_level: debug"); - btnActionOptG6.setAttribute("id", "optHalog"); - btnActionOptG6.classList.add("btnActionOption"); - btnActionOptG6.appendChild(btnActionOptG6Txt); - btnAction.appendChild(btnActionOptG6); + const btnAction = document.createElement('select') + btnAction.id = "btnAction" + btnAction.style.setProperty('visibility', 'visible') + btnAction.setDefault + btnAction.classList.add("btnBaseFormat") + btnAction.classList.add("btnAction") + + var btnActionOptA = document.createElement("option") + var btnActionOptATxt = document.createTextNode("Actions") + btnActionOptA.setAttribute("value", "action") + btnActionOptA.setAttribute("id", "optAction") + btnActionOptA.classList.add("btnActionOptionTransparent") + btnActionOptA.appendChild(btnActionOptATxt) + btnAction.appendChild(btnActionOptA) + + var btnActionOptG = document.createElement("optGroup") + btnActionOptG.setAttribute("label", "———— Global Actions ————") + btnActionOptG.classList.add("btnActionOptionGroup") + btnAction.appendChild(btnActionOptG) + + var btnActionOptG1 = document.createElement("option") + var btnActionOptG1Txt = document.createTextNode("Restart iCloud3") + btnActionOptG1.setAttribute("value", "restart") + btnActionOptG1.classList.add("btnActionOption") + btnActionOptG1.appendChild(btnActionOptG1Txt) + btnAction.appendChild(btnActionOptG1) + + var btnActionOptG2 = document.createElement("option") + var btnActionOptG2Txt = document.createTextNode("Pause Polling") + btnActionOptG2.setAttribute("value", "pause") + btnActionOptG2.classList.add("btnActionOption") + btnActionOptG2.appendChild(btnActionOptG2Txt) + btnAction.appendChild(btnActionOptG2) + + var btnActionOptG3 = document.createElement("option") + var btnActionOptG3Txt = document.createTextNode("Resume Polling") + btnActionOptG3.setAttribute("value", "resume") + btnActionOptG3.classList.add("btnActionOption") + btnActionOptG3.appendChild(btnActionOptG3Txt) + btnAction.appendChild(btnActionOptG3) + + var btnActionOptG7 = document.createElement("option") + var btnActionOptG7Txt = document.createTextNode("Update All Locations") + btnActionOptG7.setAttribute("value", "location") + btnActionOptG7.classList.add("btnActionOption") + btnActionOptG7.appendChild(btnActionOptG7Txt) + btnAction.appendChild(btnActionOptG7) + + var btnActionOptG4 = document.createElement("option") + var btnActionOptG4Txt = document.createTextNode("Show Tracking Monitors") + btnActionOptG4.setAttribute("value", "dev-log_level: eventlog") + btnActionOptG4.setAttribute("id", "optEvlog") + btnActionOptG4.classList.add("btnActionOption") + btnActionOptG4.appendChild(btnActionOptG4Txt) + btnAction.appendChild(btnActionOptG4) + + var btnActionOptG8 = document.createElement("option") + var btnActionOptG8Txt = document.createTextNode("Show Startup Log, Errors & Alerts") + btnActionOptG8.setAttribute("value", "dev-refresh_event_log") + btnActionOptG8.setAttribute("id", "optStartuplog") + btnActionOptG8.classList.add("btnActionOption") + btnActionOptG8.appendChild(btnActionOptG8Txt) + btnAction.appendChild(btnActionOptG8) + + var btnActionOptG5 = document.createElement("option") + var btnActionOptG5Txt = document.createTextNode("Export Event Log") + btnActionOptG5.setAttribute("value", "dev-export_event_log") + btnActionOptG5.classList.add("btnActionOption") + btnActionOptG5.appendChild(btnActionOptG5Txt) + btnAction.appendChild(btnActionOptG5) + + var btnActionOptG6 = document.createElement("option") + var btnActionOptG6Txt = document.createTextNode("Start HA Debug Logging") + btnActionOptG6.setAttribute("value", "dev-log_level: debug") + btnActionOptG6.setAttribute("id", "optHalog") + btnActionOptG6.classList.add("btnActionOption") + btnActionOptG6.appendChild(btnActionOptG6Txt) + btnAction.appendChild(btnActionOptG6) //--------------------------------------------------------- - var btnActionOptD = document.createElement("optGroup"); - btnActionOptD.setAttribute("label", "———— Device Actions ————"); - btnActionOptD.classList.add("btnActionOptionGroup"); - btnAction.appendChild(btnActionOptD); - - var btnActionOptD1 = document.createElement("option"); - var btnActionOptD1Txt = document.createTextNode("Pause Polling"); - btnActionOptD1.setAttribute("value", "dev-pause"); - btnActionOptD1.classList.add("btnActionOption"); - btnActionOptD1.appendChild(btnActionOptD1Txt); - btnAction.appendChild(btnActionOptD1); - - var btnActionOptD2 = document.createElement("option"); - var btnActionOptD2Txt = document.createTextNode("Resume Polling"); - btnActionOptD2.setAttribute("value", "dev-resume"); - btnActionOptD2.classList.add("btnActionOption"); - btnActionOptD2.appendChild(btnActionOptD2Txt); - btnAction.appendChild(btnActionOptD2); - - var btnActionOptD3 = document.createElement("option"); - var btnActionOptD3Txt = document.createTextNode("Request iOS App Location"); - btnActionOptD3.setAttribute("value", "dev-location"); - btnActionOptD3.classList.add("btnActionOption"); - btnActionOptD3.appendChild(btnActionOptD3Txt); - btnAction.appendChild(btnActionOptD3); - - var btnActionOptBL = document.createElement("option"); - var btnActionOptBLTxt = document.createTextNode(""); - btnActionOptBL.classList.add("btnActionOption"); + var btnActionOptD = document.createElement("optGroup") + btnActionOptD.setAttribute("label", "———— Selected Phone ————") + btnActionOptD.classList.add("btnActionOptionGroup") + btnAction.appendChild(btnActionOptD) + + var btnActionOptD1 = document.createElement("option") + var btnActionOptD1Txt = document.createTextNode("Pause Polling") + btnActionOptD1.setAttribute("value", "dev-pause") + btnActionOptD1.classList.add("btnActionOption") + btnActionOptD1.appendChild(btnActionOptD1Txt) + btnAction.appendChild(btnActionOptD1) + + var btnActionOptD2 = document.createElement("option") + var btnActionOptD2Txt = document.createTextNode("Resume Polling") + btnActionOptD2.setAttribute("value", "dev-resume") + btnActionOptD2.classList.add("btnActionOption") + btnActionOptD2.appendChild(btnActionOptD2Txt) + btnAction.appendChild(btnActionOptD2) + + var btnActionOptD3 = document.createElement("option") + var btnActionOptD3Txt = document.createTextNode("Update Phone's Location") + btnActionOptD3.setAttribute("value", "dev-location") + btnActionOptD3.classList.add("btnActionOption") + btnActionOptD3.appendChild(btnActionOptD3Txt) + btnAction.appendChild(btnActionOptD3) + + var btnActionOptBL = document.createElement("option") + var btnActionOptBLTxt = document.createTextNode("") + btnActionOptBL.classList.add("btnActionOption") btnActionOptBL.appendChild(btnActionOptBLTxt) - btnAction.appendChild(btnActionOptBL); - var btnActionOptV = document.createElement("optGroup"); - btnActionOptV.setAttribute("label", "—— Event Log v"+version+" ———"); - btnActionOptV.classList.add("btnActionOptionGroup"); - btnAction.appendChild(btnActionOptV); + btnAction.appendChild(btnActionOptBL) + var btnActionOptV = document.createElement("optGroup") + btnActionOptV.setAttribute("label", "—— Event Log v"+version+" ———") + btnActionOptV.classList.add("btnActionOptionGroup") + btnAction.appendChild(btnActionOptV) //------------------------------------------------------------- - const btnRefresh = document.createElement('btnName'); - btnRefresh.id = "btnRefresh"; - btnRefresh.classList.add("btnRefresh"); - btnRefresh.style.setProperty('visibility', 'visible'); - btnRefresh.innerHTML=`` + var btnHelpIcon24 = document.createElement('IMG') + btnHelpIcon24.id = "btnHelpIcon24" + btnHelpIcon24.setAttribute("alt", "iCloud3 Documentation") + //btnHelpIcon24.style.setProperty('visibility', 'visible') + btnHelpIcon24.setAttribute("src", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAYCAYAAADkgu3FAAAEEElEQVRIS72WfUzUZRzAP7zccefB8fY7DhDwmIgY/2S2dC1QBDFXbNp8bxlGNl9oDUyjmvhS4ZhQKIQvCVe4Nhthjj9glQqVscbmJNecJAZXdLyI3h0HCNzBtYN+7Afd8dJaz7/fl8/z/T7fl8eD/+l4zMRJB4VcQUi4D7HJamKDZfj9YcdU30tz3xD3Gh7RdQNsM/lxC1oF3k+peeJAKBmCjNUOB5pBsNjALhtFrvTEF+g0DFN7sgP9R/38AjjcAV2C3lCh3aMlZ7GKHW1D3HkwxLUOGzd+tdPaPkh/lBx1vDcLgxU8Od+HZK2MqIY+SivNFBWZMbuC/QP0ui+P5UeiV3oh1Js5ntXOl024NnY6TFcR+koQ2xICeNNq49bRTnYXmjFMhU0CHVQSkbeAS22j2Mq72Zdnpkk0KAokaqvABpuDeBk0numk+kgf3aL8vIbEjRo+ljkw5LaTXmilRwqbAK0CRfkiTkbIWPmhkS05Zn4WFd8PYMGrApdH4HEvD4btDuTAtdIOtuf10yXqVWpJ3hjC51etnE1p4xgwIsomQIUCSdmhVH3zkD1rjXwhKqwDn/IY8kYh2zxCldHGdzo565WerPaC/LAWcqQ3/0FHzjN+HDjaTtIRE7cmgV4CVdliyv4cJTD6LuuAUVFhOWirYjDIPbjbOETi879jqtOhW+LNdRuoI1tQS0Gv+SF8EMHVIRtXdrXwTi0MOeVjEW3xYeHFWL5vsnJiaRtFUsPrkYQvUXDxvp36uFZynbK6+UTEKWmwg19kC4FTH745moLYeaTtMJBw4e93HAOdEUh7Wcun+h6e29vFT5NuCLKAeWjMA/SfA0uFFlWiL+e9PdjqKnVO29owNqQGo9/ZSmJF/3j6xkBN0WTqFBxMMrDi5gDG6brcGEOBA/aPOCg5YeLd4of0TtUvEFi2T0tN6QN27u+kZs6gc8GkrA+iCgc/Hr7Pi6ctmFxdSgTpu9i1t4fqCdB0qZM6qgknc5mK4h47m+NbqXQX+UTqfiOpYoCbsyoGqbPb0RyKlHPseCepeRa+dQdyWwzTlbfU2TY58WsCSLzcz6VqSaPOurydiu4aVuok1581qWoyL5h4+2wft11FNG3DOg2mG0GiQ71A9qZgCgs7ePZwL19PBc1qBDmNpEP1s24y3zOPP6R4PtGQsCmI7cWdFByycE8qKxdY+UIIJTMOVdFoYk14oKm3UnjKROVXkik9NYocBbq0EDY/7U+W1UbTrNaE6MS5+HZreStORUbHMM3GR1zpsNM4dfEJSpbH+LDWz5uwhl5KKnvnsPhEmHOVr1CzNEtLRoiMFAcILlZ5l2GQmtPdlOWPF8fcVrk0PeLnRPBhUYI/MZGe+BtHsdT1cuc/+ZxMN+/+jewvN+q9KPbla94AAAAASUVORK5CYII=") + + var btnHelpIcon24Hover = document.createElement('IMG') + btnHelpIcon24Hover.id = "btnHelpIcon24Hover" + btnHelpIcon24Hover.setAttribute("alt", "iCloud3 Documentation") + btnHelpIcon24Hover.classList.add("btnHidden") + btnHelpIcon24Hover.setAttribute("src", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAYCAYAAADkgu3FAAAELUlEQVRIS72Wf0zUdRjHXwRc3kiUeSASB5RGKIv5a0FNjt8YphsYqNA08AdThBmQRhqgaMgJVxCIiMApyq8IcdSOmT+gNNZoyMWckxxLlvHDNCB1kw6OdrA77vjN1vr++zzv5/V9ns/zeZ6PEf/TZzQtxzN8DmKBFfNtHHnLxxHzBXPp/L2HW/WtqJ620dzQTVOTaro4k4M8PU1wenMlW/fvYJ7Im6EhS/qf9zGgGsDEVIBQ+BLQRVd7LRVZcvK/uA0MTQacGLRz30I27knA9vVtdN2/S9/j6/R1NnHv19949OAZYjtzXnVejNmC1Vi+7IPFQjtaGnK5UpnJ2czeiWDjQRExy4iRyjEVilDWH0cW+zVK5YTi4YAh4dYEbg/lDfePeP6khdNHdlMoax8LMwTFHLAlMvUiD+6r+KZoL7mpSp0gOdMO3y1BqFTOmJg2UppXQ97hhzp7WoEESfBJBKbt5CeFky97pA8bBXl6zuFQURYiWw/KP9+MNOEXnWP8MXsCd15CPbicF4z/YXBAAFynOjeMrNRunV9OpQ+S4BIar51mp28KMKi1jYIOyrwIjavi5+/2sH1thU4cEPAiB4tSUavjeNpbxcOO77F2CEQo9MbYWIr7ogSDMl24kYDLmv0UHvEi63CLIch/qxnphYV0/2GB/ysBgFondnVdiLSqHYHgHspGCVHreyirc8B26U0GVOZ4ic0NQKGRIqI+u8Zg/1Wkuw5SW9uvsY9kFLh5MSnlP9CmTCdoRaaBsOymDfZLy+n9s551TknDtgt1ttg7NTAwMBcvscW4LlO0ZmDnuIHEbe5Unx8+xxHQsbwNrPvgLAr5u3wa9ZOBMDLSFMF8S7p7n1GZ30d6sRkrJQUYm2zByFiKx5jSacTnaoNY7i8nLUJCWfFw+UZA1cporB0OEO7lRmtzx5S3/EZHBuqheNSDORSkH6Ik++9x/gkZqwjeq6AiN4L0eMXsQUfzffEOrMKIH8lJfp/SUz0T/pQWVCvfRWJUzcxKpx+pQBGN06pseh9tYr1z5aSZa0uXEuFFVXHzzJpBP5riTiJW4hTkx/05mXplUtCkzTBVe+tHey/UGVc/CTcvXaSmZvSi6vtM2d4ax8kurH6QfUl+uPlH8+35Tyg5fWfCjKa8sBrFVCNIGzFNHodfiIxS2TvIki+PA81oBGlU+kNVcS6a7KPDB6n7Us+44xcSxlfZGaQnthnYThR5sGZjzvRDVavSrgmB0JJb9TKqv6ykunp0So9N48MEB1Zv2ITL27E8f6Kc2ZrQBtEsvqDdHyN22sHjzlb+6rhKT2fj+MUnckW8ZC3CuYu43ZDD5dksPi1Ms8qXua0gLHYHFla+qIdEE6zybrraFZSfKuSMVNMcs1zl+uXRPk7MRa/h4r4EG/E8ujv6aKq7+988TqYceLM3/gvZOcgoRP8sgAAAAABJRU5ErkJggg==") + + const btnHelp = document.createElement('A') + btnHelp.id = "btnHelp" + btnHelp.classList.add("btnHelp") + btnHelp.style.setProperty('visibility', 'visible') + btnHelp.setAttribute('href', 'https://gcobb321.github.io/icloud3/#/') + btnHelp.setAttribute('target', '_blank') + btnHelp.appendChild(btnHelpIcon24) + btnHelp.appendChild(btnHelpIcon24Hover) + + //btnHelp.innerHTML=`` + + //------------------------------------------------------------- + var btnRefreshIcon24 = document.createElement('IMG') + btnRefreshIcon24.id = "btnRefreshIcon24" + btnRefreshIcon24.setAttribute("alt", "Refresh") + //btnRefreshIcon24.style.setProperty('visibility', 'visible') + btnRefreshIcon24.setAttribute("src", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAYCAYAAADkgu3FAAADLUlEQVRIS72WbWhTVxjHf6lJkxCT+HKTW7W6ltoXt0+V4UR0Wis4cf2gyMQPumJRdFNGfS37sFnHFHHRKr5ssLZuIijx5YusbLRaFcoQirGINE63RGvS1rrG3lSbJubKrU1Im5Q0Ejzf7jnPc37n+Z/nPs9R8Z6GKhmnHHSZOqzTtRSUmiiYqsH4JERvcx9Of4BHLa/oaoVgsn3GBC0B9TwTc3dnUSFoWCrLWAbgRRBCmjCZ+gwmAp3uQRqOeak/2s89QB4LmBD0jQFxq0hVoYENrgDtzwNc8wZpfRDiv44B+mdlYvpITd5UHR/P0FIqapjV4ueU3UdNjQ9fIlgcaPtEPjw0k3r9BIRmHwcrO7joILGzsmG5gayNU1i3aBK7pCBtpnZWKPP+OVxXqbhpuM/3yvcI0B492Qc+4LIrTLCum68P+HAk0z6y/quFT9dYOKmRcXtDTBfVSBkyhw3tXB0BWgK6unyOZWtYfMTD2iofd8cLidjZRUo/m8KfKngEeFQytjiQTaBkRxaX/vqfrcs9XEgVMiyXc1glJSniQevBUFtI7dMwk3P/GdI4nCpImsMNVYyfDBlx0q3Vkne+gJsOicPFLmpShSj2/UV8PtqvM4Q57yHnonf0s0DZlyJn6ntY+VUXf78LKJnPUNY5ctmWo2NPiZv5d17iSeY0nvVnhRgVO4sTKRpRukFHstEXq5H/9aOp6IkBpVu6hmmsmmzOvHzq8eDc319yJxpROpIhVk5nLj9NMqh37nKFxLN+uqOgdKR3BLTZiPBjNk2BII2bHvJtAwRGVIZ0/LDKhrdyqFpoZHd1ByX7emmLHCBa69JVgtZYOdck8csyF/uB13EgZSK2qP7WzbYffG8vcjyjTmDxaisnlKL6XQflNomeWL+x24QKS7OE7Xgv9ivDF5oIWKUjp8zKFwvMVEpBHNWdbLH5cI+2HbPxbRHZW2SgwjuI0/OKRm+I26Mbn6Dnk9lalhvVTGvp44S9L4XGFzmJ0srnmyiuFKmwalgmg5CglXe5B/jjdDe1h/zcT7mVx4YdeZwIWvIXmZk9MwOzJ8yL6320p+VxMp4ESMXmDVKARSiFsInBAAAAAElFTkSuQmCC") + + var btnRefreshIcon24Hover = document.createElement('IMG') + btnRefreshIcon24Hover.id = "btnRefreshIcon24Hover" + btnRefreshIcon24Hover.setAttribute("alt", "Refresh") + btnRefreshIcon24Hover.classList.add("btnHidden") + //btnRefreshIcon24Hover.style.setProperty('visibility', 'hidden') + btnRefreshIcon24Hover.setAttribute("src", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAYCAYAAADkgu3FAAADLklEQVRIS72Wa0iTYRTHf6+50Vhq4swyF5XdKBIssQtmMyO7QkYXDCrLim5SdpWKSruarbTMypp2BcNsHwqli2kXJIzlkohWWEnlptlFVqBpLbZYm22ii9Hz7X3ec87vPec57/k/Av9pCR1yFPFdkYt70D1wEGOiB+Ht54X+7Wcel+lo+VpNZXkdGk1LR3HaBykUngwJH8GCTQn4yCZgMvnT3NRIa0srniIxEkk3wIChppjLmXnkHHkKmNoDOgctXRvArJXJBA1eiOHNcxo/3qFRr+Hli9c0vPuGvI83/YcFI/ULw793NL4Bfagqz+ZWQQZnM744gzmCFicOJTEtD5FEhrZsP8qkK2i1Tp0tAefE92TmkjiGj9tIk7GKcO8plv1HX0sRhHuESXeaH9uCEjcHsXzfVd69aeFa7mqy92k7qv2f9wfORBI5+zhiUQ0f9IH4BRjp4pHOSOn1tiCFoivbcjORBY0n//A80pKfdBpiNcwqiCZ88g0EoRqoxUNQOoK2KqOIW1/Io5srWRJz2WXI73LpEBAwWZrCCWjSAinpKhV1732Z1M9c458ugyqMdxEEm5/J5OFYupnzgknNv0e1Np3Y0AyXIWYHzbfpDn4NBh9igi/ZzmjPyRlMXXSWorxpbF/18J9AHTj97jq1dg09+24mPmo0uspat4AefPCyxInwN9oycjco6bCEkFAT9a9EbEmwA7m7dOeKY8Ui36vfC7NHUHi+0paRO5rBvt5FukOe0u4bWjM2BqC+UG8DuaO9raC45TJW7S3hR/Nt0pZtpbi4ue1kcMcPa4548X4yIRGbUKVEkbmrysq3zTp3jaDI2ZeoKDnF0ompwA9HkHnHfqgWnVvDsd2Wg+zUOpg7nohZWZahmrMjnhxlg71f+zIhlvjzuEyJ+mgBarXlQJ2udcl9CZsxl5CxSTQZtZxKWYFKWfO3bfvCF7tiC/IhCXzU6/hUe5vP+gpH4ZONQj4gBolXL56WZ3HDFeGzfopZyoeODmV+UgK+PSby0yRzIuV1GGqKyD+h4nTaM9el3D5v6+XEWzaQkHEDCJT7UFfbiKb0uXsuJ53qgM4b/QIdc0go4VmAXgAAAABJRU5ErkJggg==") + + const btnRefresh = document.createElement('btnName') + btnRefresh.id = "btnRefresh" + btnRefresh.classList.add("btnRefresh") + btnRefresh.style.setProperty('visibility', 'visible') + btnRefresh.appendChild(btnRefreshIcon24) + btnRefresh.appendChild(btnRefreshIcon24Hover) + + //btnRefresh.innerHTML=`` + // Message Bar - const eltInfoBar = document.createElement("div"); - eltInfoBar.id = "eltInfoBar"; - - const eltInfoName = document.createElement("div"); - eltInfoName.id = "eltInfoName"; - eltInfoName.innerText = "Select Person"; - eltInfoName.style.color = "firebrick" - - const eltInfoTime = document.createElement("div"); - eltInfoTime.id = "eltInfoTime"; - eltInfoTime.innerText = "setup"; - eltInfoTime.style.color = "firebrick" - - const eltInfoMsgPopup = document.createElement("div"); - eltInfoMsgPopup.id = "eltInfoMsgPopup"; - eltInfoMsgPopup.classList.add("eltInfoMsgPopup"); - eltInfoMsgPopup.classList.add("eltInfoMsgPopupHidden"); - eltInfoMsgPopup.style.setProperty('zIndex', '9999'); - - const tblEvlogContainer = document.createElement("div"); + const statusBar = document.createElement("div") + statusBar.id = "statusBar" + + const statusName = document.createElement("div") + statusName.id = "statusName" + statusName.innerText = "Select Person" + statusName.style.color = "firebrick" + + const statusTime = document.createElement("div") + statusTime.id = "statusTime" + statusTime.innerText = "setup" + statusTime.style.color = "firebrick" + + const statusMsgPopup = document.createElement("div") + statusMsgPopup.id = "statusMsgPopup" + statusMsgPopup.classList.add("statusMsgPopup") + statusMsgPopup.classList.add("statusMsgPopupHidden") + statusMsgPopup.style.setProperty('zIndex', '9999') + + //Event Table + const tblEvlogContainer = document.createElement("div") tblEvlogContainer.id = "tblEvlogContainer" const tblEvlog = document.createElement("TABLE") @@ -268,7 +314,7 @@ class iCloud3EventLogCard extends HTMLElement { tblEvlogBody.classList.add("tblEvlogBody") // Style - const cssStyle = document.createElement('style'); + const cssStyle = document.createElement('style') cssStyle.textContent = ` /* Text special colors */ .blue {color: blue;} @@ -365,16 +411,15 @@ class iCloud3EventLogCard extends HTMLElement { width: 100%; /*border: 1px solid dodgerblue;*/ } - #thisButtonId, #logRecdCnt, #devType, #hdrCellWidth { + #thisButtonId, #logRecdCnt, #devType, #hdrCellWidth, #versionText { /*font-size: 2px;*/ color: transparent; - width: 25px; + width: 5px; float: left; /*border: 1px solid green;*/ } - - #versionText { - color: silver; + #infoText { + color: dodgerblue; float: right; } @@ -385,12 +430,12 @@ class iCloud3EventLogCard extends HTMLElement { } /* Message Bar setup */ - #eltInfoBar { + #statusBar { position: relative; width: 100%; /*border: 1px solid dodgerblue;*/ } - #eltInfoName { + #statusName { width: 40%; color: firebrick; float: left; @@ -399,7 +444,7 @@ class iCloud3EventLogCard extends HTMLElement { margin: 2px 0px 4px 0px; /*border: 1px solid var(--label-badge-red);*/ } - #eltInfoTime { + #statusTime { margin: 2px 2px 4px 0px; color: firebrick; float: right; @@ -407,7 +452,7 @@ class iCloud3EventLogCard extends HTMLElement { font-weight: 400; /*border: 1px solid green;*/ } - .eltInfoMsgPopup { + .statusMsgPopup { position: relative; width: 85%; margin-left: auto; @@ -422,7 +467,7 @@ class iCloud3EventLogCard extends HTMLElement { -moz-box-shadow: 5px 5px 23px 3px rgba(0,0,0,0.75); box-shadow: 3px 3px 20px 3px rgba(0,0,0,0.75); } - .eltInfoMsgPopupHidden { + .statusMsgPopupHidden { height: 0px; width: 0px; visibility: hidden; @@ -561,17 +606,35 @@ class iCloud3EventLogCard extends HTMLElement { } .btnHover {border: 1px solid var(--primary-color);} + /* Helph Select Button */ + #btnHelp { + display: inline-block; + visibility: visible; + color: var(--primary-text-color); + background-color: transparent; + /*height: 28px;*/ + /*width: 30px;*/ + margin: 0px 0px 0px 4px; + float: right; + } + .btnHelp { + border: 0px solid transparent; + background-color: transparent; + box-shadow: transparent; + } + /* Refresh Select Button */ #btnRefresh { display: inline-block; visibility: visible; color: var(--primary-text-color); background-color: transparent; - height: 24px; - margin: -4px 2px; + /*height: 28px;*/ + /*width: 30px;*/ + margin: 0px 0px 0px 4px; float: right; - box-sizing: border-box; } + .btnRefresh { border: 0px solid transparent; background-color: transparent; @@ -655,37 +718,39 @@ class iCloud3EventLogCard extends HTMLElement { ::-webkit-scrollbar {width: 1px;} ::-webkit-scrollbar-thumb {background: rgba(var(--rgb-accent-color), 0.7);} } - */ + */ - `; + ` // Build title - titleBar.appendChild(title); - titleBar.appendChild(btnRefresh); + titleBar.appendChild(title) + titleBar.appendChild(btnHelp) + titleBar.appendChild(btnRefresh) - utilityBar.appendChild(thisButtonId); - utilityBar.appendChild(logRecdCnt); - utilityBar.appendChild(devType); - utilityBar.appendChild(hdrCellWidth); - utilityBar.appendChild(versionText); + utilityBar.appendChild(thisButtonId) + utilityBar.appendChild(logRecdCnt) + utilityBar.appendChild(devType) + utilityBar.appendChild(hdrCellWidth) + utilityBar.appendChild(versionText) + utilityBar.appendChild(infoText) // Create Buttons - buttonBar.appendChild(btnName0); - buttonBar.appendChild(btnName1); - buttonBar.appendChild(btnName2); - buttonBar.appendChild(btnName3); - buttonBar.appendChild(btnName4); - buttonBar.appendChild(btnName5); - buttonBar.appendChild(btnAction); - buttonBar.appendChild(btnName6); - buttonBar.appendChild(btnName7); - buttonBar.appendChild(btnName8); - buttonBar.appendChild(btnName9); + buttonBar.appendChild(btnName0) + buttonBar.appendChild(btnName1) + buttonBar.appendChild(btnName2) + buttonBar.appendChild(btnName3) + buttonBar.appendChild(btnName4) + buttonBar.appendChild(btnName5) + buttonBar.appendChild(btnAction) + buttonBar.appendChild(btnName6) + buttonBar.appendChild(btnName7) + buttonBar.appendChild(btnName8) + buttonBar.appendChild(btnName9) // Build Message Bar - eltInfoBar.appendChild(eltInfoName); - eltInfoBar.appendChild(eltInfoTime); - eltInfoBar.appendChild(eltInfoMsgPopup) + statusBar.appendChild(statusName) + statusBar.appendChild(statusTime) + statusBar.appendChild(statusMsgPopup) tblEvlog.appendChild(tblEvlogHdr) tblEvlog.appendChild(tblEvlogBody) @@ -695,33 +760,37 @@ class iCloud3EventLogCard extends HTMLElement { background.appendChild(titleBar) background.appendChild(utilityBar) background.appendChild(buttonBar) - background.appendChild(eltInfoBar) + background.appendChild(statusBar) background.appendChild(tblEvlogContainer) - background.appendChild(cssStyle); + background.appendChild(cssStyle) - card.appendChild(background); - root.appendChild(card); + card.appendChild(background) + root.appendChild(card) // Click & Mouse Events for (let i = 0; i <= 9; i++) { let buttonId = 'btnName' + i let button = root.getElementById(buttonId) - button.addEventListener("mousedown", event => { this._nameButtonPress(buttonId); }); - button.addEventListener("mouseover", event => { this._btnClassMouseOver(buttonId); }); - button.addEventListener("mouseout", event => { this._btnClassMouseOut(buttonId); }); + button.addEventListener("mousedown", event => { this._nameButtonPress(buttonId); }) + button.addEventListener("mouseover", event => { this._btnClassMouseOver(buttonId); }) + button.addEventListener("mouseout", event => { this._btnClassMouseOut(buttonId); }) } - btnAction.addEventListener("change", event => { this._commandButtonPress("btnAction"); }); - //btnAction.addEventListener("mouseover", event => { this._btnClassMouseOver("btnAction"); }); - //btnAction.addEventListener("mouseout", event => { this._btnClassMouseOut("btnAction"); }); + btnAction.addEventListener("change", event => { this._commandButtonPress("btnAction"); }) + //btnAction.addEventListener("mouseover", event => { this._btnClassMouseOver("btnAction"); }) + //btnAction.addEventListener("mouseout", event => { this._btnClassMouseOut("btnAction"); }) - btnRefresh.addEventListener("mousedown", event => { this._commandButtonPress("btnRefresh"); }); - btnRefresh.addEventListener("mouseover", event => { this._btnClassMouseOver("btnRefresh"); }); - btnRefresh.addEventListener("mouseout", event => { this._btnClassMouseOut("btnRefresh"); }); + //btnHelp.addEventListener("mousedown", event => { this._commandButtonPress("btnHelp"); }) + btnHelp.addEventListener("mouseover", event => { this._btnClassMouseOver("btnHelp"); }) + btnHelp.addEventListener("mouseout", event => { this._btnClassMouseOut("btnHelp"); }) + + btnRefresh.addEventListener("mousedown", event => { this._commandButtonPress("btnRefresh"); }) + btnRefresh.addEventListener("mouseover", event => { this._btnClassMouseOver("btnRefresh"); }) + btnRefresh.addEventListener("mouseout", event => { this._btnClassMouseOut("btnRefresh"); }) // Add to root - this._config = config; + this._config = config } // Create card. @@ -733,8 +802,8 @@ class iCloud3EventLogCard extends HTMLElement { const root = this.shadowRoot this._hass = hass const thisButtonId = root.getElementById("thisButtonId") - const eltInfoTime = root.getElementById("eltInfoTime") - const eltInfoMsgPopup = root.getElementById("eltInfoMsgPopup") + const statusTime = root.getElementById("statusTime") + const statusMsgPopup = root.getElementById("statusMsgPopup") try { const updateTimeAttr = hass.states['sensor.icloud3_event_log'].attributes['update_time'] @@ -744,17 +813,17 @@ class iCloud3EventLogCard extends HTMLElement { this._nameButtonPress(this._currentButtonId()) } - //this._displayNameMsgL('/'+eltInfoTime.innerText + '/'+updateTimeAttr+'/') - if (eltInfoTime.innerText.indexOf(updateTimeAttr) == -1) { + //this._displayNameMsgL('/'+statusTime.innerText + '/'+updateTimeAttr+'/') + if (statusTime.innerText.indexOf(updateTimeAttr) == -1) { this._setupEventLogTable('hass') } - eltInfoMsgPopup.classList.add('eltInfoMsgPopupHidden') + statusMsgPopup.classList.add('statusMsgPopupHidden') } catch(err) { - const eltInfoMsgPopup = root.getElementById("eltInfoMsgPopup") - const eltInfoTime = root.getElementById("eltInfoTime") + const statusMsgPopup = root.getElementById("statusMsgPopup") + const statusTime = root.getElementById("statusTime") - if (eltInfoMsgPopup.classList.contains('eltInfoMsgPopupHidden') == false) { + if (statusMsgPopup.classList.contains('statusMsgPopupHidden') == false) { return } const msgRestarting = '

iCloud3 is restarting

' @@ -762,13 +831,13 @@ class iCloud3EventLogCard extends HTMLElement { if (err.name == 'TypeError') { if (err.message.indexOf('attributes') > -1) { - //if (eltInfoTime.innerText == 'setup') { + //if (statusTime.innerText == 'setup') { if (thisButtonId.innerText == "setup") { - eltInfoMsgPopup.innerHTML = msgNotRunning + statusMsgPopup.innerHTML = msgNotRunning } else { - eltInfoMsgPopup.innerHTML = msgRestarting + statusMsgPopup.innerHTML = msgRestarting } - eltInfoMsgPopup.classList.remove('eltInfoMsgPopupHidden') + statusMsgPopup.classList.remove('statusMsgPopupHidden') } else if (err.message.indexOf('undefined') == -1) { alert(err) } @@ -783,8 +852,8 @@ class iCloud3EventLogCard extends HTMLElement { /* Cycle through the sensor.icloud3_event_log attributes and build the names on the buttons, and make them visible. */ - const root = this.shadowRoot; - const hass = this._hass; + const root = this.shadowRoot + const hass = this._hass const thisButtonId = root.getElementById("thisButtonId") const btnName0 = root.getElementById("btnName0") const filtername = hass.states['sensor.icloud3_event_log'].attributes['filtername'] @@ -806,13 +875,13 @@ class iCloud3EventLogCard extends HTMLElement { if (i < names.length) { button.innerText = names[i] - button.style.setProperty('visibility', 'visible'); + button.style.setProperty('visibility', 'visible') button.classList.remove('btnHidden') button.classList.add('btnNotSelected') //} else { // button.innerText = "Device-"+i - // button.style.setProperty('visibility', 'visible'); + // button.style.setProperty('visibility', 'visible') // button.classList.remove('btnHidden') } } @@ -824,10 +893,10 @@ class iCloud3EventLogCard extends HTMLElement { build the event log table */ - const root = this.shadowRoot; - const hass = this._hass; + const root = this.shadowRoot + const hass = this._hass const tblEvlog = root.getElementById("tblEvlog") - const eltInfoTime = root.getElementById("eltInfoTime") + const statusTime = root.getElementById("statusTime") const hdrCellWidth = root.getElementById("hdrCellWidth") const logRecdCnt = root.getElementById("logRecdCnt") const devType = root.getElementById("devType") @@ -966,6 +1035,8 @@ class iCloud3EventLogCard extends HTMLElement { maxStatZoneLength = 9 if (tStat == 'stationary') {tStat = 'stationry'} if (tZone == 'stationary') {tZone = 'stationry'} + if (tStat == 'Stationary') {tStat = 'Stationry'} + if (tZone == 'Stationary') {tZone = 'Stationry'} } if (tStat.length > maxStatZoneLength) { tStat = tStat.substr(0, maxStatZoneLength) + "
" + tStat.substr(maxStatZoneLength, tStat.length) @@ -1091,7 +1162,7 @@ class iCloud3EventLogCard extends HTMLElement { && tText.indexOf("Complete") == -1) { initializationRecdFound = true } - if (tText.indexOf("Error") >= 0) { + if (tText.indexOf(" Error ") >= 0) { classErrorMsg = ' errorMsg' if (initializationRecdFound == false) { alertErrorMsg = "iCloud3 Error Msg at "+tTime @@ -1270,7 +1341,7 @@ class iCloud3EventLogCard extends HTMLElement { //--------------------------------------------------------------------------- _resize_header_width() { - const root = this.shadowRoot; + const root = this.shadowRoot const tblEvlog = root.getElementById("tblEvlog") const devType = root.getElementById("devType") var rowCnt = tblEvlog.rows.length @@ -1298,7 +1369,7 @@ class iCloud3EventLogCard extends HTMLElement { } //--------------------------------------------------------------------------- _setupDevType() { - const root = this.shadowRoot; + const root = this.shadowRoot const devType = root.getElementById("devType") //iPhone (portrait) width=375, ,height=768 @@ -1335,8 +1406,8 @@ class iCloud3EventLogCard extends HTMLElement { and then the Event Log was displayed in another, the Log revs are for the selected device but the name highlighter will be for the precious device selected. */ - const root = this.shadowRoot; - const hass = this._hass; + const root = this.shadowRoot + const hass = this._hass this.namesAttr = hass.states['sensor.icloud3_event_log'].attributes['names'] var filtername = hass.states['sensor.icloud3_event_log'].attributes['filtername'] const namesAttr = this.namesAttr @@ -1375,8 +1446,8 @@ class iCloud3EventLogCard extends HTMLElement { /* Handle the button press events. Get the devicename, do an 'icloud3_update' event_log devicename' service call to have the event_log attribute populated. */ - const root = this.shadowRoot; - const hass = this._hass; + const root = this.shadowRoot + const hass = this._hass this.namesAttr = hass.states['sensor.icloud3_event_log'].attributes['names'] const namesAttr = this.namesAttr const names = Object.values(namesAttr) @@ -1388,9 +1459,9 @@ class iCloud3EventLogCard extends HTMLElement { var lastButtonId = this._currentButtonId() var lastButtonPressed = root.getElementById(lastButtonId) var buttonPressX = buttonPressId.substr(-1) - var eltInfoName = names[buttonPressX]+" ("+devicenames[buttonPressX]+")" + var statusName = names[buttonPressX]+" ("+devicenames[buttonPressX]+")" - this._displayNameMsgL(eltInfoName) + this._displayNameMsgL(statusName) thisButtonId.innerText = buttonPressId lastButtonPressed.classList.remove('btnSelected') @@ -1409,8 +1480,8 @@ class iCloud3EventLogCard extends HTMLElement { /* Handle the button press events. Get the devicename, do an 'icloud3_update' event_log devicename' service call to have the event_log attribute populated. */ - const root = this.shadowRoot; - const hass = this._hass; + const root = this.shadowRoot + const hass = this._hass this.namesAttr = hass.states['sensor.icloud3_event_log'].attributes['names'] const namesAttr = this.namesAttr const devicenames = Object.keys(namesAttr) @@ -1465,15 +1536,27 @@ class iCloud3EventLogCard extends HTMLElement { //--------------------------------------------------------------------------- _btnClassMouseOver(buttonId) { - const root = this.shadowRoot; + const root = this.shadowRoot const button = root.getElementById(buttonId) - const thisButtonId = root.getElementById("thisButtonId") + const btnHelp = root.getElementById("bthHelp") + const btnHelpIcon24 = root.getElementById("btnHelpIcon24") + const btnHelpIcon24Hover = root.getElementById("btnHelpIcon24Hover") + const btnRefreshIcon24 = root.getElementById("btnRefreshIcon24") + const btnRefreshIcon24Hover = root.getElementById("btnRefreshIcon24Hover") const versionText = root.getElementById("versionText") + const infoText = root.getElementById("infoText") const devType = root.getElementById("devType") - if (buttonId == "btnRefresh") { - this._displayTimeMsgR("Refresh Event Log") - versionText.style.setProperty('visibility', 'visible'); + if (buttonId == "btnHelp") { + btnHelpIcon24Hover.classList.remove('btnHidden') + btnHelpIcon24.classList.add('btnHidden') + this._displayInfoText("iCloud3 User Maual") + this._displayTimeMsgR("Version "+versionText.textContent) + + } else if (buttonId == "btnRefresh") { + btnRefreshIcon24Hover.classList.remove('btnHidden') + btnRefreshIcon24.classList.add('btnHidden') + this._displayInfoText("Refresh Event Log") } else if (buttonId == "btnAction") { this._displayTimeMsgR("Show Action Command List") @@ -1484,16 +1567,29 @@ class iCloud3EventLogCard extends HTMLElement { //--------------------------------------------------------------------------- _btnClassMouseOut(buttonId) { - const root = this.shadowRoot; - const hass = this._hass; + const root = this.shadowRoot + const hass = this._hass this.logLevelDebug = hass.states['sensor.icloud3_event_log'].attributes['log_level_debug'] const button = root.getElementById(buttonId) + const btnHelp = root.getElementById("bthHelp") + const btnHelpIcon24 = root.getElementById("btnHelpIcon24") + const btnHelpIcon24Hover = root.getElementById("btnHelpIcon24Hover") + const btnRefreshIcon24 = root.getElementById("btnRefreshIcon24") + const btnRefreshIcon24Hover = root.getElementById("btnRefreshIcon24Hover") const versionText = root.getElementById('versionText') + const infoText = root.getElementById("infoText") const devType = root.getElementById("devType") const thisButtonId = root.getElementById("thisButtonId") - if (buttonId == 'btnRefresh') { - versionText.style.setProperty('visibility', 'hidden') + if (buttonId == 'btnHelp') { + btnHelpIcon24.classList.remove('btnHidden') + btnHelpIcon24Hover.classList.add('btnHidden') + this._displayInfoText('') + + } else if (buttonId == 'btnRefresh') { + btnRefreshIcon24.classList.remove('btnHidden') + btnRefreshIcon24Hover.classList.add('btnHidden') + this._displayInfoText('') } if (devType.innerText == "") {button.classList.remove("btnHover")} @@ -1501,42 +1597,50 @@ class iCloud3EventLogCard extends HTMLElement { } //--------------------------------------------------------------------------- _currentButtonId() { - const root = this.shadowRoot; + const root = this.shadowRoot const thisButtonId = root.getElementById("thisButtonId") return thisButtonId.innerText } //--------------------------------------------------------------------------- _displayTimeMsgR(msg) { - // Display message before time field - const root = this.shadowRoot; - const hass = this._hass; - const eltInfoTime = root.getElementById("eltInfoTime") + // Display text below action button + const root = this.shadowRoot + const hass = this._hass + const statusTime = root.getElementById("statusTime") const updateTimeAttr = hass.states['sensor.icloud3_event_log'].attributes['update_time'] - //if (eltInfoTime.innerText.startsWith("●●")) { + //if (statusTime.innerText.startsWith("●●")) { //pass if (msg == "") { - eltInfoTime.innerHTML = "Refreshed: " + updateTimeAttr + statusTime.innerHTML = "Refreshed: " + updateTimeAttr } else { - eltInfoTime.innerHTML = msg + statusTime.innerHTML = msg } } //--------------------------------------------------------------------------- _displayNameMsgL(msg) { - /* Display test messages */ - const root = this.shadowRoot; - const eltInfoName = root.getElementById("eltInfoName") - eltInfoName.innerHTML = msg + /* Display text below name button */ + const root = this.shadowRoot + const statusName = root.getElementById("statusName") + statusName.innerHTML = msg + } + + //--------------------------------------------------------------------------- + _displayInfoText(msg) { + /* Display text in area below refresh & help buttons */ + const root = this.shadowRoot + const infoText = root.getElementById("infoText") + infoText.innerText = msg } //--------------------------------------------------------------------------- getCardSize() { - return 1; + return 1 } } -customElements.define('icloud3-event-log-card', iCloud3EventLogCard); +customElements.define('icloud3-event-log-card', iCloud3EventLogCard)