muxa / esphome-state-machine

ESPHome State Machine component
MIT License
76 stars 7 forks source link

One state machine model for many instances #36

Closed samturner3 closed 1 year ago

samturner3 commented 1 year ago

Hi,

I have designed a state machine that works well for a light switch with a single gang (1 button, 1 relay with 1 PIR motion sensor etc). However I now want to use this same state machine model for a 3 gang switch (3 buttons, 3 relays etc) each with the same model of state machine, but separate instances (IDs: sm1, sm2, sm3).

In the state machine file I have hardcoded the IDs of lights to turn on/off etc

I can’t figure out how to dynamically import this state machine model 3 times, each instance with different variables. I was wondering if anyone has come across and solved this issue before.

I have posted this question with much more detail and examples on the HA ESPHome community forum, but wanted to post here for visibility as it concerns esphome-state-machine.

muxa commented 1 year ago

One possible solution in state machine is to add support for transition parameters, so when transitions are triggered they have parameters that keeps the state machine configuration generic.

Something like this:

    on_press:
        - state_machine.transition:
            input: TOGGLE
            args:
              - "id(light1)"

state_machine:
  states:
    - name: LIGHT_ON
      on_enter:
        - lambda: "static_cast<LightComponent>(args[0]).toggle()"

This will be quite a bit of work required to support this. I won't be able to spend any time if this in the next several months unfortunately. Happy to review a PR that implements this though :)

muxa commented 1 year ago

Actually, ESPHome supports including files and variable replacements, e.g.:

binary_sensor:
  - platform: gpio
    id: button1
    pin: GPIO16
    on_multi_click: !include { file: on-multi-click.yaml, vars: { id: 1 } } # inline syntax
  - platform: gpio
    id: button2
    pin: GPIO4
    on_multi_click: !include
      # multi-line syntax
      file: on-multi-click.yaml
      vars:
        id: 2

More: https://esphome.io/guides/faq.html