-
-
Notifications
You must be signed in to change notification settings - Fork 37.7k
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
Add Compensation Integration #41675
Changes from 24 commits
b926866
102aa71
1bcf661
8066f5f
595d051
30a9550
65da993
2795e7d
40e2cdb
60c17b6
81ad51e
0300304
82e9ee6
65064bc
8156fee
2f1b689
bb57140
182eb81
98b4eac
c295d2e
b666a78
2f8d8c2
ad79693
aaee774
5c1e684
f0f03c0
8575436
713ede8
8ba6559
a83dd13
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| """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_ENTITY_ID, | ||
| CONF_NAME, | ||
| 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_NAME, | ||
| 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_ENTITY_ID): cv.entity_id, | ||
| vol.Required(CONF_DATAPOINTS): [ | ||
| vol.ExactSequence([vol.Coerce(float), vol.Coerce(float)]) | ||
| ], | ||
| vol.Optional(CONF_NAME, default=DEFAULT_NAME): 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, | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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.
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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(), | ||
| ) | ||
|
Petro31 marked this conversation as resolved.
|
||
|
|
||
| if coefficients is not None: | ||
|
Petro31 marked this conversation as 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.
|
||
|
|
||
| hass.async_create_task( | ||
| async_load_platform( | ||
| hass, | ||
| SENSOR_DOMAIN, | ||
| DOMAIN, | ||
| {CONF_COMPENSATION: compensation}, | ||
| config, | ||
| ) | ||
| ) | ||
|
|
||
| return True | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| """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_NAME = "Compensation" | ||
| DEFAULT_DEGREE = 1 | ||
| DEFAULT_PRECISION = 2 | ||
|
|
||
| MATCH_DATAPOINT = r"([-+]?[0-9]+\.?[0-9]*){1} -> ([-+]?[0-9]+\.?[0-9]*){1}" | ||
|
Petro31 marked this conversation as resolved.
Outdated
|
||
| 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.19.2"], | ||
| "codeowners": ["@Petro31"] | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| """Support for compensation sensor.""" | ||
| import logging | ||
|
|
||
| from homeassistant.const import ( | ||
| ATTR_ENTITY_ID, | ||
| ATTR_UNIT_OF_MEASUREMENT, | ||
| CONF_ATTRIBUTE, | ||
| CONF_ENTITY_ID, | ||
| CONF_NAME, | ||
| CONF_UNIT_OF_MEASUREMENT, | ||
| STATE_UNKNOWN, | ||
| ) | ||
| from homeassistant.core import callback | ||
| from homeassistant.helpers.entity import Entity | ||
| from homeassistant.helpers.event import async_track_state_change_event | ||
|
|
||
| from .const import CONF_COMPENSATION, CONF_POLYNOMIAL, CONF_PRECISION, DATA_COMPENSATION | ||
|
|
||
| _LOGGER = logging.getLogger(__name__) | ||
|
|
||
| ATTR_ATTRIBUTE = "attribute" | ||
| ATTR_COEFFICIENTS = "coefficients" | ||
|
|
||
|
|
||
| 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.get(CONF_COMPENSATION) | ||
|
Petro31 marked this conversation as resolved.
Outdated
|
||
| conf = hass.data[DATA_COMPENSATION][compensation] | ||
|
|
||
| async_add_entities( | ||
| [ | ||
| CompensationSensor( | ||
| hass, | ||
| conf[CONF_ENTITY_ID], | ||
| conf.get(CONF_NAME), | ||
| conf.get(CONF_ATTRIBUTE), | ||
| conf[CONF_PRECISION], | ||
| conf[CONF_POLYNOMIAL], | ||
| conf.get(CONF_UNIT_OF_MEASUREMENT), | ||
| ) | ||
| ] | ||
| ) | ||
|
|
||
|
|
||
| class CompensationSensor(Entity): | ||
|
Petro31 marked this conversation as resolved.
Outdated
MartinHjelmare marked this conversation as resolved.
Outdated
|
||
| """Representation of a Compensation sensor.""" | ||
|
|
||
| def __init__( | ||
| self, | ||
| hass, | ||
|
Petro31 marked this conversation as resolved.
Outdated
|
||
| entity_id, | ||
| name, | ||
| attribute, | ||
| precision, | ||
| polynomial, | ||
| unit_of_measurement, | ||
| ): | ||
| """Initialize the Compensation sensor.""" | ||
| self._entity_id = entity_id | ||
|
Petro31 marked this conversation as resolved.
Outdated
|
||
| self._name = name | ||
| self._precision = precision | ||
| self._attribute = attribute | ||
| self._unit_of_measurement = unit_of_measurement | ||
| self._poly = polynomial | ||
| self._coefficients = polynomial.coefficients.tolist() | ||
| self._state = STATE_UNKNOWN | ||
|
Petro31 marked this conversation as resolved.
Outdated
|
||
|
|
||
| async def async_added_to_hass(self): | ||
| """Handle added to Hass.""" | ||
| self.async_on_remove( | ||
| async_track_state_change_event( | ||
| self.hass, | ||
| [self._entity_id], | ||
| self._async_compensation_sensor_state_listener, | ||
| ) | ||
| ) | ||
|
|
||
| @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 device_state_attributes(self): | ||
|
Petro31 marked this conversation as resolved.
Outdated
Petro31 marked this conversation as resolved.
Outdated
|
||
| """Return the state attributes of the sensor.""" | ||
| ret = { | ||
| ATTR_ENTITY_ID: self._entity_id, | ||
|
MartinHjelmare marked this conversation as resolved.
Outdated
|
||
| ATTR_COEFFICIENTS: self._coefficients, | ||
| } | ||
| if self._attribute: | ||
| ret[ATTR_ATTRIBUTE] = self._attribute | ||
|
Petro31 marked this conversation as resolved.
Outdated
|
||
| 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._attribute is None: | ||
| self._unit_of_measurement = new_state.attributes.get( | ||
| ATTR_UNIT_OF_MEASUREMENT | ||
| ) | ||
|
|
||
| try: | ||
| if self._attribute: | ||
| value = float(new_state.attributes.get(self._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 = STATE_UNKNOWN | ||
|
Petro31 marked this conversation as resolved.
Outdated
|
||
| if self._attribute: | ||
| _LOGGER.warning( | ||
| "%s attribute %s is not numerical", | ||
| self._entity_id, | ||
| self._attribute, | ||
| ) | ||
| else: | ||
| _LOGGER.warning("%s state is not numerical", self._entity_id) | ||
|
|
||
| self.async_write_ha_state() | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| """Tests for the compensation component.""" |
Uh oh!
There was an error while loading. Please reload this page.