Home Assistant Unofficial Reference 2024.12.1
camera.py
Go to the documentation of this file.
1 """Camera entity for PrusaLink."""
2 
3 from __future__ import annotations
4 
5 from pyprusalink.types import PrinterState
6 
7 from homeassistant.components.camera import Camera
8 from homeassistant.config_entries import ConfigEntry
9 from homeassistant.core import HomeAssistant
10 from homeassistant.helpers.entity_platform import AddEntitiesCallback
11 
12 from .const import DOMAIN
13 from .coordinator import JobUpdateCoordinator
14 from .entity import PrusaLinkEntity
15 
16 
18  hass: HomeAssistant,
19  entry: ConfigEntry,
20  async_add_entities: AddEntitiesCallback,
21 ) -> None:
22  """Set up PrusaLink camera."""
23  coordinator: JobUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]["job"]
25 
26 
28  """Defines a PrusaLink camera."""
29 
30  last_path = ""
31  last_image: bytes
32  _attr_translation_key = "job_preview"
33 
34  def __init__(self, coordinator: JobUpdateCoordinator) -> None:
35  """Initialize a PrusaLink camera entity."""
36  super().__init__(coordinator)
37  Camera.__init__(self)
38  self._attr_unique_id_attr_unique_id = f"{self.coordinator.config_entry.entry_id}_job_preview"
39 
40  @property
41  def available(self) -> bool:
42  """Get if camera is available."""
43  return (
44  super().available
45  and self.coordinator.data.get("state") != PrinterState.IDLE.value
46  and (file := self.coordinator.data.get("file"))
47  and file.get("refs", {}).get("thumbnail")
48  )
49 
50  async def async_camera_image(
51  self, width: int | None = None, height: int | None = None
52  ) -> bytes | None:
53  """Return a still image from the camera."""
54  if not self.availableavailableavailableavailableavailable:
55  return None
56 
57  path = self.coordinator.data["file"]["refs"]["thumbnail"]
58 
59  if self.last_pathlast_pathlast_path == path:
60  return self.last_imagelast_image
61 
62  self.last_imagelast_image = await self.coordinator.api.get_file(path)
63  self.last_pathlast_pathlast_path = path
64  return self.last_imagelast_image
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88