2019-02-14 04:35:12 +00:00
|
|
|
"""Support for Modbus Register sensors."""
|
2021-03-18 12:07:04 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2021-09-20 05:35:11 +00:00
|
|
|
from datetime import datetime
|
2022-02-28 19:07:55 +00:00
|
|
|
import logging
|
2021-05-26 17:28:14 +00:00
|
|
|
from typing import Any
|
2019-12-06 05:10:29 +00:00
|
|
|
|
2021-08-27 03:54:50 +00:00
|
|
|
from homeassistant.components.sensor import CONF_STATE_CLASS, SensorEntity
|
2021-07-20 04:52:58 +00:00
|
|
|
from homeassistant.const import CONF_NAME, CONF_SENSORS, CONF_UNIT_OF_MEASUREMENT
|
2022-02-28 19:07:55 +00:00
|
|
|
from homeassistant.core import HomeAssistant, callback
|
2021-09-20 05:35:11 +00:00
|
|
|
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
2019-02-24 09:22:17 +00:00
|
|
|
from homeassistant.helpers.restore_state import RestoreEntity
|
2021-04-19 08:13:32 +00:00
|
|
|
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
|
2022-02-28 19:07:55 +00:00
|
|
|
from homeassistant.helpers.update_coordinator import (
|
|
|
|
CoordinatorEntity,
|
|
|
|
DataUpdateCoordinator,
|
|
|
|
)
|
2015-04-15 14:47:42 +00:00
|
|
|
|
2021-08-08 20:48:33 +00:00
|
|
|
from . import get_hub
|
2021-07-20 04:52:58 +00:00
|
|
|
from .base_platform import BaseStructPlatform
|
2022-02-28 19:07:55 +00:00
|
|
|
from .const import CONF_SLAVE_COUNT
|
2021-05-26 17:28:14 +00:00
|
|
|
from .modbus import ModbusHub
|
2019-03-21 05:56:46 +00:00
|
|
|
|
2022-02-28 19:07:55 +00:00
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2021-05-15 17:54:17 +00:00
|
|
|
PARALLEL_UPDATES = 1
|
2017-05-02 16:18:47 +00:00
|
|
|
|
2019-08-10 00:03:12 +00:00
|
|
|
|
2021-03-27 21:48:06 +00:00
|
|
|
async def async_setup_platform(
|
2021-04-19 08:13:32 +00:00
|
|
|
hass: HomeAssistant,
|
2021-03-27 21:48:06 +00:00
|
|
|
config: ConfigType,
|
2021-09-20 05:35:11 +00:00
|
|
|
async_add_entities: AddEntitiesCallback,
|
2021-03-27 21:48:06 +00:00
|
|
|
discovery_info: DiscoveryInfoType | None = None,
|
2021-09-20 05:35:11 +00:00
|
|
|
) -> None:
|
2016-10-30 08:58:34 +00:00
|
|
|
"""Set up the Modbus sensors."""
|
2017-11-13 22:27:15 +00:00
|
|
|
|
2022-03-11 17:58:18 +00:00
|
|
|
if discovery_info is None:
|
2021-05-26 17:28:14 +00:00
|
|
|
return
|
2021-03-27 21:48:06 +00:00
|
|
|
|
2022-02-28 19:07:55 +00:00
|
|
|
sensors: list[ModbusRegisterSensor | SlaveSensor] = []
|
|
|
|
hub = get_hub(hass, discovery_info[CONF_NAME])
|
2021-03-27 21:48:06 +00:00
|
|
|
for entry in discovery_info[CONF_SENSORS]:
|
2022-02-28 19:07:55 +00:00
|
|
|
slave_count = entry.get(CONF_SLAVE_COUNT, 0)
|
|
|
|
sensor = ModbusRegisterSensor(hub, entry)
|
|
|
|
if slave_count > 0:
|
|
|
|
sensors.extend(await sensor.async_setup_slaves(hass, slave_count, entry))
|
|
|
|
sensors.append(sensor)
|
2021-05-27 06:28:31 +00:00
|
|
|
async_add_entities(sensors)
|
2015-04-15 14:47:42 +00:00
|
|
|
|
2015-04-21 14:40:13 +00:00
|
|
|
|
2021-07-20 04:52:58 +00:00
|
|
|
class ModbusRegisterSensor(BaseStructPlatform, RestoreEntity, SensorEntity):
|
2017-09-23 15:15:46 +00:00
|
|
|
"""Modbus register sensor."""
|
2015-04-15 14:47:42 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
2021-05-26 17:28:14 +00:00
|
|
|
hub: ModbusHub,
|
|
|
|
entry: dict[str, Any],
|
|
|
|
) -> None:
|
2016-09-13 20:47:44 +00:00
|
|
|
"""Initialize the modbus register sensor."""
|
2021-05-20 14:56:11 +00:00
|
|
|
super().__init__(hub, entry)
|
2022-02-28 19:07:55 +00:00
|
|
|
self._coordinator: DataUpdateCoordinator[Any] | None = None
|
2021-08-11 19:17:47 +00:00
|
|
|
self._attr_native_unit_of_measurement = entry.get(CONF_UNIT_OF_MEASUREMENT)
|
2021-08-25 09:50:54 +00:00
|
|
|
self._attr_state_class = entry.get(CONF_STATE_CLASS)
|
2015-04-15 14:47:42 +00:00
|
|
|
|
2022-02-28 19:07:55 +00:00
|
|
|
async def async_setup_slaves(
|
|
|
|
self, hass: HomeAssistant, slave_count: int, entry: dict[str, Any]
|
|
|
|
) -> list[SlaveSensor]:
|
|
|
|
"""Add slaves as needed (1 read for multiple sensors)."""
|
|
|
|
|
|
|
|
# Add a dataCoordinator for each sensor that have slaves
|
|
|
|
# this ensures that idx = bit position of value in result
|
|
|
|
# polling is done with the base class
|
|
|
|
name = self._attr_name if self._attr_name else "modbus_sensor"
|
|
|
|
self._coordinator = DataUpdateCoordinator(
|
|
|
|
hass,
|
|
|
|
_LOGGER,
|
|
|
|
name=name,
|
|
|
|
)
|
|
|
|
|
|
|
|
slaves: list[SlaveSensor] = []
|
|
|
|
for idx in range(0, slave_count):
|
|
|
|
slaves.append(SlaveSensor(self._coordinator, idx, entry))
|
|
|
|
return slaves
|
|
|
|
|
2021-09-20 05:35:11 +00:00
|
|
|
async def async_added_to_hass(self) -> None:
|
2019-02-11 19:00:37 +00:00
|
|
|
"""Handle entity which will be added."""
|
2021-05-20 14:56:11 +00:00
|
|
|
await self.async_base_added_to_hass()
|
2021-10-30 14:30:13 +00:00
|
|
|
if state := await self.async_get_last_state():
|
2021-08-11 19:17:47 +00:00
|
|
|
self._attr_native_value = state.state
|
2015-04-15 14:47:42 +00:00
|
|
|
|
2021-09-20 05:35:11 +00:00
|
|
|
async def async_update(self, now: datetime | None = None) -> None:
|
2016-02-23 05:21:49 +00:00
|
|
|
"""Update the state of the sensor."""
|
2021-05-15 17:54:17 +00:00
|
|
|
# remark "now" is a dummy parameter to avoid problems with
|
|
|
|
# async_track_time_interval
|
2022-02-28 19:07:55 +00:00
|
|
|
raw_result = await self._hub.async_pymodbus_call(
|
2021-05-26 17:28:14 +00:00
|
|
|
self._slave, self._address, self._count, self._input_type
|
2021-05-17 09:20:12 +00:00
|
|
|
)
|
2022-02-28 19:07:55 +00:00
|
|
|
if raw_result is None:
|
2021-08-21 13:49:50 +00:00
|
|
|
if self._lazy_errors:
|
|
|
|
self._lazy_errors -= 1
|
|
|
|
return
|
|
|
|
self._lazy_errors = self._lazy_error_count
|
2021-07-26 19:20:34 +00:00
|
|
|
self._attr_available = False
|
2022-03-02 17:49:57 +00:00
|
|
|
self._attr_native_value = None
|
|
|
|
if self._coordinator:
|
|
|
|
self._coordinator.async_set_updated_data(None)
|
2021-05-15 17:54:17 +00:00
|
|
|
self.async_write_ha_state()
|
2020-02-12 17:37:16 +00:00
|
|
|
return
|
|
|
|
|
2022-02-28 19:07:55 +00:00
|
|
|
result = self.unpack_structure_result(raw_result.registers)
|
|
|
|
if self._coordinator:
|
|
|
|
if result:
|
|
|
|
result_array = result.split(",")
|
|
|
|
self._attr_native_value = result_array[0]
|
|
|
|
self._coordinator.async_set_updated_data(result_array)
|
|
|
|
else:
|
|
|
|
self._attr_native_value = None
|
|
|
|
self._coordinator.async_set_updated_data(None)
|
|
|
|
else:
|
|
|
|
self._attr_native_value = result
|
2021-10-20 22:22:01 +00:00
|
|
|
if self._attr_native_value is None:
|
|
|
|
self._attr_available = False
|
|
|
|
else:
|
|
|
|
self._attr_available = True
|
2021-08-21 13:49:50 +00:00
|
|
|
self._lazy_errors = self._lazy_error_count
|
2021-05-15 17:54:17 +00:00
|
|
|
self.async_write_ha_state()
|
2022-02-28 19:07:55 +00:00
|
|
|
|
|
|
|
|
|
|
|
class SlaveSensor(CoordinatorEntity, RestoreEntity, SensorEntity):
|
|
|
|
"""Modbus slave binary sensor."""
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self, coordinator: DataUpdateCoordinator[Any], idx: int, entry: dict[str, Any]
|
|
|
|
) -> None:
|
|
|
|
"""Initialize the Modbus binary sensor."""
|
|
|
|
idx += 1
|
|
|
|
self._idx = idx
|
|
|
|
self._attr_name = f"{entry[CONF_NAME]} {idx}"
|
|
|
|
self._attr_available = False
|
|
|
|
super().__init__(coordinator)
|
|
|
|
|
|
|
|
async def async_added_to_hass(self) -> None:
|
|
|
|
"""Handle entity which will be added."""
|
|
|
|
if state := await self.async_get_last_state():
|
|
|
|
self._attr_native_value = state.state
|
|
|
|
await super().async_added_to_hass()
|
|
|
|
|
|
|
|
@callback
|
|
|
|
def _handle_coordinator_update(self) -> None:
|
|
|
|
"""Handle updated data from the coordinator."""
|
|
|
|
result = self.coordinator.data
|
|
|
|
if result:
|
|
|
|
self._attr_native_value = result[self._idx]
|
|
|
|
super()._handle_coordinator_update()
|