Homelab, Linux, JS & ABAP (~˘▾˘)~
 

[Home Assistant] Offline detection for Zigbee2MQTT devices using the last_seen attribute

Activate the last_seen attribute via the Zigbee2MQTT interface. Go to Settings → Advanced → Last seen → Choose ISO_8601

Per default, the last seen sensor is disabled for all Home Assistant entities. To enable the last_seen attribute for all devices, add the following lines via VS Code in homeassistant → zigbee2mqtt → configuration.yaml

device_options:
  legacy: false
  homeassistant:
    last_seen:
        enabled_by_default: true

Now you must either restart Home Assistant or activate the entity manually: Go to Settings → Devices & services → Entities and adjust your Filter like this:

  • Integrations: Select “MQTT”
  • Status: Select “Disabled”

Then search for last seen, click on select all (right next to the filter button) and choose Enable selected in the context menu when clicking on the three dots in the top right corner.

Now the last_seen entity values should be visible, and you can use this new entity to detect an offline device. For example, by using this blueprint or by creating a template sensor like it is described here (related YT video).

{% set result = namespace(sensors=[]) %}
{% for state in states.sensor | rejectattr('attributes.device_class', 'undefined') | selectattr('attributes.device_class', '==', 'timestamp') %}
    {% if 'last_seen' in state.entity_id and (states(state.entity_id) == 'unavailable' or ((as_timestamp(now()) - as_timestamp(states(state.entity_id))) > ((24 | int) * 60 * 60))) %}
        {% set result.sensors = result.sensors + [state.name | regex_replace(find=' last seen', replace='') ~ ' (' ~ relative_time(strptime(states(state.entity_id), '%Y-%m-%dT%H:%M:%S%z', 'unavailable')) ~ ')'] %}
    {% endif %}
{% endfor %}
{{ result.sensors | join('\n') | truncate(254, True) }}

The template sensor can be put somewhere on your dashboard or used in an automation. Following the automation I’m using:

alias: Notify when zigbee device goes offline using last_seen
description: ""
trigger:
  - platform: state
    entity_id:
      - sensor.offline_zigbee_devices
    from: null
    to: null
    for:
      hours: 0
      minutes: 10
      seconds: 0
condition: []
action:
  - service: notify.mobile_app_mi_8
    metadata: {}
    data:
      title: |-
        {% if not states('sensor.offline_zigbee_devices') %}
          All Zigbee Devices Online!
        {% else %}
          The following Zigbee Devices are offline:
        {% endif %}
      message: >-
        {% for entity in expand('sensor.offline_zigbee_devices') | map(attribute='entity_id') | list %} 
          {{ states(entity) }} 
        {% endfor %}
mode: single

I also recommend excluding the last_seen sensors from the Logbook, because else the Logbook is flooded with changes. To do this, simply add the following lines in your configuration.yaml file:

logbook:
  exclude:
    entity_globs:
      - sensor.*_last_seen

[Home Assistant] Get friendly name of the triggering device in an automation

In an automation, you can retrieve the friendly_name of the triggering device using:

{{ trigger.to_state.attributes.friendly_name }}

Helpful if an automation can be triggered by different devices (e.g. garage door 1 or garage door 2) and you want to send a notification that explicitly names the triggering device:

  - service: notify.ALL_DEVICES
    data:
      title: Garage open!
      message: >-
        {{ trigger.to_state.attributes.friendly_name }} is open

[Home Assistant] Send notification only when you are home or when you come home

If you have a notification, which is only relevant for you when you are at home, it does not make sense to send it, if you are away. Instead, it would make sense to receive it the moment you get home.

To do this, simply add an Wait for a template action before sending the notification, with the following content. This can be done via YAML configuration

  - wait_template: "{{ is_state('person.nico', 'home') }}"
    continue_on_timeout: true

or via the web interface

If you are currently at home, means the entity status is already in the state home, it will be resolved immediately, otherwise it will wait until your status changes to home.

[Home Assistant] Motion sensor in combination with Adaptive Lightning

I have some lights in my garden which are turned on in the night and are controlled by the Adaptive Lighting component, to automatically adjust brightness and color during the night. But if someone comes home late and this is detected by a motion sensor, I wanted to increase the brightness of all the lights in the garden for a short time.

Increasing the brightness was easy, as it can be done by using the light.turn_on service. However, it took me a few minutes to figure out how to reactivate adaptive lighting on these lights when motion is no longer detected. But it’s actually super simple (and it’s directly written on the GitHub start page here and here). You just have to deactivate the “manually controlled” flag that got activated by “manually” increasing the brightness. Following an example with a single motion sensor (binary_sensor.haustuer_motion), a lamp (light.haustur_light) and the adaptive lightning switch entity (switch.adaptive_lighting_haustuer).

alias: Motion sensor front door
description: "Increase brightness for three minutes when motion is detected"
trigger:
  - platform: state
    entity_id:
      - binary_sensor.haustuer_motion
    to: "on"
condition:
  - condition: state
    entity_id: sun.sun
    state: below_horizon
action:
  - service: light.turn_on
    data:
      transition: 3
      brightness_pct: 70
    target:
      entity_id: light.haustur_light
  - wait_for_trigger:
      - platform: state
        entity_id:
          - binary_sensor.haustuer_motion
        to: "off"
        for:
          hours: 0
          minutes: 3
          seconds: 0
    timeout:
      hours: 0
      minutes: 0
      seconds: 0
      milliseconds: 0
  - service: adaptive_lighting.set_manual_control
    data:
      manual_control: false
      entity_id: switch.adaptive_lighting_haustuer
      lights:
        - light.haustur_light
mode: single

[Home Assistent] AWSH Müllabfuhrtermine einbinden

HACS Integration: https://github.com/mampfes/hacs_waste_collection_schedule

Die Integration bietet eine custom component für die AWSH. Nach Angabe von Ort und Straße bekommt man hier für alle Abfallbehälterarten die entsprechenden Termine zurück. Man muss daher noch die relevanten für sich heraussuchen. Diese kann man unter customize dann angeben und zusätzlich mit einem alias und einem icon versehen.

# Waste Collection Schedule
waste_collection_schedule:
  sources:
    # Integrated Service Provider for AWSH
    - name: awsh_de
      args:
        city: Ammersbek
        street: Frahmredder
      customize:
        # my waste types I ordered
        - type: Restabfall 40L-240L(2-wöchentlich)
          alias: restabfall
          icon: mdi:trash-can          
        - type: Bioabfall(2-wöchentlich)
          alias: bioabfall
          icon: mdi:leaf-circle
        - type: Wertstoff/LVP(2-wöchentlich)
          alias: wertstoff
          icon: mdi:recycle
        - type: Papiertonne(monatlich)
          alias: papier
          icon: mdi:trash-can

Alternativ bekommt man hier den Link zu einer .ics Kalenderdatei. Man kann vorher die für sich relevanten Abfallbehälter auswählen. Die .ics kann ebenfalls direkt eingebunden werden (siehe hier)

# Waste Collection Schedule
waste_collection_schedule:
  sources:
    # ICS
    - name: ics
      args:
        url: https://www.awsh.de/api_v2/collection_dates/1/ort/XXX/strasse/XXX/hausnummern/0/abfallarten/R02-B02-D02-P04/kalender.ics

Nach einem Reboot kann man nun im Home Assistant Kalender seine Abholtermine einsehen.

Im nächsten Schritt definiert man sich noch seine Sensoren je Abfallart.

sensor:
  - platform: waste_collection_schedule
    name: Restabfall
    value_template: 'in {{value.daysTo}} Tag(en)'
    types:
      - restabfall
  - platform: waste_collection_schedule
    name: Bio
    value_template: 'in {{value.daysTo}} Tag(en)'
    types:
      - bioabfall
  - platform: waste_collection_schedule
    name: Wertstoff
    value_template: 'in {{value.daysTo}} Tag(en)'
    types:
      - wertstoff
  - platform: waste_collection_schedule
    name: Papier
    value_template: 'in {{value.daysTo}} Tag(en)'
    types:
      - papier  

Die Sensoren kann man dann zu seinem Dashboard hinzufügen und bei Bedarf auch noch umbenennen. So sieht es bei mir dann aus:

Button-card

Für eine Button-card habe ich mir noch einen weiteren Sensor angelegt. Diesem Sensor einfach alle Abfallarten zuordnen.

  # Used with custom:button-card
  - platform: waste_collection_schedule
    name: wasteButton
    count: 4
    value_template: '{{value.types|join(", ")}}|{{value.daysTo}}|{{value.date.strftime("%d.%m.%Y")}}|{{value.date.strftime("%a")}}'
    types:
      - Restabfall
      - Bioabfall
      - Wertstoff
      - Papier

Die Button-card dann noch befüllen mit:

type: custom:button-card
entity: sensor.wastebutton
layout: icon_name_state2nd
show_label: true
label: |
  [[[
    var days_to = entity.state.split("|")[1]
    if (days_to == 0)
    { return "War heute" }
    else if (days_to == 1)
    { return "Heute Abend raus" }
    else
    { return "in " + days_to + " Tagen" }
  ]]]
show_name: true
name: |
  [[[
    return entity.state.split("|")[0]
  ]]]
state:
  - color: red
    operator: template
    value: '[[[ return entity.state.split("|")[1] == 0 ]]]'
  - color: orange
    operator: template
    value: '[[[ return entity.state.split("|")[1] == 1 ]]]'
  - value: default

Benachrichtigung

Um immer die Anzahl der Tage bis zum nächsten Abholtermin zu kennen, am besten noch einen weiteren Sensor anlegen und diesem wieder alle Abfallarten zuordnen.

  # Sensor for upcoming waste. Used in my reminder automation
  - platform: waste_collection_schedule
    name: upcomingWaste
    value_template: "{{value.daysTo}}"
    types:
      - Restabfall
      - Bioabfall
      - Wertstoff
      - Papier

Dieser kann dann in einer Erinnerungsautomatisierung verwendet werden, welche z.b. eine Notification am Vortag um 19Uhr verschickt.

alias: Abfall Erinnerung
description: ""
trigger:
  - platform: time
    at: "19:00:00"
condition:
  - condition: state
    state: "1"
    entity_id: sensor.upcomingwaste
action:
  - service: notify.family
    data:
      message: >-
        Müll rausbringen: {{ states.sensor.upcomingwaste.attributes.values() |
        first | 
        replace("restabfall","Restmüll") |
        replace("wertstoff","Wertstoff") |  
        replace("bio","Bio") |
        replace("papier","Papier") }}
      data:
        actions:
          - action: YES_TRASHCAN_IS_OUTSIDE
            title: Ja, ist rausgestellt!
        tag: trashcan_done
mode: single

Die Notification beinhaltet eine Bestätigungsmöglichkeit. Hat jemand die Tonne herausgestellt, kann dieser darüber dies einfach kurz bestätigen und mit einer zweiten Automatisierung kann man die Benachrichtigung dann bei anderen verschwinden lassen. Mehr dazu hier.

alias: Abfall Erinnerung - cleared
description: ""
trigger:
  - platform: event
    event_type: mobile_app_notification_action
    event_data:
      action: YES_TRASHCAN_IS_OUTSIDE
condition: []
action:
  - service: notify.family
    data:
      message: clear_notification
      data:
        tag: trashcan_done
mode: single

Karte für das Dashboard

Ein tolles Beispiel für eine schöne Dashboard-Karte findet man hier.

Dafür müssen jedoch noch ein paar weitere Sensoren hinzugefügt werden, wie es hier ebenfalls beschrieben ist.

[Home Assistant] Open window reminder

This automation is triggered when a window stays open for >10 minutes. It will then send a reminder every 10 minutes (max 6 times).

This post helped me to create this script.

alias: Open window reminder
description: ''
trigger:
  - platform: state
    entity_id: binary_sensor.lumi_lumi_sensor_magnet_aq2_xxx_on_off
    from: 'off'
    to: 'on'
    for:
      hours: 0
      minutes: 10
      seconds: 0
condition: []
action:
  - repeat:
      while:
        - condition: state
          entity_id: binary_sensor.lumi_lumi_sensor_magnet_aq2_xxx_on_off
          state: 'on'
        - condition: template
          value_template: '{{ repeat.index <= 6 }}'
      sequence:
        - variables:
            counter: '{{ repeat.index * 10 }}'
        - service: telegram_bot.send_message
          data:
            message: Window is open for {{ counter }} minutes
        - delay: '00:10:00'
mode: single

[Home Assistant] Control lights with multiple motion sensors

Create group of motion sensors in groups.yaml
https://www.home-assistant.io/integrations/group/

cellar_motion:
  name: Cellar Presence
  icon: mdi:motion-sensor
  entities:
    - binary_sensor.bewegungsmelder_xxx_ias_zone
    - binary_sensor.bewegungsmelder_xxx_ias_zone

Next, if you have more than one light you’d like to control, create a group of lights in your configuration.yaml
https://www.home-assistant.io/integrations/light.group/

# Light Groups      
light:
  - platform: group
    name: Cellar Lights
    entities:
      - light.ikea_of_sweden_tradfri_bulb_e27_ww_806lm_xxx_level_on_off
      - light.ikea_of_sweden_tradfri_bulb_e27_ww_806lm_xxx_level_on_off   

And finally use both in an automation

alias: My motion activated lights
description: Turn on a light when motion is detected.
trigger:
  - platform: state
    entity_id: group.cellar_motion
    from: 'off'
    to: 'on'
condition: []
action:
  - service: light.turn_on
    target:
      entity_id: light.cellar_lights
    data: {}
  - wait_for_trigger:
      platform: state
      entity_id: group.cellar_motion
      from: 'on'
      to: 'off'
  - delay: 120
  - service: light.turn_off
    target:
      entity_id: light.cellar_lights
    data: {}
mode: restart
max_exceeded: silent # https://www.home-assistant.io/docs/automation/modes/