import network
import urequests
import ujson
import dht
import time
from machine import Pin, PWM
# ─── Konfigurasi WiFi & Firebase ─────────────────────────────────
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# URL Firebase langsung ke node, tanpa slash ganda
FIREBASE_URL = "https://iotp3cloud-default-rtdb.asia-southeast1.firebasedatabase.app/monitoring-fog.json"
# ─── Pin konfigurasi ─────────────────────────────────────────────
PIN_DHT = 4
PIN_LED_R = 16
PIN_LED_G = 17
PIN_BUZZER = 18
# ─── Konstanta fog logic ─────────────────────────────────────────
TEMP_THRESHOLD = 35.0
READ_INTERVAL = 1 # detik
CLOUD_INTERVAL = 10 # detik
AVG_WINDOW = 10
# ─── Inisialisasi hardware ───────────────────────────────────────
sensor = dht.DHT22(Pin(PIN_DHT))
led_alarm = Pin(PIN_LED_R, Pin.OUT)
led_ok = Pin(PIN_LED_G, Pin.OUT)
buzzer = PWM(Pin(PIN_BUZZER), freq=1000, duty=0)
# ─── Buffer ──────────────────────────────────────────────────────
temp_buffer = []
hum_buffer = []
read_count = 0
# ═════════════════════════════════════════════════════════════════
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if wlan.isconnected():
print("[WiFi] Sudah terhubung:", wlan.ifconfig()[0])
return
print("[WiFi] Menghubungkan ke", WIFI_SSID, "...")
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
batas = 20
while not wlan.isconnected() and batas > 0:
time.sleep(1)
batas -= 1
print(" tunggu...", 20 - batas, "detik")
if wlan.isconnected():
print("[WiFi] Terhubung! IP:", wlan.ifconfig()[0])
else:
print("[WiFi] GAGAL terhubung - lanjut tanpa cloud")
def buzzer_beep():
buzzer.duty(512)
time.sleep_ms(200)
buzzer.duty(0)
def set_alarm(active):
if active:
led_alarm.value(1)
led_ok.value(0)
buzzer_beep()
else:
led_alarm.value(0)
led_ok.value(1)
def hitung_rata(lst):
if not lst:
return 0.0
return round(sum(lst) / len(lst), 2)
def send_to_firebase(avg_t, avg_h, latest_t, alarm):
payload = ujson.dumps({
"suhu_rata" : avg_t,
"humidity_rata" : avg_h,
"suhu_terkini" : latest_t,
"status_alarm" : alarm,
"jumlah_baca" : read_count,
"uptime_detik" : time.ticks_ms() // 1000
})
try:
resp = urequests.put(
FIREBASE_URL,
data=payload,
headers={"Content-Type": "application/json"}
)
print("[Firebase] Status:", resp.status_code)
resp.close()
except Exception as e:
print("[Firebase] Gagal:", e)
# ═════════════════════════════════════════════════════════════════
def main():
global read_count
# Status awal
led_ok.value(1)
led_alarm.value(0)
print("=" * 44)
print(" Simulasi Fog Computing - MicroPython")
print("=" * 44)
print("Layer IoT : DHT22 baca tiap", READ_INTERVAL, "detik")
print("Layer Fog : ESP32 proses lokal")
print("Layer Cloud : Firebase update tiap", CLOUD_INTERVAL, "detik")
print("Batas alarm : suhu >", TEMP_THRESHOLD, "C")
print("-" * 44)
connect_wifi()
print("\n[System] Mulai loop utama...\n")
last_cloud_time = time.time()
while True:
loop_start = time.ticks_ms()
# ── Layer IoT: baca sensor ────────────────────────────
try:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
except OSError as e:
print("[Sensor] Error baca DHT22:", e)
time.sleep_ms(1000)
continue
read_count += 1
# ── Layer Fog: simpan buffer ──────────────────────────
temp_buffer.append(temp)
hum_buffer.append(hum)
if len(temp_buffer) > AVG_WINDOW:
temp_buffer.pop(0)
hum_buffer.pop(0)
# ── Layer Fog: keputusan lokal (tanpa cloud) ──────────
alarm = temp > TEMP_THRESHOLD
set_alarm(alarm)
status = "!! ALARM !!" if alarm else "Normal"
print("[#" + ("00" + str(read_count))[-3:] + "]",
"Suhu:", str(temp) + "C",
" Hum:", str(hum) + "%",
" Status:", status,
" Buf:", str(len(temp_buffer)) + "/" + str(AVG_WINDOW))
# ── Layer Cloud: kirim ke Firebase tiap 10 detik ─────
now = time.time()
if (now - last_cloud_time) >= CLOUD_INTERVAL:
last_cloud_time = now
avg_t = hitung_rata(temp_buffer)
avg_h = hitung_rata(hum_buffer)
print("\n[FOG->CLOUD] Kirim agregat ke Firebase...")
print(" avg suhu :", avg_t, "C")
print(" avg hum :", avg_h, "%")
print(" alarm :", alarm)
send_to_firebase(avg_t, avg_h, temp, alarm)
print()
# ── Jaga timing 1 detik ───────────────────────────────
elapsed = time.ticks_diff(time.ticks_ms(), loop_start)
sleep_ms = max(0, READ_INTERVAL * 1000 - elapsed)
time.sleep_ms(sleep_ms)
main()