Add unique_id to mqtt camera (#16569)

* Add unique_id to mqtt camera

* Remove whitespaces

* Add test for unique_id

* Add blank line
pull/10917/merge
Maciej Bieniek 2018-09-21 13:09:54 +02:00 committed by Paulus Schoutsen
parent 3bfe9e757e
commit a0a54dfd5b
2 changed files with 33 additions and 1 deletions

View File

@ -19,12 +19,14 @@ from homeassistant.helpers import config_validation as cv
_LOGGER = logging.getLogger(__name__)
CONF_TOPIC = 'topic'
CONF_UNIQUE_ID = 'unique_id'
DEFAULT_NAME = 'MQTT Camera'
DEPENDENCIES = ['mqtt']
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_TOPIC): mqtt.valid_subscribe_topic,
vol.Optional(CONF_UNIQUE_ID): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string
})
@ -38,6 +40,7 @@ def async_setup_platform(hass, config, async_add_entities,
async_add_entities([MqttCamera(
config.get(CONF_NAME),
config.get(CONF_UNIQUE_ID),
config.get(CONF_TOPIC)
)])
@ -45,11 +48,12 @@ def async_setup_platform(hass, config, async_add_entities,
class MqttCamera(Camera):
"""representation of a MQTT camera."""
def __init__(self, name, topic):
def __init__(self, name, unique_id, topic):
"""Initialize the MQTT Camera."""
super().__init__()
self._name = name
self._unique_id = unique_id
self._topic = topic
self._qos = 0
self._last_image = None
@ -64,6 +68,11 @@ class MqttCamera(Camera):
"""Return the name of this camera."""
return self._name
@property
def unique_id(self):
"""Return a unique ID."""
return self._unique_id
@asyncio.coroutine
def async_added_to_hass(self):
"""Subscribe MQTT events."""

View File

@ -29,3 +29,26 @@ def test_run_camera_setup(hass, aiohttp_client):
assert resp.status == 200
body = yield from resp.text()
assert body == 'beer'
@asyncio.coroutine
def test_unique_id(hass):
"""Test unique id option only creates one camera per unique_id."""
yield from async_mock_mqtt_component(hass)
yield from async_setup_component(hass, 'camera', {
'camera': [{
'platform': 'mqtt',
'name': 'Test Camera 1',
'topic': 'test-topic',
'unique_id': 'TOTALLY_UNIQUE'
}, {
'platform': 'mqtt',
'name': 'Test Camera 2',
'topic': 'test-topic',
'unique_id': 'TOTALLY_UNIQUE'
}]
})
async_fire_mqtt_message(hass, 'test-topic', 'payload')
yield from hass.async_block_till_done()
assert len(hass.states.async_all()) == 1