Add base class for all modbus platforms (#50878)

* Add base for all platforms.

* Please pylint.
This commit is contained in:
jan iversen 2021-05-20 16:56:11 +02:00 committed by GitHub
parent f212049fc2
commit c650deef98
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 98 additions and 182 deletions

View file

@ -1,7 +1,6 @@
"""Support for Modbus Coil and Discrete Input sensors."""
from __future__ import annotations
from datetime import timedelta
import logging
import voluptuous as vol
@ -21,9 +20,9 @@ from homeassistant.const import (
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.event import async_track_time_interval
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from .base_platform import BasePlatform
from .const import (
CALL_TYPE_COIL,
CALL_TYPE_DISCRETE,
@ -92,65 +91,25 @@ async def async_setup_platform(
hub = hass.data[MODBUS_DOMAIN][discovery_info[CONF_NAME]]
if CONF_SCAN_INTERVAL not in entry:
entry[CONF_SCAN_INTERVAL] = DEFAULT_SCAN_INTERVAL
sensors.append(ModbusBinarySensor(hub, hass, entry))
sensors.append(ModbusBinarySensor(hub, entry))
async_add_entities(sensors)
class ModbusBinarySensor(BinarySensorEntity):
class ModbusBinarySensor(BasePlatform, BinarySensorEntity):
"""Modbus binary sensor."""
def __init__(self, hub, hass, entry):
"""Initialize the Modbus binary sensor."""
self._hub = hub
self._hass = hass
self._name = entry[CONF_NAME]
self._slave = entry.get(CONF_SLAVE)
self._address = int(entry[CONF_ADDRESS])
self._device_class = entry.get(CONF_DEVICE_CLASS)
self._input_type = entry[CONF_INPUT_TYPE]
self._value = None
self._available = True
self._scan_interval = timedelta(seconds=entry[CONF_SCAN_INTERVAL])
async def async_added_to_hass(self):
"""Handle entity which will be added."""
async_track_time_interval(self._hass, self.async_update, self._scan_interval)
@property
def name(self):
"""Return the name of the sensor."""
return self._name
await self.async_base_added_to_hass()
@property
def is_on(self):
"""Return the state of the sensor."""
return self._value
@property
def device_class(self) -> str | None:
"""Return the device class of the sensor."""
return self._device_class
@property
def should_poll(self):
"""Return True if entity has to be polled for state.
False if entity pushes its state to HA.
"""
# Handle polling directly in this entity
return False
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._available
async def async_update(self, now=None):
"""Update the state of the sensor."""
# remark "now" is a dummy parameter to avoid problems with
# async_track_time_interval
result = await self._hub.async_pymodbus_call(
self._slave, self._address, 1, self._input_type
)