Home Assistant Unofficial Reference 2024.12.1
notify.py
Go to the documentation of this file.
1 """Support for SMS notification services."""
2 
3 from __future__ import annotations
4 
5 import logging
6 
7 import gammu
8 
9 from homeassistant.components.notify import ATTR_DATA, BaseNotificationService
10 from homeassistant.const import CONF_TARGET
11 from homeassistant.core import HomeAssistant
12 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
13 
14 from .const import CONF_UNICODE, DOMAIN, GATEWAY, SMS_GATEWAY
15 
16 _LOGGER = logging.getLogger(__name__)
17 
18 
20  hass: HomeAssistant,
21  config: ConfigType,
22  discovery_info: DiscoveryInfoType | None = None,
23 ) -> SMSNotificationService | None:
24  """Get the SMS notification service."""
25 
26  if discovery_info is None:
27  return None
28 
29  return SMSNotificationService(hass)
30 
31 
32 class SMSNotificationService(BaseNotificationService):
33  """Implement the notification service for SMS."""
34 
35  def __init__(self, hass):
36  """Initialize the service."""
37 
38  self.hasshass = hass
39 
40  async def async_send_message(self, message="", **kwargs):
41  """Send SMS message."""
42 
43  if SMS_GATEWAY not in self.hasshass.data[DOMAIN]:
44  _LOGGER.error("SMS gateway not found, cannot send message")
45  return
46 
47  gateway = self.hasshass.data[DOMAIN][SMS_GATEWAY][GATEWAY]
48 
49  targets = kwargs.get(CONF_TARGET)
50  if targets is None:
51  _LOGGER.error("No target number specified, cannot send message")
52  return
53 
54  extended_data = kwargs.get(ATTR_DATA)
55  _LOGGER.debug("Extended data:%s", extended_data)
56 
57  if extended_data is None:
58  is_unicode = True
59  else:
60  is_unicode = extended_data.get(CONF_UNICODE, True)
61 
62  smsinfo = {
63  "Class": -1,
64  "Unicode": is_unicode,
65  "Entries": [{"ID": "ConcatenatedTextLong", "Buffer": message}],
66  }
67  try:
68  # Encode messages
69  encoded = gammu.EncodeSMS(smsinfo)
70  except gammu.GSMError as exc:
71  _LOGGER.error("Encoding message %s failed: %s", message, exc)
72  return
73 
74  # Send messages
75  for encoded_message in encoded:
76  # Fill in numbers
77  encoded_message["SMSC"] = {"Location": 1}
78 
79  for target in targets:
80  encoded_message["Number"] = target
81  try:
82  # Actually send the message
83  await gateway.send_sms_async(encoded_message)
84  except gammu.GSMError as exc:
85  _LOGGER.error("Sending to %s failed: %s", target, exc)
def async_send_message(self, message="", **kwargs)
Definition: notify.py:40
SMSNotificationService|None async_get_service(HomeAssistant hass, ConfigType config, DiscoveryInfoType|None discovery_info=None)
Definition: notify.py:23