Upgrade thethingsnetwork to v3 (#113375)
* thethingsnetwork upgrade to v3 * add en translations and requirements_all * fix most of the findings * hassfest * use ttn_client v0.0.3 * reduce content of initial release * remove features that trigger errors * remove unneeded * add initial testcases * Exception warning * add strict type checking * add strict type checking * full coverage * rename to conftest * review changes * avoid using private attributes - use protected instead * simplify config_flow * remove unused options * review changes * upgrade client * add types client library - no need to cast * use add_suggested_values_to_schema * add ruff fix * review changes * remove unneeded comment * use typevar for TTN value * use typevar for TTN value * review * ruff error not detected in local * test review * re-order fixture * fix test * reviews * fix case * split testcases * review feedback * Update homeassistant/components/thethingsnetwork/__init__.py Co-authored-by: Joost Lekkerkerker <joostlek@outlook.com> * Update homeassistant/components/thethingsnetwork/__init__.py Co-authored-by: Joost Lekkerkerker <joostlek@outlook.com> * Update tests/components/thethingsnetwork/test_config_flow.py Co-authored-by: Joost Lekkerkerker <joostlek@outlook.com> * Remove deprecated var * Update tests/components/thethingsnetwork/test_config_flow.py Co-authored-by: Joost Lekkerkerker <joostlek@outlook.com> * Remove unused import * fix ruff warning --------- Co-authored-by: Joost Lekkerkerker <joostlek@outlook.com>
This commit is contained in:
parent
a7938091bf
commit
b85cf36a68
21 changed files with 725 additions and 165 deletions
|
@ -1,165 +1,56 @@
|
|||
"""Support for The Things Network's Data storage integration."""
|
||||
"""The Things Network's integration sensors."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from http import HTTPStatus
|
||||
import logging
|
||||
|
||||
import aiohttp
|
||||
from aiohttp.hdrs import ACCEPT, AUTHORIZATION
|
||||
import voluptuous as vol
|
||||
from ttn_client import TTNSensorValue
|
||||
|
||||
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
|
||||
from homeassistant.const import (
|
||||
ATTR_DEVICE_ID,
|
||||
ATTR_TIME,
|
||||
CONF_DEVICE_ID,
|
||||
CONTENT_TYPE_JSON,
|
||||
)
|
||||
from homeassistant.components.sensor import SensorEntity, StateType
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
|
||||
|
||||
from . import DATA_TTN, TTN_ACCESS_KEY, TTN_APP_ID, TTN_DATA_STORAGE_URL
|
||||
from .const import CONF_APP_ID, DOMAIN
|
||||
from .entity import TTNEntity
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
ATTR_RAW = "raw"
|
||||
|
||||
DEFAULT_TIMEOUT = 10
|
||||
CONF_VALUES = "values"
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
||||
{
|
||||
vol.Required(CONF_DEVICE_ID): cv.string,
|
||||
vol.Required(CONF_VALUES): {cv.string: cv.string},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def async_setup_platform(
|
||||
hass: HomeAssistant,
|
||||
config: ConfigType,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
discovery_info: DiscoveryInfoType | None = None,
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
|
||||
) -> None:
|
||||
"""Set up The Things Network Data storage sensors."""
|
||||
ttn = hass.data[DATA_TTN]
|
||||
device_id = config[CONF_DEVICE_ID]
|
||||
values = config[CONF_VALUES]
|
||||
app_id = ttn.get(TTN_APP_ID)
|
||||
access_key = ttn.get(TTN_ACCESS_KEY)
|
||||
"""Add entities for TTN."""
|
||||
|
||||
ttn_data_storage = TtnDataStorage(hass, app_id, device_id, access_key, values)
|
||||
success = await ttn_data_storage.async_update()
|
||||
coordinator = hass.data[DOMAIN][entry.entry_id]
|
||||
|
||||
if not success:
|
||||
return
|
||||
sensors: set[tuple[str, str]] = set()
|
||||
|
||||
devices = []
|
||||
for value, unit_of_measurement in values.items():
|
||||
devices.append(
|
||||
TtnDataSensor(ttn_data_storage, device_id, value, unit_of_measurement)
|
||||
)
|
||||
async_add_entities(devices, True)
|
||||
def _async_measurement_listener() -> None:
|
||||
data = coordinator.data
|
||||
new_sensors = {
|
||||
(device_id, field_id): TtnDataSensor(
|
||||
coordinator,
|
||||
entry.data[CONF_APP_ID],
|
||||
ttn_value,
|
||||
)
|
||||
for device_id, device_uplinks in data.items()
|
||||
for field_id, ttn_value in device_uplinks.items()
|
||||
if (device_id, field_id) not in sensors
|
||||
and isinstance(ttn_value, TTNSensorValue)
|
||||
}
|
||||
if len(new_sensors):
|
||||
async_add_entities(new_sensors.values())
|
||||
sensors.update(new_sensors.keys())
|
||||
|
||||
entry.async_on_unload(coordinator.async_add_listener(_async_measurement_listener))
|
||||
_async_measurement_listener()
|
||||
|
||||
|
||||
class TtnDataSensor(SensorEntity):
|
||||
"""Representation of a The Things Network Data Storage sensor."""
|
||||
class TtnDataSensor(TTNEntity, SensorEntity):
|
||||
"""Represents a TTN Home Assistant Sensor."""
|
||||
|
||||
def __init__(self, ttn_data_storage, device_id, value, unit_of_measurement):
|
||||
"""Initialize a The Things Network Data Storage sensor."""
|
||||
self._ttn_data_storage = ttn_data_storage
|
||||
self._state = None
|
||||
self._device_id = device_id
|
||||
self._unit_of_measurement = unit_of_measurement
|
||||
self._value = value
|
||||
self._name = f"{self._device_id} {self._value}"
|
||||
_ttn_value: TTNSensorValue
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the sensor."""
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def native_value(self):
|
||||
def native_value(self) -> StateType:
|
||||
"""Return the state of the entity."""
|
||||
if self._ttn_data_storage.data is not None:
|
||||
try:
|
||||
return self._state[self._value]
|
||||
except KeyError:
|
||||
return None
|
||||
return None
|
||||
|
||||
@property
|
||||
def native_unit_of_measurement(self):
|
||||
"""Return the unit this state is expressed in."""
|
||||
return self._unit_of_measurement
|
||||
|
||||
@property
|
||||
def extra_state_attributes(self):
|
||||
"""Return the state attributes of the sensor."""
|
||||
if self._ttn_data_storage.data is not None:
|
||||
return {
|
||||
ATTR_DEVICE_ID: self._device_id,
|
||||
ATTR_RAW: self._state["raw"],
|
||||
ATTR_TIME: self._state["time"],
|
||||
}
|
||||
|
||||
async def async_update(self) -> None:
|
||||
"""Get the current state."""
|
||||
await self._ttn_data_storage.async_update()
|
||||
self._state = self._ttn_data_storage.data
|
||||
|
||||
|
||||
class TtnDataStorage:
|
||||
"""Get the latest data from The Things Network Data Storage."""
|
||||
|
||||
def __init__(self, hass, app_id, device_id, access_key, values):
|
||||
"""Initialize the data object."""
|
||||
self.data = None
|
||||
self._hass = hass
|
||||
self._app_id = app_id
|
||||
self._device_id = device_id
|
||||
self._values = values
|
||||
self._url = TTN_DATA_STORAGE_URL.format(
|
||||
app_id=app_id, endpoint="api/v2/query", device_id=device_id
|
||||
)
|
||||
self._headers = {ACCEPT: CONTENT_TYPE_JSON, AUTHORIZATION: f"key {access_key}"}
|
||||
|
||||
async def async_update(self):
|
||||
"""Get the current state from The Things Network Data Storage."""
|
||||
try:
|
||||
session = async_get_clientsession(self._hass)
|
||||
async with asyncio.timeout(DEFAULT_TIMEOUT):
|
||||
response = await session.get(self._url, headers=self._headers)
|
||||
|
||||
except (TimeoutError, aiohttp.ClientError):
|
||||
_LOGGER.error("Error while accessing: %s", self._url)
|
||||
return None
|
||||
|
||||
status = response.status
|
||||
|
||||
if status == HTTPStatus.NO_CONTENT:
|
||||
_LOGGER.error("The device is not available: %s", self._device_id)
|
||||
return None
|
||||
|
||||
if status == HTTPStatus.UNAUTHORIZED:
|
||||
_LOGGER.error("Not authorized for Application ID: %s", self._app_id)
|
||||
return None
|
||||
|
||||
if status == HTTPStatus.NOT_FOUND:
|
||||
_LOGGER.error("Application ID is not available: %s", self._app_id)
|
||||
return None
|
||||
|
||||
data = await response.json()
|
||||
self.data = data[-1]
|
||||
|
||||
for value in self._values.items():
|
||||
if value[0] not in self.data:
|
||||
_LOGGER.warning("Value not available: %s", value[0])
|
||||
|
||||
return response
|
||||
return self._ttn_value.value
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue