Using light brightness as a condition

Hi,

I’m very new to ESPHome and YAML. I have a switch that I want to use to controll my light. I already created the basic configuration and it works.

Now I would like to add the ability to change brightness with doube click. It should work like this: If the light has more then 50% brightness, then dimm it to 10%, if it has less then 50%, set full brightness. So basically the doubleclick should toggle between 100% and 10%.

To do this, I need to create a condition based on the current brightness of the light. I need to get this value form HA end use it in ESPHome. I know hot to set the brigtness, but I can not figure out, how to get it and use it in a condition.

Does anybode have an indea? Thank you.

This would be an automation of course, and instead of doing it in a condition to check for the value as it is a little clunky for your use case - have as the trigger a double-click, no condition, and then for the action use if-then-else (which can also be nested) and you can have all of the logic there.

Yes this should be possible. Please share your device yaml.

Hi, this is my configuration:

substitutions:
  # Default name
  name: "athom-mini-switch"
  # Default friendly name
  friendly_name: "Athom Relay Switch"
  # Allows ESP device to be automatically linked to an 'Area' in Home Assistant. Typically used for areas such as 'Lounge Room', 'Kitchen' etc
  room: ""
  # Description as appears in ESPHome & top of webserver page
  device_description: "athom mini relay switch module"
  # Project Name
  project_name: "Athom Technology.Mini Relay Switch"
  # Projection version denotes the release version of the yaml file, allowing checking of deployed vs latest version
  project_version: "v1.1.3"
   # Restore the relay (GPO switch) upon reboot to state:
  light_restore_mode: RESTORE_DEFAULT_ON
  # Define a domain for this device to use. i.e. iot.home.lan (so device will appear as athom-smart-plug-v2.iot.home.lan in DNS/DHCP logs)
  dns_domain: ".local"
  # Set timezone of the smart plug. Useful if the plug is in a location different to the HA server. Can be entered in unix Country/Area format (i.e. "Australia/Sydney")
  timezone: ""
  # Set the duration between the sntp service polling ntp.org servers for an update
  sntp_update_interval: 6h
  # Network time servers for your region, enter from lowest to highest priority. To use local servers update as per zones or countries at: https://www.ntppool.org/zone/@
  sntp_server_1: "0.pool.ntp.org"
  sntp_server_2: "1.pool.ntp.org"
  sntp_server_3: "2.pool.ntp.org"
  # Enables faster network connections, with last connected SSID being connected to and no full scan for SSID being undertaken
  wifi_fast_connect: "true"
  # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (Default), VERBOSE, VERY_VERBOSE
  log_level: "DEBUG"
  # Enable or disable the use of IPv6 networking on the device
  ipv6_enable: "false"
  hass_light: light.svetlo_jidelni_stul

esphome:
  name: "${name}"
  friendly_name: "${friendly_name}"
  comment: "${device_description}"
  area: "${room}"
  name_add_mac_suffix: true
  min_version: 2024.6.0
  project:
    name: "${project_name}"
    version: "${project_version}"
  on_boot:
    - priority: 600
      then:
        - select.set_index:
            id: power_mode
            index: !lambda |-
                    return id(restore_mode)-1;
        - lambda: |-
              switch(id(restore_mode))
              {
              case 1:{
                      id(mini_relay).turn_off();
                      break;
                            }
              case 2:{
                      id(mini_relay).turn_on();
                      break;
                            }
              default:{
                      break;
                            }
              }

esp8266:
  board: esp8285
  restore_from_flash: true

preferences:
  flash_write_interval: 1min

api:

ota:
  - platform: esphome

logger:
  level: ${log_level}
  baud_rate: 115200

mdns:
  disabled: false

web_server:
  port: 80

network:
  enable_ipv6: ${ipv6_enable}

wifi:
  # This spawns an AP with the device name and mac address with no password.
  ssid: !secret wifi_ssid
  password: !secret wifi_password
  manual_ip:
    static_ip: 192.168.1.195
    gateway: 192.168.1.1
    subnet: 255.255.255.0      
  # Allow rapid re-connection to previously connect WiFi SSID, skipping scan of all SSID
  fast_connect: "${wifi_fast_connect}"
  # Define dns domain / suffix to add to hostname
  domain: "${dns_domain}"

captive_portal:

dashboard_import:
  package_import_url: github://athom-tech/athom-configs/athom-mini-switch.yaml

globals:
  - id: restore_mode
    type: int
    restore_value: yes
    initial_value: "3"

select:
  - platform: template
    name: "Power On State"
    id: "power_mode"
    optimistic: true
    options:
      - Always Off
      - Always On
      - Restore Power Off State
    on_value:
      then:
        - lambda: |-
            id(restore_mode)=i+1;

button:
  - platform: restart
    name: "Restart"
    entity_category: config

  - platform: factory_reset
    name: "Factory Reset"
    id: Reset
    entity_category: config

  - platform: safe_mode
    name: "Safe Mode"
    internal: false
    entity_category: config

output:
  - platform: gpio
    id: relay_output
    pin: GPIO13

light:
  - platform: status_led
    id: led
    name: "Blue LED"
    disabled_by_default: true
    pin:
      number: GPIO4
      inverted: true

  - platform: binary
    id: mini_relay
    output: relay_output
    name: "Mini Switch"
    restore_mode: ${light_restore_mode}
    #on_turn_on:
    #  - light.turn_on: led
    #on_turn_off:
    #  - light.turn_off: led

sensor:
  - platform: uptime
    name: "Uptime Sensor"
    id: uptime_sensor
    entity_category: diagnostic
    internal: true

  - platform: wifi_signal
    name: "WiFi Signal dB"
    id: wifi_signal_db
    update_interval: 60s
    entity_category: "diagnostic"

  - platform: copy
    source_id: wifi_signal_db
    name: "WiFi Signal Percent"
    filters:
      - lambda: return min(max(2 * (x + 100.0), 0.0), 100.0);
    unit_of_measurement: "Signal %"
    entity_category: "diagnostic"
    device_class: ""


script:
  - id: hass_light_toggle
    then:
      if:
        condition:
          api.connected:
        then:
          - if:
              condition:
                light.is_off: mini_relay
              then:
                # Turn the relay back on and turn on the light.
                - light.turn_on: mini_relay

                - homeassistant.action:
                    action: light.turn_on
                    data:
                      entity_id: $hass_light
              else:
                # Have Home Assistant toggle the light.
                - homeassistant.action:
                    action: light.toggle
                    data:
                      entity_id: $hass_light
        else:
          # When HA is unavailable, toggle the relay.
          - light.toggle: mini_relay

  - id: hass_light_brightness
    then:
      if:
        condition:
          ?????
        then:
          # Turn the relay back on and turn on the light.
          - light.turn_on: mini_relay

          - homeassistant.action:
              action: light.turn_on
              data:
                entity_id: $hass_light
                brightness: '255'
        else:
          - light.turn_on: mini_relay

          - homeassistant.action:
              action: light.turn_on
              data:
                entity_id: $hass_light
                brightness: '25'

binary_sensor:
  # Wired switch
  - platform: gpio
    id: the_switch
    name: "Power Switch"
    disabled_by_default: true
    pin:
      number: GPIO14
      mode: INPUT_PULLUP
      inverted: true
    #on_state:
    #  - light.toggle: mini_relay
    on_multi_click:
      - timing:
          - ON for at most 0.5s
          - OFF for at most 0.5s
          - ON for at most 0.5s
          - OFF for at least 0.1s
        then:
          - logger.log: "Double clicked"
          - script.execute: hass_light_brightness
      - timing:        
          - ON for at most 0.5s
          - OFF for at least 0.6s
        then:
          - logger.log: "Single click"
          - script.execute: hass_light_toggle
      - timing:
          - ON for at most 0.5s
          - OFF for at most 0.5s
          - ON for at most 0.5s
          - OFF for at most 0.5s
          - ON for at most 0.5s
          - OFF for at most 0.5s
          - ON for at most 0.5s
          - OFF for at most 0.5s
        then:
          - button.press: Reset

  # Button on mini switch
  - platform: gpio
    pin:
      number: GPIO3
      mode: INPUT_PULLUP
      inverted: true
    name: "Power Button"
    disabled_by_default: true
    on_multi_click:
      - timing:
          - ON for at most 1s
          - OFF for at least 0.2s
        then:
          - light.toggle: mini_relay
      - timing:
          - ON for at least 4s
        then:
          - button.press: Reset

  - platform: status
    name: "Status"
    entity_category: diagnostic

text_sensor:
  - platform: wifi_info
    ip_address:
      name: "IP Address"
      entity_category: diagnostic
    ssid:
      name: "Connected SSID"
      entity_category: diagnostic
    mac_address:
      name: "Mac Address"
      entity_category: diagnostic

  #  Creates a sensor showing when the device was last restarted
  - platform: template
    name: 'Last Restart'
    id: device_last_restart
    icon: mdi:clock
    entity_category: diagnostic
#    device_class: timestamp

  #  Creates a sensor of the uptime of the device, in formatted days, hours, minutes and seconds
  - platform: template
    name: "Uptime"
    entity_category: diagnostic
    lambda: |-
      int seconds = (id(uptime_sensor).state);
      int days = seconds / (24 * 3600);
      seconds = seconds % (24 * 3600);
      int hours = seconds / 3600;
      seconds = seconds % 3600;
      int minutes = seconds /  60;
      seconds = seconds % 60;
      if ( days > 3650 ) {
        return { "Starting up" };
      } else if ( days ) {
        return { (String(days) +"d " + String(hours) +"h " + String(minutes) +"m "+ String(seconds) +"s").c_str() };
      } else if ( hours ) {
        return { (String(hours) +"h " + String(minutes) +"m "+ String(seconds) +"s").c_str() };
      } else if ( minutes ) {
        return { (String(minutes) +"m "+ String(seconds) +"s").c_str() };
      } else {
        return { (String(seconds) +"s").c_str() };
      }
    icon: mdi:clock-start

time:
  - platform: sntp
    id: sntp_time
  # Define the timezone of the device
    timezone: "${timezone}"
  # Change sync interval from default 5min to 6 hours (or as set in substitutions)
    update_interval: ${sntp_update_interval}
  # Set specific sntp servers to use
    servers:
      - "${sntp_server_1}"
      - "${sntp_server_2}"
      - "${sntp_server_3}"
  # Publish the time the device was last restarted
    on_time_sync:
      then:
        # Update last restart time, but only once.
        - if:
            condition:
              lambda: 'return id(device_last_restart).state == "";'
            then:
              - text_sensor.template.publish:
                  id: device_last_restart
                  state: !lambda 'return id(sntp_time).now().strftime("%a %d %b %Y - %I:%M:%S %p");'

It is based on the default Athom mini switch configuration, but I implemented changes based on the article Making a dumb light switch smart. In normal case I don’t want the switch to change it’s power but instead controll a ZigBee light. This part works fine.

The thing I can not figure out is how to get the brioghtness of this light and use it as a condition. The script hass_light_brightness is ment for it.

If the light was in esphome I would try with
id(my_light).current_values.get_brightness()
but no idea how you deal with HA light.
What about creating a sensor in HA to present brightness?

Yes, I thought about something like this. But I have no idea how to do it. Maybe creating a helper? I will take a look at it.

You can create a template sensor of the attribute.

template:
  - sensor:
      - name: Light xyz brightness
        state: "{{ state_attr('light.some_light', 'brightness') }}"
        availability: "{{ has_value('light.some_light') }}"
1 Like
sensor:
  - platform: homeassistant
    name: Light HA
    internal: false
    id: current_brightness
    entity_id: light.my_light
    attribute: brightness
2 Likes