Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """Support for sending data to Logentries webhook endpoint."""
2 
3 import json
4 import logging
5 
6 import requests
7 import voluptuous as vol
8 
9 from homeassistant.const import CONF_TOKEN, EVENT_STATE_CHANGED
10 from homeassistant.core import HomeAssistant
11 from homeassistant.helpers import state as state_helper
13 from homeassistant.helpers.typing import ConfigType
14 
15 _LOGGER = logging.getLogger(__name__)
16 
17 DOMAIN = "logentries"
18 
19 DEFAULT_HOST = "https://webhook.logentries.com/noformat/logs/"
20 
21 CONFIG_SCHEMA = vol.Schema(
22  {DOMAIN: vol.Schema({vol.Required(CONF_TOKEN): cv.string})}, extra=vol.ALLOW_EXTRA
23 )
24 
25 
26 def setup(hass: HomeAssistant, config: ConfigType) -> bool:
27  """Set up the Logentries component."""
28  conf = config[DOMAIN]
29  token = conf.get(CONF_TOKEN)
30  le_wh = f"{DEFAULT_HOST}{token}"
31 
32  def logentries_event_listener(event):
33  """Listen for new messages on the bus and sends them to Logentries."""
34  if (state := event.data.get("new_state")) is None:
35  return
36  try:
37  _state = state_helper.state_as_number(state)
38  except ValueError:
39  _state = state.state
40  json_body = [
41  {
42  "domain": state.domain,
43  "entity_id": state.object_id,
44  "attributes": dict(state.attributes),
45  "time": str(event.time_fired),
46  "value": _state,
47  }
48  ]
49  try:
50  payload = {"host": le_wh, "event": json_body}
51  requests.post(le_wh, data=json.dumps(payload), timeout=10)
52  except requests.exceptions.RequestException:
53  _LOGGER.exception("Error sending to Logentries")
54 
55  hass.bus.listen(EVENT_STATE_CHANGED, logentries_event_listener)
56 
57  return True
bool setup(HomeAssistant hass, ConfigType config)
Definition: __init__.py:26