import network
import time
import ujson
import urequests
from machine import Pin, time_pulse_us
# =====================================
# KONFIGURASI WIFI WOKWI
# =====================================
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# GANTI dengan URL Cloudflare Tunnel Anda
API_BASE = "https://motels-ver-lip-loans.trycloudflare.com"
TELEMETRY_URL = API_BASE + "/api/v1/telemetry"
STATUS_URL = API_BASE + "/api/v1/status"
DEVICE_ID = "ESP32_TANDON_01"
# Tinggi efektif tandon dalam cm
TANK_HEIGHT_CM = 100
# Interval pengiriman data
INTERVAL = 1
# =====================================
# PIN ESP32
# =====================================
TRIG = Pin(5, Pin.OUT)
ECHO = Pin(18, Pin.IN)
PUMP_LED = Pin(2, Pin.OUT)
TRIG.value(0)
PUMP_LED.value(0)
# =====================================
# KONEKSI WIFI
# =====================================
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if wlan.isconnected():
print("WiFi sudah terhubung")
return True
print("Menghubungkan ke WiFi Wokwi...")
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
for i in range(30):
if wlan.isconnected():
print("WiFi berhasil terhubung")
print("IP:", wlan.ifconfig()[0])
return True
time.sleep(1)
print("WiFi gagal terhubung")
return False
# =====================================
# MEMBACA HC-SR04
# =====================================
def read_distance():
TRIG.value(0)
time.sleep_us(5)
TRIG.value(1)
time.sleep_us(10)
TRIG.value(0)
try:
duration = time_pulse_us(ECHO, 1, 30000)
if duration <= 0:
print("ECHO timeout:", duration)
return None
distance = duration * 0.0343 / 2
if distance < 2 or distance > 400:
print("Jarak di luar rentang:", distance)
return None
return distance
except Exception as e:
print("Error sensor:", e)
return None
# =====================================
# MENGHITUNG LEVEL AIR
# =====================================
def calculate_level(distance):
# Jarak diukur dari sensor di bagian atas tandon
level = TANK_HEIGHT_CM - distance
if level < 0:
level = 0
if level > TANK_HEIGHT_CM:
level = TANK_HEIGHT_CM
percent = (level / TANK_HEIGHT_CM) * 100
return level, percent
# =====================================
# MENGIRIM TELEMETRY KE FASTAPI
# =====================================
def send_telemetry(distance, level, percent):
payload = {
"device_id": DEVICE_ID,
"distance_cm": round(distance, 2),
"level_cm": round(level, 2),
"level_percent": round(percent, 1),
"sensor_ok": True
}
response = None
try:
print("Mengirim telemetry:", payload)
response = urequests.post(
TELEMETRY_URL,
data=ujson.dumps(payload),
headers={
"Content-Type": "application/json"
}
)
print("Telemetry HTTP:", response.status_code)
print("Respons:", response.text[:300])
return 200 <= response.status_code < 300
except Exception as e:
print("Gagal mengirim telemetry:", repr(e))
return False
finally:
if response is not None:
response.close()
# =====================================
# MEMBACA STATUS POMPA DARI FASTAPI
# =====================================
def read_pump_status():
response = None
try:
response = urequests.get(STATUS_URL)
print("Status HTTP:", response.status_code)
if not 200 <= response.status_code < 300:
print("Gagal membaca status API")
return
data = response.json()
print("Data status:", data)
# Sesuaikan key ini dengan JSON FastAPI Anda
command = data.get(
"pump",
data.get(
"pump_state",
data.get("pump_command", "OFF")
)
)
# Mendukung status berupa teks atau boolean
is_on = (
command is True
or str(command).upper() == "ON"
)
PUMP_LED.value(1 if is_on else 0)
print("Status indikator pompa:",
"ON" if is_on else "OFF")
except Exception as e:
print("Gagal membaca status:", repr(e))
finally:
if response is not None:
response.close()
# =====================================
# PROGRAM UTAMA
# =====================================
print("================================")
print(" BAS TANDON AIR - ESP32 WOKWI")
print("================================")
if connect_wifi():
while True:
try:
distance = read_distance()
if distance is not None:
level, percent = calculate_level(distance)
print("-------------------------------")
print("Jarak air :", round(distance, 2), "cm")
print("Level air :", round(level, 2), "cm")
print("Level :", round(percent, 1), "%")
send_telemetry(
distance,
level,
percent
)
read_pump_status()
else:
print("Data sensor tidak valid")
# Jangan mengirim data palsu ke server
except Exception as e:
print("Error program:", repr(e))
time.sleep(INTERVAL)
else:
print("Periksa koneksi WiFi Wokwi")
Loading
esp32-devkit-c-v4
esp32-devkit-c-v4