ESP32 --Describes how to request Discord-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.
code | Description | Remarks |
---|---|---|
SSID | Access point SSID | - |
PASS | Access point password | - |
URL | Discord - webhook URL | - |
discord.py
import network
import time
import urequests as requests
# AP
SSID = "XXXXXXXXXXXXX"
PASS = "YYYYYYYYYYYYY"
# discord webhook url
URL = "https://discord.com/api/webhooks/aaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
def do_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect(SSID, PASS)
while not wlan.isconnected():
time.sleep(1)
print('network config:', wlan.ifconfig())
return
def main():
do_connect()
payload = """content=This message is sent by "ESP32"."""
response = requests.post(URL, headers={"Content-Type": "application/x-www-form-urlencoded"}, data=payload)
response.close()
main()
>>> import discord
The above code itself works, but If you add various functions, an OS error (MemoryError) will occur.
It seems to use a lot of memory here because it requires HTTPS communication. I tried various things, but I think that it can be avoided by the following method.
--Create in a single thread --Actively carry out garage collection --Implemented in C language --Change device
Even making each process a thread consumes a lot of memory. Also, in MicroPython, you cannot use Queue etc. If socket communication is used to communicate between threads, this also uses memory. It seems better to make it so that all processing is done in the main loop.
The condition for MicroPython's garbage collection to run is when the free memory is less than a certain value.
Since a large amount of memory is acquired in HTTPS communication, it is safer to actively perform garbage collection immediately before that. You can do this with the code below.
import gc
gc.collect()
Since MicroPython reads and executes files, it has a memory disadvantage unless it is frozen code. With C language, I feel that I can save a little more memory. I've written code like this on FreeRTOS on the same device before, I remember that there was no particular problem.
In the first place, there is a problem in implementing it on 512KByte. The ESP32-WROVER series has 4MByte of RAM. It's easy, but it's annoying because the price goes up.