core icon indicating copy to clipboard operation
core copied to clipboard

Add ambient temperature and humidity status sensors to NUT

Open tdfountain opened this issue 1 year ago • 6 comments

Proposed change

Add ambient temperature and humidity status sensors. PDUs and select UPSs monitor the status of ambient environmental and report status relative to pre-defined ranges. This status information is communicated with NUT using ambient.humidity.status and ambient.temperature.status. These sensors are useful for signaling a warning or critical event to an environmental condition. This information is Diagnostic in nature since it is not the primary purpose of a PDU or UPS.

Implementation uses translation keys with both strings.json and icons.json.

Type of change

  • [ ] Dependency upgrade
  • [ ] Bugfix (non-breaking change which fixes an issue)
  • [ ] New integration (thank you!)
  • [x] New feature (which adds functionality to an existing integration)
  • [ ] Deprecation (breaking change to happen in the future)
  • [ ] Breaking change (fix/feature causing existing functionality to break)
  • [ ] Code quality improvements to existing code or addition of tests

Additional information

  • This PR fixes or closes issue: fixes #
  • This PR is related to issue:
  • Link to documentation pull request:

Checklist

  • [x] The code change is tested and works locally.
  • [x] Local tests pass. Your PR cannot be merged unless tests pass
  • [x] There is no commented out code in this PR.
  • [x] I have followed the development checklist
  • [x] I have followed the perfect PR recommendations
  • [x] The code has been formatted using Ruff (ruff format homeassistant tests)
  • [ ] Tests have been added to verify that the new code works.

If user exposed functionality or configuration variables are added/changed:

If the code communicates with devices, web services, or third-party tools:

  • [ ] The manifest file has all fields filled out correctly.
    Updated and included derived files by running: python3 -m script.hassfest.
  • [ ] New or updated dependencies have been added to requirements_all.txt.
    Updated by running python3 -m script.gen_requirements_all.
  • [ ] For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description.

To help with the load of incoming pull requests:

tdfountain avatar Aug 18 '24 20:08 tdfountain

Hey there @bdraco, @ollo69, @pestevez, mind taking a look at this pull request as it has been labeled with an integration (nut) you are listed as a code owner for? Thanks!

Code owner commands

Code owners of nut can trigger bot actions by commenting:

  • @home-assistant close Closes the pull request.
  • @home-assistant rename Awesome new title Renames the pull request.
  • @home-assistant reopen Reopen the pull request.
  • @home-assistant unassign nut Removes the current integration label and assignees on the pull request, add the integration domain after the command.
  • @home-assistant add-label needs-more-information Add a label (needs-more-information, problem in dependency, problem in custom component) to the pull request.
  • @home-assistant remove-label needs-more-information Remove a label (needs-more-information, problem in dependency, problem in custom component) on the pull request.

home-assistant[bot] avatar Aug 18 '24 20:08 home-assistant[bot]

Please take a look at the requested changes, and use the Ready for review button when you are done, thanks :+1:

Learn more about our pull request process.

home-assistant[bot] avatar Aug 18 '24 21:08 home-assistant[bot]

Thanks for reviewing. I believe it is a text field returned by NUT.

At least for Eaton devices, these are mapped to MIB entries that track threshold statuses. The two relevant thresholds status are reported as integer values humidityThStatus and temperatureThStatus . The corresponding MIB entry is:

humidityThStatus  OBJECT-TYPE
        SYNTAX     INTEGER {
                good (0),
                lowWarning (1),
                lowCritical (2),
                highWarning (3),
                highCritical (4)
        }
        MAX-ACCESS read-only
        STATUS     current
        DESCRIPTION 
                "Status of the measured humidity relative to the configured
                      thresholds."

and

temperatureThStatus  OBJECT-TYPE
        SYNTAX     INTEGER {
                good (0),
                lowWarning (1),
                lowCritical (2),
                highWarning (3),
                highCritical (4)
        }
        MAX-ACCESS read-only
        STATUS     current
        DESCRIPTION 
                "Status of the measured temperature relative to the configured
                      thresholds."

The NUT drivers I reviewed all map these to "good", "warning-low", "critical-low", "warning-high", and "critical-high". It is possible some other NUT drivers map to different text strings but those are the ones I could find in the NUT source code.

The PDUs I have return "good" in a normal operational state.

tdfountain avatar Aug 18 '24 21:08 tdfountain

Please let me know if any additional information or changes are required. I have a number of other NUT improvements that I would like to commit but cannot until these are resolved. Thanks!

tdfountain avatar Sep 16 '24 20:09 tdfountain

@tdfountain if it is now ready, please make the PR as ready for review.

Thanks!

davet2001 avatar Oct 06 '24 21:10 davet2001

@tdfountain Please can you increase the test coverage to enable the checks to pass?

davet2001 avatar Oct 07 '24 19:10 davet2001

Added two pytest cases not related to this PR to improve code coverage and bring NUT component code coverage to 100%. Added pytest and fixture to test for temperature and humidity status sensors.

The pytest code coverage failure appears to be due to other components. Please let me know if I now need to go learn another component to be able to submit this PR.

tdfountain avatar Nov 03 '24 19:11 tdfountain

Thank you for your contribution thus far! 🎖 Since this is a significant contribution, we would appreciate you'd added yourself to the list of code owners for this integration. ❤️

Please, add your GitHub username to the manifest.json of this integration.

For more information about "code owners", see: Architecture Decision Record 0008: Code owners.

bdraco avatar Nov 03 '24 19:11 bdraco

diff --git a/homeassistant/components/nut/sensor.py b/homeassistant/components/nut/sensor.py
index 2bdfcdab5b4..e212cdf1ad3 100644
--- a/homeassistant/components/nut/sensor.py
+++ b/homeassistant/components/nut/sensor.py
@@ -6,7 +6,7 @@ from collections.abc import Callable
 from dataclasses import asdict, dataclass
 import logging
 from typing import Final, cast
-
+from operator import methodcaller
 from homeassistant.components.sensor import (
     SensorDeviceClass,
     SensorEntity,
@@ -951,7 +951,7 @@ SENSOR_TYPES: Final[dict[str, NutSensorEntityDescription]] = {
         translation_key="ambient_humidity_status",
         device_class=SensorDeviceClass.ENUM,
         options=AMBIENT_THRESHOLD_STATUS_OPTIONS,
-        ambient_threshold_value_fn=lambda x: x.lower() if isinstance(x, str) else None,
+        ambient_threshold_value_fn=methodcaller("lower"),
         entity_category=EntityCategory.DIAGNOSTIC,
     ),
     "ambient.temperature": NutSensorEntityDescription(
@@ -967,7 +967,7 @@ SENSOR_TYPES: Final[dict[str, NutSensorEntityDescription]] = {
         translation_key="ambient_temperature_status",
         device_class=SensorDeviceClass.ENUM,
         options=AMBIENT_THRESHOLD_STATUS_OPTIONS,
-        ambient_threshold_value_fn=lambda x: x.lower() if isinstance(x, str) else None,
+        ambient_threshold_value_fn=methodcaller("lower"),
         entity_category=EntityCategory.DIAGNOSTIC,
     ),
     "watts": NutSensorEntityDescription(

But you also need a new entity type that calls the callable.

bdraco avatar Nov 03 '24 23:11 bdraco

My apologies but I need a bit more help on this construct. I originally made those changes but struggled with the new entity type. I revised the NutSensorEntityDescription class to define the following:

ambient_threshold_value_fn: Callable[[NutAmbientThresholdSensor], StateType]

and I tried creating a new entity:

@dataclass
class NutAmbientThresholdSensor(SensorEntityDescription):
    """Describes Nut ambient threshold sensor state."""
    def __init__(self, string: str) -> None:
        """Initialize the sensor."""
        self._string = string

    @property
    def native_value(self) -> str | None:
        """Get the current value."""
        return _string

The above unfortunately generates an error: "TypeError: non-default argument 'ambient_threshold_value_fn' follows default argument". I have tried a number of other variants without success. I was trying to mimic the powerwall component's MeterResponse but I am clearly missing something. Thank you for any additional direction.

tdfountain avatar Nov 04 '24 01:11 tdfountain

My apologies but I need a bit more help on this construct. I originally made those changes but struggled with the new entity type.

A custom __init__ in a dataclass is probably not what you want. Please message me, @emontnemery, on Discord and let's try to work this out 👍

emontnemery avatar Nov 12 '24 07:11 emontnemery

The state string returned by NUT is always lowercase (the options are provided). I therefore believe we do not need either a lambda function or a methodcaller.

tdfountain avatar Jan 20 '25 20:01 tdfountain

Just had a look through again - from my side all ok but I am not familiar with methodcaller etc so can't really comment on that.

Thanks @tdfountain!

Edit - minor comment: Possibly the custom class NutSensorEntityDescription is no longer necessary. But I don't see this as a showstopper.

davet2001 avatar Jan 23 '25 12:01 davet2001

Thanks @tdfountain

bdraco avatar Feb 24 '25 05:02 bdraco

Wonderful @bdraco. Please let me know if there is anything else required to complete the merge. It may need force.

tdfountain avatar Feb 24 '25 14:02 tdfountain