Mixing sensors in Custom Component

I’m working on a custom component for a rotary encoder: the M5Stack Faces Encoder. You can both press the knob like a button and turn the know. Actually I have it working with 2 “Sensors”:

  1. Turning the know in- or decreases a value and returns it
  2. Pushing the button returns a 1 when pressed and 0 when released

So far so good. Now I would like to make the button a Binary Sensor. Changed the button to a binary sensor and changed all the integers to bools.

Small parts of the C++ code:

BinarySensor *button_sensor = new BinarySensor();
Sensor *encoder_sensor = new Sensor();

bool button;
int encoder;

Wire.requestFrom(I2C_ADDR_FACESENCODER, 3);

if (Wire.available())
{
    encoder = Wire.read();
    button = Wire.read(); //returns either 0 or 1
}

button_sensor->publish_state(button);
encoder_sensor->publish_state(encoder);

My C++ compiles just fine. The problem is that I don’t know how to add both these sensors to the YAML.

When both were just normal sensors returning a integer I had this:

sensor:
  - platform: custom
    lambda: |-
      auto m5encoder = new M5RotaryEncoder();
      App.register_component(m5encoder);
      return {m5encoder->button_sensor, m5encoder->encoder_sensor};
    sensors:
    - name: ${friendly_name} Button
    - name: ${friendly_name} Encoder

Again, this was working fine until I decided to make the button a binary sensor. I tried a few different YAML configs, but none were working. One of the configs that validates and compiles just fine is this:

sensor:
  - platform: custom
    lambda: |-
      auto m5encoder = new M5RotaryEncoder();
      App.register_component(m5encoder);
      return {m5encoder->encoder_sensor};
    sensors:
    - name: ${friendly_name} Encoder

binary_sensor:
  - platform: custom
    lambda: |-
      auto m5encoder = new M5RotaryEncoder();
      App.register_component(m5encoder);
      return {m5encoder->button_sensor};
    binary_sensors:
    - name: ${friendly_name} Button

Now this clearly does not work as it starts the loop to read the same I2C address twice.

Any idea if it’s possible to mix 2 types of sensors in a single ESPHome component class?

If you get no response here try asking on the ESPHome dev’s discord: https://discord.gg/bQPxgK

1 Like