#:########################################################################################:#
# TITLE: 6 CHANNEL LOUNGE DMX MAINS DIMMER
# zorruno.com layout v1.1 2026
#:########################################################################################:#
# REPO:
# https://home.fox.co.nz/gitea/zorruno/zorruno-homeassistant/src/branch/master/esphome/esp-lounge6chdimmer.yaml
#:########################################################################################:#
# VERSIONS:
# V1.2 2026-03-04 Updated yaml to zorruno layout V1.1
# V1.1 2025-09-13 Extended to 3 modules and installed
# V1.0 2025-09-06 First Rev (only tested one module, 2 channels at this stage, and incandescent)
#:########################################################################################:#
# HARDWARE:
# - ESP8266 D1 Mini Pro
# - 3 x 2-channel DMX mains dimmer modules (1.2 A per channel)
#   Controller: https://www.aliexpress.com/item/32838426377.html
# - RS-485 TTL converter (MAX485 style)
#   RS-485 TTL converter: https://www.aliexpress.com/item/1005005737922222.html
#
# MAX485 Module (You could also use a MAX3485 which is 3.3 V)
# - MAX485 VCC  -> ESP +5V
# - MAX485 GND  -> ESP GND
# - MAX485 DE   -> ESP +5V
# - MAX485 RE   -> Pullup so can leave unconnected (or +5V) or a designated enable_pin
# - MAX485 DI   -> ESP GPIO2 (ESP8266) or GPIO5 (ESP32)
# - MAX485 A    -> XLR 3 (DMX +)
# - MAX485 B    -> XLR 2 (DMX -)
# - MAX485 GND  -> XLR 1 (DMX GND)
#:########################################################################################:#
# OPERATION NOTES:
# - ESP8266 transmits DMX512 over UART (one-way TX only) via RS-485 adaptor
# - Dimmer modules must be set to DMX mode and assigned a fixed ID (1-999)
# - Incandescent trial notes:
#   - 10% writes ~26 (max 255)
#   - Very low levels may not visibly output below ~15%
# - Using GPIO2 as UART TX on ESP8266 is handy, as the onboard LED flashes with TX
# - Dimmers are smooth and remember values even if DMX data stops transmitting
# - This design assumes mains power is controlled by a smart wall switch:
#   - If networks fail, toggling power restores the dimmer outputs (and this YAML restores channels to ON)
#
# System Settings on Dimmer: (onboard buttons M and < held for 2 secs)
# - Set "1 Channel" (d-1) and both channels output the same level, or "2 Channel" (d-2)
# - Set reverse phase dimming / trailing edge (C-R) or forward / leading edge (C-F)
# - Set minimum brightness on the dimmer, from b01-b40 (b01 gives ~5% min)
# - Set the 3x 8 segment display to automatically turn off (Bon/BoF)
# - Pull both DE and RE high on the 485 converter to ensure data enabled (or wire enable_pin)
#
# Other useful references
# - Arduino DMX Controller: https://www.youtube.com/watch?v=4PjBBBQB2m4
# - ESP32 DMX Contoller with ESPixelstick (errors in his wiring diagram):
#   https://www.youtube.com/watch?v=GWZ63vsKzT8
# - ESPHome DMX512 Custom component used here:
#   https://github.com/andyboeh/esphome-dmx512
#:########################################################################################:#
# MQTT COMMANDS:
# - None (DMX is driven by HA light entities).
#:########################################################################################:#
# OFFLINE NOTES:
# a) Home Assistant OFFLINE (WiFi + network still online):
# - Device continues DMX output at last set levels (dimmers remember output).
#
# b) MQTT OFFLINE (or HA/MQTT offline):
# - No MQTT dependency for operation; last levels remain active.
#
# c) Entire WiFi/Network OFFLINE:
# - Accurate time is not needed (SNTP not needed; no schedules/timeclocks).
# - Wall switch power-cycling restores dimmer module output state (modules remember).
#:########################################################################################:#

#:########################################################################################:#
# SUBSTITUTIONS: Specific device variable substitutions
# If NOT using a secrets file, just replace these with the passwords etc (in quotes)
#:########################################################################################:#
substitutions:
  # Device Naming
  device_name: "esp-lounge6chdimmer"
  friendly_name: "6 Channel Lounge Dimmer"
  description_comment: "Lounge 6 Channel Mains Lighting Dimmer (3 x 2 channel modules) controlled using DMX512 protocol with a D1 Mini Pro (Layout V1.1)"
  device_area: "Lounge" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant.

  # Project Naming
  project_name: "Generic ESP8266.D1 Mini" # Project Details
  project_version: "v1.2"  # Project V denotes release of yaml file, allowing checking of deployed vs latest version

  # Passwords and Secrets
  api_key: !secret esp-api_key # unfortunately you can't use substitutions inside secrets names
  ota_pass: !secret esp-ota_pass # unfortunately you can't use substitutions inside secrets names
  static_ip_address: !secret esp-lounge6chdimmer_ip

  # Layout v1.1 requirement
  current_ip_address: ${static_ip_address}

  # Device Settings
  #relay_icon: "mdi:lightbulb-group"
  log_level: "INFO" # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (Default), VERBOSE, VERY_VERBOSE
  update_interval: "60s" # update time for for general sensors etc

  output_1_name: "Lounge Downlights South"
  output_2_name: "Lounge Rafter Buttons"
  output_3_name: "Lounge Downlights Centre"
  output_4_name: "Dining Table Light"
  output_5_name: "Couch Spots Right"
  output_6_name: "Couch Spots Left"

  # Per-channel minimum output when ON (0.00f..1.00f). OFF remains 0%.
  # Adjust per channel to avoid flicker at very low levels.
  min_output_1: "0.20f"
  min_output_2: "0.20f"
  min_output_3: "0.20f"
  min_output_4: "0.20f"
  min_output_5: "0.10f"
  min_output_6: "0.10f"

  # Per-channel gamma correct
  gamma_output_1: "2.2"
  gamma_output_2: "2.2"
  gamma_output_3: "2.2"
  gamma_output_4: "1"
  gamma_output_5: "2.2"
  gamma_output_6: "2.2"

#:########################################################################################:#
# PACKAGES: Included Common Packages
# https://esphome.io/components/packages.html
# Comment some of these out where not needed, eg MQTT, Web portal, SNTP, General Sensors
#:########################################################################################:#
packages:
  #### WIFI, Network (Static/DHCP/IPV6 etc), Fallback AP, Safemode ####
  common_wifi: !include
    file: common/network_common.yaml
    vars:
      local_device_name: "${device_name}"
      local_static_ip_address: "${static_ip_address}"
      local_ota_pass: "${ota_pass}"
      local_current_ip_address: "${current_ip_address}"

  #### HOME ASSISTANT API (choose encryption or no encryption options) ####
  common_api: !include
    file: common/api_common.yaml
    #file: common/api_common_noencryption.yaml
    vars:
      local_api_key: "${api_key}"

  #### MQTT ####
  common_mqtt: !include
    file: common/mqtt_common.yaml
    vars:
      local_device_name: "${device_name}"

  #### WEB PORTAL ####
  #common_webportal: !include common/webportal_common.yaml

  #### SNTP (Only use if you want/need accurate timeclocks) ####
  common_sntp: !include common/sntp_common.yaml

  #### DIAGNOSTICS Sensors ####
  diag_basic: !include common/include_basic_diag_sensors.yaml
  diag_more: !include common/include_more_diag_sensors.yaml
  diag_debug: !include common/include_debug_diag_sensors.yaml
  #diag_resetcount:  !include common/include_resetcount_diag_sensors.yaml

#:########################################################################################:#
# ESPHOME:
# https://esphome.io/components/esphome.html
#:########################################################################################:#
esphome:
  name: "${device_name}"
  friendly_name: "${friendly_name}"
  comment: "${description_comment}" # Appears on the esphome page in HA
  area: "${device_area}"
  project:
    name: "${project_name}"
    version: "${project_version}"
  on_boot:
    priority: -100
    then:
      - lambda: |-
          id(dmx_ch1_sensor).publish_state(0);
          id(dmx_ch2_sensor).publish_state(0);
          id(dmx_ch3_sensor).publish_state(0);
          id(dmx_ch4_sensor).publish_state(0);
          id(dmx_ch5_sensor).publish_state(0);
          id(dmx_ch6_sensor).publish_state(0);

#:########################################################################################:#
# ESP PLATFORM AND FRAMEWORK:
# https://esphome.io/components/esp8266/
#:########################################################################################:#
esp8266:
  board: d1_mini_pro
  #early_pin_init: false # Initialise pins early to known values. Recommended false where switches are involved. Defaults to true.
  board_flash_mode: dout # Default is dout
  restore_from_flash: true # restore some values on reboot

#:########################################################################################:#
# MDNS:
# https://esphome.io/components/mdns.html
#:########################################################################################:#
mdns:
  disabled: false # Disabling will make the build file smaller (and it is still available via static IP)

#:########################################################################################:#
# LOGGING: ESPHome Logging Enable
# https://esphome.io/components/logger.html
#:########################################################################################:#
logger:
  level: "${log_level}" # INFO Level suggested, or DEBUG for testing
  baud_rate: 0 # set to 0 for no logging via UART, needed if you are using it for other serial things (eg PZEM)
  #esp8266_store_log_strings_in_flash: false
  #tx_buffer_size: 64

#:########################################################################################:#
# STATUS LED:
# https://esphome.io/components/status_led.html
#:########################################################################################:#
#status_led:
#  pin:
#    number: GPIO2
#    inverted: true

#:########################################################################################:#
# UART COMPONENT:
# https://esphome.io/components/uart/
#:########################################################################################:#
uart:
  # Needed for the DMX component.
  # This UART talks to the RS485 adaptor.
  # There is no receiving, it is a one-way send.
  id: uart_bus
  baud_rate: 250000
  tx_pin:
    number: GPIO2 # ESP8266
    allow_other_uses: true # For ESPHome >= 2023.12.0
  stop_bits: 2

#:########################################################################################:#
# LIGHT COMPONENT:
# https://esphome.io/components/light/
#:########################################################################################:#
light:
  - platform: monochromatic
    name: "${output_1_name}"
    output: dmx_1
    id: light_test_1
    default_transition_length: 10s
    gamma_correct: "${gamma_output_1}"
    restore_mode: ALWAYS_ON

  - platform: monochromatic
    name: "${output_2_name}"
    output: dmx_2
    id: light_test_2
    default_transition_length: 10s
    gamma_correct: "${gamma_output_2}"
    restore_mode: ALWAYS_ON

  - platform: monochromatic
    name: "${output_3_name}"
    output: dmx_3
    id: light_test_3
    default_transition_length: 10s
    gamma_correct: "${gamma_output_3}"
    restore_mode: ALWAYS_ON

  - platform: monochromatic
    name: "${output_4_name}"
    output: dmx_4
    id: light_test_4
    default_transition_length: 10s
    gamma_correct: "${gamma_output_4}"
    restore_mode: ALWAYS_ON

  - platform: monochromatic
    name: "${output_5_name}"
    output: dmx_5
    id: light_test_5
    default_transition_length: 3s
    gamma_correct: "${gamma_output_5}"
    restore_mode: RESTORE_DEFAULT_OFF

  - platform: monochromatic
    name: "${output_6_name}"
    output: dmx_6
    id: light_test_6
    default_transition_length: 3s
    gamma_correct: "${gamma_output_6}"
    restore_mode: RESTORE_DEFAULT_OFF

#:########################################################################################:#
# SENSOR COMPONENT:
# https://esphome.io/components/sensor/
#:########################################################################################:#
sensor:
  # Expose each DMX channel's current output level as 0..255 integers
  - platform: template
    id: dmx_ch1_sensor
    name: "${output_1_name} Output"
    icon: mdi:counter
    #entity_category: diagnostic
    accuracy_decimals: 0
    update_interval: never
    filters:
      - throttle: 200ms
      - delta: 1
      - round: 0
      - clamp:
          min_value: 0
          max_value: 255

  - platform: template
    id: dmx_ch2_sensor
    name: "${output_2_name} Output"
    icon: mdi:counter
    #entity_category: diagnostic
    accuracy_decimals: 0
    update_interval: never
    filters:
      - throttle: 200ms
      - delta: 1
      - round: 0
      - clamp:
          min_value: 0
          max_value: 255

  - platform: template
    id: dmx_ch3_sensor
    name: "${output_3_name} Output"
    icon: mdi:counter
    #entity_category: diagnostic
    accuracy_decimals: 0
    update_interval: never
    filters:
      - throttle: 200ms
      - delta: 1
      - round: 0
      - clamp:
          min_value: 0
          max_value: 255

  - platform: template
    id: dmx_ch4_sensor
    name: "${output_4_name} Output"
    icon: mdi:counter
    #entity_category: diagnostic
    accuracy_decimals: 0
    update_interval: never
    filters:
      - throttle: 200ms
      - delta: 1
      - round: 0
      - clamp:
          min_value: 0
          max_value: 255

  - platform: template
    id: dmx_ch5_sensor
    name: "${output_5_name} Output"
    icon: mdi:counter
    #entity_category: diagnostic
    accuracy_decimals: 0
    update_interval: never
    filters:
      - throttle: 200ms
      - delta: 1
      - round: 0
      - clamp:
          min_value: 0
          max_value: 255

  - platform: template
    id: dmx_ch6_sensor
    name: "${output_6_name} Output"
    icon: mdi:counter
    #entity_category: diagnostic
    accuracy_decimals: 0
    update_interval: never
    filters:
      - throttle: 200ms
      - delta: 1
      - round: 0
      - clamp:
          min_value: 0
          max_value: 255

#:########################################################################################:#
# EXTERNAL COMPONENTS:
# https://github.com/andyboeh/esphome-dmx512
#:########################################################################################:#
external_components:
  - source: github://andyboeh/esphome-dmx512

#:########################################################################################:#
# DMX512 COMPONENT:
# https://github.com/andyboeh/esphome-dmx512
#:########################################################################################:#
dmx512:
  id: dmx
  uart_id: uart_bus
  #enable_pin: GPIOXX (Optional, I have wired them to be always active)
  tx_pin:
    number: GPIO2
    allow_other_uses: true # For ESPHome >= 2023.12.0
  uart_num: 1
  periodic_update: true     # optional. Some dimmers may turn off without regular updates.
  #force_full_frames: false  # optional. If true the 513 byte is always sent
  #custom_break_len: 92      # optional. Break Length. Default is 92uS
  #custom_mab_len: 12        # optional. Mark after Break Length. Default is 12mS
  #update_interval: 500      # optional. Custom update interval. Default is 500mS

#:########################################################################################:#
# OUTPUT COMPONENT:
# https://esphome.io/components/output/
#:########################################################################################:#
output:
  # Raw DMX slots (these are the actual DMX universes/slots)
  - platform: dmx512
    channel: 1        # The ID we set the device to
    universe: dmx     # The ID of the DMX512 Component
    id: dmx_1_raw

  - platform: dmx512
    channel: 2        # The ID we set the device to
    universe: dmx     # The ID of the DMX512 Component
    id: dmx_2_raw

  - platform: dmx512
    channel: 3        # The ID we set the device to
    universe: dmx     # The ID of the DMX512 Component
    id: dmx_3_raw

  - platform: dmx512
    channel: 4        # The ID we set the device to
    universe: dmx     # The ID of the DMX512 Component
    id: dmx_4_raw

  - platform: dmx512
    channel: 5        # The ID we set the device to
    universe: dmx     # The ID of the DMX512 Component
    id: dmx_5_raw

  - platform: dmx512
    channel: 6        # The ID we set the device to
    universe: dmx     # The ID of the DMX512 Component
    id: dmx_6_raw

  # Wrapped outputs: publish exact 0..255 to sensors, then forward float to raw DMX
  - platform: template
    id: dmx_1
    type: float
    write_action:
      - lambda: |-
          const float MIN = ${min_output_1};
          float scaled = state;
          if (state > 0.0f) {
            // Remap 0..1 -> MIN..1.0 (keep OFF at 0)
            scaled = state * (1.0f - MIN) + MIN;
          }
          id(dmx_ch1_sensor).publish_state(scaled * 255.0f);
          id(dmx_1_raw).set_level(scaled);

  - platform: template
    id: dmx_2
    type: float
    write_action:
      - lambda: |-
          const float MIN = ${min_output_2};
          float scaled = state;
          if (state > 0.0f) {
            scaled = state * (1.0f - MIN) + MIN;
          }
          id(dmx_ch2_sensor).publish_state(scaled * 255.0f);
          id(dmx_2_raw).set_level(scaled);

  - platform: template
    id: dmx_3
    type: float
    write_action:
      - lambda: |-
          const float MIN = ${min_output_3};
          float scaled = state;
          if (state > 0.0f) {
            scaled = state * (1.0f - MIN) + MIN;
          }
          id(dmx_ch3_sensor).publish_state(scaled * 255.0f);
          id(dmx_3_raw).set_level(scaled);

  - platform: template
    id: dmx_4
    type: float
    write_action:
      - lambda: |-
          const float MIN = ${min_output_4};
          float scaled = state;
          if (state > 0.0f) {
            scaled = state * (1.0f - MIN) + MIN;
          }
          id(dmx_ch4_sensor).publish_state(scaled * 255.0f);
          id(dmx_4_raw).set_level(scaled);

  - platform: template
    id: dmx_5
    type: float
    write_action:
      - lambda: |-
          const float MIN = ${min_output_5};
          float scaled = state;
          if (state > 0.0f) {
            scaled = state * (1.0f - MIN) + MIN;
          }
          id(dmx_ch5_sensor).publish_state(scaled * 255.0f);
          id(dmx_5_raw).set_level(scaled);

  - platform: template
    id: dmx_6
    type: float
    write_action:
      - lambda: |-
          const float MIN = ${min_output_6};
          float scaled = state;
          if (state > 0.0f) {
            scaled = state * (1.0f - MIN) + MIN;
          }
          id(dmx_ch6_sensor).publish_state(scaled * 255.0f);
          id(dmx_6_raw).set_level(scaled);