##########################################################################################
##########################################################################################
# Moes Mains Dimmer
# Mains dimmer 150W single channel - Moes Wi-Fi Dimmer Module
# Module swapped to a ESP-02S module (from a Tuya WB2S) 
#
# V1.0 2025-09-05 First Rev
##########################################################################################
#
# NOTES RE TUYA COMMS FOR THIS MODULE
# - Toggle DP1 (switch) to 1 or 0 for ON or OFF. The dimmer's MCU does the smooth ramp itself over a few seconds.
# - We set DP2 (brightness) on a 0-1000 scale; this is the actual brightness level your firmware uses.
# - We read DP2 back as a sensor (and also show a % view) so we can see the live target the MCU is using.
# - DP3 is exposed only as an optional minimum-brightness limit; not touched during normal dimming unless you tune the low end.
# - It appears that 11 is the lowest DP3 raw value.  Brightness of 1% sets this, and 2% ramps it to 19.
# - 50% brightness is 501, so it is pretty linear (you can't set Gamma, see below - I guess you could script it though)
# - DP4 (mode) exists but left alone (unless you want to experiment with load type/behavior).  I can't see it do anything.  Disabled by default in HA.
# - gamma_correct supposedly remaps the HA slider (no Tuya traffic) BUT it must be set to 1 or weird behaviour (keeps ramping to 0)
# - setting logs to DEBUG will show what is happening with Tuya commands
#
##########################################################################################
##########################################################################################

##########################################################################################
# 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-loungemoesdimmer1"
  friendly_name: "Lounge Lighting Moes Dimmer 1"
  description_comment: "tba"
  device_area: "Lounge" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant.  

  # Project Naming
  project_name: "Generic ESP8266.ESP-02S" # Project Details 
  project_version: "v1.0"  # Project V denotes release of yaml file, allowing checking of deployed vs latest version

  # Passwords & 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-loungemoesdimmer1_ip

  # 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

#########################################################################################
# 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:
  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}"
  common_api: !include
    file: common/api_common.yaml
    vars:
      local_api_key: "${api_key}"
  #common_webportal: !include
  #  file: common/webportal_common.yaml
  common_mqtt: !include
    file: common/mqtt_common.yaml
    vars:
      local_device_name: "${device_name}"
  common_sntp: !include
    file: common/sntp_common.yaml
  common_general_sensors: !include
    file: common/sensors_common.yaml
    vars:
      local_friendly_name: "${friendly_name}"
      local_update_interval: "${update_interval}"

#########################################################################################
# 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}"

#########################################################################################
# ESP Platform and Framework
# https://esphome.io/components/esp32.html
#########################################################################################
esp8266:
  board: esp01_1m
  #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

#########################################################################################    
# 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: yes

#########################################################################################
# UART COMPONENT
# https://esphome.io/components/uart/
#########################################################################################
uart:
  # Needed for the Tuya component.
  # This UART talks to the coprocessing tuya chip
  tx_pin: GPIO1
  rx_pin: GPIO3
  baud_rate: 9600

#########################################################################################
# TUYA MCU COMPONENT
# https://esphome.io/components/tuya/
#########################################################################################
tuya:
  # logger baud_rate must be 0
  id: tuyamcu

##########################################################################################
# LIGHT COMPONENT
# https://esphome.io/components/light/
##########################################################################################
light:
  - platform: tuya
    name: "Lounge Lighting Moes Dimmer 1"
    switch_datapoint: 1          # ON/OFF
    dimmer_datapoint: 2          # <-- CHANGED: brightness is DP2 on your unit
    #min_value_datapoint: 3       # optional; comment this out if it misbehaves
    min_value: 0
    max_value: 1000
    gamma_correct: 1.0
    default_transition_length: 0s

##########################################################################################
# SENSOR COMPONENT
# https://esphome.io/components/sensor/
##########################################################################################
sensor:
  # The raw value sent over the UART 
  # Listed as a dignostic, so will appear with the other diags in HA
  - platform: tuya
    id: dp2_brightness_raw
    name: "Brightness (DP2 raw)"
    sensor_datapoint: 2
    entity_category: diagnostic
  # Raw value as a percentage of max
  - platform: template
    name: "Brightness (%)"
    unit_of_measurement: "%"
    accuracy_decimals: 0
    update_interval: 2s
    lambda: |-
      if (isnan(id(dp2_brightness_raw).state)) return NAN;
      return (id(dp2_brightness_raw).state / 1000.0f) * 100.0f;

##########################################################################################
# SELECT COMPONENT
# https://esphome.io/components/select/
##########################################################################################
select:
  # Experimental
  - platform: tuya
    id: dp4_mode
    name: "DP4 Mode (experiment)"
    enum_datapoint: 4
    options:
      0: "Mode 0"
      1: "Mode 1"
      2: "Mode 2"
      3: "Mode 3"
      4: "Mode 4"
      255: "Default/Unknown"
    entity_category: config
    disabled_by_default: true