Revert "Introduce base entity for ping" (#104682)

This commit is contained in:
Jan-Philipp Benecke 2023-11-29 08:42:02 +01:00 committed by GitHub
parent 017d05c03e
commit a9a95ad881
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 39 additions and 111 deletions

View file

@ -18,11 +18,11 @@ import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from . import PingDomainData from . import PingDomainData
from .const import CONF_IMPORTED_BY, CONF_PING_COUNT, DEFAULT_PING_COUNT, DOMAIN from .const import CONF_IMPORTED_BY, CONF_PING_COUNT, DEFAULT_PING_COUNT, DOMAIN
from .coordinator import PingUpdateCoordinator from .coordinator import PingUpdateCoordinator
from .entity import BasePingEntity
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -84,16 +84,20 @@ async def async_setup_entry(
async_add_entities([PingBinarySensor(entry, data.coordinators[entry.entry_id])]) async_add_entities([PingBinarySensor(entry, data.coordinators[entry.entry_id])])
class PingBinarySensor(BasePingEntity, BinarySensorEntity): class PingBinarySensor(CoordinatorEntity[PingUpdateCoordinator], BinarySensorEntity):
"""Representation of a Ping Binary sensor.""" """Representation of a Ping Binary sensor."""
_attr_device_class = BinarySensorDeviceClass.CONNECTIVITY _attr_device_class = BinarySensorDeviceClass.CONNECTIVITY
_attr_available = False
def __init__( def __init__(
self, config_entry: ConfigEntry, coordinator: PingUpdateCoordinator self, config_entry: ConfigEntry, coordinator: PingUpdateCoordinator
) -> None: ) -> None:
"""Initialize the Ping Binary sensor.""" """Initialize the Ping Binary sensor."""
super().__init__(config_entry, coordinator) super().__init__(coordinator)
self._attr_name = config_entry.title
self._attr_unique_id = config_entry.entry_id
# if this was imported just enable it when it was enabled before # if this was imported just enable it when it was enabled before
if CONF_IMPORTED_BY in config_entry.data: if CONF_IMPORTED_BY in config_entry.data:
@ -108,7 +112,7 @@ class PingBinarySensor(BasePingEntity, BinarySensorEntity):
@property @property
def extra_state_attributes(self) -> dict[str, Any] | None: def extra_state_attributes(self) -> dict[str, Any] | None:
"""Return the state attributes of the ICMP echo request.""" """Return the state attributes of the ICMP checo request."""
if self.coordinator.data.data is None: if self.coordinator.data.data is None:
return None return None
return { return {

View file

@ -8,26 +8,21 @@ import voluptuous as vol
from homeassistant.components.device_tracker import ( from homeassistant.components.device_tracker import (
PLATFORM_SCHEMA as BASE_PLATFORM_SCHEMA, PLATFORM_SCHEMA as BASE_PLATFORM_SCHEMA,
AsyncSeeCallback, AsyncSeeCallback,
ScannerEntity,
SourceType, SourceType,
) )
from homeassistant.components.device_tracker.config_entry import BaseTrackerEntity
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import ( from homeassistant.const import CONF_HOST, CONF_HOSTS, CONF_NAME
CONF_HOST,
CONF_HOSTS,
CONF_NAME,
STATE_HOME,
STATE_NOT_HOME,
)
from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from . import PingDomainData from . import PingDomainData
from .const import CONF_IMPORTED_BY, CONF_PING_COUNT, DOMAIN from .const import CONF_IMPORTED_BY, CONF_PING_COUNT, DOMAIN
from .entity import BasePingEntity from .coordinator import PingUpdateCoordinator
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -89,20 +84,37 @@ async def async_setup_entry(
async_add_entities([PingDeviceTracker(entry, data.coordinators[entry.entry_id])]) async_add_entities([PingDeviceTracker(entry, data.coordinators[entry.entry_id])])
class PingDeviceTracker(BasePingEntity, BaseTrackerEntity): class PingDeviceTracker(CoordinatorEntity[PingUpdateCoordinator], ScannerEntity):
"""Representation of a Ping device tracker.""" """Representation of a Ping device tracker."""
def __init__(
self, config_entry: ConfigEntry, coordinator: PingUpdateCoordinator
) -> None:
"""Initialize the Ping device tracker."""
super().__init__(coordinator)
self._attr_name = config_entry.title
self.config_entry = config_entry
@property
def ip_address(self) -> str:
"""Return the primary ip address of the device."""
return self.coordinator.data.ip_address
@property
def unique_id(self) -> str:
"""Return a unique ID."""
return self.config_entry.entry_id
@property @property
def source_type(self) -> SourceType: def source_type(self) -> SourceType:
"""Return the source type which is router.""" """Return the source type which is router."""
return SourceType.ROUTER return SourceType.ROUTER
@property @property
def state(self) -> str: def is_connected(self) -> bool:
"""Return the state of the device.""" """Return true if ping returns is_alive."""
if self.coordinator.data.is_alive: return self.coordinator.data.is_alive
return STATE_HOME
return STATE_NOT_HOME
@property @property
def entity_registry_enabled_default(self) -> bool: def entity_registry_enabled_default(self) -> bool:

View file

@ -1,28 +0,0 @@
"""Base entity for Ping integration."""
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .coordinator import PingUpdateCoordinator
class BasePingEntity(CoordinatorEntity[PingUpdateCoordinator]):
"""Representation of a Ping base entity."""
_attr_has_entity_name = True
_attr_name = None
def __init__(
self, config_entry: ConfigEntry, coordinator: PingUpdateCoordinator
) -> None:
"""Initialize the Ping Binary sensor."""
super().__init__(coordinator)
self._attr_unique_id = config_entry.entry_id
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, self.coordinator.data.ip_address)},
manufacturer="Ping",
)
self.config_entry = config_entry

View file

@ -72,7 +72,7 @@
'domain': 'binary_sensor', 'domain': 'binary_sensor',
'entity_category': None, 'entity_category': None,
'entity_id': 'binary_sensor.10_10_10_10', 'entity_id': 'binary_sensor.10_10_10_10',
'has_entity_name': True, 'has_entity_name': False,
'hidden_by': None, 'hidden_by': None,
'icon': None, 'icon': None,
'id': <ANY>, 'id': <ANY>,
@ -81,7 +81,7 @@
}), }),
'original_device_class': <BinarySensorDeviceClass.CONNECTIVITY: 'connectivity'>, 'original_device_class': <BinarySensorDeviceClass.CONNECTIVITY: 'connectivity'>,
'original_icon': None, 'original_icon': None,
'original_name': None, 'original_name': '10.10.10.10',
'platform': 'ping', 'platform': 'ping',
'previous_unique_id': None, 'previous_unique_id': None,
'supported_features': 0, 'supported_features': 0,
@ -90,34 +90,6 @@
}) })
# --- # ---
# name: test_setup_and_update.1 # name: test_setup_and_update.1
DeviceRegistryEntrySnapshot({
'area_id': None,
'config_entries': <ANY>,
'configuration_url': None,
'connections': set({
}),
'disabled_by': None,
'entry_type': None,
'hw_version': None,
'id': <ANY>,
'identifiers': set({
tuple(
'ping',
'10.10.10.10',
),
}),
'is_new': False,
'manufacturer': 'Ping',
'model': None,
'name': '10.10.10.10',
'name_by_user': None,
'serial_number': None,
'suggested_area': None,
'sw_version': None,
'via_device_id': None,
})
# ---
# name: test_setup_and_update.2
StateSnapshot({ StateSnapshot({
'attributes': ReadOnlyDict({ 'attributes': ReadOnlyDict({
'device_class': 'connectivity', 'device_class': 'connectivity',
@ -134,7 +106,7 @@
'state': 'on', 'state': 'on',
}) })
# --- # ---
# name: test_setup_and_update.3 # name: test_setup_and_update.2
StateSnapshot({ StateSnapshot({
'attributes': ReadOnlyDict({ 'attributes': ReadOnlyDict({
'device_class': 'connectivity', 'device_class': 'connectivity',

View file

@ -10,11 +10,7 @@ from syrupy.filters import props
from homeassistant.components.ping.const import CONF_IMPORTED_BY, DOMAIN from homeassistant.components.ping.const import CONF_IMPORTED_BY, DOMAIN
from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant
from homeassistant.helpers import ( from homeassistant.helpers import entity_registry as er, issue_registry as ir
device_registry as dr,
entity_registry as er,
issue_registry as ir,
)
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
@ -24,7 +20,6 @@ from tests.common import MockConfigEntry
async def test_setup_and_update( async def test_setup_and_update(
hass: HomeAssistant, hass: HomeAssistant,
entity_registry: er.EntityRegistry, entity_registry: er.EntityRegistry,
device_registry: dr.DeviceRegistry,
freezer: FrozenDateTimeFactory, freezer: FrozenDateTimeFactory,
snapshot: SnapshotAssertion, snapshot: SnapshotAssertion,
) -> None: ) -> None:
@ -34,10 +29,6 @@ async def test_setup_and_update(
entry = entity_registry.async_get("binary_sensor.10_10_10_10") entry = entity_registry.async_get("binary_sensor.10_10_10_10")
assert entry == snapshot(exclude=props("unique_id")) assert entry == snapshot(exclude=props("unique_id"))
# check the device
device = device_registry.async_get_device({(DOMAIN, "10.10.10.10")})
assert device == snapshot
state = hass.states.get("binary_sensor.10_10_10_10") state = hass.states.get("binary_sensor.10_10_10_10")
assert state == snapshot assert state == snapshot

View file

@ -1,9 +1,5 @@
"""Test the binary sensor platform of ping.""" """Test the binary sensor platform of ping."""
from datetime import timedelta
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
from icmplib import Host
import pytest import pytest
from homeassistant.components.ping.const import DOMAIN from homeassistant.components.ping.const import DOMAIN
@ -19,7 +15,6 @@ async def test_setup_and_update(
hass: HomeAssistant, hass: HomeAssistant,
entity_registry: er.EntityRegistry, entity_registry: er.EntityRegistry,
config_entry: MockConfigEntry, config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None: ) -> None:
"""Test sensor setup and update.""" """Test sensor setup and update."""
@ -47,24 +42,6 @@ async def test_setup_and_update(
state = hass.states.get("device_tracker.10_10_10_10") state = hass.states.get("device_tracker.10_10_10_10")
assert state.state == "home" assert state.state == "home"
freezer.tick(timedelta(minutes=5))
await hass.async_block_till_done()
# check device tracker is still "home"
state = hass.states.get("device_tracker.10_10_10_10")
assert state.state == "home"
# check if device tracker updates to "not home"
with patch(
"homeassistant.components.ping.helpers.async_ping",
return_value=Host(address="10.10.10.10", packets_sent=10, rtts=[]),
):
freezer.tick(timedelta(minutes=5))
await hass.async_block_till_done()
state = hass.states.get("device_tracker.10_10_10_10")
assert state.state == "not_home"
async def test_import_issue_creation( async def test_import_issue_creation(
hass: HomeAssistant, hass: HomeAssistant,