forked from LazzaAU/skill_HomeAssistant
-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
HomeAssistant.py
1564 lines (1220 loc) · 52.2 KB
/
HomeAssistant.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
import threading
import json
from typing import Dict, List
import requests
import subprocess
import uuid
from datetime import datetime
from dateutil import tz
import pytz
from core.device.model.Device import Device
from core.base.model.AliceSkill import AliceSkill
from core.dialog.model.DialogSession import DialogSession
from core.util.Decorators import IntentHandler
from requests import get
from core.util.model.TelemetryType import TelemetryType
# noinspection PyTypeChecker,SqlWithoutWhere
class HomeAssistant(AliceSkill):
"""
Author: Lazza
Description: Connect Alice to your home assistant
"""
# todo add further sensor support
def __init__(self):
self._broadcastFlag = threading.Event()
self._switchDictionary = dict()
self._dbSensorList = list()
self._lightList = list()
self._action = ""
self._entity: Device = None
self._sunState = tuple
self._triggerType = ""
self._IpList = list()
self._configureActivated = False
self._jsonDict = dict()
self._newDeviceCount = 0
self._haDevicesFromAliceDatabase = list()
# IntentCapture Vars
self._captureUtterances = ""
self._captureSlotValue = ""
self._captureSynonym = ""
self._utteranceID = 0
self._slotValueID = 0
self._utteranceList = list()
self._slotValueList = list()
self._data = dict()
self._finalsynonymList = list()
super().__init__()
############################### INTENT HANDLERS #############################
@IntentHandler('LightControl')
def controlLightEntities(self, session: DialogSession):
"""
Light entities in HA can turn on and off lights, control colour etc. This method,
allows for that to happen.
:param session: the incoming dialogSession
:return:
"""
eventKey = ""
eventValue = ""
textResponce = ""
if 'LightControllers' in session.slots:
if 'AliceColor' in session.slots:
eventKey = "Color_name"
eventValue = session.slotRawValue("AliceColor")
textResponce = "changeColor"
elif 'dimmer' in session.slots:
eventKey = "brightness_pct"
eventValue = session.slotValue("dimmer")
textResponce = "changeBrightness"
trigger = 'turn_on'
device = self.DeviceManager.getDeviceByName(session.slotValue('LightControllers'))
header, url = self.retrieveAuthHeader(urlPath='services/light/', urlAction=trigger)
jsonData = {"entity_id": f'{device.getParam("entityName")}', f'{eventKey}': f'{eventValue}'}
requests.request("POST", url=url, headers=header, json=jsonData)
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk(text=textResponce, replace=[eventValue]),
deviceUid=session.deviceUid
)
# Alice speaks what Devices she knows about
@IntentHandler('WhatHomeAssistantDevices')
def sayListOfDevices(self, session: DialogSession):
self.updateKnownDeviceLists()
activeFriendlyName = list()
for device in self._haDevicesFromAliceDatabase:
activeFriendlyName.append(device.displayName)
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk(text='sayListOfDevices', replace=[activeFriendlyName]),
deviceUid=session.deviceUid
)
def skipAddingSelectedDevice(self, item) -> bool:
""" if a user has added { aliceIgnore : true} as a attribute in Home Assistant
Then Alice will ignore that device and not add it to the database
:param item: The current dictionary item from the incomming HA payload
:return True: if AliceIgnore is set to true
"""
try:
aliceIgnore: str = item['attributes']['AliceIgnore']
if 'true' in aliceIgnore.lower():
if self.getConfig('debugMode') and self.getDebugControl('skippingDevice'):
self.logDebug(
f"Skipping the devices {item['attributes']['friendly_name']}. AliceIgnore set to {item['attributes']['AliceIgnore']} ")
self.logDebug("")
return True
else:
return False
except:
return False
# Used for picking required data from incoming JSON (used in two places)
def sortThroughJson(self, item):
"""
A main method for The Skill. This method reads the incoming JSON data from HA.
It then goes through each line and based on below code will add devices to a specific list
depending on the type of device. These list will later get iterated over and added to Alice and
HA databases. Or if it's 5 minute update then this method gets used also to recreate the lists
with updated info and then iterated over those lists to update device states
:param item: The current dictionary item from incoming payload
:return: nothing , but updates entity lists
"""
if not self.skipAddingSelectedDevice(item):
if 'IPAddress' in item["attributes"]:
ipaddress: str = item["attributes"]["IPAddress"]
deviceName: str = item["attributes"]["friendly_name"]
editedDeviceName: str = deviceName.replace(' status', '').lower()
iplist = [editedDeviceName, ipaddress]
self._IpList.append(iplist)
if 'device_class' in item["attributes"]:
dbSensorList = [self.getFriendyNameAttributes(item=item), item["entity_id"], item["state"],
item["attributes"]["device_class"], item["entity_id"]]
self._dbSensorList.append(dbSensorList)
# if a user has added the haDeviceType attribute in HA customise.yaml
if not 'device_class' in item["attributes"] and 'HaDeviceType' in item["attributes"] and item["entity_id"].split('.')[0] == 'sensor':
dbSensorList = [self.getFriendyNameAttributes(item=item), item["entity_id"], item["state"],
item["attributes"]["HaDeviceType"], item["entity_id"]]
self._dbSensorList.append(dbSensorList)
try:
if 'DewPoint' in item["attributes"]["friendly_name"]:
sensorType: str = 'dewpoint'
dbSensorList = [self.getFriendyNameAttributes(item=item), item["entity_id"], item["state"],
sensorType, item["entity_id"]]
self._dbSensorList.append(dbSensorList)
if 'Gas' in item["attributes"]["friendly_name"]:
sensorType: str = 'gas'
dbSensorList = [self.getFriendyNameAttributes(item=item), item["entity_id"], item["state"],
sensorType, item["entity_id"]]
self._dbSensorList.append(dbSensorList)
# Capture Non sensor devices
deviceType = item["entity_id"].split('.')[0]
deviceGroup = deviceType
if deviceType == "input_boolean" or deviceType == "group":
aliceType = "HAswitch"
else:
aliceType = f"HA{deviceType}"
if (deviceType == "light") \
or (deviceType == "group") \
or (deviceType == "switch") \
or (deviceType == "input_boolean"):
self._switchDictionary[item["entity_id"]] = {
"friendlyName": self.getFriendyNameAttributes(item=item),
"state" : item['state'],
"deviceType" : aliceType,
"deviceGroup" : deviceGroup
}
except Exception:
pass
@staticmethod
def getFriendyNameAttributes(item):
"""
Extract the friendly name from incoming JSON payload
:param item: The current dictionary item from incoming payload
:return: The devices friendly name
"""
friendlyName: str = item["attributes"]["friendly_name"]
friendlyName = friendlyName.lower()
return friendlyName
@IntentHandler('AddHomeAssistantDevices')
def addHomeAssistantDevices(self, session: DialogSession):
"""
User has requested to add home assistant devices so this method GETS the payload using
RestAPI , then sends that data off for sorting through, then sends the results off for adding to the
database. Then it triggers adding synonyms to the dialog file. then gives the user feedback
:param session: DialogSession
:return:
"""
if not self.checkConnection(): # If not connected to HA, say so and stop
self.sayConnectionOffline(session)
return
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk(text='addHomeAssistantDevices'),
deviceUid=session.deviceUid
)
# connect to the HomeAssistant API/States to retrieve entity names and values
header, url = self.retrieveAuthHeader(urlPath='states')
data = get(url, headers=header).json()
if self.getConfig('viewJsonPayload'):
self.logDebug(f'!-!-!-!-!-!-!-! **INCOMING JSON PAYLOAD** !-!-!-!-!-!-!-!')
self.logDebug(f'')
self.logDebug(f'Incomming payload has been written to HomeAssistant/debugInfo/jsonPayload.json ')
file = self.getResource('debugInfo/jsonPayload.json')
file.write_text(json.dumps(data, ensure_ascii=False, indent=4))
self.logDebug(f'')
self.logDebug(f'')
# Loop through the incoming json payload to grab data that we need
for item in data:
if isinstance(item, dict):
self.sortThroughJson(item=item)
# Split above and below into other methods to reduce complexity complaint from sonar
# todo This is a process data retrival shortcut
self.processRetrievedHaData()
# write friendly names to dialogTemplate as slotValues
self.addSlotValues()
# restore previously saved dialog template file
self._configureActivated = True
# update the known device.
self.updateKnownDeviceLists()
if self._switchDictionary:
self.ThreadManager.doLater(
interval=5,
func=self.sayNumberOfDeviceViaThread
)
else:
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk(text='addHomeAssistantDevicesError'),
deviceUid=session.deviceUid
)
# Do the actual switching via here
@IntentHandler('HomeAssistantAction')
def homeAssistantSwitchDevice(self, session: DialogSession):
if not self.checkConnection():
self.sayConnectionOffline(session)
return
if 'on' in session.slotRawValue('OnOrOff') or 'open' in session.slotRawValue('OnOrOff'):
self._action = "turn_on" # Set HA compatible on command
elif 'off' in session.slotRawValue('OnOrOff') or 'close' in session.slotRawValue('OnOrOff'):
self._action = "turn_off"
if session.slotValue('switchNames'):
self._entity = self.DeviceManager.getDeviceByName(session.slotRawValue('switchNames'))
if self.getConfig('debugMode') and self.getDebugControl('switching'):
self.logDebug(f'!-!-!-!-!-!-!-! **SWITCHING EVENT** !-!-!-!-!-!-!-!')
self.logDebug(f'')
self.logDebug(f'I was requested to "{self._action}" the devices called "{self._entity.displayName}" ')
try:
self.logDebug(f'debugSwitchId = {self._entity.getParam("entityName")}')
except Exception as e:
self.logDebug(f' a error occured switching the switch : {e}')
if self._action and self._entity.getParam('entityName'):
header, url = self.retrieveAuthHeader(urlPath=f'services/{self._entity.getParam(key="entityGroup")}/',
urlAction=self._action)
jsonData = {"entity_id": self._entity.getParam('entityName')}
requests.request("POST", url=url, headers=header, json=jsonData)
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk(text='homeAssistantSwitchDevice', replace=[self._action]),
deviceUid=session.deviceUid
)
self._entity = None
# Get the state of a single devices
@IntentHandler('HomeAssistantState')
def getDeviceState(self, session: DialogSession):
""" return the current state of the requested device"""
if not self.checkConnection():
self.sayConnectionOffline(session)
return
if 'DeviceState' in session.slots:
device = self.DeviceManager.getDeviceByName(name=session.slotRawValue("DeviceState"))
# get info from HomeAssitant
header, url = self.retrieveAuthHeader(urlPath='states/', urlAction=device.getParam(key="entityName"))
stateResponce = requests.get(url=url, headers=header)
data = stateResponce.json()
entityID = data['entity_id']
entityState = data['state']
# add the devices state to the database
device = self.DeviceManager.getDevice(uid=entityID)
device.updateParam(key='state', value=entityState)
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk(text='getActiveDeviceState',
replace=[session.slotRawValue("DeviceState"), entityState]),
deviceUid=session.deviceUid
)
@IntentHandler('HomeAssistantSun')
def sunData(self, session: DialogSession):
"""Returns various states of the sun"""
if not self.checkConnection():
self.sayConnectionOffline(session)
return
# connect to the HomeAssistant API/States to retrieve sun values
header, url = self.retrieveAuthHeader(urlPath='states')
data = get(url, headers=header).json()
# Loop through the incoming json payload to grab the Sun data that we need
for item in data:
if isinstance(item, dict) and 'friendly_name' in item["attributes"] and 'Sun' in item["attributes"][
'friendly_name']:
if self.getConfig('debugMode'):
self.logDebug(f'!-!-!-!-!-!-!-! **SUN DEBUG LOG** !-!-!-!-!-!-!-!')
self.logDebug(f'')
self.logDebug(f'The sun JSON is ==> {item}')
self.logDebug(f'')
try:
self._sunState = item["attributes"]['friendly_name'], item["attributes"]['next_dawn'], \
item["attributes"]['next_dusk'], item["attributes"]['next_rising'], \
item["attributes"]['next_setting'], item['state']
except Exception as e:
self.logDebug(f'Error getting full sun attributes from Home Assistant: {e}')
return
request = session.slotRawValue('sunState')
if 'position' in request:
horizon = self._sunState[5].replace("_", " the ")
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk(text='sayHorizon', replace=[horizon]),
deviceUid=session.deviceUid
)
elif 'dusk' in request:
dateObj = self.makeDateObjFromString(sunState=self._sunState[2])
result, hours, minutes = self.standard_date(dateObj)
if result:
stateType = self.randomTalk(text='nextSunEvent', replace=[request])
self.saysunState(session=session, state=stateType, result=result, hours=hours, minutes=minutes)
elif 'sunrise' in request:
dateObj = self.makeDateObjFromString(sunState=self._sunState[3])
result, hours, minutes = self.standard_date(dateObj)
if result:
stateType = self.randomTalk(text='nextSunEvent', replace=[request])
self.saysunState(session=session, state=stateType, result=result, hours=hours, minutes=minutes)
elif 'dawn' in request:
dateObj = self.makeDateObjFromString(sunState=self._sunState[1])
result, hours, minutes = self.standard_date(dateObj)
if result:
stateType = self.randomTalk(text='nextSunEvent', replace=[request])
self.saysunState(session=session, state=stateType, result=result, hours=hours, minutes=minutes)
elif 'sunset' in request:
dateObj = self.makeDateObjFromString(sunState=self._sunState[4])
result, hours, minutes = self.standard_date(dateObj)
if result:
stateType = self.randomTalk(text='nextSunEvent', replace=[request])
self.saysunState(session=session, state=stateType, result=result, hours=hours, minutes=minutes)
@IntentHandler('GetIpOfDevice')
def returnIpAddressOfDevice(self, session: DialogSession):
"""Tells user the ip address of the requested device (if known)"""
device = self.DeviceManager.getDeviceByName(session.slotRawValue('switchNames'))
if device:
ipOfDevice = device.getParam('entityIP')
else:
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk(text='sayIpError', replace=[session.slotRawValue("switchNames")]),
deviceUid=session.deviceUid
)
self.logWarning(
f'Getting devices IP failed: I may not have that data available from HA - {session.slotRawValue("switchNames")}')
return
if ipOfDevice:
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk(text='sayIpAddress', replace=[ipOfDevice]),
deviceUid=session.deviceUid
)
self.logInfo(f'You can view the {session.slotRawValue("switchNames")} at ->> http://{ipOfDevice}')
else:
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk(text='sayIpError2', replace=[session.slotRawValue("switchNames")]),
deviceUid=session.deviceUid
)
self.logWarning(f'Device name not available, HA may not of supplied that devices IP')
# device was asked to switch from Myhome
def deviceClicked(self, uid: str):
"""
User has clicked a device in My home. The uid of the device is used to grab the current
state of the device and turn on or off the device as required. Last of all it also writes
The device states to the file found in the skill folder.
:param uid: The uid of the device
:return:
"""
if not self.checkConnection():
return
device = self.DeviceManager.getDevice(uid=uid)
if "on" in device.getParam("state") or "open" in device.getParam("state"):
self._action = 'turn_on'
elif "off" in device.getParam("state") or "close" in device.getParam("state"):
self._action = 'turn_off'
else:
answer = f"Sorry but the {device.displayName} is currently unavailable. Is it connected to the network ?"
self.say(
text=answer,
deviceUid=self.DeviceManager.getMainDevice().uid
)
return
deviceType = device.getParam('entityGroup')
header, url = self.retrieveAuthHeader(urlPath=f'services/{deviceType}/', urlAction=self._action)
# Update json file on click via Myhome
self._jsonDict = json.loads(str(self.getResource('currentStateOfDevices.json').read_text()))
self._jsonDict[device.getParam('entityName')] = device.getParam("state")
jsonData = {"entity_id": device.getParam('entityName')}
requests.request("POST", url=url, headers=header, json=jsonData)
self.updateDeviceStateJSONfile()
##################### POST AND GET HANDLERS ##############################
def getUpdatedDetails(self):
"""
Request the data from HA's restApi
:return:
"""
header, url = self.retrieveAuthHeader(urlPath='states')
data = get(url, headers=header).json()
# Loop through the incoming json payload to grab data that we need
self._lightList = list()
for item in data:
if isinstance(item, dict):
self.sortThroughJson(item=item)
if self.getConfig('debugMode') and self.getDebugControl('updateStates'):
self.logDebug(f'!-!-!-!-!-!-!-! **updateDBStates code** !-!-!-!-!-!-!-!')
def updateDBStates(self):
"""Update entity states from a 5 min timer and on boot"""
# use getUpdatedDetails method to reduce complexity of updateDBStates and keep sonar quiet
self.getUpdatedDetails()
self.updateKnownDeviceLists()
self.updateDeviceState()
self.updateSensors()
def updateDeviceState(self):
""" add updated states of switch-able devices to devices.params"""
for device in self._haDevicesFromAliceDatabase:
for deviceId, entityDetails in self._switchDictionary.items():
if device.getParam('entityName') == deviceId:
# update the state of the json states file
self._jsonDict[deviceId] = entityDetails['state']
if self.getConfig('debugMode') and self.getDebugControl('updateStates'):
self.logDebug(f'')
self.logDebug(f'I\'m updating the "{deviceId}" with state "{entityDetails["state"]}" ')
device.updateParam(key='state', value=entityDetails['state'])
# send HeartBeat
if not 'unavailable' in entityDetails['state'] and entityDetails['state']:
self.DeviceManager.onDeviceHeartbeat(uid=device.uid)
def updateSensors(self):
"""
Update the values of sensors in alice database. update the JSON file for states
in the main skill directory
:return:
"""
for sensorName, entity, state, haClass, uid in self._dbSensorList:
# Locate sensor in the database and update it's value
for device in self._haDevicesFromAliceDatabase:
if device.getParam('entityName') == entity:
self._jsonDict[entity] = state
if self.getConfig('debugMode') and self.getDebugControl('updateStates'):
self.logDebug(f'')
self.logDebug(f'I\'m now updating the SENSOR "{sensorName}" with the state of "{state}" ')
self.logDebug(f'HA class is "{haClass}" ')
self.logDebug(f'The entity ID is "{entity}"')
device.updateParam(key='state', value=state)
device.updateParam(key="haDeviceType", value=haClass)
if not 'unavailable' in state and state:
self.DeviceManager.onDeviceHeartbeat(uid=device.uid)
else:
self._jsonDict[entity] = state
# reset object value to prevent multiple items each update
self._dbSensorList = list()
self.updateDeviceStateJSONfile()
def retrieveAuthHeader(self, urlPath: str, urlAction: str = None):
"""
Sets up and returns the Request Header file and url
:param urlPath - sets the path such as services/Switch/
:param urlAction - sets the action such as turn_on or turn_off
EG: usage - header, url = self.requestAuthHeader(urlPath='services/switch/', urlAction=self._action)
:returns: header and url
"""
header = {"Authorization": f'Bearer {self.getConfig("haAccessToken")}', "content-type": "application/json", }
if urlAction:
url = f'{self.getConfig("haIpAddress")}{urlPath}{urlAction}'
else: # else is used for checking HA connection and boot up
url = f'{self.getConfig("haIpAddress")}{urlPath}'
return header, url
def checkConnection(self) -> bool:
"""
Used several times through out the code to check if there is a active connection to Home Assistant
:return: True if connected
"""
try:
header, url = self.retrieveAuthHeader(' ', ' ')
response = get(self.getConfig('haIpAddress'), headers=header)
if 'API running.' in response.text:
return True
else:
self.logWarning(f'It seems HomeAssistant is currently not connected ')
return False
except Exception as e:
self.logWarning(
f'Detected a error in HA skill, did you just add a new HA devices but not run "Configure home assistant skill" yet?: {e}')
return False
########################## DATABASE ITEMS ####################################
def AddToAliceDB(self, uID: str, friendlyName: str, deviceType: str, deviceParam: dict = None):
"""
Add devices to Alices Devicemanager-Devices table. Create and store devices in a StoreRoom
:param uID: The devices uid (in HA's case this is same as entity name)
:param friendlyName: The devices friendly name
:param deviceType: The devices Type EG: HAswitch, HAlight etc
:param deviceParam: A user defined dictionary of values
:return:
"""
# If there is no "storeroom" location, create it and store devices there.
if not self.LocationManager.getLocationByName('StoreRoom'):
self.LocationManager.addNewLocation({"name": "StoreRoom", "parentLocation": 0})
# register the device type if not already existing
if not self.DeviceManager.getDeviceType(skillName=self.name, deviceType=deviceType):
self.DeviceManager.registerDeviceType(skillName=self.name, data={"deviceTypeName": deviceType})
self.DeviceManager.addNewDevice(deviceType=deviceType,
skillName=self.name,
locationId=self.LocationManager.getLocation(locationName='StoreRoom').id,
uid=uID,
displaySettings={"x": "10", "y": "10", "z": 25, "w": 38, "h": 40, "r": 0},
deviceParam=deviceParam,
displayName=friendlyName
)
################# General Methods ###################
# todo General methods shortcut
def wipeAllHaData(self):
# delete and existing values in DB so we can update with a fresh list of Devices
for device in self.DeviceManager.getDevicesBySkill(skillName=self.name, connectedOnly=False):
self.DeviceManager.deleteDevice(deviceId=device.id)
self.logWarning(f'Just deleted your Home Assistant records.')
self.updateConfig(key="wipeAll", value='false')
def sayNumberOfDeviceViaThread(self):
self.say(
text=self.randomTalk(text='saynumberOfDevices', replace=[self._newDeviceCount, len(self._haDevicesFromAliceDatabase)]),
deviceUid=self.DeviceManager.getMainDevice().uid
)
def sayConnectionOffline(self, session: DialogSession):
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk(text='sayConnectionOffline'),
deviceUid=session.deviceUid
)
@staticmethod
def isNumber(string) -> bool:
try:
float(string)
return True
except ValueError:
return False
def onFiveMinute(self):
if not self.checkConnection():
return
# todo LARRY sensor shortcut
self.updateDBStates()
self.getTelemetryValues()
def getTelemetryValues(self):
"""
Pull out telemetry sensors and send those updated states to the telemetry db
:return:
"""
debugtrigger = 0
for device in self._haDevicesFromAliceDatabase:
state = device.getParam('state')
if device.deviceTypeName == 'HAtelemetrySensor' and state.isnumeric() or self.isNumber(state):
haDeviceType = device.getParam('haDeviceType')
newPayload = dict()
newPayload[str(haDeviceType).upper()] = state
# self.createTelemetryPayloadBasedOnDeviceType(haDeviceType=haDeviceType, state=state, newPayload=newPayload)
if newPayload:
try:
if self.getConfig('debugMode') and self.getDebugControl("telemetry") and debugtrigger == 0:
self.logDebug("")
self.logDebug(f'!-!-!-!-!-!-!-! **Now adding to the Telemetry DataBase** !-!-!-!-!-!-!-!')
debugtrigger = 1
# senddata to telemtry Database
self.sendToTelemetry(newPayload=newPayload, device=device)
except Exception as e:
self.logWarning(f'There was a error logging data for sensor {device.displayName} as : {e}')
else:
continue
# add friendlyNames to dialog template as a list of slotValues
def addSlotValues(self):
"""
Find the slotValues to write to the existing dialogTemplate file for the skill
"""
file = self.getResource(f'dialogTemplate/{self.activeLanguage()}.json')
self.updateKnownDeviceLists()
if not file:
return
if self.getConfig('debugMode'):
self.logDebug('!-!-!-!-!-!-!-! **ADDING THE SLOTVALUE** !-!-!-!-!-!-!-!')
lightValueList: List[Dict[str, str]] = list()
switchValueList: List[Dict[str, str]] = list()
for device in self._haDevicesFromAliceDatabase:
dictValue = {'value': device.displayName}
try:
if device.getParam('entityGroup') == 'switch' \
or device.getParam('entityGroup') == 'group' \
or device.getParam('entityGroup') == 'input_boolean':
switchValueList.append(dictValue)
if self.getConfig('debugMode'):
self.logDebug(
f'Adding slotValue {device.displayName}, of type "{device.getParam("entityGroup")}"')
self.logDebug('')
if 'light' in device.getParam('entityGroup'):
lightValueList.append(dictValue)
if self.getConfig('debugMode'):
self.logDebug(
f'Adding slot value {device.displayName}, of type "{device.getParam("entityGroup")}"')
self.logDebug('')
except:
continue
data = json.loads(file.read_text())
self.writeSlotValues(data=data,
switchValueList=switchValueList,
lightValueList=lightValueList,
file=file)
@staticmethod
def writeSlotValues(data, switchValueList, lightValueList, file) -> bool:
"""
:param data: The dialog template data
:param switchValueList: A list of switch names
:param lightValueList: A list of Light names
:param file: The dialog File to write data to
:return: bool
"""
if 'slotTypes' not in data:
return False
for i, suggestedSlot in enumerate(data['slotTypes']):
if "switchnames" in suggestedSlot['name'].lower():
# create a dictionary and append the new slot value to original list
data['slotTypes'][i]['values'] = switchValueList
if "lightcontrollers" in suggestedSlot['name'].lower():
# create a dictionary and append the new slot value to original list
data['slotTypes'][i]['values'] = lightValueList
file.write_text(json.dumps(data, ensure_ascii=False, indent=4))
return True
def processRetrievedHaData(self):
# remove duplicate sensors
finalSensorList = dict((x[0], x) for x in self._dbSensorList).values()
self.updateKnownDeviceLists()
# reset the device counter
self._newDeviceCount = 0
entityNames = list()
for device in self._haDevicesFromAliceDatabase:
entityNames.append(device.getParam('entityName'))
# Add Switches, booleans and group entities to the database
self.addDevicesToDatabaseTable(aliceList=entityNames)
# Process Sensor entities
for sensorDevice in finalSensorList:
newUid = str(uuid.uuid4())
isTelemtryType = False
try:
if TelemetryType[str(sensorDevice[3]).upper()]:
isTelemtryType = True
except:
pass
## If the sensor matches the TelemetryType Enum list. then do this block
if not sensorDevice[4] in entityNames and isTelemtryType:
self._newDeviceCount += 1
self.AddToAliceDB(
uID=newUid,
friendlyName=sensorDevice[0],
deviceType="HAtelemetrySensor",
deviceParam={"haDeviceType": str(sensorDevice[3]).upper(), "state": sensorDevice[2],
"entityName" : sensorDevice[4], "entityGroup": "sensor"}
)
classList = ["motion", 'power', 'current', 'tanklevel4', 'tanklevel3', 'tanklevel2', 'tanklevel1']
if not sensorDevice[4] in entityNames and str(sensorDevice[3]).lower() in classList:
self._newDeviceCount += 1
self.AddToAliceDB(uID=newUid,
friendlyName=sensorDevice[0],
deviceType=f"HA{sensorDevice[3]}",
deviceParam={
"haDeviceType": sensorDevice[3],
"state" : sensorDevice[2],
"entityName" : sensorDevice[4],
"entityGroup" : "sensor"
}
)
# Process Sensor entities
for deviceDetails in self._IpList:
# self.updateDeviceIPInfo(ip=deviceDetails[1], nameIdentity=deviceDetails[0])
device = self.DeviceManager.getDeviceByName(deviceDetails[0])
if device:
device.updateParam(key="entityIP", value=deviceDetails[1])
def updateKnownDeviceLists(self):
"""
Adds alices known HA devices to a list for later reference
Purpose : To reduce the need to read the database frequently
:return:
"""
self._haDevicesFromAliceDatabase = list()
# get all known Home Assistant devices from Alices database
self._haDevicesFromAliceDatabase = self.DeviceManager.getDevicesBySkill(skillName=self.name,
connectedOnly=False)
def addDevicesToDatabaseTable(self, aliceList: list):
"""
Add new devices to Alice
:param aliceList: A list of known device entityNames from Alices database
:return:
"""
for deviceId, entityDetails in self._switchDictionary.items():
newUid = str(uuid.uuid4())
if not deviceId in aliceList:
self._newDeviceCount += 1
self.AddToAliceDB(uID=newUid,
friendlyName=entityDetails['friendlyName'],
deviceType=entityDetails['deviceType'],
deviceParam={"entityName" : deviceId, "state": entityDetails["state"],
"entityGroup": entityDetails['deviceGroup']})
def sendToTelemetry(self, newPayload: dict, device):
"""
Send the incoming data to the TelemtryManager for storing in Telemtry Database
:param newPayload: A Dict containing 'deviceType' and the 'value'. EG: {"TEMPERATURE": 23.4}
:param device: The current device
:return:
"""
# create location if it doesnt exist and get the id
locationID = self.LocationManager.getLocation(locId=device.parentLocation).id
haTelemetryType = list(newPayload.keys())[0]
try:
if TelemetryType[str(haTelemetryType)]:
self.TelemetryManager.storeData(ttype=TelemetryType[str(haTelemetryType)],
value=newPayload[str(haTelemetryType)],
service=self.name,
deviceId=device.id,
locationId=locationID)
if self.getConfig('debugMode') and self.getDebugControl('telemetry'):
self.logDebug(f'')
self.logDebug(
f'The {str(haTelemetryType)} reading for the {device.displayName} is {newPayload[str(haTelemetryType)]} ')
except:
pass
def updateDeviceStateJSONfile(self):
"""
Write all Device states to the Json file in the skill folder.
Purpose: So user can refrence them from Node red rather than access database
:return: Writes a json file to the skill directory /currentStateOfDevices.json
"""
if self.getConfig('debugMode'):
self.logDebug(f'Updated currentStateOfDevices.json')
self.getResource('currentStateOfDevices.json').write_text(
json.dumps(self._jsonDict, ensure_ascii=False, indent=4))
################### AUTO BACKUP AND RESTORE CODE ########################
def restoreDisplaySettings(self):
"""
Restore display positions of devices if lost
:return nothing:
"""
#todo if option to restore backup display settings is enabled
#and display.json exists
#loop through devices in database and update location and display settings for each valid device name
print("this is a todo ")
# Make a backup directory if it doesn't exist
def runBackup(self):
"""
Initialises the backup Process, Creates the Backup directory if it doesn't exist
:return:
"""
if not self.getResource('Backup').exists():
self.logInfo(f'No Home Assistant BackUp directory found, so I\'m making one')
self.getResource("Backup").mkdir()
self.makeDialogFileCopy()
# Back up existing DialogTemplate file
def makeDialogFileCopy(self):
file = self.getResource(f'dialogTemplate/{self.activeLanguage()}.json')
subprocess.run(['cp', file, f'{self.getResource("Backup")}/{self.activeLanguage()}.json'])
self.logInfo(f'![green](Backing up dialog file)')
def mergeDialogIntents(self):
activeDialogFile = json.loads(self.getResource(f'dialogTemplate/{self.activeLanguage()}.json').read_text())
backupDialogFile = json.loads(self.getResource(f'Backup/{self.activeLanguage()}.json').read_text())
filePath = self.getResource(f'dialogTemplate/{self.activeLanguage()}.json')
for i, backupItem in enumerate(backupDialogFile['intents']):
if "userintent" in backupItem['name'].lower():
backupUserIntents = backupItem.get('utterances', list())
for x, activeItem in enumerate(activeDialogFile['intents']):
if "userintent" in activeItem['name'].lower():
activeDialogFile['intents'][x]['utterances'] = backupUserIntents
filePath.write_text(json.dumps(activeDialogFile, ensure_ascii=False, indent=4))
self.mergeDialogSlots()
def mergeDialogSlots(self):
activeDialogFile = json.loads(self.getResource(f'dialogTemplate/{self.activeLanguage()}.json').read_text())
backupDialogFile = json.loads(self.getResource(f'Backup/{self.activeLanguage()}.json').read_text())
filePath = self.getResource(f'dialogTemplate/{self.activeLanguage()}.json')
for i, backupItem in enumerate(backupDialogFile['slotTypes']):
if "haintent" in backupItem['name'].lower():
backupUserSlots = backupItem.get('values', list())
for x, activeItem in enumerate(activeDialogFile['slotTypes']):
if "haintent" in activeItem['name'].lower():
activeDialogFile['slotTypes'][x]['values'] = backupUserSlots
filePath.write_text(json.dumps(activeDialogFile, ensure_ascii=False, indent=4))
if not self._configureActivated:
self.mergeSwitchAndLightDialog(backupItem=backupItem, activeDialogFile=activeDialogFile,
filePath=filePath)