core/homeassistant/components/conversation.py

78 lines
2.1 KiB
Python
Raw Normal View History

2015-03-10 07:08:50 +00:00
"""
homeassistant.components.conversation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides functionality to have conversations with Home Assistant.
2015-10-25 14:40:21 +00:00
For more details about this component, please refer to the documentation at
2015-11-09 12:12:18 +00:00
https://home-assistant.io/components/conversation/
2015-03-10 07:08:50 +00:00
"""
import logging
import re
2015-08-17 03:44:46 +00:00
from homeassistant import core
2015-03-10 07:08:50 +00:00
from homeassistant.const import (
2015-09-01 07:18:26 +00:00
ATTR_ENTITY_ID, SERVICE_TURN_ON, SERVICE_TURN_OFF)
2015-03-10 07:08:50 +00:00
DOMAIN = "conversation"
SERVICE_PROCESS = "process"
ATTR_TEXT = "text"
REGEX_TURN_COMMAND = re.compile(r'turn (?P<name>(?: |\w)+) (?P<command>\w+)')
REQUIREMENTS = ['fuzzywuzzy==0.8.0']
2015-03-10 07:08:50 +00:00
def setup(hass, config):
""" Registers the process service. """
from fuzzywuzzy import process as fuzzyExtract
2015-03-10 07:08:50 +00:00
logger = logging.getLogger(__name__)
def process(service):
2015-03-10 07:09:27 +00:00
""" Parses text into commands for Home Assistant. """
2015-03-10 07:08:50 +00:00
if ATTR_TEXT not in service.data:
logger.error("Received process service call without a text")
return
text = service.data[ATTR_TEXT].lower()
match = REGEX_TURN_COMMAND.match(text)
if not match:
logger.error("Unable to process: %s", text)
return
name, command = match.groups()
entities = {state.entity_id: state.name for state in hass.states.all()}
entity_ids = fuzzyExtract.extractOne(name,
entities,
score_cutoff=65)[2]
2015-03-10 07:08:50 +00:00
if not entity_ids:
logger.error(
"Could not find entity id %s from text %s", name, text)
return
if command == 'on':
2015-08-17 03:44:46 +00:00
hass.services.call(core.DOMAIN, SERVICE_TURN_ON, {
ATTR_ENTITY_ID: entity_ids,
}, blocking=True)
2015-03-10 07:08:50 +00:00
elif command == 'off':
2015-08-17 03:44:46 +00:00
hass.services.call(core.DOMAIN, SERVICE_TURN_OFF, {
ATTR_ENTITY_ID: entity_ids,
}, blocking=True)
2015-03-10 07:08:50 +00:00
else:
logger.error(
'Got unsupported command %s from text %s', command, text)
hass.services.register(DOMAIN, SERVICE_PROCESS, process)
return True