Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support for Zabbix sensors."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 from typing import Any
8 
9 from pyzabbix import ZabbixAPI
10 import voluptuous as vol
11 
13  PLATFORM_SCHEMA as SENSOR_PLATFORM_SCHEMA,
14  SensorEntity,
15 )
16 from homeassistant.const import CONF_NAME
17 from homeassistant.core import HomeAssistant
19 from homeassistant.helpers.entity_platform import AddEntitiesCallback
20 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType, StateType
21 
22 from .const import DOMAIN
23 
24 _LOGGER = logging.getLogger(__name__)
25 
26 _CONF_TRIGGERS = "triggers"
27 _CONF_HOSTIDS = "hostids"
28 _CONF_INDIVIDUAL = "individual"
29 
30 _ZABBIX_ID_LIST_SCHEMA = vol.Schema([int])
31 _ZABBIX_TRIGGER_SCHEMA = vol.Schema(
32  {
33  vol.Optional(_CONF_HOSTIDS, default=[]): _ZABBIX_ID_LIST_SCHEMA,
34  vol.Optional(_CONF_INDIVIDUAL, default=False): cv.boolean,
35  vol.Optional(CONF_NAME): cv.string,
36  }
37 )
38 
39 # SCAN_INTERVAL = 30
40 #
41 PLATFORM_SCHEMA = SENSOR_PLATFORM_SCHEMA.extend(
42  {vol.Required(_CONF_TRIGGERS): vol.Any(_ZABBIX_TRIGGER_SCHEMA, None)}
43 )
44 
45 
47  hass: HomeAssistant,
48  config: ConfigType,
49  add_entities: AddEntitiesCallback,
50  discovery_info: DiscoveryInfoType | None = None,
51 ) -> None:
52  """Set up the Zabbix sensor platform."""
53  sensors: list[ZabbixTriggerCountSensor] = []
54 
55  if not (zapi := hass.data[DOMAIN]):
56  _LOGGER.error("Zabbix integration hasn't been loaded? zapi is None")
57  return
58 
59  _LOGGER.debug("Connected to Zabbix API Version %s", zapi.api_version())
60 
61  # The following code seems overly complex. Need to think about this...
62  if trigger_conf := config.get(_CONF_TRIGGERS):
63  hostids = trigger_conf.get(_CONF_HOSTIDS)
64  individual = trigger_conf.get(_CONF_INDIVIDUAL)
65  name = trigger_conf.get(CONF_NAME)
66 
67  if individual:
68  # Individual sensor per host
69  if not hostids:
70  # We need hostids
71  _LOGGER.error("If using 'individual', must specify hostids")
72  return
73 
74  for hostid in hostids:
75  _LOGGER.debug("Creating Zabbix Sensor: %s", str(hostid))
76  sensors.append(ZabbixSingleHostTriggerCountSensor(zapi, [hostid], name))
77  elif not hostids:
78  # Single sensor that provides the total count of triggers.
79  _LOGGER.debug("Creating Zabbix Sensor")
80  sensors.append(ZabbixTriggerCountSensor(zapi, name))
81  else:
82  # Single sensor that sums total issues for all hosts
83  _LOGGER.debug("Creating Zabbix Sensor group: %s", str(hostids))
84  sensors.append(ZabbixMultipleHostTriggerCountSensor(zapi, hostids, name))
85 
86  else:
87  # Single sensor that provides the total count of triggers.
88  _LOGGER.debug("Creating Zabbix Sensor")
89  sensors.append(ZabbixTriggerCountSensor(zapi))
90 
91  add_entities(sensors)
92 
93 
95  """Get the active trigger count for all Zabbix monitored hosts."""
96 
97  def __init__(self, zapi: ZabbixAPI, name: str | None = "Zabbix") -> None:
98  """Initialize Zabbix sensor."""
99  self._name_name = name
100  self._zapi_zapi = zapi
101  self._state_state: int | None = None
102  self._attributes: dict[str, Any] = {}
103 
104  @property
105  def name(self) -> str | None:
106  """Return the name of the sensor."""
107  return self._name_name
108 
109  @property
110  def native_value(self) -> StateType:
111  """Return the state of the sensor."""
112  return self._state_state
113 
114  @property
115  def native_unit_of_measurement(self) -> str:
116  """Return the units of measurement."""
117  return "issues"
118 
119  def _call_zabbix_api(self):
120  return self._zapi_zapi.trigger.get(
121  output="extend", only_true=1, monitored=1, filter={"value": 1}
122  )
123 
124  def update(self) -> None:
125  """Update the sensor."""
126  _LOGGER.debug("Updating ZabbixTriggerCountSensor: %s", str(self._name_name))
127  triggers = self._call_zabbix_api_call_zabbix_api()
128  self._state_state = len(triggers)
129 
130  @property
131  def extra_state_attributes(self) -> Mapping[str, Any] | None:
132  """Return the state attributes of the device."""
133  return self._attributes
134 
135 
137  """Get the active trigger count for a single Zabbix monitored host."""
138 
139  def __init__(
140  self, zapi: ZabbixAPI, hostid: list[str], name: str | None = None
141  ) -> None:
142  """Initialize Zabbix sensor."""
143  super().__init__(zapi, name)
144  self._hostid_hostid = hostid
145  if not name:
146  self._name_name_name = self._zapi_zapi.host.get(hostids=self._hostid_hostid, output="extend")[0][
147  "name"
148  ]
149 
150  self._attributes["Host ID"] = self._hostid_hostid
151 
152  def _call_zabbix_api(self):
153  return self._zapi_zapi.trigger.get(
154  hostids=self._hostid_hostid,
155  output="extend",
156  only_true=1,
157  monitored=1,
158  filter={"value": 1},
159  )
160 
161 
163  """Get the active trigger count for specified Zabbix monitored hosts."""
164 
165  def __init__(
166  self, zapi: ZabbixAPI, hostids: list[str], name: str | None = None
167  ) -> None:
168  """Initialize Zabbix sensor."""
169  super().__init__(zapi, name)
170  self._hostids_hostids = hostids
171  if not name:
172  host_names = self._zapi_zapi.host.get(hostids=self._hostids_hostids, output="extend")
173  self._name_name_name = " ".join(name["name"] for name in host_names)
174  self._attributes["Host IDs"] = self._hostids_hostids
175 
176  def _call_zabbix_api(self):
177  return self._zapi_zapi.trigger.get(
178  hostids=self._hostids_hostids,
179  output="extend",
180  only_true=1,
181  monitored=1,
182  filter={"value": 1},
183  )
None __init__(self, ZabbixAPI zapi, list[str] hostids, str|None name=None)
Definition: sensor.py:167
None __init__(self, ZabbixAPI zapi, list[str] hostid, str|None name=None)
Definition: sensor.py:141
None __init__(self, ZabbixAPI zapi, str|None name="Zabbix")
Definition: sensor.py:97
def add_entities(account, async_add_entities, tracked)
Definition: sensor.py:40
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: sensor.py:51