import network
import time
import urequests
from machine import Pin
# =====================================
# KONFIGURASI WIFI WOKWI
# =====================================
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# Ganti dengan URL Cloudflare Tunnel Anda
API_BASE = "https://motels-ver-lip-loans.trycloudflare.com"
STATUS_URL = API_BASE + "/api/v1/status"
# LED internal ESP32
# Umumnya GPIO 2 pada board ESP32 di Wokwi
led = Pin(2, Pin.OUT)
led.off()
POLL_INTERVAL = 1
# =====================================
# KONEKSI WIFI
# =====================================
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if wlan.isconnected():
print("WiFi sudah terhubung")
return wlan
print("Menghubungkan ke WiFi...")
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
start = time.time()
while not wlan.isconnected():
if time.time() - start > 20:
print("Koneksi WiFi gagal")
return None
time.sleep(1)
print("WiFi terhubung")
print("IP ESP32:", wlan.ifconfig()[0])
return wlan
# =====================================
# MEMPROSES PERINTAH GESTURE
# =====================================
def process_command(data):
if not isinstance(data, dict):
print("Format JSON tidak valid")
return
# Membaca status pompa dari FastAPI
pump = data.get("pump")
if isinstance(pump, str):
pump = pump.upper().strip()
if pump == "ON":
led.on()
print("STATUS POMPA ON -> LED INTERNAL MENYALA")
elif pump == "OFF":
led.off()
print("STATUS POMPA OFF -> LED INTERNAL MATI")
else:
print("Status pompa tidak dikenal:", pump)
else:
print("Field pump tidak ditemukan dalam JSON")
# =====================================
# MEMBACA FASTAPI
# =====================================
def read_command():
response = None
try:
response = urequests.get(STATUS_URL)
if response.status_code == 200:
data = response.json()
print("Data API:", data)
process_command(data)
else:
print("HTTP status:", response.status_code)
except Exception as error:
print("Gagal membaca API:", error)
finally:
if response is not None:
response.close()
# =====================================
# PROGRAM UTAMA
# =====================================
print("================================")
print(" ESP32 HAND GESTURE LED CONTROL")
print("================================")
wlan = connect_wifi()
if wlan is None:
print("Periksa koneksi WiFi")
else:
while True:
if not wlan.isconnected():
print("WiFi terputus, mencoba ulang...")
wlan = connect_wifi()
if wlan is None:
led.off()
time.sleep(3)
continue
read_command()
time.sleep(POLL_INTERVAL)
Loading
esp32-devkit-c-v4
esp32-devkit-c-v4