# Cambridge Audio CXA81 amplifier, controlled over RS-232.
#
# Hardware: M5Stack ATOM Lite (ESP32-PICO-D4) on an Atomic RS232 Base (A136),
# wired to the amplifier's RS-232 port (TX, RX, GND).
#
# Protocol: Cambridge Audio "CXA61 and CXA81 Serial Control Protocol" v1.0 (AP36646).
#   9600 8N1, ASCII, messages are  #gg,nn[,data]\r
#   The amp sends a reply to every command and also announces power, mute and
#   source changes on its own (e.g. from the IR remote), so HA stays in sync.
#   There is no volume command in the protocol.
#
# Volume goes over infrared instead, through a wire into the amp's rear "IR in"
# jack (3.5 mm mono plug: tip = signal, sleeve = ground), driven straight from
# the ATOM's Grove port: G26 -> tip, GND -> sleeve. NO series resistor: with
# 1 kOhm in line the ATOM could not pull the input low enough and the amp
# ignored it. Verified working 2026-11-25: RC-5 with 36 kHz carrier, inverted
# (line idles high, pulled low for each burst).

substitutions:
  name: cxa81
  friendly_name: Amplifier
  # RC-5 codes for the CXA81 remote, recorded from the original remote with a
  # Flipper Zero (address 0x10; volume up 0x10, volume down 0x11).
  ir_address: "0x10"
  ir_volume_up: "0x10"
  ir_volume_down: "0x11"

esphome:
  name: ${name}
  friendly_name: ${friendly_name}
  on_boot:
    priority: -100
    then:
      - script.execute: query_all

esp32:
  board: m5stack-atom
  framework:
    type: esp-idf

logger:
  # The amp's UART is separate; keep the USB serial log for debugging.
  # DEBUG shows every command sent to (TX) and reply from (RX) the amp.
  level: DEBUG

api:
  encryption:
    key: !secret cxa81_api_key
  actions:
    # Called from Home Assistant, e.g. by a scroll wheel:
    # positive steps = louder, negative = quieter.
    - action: volume_step
      variables:
        steps: int
      then:
        - repeat:
            count: !lambda "return std::min<int>(abs(steps), 20);"
            then:
              - if:
                  condition:
                    lambda: "return steps > 0;"
                  then:
                    - script.execute: ir_volume_up
                  else:
                    - script.execute: ir_volume_down
              - script.wait: ir_volume_up
              - script.wait: ir_volume_down

ota:
  # Encrypted with the same key as the API (ESPHome requires them to match).
  - platform: esphome
    encryption: {}

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password
  ap:
    ssid: "CXA81 Fallback"
    password: !secret cxa81_fallback_password

captive_portal:

# Atomic RS232 Base. Pin assignment per M5Stack's example code for this base.
# If the amp never answers, swap tx_pin and rx_pin.
uart:
  id: amp_uart
  tx_pin: GPIO19
  rx_pin: GPIO22
  baud_rate: 9600
  data_bits: 8
  parity: NONE
  stop_bits: 1

globals:
  - id: rx_buf
    type: std::string
    restore_value: no

script:
  - id: amp_send
    mode: queued
    max_runs: 20
    parameters:
      cmd: string
    then:
      - lambda: |-
          std::string msg = cmd + "\r";
          id(amp_uart).write_str(msg.c_str());
          ESP_LOGD("cxa81", "TX %s", cmd.c_str());
      # Give the amp time to answer before the next command.
      - delay: 150ms
  # One volume step = one RC-5 frame, then a short gap so the amp sees
  # separate presses.
  - id: ir_volume_up
    mode: queued
    then:
      - logger.log:
          level: INFO
          tag: cxa81
          format: "IR volume up (RC5 address ${ir_address}, command ${ir_volume_up})"
      - remote_transmitter.transmit_rc5:
          address: ${ir_address}
          command: ${ir_volume_up}
      - delay: 120ms
  - id: ir_volume_down
    mode: queued
    then:
      - logger.log:
          level: INFO
          tag: cxa81
          format: "IR volume down (RC5 address ${ir_address}, command ${ir_volume_down})"
      - remote_transmitter.transmit_rc5:
          address: ${ir_address}
          command: ${ir_volume_down}
      - delay: 120ms
  - id: query_all
    then:
      - script.execute: { id: amp_send, cmd: "#1,01" }   # power
      - script.execute: { id: amp_send, cmd: "#1,03" }   # mute
      - script.execute: { id: amp_send, cmd: "#3,01" }   # source
      - script.execute: { id: amp_send, cmd: "#13,02" }  # firmware

# Read replies, one line per '\r', and update the entities.
interval:
  - interval: 50ms
    then:
      - lambda: |-
          uint8_t c;
          while (id(amp_uart).available() && id(amp_uart).read_byte(&c)) {
            if (c == '\n') continue;
            if (c != '\r') {
              if (id(rx_buf).size() < 64) id(rx_buf).push_back((char) c);
              continue;
            }
            std::string line = id(rx_buf);
            id(rx_buf).clear();
            if (line.empty() || line[0] != '#') continue;
            ESP_LOGD("cxa81", "RX %s", line.c_str());

            // Split "#gg,nn[,data]"
            size_t c1 = line.find(',');
            if (c1 == std::string::npos) continue;
            size_t c2 = line.find(',', c1 + 1);
            int group = atoi(line.substr(1, c1 - 1).c_str());
            int number = atoi(line.substr(c1 + 1, c2 == std::string::npos ? std::string::npos : c2 - c1 - 1).c_str());
            std::string data = c2 == std::string::npos ? "" : line.substr(c2 + 1);

            if (group == 2 && number == 1) {
              id(amp_power).publish_state(data == "1");
            } else if (group == 2 && number == 3) {
              id(amp_mute).publish_state(data == "1");
            } else if (group == 4 && number == 1) {
              int code = atoi(data.c_str());
              const char *name = nullptr;
              switch (code) {
                case 0:  name = "A1"; break;
                case 1:  name = "A2"; break;
                case 2:  name = "A3"; break;
                case 3:  name = "A4"; break;
                case 4:  name = "D1"; break;
                case 5:  name = "D2"; break;
                case 6:  name = "D3"; break;
                case 14: name = "Bluetooth"; break;
                case 16: name = "USB Audio"; break;
                case 20: name = "A1 Balanced"; break;
              }
              if (name != nullptr) id(amp_source).publish_state(name);
              else ESP_LOGW("cxa81", "Unknown source code %s", data.c_str());
            } else if (group == 14 && number == 2) {
              id(amp_firmware).publish_state(data);
            } else if (group == 0) {
              // 01 group unknown, 02 number unknown, 03 data error, 04 not available now
              ESP_LOGW("cxa81", "Amp error %02d for last command", number);
            }
          }

  # Safety net in case an unsolicited update is missed.
  - interval: 60s
    then:
      - script.execute: query_all

switch:
  - platform: template
    id: amp_power
    # Never send anything at boot; the state comes from the amp's replies.
    restore_mode: DISABLED
    name: Power
    icon: mdi:amplifier
    turn_on_action:
      - script.execute: { id: amp_send, cmd: "#1,02,1" }
    turn_off_action:
      - script.execute: { id: amp_send, cmd: "#1,02,0" }

  - platform: template
    id: amp_mute
    # Never send anything at boot; the state comes from the amp's replies.
    restore_mode: DISABLED
    name: Mute
    icon: mdi:volume-off
    turn_on_action:
      - script.execute: { id: amp_send, cmd: "#1,04,1" }
    turn_off_action:
      - script.execute: { id: amp_send, cmd: "#1,04,0" }

select:
  - platform: template
    id: amp_source
    name: Source
    icon: mdi:import
    optimistic: false
    options: ["A1", "A2", "A3", "A4", "D1", "D2", "D3", "Bluetooth", "USB Audio", "A1 Balanced"]
    set_action:
      - lambda: |-
          static const std::map<std::string, std::string> codes = {
            {"A1", "00"}, {"A2", "01"}, {"A3", "02"}, {"A4", "03"},
            {"D1", "04"}, {"D2", "05"}, {"D3", "06"},
            {"Bluetooth", "14"}, {"USB Audio", "16"}, {"A1 Balanced", "20"},
          };
          auto it = codes.find(x);
          if (it != codes.end()) id(amp_send).execute("#3,04," + it->second);

text_sensor:
  - platform: template
    id: amp_firmware
    name: Firmware
    entity_category: diagnostic

# Wired IR into the amp's "IR in" jack (Grove port, G26, no resistor).
# Tested on the CXA81 without the resistor: inverted + 36 kHz carrier works
# (the RC-5 action sets the carrier frequency). Other formats were only tried
# while the resistor was still fitted, so they are untested.
remote_transmitter:
  id: ir_tx
  pin:
    number: GPIO26
    inverted: true
  carrier_duty_percent: 50%
  non_blocking: true

button:
  - platform: template
    name: Volume up
    icon: mdi:volume-plus
    on_press:
      - script.execute: ir_volume_up
  - platform: template
    name: Volume down
    icon: mdi:volume-minus
    on_press:
      - script.execute: ir_volume_down
  - platform: template
    name: Refresh state
    entity_category: diagnostic
    on_press:
      - script.execute: query_all

sensor:
  - platform: wifi_signal
    name: WiFi signal
    update_interval: 60s

# ATOM Lite onboard RGB LED (SK6812) and button.
light:
  - platform: esp32_rmt_led_strip
    id: status_led
    name: Status LED
    pin: GPIO27
    num_leds: 1
    chipset: SK6812
    channel_colors: GRB
    entity_category: config

binary_sensor:
  # Pressing the ATOM's button toggles the amp's power.
  - platform: gpio
    pin:
      number: GPIO39
      inverted: true
    name: Button
    entity_category: diagnostic
    on_press:
      - switch.toggle: amp_power
