Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """Support for sending data to Dweet.io."""
2 
3 from datetime import timedelta
4 import logging
5 
6 import dweepy
7 import voluptuous as vol
8 
9 from homeassistant.const import (
10  ATTR_FRIENDLY_NAME,
11  CONF_NAME,
12  CONF_WHITELIST,
13  EVENT_STATE_CHANGED,
14  STATE_UNKNOWN,
15 )
16 from homeassistant.core import HomeAssistant
17 from homeassistant.helpers import state as state_helper
19 from homeassistant.helpers.typing import ConfigType
20 from homeassistant.util import Throttle
21 
22 _LOGGER = logging.getLogger(__name__)
23 
24 DOMAIN = "dweet"
25 
26 MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=1)
27 
28 CONFIG_SCHEMA = vol.Schema(
29  {
30  DOMAIN: vol.Schema(
31  {
32  vol.Required(CONF_NAME): cv.string,
33  vol.Required(CONF_WHITELIST, default=[]): vol.All(
34  cv.ensure_list, [cv.entity_id]
35  ),
36  }
37  )
38  },
39  extra=vol.ALLOW_EXTRA,
40 )
41 
42 
43 def setup(hass: HomeAssistant, config: ConfigType) -> bool:
44  """Set up the Dweet.io component."""
45  conf = config[DOMAIN]
46  name = conf.get(CONF_NAME)
47  whitelist = conf.get(CONF_WHITELIST)
48  json_body = {}
49 
50  def dweet_event_listener(event):
51  """Listen for new messages on the bus and sends them to Dweet.io."""
52  state = event.data.get("new_state")
53  if (
54  state is None
55  or state.state in (STATE_UNKNOWN, "")
56  or state.entity_id not in whitelist
57  ):
58  return
59 
60  try:
61  _state = state_helper.state_as_number(state)
62  except ValueError:
63  _state = state.state
64 
65  json_body[state.attributes.get(ATTR_FRIENDLY_NAME)] = _state
66 
67  send_data(name, json_body)
68 
69  hass.bus.listen(EVENT_STATE_CHANGED, dweet_event_listener)
70 
71  return True
72 
73 
74 @Throttle(MIN_TIME_BETWEEN_UPDATES)
75 def send_data(name, msg):
76  """Send the collected data to Dweet.io."""
77  try:
78  dweepy.dweet_for(name, msg)
79  except dweepy.DweepyError:
80  _LOGGER.error("Error saving data to Dweet.io: %s", msg)
def send_data(name, msg)
Definition: __init__.py:75
bool setup(HomeAssistant hass, ConfigType config)
Definition: __init__.py:43