Home Assistant Unofficial Reference 2024.12.1
camera.py
Go to the documentation of this file.
1 """Camera that loads a picture from an MQTT topic."""
2 
3 from __future__ import annotations
4 
5 from base64 import b64decode
6 import logging
7 from typing import TYPE_CHECKING
8 
9 import voluptuous as vol
10 
11 from homeassistant.components import camera
12 from homeassistant.components.camera import Camera
13 from homeassistant.config_entries import ConfigEntry
14 from homeassistant.const import CONF_NAME
15 from homeassistant.core import HomeAssistant, callback
16 from homeassistant.helpers import config_validation as cv
17 from homeassistant.helpers.entity_platform import AddEntitiesCallback
18 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
19 
20 from . import subscription
21 from .config import MQTT_BASE_SCHEMA
22 from .const import CONF_TOPIC
23 from .entity import MqttEntity, async_setup_entity_entry_helper
24 from .models import ReceiveMessage
25 from .schemas import MQTT_ENTITY_COMMON_SCHEMA
26 from .util import valid_subscribe_topic
27 
28 _LOGGER = logging.getLogger(__name__)
29 
30 PARALLEL_UPDATES = 0
31 
32 CONF_IMAGE_ENCODING = "image_encoding"
33 
34 DEFAULT_NAME = "MQTT Camera"
35 
36 MQTT_CAMERA_ATTRIBUTES_BLOCKED = frozenset(
37  {
38  "access_token",
39  "brand",
40  "model_name",
41  "motion_detection",
42  }
43 )
44 
45 PLATFORM_SCHEMA_BASE = MQTT_BASE_SCHEMA.extend(
46  {
47  vol.Optional(CONF_NAME): vol.Any(cv.string, None),
48  vol.Required(CONF_TOPIC): valid_subscribe_topic,
49  vol.Optional(CONF_IMAGE_ENCODING): "b64",
50  }
51 ).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
52 
53 PLATFORM_SCHEMA_MODERN = vol.All(
54  PLATFORM_SCHEMA_BASE.schema,
55 )
56 
57 DISCOVERY_SCHEMA = PLATFORM_SCHEMA_BASE.extend({}, extra=vol.REMOVE_EXTRA)
58 
59 
61  hass: HomeAssistant,
62  config_entry: ConfigEntry,
63  async_add_entities: AddEntitiesCallback,
64 ) -> None:
65  """Set up MQTT camera through YAML and through MQTT discovery."""
67  hass,
68  config_entry,
69  MqttCamera,
70  camera.DOMAIN,
71  async_add_entities,
72  DISCOVERY_SCHEMA,
73  PLATFORM_SCHEMA_MODERN,
74  )
75 
76 
78  """representation of a MQTT camera."""
79 
80  _default_name = DEFAULT_NAME
81  _entity_id_format: str = camera.ENTITY_ID_FORMAT
82  _attributes_extra_blocked: frozenset[str] = MQTT_CAMERA_ATTRIBUTES_BLOCKED
83  _last_image: bytes | None = None
84 
85  def __init__(
86  self,
87  hass: HomeAssistant,
88  config: ConfigType,
89  config_entry: ConfigEntry,
90  discovery_data: DiscoveryInfoType | None,
91  ) -> None:
92  """Initialize the MQTT Camera."""
93  Camera.__init__(self)
94  MqttEntity.__init__(self, hass, config, config_entry, discovery_data)
95 
96  @staticmethod
97  def config_schema() -> vol.Schema:
98  """Return the config schema."""
99  return DISCOVERY_SCHEMA
100 
101  @callback
102  def _image_received(self, msg: ReceiveMessage) -> None:
103  """Handle new MQTT messages."""
104  if CONF_IMAGE_ENCODING in self._config_config:
105  self._last_image_last_image = b64decode(msg.payload)
106  else:
107  if TYPE_CHECKING:
108  assert isinstance(msg.payload, bytes)
109  self._last_image_last_image = msg.payload
110 
111  @callback
112  def _prepare_subscribe_topics(self) -> None:
113  """(Re)Subscribe to topics."""
114 
115  self.add_subscriptionadd_subscription(
116  CONF_TOPIC, self._image_received_image_received, None, disable_encoding=True
117  )
118 
119  async def _subscribe_topics(self) -> None:
120  """(Re)Subscribe to topics."""
121  subscription.async_subscribe_topics_internal(self.hasshasshass, self._sub_state_sub_state)
122 
124  self, width: int | None = None, height: int | None = None
125  ) -> bytes | None:
126  """Return image response."""
127  return self._last_image_last_image
bytes|None async_camera_image(self, int|None width=None, int|None height=None)
Definition: camera.py:125
None _image_received(self, ReceiveMessage msg)
Definition: camera.py:102
None __init__(self, HomeAssistant hass, ConfigType config, ConfigEntry config_entry, DiscoveryInfoType|None discovery_data)
Definition: camera.py:91
bool add_subscription(self, str state_topic_config_key, Callable[[ReceiveMessage], None] msg_callback, set[str]|None tracked_attributes, bool disable_encoding=False)
Definition: entity.py:1484
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: camera.py:64
None async_setup_entity_entry_helper(HomeAssistant hass, ConfigEntry entry, type[MqttEntity]|None entity_class, str domain, AddEntitiesCallback async_add_entities, VolSchemaType discovery_schema, VolSchemaType platform_schema_modern, dict[str, type[MqttEntity]]|None schema_class_mapping=None)
Definition: entity.py:245