-
-
Notifications
You must be signed in to change notification settings - Fork 33.8k
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
MartinHjelmare
merged 30 commits into
home-assistant:dev
from
Petro31:add-compensation-int-no-config-flow
Apr 3, 2021
Merged
Add Compensation Integration #41675
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 102aa71
Merge remote-tracking branch 'home-assistant/dev' into add-compensati…
Petro31 1bcf661
Add Compensation Integration
Petro31 8066f5f
Add Requirements
Petro31 595d051
Fix for tests
Petro31 30a9550
Fix isort
Petro31 65da993
Handle ADR-0007
Petro31 2795e7d
fix flake8
Petro31 40e2cdb
Added Error Trapping
Petro31 60c17b6
fix flake8 & pylint
Petro31 81ad51e
fix isort.... again
Petro31 0300304
fix tests & comments
Petro31 82e9ee6
fix flake8
Petro31 65064bc
remove discovery message
Petro31 8156fee
Merge branch 'dev' into add-compensation-int-no-config-flow
Petro31 2f1b689
Merge remote-tracking branch 'home-assistant/dev' into add-compensati…
Petro31 bb57140
Fixed Review changes
Petro31 182eb81
Roll back numpy requirement
Petro31 98b4eac
Fix flake8
Petro31 c295d2e
Merge remote-tracking branch 'home-assistant/dev' into add-compensati…
Petro31 b666a78
Fix requested changes
Petro31 2f8d8c2
Merge remote-tracking branch 'home-assistant/dev' into add-compensati…
Petro31 ad79693
Fix doc strings and continue
Petro31 aaee774
Remove periods from logger
Petro31 5c1e684
Merge remote-tracking branch 'home-assistant/dev' into add-compensati…
Petro31 f0f03c0
Merge remote-tracking branch 'home-assistant/dev' into add-compensati…
Petro31 8575436
Fixes
Petro31 713ede8
Merge remote-tracking branch 'home-assistant/dev' into add-compensati…
Petro31 8ba6559
Add name and fix unique_id
Petro31 a83dd13
removed conf name and auto construct it
Petro31 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
} | ||
) | ||
|
||
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(), | ||
) | ||
Petro31 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
if coefficients is not None: | ||
Petro31 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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 | ||
Petro31 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
hass.async_create_task( | ||
async_load_platform( | ||
hass, | ||
SENSOR_DOMAIN, | ||
DOMAIN, | ||
{CONF_COMPENSATION: compensation}, | ||
config, | ||
) | ||
) | ||
|
||
return True |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"] | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
< 46B9 /td> | @@ -0,0 +1 @@ | |
"""Tests for the compensation component.""" |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
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.