Dim light with Appdaemon, Deconz and Xiaomi wireless switch

I’ve written a dimming script in appdaemon to change brightness of a deconz light with an Xiaomi wireless switch. A short Click toggles the light. Holding the switch pressed dims or brightens the ligth

import appdaemon.appapi as appapi
import time

class dimming(appapi.AppDaemon):

  def initialize(self):
    self.listen_event(self.button_pressed, "deconz_event", id = "lumisensor_switch" )
    self.table_hold = False
    self.table_dim = False
  def button_pressed(self, event_name, data, kwargs):
    self.click_type=data["event"]
    if self.click_type == 1000:
      if self.table_hold == False or self.get_state("light.table") == "off":
        self.table_pressed = False
        self.toggle("light.table")
      self.table_hold = False
    if self.click_type == 1002:
      self.table_pressed = True
      time.sleep(0.3)
      self.table_hold = True
      if self.table_pressed:
        self.long_press()
        self.table_dim = not self.table_dim
     

  def long_press(self):
    if self.table_dim == False and self.table_hold == True and self.get_state("light.table") == "on":
      while self.table_hold:
        self.new_brightness = self.get_state("light.table", "brightness") + 25
        if self.new_brightness >= 255:
          self.new_brightness = 255
        self.turn_on("light.table", brightness = self.new_brightness)
      self.table_hold = False  

    elif self.table_dim == True and self.table_hold == True and self.get_state("light.table") == "on":
      while self.table_hold:
        self.new_brightness = self.get_state("light.table", "brightness") - 25
        if self.new_brightness <= 0:
          self.new_brightness = 6
        self.turn_on("light.table", brightness = self.new_brightness)
      self.table_hold = False
3 Likes