This repository has been archived by the owner on Feb 16, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 41
/
smarthome.py
1411 lines (1228 loc) · 57.8 KB
/
smarthome.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
# -*- coding: utf-8 -*-
import hashlib
import os
import re
import subprocess
import sys
import time
import yaml
from collections.abc import Mapping
from itertools import product
from pid import PidFile
from pathlib import Path
import requests
import trait
from auth import *
from const import (
DOMOTICZ_TO_GOOGLE_TYPES,
ERR_FUNCTION_NOT_SUPPORTED,
ERR_PROTOCOL_ERROR,
ERR_DEVICE_OFFLINE,
ERR_UNKNOWN_ERROR,
ERR_CHALLENGE_NEEDED,
DOMOTICZ_GET_ALL_DEVICES_URL,
DOMAINS,
DOMOTICZ_GET_SETTINGS_URL,
DOMOTICZ_GET_ONE_DEVICE_URL,
DOMOTICZ_GET_SCENES_URL,
DOMOTICZ_GET_PLANS,
CONFIGFILE,
LOGFILE,
REQUEST_SYNC_BASE_URL,
REPORT_STATE_BASE_URL,
ATTRS_BRIGHTNESS,
ATTRS_FANSPEED,
ATTRS_VACUUM_MODES,
ATTRS_THERMSTATSETPOINT,
ATTRS_COLOR_TEMP,
ATTRS_PERCENTAGE,
ATTRS_HUMIDITY,
VERSION,
DOMOTICZ_GET_VERSION
)
from helpers import (
configuration,
readFile,
saveFile,
SmartHomeError,
SmartHomeErrorNoChallenge,
AogState,
uptime,
getTunnelUrl,
FILE_DIR,
logger,
ReportState,
Auth,
logfilepath,
random_string
)
from jinja2 import Environment, FileSystemLoader
if 'Chromecast_Name' in configuration and configuration['Chromecast_Name'] != 'add_chromecast_name':
import pychromecast
import socket
from gtts import gTTS
from slugify import slugify
logger.info("Starting up chromecasts")
try:
chromecasts, _ = pychromecast.get_chromecasts()
cast = next(cc for cc in chromecasts if cc.device.friendly_name == configuration['Chromecast_Name'])
mc = cast.media_controller
except Exception as e:
logger.error('chromecasts init not succeeded, error : %s' % e)
t = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
t.connect(("8.8.8.8", 80))
IP_Address = t.getsockname()[0]
t.close
IP_Port = str(configuration['port_number'])
logger.info("IP_Address is : " + IP_Address)
DOMOTICZ_URL = configuration['Domoticz']['ip'] + ':' + configuration['Domoticz']['port']
CREDITS = (configuration['Domoticz']['username'], configuration['Domoticz']['password'])
file_loader = FileSystemLoader(FILE_DIR + '/templates')
env = Environment(
loader=file_loader
)
if 'PidFile' in configuration:
pidfile = PidFile(pidname=configuration['PidFile'])
else:
pidfile = PidFile('dzga')
try:
logger.info("Connecting to Domoticz on %s" % DOMOTICZ_URL)
r = requests.get(
DOMOTICZ_URL + '/json.htm?type=command¶m=addlogmessage&message=Connected to Google Assistant with DZGA v' + VERSION,
auth=CREDITS, timeout=(2, 5))
r.raise_for_status()
except requests.exceptions.HTTPError as e:
logger.error('Connection to Domoticz refused with error: %s' % e)
try:
import git
repo = git.Repo(FILE_DIR)
branch = repo.active_branch.name
except:
repo = None
branch = ''
ReportState = ReportState()
if not ReportState.enable_report_state():
logger.error("Service account key is not found. Report state will be unavailable")
def checkupdate():
if repo is not None and 'CheckForUpdates' in configuration and configuration['CheckForUpdates'] == True:
try:
r = requests.get(
'https://raw.githubusercontent.com/DewGew/Domoticz-Google-Assistant/' + branch + '/const.py')
response = r.text
if VERSION not in response:
update = 1
else:
update = 0
return update
except Exception as e:
logger.error('Connection to Github refused! Check configuration.')
return 0
else:
return 0
update = checkupdate()
if update:
logger.info("New version is availible on Github!")
# some way to convert a domain type: Domoticz to google
def AogGetDomain(device):
if device["Type"] in ['Light/Switch', 'Lighting 1', 'Lighting 2', 'Lighting 5', 'RFY', 'Value']:
if device["SwitchType"] in ['Blinds', 'Blinds + Stop', 'Venetian Blinds EU', 'Venetian Blinds US',
'Blinds Percentage']:
return DOMAINS['blinds']
elif 'Door Lock' == device["SwitchType"]:
return DOMAINS['lock']
elif 'Door Lock Inverted' == device["SwitchType"]:
return DOMAINS['lockinv']
elif "Door Contact" == device["SwitchType"]:
return DOMAINS['door']
elif "Doorbell" == device["SwitchType"]:
return DOMAINS['doorbell']
elif device["SwitchType"] in ['Push On Button', 'Push Off Button']:
return DOMAINS['push']
elif 'Motion Sensor' == device["SwitchType"]:
return DOMAINS['sensor']
elif 'Selector' == device["SwitchType"]:
if device['Image'] == 'Fan':
return DOMAINS['fan']
else:
return DOMAINS['selector']
elif 'Smoke Detector' == device["SwitchType"]:
return DOMAINS['smokedetector']
elif 'Camera_Stream' in configuration and True == device["UsedByCamera"] and True == configuration['Camera_Stream']['Enabled']:
return DOMAINS['camera']
elif device["Image"] == 'Generic':
return DOMAINS['switch']
elif device["Image"] in ['Media', 'TV']:
return DOMAINS['media']
elif device["Image"] == 'WallSocket':
return DOMAINS['outlet']
elif device["Image"] == 'Speaker':
return DOMAINS['speaker']
elif device["Image"] == 'Fan':
return DOMAINS['fan']
elif device["Image"] == 'Heating':
return DOMAINS['heater']
else:
return DOMAINS['light']
elif 'Blinds' == device["Type"]:
return DOMAINS['blinds']
elif 'Group' == device["Type"]:
return DOMAINS['group']
elif 'Scene' == device["Type"]:
return DOMAINS['scene']
elif device["Type"] in ['Temp', 'Temp + Humidity', 'Temp + Humidity + Baro']:
return DOMAINS['temperature']
elif device['Type'] in ['Thermostat', 'Setpoint']:
return DOMAINS['thermostat']
elif 'Color Switch' == device["Type"]:
if "Dimmer" == device["SwitchType"]:
return DOMAINS['color']
elif "On/Off" == device["SwitchType"]:
logger.info('%s (Idx: %s) is a color switch. To get all functions, set this device as Dimmer in Domoticz', device["Name"], device[
"idx"])
return DOMAINS['light']
elif device["SwitchType"] in ['Push On Button', 'Push Off Button']:
return DOMAINS['push']
elif 'Security' == device["Type"]:
return DOMAINS['security']
return None
def getDesc(state):
if state.domain in [DOMAINS['scene'], DOMAINS['group']]:
if 'Scene_Config' in configuration and configuration['Scene_Config'] is not None:
desc = configuration['Scene_Config'].get(int(state.id), None)
return desc
elif 'Device_Config' in configuration and configuration['Device_Config'] is not None:
desc = configuration['Device_Config'].get(int(state.id), None)
return desc
else:
return None
def getDeviceConfig(descstr):
ISLIST = ['nicknames']
rawconfig = re.findall(r'<voicecontrol>(.*?)</voicecontrol>', descstr, re.DOTALL)
if len(rawconfig) > 0:
try:
lines = rawconfig[0].strip().splitlines()
cfgdict = {}
for l in lines:
assign = l.split('=')
varname = assign[0].strip().lower()
if varname != "":
if varname in ISLIST:
allvalues = assign[1].split(',')
varvalues = []
for val in allvalues:
varvalues.append(val.strip())
cfgdict[varname] = varvalues
else:
varvalue = assign[1].strip()
if varvalue.lower() == "true":
varvalue = True
elif varvalue.lower() == "false":
varvalue = False
cfgdict[varname] = varvalue
except:
logger.error('Error parsing device configuration from Domoticz device description:', rawconfig[0])
return None
return cfgdict
return None
def getAog(device):
domain = AogGetDomain(device)
if domain is None:
return None
aog = AogState()
aog.name = device["Name"] # .encode('ascii', 'ignore')
aog.domain = domain
aog.id = device["idx"]
aog.entity_id = domain + aog.id
aog.plan = device.get("PlanID")
aog.state = device.get("Data")
if aog.domain in [DOMAINS['scene'], DOMAINS['group']]:
aog.state = device.get("Status")
aog.level = device.get("LevelInt", 0)
aog.temp = device.get("Temp")
aog.humidity = device.get("Humidity")
aog.setpoint = device.get("SetPoint")
if aog.domain is DOMAINS['color']:
aog.color = device.get("Color")
aog.protected = device.get("Protected")
aog.maxdimlevel = device.get("MaxDimLevel")
aog.battery = device.get("BatteryLevel")
aog.hardware = device.get("HardwareName")
aog.selectorLevelName = device.get("LevelNames")
aog.lastupdate = device.get("LastUpdate")
aog.language = settings.get("Language")
aog.tempunit = settings.get("TempUnit")
if aog.domain == "Security":
aog.seccode = settings.get("SecPassword")
aog.secondelay = settings.get("SecOnDelay")
# Try to get device specific voice control configuration from Domoticz
# Read it from the configuration file if not in Domoticz (for backward compatibility)
desc = getDeviceConfig(device.get("Description"))
if desc is not None:
logger.debug('<voicecontrol> tags found for idx %s in domoticz description.', aog.id)
logger.debug('Device_Config for idx %s will be ignored in config.yaml!', aog.id)
if desc is None:
desc = getDesc(aog)
if desc is not None:
dt = desc.get('devicetype', None)
if dt is not None:
if aog.domain in [DOMAINS['blinds']]:
if dt.lower() in ['window', 'gate', 'garage', 'door']:
aog.domain = DOMAINS[dt.lower()]
if aog.domain in [DOMAINS['light'], DOMAINS['switch']]:
if dt.lower() in ['window', 'door', 'doorbell', 'gate', 'garage', 'light', 'ac_unit', 'bathtub', 'coffeemaker', 'dishwasher', 'dryer', 'fan', 'heater', 'kettle', 'media', 'microwave', 'outlet', 'oven', 'speaker', 'switch', 'vacuum', 'washer', 'waterheater']:
aog.domain = DOMAINS[dt.lower()]
if aog.domain in [DOMAINS['door']]:
if dt.lower() in ['window', 'gate', 'garage']:
aog.domain = DOMAINS[dt.lower()]
if aog.domain in [DOMAINS['selector']]:
if dt.lower() in ['vacuum']:
aog.domain = DOMAINS[dt.lower()]
if aog.domain in [DOMAINS['camera']]:
if dt.lower() in ['doorbell']:
aog.domain = DOMAINS[dt.lower()]
if aog.domain in [DOMAINS['push']]:
if dt.lower() in ['doorbell', 'outlet', 'light']:
aog.domain = DOMAINS[dt.lower()]
pn = desc.get('name', None)
if pn is not None:
aog.name = pn
n = desc.get('nicknames', None)
if n is not None:
aog.nicknames = n
r = desc.get('room', None)
if r is not None:
aog.room = r
ack = desc.get('ack', False)
if ack:
aog.ack = ack
report_state = desc.get('report_state', True)
if not ReportState.enable_report_state():
aog.report_state = False
if not report_state:
aog.report_state = report_state
if DOMAINS['thermostat'] == aog.domain:
minT = desc.get('minThreehold', None)
if minT is not None:
aog.minThreehold = minT
maxT = desc.get('maxThreehold', None)
if maxT is not None:
aog.maxThreehold = maxT
at_idx = desc.get('actual_temp_idx', None)
if at_idx is not None:
aog.actual_temp_idx = at_idx
try:
aog.state = str(aogDevs[DOMAINS['temperature'] + at_idx].temp)
aogDevs[DOMAINS['temperature'] + at_idx].domain = DOMAINS['merged'] + aog.id + ')'
except:
logger.error('Merge Error, Cant find temperature device with idx %s', at_idx)
modes_idx = desc.get('selector_modes_idx', None)
if modes_idx is not None:
aog.modes_idx = modes_idx
try:
aog.level = aogDevs[DOMAINS['selector'] + modes_idx].level
aog.selectorLevelName = aogDevs[DOMAINS['selector'] + modes_idx].selectorLevelName
aogDevs[DOMAINS['selector'] + modes_idx].domain = DOMAINS['merged'] + aog.id + ')'
except:
logger.error('Merge Error, Cant find selector device with idx %s', modes_idx)
if aog.domain in [DOMAINS['heater'], DOMAINS['kettle'], DOMAINS['waterheater'], DOMAINS['oven']]:
tc_idx = desc.get('merge_thermo_idx', None)
if tc_idx is not None:
aog.merge_thermo_idx = tc_idx
try:
aog.temp = aogDevs[DOMAINS['thermostat'] + tc_idx].state
aog.setpoint = aogDevs[DOMAINS['thermostat'] + tc_idx].setpoint
aogDevs[DOMAINS['thermostat'] + tc_idx].domain = DOMAINS['merged'] + aog.id + ')'
except:
logger.error('Merge Error, Cant find thermostat device with idx %s', tc_idx)
hide = desc.get('hide', False)
if hide:
if aog.domain not in [DOMAINS['scene'], DOMAINS['group']]:
aog.domain = DOMAINS['hidden']
else:
logger.error('Scenes and Groups does not support function "hide" yet')
if aog.domain in [DOMAINS['camera'], DOMAINS['doorbell']]:
aog.report_state = False
if DOMAINS['light'] == aog.domain and "Dimmer" == device["SwitchType"]:
aog.attributes = ATTRS_BRIGHTNESS
if DOMAINS['fan'] == aog.domain and "Selector" == device["SwitchType"]:
aog.attributes = ATTRS_FANSPEED
if DOMAINS['outlet'] == aog.domain and "Dimmer" == device["SwitchType"]:
aog.attributes = ATTRS_BRIGHTNESS
if DOMAINS['color'] == aog.domain and "Dimmer" == device["SwitchType"]:
aog.attributes = ATTRS_BRIGHTNESS
if DOMAINS['color'] == aog.domain and device["SubType"] in ["RGBWW", "RGBWZ", "White"]:
aog.attributes = ATTRS_COLOR_TEMP
if DOMAINS['thermostat'] == aog.domain and "Thermostat" == device["Type"]:
aog.attributes = ATTRS_THERMSTATSETPOINT
if DOMAINS['blinds'] == aog.domain and ("Blinds Percentage" == device["SwitchType"] or "Blinds + Stop" == device["SwitchType"]):
aog.attributes = ATTRS_PERCENTAGE
if DOMAINS['vacuum'] == aog.domain and "Selector" == device["SwitchType"]:
aog.attributes = ATTRS_VACUUM_MODES
if DOMAINS['temperature'] == aog.domain and device["Type"] in ['Temp + Humidity', 'Temp + Humidity + Baro']:
aog.attributes = ATTRS_HUMIDITY
if aog.room == None:
if aog.domain not in [DOMAINS['scene'], DOMAINS['group']]:
if aog.plan != "0":
aog.room = getPlans(aog.plan)
return aog
aogDevsReady = False
aogDevs = {}
deviceList = {}
def getDevices(devices="all", idx="0"):
global aogDevs
global deviceList
url = ""
if "all" == devices:
url = DOMOTICZ_URL + DOMOTICZ_GET_ALL_DEVICES_URL + configuration['Domoticz'][
'roomplan'] + '&filter=all&used=true'
elif "scene" == devices:
url = DOMOTICZ_URL + DOMOTICZ_GET_SCENES_URL
elif "id" == devices:
url = DOMOTICZ_URL + DOMOTICZ_GET_ONE_DEVICE_URL + idx
r = requests.get(url, auth=CREDITS)
if r.status_code == 200:
devs = r.json()['result']
for d in devs:
aog = getAog(d)
if aog is None:
continue
aogDevs[aog.entity_id] = aog
if 'loglevel' in configuration and (configuration['loglevel']).lower() == 'debug':
req = {aog.name: {}}
req[aog.name]['idx'] = int(aog.id)
req[aog.name]['type'] = aog.domain
req[aog.name]['state'] = aog.state
req[aog.name]['lastupdate'] = aog.lastupdate
if aog.nicknames is not None:
req[aog.name]['nicknames'] = aog.nicknames
if aog.modes_idx is not None:
req[aog.name]['modes_idx'] = aog.modes_idx
if aog.hide is not False:
req[aog.name]['hidden'] = aog.hide
if aog.actual_temp_idx is not None:
req[aog.name]['actual_temp_idx'] = aog.actual_temp_idx
if aog.merge_thermo_idx is not None:
req[aog.name]['merge_thermo_idx'] = aog.merge_thermo_idx
req[aog.name]['willReportState'] = aog.report_state
logger.debug(json.dumps(req, indent=2, sort_keys=False, ensure_ascii=False))
devlist = [(d.name, int(d.id), d.domain, d.state, d.room, d.nicknames, d.report_state, d.entity_id) for d in aogDevs.values()]
devlist.sort(key=takeSecond)
deviceList = json.dumps(devlist)
if "all" == devices:
aogDevsReady = True
def takeSecond(elem):
return elem[1]
def deep_update(target, source):
"""Update a nested dictionary with another nested dictionary."""
for key, value in source.items():
if isinstance(value, Mapping):
target[key] = deep_update(target.get(key, {}), value)
else:
target[key] = value
return target
settings = {}
settings['dzversion'] = "Unavailable"
def getSettings():
"""Get domoticz settings."""
global settings
global aogDevsReady
url = DOMOTICZ_URL + DOMOTICZ_GET_SETTINGS_URL
r = requests.get(url, auth=CREDITS)
if r.status_code == 200:
devs = r.json()
settings['SecPassword'] = devs['SecPassword']
settings["SecOnDelay"] = devs["SecOnDelay"]
settings['TempUnit'] = devs['TempUnit']
settings['Language'] = devs['Language']
getVersion()
aogDevsReady = True
logger.debug(json.dumps(settings, indent=2, sort_keys=False, ensure_ascii=False))
def getVersion():
"""Get domoticz version."""
global settings
url = DOMOTICZ_URL + DOMOTICZ_GET_VERSION
r = requests.get(url, auth=CREDITS)
if r.status_code == 200:
vers = r.json()
settings['dzversion'] = vers['version']
def getPlans(idx):
"""Get domoticz plan name."""
global settings
url = DOMOTICZ_URL + DOMOTICZ_GET_PLANS + '&order=name&used=true'
r = requests.get(url, auth=CREDITS)
if r.status_code == 200:
rooms = r.json()['result']
plan = [i for i in rooms if i['idx'] == idx][0]
return plan['Name']
def restartServer():
"""Restart."""
logger.info(' ')
logger.info("Restart server")
logger.info(' ')
time.sleep(5)
pidfile.close()
os.execv(sys.executable, ['python'] + sys.argv)
class _GoogleEntity:
"""Adaptation of Entity expressed in Google's terms."""
def __init__(self, state):
self.state = state
@property
def entity_id(self):
"""Return entity ID."""
return self.state.entity_id
def traits(self):
"""Return traits for entity."""
state = self.state
domain = state.domain
features = state.attributes
t = [Trait(state) for Trait in trait.TRAITS
if Trait.supported(domain, features)]
return t
def sync_serialize(self, agent_user_id):
"""Serialize entity for a SYNC response.
https://developers.google.com/actions/smarthome/create-app#actiondevicessync
"""
state = self.state
enableReport = ReportState.enable_report_state()
traits = self.traits()
# Found no supported traits for this entity
if not traits:
return None
if enableReport:
reportState = state.report_state
else:
reportState = enableReport
device = {
'id': state.entity_id,
'notificationSupportedByAgent': (True if state.domain in [DOMAINS['doorbell'], DOMAINS['smokedetector']] else False),
'name': {
'name': state.name
},
'attributes': {},
'traits': [trait.name for trait in traits],
'willReportState': reportState,
'deviceInfo': {
'manufacturer': "Domoticz",
"model": state.hardware
},
'type': DOMOTICZ_TO_GOOGLE_TYPES[state.domain],
}
# use aliases
aliases = state.nicknames
if aliases:
device['name']['nicknames'] = [state.name] + aliases
for trt in traits:
device['attributes'].update(trt.sync_attributes())
# Add room hint if annotated
room = state.room
if room:
device['roomHint'] = room
if state.domain == DOMAINS['doorbell']:
device['traits'].append('action.devices.traits.ObjectDetection')
return device
def query_serialize(self):
"""Serialize entity for a QUERY response.
https://developers.google.com/actions/smarthome/create-app#actiondevicesquery
"""
state = self.state
# if state.state == STATE_UNAVAILABLE:
# return {'online': False}
attrs = {'online': True, 'status': "SUCCESS"}
for trt in self.traits():
deep_update(attrs, trt.query_attributes())
return attrs
def execute(self, command, params, challenge):
"""Execute a command.
https://developers.google.com/actions/smarthome/create-app#actiondevicesexecute
"""
executed = False
for trt in self.traits():
if trt.can_execute(command, params):
acknowledge = self.state.ack # ack is now stored in state
protect = self.state.protected
pincode = False
if protect or self.state.domain == DOMAINS['security']:
pincode = self.state.seccode
acknowledge = False
if challenge is None:
raise SmartHomeErrorNoChallenge(ERR_CHALLENGE_NEEDED, 'pinNeeded',
'Unable to execute {} for {} - challenge needed '.format(
command, self.state.entity_id))
elif not challenge.get('pin', False):
raise SmartHomeErrorNoChallenge(ERR_CHALLENGE_NEEDED, 'userCancelled',
'Unable to execute {} for {} - challenge needed '.format(
command, self.state.entity_id))
elif self.state.domain == DOMAINS['security'] and pincode != hashlib.md5(
str.encode(challenge.get('pin'))).hexdigest():
raise SmartHomeErrorNoChallenge(ERR_CHALLENGE_NEEDED, 'challengeFailedPinNeeded',
'Unable to execute {} for {} - challenge needed '.format(
command, self.state.entity_id))
if acknowledge:
if challenge is None:
raise SmartHomeErrorNoChallenge(ERR_CHALLENGE_NEEDED, 'ackNeeded',
'Unable to execute {} for {} - challenge needed '.format(
command, self.state.entity_id))
elif not challenge.get('ack', False):
raise SmartHomeErrorNoChallenge(ERR_CHALLENGE_NEEDED, 'userCancelled',
'Unable to execute {} for {} - challenge needed '.format(
command, self.state.entity_id))
trt.execute(command, params, challenge)
executed = True
break
if not executed:
raise SmartHomeError(ERR_FUNCTION_NOT_SUPPORTED,
'Unable to execute {} for {}'.format(command, self.state.entity_id))
def async_update(self):
"""Update the entity with latest info from Domoticz."""
if not self.state:
return
if self.state.domain == DOMAINS['group'] or self.state.domain == DOMAINS['scene']:
getDevices('scene')
else:
getDevices('id', self.state.id)
class SmartHomeReqHandler(OAuthReqHandler):
global smarthomeControlMappings
global aogDevs
def __init__(self, *args, **kwargs):
super(SmartHomeReqHandler, self).__init__(*args, **kwargs)
self._request_id = None
def report_state(self, states, token):
"""Send a state report to Google."""
data = {
'requestId': self._request_id,
'agentUserId': token.get('userAgentId', None),
'payload': {
'devices': {
'states': states,
}
}
}
ReportState.call_homegraph_api(REPORT_STATE_BASE_URL, data)
def smarthome_process(self, message, token):
request_id = self._request_id # type: str
inputs = message.get('inputs') # type: list
if len(inputs) != 1:
return {
'requestId': request_id,
'payload': {'errorCode': ERR_PROTOCOL_ERROR}
}
handler = smarthomeControlMappings.get(inputs[0].get('intent'))
logger.info("Google Assistant requests an " + inputs[0].get('intent'))
if handler is None:
return {'requestId': request_id, 'payload': {'errorCode': ERR_PROTOCOL_ERROR}}
try:
result = handler(self, inputs[0].get('payload'), token)
return {'requestId': request_id, 'payload': result}
except SmartHomeError as err:
return {'requestId': request_id, 'payload': {'errorCode': err.code}}
except Exception as e:
logger.error(e)
return {'requestId': request_id, 'payload': {'errorCode': ERR_UNKNOWN_ERROR}}
def smarthome_post(self, s):
logger.debug(s.headers)
a = s.headers.get('Authorization', None)
token = None
if a is not None:
types, tokenH = a.split()
if types.lower() == 'bearer':
token = Auth['tokens'].get(tokenH, None)
if token is None:
raise SmartHomeError(ERR_PROTOCOL_ERROR, 'not authorized access!!')
message = json.loads(s.body)
self._request_id = message.get('requestId')
logger.info(json.dumps(message, indent=2, sort_keys=True, ensure_ascii=False))
response = self.smarthome_process(message, token)
try:
if 'errorCode' in response['payload']:
logger.error('Error handling message %s: %s' % (message, response['payload']))
except:
pass
s.send_json(200, json.dumps(response, ensure_ascii=False).encode('utf-8'), True)
def syncDevices_post(self, s):
logger.debug(s.headers)
a = s.headers.get('Authorization', None)
token = None
if a is not None:
types, tokenH = a.split()
if types.lower() == 'bearer':
token = Auth['tokens'].get(tokenH, None)
if token is None:
raise SmartHomeError(ERR_PROTOCOL_ERROR, 'not authorized access!!')
r = self.forceDevicesSync()
s.send_message(200, 'Synchronization request sent, status_code: ' + str(r))
def notification_post(self, s):
logger.debug(s.headers)
a = s.headers.get('Authorization', None)
token = None
if a is not None:
types, tokenH = a.split()
if types.lower() == 'bearer':
token = Auth['tokens'].get(tokenH, None)
if token is None:
raise SmartHomeError(ERR_PROTOCOL_ERROR, 'not authorized access!!')
event_id = random_string(10)
request_id = random_string(20)
message = s.body
if '|' in message: message = message.replace('|', ' ').split()
if '>>' in message: message.remove('>>')
devid = message[0]
state = message[1]
aog = aogDevs.get(devid, None)
if aog != None:
if aog.domain in DOMAINS['doorbell']:
data = {
'requestId': str(request_id),
'agentUserId': token.get('userAgentId', None),
'eventId': str(event_id),
'payload': {
'devices': {
'states': {
devid: {
'on': (True if state.lower() in ['on', 'pressed'] else False)
},
},
'notifications': {
devid: {
"ObjectDetection": {
"objects": {
"unfamiliar": 1
},
"priority": 0,
"detectionTimestamp": time.time()
}
}
}
}
}
}
ReportState.call_homegraph_api(REPORT_STATE_BASE_URL, data)
elif aog.domain in DOMAINS['smokedetector']:
data = {
'requestId': str(request_id),
'agentUserId': token.get('userAgentId', None),
'eventId': str(event_id),
'payload': {
'devices': {
'states': {
devid: {
'on': (True if state.lower() in ['on', 'alarm/fire'] else False)
},
},
'notifications': {
devid: {
'SensorState': {
'priority': 0,
'name': 'SmokeLevel',
'currentSensorState': 'smoke detected'
}
}
}
}
}
}
ReportState.call_homegraph_api(REPORT_STATE_BASE_URL, data)
else:
logger.info('Notification is not supported for ' + message[0])
elif message == 'Domoticz test message!':
logger.info('Great! Test is working, Now add custom message e.g "light123|$value" in the device notification settings')
else:
logger.error('Something went wrong, check your notification settings!')
def smarthome(self, s):
s.send_message(500, "not supported")
def forceDevicesSync(self):
userAgent = self.getUserAgent()
enableReport = ReportState.enable_report_state()
if userAgent is None:
# return 500 # internal error
userAgent = "1234"
data = {"agentUserId": userAgent}
if enableReport:
r = ReportState.call_homegraph_api(REQUEST_SYNC_BASE_URL, data)
logger.info('Device syncronization sent')
elif 'Homegraph_API_Key' in configuration and configuration['Homegraph_API_Key'] != 'ADD_YOUR HOMEGRAPH_API_KEY_HERE':
r = ReportState.call_homegraph_api_key(REQUEST_SYNC_BASE_URL, data)
logger.info('Device syncronization sent')
else:
logger.error("No configuration for request_sync available")
return r
def syncDevices(self, s):
user = self.getSessionUser()
if user is None or user.get('uid', '') == '':
s.redirect('login?redirect_uri={0}'.format('sync'))
return
r = self.forceDevicesSync()
s.send_message(200, 'Synchronization request sent, status_code: ' + str(r))
def restartServer(self, s):
user = self.getSessionUser()
if user is None or user.get('uid', '') == '':
s.redirect('login?redirect_uri={0}'.format('restart'))
return
s.send_message(200, 'Restart request sent, status_code: True')
restartServer()
def log(self, s):
user = self.getSessionUser()
if user is None or user.get('uid', '') == '':
s.redirect('login?redirect_uri={0}'.format('log'))
return
latestlogs = readFile(os.path.join(logfilepath, LOGFILE))
s.send_message(200, latestlogs)
def states(self, s):
user = self.getSessionUser()
if user is None or user.get('uid', '') == '':
s.redirect('login?redirect_uri={0}'.format('log'))
return
deviceList
s.send_message(200, deviceList)
def settings(self, s):
user = self.getSessionUser()
if user is None or user.get('uid', '') == '':
s.redirect('login?redirect_uri={0}'.format('settings'))
return
enableReport = ReportState.enable_report_state()
update = checkupdate()
public_url = getTunnelUrl()
message = ''
meta = '<!-- <meta http-equiv="refresh" content="5"> -->'
code = readFile(os.path.join(FILE_DIR, CONFIGFILE))
templatepage = env.get_template('home.html')
s.send_message(200, templatepage.render(message=message, uptime=uptime(), meta=meta, code=code,
conf=configuration, public_url=public_url, update=update, keyfile=enableReport,
branch=branch, dzversion=settings['dzversion'], dzgaversion=VERSION))
def settings_post(self, s):
enableReport = ReportState.enable_report_state()
update = checkupdate()
public_url = getTunnelUrl()
code = readFile(os.path.join(FILE_DIR, CONFIGFILE))
meta = '<!-- <meta http-equiv="refresh" content="5"> -->'
if s.form.get("save"):
textToSave = s.form.get("save", None)
codeToSave = textToSave.replace("+", " ")
saveFile(CONFIGFILE, codeToSave)
message = 'Configuration saved. Restart DZGA for the settings to take effect'
logger.info(message)
logs = readFile(os.path.join(logfilepath, LOGFILE))
templatepage = env.get_template('home.html')
s.send_message(200, templatepage.render(message=message, uptime=uptime(), meta=meta, code=code,
conf=configuration, public_url=public_url, update=update, keyfile=enableReport,
branch=branch, dzversion=settings['dzversion'], dzgaversion=VERSION))
if s.form.get("backup"):
codeToSave = readFile(os.path.join(FILE_DIR, CONFIGFILE))
saveFile('config/config.yaml.bak', codeToSave)
message = 'Backup saved'
logger.info(message)
templatepage = env.get_template('home.html')
s.send_message(200, templatepage.render(message=message, uptime=uptime(), meta=meta, code=code,
conf=configuration, public_url=public_url, update=update, keyfile=enableReport,
branch=branch, dzversion=settings['dzversion'], dzgaversion=VERSION))
if s.form.get("restart"):
meta = '<meta http-equiv="refresh" content="10">'
message = 'Restarts DZGA server'
templatepage = env.get_template('home.html')
s.send_message(200, templatepage.render(message=message, uptime=uptime(), meta=meta, code=code,
conf=configuration, public_url=public_url, update=update, keyfile=enableReport,
branch=branch, dzversion=settings['dzversion'], dzgaversion=VERSION))
restartServer()
if s.form.get("sync"):
if 'Homegraph_API_Key' in configuration and configuration['Homegraph_API_Key'] != 'ADD_YOUR HOMEGRAPH_API_KEY_HERE' or enableReport == True:
r = self.forceDevicesSync()
time.sleep(0.5)
if r:
message = 'Devices syncronized'
else:
message = 'Homegraph api key not valid!'
else:
message = 'Add Homegraph api key or a Homegraph Service Account json file to sync devices in the UI! You can still sync by voice eg. "Hey Google, Sync my devices".'
templatepage = env.get_template('home.html')
s.send_message(200, templatepage.render(message=message, uptime=uptime(), meta=meta, code=code,
conf=configuration, public_url=public_url, update=update, keyfile=enableReport,
branch=branch, dzversion=settings['dzversion'], dzgaversion=VERSION))
if s.form.get("reload"):
message = ''
templatepage = env.get_template('home.html')
s.send_message(200, templatepage.render(message=message, uptime=uptime(), meta=meta, code=code,
conf=configuration, public_url=public_url, update=update, keyfile=enableReport,
branch=branch, dzversion=settings['dzversion'], dzgaversion=VERSION))
if s.form.get("deletelogs"):
logfile = os.path.join(logfilepath, LOGFILE)
if os.path.exists(logfile):
f = open(logfile, 'w')
f.close()
logger.info('Logs removed by user')
message = 'Logs removed'
templatepage = env.get_template('home.html')
s.send_message(200, templatepage.render(message=message, uptime=uptime(), meta=meta, code=code,
conf=configuration, public_url=public_url, update=update, keyfile=enableReport,
branch=branch, dzversion=settings['dzversion'], dzgaversion=VERSION))
if s.form.get("update"):
repo.git.reset('--hard')
repo.remotes.origin.pull()
message = 'Updating to latest ' + branch + ', please wait a minute!'
meta = '<meta http-equiv="refresh" content="20">'
templatepage = env.get_template('home.html')
s.send_message(200, templatepage.render(message=message, uptime=uptime(), meta=meta, code=code,