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

[Home Assistant] Zigbee Garagentoröffner

Wir haben zu unserem alten Haus auch eine alte Doppelgarage bekommen. Die Garage ist in einem Zustand, dass man sie eigentlich nur noch abreißen kann. Aufgrund des Alters ist sie so schmal, dass heute gängige Autos quasi gar nicht hineinpassen. Von den zwei Garagentoren ist immerhin eines elektrisch. Verbaut ist ein Genie Screw Drive Antrieb. Die Firma Genie gibt es heute noch, unser Modell ist aber sicher >30 Jahre alt und gibt es natürlich nicht mehr im Sortiment.

Das Tor öffnen kann man über einen Taster oder einer Fernbedienung. Dafür wurde zusätzlich noch ein Genie Radio Control Modul verbaut (der graue Kasten rechts neben der Steckdose). In der Steckdose ist praktischerweise der Garagentormotor angeschlossen. Und der weiße dünne Draht, der an dem Stromkabel nach rechts langläuft, führt zum Taster.

Die Fernbedienungen hatten mittlerweile beide das zeitliche gesegnet. Na gut, über eine sind wir auch mit einem Auto drübergefahren… 🙂

Interessanterweise gibt es den Dickert Handsender MAHS40-01 (10 Codierschalter) heute noch. Der Preis ist natürlich absolut lächerlich mit >30€.

Nach kurzer Recherche auf AliExpress habe mir daher lieber einen Zigbee Garagentoröffner gekauft für 13,08€.

Erheblich günstiger und nun kann die Garage auch in Home Assistant integriert werden. Erkannt wird der MANHOT Garage Door Opener in Zigbee2MQTT als Tuya TS603. Zwei Entitäten werden bereitgestellt, eine zum Öffnen und Schließen des Tores und eine weitere zeigt den aktuellen Status des Tores an.

Die Installation habe ich mir so einfach wie möglich gemacht. Einen Schönheitswettbewerb bei der Verkabelung gewinnt man in unserer abrissreifen Garage sowieso nicht mehr. Ich habe daher einfach den Draht vom Taster durchtrennt

und dann wieder mit zwei 3er WAGO Klemmen verbunden, sodass die Taster Funktion erhalten bleibt. Die WAGOs sind eigentlich etwas zu groß für den dünnen Draht, aber hatte gerade nichts Besseres zur Hand. Und auf eine Lüsterklemme hatte ich noch wenig Lust.

Das schwarze Kabel war bereits beim Zigbee Garagentoröffner beigelegt und habe ich in die verbliebenen freien WAGO Plätze gesteckt und mit dem anderen Ende in den Zigbee Schalter. Jetzt fehlte nur noch Strom und der Sensor für den Zustand des Tores (offen/geschlossen). Da ich die alte Verkabelung in der Aufputzdose nicht anrühren wollte, habe ich mir einfach einen 2-fach Steckdosenadapter genommen und für die 230v Stromversorgung des Schalters einen alten Stecker (mit viel zu langem Kabel), den ich irgendwo mal abgeschnitten hatte.

Jetzt noch den Sensor mit dem Zigbee Schalter verbunden und das andere Ende zum Tor geführt und drangeklebt (ja, das Tor müsste mal lackiert werden…).

Und das war es auch schon! Neben dem Taster und den Fernbedienungen kann das Tor nun auch via Home Assistant gesteuert werden.

An beiden Toren hatte ich bereits Tür/Fenster Kontaktsensoren, um einfach prüfen zu können, ob wir das Tor offen stehen lassen haben. Die Sensoren werden mit 2 x AAA-Batterien betrieben und müssen vermutlich alle 2-3 Jahre getauscht werden. Zumindest an einem Tor kann ich mir das jetzt aber sparen.

Eine geeignete Darstellung auf dem Dashboard fehlt mir allerdings noch.

    [Home Assistant] HASS VM High CPU Usage on Proxmox

    Since my Proxmox Server is also my HTPC in my living room, I noticed that suddenly the CPU fan become very noisy. When checking all LXCs and VMs, it turned out that the Home Assistant VW was the cause.

    When checking the Supervisor logs, I saw that there was a docker container that got terminated. This semmed to match the CPU usage pattern I checked before.

    To inspect the docker container via the Advanced SSH & Web Terminal add-on, you must disable the Protection mode first.

    After that, simply run docker stats.

    If there are no suspicious values, simply open some of the add-ons in another window and check how the values behave. In the above screenshot, I simply opened the VSCode editor, and you can immediately see an extreme high CPU usage. After a quick search, I found open issues that seem to be related to this issue:

    As a workaround, a user had the idea to simply restart VSCode via an automation, when its CPU rises above a threshold. To do this, you have to enable some CPU & Memory sensors of the VSCode add-on. Search for your Home Assistant Supervisor Integration.

    Select the Studio Code Server add-on.

    And enable the sensors.

    Now you can set up a simple automation like the following.

    alias: Restart VSCode when cpu/memory too high
    description: ""
    triggers:
      - trigger: numeric_state
        entity_id:
          - sensor.studio_code_server_cpu_percent
        for:
          hours: 0
          minutes: 5
          seconds: 0
        above: 50
      - trigger: numeric_state
        entity_id:
          - sensor.studio_code_server_memory_percent
        above: 30
        for:
          hours: 0
          minutes: 5
          seconds: 0
    conditions: []
    actions:
      - action: hassio.addon_restart
        metadata: {}
        data:
          addon: a0d7b954_vscode
    mode: single
    
    

    Since I have the automation setup, the Proxmox CPU fan is quiet again and the VM behaves normal.

    [Home Assistant] Editor shortcuts

    All VS Code shortcuts will also work in Home Assistant. I mostly need the following:

    TabMove lines to right
    Ctrl + Tab (on Linux Mint it’s Shit + Tab)Move lines to left
    Ctrl + Alt + Mouse selectionMark area over multiple lines (works only in YAML editor)
    Ctrl + Shift + KDelete row
    Alt + Arrow key up or downMove row(s) up or down
    Alt + Shift + Arrow downDuplicate selected rows
    Ctrl + Shit + /Comment line/area

    Also, you can simply expand the window you are working in, by clicking on the window title.

    [Home Assistant] Person card with step counter

    I recently enhanced the person cards on my dashboard to display some mobile phone sensor data (check here). In addition, I now also added the daily steps by using the Steps sensor of my mobile phone in combination with a utility helper sensor, which counts the daily steps, as the mobile Steps sensor is an increasing counter without daily reset. This is how it looks now:

    To include the daily steps, you first have to enable the Steps sensor in the Home Assistant Companion App on your mobile phone.

    Next, create a utility sensor which uses the Steps sensor as Input and daily resets the counted steps.

    The utility sensor history should look like this after a few days:

    Now we can add the utility sensor to the dashboard. As I’m using the vertical-stack-in-card, I simply had to add a new horizontal-stack to the person card to get a new line, and include a mushroom-chips-card which displays the steps.

      - type: horizontal-stack
        cards:
          - type: custom:mushroom-chips-card
            alignment: center
            card_mod:
              style: |
                ha-card {
                    --chip-font-size: 0.32em;
                    --chip-icon-size: 0.5em;
                    --chip-border-width: 0;
                    --chip-box-shadow: none;
                    --chip-background: none;
                    --chip-border: none;
                    --chip-spacing: none;
                    --chip-font-weight: bold;
                }
            chips:
              - type: template
                entity: sensor.daily_steps_mi8
                content: "{{ states('sensor.daily_steps_mi8')}} steps today"
                tap_action:
                  action: more-info
    

    I noticed, that the Steps sensor sometimes does not count steps, and it helps to have some separate steps counter app running on the phone like Paseo.

    [Home Assistant] Combine Adaptive Lightning, motion activated light and lights turned on by sunset

    I have some motion activated lights in my home, for example in the kitchen. During daytime, the kitchen light should simply be turned on and off by the motion sensor. But when the sun sets, I like to turn on most of the lights in the house to 1% brightness, so that you never walk into a completely dark room. In this case, the motion sensor should not turn the kitchen light on and off, but instead should increase the brightness and afterward go back to the previous state of 1% brightness. And with “increase the brightness”, I don’t mean a fix value, but instead it should set the right brightness provided by the Adaptive Lightning integration. When it’s late, and the sleep mode is tuned on for the house, the kitchen light of course should be turned off, and when it is turned on, it should respect the configured sleep values from Adaptive Lightning settings.

    Most things turned out to be quite easy by using Scenes to store the current light state and of course by using the great Adaptive Lightning features. But my automation had one important gap. When someone was is the kitchen, means kitchen light was turned on by the motion sensor, and we had sunset in this exact moment, it would always turn down the brightness to 1%, because the automation which turns on all lights to 1% brightness when the sun sets got triggered. Also, when the person left the kitchen, the previous stored scene was loaded, which was created before sunset, means it turned off the kitchen light, instead of the now required 1% brightness. This was of course really confusing for people in the kitchen…

    I needed a way, to only activate the 1% sunset brightness, when no one is currently in the kitchen. The solution was a wait_template which checks if currently a motion automation is running in the kitchen. I could have also used the wait check on motion sensor directly, but I wanted to be able to use timeouts in my automation, which can be longer than the actual motion detection.

    The important snippet is this one, which checks if no automation is currently running:

    {{ is_state_attr('automation.bewegungsmelder_kuche', 'current', 0) }}
    

    And this is the whole part I have added to my sunset automation (and also for the sleep automation similarly) for every room, which has a motion activated light:

    sequence:
      - wait_template: "{{ is_state_attr('automation.bewegungsmelder_kuche', 'current', 0) }}"
        continue_on_timeout: true
      - action: adaptive_lighting.set_manual_control
        metadata: {}
        data:
          manual_control: true
          lights:
            - light.kueche
      - action: light.turn_on
        metadata: {}
        data:
          brightness_pct: 1
          kelvin: 2000
        target:
          entity_id: light.kueche
    enabled: true
    
    

    It simply waits until the motion sensor automation is done, then turns on the manual_control flag in Adaptive Lightning, so it does not adjust the light automatically, as it should stay at 1%, and finally turns on the light with 1% brightness. The only drawback is, that there is a millisecond where the light is turned off by the motion automation and until this wait_template fires and turns the light back on to 1% brightness. But as in this case no one should be in the room anymore, I can live with that.

    And this is my motion sensor automation for the kitchen:

    alias: Bewegungsmelder Küche
    description: ""
    mode: single
    triggers:
      - entity_id:
          - binary_sensor.0xb4e3f9fffeb689d4_occupancy
        to: "on"
        trigger: state
    conditions: []
    actions:
      - data:
          scene_id: zustand_kueche_alt
          snapshot_entities:
            - light.kueche
        action: scene.create
      - action: adaptive_lighting.set_manual_control
        metadata: {}
        data:
          manual_control: false
          lights:
            - light.kueche
      - target:
          entity_id:
            - light.kueche
        data:
          transition: 5
        action: light.turn_on
        enabled: true
      - wait_for_trigger:
          - entity_id:
              - binary_sensor.0xb4e3f9fffeb689d4_occupancy
            to: "off"
            for:
              hours: 0
              minutes: 0
              seconds: 10
            trigger: state
      - target:
          entity_id: scene.zustand_kueche_alt
        data:
          transition: 5
        action: scene.turn_on
    

    Before turning on the kitchen light, it stores the current state in a scene, then always disables the manual_control flag (in case the sunset automation turned it on), so that when in the next step the light is turned on, it automatically adjusts the brightness to the right value. When no motion is detected for 10 seconds, it restores the previous scene.

    [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] Zigbee2MQTT device_class motion is now occupancy

    After the last Zigbee2MQTT update to version 1.39.0, suddenly the motion sensors were missing in my auto-entities cards, which I use to display all motions sensors for specific areas.

    type: vertical-stack
    title: Bewegungsmelder
    cards:
      - type: custom:auto-entities
        card:
          show_header_toggle: false
          title: null
          type: entities
          state_color: true
        filter:
          include:
            - attributes:
                device_class: motion
              options:
                secondary_info: last-changed
              area: cellar
        sort:
          method: last_changed
          reverse: true
    

    When checking the changes included in the new Zigbee2MQTT version, I found the reason: https://github.com/Koenkk/zigbee2mqtt/pull/22896
    With this pull request, the device_class is motion is replaced with occupancy. After changing the device_class in the auto_entities config, the motions sensors are displayed again.

    Alternatively, you can switch the device_class back to motion, like it is described here. This would also bring back the old icon mdi:motion-sensor instead of mdi:home-outline.

    [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.