Create sensor with attributes in integration

Dear all,

I am new to HA and also to Python. Python is not the problem at the moment.

I try to create my own integration.
So far, I am on a good way, but now I am stuck.

The easiest way would be, if HA would display HTML from a sensor value in a card. I mean pure HTML, not this Markdown card. :wink: In this case, I can format it in the sensor.py and all is fine. But as far as I know this is no feature from HA. I also do not want template scripting in the configuration.yaml because I want to share the integration later and this will lead to more problems than without.

Background is, I want to create a “Train Display” for my local train station.
So far I get the data from the API and have them available in my integration.

My problem is, that I am stuck with creating the attributes for the sensor.
The attributes don’t show up under Stats – Attributes. Only friendly_name is there

This is my code. I reduced non important parts like the function to call the API

"""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_ID, 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

from .const import (
    DOMAIN,  # noqa
    SCAN_INTERVAL,  # noqa
    CONF_GLOBALID,
)

# integration imports start
# removed
# integration imports end

DEFAULT_NAME = "S-Bahn"

_LOGGER = logging.getLogger(__name__)

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {
        vol.Required(CONF_GLOBALID): cv.string,
        vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
    }
)

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([ConnectionInfo(hass, globalid, name)], True)

class ConnectionInfo(SensorEntity):

    def __init__(self, hass, globalid, name) -> None:
        self._globalid = globalid
        self._name = name
        self._attr_name = name
        self._hass = hass
        self._hass.custom_attributes = {}

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

    @property
    def device_state_attributes(self):
        """Return the state attributes of the sensor."""
        return self._hass.custom_attributes

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

# removed

    def update(self) -> None:
        """Fetch new state data for the sensor."""
        
        _LOGGER.error("UPDATE - Test, if integration is running")

        self._attr_native_value = "" + self.abfahrt()

        attributes = {}
        attributes['delay'] = '1'
        attributes['linie'] = 'S3'
        attributes['destination'] = 'Far Far Away'
        self._hass.custom_attributes = attributes

This value is available in HA

self._attr_native_value = "" + self.abfahrt()

at the moment I have everything in 1 line, means the next departures in 1 line without formating

This is not available in HA

        attributes = {}
        attributes['delay'] = '1'
        attributes['linie'] = 'S3'
        attributes['destination'] = 'Far Far Away'
        self._hass.custom_attributes = attributes

Any idea why ?

You need to return your attributes in the extra_state_attributes property.

Ie

@property
def extra_state_attributes(self):
    attributes = {}
    attributes['delay'] = '1'
    attributes['linie'] = 'S3'
    attributes['destination'] = 'Far Far Away'
    return attributes

@msp1974

thx for your answer. :slight_smile:

So you mean, I have to use

def extra_state_attributes(self):

instead of

def device_state_attributes(self):

or do I have to add this function additionally ?

But your code looks not correct for me

@property
def extra_state_attributes(self):
    attributes = {}
    attributes['delay'] = '1'
    attributes['linie'] = 'S3'
    attributes['destination'] = 'Far Far Away'
    return attributes

because its returning static values.

Do you mean this ?

    @property
    def extra_state_attributes(self):
        """Return the state attributes of the sensor."""
        return self._hass.custom_attributes

Can not test it at the moment, bacause I am at work.

OK, it has to be

    @property
    def extra_state_attributes(self):
        """Return the state attributes of the sensor."""
        return self._hass.custom_attributes

thx for your help, now its working. :slight_smile: