8000 Add Compensation Integration by Petro31 · Pull Request #41675 · home-assistant/core · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Add Compensation Integration #41675

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
b926866
Merge branch 'dev' into add-compensation-int-no-config-flow
Petro31 Oct 5, 2020
102aa71
Merge remote-tracking branch 'home-assistant/dev' into add-compensati…
Petro31 Oct 11, 2020
1bcf661
Add Compensation Integration
Petro31 Oct 11, 2020
8066f5f
Add Requirements
Petro31 Oct 11, 2020
595d051
Fix for tests
Petro31 Oct 11, 2020
30a9550
Fix isort
Petro31 Oct 11, 2020
65da993
Handle ADR-0007
Petro31 Oct 13, 2020
2795e7d
fix flake8
Petro31 Oct 13, 2020
40e2cdb
Added Error Trapping
Petro31 Oct 14, 2020
60c17b6
fix flake8 & pylint
Petro31 Oct 14, 2020
81ad51e
fix isort.... again
Petro31 Oct 14, 2020
0300304
fix tests & comments
Petro31 Oct 15, 2020
82e9ee6
fix flake8
Petro31 Oct 15, 2020
65064bc
remove discovery message
Petro31 Oct 15, 2020
8156fee
Merge branch 'dev' into add-compensation-int-no-config-flow
Petro31 Feb 23, 2021
2f1b689
Merge remote-tracking branch 'home-assistant/dev' into add-compensati…
Petro31 Feb 27, 2021
bb57140
Fixed Review changes
Petro31 Feb 27, 2021
182eb81
Roll back numpy requirement
Petro31 Feb 27, 2021
98b4eac
Fix flake8
Petro31 Feb 27, 2021
c295d2e
Merge remote-tracking branch 'home-assistant/dev' into add-compensati…
Petro31 Mar 14, 2021
b666a78
Fix requested changes
Petro31 Mar 14, 2021
2f8d8c2
Merge remote-tracking branch 'home-assistant/dev' into add-compensati…
Petro31 Mar 20, 2021
ad79693
Fix doc strings and continue
Petro31 Mar 20, 2021
aaee774
Remove periods from logger
Petro31 Mar 20, 2021
5c1e684
Merge remote-tracking branch 'home-assistant/dev' into add-compensati…
Petro31 Apr 1, 2021
f0f03c0
Merge remote-tracking branch 'home-assistant/dev' into add-compensati…
Petro31 Apr 2, 2021
8575436
Fixes
Petro31 Apr 2, 2021
713ede8
Merge remote-tracking branch 'home-assistant/dev' into add-compensati…
Petro31 Apr 2, 2021
8ba6559
Add name and fix unique_id
Petro31 Apr 2, 2021
a83dd13
removed conf name and auto construct it
Petro31 Apr 3, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ homeassistant/components/cloud/* @home-assistant/cloud
homeassistant/components/cloudflare/* @ludeeus @ctalkington
homeassistant/components/color_extractor/* @GenericStudent
homeassistant/components/comfoconnect/* @michaelarnauts
homeassistant/components/compensation/* @Petro31
homeassistant/components/config/* @home-assistant/core
homeassistant/components/configurator/* @home-assistant/core
homeassistant/components/control4/* @lawtancool
Expand Down
120 changes: 120 additions & 0 deletions homeassistant/components/compensation/__init__.py
{
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
"""The Compensation integration."""
import logging
import warnings

import numpy as np
import voluptuous as vol

from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.const import (
CONF_ATTRIBUTE,
CONF_SOURCE,
CONF_UNIQUE_ID,
CONF_UNIT_OF_MEASUREMENT,
)
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.discovery import async_load_platform

from .const import (
CONF_COMPENSATION,
CONF_DATAPOINTS,
CONF_DEGREE,
CONF_POLYNOMIAL,
CONF_PRECISION,
DATA_COMPENSATION,
DEFAULT_DEGREE,
DEFAULT_PRECISION,
DOMAIN,
)

_LOGGER = logging.getLogger(__name__)


def datapoints_greater_than_degree(value: dict) -> dict:
"""Validate data point list is greater than polynomial degrees."""
if len(value[CONF_DATAPOINTS]) <= value[CONF_DEGREE]:
raise vol.Invalid(
f"{CONF_DATAPOINTS} must have at least {value[CONF_DEGREE]+1} {CONF_DATAPOINTS}"
)

return value


COMPENSATION_SCHEMA = vol.Schema(
vol.Required(CONF_SOURCE): cv.entity_id,
vol.Required(CONF_DATAPOINTS): [
vol.ExactSequence([vol.Coerce(float), vol.Coerce(float)])
],
vol.Optional(CONF_UNIQUE_ID): cv.string,
vol.Optional(CONF_ATTRIBUTE): cv.string,
vol.Optional(CONF_PRECISION, default=DEFAULT_PRECISION): cv.positive_int,
vol.Optional(CONF_DEGREE, default=DEFAULT_DEGREE): vol.All(
vol.Coerce(int),
vol.Range(min=1, max=7),
),
vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string,
Copy link
Member
@frenck frenck Mar 31, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should these properties be inherited from the entity ID passed in? for example, the unit of measurement?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It depends on the input units and the output units. I was on the fence about that. I can add it but it should be overridable.

8000 Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why? It compensates for a value, that doesn't change the unit, right?

Copy link
Contributor Author
@Petro31 Petro31 Mar 31, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That would be like 80% of the cases. But we should consider voltage -> random unit conversions. Also, I currently use it for volume, basically unitless to dB.

}
)

CONFIG_SCHEMA = vol.Schema(
{
DOMAIN: vol.Schema(
{cv.slug: vol.All(COMPENSATION_SCHEMA, datapoints_greater_than_degree)}
)
},
extra=vol.ALLOW_EXTRA,
)


async def async_setup(hass, config):
"""Set up the Compensation sensor."""
hass.data[DATA_COMPENSATION] = {}

for compensation, conf in config.get(DOMAIN).items():
_LOGGER.debug("Setup %s.%s", DOMAIN, compensation)

degree = conf[CONF_DEGREE]

# get x values and y values from the x,y point pairs
x_values, y_values = zip(*conf[CONF_DATAPOINTS])

# try to get valid coefficients for a polynomial
coefficients = None
with np.errstate(all="raise"):
with warnings.catch_warnings(record=True) as all_warnings:
warnings.simplefilter("always")
try:
coefficients = np.polyfit(x_values, y_values, degree)
except FloatingPointError as error:
_LOGGER.error(
"Setup of %s encountered an error, %s",
compensation,
error,
)
for warning in all_warnings:
_LOGGER.warning(
"Setup of %s encountered a warning, %s",
compensation,
str(warning.message).lower(),
)

if coefficients is not None:
data = {
k: v for k, v in conf.items() if k not in [CONF_DEGREE, CONF_DATAPOINTS]
}
data[CONF_POLYNOMIAL] = np.poly1d(coefficients)

hass.data[DATA_COMPENSATION][compensation] = data

hass.async_create_task(
async_load_platform(
hass,
SENSOR_DOMAIN,
DOMAIN,
{CONF_COMPENSATION: compensation},
config,
)
)

return True
16 changes: 16 additions & 0 deletions homeassistant/components/compensation/const.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""Compensation constants."""
DOMAIN = "compensation"

SENSOR = "compensation"

CONF_COMPENSATION = "compensation"
CONF_DATAPOINTS = "data_points"
CONF_DEGREE = "degree"
CONF_PRECISION = "precision"
CONF_POLYNOMIAL = "polynomial"

DATA_COMPENSATION = "compensation_data"

DEFAULT_DEGREE = 1
DEFAULT_NAME = "Compensation"
DEFAULT_PRECISION = 2
7 changes: 7 additions & 0 deletions homeassistant/components/compensation/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"domain": "compensation",
"name": "Compensation",
"documentation": "https://www.home-assistant.io/integrations/compensation",
"requirements": ["numpy==1.20.2"],
"codeowners": ["@Petro31"]
}
162 changes: 162 additions & 0 deletions homeassistant/components/compensation/sensor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
"""Support for compensation sensor."""
import logging

from homeassistant.components.sensor import SensorEntity
from homeassistant.const import (
ATTR_UNIT_OF_MEASUREMENT,
CONF_ATTRIBUTE,
CONF_SOURCE,
CONF_UNIQUE_ID,
CONF_UNIT_OF_MEASUREMENT,
STATE_UNKNOWN,
)
from homeassistant.core import callback
from homeassistant.helpers.event import async_track_state_change_event

from .const import (
CONF_COMPENSATION,
CONF_POLYNOMIAL,
CONF_PRECISION,
DATA_COMPENSATION,
DEFAULT_NAME,
)

_LOGGER = logging.getLogger(__name__)

ATTR_COEFFICIENTS = "coefficients"
ATTR_SOURCE = "source"
ATTR_SOURCE_ATTRIBUTE = "source_attribute"


async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Compensation sensor."""
if discovery_info is None:
return

compensation = discovery_info[CONF_COMPENSATION]
conf = hass.data[DATA_COMPENSATION][compensation]

source = conf[CONF_SOURCE]
attribute = conf.get(CONF_ATTRIBUTE)
name = f"{DEFAULT_NAME} {source}"
if attribute is not None:
name = f"{name} {attribute}"

async_add_entities(
[
CompensationSensor(
conf.get(CONF_UNIQUE_ID),
name,
source,
attribute,
conf[CONF_PRECISION],
conf[CONF_POLYNOMIAL],
conf.get(CONF_UNIT_OF_MEASUREMENT),
)
]
)


class CompensationSensor(SensorEntity):
"""Representation of a Compensation sensor."""

def __init__(
self,
unique_id,
name,
source,
attribute,
precision,
polynomial,
unit_of_measurement,
):
"""Initialize the Compensation sensor."""
self._source_entity_id = source
self._precision = precision
self._source_attribute = attribute
self._unit_of_measurement = unit_of_measurement
self._poly = polynomial
self._coefficients = polynomial.coefficients.tolist()
self._state = None
self._unique_id = unique_id
self._name = name

async def async_added_to_hass(self):
"""Handle added to Hass."""
self.async_on_remove(
async_track_state_change_event(
self.hass,
[self._source_entity_id],
self._async_compensation_sensor_state_listener,
)
)

@property
def unique_id(self):
"""Return the unique id of this sensor."""
return self._unique_id

@property
def name(self):
"""Return the name of the sensor."""
return self._name

@property
def should_poll(self):
"""No polling needed."""
return False

@property
def state(self):
"""Return the state of the sensor."""
return self._state

@property
def extra_state_attributes(self):
"""Return the state attributes of the sensor."""
ret = {
ATTR_SOURCE: self._source_entity_id,
ATTR_COEFFICIENTS: self._coefficients,
}
if self._source_attribute:
ret[ATTR_SOURCE_ATTRIBUTE] = self._source_attribute
return ret

@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._unit_of_measurement

@callback
def _async_compensation_sensor_state_listener(self, event):
"""Handle sensor state changes."""
new_state = event.data.get("new_state")
if new_state is None:
return

if self._unit_of_measurement is None and self._source_attribute is None:
self._unit_of_measurement = new_state.attributes.get(
ATTR_UNIT_OF_MEASUREMENT
)

try:
if self._source_attribute:
value = float(new_state.attributes.get(self._source_attribute))
else:
value = (
None if new_state.state == STATE_UNKNOWN else float(new_state.state)
)
self._state = round(self._poly(value), self._precision)

except (ValueError, TypeError):
self._state = None
if self._source_attribute:
_LOGGER.warning(
"%s attribute %s is not numerical",
self._source_entity_id,
self._source_attribute,
)
else:
_LOGGER.warning("%s state is not numerical", self._source_entity_id)

self.async_write_ha_state()
1 change: 1 addition & 0 deletions requirements_all.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1011,6 +1011,7 @@ nuheat==0.3.0
# homeassistant.components.numato
numato-gpio==0.10.0

# homeassistant.components.compensation
# homeassistant.components.iqvia
# homeassistant.components.opencv
# homeassistant.components.tensorflow
Expand Down
1 change: 1 addition & 0 deletions requirements_test_all.txt
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,7 @@ nuheat==0.3.0
# homeassistant.components.numato
numato-gpio==0.10.0

# homeassistant.components.compensation
# homeassistant.components.iqvia
# homeassistant.components.opencv
# homeassistant.components.tensorflow
Expand Down
1 change: 1 addition & 0 deletions tests/components/compensation/__init__.py
Original file line number Diff line number Diff line change
< 46B9 /td> @@ -0,0 +1 @@
"""Tests for the compensation component."""
Loading
0