How do I run an ESPHome script from Home Assistant?

Yes, the esp device is allowed to make service calls.
In “Entities”, the script does not appear, nor when trying to build an automation.

Here is the script in ESPHome:

  - id: toggle_play
    then:
      - switch.turn_on: ${device_name}_start
      - delay: 10ms
      - switch.turn_off: ${device_name}_start

I am sure I have overlooked something simple, but nothing comes to mind.

Here is the switch that the script is supposed to control:

switch:
  - platform: gpio
    name: ${device_name} start
    id: ${device_name}_start
    pin: GPIO12

Any help would be appreciated.

I usually create a button to run the script.

HA:

action: button.press
target:
  entity_id: button.abrir_garagem
data: {}

1 Like

By referring to the documentation.

Using a button, switch, select, etc… like mentioned already, they work just as well and are sometimes the better option to use.

1 Like

I can run the ESPHome script from a button in ESPHome. But that was not the question.

I want to run the script from an automation in Home Assistant.

The Native API docs go the other way, running a Home Assistant action from ESPHome, but I need to go the other way.

Never mind- I found the missing piece, but thanks for the feedback.

api:
  services:
    - service: toggle_play
      variables: {}
      then:
        - script.execute: toggle_play

This exposes the sensor to Home Assistant as

esphome.sound_sensor_toggle_play
2 Likes

I believe you didn’t understand my answer.
After creating the button to run the script in esphome, you call the press button action in your automation in home assistant.

But I’m glad you found another way.

Thanks again.
I tried this but the button on the ESPHome configuration isn’t anywhere to be found.

Thanks for this Steve, this is what I have been searching for too…

Initially I assumed that this was below the api: section in the esphome code, as follows

api:
  encryption:
    key: "xxxx"

  services:
    - service: confirmation_beep
      variables: {}
      then:
        - script.execute: confirmation_beep

however has not resulted in any entity being published in HA, so assume this is not correct or should be injected into HA (somehow this does not appear to be correct)

please let me know where in the HA or ESP code you placed this code so that this script is exposed…

thanks in advance

Note that what walberjunior suggested is still the most logical way. The solution for the OP provided is creating a service in the esp, define an api call in HA to trigger it, define a button in HA and create an automation for it to call the api.

What walberjunior suggested was: define a button in the esp to do what you need. That is all. Because the esp button gets exposed to HA, you will see the button there. You can use it there the way you use any other button.