-
Notifications
You must be signed in to change notification settings - Fork 5
/
__init__.py
executable file
·967 lines (883 loc) · 39.3 KB
/
__init__.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
# Copyright 2018-2019, domcross
# Github https://github.com/domcross
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from adapt.intent import IntentBuilder
from mycroft import intent_handler, intent_file_handler
from mycroft.api import DeviceApi
from mycroft.skills.core import FallbackSkill
from mycroft.util.log import LOG
#from mycroft.util.parse import match_one
# from os.path import dirname, join
from rapidfuzz import fuzz
import re
import fhem as python_fhem
__author__ = 'domcross'
REQUIRED_RATIO_FOR_BONUS = 89
BONUS = 25
class FhemSkill(FallbackSkill):
def __init__(self):
super(FhemSkill, self).__init__(name="FhemSkill")
LOG.info("__init__")
self.fhem = None
self.enable_fallback = False
self.device_location = ""
def _setup(self, force=False):
# when description of home.mycroft.ai > Devices > [this mycroft device]
# is filled, use this the name of the room where mycroft is located
if self.settings.get('device_location', False):
dev = DeviceApi()
info = dev.get()
if 'description' in info:
self.device_location = info['description']
LOG.debug("mycroft device location: {}".format(self.device_location))
if self.settings and (force or self.fhem is None):
LOG.debug("_setup")
portnumber = self.settings.get('portnum')
try:
portnumber = int(portnumber)
except TypeError:
portnumber = 8083
except ValueError:
# String might be some rubbish (like '')
portnumber = 0
self.fhem = \
python_fhem.Fhem(self.settings.get('host'),
port=portnumber, csrf=True,
protocol=self.settings.get('protocol',
'http').lower(),
use_ssl=self.settings.get('ssl', False),
username=self.settings.get('username'),
password=self.settings.get('password')
)
self.fhem.connect()
LOG.debug("connect: {}".format(self.fhem.connected()))
if self.fhem.connected():
self.allowed_devices_room = self.settings.get('room', 'Homebridge')
self.ignore_rooms = self.settings.get('ignore_rooms', '')
# Check if natural language control is loaded at fhem-server
# and activate fallback accordingly
LOG.debug("fallback_device_name %s" %
self.settings.get('fallback_device_name'))
LOG.debug("enable_fallback %s" %
self.settings.get('enable_fallback'))
if self.settings.get('enable_fallback') and \
self.settings.get('fallback_device_name', ""):
fallback_device = \
self.fhem.get_device(self.settings.get(
'fallback_device_name', ""))
if fallback_device:
# LOG.debug("fallback device {}".format(fallback_device))
self.fallback_device_name = self.settings.get(
'fallback_device_name', "")
self.fallback_device_type = self.fhem.get_internals(
"TYPE", name=self.fallback_device_name)[
self.fallback_device_name]
LOG.debug("fallback_device_type is %s" %
self.fallback_device_type)
if self.fallback_device_type in ["Talk2Fhem",
"TEERKO",
"Babble"]:
self.enable_fallback = True
else:
self.enable_fallback = False
else:
self.enable_fallback = False
LOG.debug('fhem-fallback enabled: %s' % self.enable_fallback)
def initialize(self):
self._setup(True)
# Needs higher priority than general fallback skills
self.register_fallback(self.handle_fallback, 2)
# Check and then monitor for credential changes
self.settings_change_callback = self.on_websettings_changed
# registering entities, is that actually necessary?
self.register_entity_file('action.entity')
self.register_entity_file('room.entity')
self.register_entity_file('open.entity')
self.register_entity_file('close.entity')
#self.register_entity_file('blind.entity')
def on_websettings_changed(self):
# Only attempt to load if the host is set
LOG.debug("websettings changed")
if self.settings.get('host', None):
try:
self._setup(force=True)
except Exception:
pass
#@intent_file_handler('blind.intent')
def handle_blind_intent(self, message):
self._setup()
if self.fhem is None:
self.speak_dialog('fhem.error.setup')
return
LOG.info("Starting Blind Intent")
LOG.info("message.data {}".format(message.data))
device = message.data.get("device")
action = ""
percent = None
if message.data.get("open"):
action = "open"
speak_action = message.data.get("open")
target_pct = 0
elif message.data.get("close"):
action = "closed" # sic!
speak_action = message.data.get("close")
target_pct = 100
elif message.data.get("percent"):
percent = message.data.get("percent")
if percent.isdigit():
action = "pct"
target_pct = int(percent)
if not action:
LOG.info("no action for blind intent found!")
return False
if message.data.get("room"):
room = message.data.get("room")
else:
# if no room is given use device location
room = self.device_location
allowed_types = 'blind'
LOG.info("Device: %s" % device)
LOG.info("Action: %s" % action)
LOG.info("Room: %s" % room)
if percent:
LOG.info("Percent: %s" % percent)
try:
fhem_device = self._find_device(device, allowed_types, room)
except ConnectionError:
self.speak_dialog('fhem.error.offline')
return
if fhem_device is None:
self.speak_dialog('fhem.device.unknown', data={"dev_name": device})
return
LOG.info("Entity State: %s" % fhem_device['state'])
open_pct = 0
closed_pct = 100
blind = self.fhem.get_device(fhem_device['id'])[0]
if blind['Internals']['TYPE'] == 'ROLLO':
if action == "pct":
self.fhem.send_cmd("set {} pct {}".format(fhem_device['id'],
target_pct))
self.speak_dialog('fhem.blind.set',
data={"device": device,
"percent": target_pct})
else:
self.fhem.send_cmd("set {} {}".format(fhem_device['id'],
action))
self.speak_dialog('fhem.blind', data={"device": device,
"action": speak_action,
"room": room})
else:
self.speak_dialog('fhem.error.notsupported')
return
@intent_file_handler('switch.intent')
def handle_switch_intent(self, message):
self._setup()
if self.fhem is None:
self.speak_dialog('fhem.error.setup')
return
LOG.debug("Starting Switch Intent")
LOG.debug("message.data {}".format(message.data))
device = message.data.get("device")
if message.data.get("action"):
action = message.data.get("action")
self.log.info("action: {}".format(action))
else:
# when no action is given toggle the device
action = "toggle"
if message.data.get("room"):
room = message.data.get("room")
else:
# if no room is given use device location
room = self.device_location
allowed_types = '(light|switch|outlet)'
LOG.debug("Device: %s" % device)
LOG.debug("Action: %s" % action)
LOG.debug("Room: %s" % room)
# TODO if entity is 'all', 'any' or 'every' turn on
# every single entity not the whole group
try:
fhem_device = self._find_device(device, allowed_types, room)
except ConnectionError:
self.speak_dialog('fhem.error.offline')
return
if fhem_device is None:
self.speak_dialog('fhem.device.unknown', data={"dev_name": device})
return
LOG.debug("Entity State: %s" % fhem_device['state'])
# fhem_data = {'entity_id': fhem_entity['id']}
# keep original actioname for speak_dialog
# when device already is in desiredstate
if action != 'toggle':
original_action = action
else:
original_action = self.translate('toggle_keyword')
action_values = self.translate_namedvalues('actions.value')
if action in action_values.keys():
action = action_values[action]
LOG.debug("- action: %s" % action)
LOG.debug("- state: %s" % fhem_device['state']['Value'])
if fhem_device['state']['Value'] == action:
LOG.debug("Entity in requested state")
self.speak_dialog('fhem.device.already', data={
'dev_name': fhem_device['dev_name'],
'action': original_action})
elif action == 'toggle':
if(fhem_device['state']['Value'] == 'off'):
action = 'on'
else:
action = 'off'
LOG.debug("toggled action: %s" % action)
self.fhem.send_cmd("set {} {}".format(fhem_device['id'], action))
self.speak_dialog('fhem.switch',
data={'dev_name': fhem_device['dev_name'],
'action': original_action})
elif action in ["on", "off"]:
LOG.debug("action: on/off")
self.speak_dialog('fhem.switch',
data={'dev_name': fhem_device['dev_name'],
'action': original_action})
self.fhem.send_cmd("set {} {}".format(fhem_device['id'], action))
else:
self.speak_dialog('fhem.error.sorry')
return
@intent_handler(IntentBuilder("").optionally("LightsKeyword")
.require("SetVerb").require("Device")
.require("BrightnessValue").build())
def handle_light_set_intent(self, message):
# TODO not supported yet
self.speak_dialog('fhem.error.notsupported')
return
#
self._setup()
if(self.fhem is None):
self.speak_dialog('fhem.error.setup')
return
device = message.data["Device"]
allowed_types = ['light'] # TODO
try:
brightness_req = float(message.data["BrightnessValue"])
if brightness_req > 100 or brightness_req < 0:
self.speak_dialog('fhem.brightness.badreq')
except KeyError:
brightness_req = 10.0
brightness_value = int(brightness_req / 100 * 255)
brightness_percentage = int(brightness_req)
LOG.debug("device: %s" % device)
LOG.debug("Brightness Value: %s" % brightness_value)
LOG.debug("Brightness Percent: %s" % brightness_percentage)
try:
fhem_device = self.fhem.find_device(device, allowed_types)
except ConnectionError:
self.speak_dialog('fhem.error.offline')
return
if fhem_device is None:
self.speak_dialog('fhem.device.unknown', data={
"dev_name": device})
return
fhem_data = {'device_id': fhem_device['id']}
# IDEA: set context for 'turn it off again' or similar
# self.set_context('Entity', fhem_entity['dev_name'])
# TODO - Allow value set
if "SetVerb" in message.data:
fhem_data['brightness'] = brightness_value
fhem_data['dev_name'] = fhem_device['dev_name']
self.fhem.execute_service("fhem", "turn_on", fhem_data)
self.speak_dialog('fhem.brightness.dimmed',
data=fhem_data)
else:
self.speak_dialog('fhem.error.sorry')
return
@intent_handler(IntentBuilder("").optionally("LightsKeyword")
.one_of("IncreaseVerb", "DecreaseVerb",
"LightBrightenVerb", "LightDimVerb")
.require("Device").optionally("BrightnessValue").build())
def handle_light_adjust_intent(self, message):
# TODO not supported yet
self.speak_dialog('fhem.error.notsupported')
return
#
self._setup()
if self.fhem is None:
self.speak_dialog('fhem.error.setup')
return
allowed_types = ['light']
device = message.data["Device"]
try:
brightness_req = float(message.data["BrightnessValue"])
if brightness_req > 100 or brightness_req < 0:
self.speak_dialog('fhem.brightness.badreq')
except KeyError:
brightness_req = 10.0
brightness_value = int(brightness_req / 100 * 255)
# brightness_percentage = int(brightness_req) # debating use
LOG.debug("device: %s" % device)
LOG.debug("Brightness Value: %s" % brightness_value)
try:
fhem_device = self.fhem.find_device(device, allowed_types)
except ConnectionError:
self.speak_dialog('fhem.error.offline')
return
if fhem_device is None:
self.speak_dialog('fhem.device.unknown', data={
"dev_name": device})
return
fhem_data = {'device_id': fhem_device['id']}
# IDEA: set context for 'turn it off again' or similar
# self.set_context('Entity', fhem_entity['dev_name'])
# if self.lang == 'de':
# if action == 'runter' or action == 'dunkler':
# action = 'dim'
# elif action == 'heller' or action == 'hell':
# action = 'brighten'
if "DecreaseVerb" in message.data or \
"LightDimVerb" in message.data:
if fhem_device['state'] == "off":
self.speak_dialog('fhem.brightness.cantdim.off',
data=fhem_device)
else:
light_attrs = self.fhem.find_entity_attr(fhem_device['id'])
if light_attrs['unit_measure'] is None:
self.speak_dialog(
'fhem.brightness.cantdim.dimmable',
data=fhem_device)
else:
fhem_data['brightness'] = light_attrs['unit_measure']
if fhem_data['brightness'] < brightness_value:
fhem_data['brightness'] = 10
else:
fhem_data['brightness'] -= brightness_value
self.fhem.execute_service("fhem", "turn_on", fhem_data)
fhem_data['dev_name'] = fhem_device['dev_name']
self.speak_dialog('fhem.brightness.decreased',
data=fhem_data)
elif "IncreaseVerb" in message.data or \
"LightBrightenVerb" in message.data:
if fhem_device['state'] == "off":
self.speak_dialog(
'fhem.brightness.cantdim.off',
data=fhem_device)
else:
light_attrs = self.fhem.find_entity_attr(fhem_device['id'])
if light_attrs['unit_measure'] is None:
self.speak_dialog(
'fhem.brightness.cantdim.dimmable',
data=fhem_device)
else:
fhem_data['brightness'] = light_attrs['unit_measure']
if fhem_data['brightness'] > brightness_value:
fhem_data['brightness'] = 255
else:
fhem_data['brightness'] += brightness_value
self.fhem.execute_service("fhem", "turn_on", fhem_data)
fhem_data['dev_name'] = fhem_device['dev_name']
self.speak_dialog('fhem.brightness.increased',
data=fhem_data)
else:
self.speak_dialog('fhem.error.sorry')
return
@intent_handler(IntentBuilder("").require("AutomationActionKeyword")
.require("Entity").build())
def handle_automation_intent(self, message):
# TODO not supported yet
self.speak_dialog('fhem.error.notsupported')
return
#
self._setup()
if self.fhem is None:
self.speak_dialog('fhem.error.setup')
return
entity = message.data["Entity"]
allowed_types = ['automation', 'scene', 'script'] # TODO
LOG.debug("Entity: %s" % entity)
# also handle scene and script requests
try:
fhem_entity = self.fhem.find_device(entity, allowed_types)
except ConnectionError:
self.speak_dialog('fhem.error.offline')
return
fhem_data = {'entity_id': fhem_entity['id']}
if fhem_entity is None:
self.speak_dialog('fhem.device.unknown', data={
"dev_name": entity})
return
# IDEA: set context for 'turn it off again' or similar
# self.set_context('Entity', fhem_entity['dev_name'])
LOG.debug("Triggered automation/scene/script: {}".format(fhem_data))
if "automation" in fhem_entity['id']:
self.fhem.execute_service('automation', 'trigger', fhem_data)
self.speak_dialog('fhem.automation.trigger',
data={"dev_name": fhem_entity['dev_name']})
elif "script" in fhem_entity['id']:
self.speak_dialog('fhem.automation.trigger',
data={"dev_name": fhem_entity['dev_name']})
self.fhem.execute_service("fhem", "turn_on", data=fhem_data)
elif "scene" in fhem_entity['id']:
self.speak_dialog('fhem.device.on',
data=fhem_entity)
self.fhem.execute_service("fhem", "turn_on", data=fhem_data)
@intent_file_handler('sensor.intent')
def handle_sensor_intent(self, message):
self._setup()
if self.fhem is None:
self.speak_dialog('fhem.error.setup')
return
device = message.data.get("device")
if message.data.get("room"):
room = message.data.get("room")
else:
# if no room is given use device location
room = self.device_location
allowed_types = '(sensor|thermometer)'
LOG.debug("device: %s" % device)
try:
fhem_device = self._find_device(device, allowed_types, room)
except ConnectionError:
self.speak_dialog('fhem.error.offline')
return
if fhem_device is None:
self.speak_dialog('fhem.device.unknown', data={
"dev_name": device})
return
device = fhem_device['id']
sensor_name = fhem_device['dev_name']
sensor_state = ""
sensor_unit = ""
sensor_values = self.translate_namedvalues('sensor.value')
tokens = fhem_device['state']['Value'].split(" ")
for t in range(0, len(tokens)):
tok = tokens[t].lower().replace(":", "")
# LOG.debug("tok = %s" % tok)
if tok in ['t', 'temp', 'temperatur', 'temperature']:
sensor_state += sensor_values["temperature"]
elif tok in ['h', 'hum', 'humidity']:
sensor_state += sensor_values["humidity"]
elif tok in ['p', 'pamb', 'press', 'pressure']:
sensor_state += sensor_values["pressure"]
else:
sensor_state += tokens[t]
sensor_state += " "
LOG.debug("fhem_device['state']['Value']: %s" %
fhem_device['state']['Value'])
LOG.debug("sensor_state: %s" % sensor_state)
self.speak_dialog('fhem.sensor', data={
"dev_name": sensor_name,
"value": sensor_state,
"unit": sensor_unit})
# # IDEA: set context for 'read it out again' or similar
# # self.set_context('Entity', fhem_entity['dev_name'])
#
# unit_measurement = self.fhem.find_entity_attr(entity)
# if unit_measurement[0] is not None:
# sensor_unit = unit_measurement[0]
# else:
# sensor_unit = ''
#
# sensor_name = unit_measurement[1]
# sensor_state = unit_measurement[2]
# # extract unit for correct pronounciation
# # this is fully optional
# try:
# from quantulum import parser
# quantulumImport = True
# except ImportError:
# quantulumImport = False
#
# if quantulumImport and unit_measurement != '':
# quantity = parser.parse((u'{} is {} {}'.format(
# sensor_name, sensor_state, sensor_unit)))
# if len(quantity) > 0:
# quantity = quantity[0]
# if (quantity.unit.name != "dimensionless" and
# quantity.uncertainty <= 0.5):
# sensor_unit = quantity.unit.name
# sensor_state = quantity.value
#
# self.speak_dialog('fhem.sensor', data={
# "dev_name": sensor_name,
# "value": sensor_state,
# "unit": sensor_unit})
# # IDEA: Add some context if the person wants to look the unit up
# # Maybe also change to name
# # if one wants to look up "outside temperature"
# # self.set_context("SubjectOfInterest", sensor_unit)
@intent_file_handler('presence.intent')
def handle_presence_intent(self, message):
self._setup()
if self.fhem is None:
self.speak_dialog('fhem.error.setup')
return
wanted = message.data["entity"]
LOG.debug("wanted: %s" % wanted)
try:
roommates = self.fhem.get(room=self.allowed_devices_room,
device_type='ROOMMATE')
except ConnectionError:
self.speak_dialog('fhem.error.offline')
return
if len(roommates) < 1:
self.speak_dialog('fhem.presence.error')
return
presence = None
bestRatio = 66
for rm in roommates:
if 'rr_realname' in rm['Attributes'].keys():
realname = rm['Attributes'][rm['Attributes']['rr_realname']]
LOG.debug("realname: %s" % realname)
ratio = fuzz.ratio(wanted.lower(), realname.lower(),
score_cutoff=bestRatio)
LOG.debug("ratio: %s" % ratio)
if ratio > bestRatio:
presence = rm['Readings']['presence']['Value']
bestName = realname
bestRatio = ratio
presence_values = self.translate_namedvalues('presence.value')
if presence:
location = presence_values[presence]
self.speak_dialog('fhem.presence.found',
data={'wanted': bestName,
'location': location})
else:
self.speak_dialog('fhem.presence.error')
@intent_file_handler('set.climate.intent')
def handle_set_thermostat_intent(self, message):
self._setup()
if self.fhem is None:
self.speak_dialog('fhem.error.setup')
return
LOG.debug("Starting Thermostat Intent")
if message.data.get("device"):
device = message.data.get("device")
else:
device = "thermostat"
if message.data.get("room"):
room = message.data.get("room")
else:
room = self.device_location
LOG.debug("Device: %s" % device)
LOG.debug("This is the message data: %s" % message.data)
temperature = message.data["temp"]
LOG.debug("desired temperature from message: %s" % temperature)
allowed_types = 'thermostat'
try:
fhem_device = self._find_device(device, allowed_types, room)
except ConnectionError:
self.speak_dialog('fhem.error.offline')
return
if fhem_device is None:
self.speak_dialog('fhem.device.unknown', data={"dev_name": device})
return
LOG.debug("Entity State: %s" % fhem_device['state'])
device_id = fhem_device['id']
target_device = device_id
# defaults for min/max temp and step
minValue = 5.0
maxValue = 35.0
minStep = 0.5
unit = ""
cmd = ""
# check thermostat type, derive command and min/max values
LOG.debug("fhem_device: %s" % fhem_device)
# for that get thermostat device
td = self.fhem.get_device(fhem_device['id'])
if len(td) != 1:
self.speak_dialog('fhem.device.unknown', data={"dev_name": device})
return
td = td[0]
LOG.debug("td: %s" % td)
if 'desired-temp' in td['Readings']:
cmd = "desired-temp"
if ('FBTYPE' in td['Readings']) and \
(td['Readings']['FBTYPE'] == 'Comet DECT'):
# LOG.debug("Comet DECT")
minValue = 8.0
maxValue = 28.0
elif td['Internals']['TYPE'] == 'FHT':
# LOG.debug("FHT")
minValue = 6.0
maxValue = 30.0
elif td['Internals']['TYPE'] == 'CUL_HM':
LOG.debug("HM")
# test for Clima-Subdevice
if 'channel_04' in td['Internals']:
target_device = td['Internals']['channel_04']
elif 'desiredTemperature' in td['Readings']:
# LOG.debug("MAX")
cmd = "desiredTemperature"
minValue = 4.5
maxValue = 30.5
elif 'desired' in td['Readings']:
# LOG.debug("PID20")
cmd = "desired"
elif 'homebridgeMapping' in td['Attributes']:
LOG.debug("homebridgeMapping")
hbm = td['Attributes']['homebridgeMapping'].split(" ")
for h in hbm:
# TargetTemperature=desired-temp::desired-temp,
# minValue=5,maxValue=35,minStep=0.5,nocache=1
if h.startswith("TargetTemperature"):
targettemp = (h.split("=", 1)[1]).split(",")
LOG.debug("targettemp = %s" % targettemp)
for t in targettemp:
LOG.debug("t = %s" % t)
if t.startswith("desired-temp"):
t2 = t.split(":")
cmd = t2[0]
if t2[1] != '':
target_device = t2[1]
elif t.startswith("minValue"):
minValue = float(t.split("=")[1])
elif t.startswith("maxValue"):
maxValue = float(t.split("=")[1])
elif t.startswith("minStep"):
minStep = float(t.split("=")[1])
if not cmd:
LOG.info("FHEM device %s has unknown thermostat type" % device_id)
self.speak_dialog('fhem.error.notsupported')
return
LOG.debug("target_device: %s cmd: %s" % (target_device, cmd))
LOG.debug("minValue: %s maxValue: %s minStep: %s" % (minValue, maxValue,
minStep))
# check if desired temperature is out of bounds
if (float(temperature) < minValue) or (float(temperature) > maxValue) \
or (float(temperature) % minStep != 0.0):
self.speak_dialog('fhem.thermostat.badreq',
data={"minValue": minValue,
"maxValue": maxValue,
"minStep": minStep})
return
action = "%s %s" % (cmd, temperature)
LOG.debug("set %s %s" % (target_device, action))
self.fhem.send_cmd("set {} {}".format(target_device, action))
self.speak_dialog('fhem.set.thermostat',
data={
"dev_name": device,
"value": temperature,
"unit": unit})
def handle_fallback(self, message):
LOG.debug("entering handle_fallback with utterance '%s'" %
message.data.get('utterance'))
self._setup()
if self.fhem is None:
LOG.debug("FHEM setup error")
self.speak_dialog('fhem.error.setup')
return False
if not self.enable_fallback:
LOG.debug("fallback not enabled!")
return False
# pass message to FHEM-server
try:
# TODO check response after switch to python-fhem lib
if self.fallback_device_type == "TEERKO":
# LOG.debug("fallback device type TEERKO")
response = self.fhem.send_cmd(
"set {} TextCommand {}".format(self.fallback_device_name,
message.data.get('utterance')))
elif self.fallback_device_type == "Talk2Fhem":
# LOG.debug("fallback device type Talk2Fhem")
response = self.fhem.send_cmd(
"set {} {}".format(self.fallback_device_name,
message.data.get('utterance')))
elif self.fallback_device_type == "Babble":
# LOG.debug("fallback device type Babble")
cmd = '{Babble_DoIt("%s","%s","testit","1")}' % \
(self.fallback_device_name, message.data.get('utterance'))
response = self.fhem.send_cmd(cmd)
# Babble gives feedback through response
# existence of string '[Babble_Normalize]' means success!
if response.text.find('[Babble_Normalize]') > 0:
return True
else:
return False
else:
LOG.debug("fallback device type UNKNOWN")
return False
except ConnectionError:
LOG.debug("connection error")
self.speak_dialog('fhem.error.offline')
return False
fdn = self.fallback_device_name
result = self.fhem.get_readings(name=fdn)
LOG.debug("result: %s" % result)
if not result:
# LOG.debug("no result")
return False
answer = ""
if self.fallback_device_type == "Talk2Fhem":
if result[fdn]['status']['Value'] == 'answers':
# LOG.debug("answering with Talk2Fhem result")
answer = result[fdn]['answers']['Value']
else:
return False
elif self.fallback_device_type == "TEERKO":
if result[fdn]['Answer']['Value'] is not None:
# LOG.debug("answering with TEERKO result")
answer = result[fdn]['Answer']['Value']
else:
return False
# Babble gives feedback through response, so nothing to do here
else:
# LOG.debug("status undefined")
return False
if answer == "":
# LOG.debug("empty answer")
return False
asked_question = False
# TODO: maybe enable conversation here if server asks sth like
# "In which room?" => answer should be directly passed to this skill
if answer.endswith("?"):
LOG.debug("answer endswith question mark")
asked_question = True
self.speak(answer, expect_response=asked_question)
return True
def _find_device(self, device, allowed_types, room=""):
LOG.debug("device: {} allowed_types: {} room: {}".format(device,
allowed_types,
room))
filter_dict = {'genericDeviceType': allowed_types}
# new search strategy: first check if there is a fit in specified room
if room:
room = self._normalize(self._clean_common_words(room))
# LOG.debug("normalized room: {}".format(room))
filter_dict['room'] = room
device_candidates = self.fhem.get(room=self.allowed_devices_room,
filters=filter_dict)
if len(device_candidates) == 1:
# TODO can we do anything if len(...) > 1 ?
LOG.debug("perfect match")
# we have a perfect match:
# there is only one device of the allowed type in the room
dc = device_candidates[0]
best_device = {"id": dc['Name'],
"dev_name": self._get_aliasname(dc),
"state": dc['Readings']['state'],
"best_score": 999}
return best_device
# try again without filter on room
if 'room' in filter_dict.keys():
LOG.debug("try again without filter on room")
del filter_dict['room']
device_candidates = self.fhem.get(room=self.allowed_devices_room,
filters=filter_dict)
# LOG.debug(device_candidates)
# require a score above 50%
best_score = 50
best_device = None
if device_candidates:
for dc in device_candidates:
# LOG.debug("==================================================")
norm_name = self._normalize(dc['Name'])
norm_name_list = norm_name.split(" ")
# LOG.debug("norm_name_list = %s" % norm_name_list)
dev_room = self._get_normalized_room_list(dc)
for r in dev_room:
if (r not in norm_name_list):
norm_name += (" " + self._normalize(r))
# LOG.debug("dev_room: {}".format(dev_room))
# LOG.debug("norm_name = %s" % norm_name)
alias = self._get_aliasname(dc)
norm_alias = self._normalize(alias)
try:
if (norm_name != norm_alias) and ('alias' in
dc['Attributes']):
score = fuzz.token_sort_ratio(
device,
norm_alias)
# add bonus if room name match
if room and dev_room:
score += self._get_bonus_for_room(room,
dev_room[0])
if score > best_score:
best_score = score
best_device = {
"id": dc['Name'],
"dev_name": alias,
"state": dc['Readings']['state'],
"best_score": best_score}
score = fuzz.token_sort_ratio(device, norm_name)
# add bonus if room name match
if room and dev_room:
score += self._get_bonus_for_room(room, dev_room[0])
# LOG.debug("%s %s" % (norm_name, score))
if score > best_score:
best_score = score
best_device = {
"id": dc['Name'],
"dev_name": alias,
"state": dc['Readings']['state'],
"best_score": best_score}
except KeyError:
pass # print("KeyError")
LOG.debug("best device = %s" % best_device)
return best_device
def _get_bonus_for_room(self, room, dev_room):
if fuzz.ratio(room, dev_room) > REQUIRED_RATIO_FOR_BONUS:
LOG.debug("bonus! {} {}".format(room, dev_room))
return BONUS
else:
return 0
def _get_aliasname(self, device):
if 'alias' in device['Attributes']:
alias = device['Attributes']['alias']
else:
alias = device['Name']
return alias
def _get_normalized_room_list(self, dev):
# add device room to name
dev_room = []
# LOG.debug(self.ignore_rooms)
ignore = [x.lower() for x in self.ignore_rooms.split(",")]
# LOG.debug("ignore = %s" % ignore)
if 'room' in dev['Attributes']:
rooms = [x.lower() for x in dev['Attributes']['room'].split(",")]
rooms.remove(self.allowed_devices_room.lower())
# LOG.debug("rooms = %s" % rooms)
for r in rooms:
# LOG.debug("r = %s" % r)
if (r not in ignore):
# LOG.debug("adding r = %s" % r)
dev_room.append(r)
return dev_room
def _normalize(self, name):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
s2 = re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
return s2.replace("_", " ").replace("-", " ").replace(".", " ")
def _clean_common_words(self, text):
txt = text.split(" ")
common_words = self.translate_list("common.words")
# LOG.debug("common_words {}".format(common_words))
for i in range(0, len(txt)):
if txt[i] in common_words:
txt[i] = ""
res = ""
for t in txt:
res += "{} ".format(t)
prev_len = len(res) + 1
while prev_len > len(res):
res.replace(" ", " ")
prev_len = len(res)
# LOG.debug("out {}".format(res))
return res.strip()
def shutdown(self):
self.remove_fallback(self.handle_fallback)
super(FhemSkill, self).shutdown()
def stop(self):
pass
def __translate(self, term, data=None):
try:
return self.dialog_renderer.render(term, data)
except BaseException:
# no dialog at all (e.g. unsupported language or unknown term
return term
def create_skill():
return FhemSkill()