Count Active MQTT Swtich

Hi, I am new to Home Assistant. Inspired by some youtube videos and forum like this. I have created my home automation to switch ON/OFF lights in my home. The hardware is connected to my MQTT server.

The mqtt entities are added in HA in the configurations.yaml file like below

mqtt:
switch:
- name: “Valve 1”
unique_id: “Valve 1”
state_topic: “xxxxx/trigger”
command_topic: “xxxxxxxx/trigger”
payload_on: 1
payload_off: 0
optimistic: false
retain: true

  - name: "Groud Floor Light"
    unique_id: "SW1"
    state_topic: "xxxxx/S1"
    command_topic: "xxxxxxx/S1"
    payload_on: "ON"
    payload_off: "OFF"
    optimistic: false
    retain: true    

and so on.

and it works fine.

Now I wanted to put a card showing number of Active / ON lights in my home. (mqtt switch)
got some info like this

{{ states.switch|selectattr(‘state’,‘equalto’,‘on’)|list|length }}

but which file this has to be added.

Anyone can help me?

It doesn’t have to be added to a file at all. Create a template sensor helper:

  • Settings
  • Devices & Services
  • Helpers
  • Create
  • Template > template a sensor (not binary sensor)

Paste your template into the state template box. Note that because you didn’t correctly format your code above, the quotes are wrong, so here’s a fixed version:

{{ states.switch
   |selectattr('state','eq','on')|list|length }}

Note that this counts all switches, not just your MQTT ones.

got it and its easy too. thank you.
also how to filter the switch within an area. that is to count only switch in home area like that

Line breaks only for readability, can be all on one line:

{{ area_entities('AREA_NAME')
   |select('match','switch.')
   |select('is_state','on')
   |list|count }}

area_entities() (doc) returns a list of entity IDs, which we then restrict with match (doc) to those starting with “switch.”, then run the is_state test (doc).

1 Like

clear. and got the result as expected.

image

Also is there any option to change the light colour when there is no lights active.

type: horizontal-stack
cards:

  • type: custom:mushroom-entity-card
    entity: binary_sensor.sw_light_status
    icon: mdi:connection
    icon_color: cyan
    tap_action:
    action: more-info
    layout: horizontal
    hold_action:
    action: more-info
    fill_container: true
    name: 'Network ’
  • type: custom:mushroom-entity-card
    entity: sensor.active_lights_2
    layout: horizontal
    icon: mdi:ceiling-light-multiple
    icon_color: accent
    tap_action:
    action: more-info
    name: 'Active Lights ’
    layout_options:
    grid_columns: 4
    grid_rows: 1