Create attributes for custom sensor

Hey everyone so using this write up here: https://home-assistant.io/components/sensor.template/ I see I can create a custom sensor and set its state. However I would like to create some attributes for this sensor.

My use case is I have a FedEx sensor for my wife and myself. I am adding up our packages and would like to make an attribute that says one of them is in transit one of them is out for delivery etc.

Does anyone know how to create attributes?

Thanks.

You can use python_scripts to create attributes. Alternately, just create a new sensor with the desired information (that may be easier).

Hi @arsaboo I believe I did create a custom sensor. I’m just looking to add additional attributes to it. Right now I can only set the state of the sensor (so 2 or 3 etc. however many packages are out for delivery). I want to create an additional attribute say something like package_state.

So the config file would look something like this:
custom_sensor.package_state = {{sensor.fedex.attribute + sensor.fedex2.attribute}}

Thanks.

You will use a template sensor. See here for docs.

From my understanding, the doc doesn’t mention anything about creating custom attributes for template sensor. It just shows how to take attributes from other sensors to apply in the template sensor.

I also need to create custom attributes into some template sensors.

Any chance you have a working example of a python script that adds some custom attributes to a template sensor, to share?

I use this to read my life360:

##########################################################################################
# python_script.set_state to display whether life360 are overdue or not
# triggered by automation.life360_connected
# https://community.home-assistant.io/t/life360-device-tracker-platform/52406/267?u=mariusthvdb
##########################################################################################
entity_id = data.get('entity_id')
if not entity_id:
    logger.error('No entity_id provided')
state = data.get('state')
if not state:
    logger.error('No state provided')

if entity_id and state:
#    old_state = hass.states.get(entity_id)
#    if old_state:
#        attrs = old_state.attributes
#    else:
#        attrs = None
    theme = 'red' if state == 'on' else 'green'
    friendlyName = entity_id.split('.')[1].title().replace('_',' ')

    hass.states.set(entity_id, state,{
      'custom_ui_state_card': 'state-card-custom-ui',
      'friendly_name': friendlyName,
      'device_class': 'problem',
      'theme': theme,
      'show_last_changed': 'true'
      })

as you can see I use custom attributes, in fact you can set anything you want. In this script and automation even the (binary_)sensor itself is ‘created’.

use this automation to call the script:

  - alias: Life360 connected
    trigger: 
      - platform: event
        event_type: life360_update_overdue
      - platform: event
        event_type: life360_update_restored
    action:
      service: python_script.set_state
      data_template:
        entity_id: >
          binary_sensor.overdue_{{ trigger.event.data.entity_id.split('.')[1] }}
        state: >
          {{ 'on' if trigger.event.event_type.endswith('overdue') else 'off' }}
2 Likes

Hi, Cody Horton

I can add my custom attributes for my custom sensor,here is steps:

 class MyCustomSensor(Entity):
     def __init__(self, hass, config):
         """Initialize the sensor."""
         self._hass = hass
         self._hass.custom_attributes = {}

     @property
     def device_state_attributes(self):
         """Return the state attributes of the sensor."""
         return self._hass.custom_attributes
 
     def update(self):
         attributes = {}
         attributes['mac'] = 'some data'
         attributes['sn'] = 'some other data'
         self._hass.custom_attributes = attributes

the key point is return the attributes in predefined function “device_state_attributes”

hope this can help.
:slight_smile:

3 Likes

Thanks, @yangbo1979 - that worked like a charm!!

Another question for the community - looking for a good custom component example that shows how to add an input_number to HA. For example, I’m creating a CC that calculates a number of thermal comfort parameters - those require inputs of physical insulation properties (these are estimates, or more like tuning parameters). Is there a way I can have those created at the same time the CC is instantiated? Now that I’m thinking a bit more about it, I know I can create entities on the fly in appdaemon using the hass.set command. I’m going to give it shot, but has anyone done this with a CC? Thanks!

That didn’t work… Now I’m trying this within the __init__ function:

input_numbers = ["input_number.htc_test"]
dev = []
for input_number in input_numbers:
    dev.append(InputNumberClass(input_number))
add_devices_callback(dev, True)

After some time looking to solve this, found there’s an important difference between:

  • sensor:
    platform: template …

, and
template:

  • sensor: …

With the latest there’s the chance to add any additional attributes to the sensor.

1 Like

And how to add attributes for:

template:
 - platform: ...