import network
import urequests
import time
import ujson
import gc
SSID = "Wokwi-GUEST"
PASSWORD = ""
WEBHOOK_URL = "https://omari-uncollegiate-hang.ngrok-free.dev/crypto"
coins = ["BTCUSDT","ETHUSDT","SOLUSDT"]
# -------------------
# WIFI
# -------------------
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Connecting WiFi...")
wlan.connect(SSID, PASSWORD)
while not wlan.isconnected():
time.sleep(1)
print("WiFi Connected:", wlan.ifconfig())
return wlan
# -------------------
# Send Webhook
# -------------------
def send(msg):
try:
print("Sending:", msg)
payload = ujson.dumps({
"msg": msg
})
headers = {
"Content-Type": "application/json"
}
r = urequests.post(
WEBHOOK_URL,
data=payload,
headers=headers
)
print("Server:", r.status_code)
r.close()
except Exception as e:
print("Webhook error:", e)
# -------------------
# Get Crypto Price
# -------------------
def get_price(symbol):
try:
url = "https://api.binance.com/api/v3/ticker/price?symbol=" + symbol
r = urequests.get(url)
data = r.json()
r.close()
return data["price"]
except Exception as e:
print("Price error:", e)
return None
# -------------------
# MAIN
# -------------------
wifi = connect_wifi()
send("🚀 ESP32 Crypto Alert Started")
while True:
try:
if not wifi.isconnected():
print("WiFi reconnecting...")
wifi = connect_wifi()
print("Free RAM:", gc.mem_free())
for coin in coins:
print("Checking:", coin)
price = get_price(coin)
if price:
msg = coin + " : " + price
send(msg)
gc.collect()
time.sleep(3)
except Exception as e:
print("Loop error:", e)
time.sleep(60)