forked from pippyn/icloud3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdevice_tracker.py
5769 lines (4764 loc) · 246 KB
/
device_tracker.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
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 = '1.0.6' #Custom Component Updater
import logging
import os
import time
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.zone.zone import async_active_zone
#from homeassistant.util.async_ import run_callback_threadsafe
from homeassistant.components.device_tracker import (
PLATFORM_SCHEMA, DOMAIN, ATTR_ATTRIBUTES)
#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 = 'YES'
except ImportError:
WAZE_IMPORT_SUCCESSFUL = 'NO'
pass
_LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['pyicloud==0.9.1']
DEBUG_TRACE_CONTROL_FLAG = False
CONF_ACCOUNTNAME = 'account_name'
CONF_DEVICENAME = 'device_name'
CONF_NAME = 'name'
CONF_ICLOUD_DISABLED = 'icloud_disabled'
CONF_MAX_IOSAPP_LOCATE_CNT = 'max_iosapp_locate_cnt'
CONF_INCLUDE_DEVICETYPES = 'include_device_types'
CONF_INCLUDE_DEVICETYPE = 'include_device_type'
CONF_INCLUDE_DEVICES = 'include_devices'
CONF_INCLUDE_DEVICE = 'include_device'
CONF_EXCLUDE_DEVICETYPES = 'exclude_device_types'
CONF_EXCLUDE_DEVICETYPE = 'exclude_device_type'
CONF_EXCLUDE_DEVICES = 'exclude_devices'
CONF_EXCLUDE_DEVICE = 'exclude_device'
CONF_IOSAPP_DEVICE_IDS = 'iosapp_device_ids'
CONF_IOSAPP_DEVICE_ID = 'iosapp_device_id'
CONF_FILTER_DEVICES = 'filter_devices'
CONF_UNIT_OF_MEASUREMENT = 'unit_of_measurement'
CONF_INTERVAL = 'interval'
CONF_INZONE_INTERVAL = 'inzone_interval'
CONF_STATIONARY_STILL_TIME = 'stationary_still_time'
CONF_STATIONARY_INZONE_INTERVAL = 'stationary_inzone_interval'
CONF_MAX_INTERVAL = 'max_interval'
CONF_TRAVEL_TIME_FACTOR = 'travel_time_factor'
CONF_GPS_ACCURACY_THRESHOLD = 'gps_accuracy_threshold'
CONF_IGNORE_GPS_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_SENSOR_NAME_PREFIX = 'sensor_name_prefix'
CONF_SENSOR_BADGE_PICTURE = 'sensor_badge_picture'
CONF_SENSORS = 'sensors'
CONF_EXCLUDE_SENSORS = 'exclude_sensors'
# entity attributes
ATTR_ZONE = 'zone'
ATTR_ZONE_TIMESTAMP = 'zone_timestamp'
ATTR_LAST_ZONE = 'last_zone'
ATTR_LOC_TIMESTAMP = 'timeStamp'
ATTR_TIMESTAMP = 'timestamp'
ATTR_TRIGGER = 'trigger'
ATTR_BATTERY = 'battery'
ATTR_INTERVAL = 'interval'
ATTR_HOME_DISTANCE = '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_BATTERY_STATUS = 'battery_status'
ATTR_TRACKING = 'tracking'
ATTR_ALIAS = 'alias'
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_SPEED = 'speed'
ATTR_VERTICAL_ACCURACY = 'vertical_acuracy'
ATTR_ALTITUDE = 'altitude'
ATTR_BADGE = 'badge'
ATTR_EVENT_LOG = 'event_log'
ATTR_SPEED = 'speed'
ATTR_SPEED_HIGH = 'speed_high'
ATTR_SPEED_AVERAGE = 'speed_average'
#icloud and other attributes
ATTR_LOCATION = 'location'
ATTR_ATTRIBUTES = 'attributes'
ATTR_RADIUS = 'radius'
ATTR_FRIENDLY_NAME = 'friendly_name'
ATTR_ISOLD = 'isOld'
ISO_TIMESTAMP = '0000-00-00T00:00:00.000'
ZERO_HHMMSS = '00:00:00'
SENSOR_EVENT_LOG_ENTITY = 'sensor.icloud3_event_log'
DEVICE_ATTRS_BASE = {ATTR_LATITUDE: 0, ATTR_LONGITUDE: 0,
ATTR_BATTERY: 0, ATTR_GPS_ACCURACY: 0,
ATTR_TIMESTAMP: ISO_TIMESTAMP,
ATTR_LOC_TIMESTAMP: ZERO_HHMMSS,
ATTR_TRIGGER: '',
ATTR_BATTERY_STATUS: '', ATTR_DEVICE_STATUS: '',
ATTR_LOW_POWER_MODE: ''}
TRACE_ATTRS_BASE = {ATTR_ZONE: '', ATTR_LAST_ZONE: '',
ATTR_ZONE_TIMESTAMP: '', ATTR_GPS: 0,
ATTR_LATITUDE: 0, ATTR_LONGITUDE: 0,
ATTR_TRIGGER: '',
ATTR_TIMESTAMP: ISO_TIMESTAMP,
ATTR_HOME_DISTANCE: 0, ATTR_INTERVAL: 0,
ATTR_DIR_OF_TRAVEL: '', ATTR_TRAVEL_DISTANCE: 0,
ATTR_LAST_UPDATE_TIME: '',
ATTR_NEXT_UPDATE_TIME: '',
ATTR_SPEED: '', ATTR_SPEED_HIGH: '',
ATTR_SPEED_AVERAGE: '',
ATTR_POLL_COUNT: '', ATTR_INFO: ''}
TRACE_ICLOUD_ATTRS_BASE = {CONF_NAME: '', 'deviceStatus': '',
ATTR_ISOLD: False,
ATTR_LATITUDE: 0, ATTR_LONGITUDE: 0,
ATTR_LOC_TIMESTAMP: 0, 'horizontalAccuracy': 0,
'positionType': 'Wifi'}
SENSOR_DEVICE_ATTRS = ['zone', 'last_zone', 'zone_timestamp',
'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',
'speed', 'speed_high', 'speed_average',
'altitude', 'badge', 'event_log']
SENSOR_ATTR_FORMAT = {'distance': 'dist',
'calc_distance': 'dist',
'waze_distance': 'diststr',
'travel_distance': 'dist',
'battery': '%',
'dir_of_travel': 'title',
'speed': 'kph-mph',
'speed_high': 'kph-mph',
'speed_average': 'kph-mph',
'altitude': 'm-ft',
'badge': 'badge'}
#---- iPhone Device Tracker Attribute Templates ----- Gary -----------
SENSOR_ATTR_ICON = {'zone': 'mdi:cellphone-iphone',
'last_zone': 'mdi:cellphone-iphone',
'zone_timestamp': 'mdi:restore-clock',
'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:restore-clock',
'last_update': 'mdi:restore-clock',
'next_update': 'mdi:update',
'poll_count': 'mdi:counter',
'travel_distance': 'mdi:map-marker-distance',
'trigger': 'mdi:flash-outline',
'battery': 'mdi:battery',
'speed': 'mdi:speedometer',
'speed_high': 'mdi:speedometer',
'speed_average': 'mdi:speedometer',
'speed_summary': 'mdi:speedometer',
'altitude': 'mdi:image-filter-hdr',
'battery_status': 'mdi:battery',
'gps_accuracy': 'mdi:map-marker-radius',
'badge': 'mdi:shield-account',
'entity_log': 'mdi:format-list-checkbox'}
ATTR_TIMESTAMP_FORMAT = '%Y-%m-%dT%H:%M:%S.%f'
#icloud_update commands
CMD_ERROR = 1
CMD_INTERVAL = 2
CMD_PAUSE = 3
CMD_RESUME = 4
CMD_WAZE = 5
#Other constants
IOSAPP_DT_ENTITY = True
ICLOUD_DT_ENTITY = False
#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_ERROR = 4
# If the location data is old during the _update_device_icloud routine,
# it will retry polling the device (or all devices) after 3 seconds,
# up to 4 times. If the data is still old, it will set the next normal
# interval to C_LOCATION_ISOLD_INTERVAL and keep track of the number of
# times it overrides the normal polling interval. If it is still old after
# C_MAX_LOCATION_ISOLD_CNT retries, the normal intervl will be used and
# the cycle starts over on the next poll. This will prevent a constant
# repolling if the location data is always old.
C_LOCATION_ISOLD_INTERVAL = 15
C_MAX_LOCATION_ISOLD_CNT = 4
ICLOUD_ACCOUNTS = {}
CONFIGURING_DEVICE = {}
DEVICE_STATUS_SET = ['deviceModel', 'rawDeviceModel', 'deviceStatus',
'deviceClass', 'batteryLevel', 'id', 'lowPowerMode',
'deviceDisplayName', 'name', 'batteryStatus', 'fmlyShare',
'location',
'locationCapable', 'locationEnabled', 'isLocating',
'remoteLock', 'activationLocked', 'lockedTimestamp',
'lostModeCapable', 'lostModeEnabled', 'locFoundEnabled',
'lostDevice', 'lostTimestamp',
'remoteWipe', 'wipeInProgress', 'wipedTimestamp',
'isMac']
DEVICE_STATUS_CODES = {
'200': 'online',
'201': 'offline',
'203': 'pending',
'204': 'unregistered',
}
SERVICE_SCHEMA = vol.Schema({
vol.Optional(CONF_ACCOUNTNAME): vol.All(cv.ensure_list, [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.Required(CONF_PASSWORD): cv.string,
vol.Optional(CONF_ACCOUNTNAME): cv.slugify,
vol.Optional(CONF_ICLOUD_DISABLED, default=False): cv.boolean,
vol.Optional(CONF_MAX_IOSAPP_LOCATE_CNT, default=100): cv.string,
#-----►►General Attributes ----------
vol.Optional(CONF_UNIT_OF_MEASUREMENT, default='mi'): cv.slugify,
vol.Optional(CONF_INZONE_INTERVAL, default='2 hrs'): cv.string,
vol.Optional(CONF_MAX_INTERVAL, default=0): 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_IGNORE_GPS_INZONE, default=True): cv.boolean,
vol.Optional(CONF_HIDE_GPS_COORDINATES, default=False): cv.boolean,
#-----►►Filter, Include, Exclude Devices ----------
vol.Optional(CONF_INCLUDE_DEVICETYPES): \
vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_INCLUDE_DEVICETYPE): \
vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_INCLUDE_DEVICES): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_INCLUDE_DEVICE): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_EXCLUDE_DEVICETYPES): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_EXCLUDE_DEVICETYPE): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_EXCLUDE_DEVICES): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_EXCLUDE_DEVICE): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_IOSAPP_DEVICE_IDS): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_IOSAPP_DEVICE_ID): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_FILTER_DEVICES): cv.slugify,
#-----►►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_SENSOR_NAME_PREFIX): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_SENSOR_BADGE_PICTURE): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_SENSORS): cv.string,
vol.Optional(CONF_EXCLUDE_SENSORS): cv.string,
vol.Optional(CONF_COMMAND): cv.string
})
def _combine_config_filter_parms(parm_devices, parm_device):
'''
Return a concatinated configuration parms string.
include_device + include_devices
exclude_device + exclude_devices
include_device_type + include_device_types
exclude_device + exclude_device_types
Returned the combine the two lists (p1 & p2)
'''
combined_list = []
if parm_devices:
for item in parm_devices:
combined_list.append(item.lower())
if parm_device:
for item in parm_device:
combined_list.append(item.lower())
return combined_list
#--------------------------------------------------------------------
def setup_scanner(hass, config: dict, see, discovery_info=None):
"""Set up the iCloud Scanner."""
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
account = config.get(CONF_ACCOUNTNAME,
slugify(username.partition('@')[0]))
icloud_disabled = config.get(CONF_ICLOUD_DISABLED)
max_iosapp_locate_cnt = int(config.get(CONF_MAX_IOSAPP_LOCATE_CNT))
log_msg =("Setting up iCloud3 v{} device tracker for {}/{}").format(
VERSION, username, account)
if HA_DEVICE_TRACKER_LEGACY_MODE:
log_msg = ("{}, using device_tracker.legacy code").format(log_msg)
_LOGGER.info(log_msg)
include_device_types = _combine_config_filter_parms(config.get(
CONF_INCLUDE_DEVICETYPES),
config.get(CONF_INCLUDE_DEVICETYPE))
include_devices = _combine_config_filter_parms(config.get(
CONF_INCLUDE_DEVICES),
config.get(CONF_INCLUDE_DEVICE))
exclude_device_types = _combine_config_filter_parms(
config.get(CONF_EXCLUDE_DEVICETYPES),
config.get(CONF_EXCLUDE_DEVICETYPE))
exclude_devices = _combine_config_filter_parms(
config.get(CONF_EXCLUDE_DEVICES),
config.get(CONF_EXCLUDE_DEVICE))
iosapp_device_ids = _combine_config_filter_parms(
config.get(CONF_IOSAPP_DEVICE_IDS),
config.get(CONF_IOSAPP_DEVICE_ID))
filter_devices = config.get(CONF_FILTER_DEVICES)
if config.get(CONF_MAX_INTERVAL) == '0':
inzone_interval_str = config.get(CONF_INZONE_INTERVAL)
else:
inzone_interval_str = config.get(CONF_MAX_INTERVAL)
max_interval = config.get(CONF_MAX_INTERVAL)
gps_accuracy_threshold = config.get(CONF_GPS_ACCURACY_THRESHOLD)
ignore_gps_accuracy_inzone_flag = config.get(CONF_IGNORE_GPS_INZONE)
hide_gps_coordinates = config.get(CONF_HIDE_GPS_COORDINATES)
unit_of_measurement = config.get(CONF_UNIT_OF_MEASUREMENT)
stationary_inzone_interval_str = config.get(CONF_STATIONARY_INZONE_INTERVAL)
stationary_still_time_str = config.get(CONF_STATIONARY_STILL_TIME)
sensor_name_prefix = config.get(CONF_SENSOR_NAME_PREFIX)
sensor_badge_picture = config.get(CONF_SENSOR_BADGE_PICTURE)
sensors = config.get(CONF_SENSORS)
exclude_sensors = 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)
waze_region = config.get(CONF_WAZE_REGION)
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 = ("Invalid Waze Region ({}). Valid Values are: "\
"NA=US or North America, EU=Europe, IL=Isreal").\
format(waze_region)
_LOGGER.error(log_msg)
waze_region = 'US'
waze_max_distance = 0
waze_min_distance = 0
icloud_account = Icloud(hass, see, username, password, account,
include_device_types, include_devices,
exclude_device_types, exclude_devices,
iosapp_device_ids, filter_devices,
icloud_disabled, max_iosapp_locate_cnt,
inzone_interval_str, gps_accuracy_threshold, hide_gps_coordinates,
stationary_inzone_interval_str, stationary_still_time_str,
ignore_gps_accuracy_inzone_flag, sensor_name_prefix,
sensor_badge_picture, sensors, exclude_sensors,
unit_of_measurement, travel_time_factor, distance_method,
waze_region, waze_realtime, waze_max_distance, waze_min_distance)
ICLOUD_ACCOUNTS[account] = icloud_account
#if icloud_account.api and icloud_disabled == False:
# ICLOUD_ACCOUNTS[account] = icloud_account
#else:
# log_msg = ("►►►► ICLOUD3 SETUP ABORTED FOR {}/{}").format(
# username, account)
# _LOGGER.error(log_msg)
# log_msg = ("►►►► No devices were set up for the iCloud account")
# _LOGGER.error(log_msg)
#
# return False
#--------------------------------------------------------------------
def service_callback_lost_iphone(call):
"""Call the lost iPhone function if the device is found."""
accounts = call.data.get(CONF_ACCOUNTNAME, ICLOUD_ACCOUNTS)
devicename = call.data.get(CONF_DEVICENAME)
for account in accounts:
if account in ICLOUD_ACCOUNTS:
ICLOUD_ACCOUNTS[account].service_handler_lost_iphone(
account, devicename)
hass.services.register(DOMAIN, 'icloud_lost_iphone',
service_callback_lost_iphone, schema=SERVICE_SCHEMA)
#--------------------------------------------------------------------
def service_callback_update_icloud(call):
"""Call the update function of an iCloud account."""
accounts = call.data.get(CONF_ACCOUNTNAME, ICLOUD_ACCOUNTS)
devicename = call.data.get(CONF_DEVICENAME)
command = call.data.get(CONF_COMMAND)
for account in accounts:
if account in ICLOUD_ACCOUNTS:
ICLOUD_ACCOUNTS[account].service_handler_icloud_update(
account, devicename, command)
hass.services.register(DOMAIN, 'icloud_update',
service_callback_update_icloud, schema=SERVICE_SCHEMA)
#--------------------------------------------------------------------
def service_callback_restart_icloud(call):
"""Reset an iCloud account."""
accounts = call.data.get(CONF_ACCOUNTNAME, ICLOUD_ACCOUNTS)
for account in accounts:
if account in ICLOUD_ACCOUNTS:
ICLOUD_ACCOUNTS[account].restart_icloud()
hass.services.register(DOMAIN, 'icloud_restart',
service_callback_restart_icloud, schema=SERVICE_SCHEMA)
#--------------------------------------------------------------------
def service_callback_setinterval(call):
"""Call the update function of an iCloud account."""
accounts = call.data.get(CONF_ACCOUNTNAME, ICLOUD_ACCOUNTS)
interval = call.data.get(CONF_INTERVAL)
devicename = call.data.get(CONF_DEVICENAME)
for account in accounts:
if account in ICLOUD_ACCOUNTS:
ICLOUD_ACCOUNTS[account].service_handler_icloud_setinterval(
account, interval, devicename)
hass.services.register(DOMAIN, 'icloud_set_interval',
service_callback_setinterval, schema=SERVICE_SCHEMA)
# Tells the bootstrapper that the component was successfully initialized
return True
#====================================================================
class Icloud(DeviceScanner):
"""Representation of an iCloud account."""
def __init__(self, hass, see, username, password, account,
include_device_types, include_devices,
exclude_device_types, exclude_devices,
iosapp_device_ids, filter_devices,
icloud_disabled, max_iosapp_locate_cnt,
inzone_interval_str, gps_accuracy_threshold, hide_gps_coordinates,
stationary_inzone_interval_str, stationary_still_time_str,
ignore_gps_accuracy_inzone_flag, sensor_name_prefix,
sensor_badge_picture, sensors, exclude_sensors,
unit_of_measurement, travel_time_factor, distance_method,
waze_region, waze_realtime, waze_max_distance, waze_min_distance):
"""Initialize an iCloud account."""
self.hass = hass
self.username = username
self.password = password
self.api = None
self.accountname = account #name
self.see = see
self.iosapp_device_ids = iosapp_device_ids
self.verification_code = None
self.trusted_device = None
self.trusted_device_id = None
self.valid_trusted_device_ids = None
self.icloud_disabled_flag_config = icloud_disabled
self.icloud_disabled_flag = icloud_disabled
self.max_iosapp_locate_cnt = max_iosapp_locate_cnt
self.restart_icloud_account_request_flag = False
self.restart_icloud_account_inprocess_flag = False
self.authenticated_time = ''
self._setup_debug_control()
self.attributes_initialized_flag = False
self.include_device_types = include_device_types
self.exclude_device_types = exclude_device_types
self.exclude_devices = exclude_devices
if filter_devices: #for iCloud2 compatiblity
self.include_devices = filter_devices
else:
self.include_devices = include_devices
self.distance_method_waze_flag = (distance_method.lower() == 'waze')
self.inzone_interval = self._time_str_to_secs(inzone_interval_str)
self.gps_accuracy_threshold = int(gps_accuracy_threshold)
self.ignore_gps_accuracy_inzone_flag = ignore_gps_accuracy_inzone_flag
self.hide_gps_coordinates = hide_gps_coordinates
self.sensor_name_prefix = sensor_name_prefix
self.sensor_badge_picture = sensor_badge_picture
self.sensors = sensors
self.exclude_sensors = exclude_sensors
self.unit_of_measurement = unit_of_measurement
self.travel_time_factor = float(travel_time_factor)
self.e_seconds_local_offset_secs = 0
self.time_zone_offset_seconds = self._calculate_time_zone_offset()
self._setup_um_formats(unit_of_measurement)
self._setup_general_variables()
self._setup_zone_tables()
self._setup_stationary_zone_variables(stationary_inzone_interval_str,
stationary_still_time_str)
self._setup_polling_variables()
self._verify_waze_installation()
self._setup_waze_variables(waze_region, waze_min_distance,
waze_max_distance, waze_realtime)
#add HA event that will call the _polling_loop_15_sec_icloud function every 15 seconds
#that will check a iphone's location if the time interval
#has passed. If so, update all tracker attributes for all phones
#being tracked with the new information.
#Restart the icloud tracker which will finish initializing the fields
#for all devices and setting everything up. Do not start the polling
#times if there is an error.
if self.restart_icloud():
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])
#--------------------------------------------------------------------
def restart_icloud(self):
"""Reset an iCloud account."""
#check to see if restart is in process
if self.restart_icloud_account_inprocess_flag:
return
self.restart_icloud_account_request_flag = False
self.restart_icloud_account_inprocess_flag = True
event_msg = ("^^^^^ {} ^^^^^ HA Started ^^^^^").format(
dt_util.now().strftime('%A, %B %-d'))
self._save_event("*", event_msg)
event_msg = ("iCloud3 Initalization, Stage 1, Verify iCloud "
"Location Service")
self._save_event("*", event_msg)
self._LOGGER_info_msg(event_msg)
if self.icloud_disabled_flag:
self.api = None
log_msg = ("iCloud location service disabled for {}/{}").\
format(self.username, self.accountname)
self._LOGGER_warning_msg(log_msg)
self._save_event("*", log_msg)
else:
from pyicloud import PyiCloudService
from pyicloud.exceptions import (
PyiCloudFailedLoginException, PyiCloudNoDevicesException)
log_msg = ("Requesting authorization for {}/{}").format(
self.username, self.accountname)
self._LOGGER_info_msg(log_msg)
icloud_dir = self.hass.config.path('icloud')
if not os.path.exists(icloud_dir):
os.makedirs(icloud_dir)
try:
self.api = PyiCloudService(self.username, self.password,
cookie_directory=icloud_dir, verify=True)
log_msg = ("Authentication for {}/{} successful").format(
self.username, self.accountname)
self._LOGGER_info_msg(log_msg)
except PyiCloudFailedLoginException as error:
self.api = None
self.icloud_disabled_flag = True
log_msg = ("Error authenticating iCloud Service for {}/{}").format(
self.username, self.accountname)
self._LOGGER_error_msg(log_msg)
event_msg = ("Error authenticating iCloud Service")
self._save_event("*", event_msg)
log_msg = ("Error returned from pyicloud: {}").format(error)
self._LOGGER_error_msg(log_msg)
log_msg = ("iCloud location service has been disabled")
self._LOGGER_error_msg(log_msg)
self._setup_device_tracking_fields()
self._setup_sensor_variables()
event_msg = ("^^^^^ {} ^^^^^ HA Started ^^^^^").format(
dt_util.now().strftime('%A, %B %-d'))
self._save_event("*", event_msg)
event_msg = ("iCloud3 Initalization, Stage 2, Checking device filters")
self._save_event("*", event_msg)
self._LOGGER_info_msg(event_msg)
log_msg = ("Filters: include_device_types={},"
" include_devices={}, exclude_device_types={},"
" exclude_devices={}").format(
self.include_device_types, self.include_devices,
self.exclude_device_types, self.exclude_devices)
self._LOGGER_info_msg(log_msg)
log_msg = ("Initializing Device Tracking for user {}").format(
self.username)
self._LOGGER_info_msg(log_msg)
try:
self.tracking_devicenames = ''
if self.icloud_disabled_flag:
#create tracked devices from include_devices and
#sensor_devicenames
self.tracked_devices = []
for devicename in self.include_devices:
if devicename not in self.tracked_devices:
self.tracked_devices.append(devicename)
for devicename in self.sensor_devicenames:
if devicename not in self.tracked_devices:
self.tracked_devices.append(devicename)
#extract friendly_name and device_type from tracked_devices
for devicename in self.tracked_devices:
fname = devicename
dtype = ''
for dev_type in ['iphone', 'ipad', 'ipod', 'watch', 'iwatch']:
dev_pos = devicename.find(dev_type)
if dev_pos > 0:
fnamew = devicename[0:dev_pos]
fname = fnamew.replace("_", "", 99)
fname = fname.replace("-", "", 99)
dtype = devicename[dev_pos:]
break
self.friendly_name[devicename] = fname.title()
self.device_type[devicename] = dtype
self.tracking_device_flag[devicename] = True
self.tracking_devicenames = '{}, {}'.format(
self.tracking_devicenames, devicename)
self._setup_sensor_name_devicename(devicename)
event_msg = ("Tracking {}/{}").format(
self.accountname, devicename)
self._save_event("*", event_msg)
else:
for device in self.api.devices:
status = device.status(DEVICE_STATUS_SET)
location = status['location']
devicename = slugify(status[CONF_NAME].replace(' ', '', 99))
device_type = status['deviceClass'].lower()
if location is None:
tracking_flag = False
log_msg = (
"Not tracking {}/{}({}), No location information").\
format(self.accountname, devicename, device_type)
self._LOGGER_info_msg(log_msg)
elif status['locationEnabled'] is False:
tracking_flag = False
log_msg = (
"Not tracking {}/{}({}), Location Disabled").\
format(self.accountname, devicename, device_type)
self._LOGGER_info_msg(log_msg)
elif status['deviceStatus'] == '204':
tracking_flag = False
log_msg = (
"Not tracking {}/{}({}), Unregistered Device").\
format(self.accountname, devicename, device_type)
self._LOGGER_info_msg(log_msg)
elif devicename in self.tracking_device_flag:
tracking_flag = False
log_msg = (
"Not tracking {}/{}({}), Multiple devices with same"
"name").format(
self.accountname, devicename, device_type)
self._LOGGER_info_msg(log_msg)
else:
tracking_flag = self._check_tracking_this_device(
devicename, device_type)
self.tracking_device_flag[devicename] = tracking_flag
if tracking_flag:
self.tracking_devicenames = '{}, {}'.format(
self.tracking_devicenames, devicename)
self.tracked_devices[devicename] = device
self.device_type[devicename] = device_type
#Try take first name of user from 'name': 'Lillian-iPhone'
user_name = status[CONF_NAME].split(" ")
user_name = user_name[0].split("'")
user_name = user_name[0].split('-')
self.friendly_name[devicename] = user_name[0]
self._setup_sensor_name_devicename(devicename)
event_msg = ("Tracking {}/{}").format(
self.accountname, devicename)
self._save_event("*", event_msg)
#nothing to do if no devices to track
if self.tracking_devicenames == '':
log_msg = ("iCloud3 Setup Aborted, no devices to track")
self._LOGGER_error_msg(log_msg)
if self.icloud_disabled_flag:
log_msg = ("devicenames must be included in "
"'include_devices', 'sensor_badge_picture' "
"or 'sensor_name_prefix' configuration parameters")
self._LOGGER_error_msg(log_msg)
else:
log_msg = ("devicenames or device_types must be "
"included in configuration parameters")
self._LOGGER_error_msg(log_msg)
return False
#Now that the devices have been set up, finish setting up
#the Event Log Sensor
self._setup_event_log()
self.tracking_devicenames = '{}'.format(
self.tracking_devicenames[1:])
log_msg = ("Tracking Devices {}").format(
self.tracking_devicenames)
self._LOGGER_info_msg(log_msg)
self._save_event("*", log_msg)
#Now we know tracked devices, associate them with the iosapp
#devices
self._setup_devicename_iosapp()
for devicename in self.tracked_devices:
event_msg = ("iCloud3 Initalization, Stage 3, "
"Setting up {}/{}").format(self.accountname, devicename)
self._save_event("*", event_msg)
self._LOGGER_info_msg(event_msg)
self._initialize_device_fields(devicename)
self._initialize_times_counts_flags(devicename)
self._initialize_intervals_distances_times(devicename)
self._initialize_location_speed_fields(devicename)
self._update_stationary_zone(devicename,
self.stat_zone_base_latitude,
self.stat_zone_base_longitude, True)
self.in_stationary_zone_flag[devicename] = False
#Initialize the new attributes
kwargs = self._setup_base_kwargs(devicename,
self.zone_home_lat, self.zone_home_long, 0, 0)
attrs = self._initialize_attrs(devicename)
self._update_device_attributes(devicename, kwargs, attrs,
'restart_icloud')
self._update_device_sensors(devicename, kwargs)
self._update_device_sensors(devicename, attrs)
#Everying reset. Now do an iCloud update to set up the device info.
self.this_update_seconds = self._time_now_secs()
event_msg = ("iCloud3 Initalization, Stage 4, Locating devices")
self._save_event("*", event_msg)
if self.icloud_disabled_flag == False:
self._update_device_icloud('Initializing location')
self._update_sensor_event_log_data(devicename)
except PyiCloudNoDevicesException:
log_msg = ('No iCloud Devices found!')
self._LOGGER_error_msg(log_msg)
self.restart_icloud_account_inprocess_flag = False
return True
#--------------------------------------------------------------------
def icloud_need_trusted_device(self):
"""We need a trusted device."""
configurator = self.hass.components.configurator
if self.accountname in CONFIGURING_DEVICE:
return
devicesstring = ''
if self.valid_trusted_device_ids == 'Invalid Entry':
devicesstring = '\n\n'\
'----------------------------------------------\n'\
'●●● Previous Trusted Device Id Entry is Invalid ●●●\n\n\n' \
'----------------------------------------------\n\n\n'
self.valid_trusted_device_ids = None
devices = self.api.trusted_devices
_LOGGER.info("Devices=%s",devices)
for i, device in enumerate(devices):
_LOGGER.info("Device=%s-%s",i,device)
devicename = "\n....Device Id={} for {}". \
format(i, device.get('phoneNumber'))
devicesstring += "{}; ".format(devicename)
self.valid_trusted_device_ids = "{},{}".\
format(i, self.valid_trusted_device_ids)
description_msg = 'Please choose the Trusted Device Id to receive ' \
'the verification code via a text message. \n\n {}' \
.format(devicesstring)
CONFIGURING_DEVICE[self.accountname] = configurator.request_config(
'iCloud Select Trusted Device for: {}'.format(self.accountname),
self.icloud_trusted_device_callback,
description = (description_msg),
entity_picture = "/static/images/config_icloud.png",
submit_caption = 'Confirm',
fields = [{'id': 'trusted_device', \
CONF_NAME: 'Trusted Device'}]
)
#--------------------------------------------------------------------
def icloud_trusted_device_callback(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'}]
"""
self.trusted_device_id = int(callback_data.get('trusted_device'))
self.trusted_device = \
self.api.trusted_devices[self.trusted_device_id]
if self.accountname in CONFIGURING_DEVICE:
request_id = CONFIGURING_DEVICE.pop(self.accountname)
configurator = self.hass.components.configurator
configurator.request_done(request_id)
if str(self.trusted_device_id) not in self.valid_trusted_device_ids:
log_msg = ("Invalid Trusted Device ID. Entered={}, "
"Valid IDs={}").format(
self.trusted_device_id,
self.valid_trusted_device_ids)
self._LOGGER_error_msg(log_msg)
self.trusted_device = None
self.valid_trusted_device_ids = 'Invalid Entry'
self.icloud_need_trusted_device()
elif not self.api.send_verification_code(self.trusted_device):
log_msg = ("Failed to send verification code")
self._LOGGER_error_msg(log_msg)
self.trusted_device = None
self.valid_trusted_device_ids = None
else:
# Get the verification code, Trigger the next step immediately
self.icloud_need_verification_code()
#------------------------------------------------------
def icloud_need_verification_code(self):
"""Return the verification code."""
configurator = self.hass.components.configurator
if self.accountname in CONFIGURING_DEVICE:
return
CONFIGURING_DEVICE[self.accountname] = configurator.request_config(
'iCloud Enter Verification Code for: {}'.format(self.accountname),
self.icloud_verification_callback,
description = ('Please enter the validation code:'),
entity_picture = "/static/images/config_icloud.png",
submit_caption = 'Confirm',
fields = [{'id': 'code', \
CONF_NAME: 'Verification Code'}]
)
#--------------------------------------------------------------------
def icloud_verification_callback(self, callback_data):
"""Handle the chosen trusted device."""
from pyicloud.exceptions import PyiCloudException
self.verification_code = callback_data.get('code')
try:
if not self.api.validate_verification_code(
self.trusted_device, self.verification_code):
raise PyiCloudException('Unknown failure')
except PyiCloudException as error:
# Reset to the initial 2FA state to allow the user to retry
log_msg = ("Failed to verify verification code: {}").format(error)
self._LOGGER_error_msg(log_msg)
self.trusted_device = None
self.verification_code = None
# Trigger the next step immediately
self.icloud_need_trusted_device()
if self.accountname in CONFIGURING_DEVICE:
request_id = CONFIGURING_DEVICE.pop(self.accountname)
configurator = self.hass.components.configurator
configurator.request_done(request_id)
#--------------------------------------------------------------------
def icloud_reauthorizing_account(self, restarting_flag = False):
'''
Make sure iCloud is still available and doesn't need to be reauthorized
in 15-second polling loop
Returns True if Reauthorization is needed.
Returns False if Authorization succeeded
'''
if self.icloud_disabled_flag:
return False
elif self.restart_icloud_account_inprocess_flag:
return False
fct_name = "icloud_reauthorizing_account"
#from "github.com/joelmoses/pyicloud" import PyiCloudService
from pyicloud import PyiCloudService
from pyicloud.exceptions import (
PyiCloudFailedLoginException, PyiCloudNoDevicesException)