diff --git a/homeassistant/components/motor/__init__.py b/homeassistant/components/motor/__init__.py new file mode 100644 index 00000000000..feea836a0dd --- /dev/null +++ b/homeassistant/components/motor/__init__.py @@ -0,0 +1,130 @@ +""" +homeassistant.components.motor +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Motor component. + +""" +import os +import logging + +from homeassistant.config import load_yaml_config_file +from homeassistant.helpers.entity_component import EntityComponent +from homeassistant.helpers.entity import Entity +from homeassistant.components import group +from homeassistant.const import ( + SERVICE_OPEN, SERVICE_CLOSE, SERVICE_STOP, + STATE_OPEN, STATE_CLOSED, STATE_UNKNOWN, ATTR_ENTITY_ID) + + +DOMAIN = 'motor' +DEPENDENCIES = [] +SCAN_INTERVAL = 15 + +GROUP_NAME_ALL_MOTORS = 'all motors' +ENTITY_ID_ALL_MOTORS = group.ENTITY_ID_FORMAT.format('all_motors') + +ENTITY_ID_FORMAT = DOMAIN + '.{}' + +# Maps discovered services to their platforms +DISCOVERY_PLATFORMS = {} + +_LOGGER = logging.getLogger(__name__) + + +def is_open(hass, entity_id=None): + """ Returns if the motor is open based on the statemachine. """ + entity_id = entity_id or ENTITY_ID_ALL_MOTORS + return hass.states.is_state(entity_id, STATE_OPEN) + + +def call_open(hass, entity_id=None): + """ Open all or specified motor. """ + data = {ATTR_ENTITY_ID: entity_id} if entity_id else None + hass.services.call(DOMAIN, SERVICE_OPEN, data) + + +def call_close(hass, entity_id=None): + """ Close all or specified motor. """ + data = {ATTR_ENTITY_ID: entity_id} if entity_id else None + hass.services.call(DOMAIN, SERVICE_CLOSE, data) + + +def call_stop(hass, entity_id=None): + """ Stops all or specified motor. """ + data = {ATTR_ENTITY_ID: entity_id} if entity_id else None + hass.services.call(DOMAIN, SERVICE_STOP, data) + + +def setup(hass, config): + """ Track states and offer events for motors. """ + component = EntityComponent( + _LOGGER, DOMAIN, hass, SCAN_INTERVAL, DISCOVERY_PLATFORMS, + GROUP_NAME_ALL_MOTORS) + component.setup(config) + + def handle_motor_service(service): + """ Handles calls to the motor services. """ + target_motors = component.extract_from_service(service) + + for motor in target_motors: + if service.service == SERVICE_OPEN: + motor.open() + elif service.service == SERVICE_CLOSE: + motor.close() + elif service.service == SERVICE_STOP: + motor.stop() + + if motor.should_poll: + motor.update_ha_state(True) + + descriptions = load_yaml_config_file( + os.path.join(os.path.dirname(__file__), 'services.yaml')) + + hass.services.register(DOMAIN, SERVICE_OPEN, + handle_motor_service, + descriptions.get(SERVICE_OPEN)) + hass.services.register(DOMAIN, SERVICE_CLOSE, + handle_motor_service, + descriptions.get(SERVICE_CLOSE)) + hass.services.register(DOMAIN, SERVICE_STOP, + handle_motor_service, + descriptions.get(SERVICE_STOP)) + + return True + + +class MotorDevice(Entity): + """ Represents a motor within Home Assistant. """ + # pylint: disable=no-self-use + + @property + def current_position(self): + """ Return current position of motor. + None is unknown, 0 is closed, 100 is fully open. """ + raise NotImplementedError() + + @property + def state(self): + current = self.current_position + + if current is None: + return STATE_UNKNOWN + + return STATE_CLOSED if current == 0 else STATE_OPEN + + @property + def state_attributes(self): + """ Returns optional state attributes. """ + return None + + def open(self, **kwargs): + """ Open the device. """ + raise NotImplementedError() + + def close(self, **kwargs): + """ Close the device. """ + raise NotImplementedError() + + def stop(self, **kwargs): + """ Stop the device. """ + raise NotImplementedError() diff --git a/homeassistant/components/motor/mqtt.py b/homeassistant/components/motor/mqtt.py new file mode 100644 index 00000000000..2aac5e37c16 --- /dev/null +++ b/homeassistant/components/motor/mqtt.py @@ -0,0 +1,117 @@ +""" +homeassistant.components.motor.mqtt +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Allows to configure a MQTT motor. +For more details about this platform, please refer to the documentation at +https://home-assistant.io/components/motor.mqtt/ +""" +import logging +import homeassistant.components.mqtt as mqtt +from homeassistant.components.motor import MotorDevice +_LOGGER = logging.getLogger(__name__) + +DEPENDENCIES = ['mqtt'] + +DEFAULT_NAME = "MQTT Motor" +DEFAULT_QOS = 0 +DEFAULT_PAYLOAD_OPEN = "OPEN" +DEFAULT_PAYLOAD_CLOSE = "CLOSE" +DEFAULT_PAYLOAD_STOP = "STOP" + +ATTR_CURRENT_POSITION = 'current_position' + + +# pylint: disable=unused-argument +def setup_platform(hass, config, add_devices_callback, discovery_info=None): + """ Add MQTT Motor """ + + if config.get('command_topic') is None: + _LOGGER.error("Missing required variable: command_topic") + return False + + add_devices_callback([MqttMotor( + hass, + config.get('name', DEFAULT_NAME), + config.get('state_topic'), + config.get('command_topic'), + config.get('qos', DEFAULT_QOS), + config.get('payload_open', DEFAULT_PAYLOAD_OPEN), + config.get('payload_close', DEFAULT_PAYLOAD_CLOSE), + config.get('payload_stop', DEFAULT_PAYLOAD_STOP), + config.get('state_format'))]) + + +# pylint: disable=too-many-arguments, too-many-instance-attributes +class MqttMotor(MotorDevice): + """ Represents a motor that can be controlled using MQTT """ + def __init__(self, hass, name, state_topic, command_topic, qos, + payload_open, payload_close, payload_stop, state_format): + self._state = None + self._hass = hass + self._name = name + self._state_topic = state_topic + self._command_topic = command_topic + self._qos = qos + self._payload_open = payload_open + self._payload_close = payload_close + self._payload_stop = payload_stop + self._parse = mqtt.FmtParser(state_format) + + if self._state_topic is None: + return + + def message_received(topic, payload, qos): + """ A new MQTT message has been received. """ + value = self._parse(payload) + if value.isnumeric() and 0 <= int(value) <= 100: + self._state = int(value) + self.update_ha_state() + else: + _LOGGER.warning( + "Payload is expected to be an integer between 0 and 100") + + mqtt.subscribe(hass, self._state_topic, message_received, self._qos) + + @property + def should_poll(self): + """ No polling needed """ + return False + + @property + def name(self): + """ The name of the motor """ + return self._name + + @property + def current_position(self): + """ Return current position of motor. + None is unknown, 0 is closed, 100 is fully open. """ + return self._state + + @property + def is_open(self): + """ True if device is current position is not zero. """ + return self._state > 0 + + def open(self, **kwargs): + """ Open the device. """ + mqtt.publish(self.hass, self._command_topic, self._payload_open, + self._qos) + + def close(self, **kwargs): + """ Close the device. """ + mqtt.publish(self.hass, self._command_topic, self._payload_close, + self._qos) + + def stop(self, **kwargs): + """ Stop the device. """ + mqtt.publish(self.hass, self._command_topic, self._payload_stop, + self._qos) + + @property + def state_attributes(self): + """ Return the state attributes. """ + state_attr = {} + if self._state is not None: + state_attr[ATTR_CURRENT_POSITION] = self._state + return state_attr diff --git a/homeassistant/components/motor/services.yaml b/homeassistant/components/motor/services.yaml new file mode 100644 index 00000000000..e69de29bb2d diff --git a/homeassistant/const.py b/homeassistant/const.py index 5b0b5a5e214..1513c188cc2 100644 --- a/homeassistant/const.py +++ b/homeassistant/const.py @@ -143,6 +143,10 @@ SERVICE_ALARM_TRIGGER = "alarm_trigger" SERVICE_LOCK = "lock" SERVICE_UNLOCK = "unlock" +SERVICE_OPEN = 'open' +SERVICE_CLOSE = 'close' +SERVICE_STOP = 'stop' + # #### API / REMOTE #### SERVER_PORT = 8123 diff --git a/tests/components/alarm_control_panel/__init__.py b/tests/components/alarm_control_panel/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/tests/components/motor/__init__.py b/tests/components/motor/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/tests/components/motor/test_mqtt.py b/tests/components/motor/test_mqtt.py new file mode 100644 index 00000000000..4d7af04ae6c --- /dev/null +++ b/tests/components/motor/test_mqtt.py @@ -0,0 +1,122 @@ +""" +tests.components.motor.test_mqtt +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Tests mqtt motor. +""" +import unittest + +from homeassistant.const import STATE_OPEN, STATE_CLOSED, STATE_UNKNOWN +import homeassistant.core as ha +import homeassistant.components.motor as motor +from tests.common import mock_mqtt_component, fire_mqtt_message + + +class TestMotorMQTT(unittest.TestCase): + """ Test the MQTT motor. """ + + def setUp(self): # pylint: disable=invalid-name + self.hass = ha.HomeAssistant() + self.mock_publish = mock_mqtt_component(self.hass) + + def tearDown(self): # pylint: disable=invalid-name + """ Stop down stuff we started. """ + self.hass.stop() + + def test_controlling_state_via_topic(self): + self.assertTrue(motor.setup(self.hass, { + 'motor': { + 'platform': 'mqtt', + 'name': 'test', + 'state_topic': 'state-topic', + 'command_topic': 'command-topic', + 'qos': 0, + 'payload_open': 'OPEN', + 'payload_close': 'CLOSE', + 'payload_stop': 'STOP' + } + })) + + state = self.hass.states.get('motor.test') + self.assertEqual(STATE_UNKNOWN, state.state) + + fire_mqtt_message(self.hass, 'state-topic', '0') + self.hass.pool.block_till_done() + + state = self.hass.states.get('motor.test') + self.assertEqual(STATE_CLOSED, state.state) + + fire_mqtt_message(self.hass, 'state-topic', '50') + self.hass.pool.block_till_done() + + state = self.hass.states.get('motor.test') + self.assertEqual(STATE_OPEN, state.state) + + fire_mqtt_message(self.hass, 'state-topic', '100') + self.hass.pool.block_till_done() + + state = self.hass.states.get('motor.test') + self.assertEqual(STATE_OPEN, state.state) + + def test_sending_mqtt_commands(self): + self.assertTrue(motor.setup(self.hass, { + 'motor': { + 'platform': 'mqtt', + 'name': 'test', + 'state_topic': 'state-topic', + 'command_topic': 'command-topic', + 'qos': 2 + } + })) + + state = self.hass.states.get('motor.test') + self.assertEqual(STATE_UNKNOWN, state.state) + + motor.call_open(self.hass, 'motor.test') + self.hass.pool.block_till_done() + + self.assertEqual(('command-topic', 'OPEN', 2), + self.mock_publish.mock_calls[-1][1]) + state = self.hass.states.get('motor.test') + self.assertEqual(STATE_UNKNOWN, state.state) + + def test_state_attributes_current_position(self): + self.assertTrue(motor.setup(self.hass, { + 'motor': { + 'platform': 'mqtt', + 'name': 'test', + 'state_topic': 'state-topic', + 'command_topic': 'command-topic', + 'payload_open': 'OPEN', + 'payload_close': 'CLOSE', + 'payload_stop': 'STOP' + } + })) + + state_attributes_dict = self.hass.states.get( + 'motor.test').attributes + self.assertFalse('current_position' in state_attributes_dict) + + fire_mqtt_message(self.hass, 'state-topic', '0') + self.hass.pool.block_till_done() + current_position = self.hass.states.get( + 'motor.test').attributes['current_position'] + self.assertEqual(0, current_position) + + fire_mqtt_message(self.hass, 'state-topic', '50') + self.hass.pool.block_till_done() + current_position = self.hass.states.get( + 'motor.test').attributes['current_position'] + self.assertEqual(50, current_position) + + fire_mqtt_message(self.hass, 'state-topic', '101') + self.hass.pool.block_till_done() + current_position = self.hass.states.get( + 'motor.test').attributes['current_position'] + self.assertEqual(50, current_position) + + fire_mqtt_message(self.hass, 'state-topic', 'non-numeric') + self.hass.pool.block_till_done() + current_position = self.hass.states.get( + 'motor.test').attributes['current_position'] + self.assertEqual(50, current_position)