ESP8266 newbie, button and HA

Hello HA lovers,
I came to HA after starting hack a Chinese smart plug called Kankun, after that I discovered this wonderful platform and now my smart plug (and a lot of other smart-things) are happily integrated in it.
When I was using my smart plug as standalone I built a nice Wi-Fi connected push button to control the plug (more info here). The button is built using an ESP8266 and it’s pretty simple, when it’s pressed the following code is fired (more details here httpget.lua):

 conn:send("GET /cgi-bin/relay.cgi?"
  .."toggle"
  .." HTTP/1.1\r\n" 
   .."Connection: close\r\n"
  .."Accept: */*\r\n" 
  .."User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\r\n" 
  .."\r\n")
 end)

It basically sends a command to a script (relay.cgi) which is host into the smartplug and which toggles the switch.

SO… my question is: I would like to use the same concept to toggle a switch (or whatever) through the HA api, basically the same thing that Bruh did for the Amazon Dash button using these lines of code:

{"buttons":[  {
"name": "Your Name",
"address": "your:dash:mac:XX:XX:XX",
"url": "http://your.ha.ip.adderss:8123/api/services/switch/toggle",
"method": "POST",
"headers": {"x-ha-access": "your_password"},
"json": true,
"body": {"entity_id": "switch.megadesk_leds"}  }]}

Since I’m a total newbie and just an amateur when we talk a about coding, can someone help me in modifying the httpget.lua to interact with the HA api?

Thanks a lot to everyone who had the patience to read all my post :slight_smile:

I never wrote lua and won’t be able to give you a specific answer, but here are some advices.

First, when I write code on embedded devices to interact with HA, I like to reduce the need to change code on the device to the strict minimum I can achieve. In order to do this, instead of calling the toggle service directly, the devices are only sending events. I write an automation (either with HA or AppDaemon) to actually do something: I can change the behavior easily if needed.

In order to send an event to HA, you’ll need a request looking like this: POST /api/events/<event_type>. You’ll also need to add the HA password.

From your lua code, I guess something like this should work (remember I never wrote lua and can’t test this):

 conn:send("POST /api/events/plug_remote_pressed?api_password=yourhapassword"
  .." HTTP/1.1\r\n" 
  .."Connection: close\r\n"
  .."Accept: */*\r\n" 
  .."User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\r\n" 
  .."\r\n")
 end)

You can probably send the password as a header, but I don’t know the syntax :slight_smile:

Then you’ll had to write an automation reacting to the event plug_remote_pressed.

2 Likes

Thanks a lot @kernald! The approach that you suggested is really clever, it’s really tricky to re-program the super tiny esp8266 boards, especially after they are embedded into a device. I tried your code and it works! Brilliant! :grinning: