mirror of
https://github.com/home-assistant/core.git
synced 2025-05-01 12:47:53 +00:00

* Add MELCloud integration * Provides a climate and sensor platforms. Multiple platforms on one go is not the best option, but it does not make sense to remove them and commit them later either. * Email and access token are stored to the ConfigEntry. The token can be updated by adding the integration again with the same email address. The config flow is aborted and the update is performed on the background. * Run isort * Fix pylint errors * Run black * Increase coverage * Update pymelcloud dependency * Add HVAC_MODE_OFF emulation * Remove print * Update pymelcloud to enable device type filtering * Collapse except blocks and chain ClientNotReadys * Add preliminary documentation URL * Use list comp for creating model info Filters out empty model names form units. * f-string galore Dropped 'HVAC' from AtaDevice name template. * Delegate fan mode mapping to pymelcloud * Fix type annotation * Access AtaDevice through self._device * Prefer list comprehension * Update pymelcloud to leverage device type grouping The updated backend lib returns devices in a dict grouped by the device type. The devices do not necessarily need to be in a single list and this way isinstance is not required to extract devices by type. * Remove DOMAIN presence check This does not seem to make much sense after all. * Fix async_setup_entry Entry setup used half-baked naming from few experimentations back. The naming conventiens were unified to match the platforms. A redundant noneness check was also removed after evaluating the possible return values from the backend lib. * Simplify empty model name check * Improve config validation * Use config_validation strings. * Add CONF_EMAIL to config schema. The value is not strictly required when configuring through configuration.yaml, but having it there makes things more consistent. * Use dict[key] to access required properties. * Add DOMAIN in config check back to async_setup. This is required if an integration is configured throught config_flow. * Remove unused manifest properties * Remove redundant ClimateDevice property override * Add __init__.py to coverage exclusion * Use CONF_USERNAME instead of CONF_EMAIL * Use asyncio.gather instead of asyncio.wait * Misc fixes * any -> Any * Better names for dict iterations * Proper dict access with mandatory/known keys * Remove unused 'name' argument * Remove unnecessary platform info from unique_ids * Remove redundant methods from climate platform * Remove redundant default value from dict get * Update ConfigFlow sub-classing * Define sensors in a dict instead of a list * Use _abort_if_unique_id_configured to update token * Fix them tests * Remove current state guards * Fix that gather call * Implement sensor definitions without str manipulation * Use relative intra-package imports * Update homeassistant/components/melcloud/config_flow.py Co-Authored-By: Martin Hjelmare <marhje52@gmail.com> Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
161 lines
4.8 KiB
Python
161 lines
4.8 KiB
Python
"""The MELCloud Climate integration."""
|
|
import asyncio
|
|
from datetime import timedelta
|
|
import logging
|
|
from typing import Any, Dict, List
|
|
|
|
from aiohttp import ClientConnectionError
|
|
from async_timeout import timeout
|
|
from pymelcloud import Device, get_devices
|
|
import voluptuous as vol
|
|
|
|
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
|
|
from homeassistant.const import CONF_TOKEN, CONF_USERNAME
|
|
from homeassistant.exceptions import ConfigEntryNotReady
|
|
import homeassistant.helpers.config_validation as cv
|
|
from homeassistant.helpers.typing import HomeAssistantType
|
|
from homeassistant.util import Throttle
|
|
|
|
from .const import DOMAIN
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
|
|
|
|
PLATFORMS = ["climate", "sensor"]
|
|
|
|
CONF_LANGUAGE = "language"
|
|
CONFIG_SCHEMA = vol.Schema(
|
|
{
|
|
DOMAIN: vol.Schema(
|
|
{
|
|
vol.Required(CONF_USERNAME): cv.string,
|
|
vol.Required(CONF_TOKEN): cv.string,
|
|
}
|
|
)
|
|
},
|
|
extra=vol.ALLOW_EXTRA,
|
|
)
|
|
|
|
|
|
async def async_setup(hass: HomeAssistantType, config: ConfigEntry):
|
|
"""Establish connection with MELCloud."""
|
|
if DOMAIN not in config:
|
|
return True
|
|
|
|
username = config[DOMAIN][CONF_USERNAME]
|
|
token = config[DOMAIN][CONF_TOKEN]
|
|
hass.async_create_task(
|
|
hass.config_entries.flow.async_init(
|
|
DOMAIN,
|
|
context={"source": SOURCE_IMPORT},
|
|
data={CONF_USERNAME: username, CONF_TOKEN: token},
|
|
)
|
|
)
|
|
return True
|
|
|
|
|
|
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry):
|
|
"""Establish connection with MELClooud."""
|
|
conf = entry.data
|
|
mel_devices = await mel_devices_setup(hass, conf[CONF_TOKEN])
|
|
hass.data.setdefault(DOMAIN, {}).update({entry.entry_id: mel_devices})
|
|
for platform in PLATFORMS:
|
|
hass.async_create_task(
|
|
hass.config_entries.async_forward_entry_setup(entry, platform)
|
|
)
|
|
return True
|
|
|
|
|
|
async def async_unload_entry(hass, config_entry):
|
|
"""Unload a config entry."""
|
|
await asyncio.gather(
|
|
*[
|
|
hass.config_entries.async_forward_entry_unload(config_entry, platform)
|
|
for platform in PLATFORMS
|
|
]
|
|
)
|
|
hass.data[DOMAIN].pop(config_entry.entry_id)
|
|
if not hass.data[DOMAIN]:
|
|
hass.data.pop(DOMAIN)
|
|
return True
|
|
|
|
|
|
class MelCloudDevice:
|
|
"""MELCloud Device instance."""
|
|
|
|
def __init__(self, device: Device):
|
|
"""Construct a device wrapper."""
|
|
self.device = device
|
|
self.name = device.name
|
|
self._available = True
|
|
|
|
@Throttle(MIN_TIME_BETWEEN_UPDATES)
|
|
async def async_update(self, **kwargs):
|
|
"""Pull the latest data from MELCloud."""
|
|
try:
|
|
await self.device.update()
|
|
self._available = True
|
|
except ClientConnectionError:
|
|
_LOGGER.warning("Connection failed for %s", self.name)
|
|
self._available = False
|
|
|
|
async def async_set(self, properties: Dict[str, Any]):
|
|
"""Write state changes to the MELCloud API."""
|
|
try:
|
|
await self.device.set(properties)
|
|
self._available = True
|
|
except ClientConnectionError:
|
|
_LOGGER.warning("Connection failed for %s", self.name)
|
|
self._available = False
|
|
|
|
@property
|
|
def available(self) -> bool:
|
|
"""Return True if entity is available."""
|
|
return self._available
|
|
|
|
@property
|
|
def device_id(self):
|
|
"""Return device ID."""
|
|
return self.device.device_id
|
|
|
|
@property
|
|
def building_id(self):
|
|
"""Return building ID of the device."""
|
|
return self.device.building_id
|
|
|
|
@property
|
|
def device_info(self):
|
|
"""Return a device description for device registry."""
|
|
_device_info = {
|
|
"identifiers": {(DOMAIN, f"{self.device.mac}-{self.device.serial}")},
|
|
"manufacturer": "Mitsubishi Electric",
|
|
"name": self.name,
|
|
}
|
|
unit_infos = self.device.units
|
|
if unit_infos is not None:
|
|
_device_info["model"] = ", ".join(
|
|
[x["model"] for x in unit_infos if x["model"]]
|
|
)
|
|
return _device_info
|
|
|
|
|
|
async def mel_devices_setup(hass, token) -> List[MelCloudDevice]:
|
|
"""Query connected devices from MELCloud."""
|
|
session = hass.helpers.aiohttp_client.async_get_clientsession()
|
|
try:
|
|
with timeout(10):
|
|
all_devices = await get_devices(
|
|
token,
|
|
session,
|
|
conf_update_interval=timedelta(minutes=5),
|
|
device_set_debounce=timedelta(seconds=1),
|
|
)
|
|
except (asyncio.TimeoutError, ClientConnectionError) as ex:
|
|
raise ConfigEntryNotReady() from ex
|
|
|
|
wrapped_devices = {}
|
|
for device_type, devices in all_devices.items():
|
|
wrapped_devices[device_type] = [MelCloudDevice(device) for device in devices]
|
|
return wrapped_devices
|