ESP32 --Describes how to request IFTTT-Webhooks using MicroPython. 
The following is the confirmed environment.
--Host PC
| item | Model name | Remarks | 
|---|---|---|
| ESP32-WROOM-32 Development board | [NodeMCU-32S ESP32-WROOM-32] | 
The code that has been confirmed to work is as follows.
ファイル名:sample_ifttt.py
import urequests as requests
import time
SSID = "xxxxxxxxx"  #Access point SSID
PASSWORD = "xxxxxxxxx" #Access point password
MY_KEY = "xxxxxxxxx" #IFTTT - webhooks -Specify token
EVENT_ID = "xxxxxxxxx" #Specify the event name of the registered webhooks
def do_connect():
    import network
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect(SSID, PASSWORD)
        while not wlan.isconnected():
            pass
            time.sleep(1)
    print('network config:', wlan.ifconfig())
# IFTTT_Webhook
def ifttt_webhook(eventid):
    #Information to put on value
    payload = "value1="
    payload += "dummy1"
    payload += "&value2="
    payload += "dummy2"
    payload += "&value3="
    payload += "dummy3"
    url = "http://maker.ifttt.com/trigger/" + eventid + "/with/key/" + MY_KEY
    response = requests.post(url, headers={"Content-Type": "application/x-www-form-urlencoded"}, data=payload)
    #If you do not need to specify the value, click ↓ to ok
    # response = requests.post(url)
    response.close()
#Connect to wifi
do_connect()
# ifttt-Trigger to webhooks
ifttt_webhook(EVENT_ID)
>>> import sample_ifttt
→ Confirm that the event specified in the code is called
This was the most addictive.
Previously, I wrote the code to make a request to IFTTT in Python 3.7 as follows. ..
import requests
def ifttt_webhook(eventid, values):
    payload = {"value1": "",
                "value2": "",
                "value3": "" }
    payload["value1"] = values[0]
    payload["value2"] = values[1]
    payload["value3"] = values[2]
    url = "https://maker.ifttt.com/trigger/" + eventid + "/with/key/" + my_key
    print(url)
    response = requests.post(url, data=payload)
If you write this as it is in MicroPython, it will not cause an error, but the value will not be applied.
When I checked the code of urequests, I felt that it would be useless if I did not specify it with json.
So, I specified json, but in urequests, the header is passed in fixed characters, "Content-Type: application/x-www-form-urlencoded" I found that it didn't work.
So, specify headers and data respectively, I applied it to value.
Recommended Posts