Home Assistant Unofficial Reference 2024.12.1
notify.py
Go to the documentation of this file.
1 """Support for file notification."""
2 
3 from __future__ import annotations
4 
5 import os
6 from typing import Any, TextIO
7 
9  ATTR_TITLE_DEFAULT,
10  NotifyEntity,
11  NotifyEntityFeature,
12 )
13 from homeassistant.config_entries import ConfigEntry
14 from homeassistant.const import CONF_FILE_PATH, CONF_NAME
15 from homeassistant.core import HomeAssistant
16 from homeassistant.exceptions import ServiceValidationError
17 from homeassistant.helpers.entity_platform import AddEntitiesCallback
18 import homeassistant.util.dt as dt_util
19 
20 from .const import CONF_TIMESTAMP, DEFAULT_NAME, DOMAIN, FILE_ICON
21 
22 
24  hass: HomeAssistant,
25  entry: ConfigEntry,
26  async_add_entities: AddEntitiesCallback,
27 ) -> None:
28  """Set up notify entity."""
29  unique_id = entry.entry_id
30  async_add_entities([FileNotifyEntity(unique_id, {**entry.data, **entry.options})])
31 
32 
34  """Implement the notification entity platform for the File service."""
35 
36  _attr_icon = FILE_ICON
37  _attr_supported_features = NotifyEntityFeature.TITLE
38 
39  def __init__(self, unique_id: str, config: dict[str, Any]) -> None:
40  """Initialize the service."""
41  self._file_path: str = config[CONF_FILE_PATH]
42  self._add_timestamp: bool = config.get(CONF_TIMESTAMP, False)
43  # Only import a name from an imported entity
44  self._attr_name_attr_name = config.get(CONF_NAME, DEFAULT_NAME)
45  self._attr_unique_id_attr_unique_id = unique_id
46 
47  def send_message(self, message: str, title: str | None = None) -> None:
48  """Send a message to a file."""
49  file: TextIO
50  filepath = self._file_path
51  try:
52  with open(filepath, "a", encoding="utf8") as file:
53  if os.stat(filepath).st_size == 0:
54  title = (
55  f"{title or ATTR_TITLE_DEFAULT} notifications (Log"
56  f" started: {dt_util.utcnow().isoformat()})\n{'-' * 80}\n"
57  )
58  file.write(title)
59 
60  if self._add_timestamp:
61  text = f"{dt_util.utcnow().isoformat()} {message}\n"
62  else:
63  text = f"{message}\n"
64  file.write(text)
65  except OSError as exc:
67  translation_domain=DOMAIN,
68  translation_key="write_access_failed",
69  translation_placeholders={"filename": filepath, "exc": f"{exc!r}"},
70  ) from exc
None __init__(self, str unique_id, dict[str, Any] config)
Definition: notify.py:39
None send_message(self, str message, str|None title=None)
Definition: notify.py:47
None async_setup_entry(HomeAssistant hass, ConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: notify.py:27
None open(self, **Any kwargs)
Definition: lock.py:86