Attributes on Template Sensors

I know template sensors are often used to break out attributes into their own sensor but I would like a way to combine sensors into attributes. My use case is a Multisensor (motion, light, temp, etc). I want the main sensor to display motion and have attributes for the other sensors.

I would anticipate it working much like the MQTT sensor:

sensor:
    - platform: template
      sensors:
        living_room_multisensor_motion:
          friendly_name: "Living Room Multisensor Motion"
          device_class: motion
          attributes:
            - name: Tamper
              entity: sensor.living_room_multisensor_tamper 

you could create a small appdaemon app for that.

if im not mistaken you already have that installed.

Hmm, I hadn’t thought of looking at AppDaemon for this. Do you have an example of setting/creating attributes? I haven’t worked with that.

you want 1 sensor with several other sensor values as attributes.

in that case you use listen_state for the sensors involved and point them all to the same callback.
in the callback you get all involved states with get_state.

with set_state you set the state from your new sensor and its attributes.
ill show you some pseudo code:

def initialise(...):
  self.listen_state(self.change_state,self.args["main_sensor"])
  for sensor in self.args["attributes"]: 
    self.listen_state(self.change_state,sensor)

def change_state(...):
  all_attributes = {}
  statevalue = self.get_state(self.args["main_sensor"])
  for name,sensor in self.args["attributes"].items():
    all_attributes[name] = self.get_state(sensor)
  self.set_state(self.args["new_sensor_name"], state=statevalue,attributes=all_attributes)

and in the yaml:

new_sensor:
  module: module_name
  class: class_name
  new_sensor_name: sensor.new_name
  main_sensor: sensor.the_sensor_giving_the_state
  attributes:
    tamper: sensor.living_room_multisensor_tamper
    other_attribute: sensor.any_sensor

you can add as many attributes as you like and for every new sensor you just add new yaml.

edit: you can also add a friendlyname in the attributes

Do you recommend creating a New Sensor or just updating an existing?

i would recommend a new sensor.
existing sensors get updated from within HA. so your values would be overwritten again with the next valuecheck.

Sorry to revive an old topic, I’m trying to use the above code as a python_script but that would not work.

I know its for app daemon, but i wanted to try.

Anyone who hows to integrate his in python_script ?

appdaemon code is completely different from python_script for HA.
so you probably rarely find AD code that can easy be changed to python_script for HA.

and i think that there are very little people who first used AD and then did go to python_script.