示例#1
0
def bind_entities_to_devices(hass: HomeAssistantType, entities,
                             device_id: str):
    """Attach all the power/energy sensors to the same device as the source entity"""

    if AwesomeVersion(HA_VERSION) < AwesomeVersion("2022.2"):
        return

    for entity in entities:
        ent_reg = entity_registry.async_get(hass)
        entity_entry = ent_reg.async_get(entity.entity_id)
        if (not entity_entry or entity_entry.platform != DOMAIN
                or entity_entry.device_id == device_id):
            continue

        _LOGGER.debug(f"Binding {entity.entity_id} to device {device_id}")
        ent_reg.async_update_entity(entity.entity_id, device_id=device_id)
示例#2
0
def create_github_release(version: str, gh_repo: Repository) -> None:
    """Create new release on Github."""
    print("Creating release...")
    gh_repo.create_git_release(
        tag=version,
        name=version,
        target_commitish="main",
        message=f"Generated for `homeassitant {version}`.",
        prerelease=AwesomeVersion(version).modifier is not None,
    )
示例#3
0
    def __init__(
        self,
        power_calculator: PowerCalculationStrategyInterface,
        calculation_mode: str,
        entity_id: str,
        entity_category: str,
        name: str,
        source_entity: str,
        source_domain: str,
        unique_id: str,
        standby_power: float | None,
        scan_interval,
        multiply_factor: float | None,
        multiply_factor_standby: bool,
        ignore_unavailable_state: bool,
        rounding_digits: int,
    ):
        """Initialize the sensor."""
        self._power_calculator = power_calculator
        self._calculation_mode = calculation_mode
        self._source_entity = source_entity
        self._source_domain = source_domain
        self._name = name
        self._power = None
        self._standby_power = standby_power
        self._attr_force_update = True
        self._attr_unique_id = unique_id
        self._scan_interval = scan_interval
        self._multiply_factor = multiply_factor
        self._multiply_factor_standby = multiply_factor_standby
        self._ignore_unavailable_state = ignore_unavailable_state
        self._rounding_digits = rounding_digits
        self.entity_id = entity_id
        if entity_category:
            if AwesomeVersion(HA_VERSION) >= AwesomeVersion("2021.11"):
                from homeassistant.helpers.entity import EntityCategory

                self._attr_entity_category = EntityCategory(entity_category)
示例#4
0
def get_available_versions(git_root: Path) -> list[str]:
    """Get list of available versions from git tags."""
    print(f"Getting list of available versions in {git_root}...")
    subprocess.run(["git", "fetch", "origin"], cwd=git_root, check=True)
    result = subprocess.run(
        ["git", "tag"],
        cwd=git_root,
        check=True,
        capture_output=True,
        text=True,
    )
    versions = [AwesomeVersion(tag) for tag in result.stdout.split()]
    versions = sorted([
        version for version in versions
        if version.strategy == AwesomeVersionStrategy.CALVER
        and version >= FIRST_SUPPORTED_VERSION
    ])
    for version in versions:
        print(f"Available version: {version.string}")
    return [version.string for version in versions]
示例#5
0
#!/usr/bin/env python3
"""Fetch the latest homeassistant tag and generate typing stubs for it."""
from __future__ import annotations

import os
import shutil
import subprocess
import sys
from pathlib import Path

from awesomeversion.awesomeversion import AwesomeVersion
from awesomeversion.strategy import AwesomeVersionStrategy
from github import Github
from github.Repository import Repository

FIRST_SUPPORTED_VERSION = AwesomeVersion("2021.4.0b3")
BLACKLISTED_VERSIONS = [
    "2021.10.0b8",  # doesn't exist on PyPI
]


def main() -> int:
    """Run main function."""
    repo_root = Path(os.path.dirname(os.path.realpath(__file__)))
    homeassistant_root = repo_root / "homeassistant_core"

    # Find which versions are missing
    current_versions = set(get_available_versions(repo_root))
    homeassistant_versions = get_available_versions(homeassistant_root)
    missing_versions = [
        version for version in homeassistant_versions if
async def create_utility_meters(
    hass: HomeAssistantType,
    energy_sensor: EnergySensor,
    sensor_config: dict,
) -> list[UtilityMeterSensor]:
    """Create the utility meters"""
    utility_meters = []

    if not sensor_config.get(CONF_CREATE_UTILITY_METERS):
        return []

    if not DATA_UTILITY in hass.data:
        hass.data[DATA_UTILITY] = {}

    tariffs = sensor_config.get(CONF_UTILITY_METER_TARIFFS)
    meter_types = sensor_config.get(CONF_UTILITY_METER_TYPES)
    for meter_type in meter_types:
        tariff_sensors = []

        name = f"{energy_sensor.name} {meter_type}"
        entity_id = f"{energy_sensor.entity_id}_{meter_type}"
        unique_id = None
        if energy_sensor.unique_id:
            unique_id = f"{energy_sensor.unique_id}_{meter_type}"

        if tariffs:
            # create tariff selection entity
            _LOGGER.debug(f"Creating utility_meter tariff select: {name}")
            utility_meter_component = cast(
                EntityComponent,
                hass.data["entity_components"].get(UTILITY_DOMAIN))

            if AwesomeVersion(HA_VERSION) >= AwesomeVersion("2022.4.0.dev0"):
                select_component = cast(
                    EntityComponent,
                    hass.data["entity_components"].get(SELECT_DOMAIN))
                tariff_select = TariffSelect(
                    name, list(tariffs),
                    utility_meter_component.async_add_entities)
                await select_component.async_add_entities([tariff_select])
            else:
                tariff_select = TariffSelect(name, list(tariffs))
                await utility_meter_component.async_add_entities(
                    [tariff_select])

            for tariff in tariffs:
                utility_meter = await create_utility_meter(
                    hass,
                    energy_sensor.entity_id,
                    entity_id,
                    name,
                    sensor_config,
                    meter_type,
                    unique_id,
                    tariff,
                    tariff_select.entity_id,
                )
                tariff_sensors.append(utility_meter)
                utility_meters.append(utility_meter)

        else:
            utility_meter = await create_utility_meter(
                hass,
                energy_sensor.entity_id,
                entity_id,
                name,
                sensor_config,
                meter_type,
                unique_id,
            )
            tariff_sensors.append(utility_meter)
            utility_meters.append(utility_meter)

        hass.data[DATA_UTILITY][entity_id] = {
            DATA_TARIFF_SENSORS: tariff_sensors
        }

    return utility_meters
from __future__ import annotations

import inspect
import logging
from typing import cast

from awesomeversion.awesomeversion import AwesomeVersion
from homeassistant.const import __version__ as HA_VERSION

if AwesomeVersion(HA_VERSION) >= AwesomeVersion("2022.4.0.dev0"):
    from homeassistant.components.select import DOMAIN as SELECT_DOMAIN
    from homeassistant.components.utility_meter.select import TariffSelect
else:
    from homeassistant.components.utility_meter import TariffSelect

from homeassistant.components.utility_meter.const import (
    DATA_TARIFF_SENSORS,
    DATA_UTILITY,
)
from homeassistant.components.utility_meter.const import DOMAIN as UTILITY_DOMAIN
from homeassistant.components.utility_meter.sensor import UtilityMeterSensor
from homeassistant.const import __short_version__
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.typing import HomeAssistantType

from custom_components.powercalc.const import (
    CONF_CREATE_UTILITY_METERS,
    CONF_ENERGY_SENSOR_PRECISION,
    CONF_UTILITY_METER_OFFSET,
    CONF_UTILITY_METER_TARIFFS,
    CONF_UTILITY_METER_TYPES,