Skip to content
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

Configuration Warning, Platform Error, Blocking Call - cannot import name 'TEMP_CELSIUS' from 'homeassistant.const' #14

Open
MankiniChykan opened this issue Jan 3, 2025 · 1 comment

Comments

@MankiniChykan
Copy link

MankiniChykan commented Jan 3, 2025

Core - 2025.1.0
Supervisor - 2024.12.3
Operating System - 14.1
Frontend - 20250103.0

Configuration warnings
Platform error 'sensor' from integration 'dewpoint' - cannot import name 'TEMP_CELSIUS' from 'homeassistant.const' (/usr/src/homeassistant/homeassistant/const.py)

Logger: homeassistant.config
Source: config.py:1055
First occurred: 13:01:08 (1 occurrences)
Last logged: 13:01:08

Platform error: sensor - cannot import name 'TEMP_CELSIUS' from 'homeassistant.const' (/usr/src/homeassistant/homeassistant/const.py)
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/config.py", line 1055, in _async_load_and_validate_platform_integration
platform = await p_integration.integration.async_get_platform(domain)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/src/homeassistant/homeassistant/loader.py", line 1108, in async_get_platform
platforms = await self.async_get_platforms((platform_name,))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/src/homeassistant/homeassistant/loader.py", line 1185, in async_get_platforms
import_future.result()
~~~~~~~~~~~~~~~~~~~~^^
File "/usr/src/homeassistant/homeassistant/loader.py", line 1173, in async_get_platforms
platforms.update(self._load_platforms(platform_names))
~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^
File "/usr/src/homeassistant/homeassistant/loader.py", line 1098, in _load_platforms
platform_name: self._load_platform(platform_name)
~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^
File "/usr/src/homeassistant/homeassistant/loader.py", line 1272, in _load_platform
cache[full_name] = self._import_platform(platform_name)
~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^
File "/usr/src/homeassistant/homeassistant/loader.py", line 1304, in _import_platform
return importlib.import_module(f"{self.pkg_path}.{platform_name}")
~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/src/homeassistant/homeassistant/util/loop.py", line 200, in protected_loop_func
return func(*args, **kwargs)
File "/usr/local/lib/python3.13/importlib/init.py", line 88, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "", line 1387, in _gcd_import
File "", line 1360, in _find_and_load
File "", line 1331, in _find_and_load_unlocked
File "", line 935, in _load_unlocked
File "", line 1026, in exec_module
File "", line 488, in _call_with_frames_removed
File "/config/custom_components/dewpoint/sensor.py", line 16, in
from homeassistant.const import (
TEMP_CELSIUS, TEMP_FAHRENHEIT, ATTR_FRIENDLY_NAME, ATTR_ENTITY_ID, CONF_SENSORS,
EVENT_HOMEASSISTANT_START, ATTR_UNIT_OF_MEASUREMENT, ATTR_TEMPERATURE)
ImportError: cannot import name 'TEMP_CELSIUS' from 'homeassistant.const' (/usr/src/homeassistant/homeassistant/const.py)

Logger: homeassistant.util.loop
Source: util/loop.py:77
First occurred: 13:01:08 (1 occurrences)
Last logged: 13:01:08

Detected blocking call to import_module with args ('custom_components.dewpoint.sensor',) in /usr/src/homeassistant/homeassistant/loader.py, line 1304: return importlib.import_module(f"{self.pkg_path}.{platform_name}") inside the event loop; This is causing stability issues. Please create a bug report at https://github.com/home-assistant/core/issues?q=is%3Aopen+is%3Aissue For developers, please see https://developers.home-assistant.io/docs/asyncio_blocking_operations/#import_module Traceback (most recent call last): File "", line 198, in _run_module_as_main File "", line 88, in _run_code File "/usr/src/homeassistant/homeassistant/main.py", line 227, in sys.exit(main()) File "/usr/src/homeassistant/homeassistant/main.py", line 213, in main exit_code = runner.run(runtime_conf) File "/usr/src/homeassistant/homeassistant/runner.py", line 154, in run return loop.run_until_complete(setup_and_run_hass(runtime_config)) File "/usr/local/lib/python3.13/asyncio/base_events.py", line 707, in run_until_complete self.run_forever() File "/usr/local/lib/python3.13/asyncio/base_events.py", line 678, in run_forever self._run_once() File "/usr/local/lib/python3.13/asyncio/base_events.py", line 2033, in _run_once handle._run() File "/usr/local/lib/python3.13/asyncio/events.py", line 89, in _run self._context.run(self._callback, *self._args) File "/usr/src/homeassistant/homeassistant/config.py", line 1055, in _async_load_and_validate_platform_integration platform = await p_integration.integration.async_get_platform(domain) File "/usr/src/homeassistant/homeassistant/loader.py", line 1108, in async_get_platform platforms = await self.async_get_platforms((platform_name,)) File "/usr/src/homeassistant/homeassistant/loader.py", line 1173, in async_get_platforms platforms.update(self._load_platforms(platform_names)) File "/usr/src/homeassistant/homeassistant/loader.py", line 1098, in _load_platforms platform_name: self._load_platform(platform_name) File "/usr/src/homeassistant/homeassistant/loader.py", line 1272, in _load_platform cache[full_name] = self._import_platform(platform_name) File "/usr/src/homeassistant/homeassistant/loader.py", line 1304, in _import_platform return importlib.import_module(f"{self.pkg_path}.{platform_name}")

@MankiniChykan MankiniChykan changed the title Configuration Warning - cannot import name 'TEMP_CELSIUS' from 'homeassistant.const' Configuration Warning, Platform Error, Blocking Call - cannot import name 'TEMP_CELSIUS' from 'homeassistant.const' Jan 4, 2025
@zeeuk
Copy link

zeeuk commented Jan 9, 2025

Updated version:

"""
Calculate Dew Point based on temperature and humidity sensors

For more details about this platform, please refer to the documentation
https://github.com/miguelangel-nubla/home-assistant-dewpoint
"""

import logging
import asyncio

import voluptuous as vol

from homeassistant import util
from homeassistant.core import callback
from homeassistant.const import (
UnitOfTemperature, ATTR_FRIENDLY_NAME, ATTR_ENTITY_ID, CONF_SENSORS,
EVENT_HOMEASSISTANT_START, ATTR_UNIT_OF_MEASUREMENT, ATTR_TEMPERATURE)
from homeassistant.helpers.entity import Entity, async_generate_entity_id
from homeassistant.helpers.event import async_track_state_change_event
import homeassistant.helpers.config_validation as cv

from homeassistant.components.sensor import (
ENTITY_ID_FORMAT, PLATFORM_SCHEMA)

_LOGGER = logging.getLogger(name)

CONF_REL_HUM = 'rel_hum'

SENSOR_SCHEMA = vol.Schema({
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Required(ATTR_TEMPERATURE): cv.entity_id,
vol.Required(CONF_REL_HUM): cv.entity_id
})

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_SENSORS): cv.schema_with_slug_keys(SENSOR_SCHEMA),
})

async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Setup the sensor platform."""

for device, device_config in config[CONF_SENSORS].items():
    friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
    entity_dry_temp = device_config.get(ATTR_TEMPERATURE)
    entity_rel_hum = device_config.get(CONF_REL_HUM)

    async_add_entities([DewPointSensor(hass, device, friendly_name, entity_dry_temp, entity_rel_hum)])

class DewPointSensor(Entity):

def __init__(self, hass, device_id, name, entity_dry_temp, entity_rel_hum):
    """Initialize the sensor."""
    self.hass = hass
    self._state = None
    self.entity_id = async_generate_entity_id(
        ENTITY_ID_FORMAT, device_id, hass=hass
    )
    self._name = name

    self._entity_dry_temp = entity_dry_temp
    self._entity_rel_hum = entity_rel_hum

async def async_added_to_hass(self):
    """Register callbacks."""
    @callback
    def sensor_state_listener(entity, old_state, new_state):
        """Handle device state changes."""
        self.async_schedule_update_ha_state(True)

    @callback
    def sensor_startup(event):
        """Update template on startup."""
        async_track_state_change_event(
            self.hass, [self._entity_dry_temp, self._entity_rel_hum], sensor_state_listener)

        self.async_schedule_update_ha_state(True)

    self.hass.bus.async_listen_once(
        EVENT_HOMEASSISTANT_START, sensor_startup)

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

@property
def icon(self):
    """Return the icon of the sensor."""
    return 'mdi:thermometer-lines'

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

@property
def unit_of_measurement(self):
    """Return the unit of measurement."""
    return UnitOfTemperature.CELSIUS

@callback
def get_dry_temp(self, entity):
    state = self.hass.states.get(entity)

    if state is None or state.state is None or state.state == 'unknown':
        _LOGGER.error('Unable to read temperature from unavailable sensor: %s', state.entity_id)
        return

    unit = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
    temp = util.convert(state.state, float)

    if temp is None:
        _LOGGER.error("Unable to parse temperature sensor %s with state:"
                      " %s", state.entity_id, state.state)
        return None

    # convert to celsius if necessary
    if unit == UnitOfTemperature.FAHRENHEIT:
        return util.temperature.fahrenheit_to_celsius(temp)
    if unit == UnitOfTemperature.CELSIUS:
        return temp
    _LOGGER.error("Temp sensor %s has unsupported unit: %s (allowed: %s, "
                  "%s)", state.entity_id, unit, UnitOfTemperature.CELSIUS,
                  UnitOfTemperature.FAHRENHEIT)

    try:
        return self.hass.config.units.temperature(
            float(state.state), unit)
    except ValueError as ex:
        _LOGGER.error('Unable to read temperature from sensor: %s', ex)

@callback
def get_rel_hum(self, entity):
    state = self.hass.states.get(entity)

    if state is None or state.state is None or state.state == 'unknown':
        _LOGGER.error('Unable to read relative humidity from unavailable sensor: %s', state.entity_id)
        return

    unit = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
    hum = util.convert(state.state, float)

    if hum is None:
        _LOGGER.error("Unable to read relative humidity from sensor %s, state: %s",
                      state.entity_id, state.state)
        return None

    if unit != '%':
        _LOGGER.error("Humidity sensor %s has unsupported unit: %s %s",
                      state.entity_id, unit, " (allowed: %)")
        return None

    if hum > 100 or hum < 0:
        _LOGGER.error("Humidity sensor %s is out of range: %s %s",
                      state.entity_id, hum, "(allowed: 0-100%)")
        return None

    return hum/100

async def async_update(self):
    """Fetch new state data for the sensor."""

    dry_temp = self.get_dry_temp(self._entity_dry_temp)
    rel_hum = self.get_rel_hum(self._entity_rel_hum)
    
    if dry_temp is not None and rel_hum is not None:
        import psychrolib
        psychrolib.SetUnitSystem(psychrolib.SI)
        TDewPoint = psychrolib.GetTDewPointFromRelHum(dry_temp, rel_hum)
        self._state = round(TDewPoint, 1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants