---
substitutions:
  device: can-node-1
  name: CAN Node 1
  area: DEV
  comment: CANopen

esphome:
  name: mcu-${device}
  friendly_name: ${name}
  area: ${area}
  comment: ${comment}

esp32:
  variant: esp32
  toolchain: esp-idf
  framework:
    type: esp-idf

external_components:
  - source: github://mrk-its/esphome-canopen@dev
    refresh: 1h
  - source: github://mrk-its/esphome-canbus-udp-multicast@dev
    refresh: 1h

packages:
  common: !include common/common.yaml

canbus:
  - platform: esp32_can
    id: can_bus
    rx_pin: 22
    tx_pin: 23
    can_id: 1
    bit_rate: 500kbps

canopen:
  id: can_open
  canbus_id: can_bus
  node_id: 1
  entities:
    - index: 1
      id: light1_state
      rpdo:
        - node_id: 2
          tpdo: 0
          offset: 0
          cmd: 0

    - index: 2
      id: light1_brightness
      size: 1
      min_value: 0.0
      max_value: 1.0
      rpdo:
        - node_id: 2
          tpdo: 0
          offset: 1
          cmd: 0

    - index: 3
      id: light2_state
      rpdo:
        - node_id: 2
          tpdo: 0
          offset: 3
          cmd: 0

    - index: 4
      id: light2_brightness
      size: 1
      min_value: 0.0
      max_value: 1.0
      rpdo:
        - node_id: 2
          tpdo: 0
          offset: 4
          cmd: 0

binary_sensor:
  - platform: template
    id: light1_state
    name: Light 1 State
  - platform: template
    id: light2_state
    name: Light 2 State

  - platform: template
    id: light1_state_cmd

  - platform: gpio
    name: Boot
    id: boot_button
    pin:
      number: 0
      inverted: true
      mode:
        input: true
        pullup: true
    on_press:
      then:
        - lambda: |-
            bool state = id(light1_state).state || id(light2_state).state;

            // send command to entity #1 (light) on node #2
            id(can_open).send_entity_cmd(2, 1, !state);

            // send command to entity #2 (light2) on node #2
            id(can_open).send_entity_cmd(2, 2, !state);

sensor:
  - platform: template
    id: light1_brightness
    name: Light 1 Brightness
  - platform: template
    id: light2_brightness
    name: Light 2 Brightness

switch:
  - platform: gpio
    name: LED
    id: blue_led
    internal: true
    pin: 2
