Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """Support for submitting data to Thingspeak."""
2 
3 import logging
4 
5 from requests.exceptions import RequestException
6 import thingspeak
7 import voluptuous as vol
8 
9 from homeassistant.const import (
10  CONF_API_KEY,
11  CONF_ID,
12  CONF_WHITELIST,
13  STATE_UNAVAILABLE,
14  STATE_UNKNOWN,
15 )
16 from homeassistant.core import HomeAssistant
17 from homeassistant.helpers import event, state as state_helper
19 from homeassistant.helpers.typing import ConfigType
20 
21 _LOGGER = logging.getLogger(__name__)
22 
23 DOMAIN = "thingspeak"
24 
25 TIMEOUT = 5
26 
27 CONFIG_SCHEMA = vol.Schema(
28  {
29  DOMAIN: vol.Schema(
30  {
31  vol.Required(CONF_API_KEY): cv.string,
32  vol.Required(CONF_ID): int,
33  vol.Required(CONF_WHITELIST): cv.string,
34  }
35  )
36  },
37  extra=vol.ALLOW_EXTRA,
38 )
39 
40 
41 def setup(hass: HomeAssistant, config: ConfigType) -> bool:
42  """Set up the Thingspeak environment."""
43  conf = config[DOMAIN]
44  api_key = conf.get(CONF_API_KEY)
45  channel_id = conf.get(CONF_ID)
46  entity = conf.get(CONF_WHITELIST)
47 
48  try:
49  channel = thingspeak.Channel(channel_id, api_key=api_key, timeout=TIMEOUT)
50  channel.get()
51  except RequestException:
52  _LOGGER.error(
53  "Error while accessing the ThingSpeak channel. "
54  "Please check that the channel exists and your API key is correct"
55  )
56  return False
57 
58  def thingspeak_listener(entity_id, old_state, new_state):
59  """Listen for new events and send them to Thingspeak."""
60  if new_state is None or new_state.state in (
61  STATE_UNKNOWN,
62  "",
63  STATE_UNAVAILABLE,
64  ):
65  return
66  try:
67  if new_state.entity_id != entity:
68  return
69  _state = state_helper.state_as_number(new_state)
70  except ValueError:
71  return
72  try:
73  channel.update({"field1": _state})
74  except RequestException:
75  _LOGGER.error("Error while sending value '%s' to Thingspeak", _state)
76 
77  event.track_state_change(hass, entity, thingspeak_listener)
78 
79  return True
bool setup(HomeAssistant hass, ConfigType config)
Definition: __init__.py:41