Platform error sensor - cannot import name from homeassistant.const

Dear all,

I am new to Home Assistant (around 2 weeks) and want to create my own custom component. I am also new to Python (used php / java before) but Python is not the problem. I was already able to create my project outside HA.

Understanding how HA works is more complicated. I tried to find easy examples but this is not so easy. There are a lot but most of the time its not so clear. At least for me. ^^

I tried to use the example_sensor

in a combination with this tutorial

this is my sensor.py (located in my project folder inside custom_components)

"""Platform for sensor integration."""

from __future__ import annotations
import voluptuous as vol
import logging

from homeassistant.components.sensor import (
    PLATFORM_SCHEMA,
    SensorDeviceClass,
    SensorEntity,
    SensorStateClass,
)
from homeassistant.const import CONF_GLOBALID, CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
import homeassistant.helpers.config_validation as cv


DEFAULT_NAME = "S-Bahn"


PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {
        vol.Required(CONF_GLOBALID): str,
        vol.Optional(CONF_NAME, default=DEFAULT_NAME): str,
        vol.Optional(CONF_UPDATERATE, default=60): int,
    }
)


async def async_setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Set up the sensor platform."""
    name = config[CONF_NAME]
    globalid = config[CONF_GLOBALID]

    add_entities([DummyGarageSensor(globalid, name)], True)


class DummyGarageSensor(SensorEntity):
    """Representation of a Sensor."""

    def __init__(self, globid, name) -> None:
        super().__init__()
        self._globid = globid
        self._name = name
        self._attr_name = name

    @property
    def name(self) -> str:
        """Return the name of the switch."""
        return self._name

    @property
    def unique_id(self) -> str:
        """Return a unique, Home Assistant friendly identifier for this entity."""
        return self._globid.replace(":", "")

    def update(self) -> None:
        """Fetch new state data for the sensor.

        This is the only method that should fetch new data for Home Assistant.
        """
        self._attr_native_value = "Test"
        _LOGGER.error("Log Check for my Integration")
        

I added this to my configuration.yaml and restarted HA (several times)

sensor:
  - platform: another_mvg
    scan_interval: 30
    name: "S3"
    globalid: "de:09179:6110"

but if I check the configuration / restart HA I get this in my logfile

Platform error: sensor - cannot import name 'CONF_GLOBALID' from 'homeassistant.const' (/usr/src/homeassistant/homeassistant/const.py)

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config.py", line 1380, in async_process_component_config
    platform = p_integration.get_platform(domain)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/loader.py", line 834, in get_platform
    cache[full_name] = self._import_platform(platform_name)
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/loader.py", line 851, in _import_platform
    return importlib.import_module(f"{self.pkg_path}.{platform_name}")
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1204, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1176, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 940, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/config/custom_components/another_mvg/sensor.py", line 24, in <module>
    from homeassistant.const import CONF_GLOBALID, CONF_NAME
ImportError: cannot import name 'CONF_GLOBALID' from 'homeassistant.const' (/usr/src/homeassistant/homeassistant/const.py)

but I passed
globalid: "de:09179:6110"
in the configuration.yaml to my integration

Whats wrong ?

Any idea ?

OK I found it by my own. For everyone who has the same “problem”, here is a short explanation.

These CONF_ from the examples are not “magically” created by putting parameters in the configuration.yaml there is a list of predefined CONFs we can use

If you want your own, you have to create a const.py in your own integration folder containing the CONFs

just put (in my example)

CONF_GLOBALID = "globalid"

in your const.py

and in your sensors.py (or switch.py …) include it in the PLATFORM_SCHEMA

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {
        vol.Required(CONF_GLOBALID): cv.string,
    }
)

then you can pass the parameter from the configuration.yaml to your integration

sensor:
  - platform: your_platform_name
    globalid: "abc123456xyz"