Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """Support for Wireless Sensor Tags."""
2 
3 import logging
4 
5 from requests.exceptions import ConnectTimeout, HTTPError
6 import voluptuous as vol
7 from wirelesstagpy import WirelessTags
8 from wirelesstagpy.exceptions import WirelessTagsException
9 
10 from homeassistant.components import persistent_notification
11 from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
12 from homeassistant.core import HomeAssistant
14 from homeassistant.helpers.dispatcher import dispatcher_send
15 from homeassistant.helpers.typing import ConfigType
16 
17 from .const import DOMAIN, SIGNAL_BINARY_EVENT_UPDATE, SIGNAL_TAG_UPDATE
18 
19 _LOGGER = logging.getLogger(__name__)
20 
21 NOTIFICATION_ID = "wirelesstag_notification"
22 NOTIFICATION_TITLE = "Wireless Sensor Tag Setup"
23 
24 DEFAULT_ENTITY_NAMESPACE = "wirelesstag"
25 
26 CONFIG_SCHEMA = vol.Schema(
27  {
28  DOMAIN: vol.Schema(
29  {
30  vol.Required(CONF_USERNAME): cv.string,
31  vol.Required(CONF_PASSWORD): cv.string,
32  }
33  )
34  },
35  extra=vol.ALLOW_EXTRA,
36 )
37 
38 
40  """Principal object to manage all registered in HA tags."""
41 
42  def __init__(self, hass, api):
43  """Designated initializer for wirelesstags platform."""
44  self.hasshass = hass
45  self.apiapi = api
46  self.tagstags = {}
47  self._local_base_url_local_base_url = None
48 
49  def load_tags(self):
50  """Load tags from remote server."""
51  self.tagstags = self.apiapi.load_tags()
52  return self.tagstags
53 
54  def arm(self, switch):
55  """Arm entity sensor monitoring."""
56  func_name = f"arm_{switch.entity_description.key}"
57  if (arm_func := getattr(self.apiapi, func_name)) is not None:
58  arm_func(switch.tag_id, switch.tag_manager_mac)
59 
60  def disarm(self, switch):
61  """Disarm entity sensor monitoring."""
62  func_name = f"disarm_{switch.entity_description.key}"
63  if (disarm_func := getattr(self.apiapi, func_name)) is not None:
64  disarm_func(switch.tag_id, switch.tag_manager_mac)
65 
66  def start_monitoring(self):
67  """Start monitoring push events."""
68 
69  def push_callback(tags_spec, event_spec):
70  """Handle push update."""
71  _LOGGER.debug(
72  "Push notification arrived: %s, events: %s", tags_spec, event_spec
73  )
74  for uuid, tag in tags_spec.items():
75  try:
76  tag_id = tag.tag_id
77  mac = tag.tag_manager_mac
78  _LOGGER.debug("Push notification for tag update arrived: %s", tag)
80  self.hasshass, SIGNAL_TAG_UPDATE.format(tag_id, mac), tag
81  )
82  if uuid in event_spec:
83  events = event_spec[uuid]
84  for event in events:
85  _LOGGER.debug(
86  "Push notification for binary event arrived: %s", event
87  )
89  self.hasshass,
90  SIGNAL_BINARY_EVENT_UPDATE.format(
91  tag_id, event.type, mac
92  ),
93  tag,
94  )
95  except Exception as ex: # noqa: BLE001
96  _LOGGER.error(
97  "Unable to handle tag update: %s error: %s",
98  str(tag),
99  str(ex),
100  )
101 
102  self.apiapi.start_monitoring(push_callback)
103 
104 
105 def setup(hass: HomeAssistant, config: ConfigType) -> bool:
106  """Set up the Wireless Sensor Tag component."""
107  conf = config[DOMAIN]
108  username = conf.get(CONF_USERNAME)
109  password = conf.get(CONF_PASSWORD)
110 
111  try:
112  wirelesstags = WirelessTags(username=username, password=password)
113 
114  platform = WirelessTagPlatform(hass, wirelesstags)
115  platform.load_tags()
116  platform.start_monitoring()
117  hass.data[DOMAIN] = platform
118  except (ConnectTimeout, HTTPError, WirelessTagsException) as ex:
119  _LOGGER.error("Unable to connect to wirelesstag.net service: %s", str(ex))
120  persistent_notification.create(
121  hass,
122  f"Error: {ex}<br />Please restart hass after fixing this.",
123  title=NOTIFICATION_TITLE,
124  notification_id=NOTIFICATION_ID,
125  )
126  return False
127 
128  return True
bool setup(HomeAssistant hass, ConfigType config)
Definition: __init__.py:105
None dispatcher_send(HomeAssistant hass, str signal, *Any args)
Definition: dispatcher.py:137