forked from eClarity/mycroft-homeassistant
-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
496 lines (438 loc) · 19.4 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
from adapt.intent import IntentBuilder
from mycroft.skills.core import FallbackSkill, intent_handler
from mycroft.util.log import getLogger
from mycroft.util.format import nice_number
from mycroft import MycroftSkill, intent_file_handler
from os.path import dirname, join
from requests.exceptions import (
RequestException,
Timeout,
InvalidURL,
URLRequired,
SSLError,
HTTPError)
from requests.packages.urllib3.exceptions import MaxRetryError
from .ha_client import HomeAssistantClient
__author__ = 'robconnolly, btotharye, nielstron'
LOGGER = getLogger(__name__)
# Timeout time for HA requests
TIMEOUT = 10
class HomeAssistantSkill(FallbackSkill):
def __init__(self):
MycroftSkill.__init__(self)
super().__init__(name="HomeAssistantSkill")
self.ha = None
self.enable_fallback = False
def _setup(self, force=False):
if self.settings is not None and (force or self.ha is None):
portnumber = self.settings.get('portnum')
try:
portnumber = int(portnumber)
except TypeError:
portnumber = 8123
except ValueError:
# String might be some rubbish (like '')
portnumber = 0
self.ha = HomeAssistantClient(
self.settings.get('host'),
self.settings.get('token'),
portnumber,
self.settings.get('ssl'),
self.settings.get('verify')
)
if self.ha.connected():
# Check if conversation component is loaded at HA-server
# and activate fallback accordingly (ha-server/api/components)
# TODO: enable other tools like dialogflow
conversation_activated = self.ha.find_component(
'conversation'
)
if conversation_activated:
self.enable_fallback = \
self.settings.get('enable_fallback') == 'true'
def _force_setup(self):
LOGGER.debug('Creating a new HomeAssistant-Client')
self._setup(True)
def initialize(self):
self.language = self.config_core.get('lang')
self.load_vocab_files(join(dirname(__file__), 'vocab', self.lang))
self.load_regex_files(join(dirname(__file__), 'regex', self.lang))
self.__build_switch_intent()
self.__build_light_adjust_intent()
self.__build_automation_intent()
self.__build_sensor_intent()
self.__build_tracker_intent()
self.register_intent_file(
'set.climate.intent',
self.handle_set_thermostat_intent
)
self.register_intent_file(
'set.light.brightness.intent',
self.handle_light_set_intent
)
# Needs higher priority than general fallback skills
self.register_fallback(self.handle_fallback, 2)
# Check and then monitor for credential changes
self.settings.set_changed_callback(self.on_websettings_changed)
self._setup()
def on_websettings_changed(self):
# Force a setting refresh after the websettings changed
# Otherwise new settings will not be regarded
self._force_setup()
def __build_switch_intent(self):
intent = IntentBuilder("switchIntent").require(
"SwitchActionKeyword").require("Action").require("Entity").build()
self.register_intent(intent, self.handle_switch_intent)
def __build_light_adjust_intent(self):
intent = IntentBuilder("LightAdjBrightnessIntent") \
.optionally("LightsKeyword") \
.one_of("IncreaseVerb", "DecreaseVerb", "LightBrightenVerb",
"LightDimVerb") \
.require("Entity").optionally("BrightnessValue").build()
self.register_intent(intent, self.handle_light_adjust_intent)
def __build_automation_intent(self):
intent = IntentBuilder("AutomationIntent").require(
"AutomationActionKeyword").require("Entity").build()
self.register_intent(intent, self.handle_automation_intent)
def __build_sensor_intent(self):
intent = IntentBuilder("SensorIntent").require(
"SensorStatusKeyword").require("Entity").build()
# TODO - Sensors - Locks, Temperature, etc
self.register_intent(intent, self.handle_sensor_intent)
def __build_tracker_intent(self):
intent = IntentBuilder("TrackerIntent").require(
"DeviceTrackerKeyword").require("Entity").build()
# TODO - Identity location, proximity
self.register_intent(intent, self.handle_tracker_intent)
# Try to find an entity on the HAServer
# Creates dialogs for errors and speaks them
# Returns None if nothing was found
# Else returns entity that was found
def _find_entity(self, entity, domains):
self._setup()
if self.ha is None:
self.speak_dialog('homeassistant.error.setup')
return False
# TODO if entity is 'all', 'any' or 'every' turn on
# every single entity not the whole group
ha_entity = self._handle_client_exception(self.ha.find_entity,
entity, domains)
if ha_entity is None:
self.speak_dialog('homeassistant.device.unknown', data={
"dev_name": entity})
return ha_entity
# Calls passed method and catches often occurring exceptions
def _handle_client_exception(self, callback, *args, **kwargs):
try:
return callback(*args, **kwargs)
except Timeout:
self.speak_dialog('homeassistant.error.offline')
except (InvalidURL, URLRequired, MaxRetryError) as e:
self.speak_dialog('homeassistant.error.invalidurl', data={
'url': e.request.url})
except SSLError:
self.speak_dialog('homeassistant.error.ssl')
except HTTPError as e:
# check if due to wrong password
if e.response.status_code == 401:
self.speak_dialog('homeassistant.error.wrong_password')
else:
self.speak_dialog('homeassistant.error.http', data={
'code': e.response.status_code,
'reason': e.response.reason})
except (ConnectionError, RequestException) as exception:
# TODO find a nice member of any exception to output
self.speak_dialog('homeassistant.error', data={
'url': exception.request.url})
return False
def handle_switch_intent(self, message):
LOGGER.debug("Starting Switch Intent")
entity = message.data["Entity"]
action = message.data["Action"]
LOGGER.debug("Entity: %s" % entity)
LOGGER.debug("Action: %s" % action)
ha_entity = self._find_entity(
entity,
[
'group',
'light',
'fan',
'switch',
'scene',
'input_boolean',
'climate'
]
)
if not ha_entity:
return
LOGGER.debug("Entity State: %s" % ha_entity['state'])
ha_data = {'entity_id': ha_entity['id']}
# IDEA: set context for 'turn it off' again or similar
# self.set_context('Entity', ha_entity['dev_name'])
if self.language == 'de':
if action == 'ein':
action = 'on'
elif action == 'aus':
action = 'off'
if ha_entity['state'] == action:
LOGGER.debug("Entity in requested state")
self.speak_dialog('homeassistant.device.already', data={
"dev_name": ha_entity['dev_name'], 'action': action})
elif action == "toggle":
self.ha.execute_service("homeassistant", "toggle",
ha_data)
if(ha_entity['state'] == 'off'):
action = 'on'
else:
action = 'off'
self.speak_dialog('homeassistant.device.%s' % action,
data=ha_entity)
elif action in ["on", "off"]:
self.speak_dialog('homeassistant.device.%s' % action,
data=ha_entity)
self.ha.execute_service("homeassistant", "turn_%s" % action,
ha_data)
else:
self.speak_dialog('homeassistant.error.sorry')
return
@intent_file_handler('set.light.brightness.intent')
def handle_light_set_intent(self, message):
entity = message.data["entity"]
try:
brightness_req = float(message.data["brightnessvalue"])
if brightness_req > 100 or brightness_req < 0:
self.speak_dialog('homeassistant.brightness.badreq')
except KeyError:
brightness_req = 10.0
brightness_value = int(brightness_req / 100 * 255)
brightness_percentage = int(brightness_req)
LOGGER.debug("Entity: %s" % entity)
LOGGER.debug("Brightness Value: %s" % brightness_value)
LOGGER.debug("Brightness Percent: %s" % brightness_percentage)
ha_entity = self._find_entity(entity, ['group', 'light'])
if not ha_entity:
return
ha_data = {'entity_id': ha_entity['id']}
# IDEA: set context for 'turn it off again' or similar
# self.set_context('Entity', ha_entity['dev_name'])
ha_data['brightness'] = brightness_value
ha_data['dev_name'] = ha_entity['dev_name']
self.ha.execute_service("homeassistant", "turn_on", ha_data)
self.speak_dialog('homeassistant.brightness.dimmed',
data=ha_data)
return
def handle_light_adjust_intent(self, message):
entity = message.data["Entity"]
try:
brightness_req = float(message.data["BrightnessValue"])
if brightness_req > 100 or brightness_req < 0:
self.speak_dialog('homeassistant.brightness.badreq')
except KeyError:
brightness_req = 10.0
brightness_value = int(brightness_req / 100 * 255)
# brightness_percentage = int(brightness_req) # debating use
LOGGER.debug("Entity: %s" % entity)
LOGGER.debug("Brightness Value: %s" % brightness_value)
ha_entity = self._find_entity(entity, ['group', 'light'])
if not ha_entity:
return
ha_data = {'entity_id': ha_entity['id']}
# IDEA: set context for 'turn it off again' or similar
# self.set_context('Entity', ha_entity['dev_name'])
# if self.language == '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 ha_entity['state'] == "off":
self.speak_dialog('homeassistant.brightness.cantdim.off',
data=ha_entity)
else:
light_attrs = self.ha.find_entity_attr(ha_entity['id'])
if light_attrs['unit_measure'] is None:
print(ha_entity)
self.speak_dialog(
'homeassistant.brightness.cantdim.dimmable',
data=ha_entity)
else:
ha_data['brightness'] = light_attrs['unit_measure']
if ha_data['brightness'] < brightness_value:
ha_data['brightness'] = 10
else:
ha_data['brightness'] -= brightness_value
self.ha.execute_service("homeassistant",
"turn_on",
ha_data)
ha_data['dev_name'] = ha_entity['dev_name']
self.speak_dialog('homeassistant.brightness.decreased',
data=ha_data)
elif "IncreaseVerb" in message.data or \
"LightBrightenVerb" in message.data:
if ha_entity['state'] == "off":
self.speak_dialog(
'homeassistant.brightness.cantdim.off',
data=ha_entity)
else:
light_attrs = self.ha.find_entity_attr(ha_entity['id'])
if light_attrs['unit_measure'] is None:
self.speak_dialog(
'homeassistant.brightness.cantdim.dimmable',
data=ha_entity)
else:
ha_data['brightness'] = light_attrs['unit_measure']
if ha_data['brightness'] > brightness_value:
ha_data['brightness'] = 255
else:
ha_data['brightness'] += brightness_value
self.ha.execute_service("homeassistant",
"turn_on",
ha_data)
ha_data['dev_name'] = ha_entity['dev_name']
self.speak_dialog('homeassistant.brightness.increased',
data=ha_data)
else:
self.speak_dialog('homeassistant.error.sorry')
return
def handle_automation_intent(self, message):
entity = message.data["Entity"]
LOGGER.debug("Entity: %s" % entity)
ha_entity = self._find_entity(
entity,
['automation', 'scene', 'script']
)
if not ha_entity:
return
ha_data = {'entity_id': ha_entity['id']}
# IDEA: set context for 'turn it off again' or similar
# self.set_context('Entity', ha_entity['dev_name'])
LOGGER.debug("Triggered automation/scene/script: {}".format(ha_data))
if "automation" in ha_entity['id']:
self.ha.execute_service('automation', 'trigger', ha_data)
self.speak_dialog('homeassistant.automation.trigger',
data={"dev_name": ha_entity['dev_name']})
elif "script" in ha_entity['id']:
self.speak_dialog('homeassistant.automation.trigger',
data={"dev_name": ha_entity['dev_name']})
self.ha.execute_service("homeassistant", "turn_on",
data=ha_data)
elif "scene" in ha_entity['id']:
self.speak_dialog('homeassistant.device.on',
data=ha_entity)
self.ha.execute_service("homeassistant", "turn_on",
data=ha_data)
def handle_sensor_intent(self, message):
entity = message.data["Entity"]
LOGGER.debug("Entity: %s" % entity)
ha_entity = self._find_entity(entity, ['sensor', 'switch'])
if not ha_entity:
return
entity = ha_entity['id']
# IDEA: set context for 'read it out again' or similar
# self.set_context('Entity', ha_entity['dev_name'])
unit_measurement = self.ha.find_entity_attr(entity)
sensor_unit = unit_measurement.get('unit_measure') or ''
sensor_name = unit_measurement['name']
sensor_state = unit_measurement['state']
# 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
try:
value = float(sensor_state)
sensor_state = nice_number(value, lang=self.language)
except ValueError:
pass
self.speak_dialog('homeassistant.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)
# In progress, still testing.
# Device location works.
# Proximity might be an issue
# - overlapping command for directions modules
# - (e.g. "How far is x from y?")
def handle_tracker_intent(self, message):
entity = message.data["Entity"]
LOGGER.debug("Entity: %s" % entity)
ha_entity = self._find_entity(entity, ['device_tracker'])
if not ha_entity:
return
# IDEA: set context for 'locate it again' or similar
# self.set_context('Entity', ha_entity['dev_name'])
entity = ha_entity['id']
dev_name = ha_entity['dev_name']
dev_location = ha_entity['state']
self.speak_dialog('homeassistant.tracker.found',
data={'dev_name': dev_name,
'location': dev_location})
@intent_file_handler('set.climate.intent')
def handle_set_thermostat_intent(self, message):
entity = message.data["entity"]
LOGGER.debug("Entity: %s" % entity)
LOGGER.debug("This is the message data: %s" % message.data)
temperature = message.data["temp"]
LOGGER.debug("Temperature: %s" % temperature)
ha_entity = self._find_entity(entity, ['climate'])
if not ha_entity:
return
climate_data = {
'entity_id': ha_entity['id'],
'temperature': temperature
}
climate_attr = self.ha.find_entity_attr(ha_entity['id'])
self.ha.execute_service("climate", "set_temperature",
data=climate_data)
self.speak_dialog('homeassistant.set.thermostat',
data={
"dev_name": climate_attr['name'],
"value": temperature,
"unit": climate_attr['unit_measure']})
def handle_fallback(self, message):
if not self.enable_fallback:
return False
self._setup()
if self.ha is None:
self.speak_dialog('homeassistant.error.setup')
return False
# pass message to HA-server
response = self._handle_client_exception(
self.ha.engage_conversation,
message.data.get('utterance'))
if not response:
return False
# default non-parsing answer: "Sorry, I didn't understand that"
answer = response.get('speech')
if not answer or answer == "Sorry, I didn't understand that":
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("?"):
asked_question = True
self.speak(answer, expect_response=asked_question)
return True
def shutdown(self):
self.remove_fallback(self.handle_fallback)
super(HomeAssistantSkill, self).shutdown()
def stop(self):
pass
def create_skill():
return HomeAssistantSkill()