import network
import urequests
import ujson
import usocket
import time
from machine import Pin, ADC
# --- Configuration ---
# Use 'Wokwi-GUEST' with a blank password for the emulator
WIFI_SSID = 'Wokwi-GUEST'
WIFI_PASSWORD = ''
WEBHOOK_URL = 'https://discord.com/api/webhooks/1570693892251066378/ljMZaroVNAb31aMFUudeL-e18f6XHtO53ftlV_ATUyoe4BnBLRKf3dmGWLXztyihBEco'
# Pump Timing Configuration (in seconds)
PumpRunTime = 10
PostPumpWaitTime = 5
# --- Safety Variables ---
PumpRunCount = 0
SavedMoisture = -1.0 # Set to -1 so the first loop always registers as a change
MoistureStagnationCount = 0
MoistureBuffer = 200
PumpRunBuffer = 10
SystemHalted = False # Prevents Discord API spam and stops the pump on critical failure
pump_status = "OFF"
# --- Hardware Setup ---
pot = ADC(Pin(34))
pot.atten(ADC.ATTN_11DB)
water_switch = ADC(Pin(35))
water_switch.atten(ADC.ATTN_11DB)
pump = Pin(2, Pin.OUT)
# Physical Override Button on D4 with internal pull-up resistor
override_button = Pin(4, Pin.IN, Pin.PULL_UP)
# --- Wi-Fi Connection ---
print("Connecting to Wi-Fi...", end="")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
timeout = 20
while not wlan.isconnected() and timeout > 0:
time.sleep(0.5)
print(".", end="")
timeout -= 1
if wlan.isconnected():
print("\nWi-Fi Connected!")
print("Network config:", wlan.ifconfig())
else:
print("\nFailed to connect!")
# --- Web Server Setup (Port 80) ---
try:
server_socket = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
server_socket.setsockopt(usocket.SOL_SOCKET, usocket.SO_REUSEADDR, 1)
# Bind to '' (all interfaces) so Wokwi's virtual bridge passes traffic through
server_socket.bind(('', 80))
server_socket.listen(5)
server_socket.settimeout(0.1) # Short timeout to keep the main loop smooth
print("Local Web Server started successfully on port 80")
except Exception as e:
print("Failed to start web server:", e)
# --- State Tracking Flag ---
alert_sent = False
# --- Main Loop ---
while True:
# --- NON-BLOCKING WEB SERVER CHECK ---
try:
conn, addr = server_socket.accept()
print(f"\n[WEB] Connection received from browser: {addr}")
conn.settimeout(2.0)
request = conn.recv(1024)
# HTML Dashboard Response
html = f"""<!DOCTYPE html>
<html>
<head>
<title>Plant Monitor Dashboard</title>
<meta http-equiv="refresh" content="3">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {{ font-family: Arial, sans-serif; text-align: center; margin-top: 30px; background: #f4f4f9; color: #333; }}
.card {{ background: white; padding: 25px; border-radius: 12px; box-shadow: 0px 4px 15px rgba(0,0,0,0.1); display: inline-block; max-width: 350px; width: 100%; }}
h2 {{ color: #2c3e50; margin-bottom: 20px; }}
.metric {{ font-size: 18px; margin: 12px 0; border-bottom: 1px solid #eee; padding-bottom: 8px; text-align: left; display: flex; justify-content: space-between; }}
.status-ok {{ color: #27ae60; font-weight: bold; }}
.status-err {{ color: #c0392b; font-weight: bold; }}
</style>
</head>
<body>
<div class="card">
<h2>Plant System Dashboard</h2>
<div class="metric"><span>Soil Moisture:</span> <strong>{round(moisture_percentage if 'moisture_percentage' in locals() else 0)}%</strong></div>
<div class="metric"><span>Water Tank:</span> <strong>{"Full" if 'WaterPresence' in locals() and WaterPresence == 1 else "Empty"}</strong></div>
<div class="metric"><span>Pump Status:</span> <strong>{pump_status}</strong></div>
<div class="metric"><span>System State:</span> <span class="{'status-err' if SystemHalted else 'status-ok'}">{"HALTED" if SystemHalted else "NORMAL"}</span></div>
<div class="metric"><span>Pump Run Count:</span> <strong>{PumpRunCount} / {PumpRunBuffer}</strong></div>
<div class="metric"><span>Stagnation Count:</span> <strong>{MoistureStagnationCount} / {MoistureBuffer}</strong></div>
</div>
</body>
</html>
"""
conn.send('HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n')
conn.send(html)
conn.close()
print("[WEB] Dashboard sent successfully.")
except OSError:
pass # Expected timeout when no browser is connecting; keeps loop running smoothly
# Read Water Presence first so button logic knows if water is available
switch_analog = water_switch.read()
switch_voltage = (switch_analog / 4095.0) * 3.3
if switch_voltage >= 0.5:
WaterPresence = 1
else:
WaterPresence = 0
# --- PHYSICAL OVERRIDE BUTTON LOGIC (Active-Low) ---
if override_button.value() == 0:
press_start = time.ticks_ms()
while override_button.value() == 0:
if time.ticks_diff(time.ticks_ms(), press_start) >= 2000:
break
time.sleep(0.05)
press_duration = time.ticks_diff(time.ticks_ms(), press_start)
if press_duration >= 2000:
print("\n[MANUAL OVERRIDE] Button held for 2+ seconds. Forcing pump cycle...")
if WaterPresence == 1:
print(f"[PUMP] Manual watering cycle initiated for {PumpRunTime} seconds...")
pump.value(1)
pump_status = "ON"
elapsed_pump_time = 0
while elapsed_pump_time < PumpRunTime:
current_switch_voltage = (water_switch.read() / 4095.0) * 3.3
if current_switch_voltage < 0.5:
print("\n[EMERGENCY STOP] Water tank emptied during manual pumping!")
WaterPresence = 0
break
time.sleep(0.5)
elapsed_pump_time += 0.5
pump.value(0)
pump_status = "OFF"
print("[PUMP] Manual watering cycle finished.")
else:
print("[MANUAL OVERRIDE DENIED] Cannot run pump: Water reservoir is empty!")
else:
print("\n[MANUAL OVERRIDE] Button tapped. Clearing errors and resetting counters...")
SystemHalted = False
PumpRunCount = 0
MoistureStagnationCount = 0
alert_sent = False
SavedMoisture = -1.0
print("[SYSTEM RESET] Errors cleared. Counters reset to 0. Resuming normal operation.")
time.sleep(0.5)
# 1. Read and Calculate Soil Moisture
analog_value = pot.read()
voltage = (analog_value / 4095.0) * 3.3
clamped_voltage = max(1.5, min(3.0, voltage))
moisture_percentage = ((3.0 - clamped_voltage) / (3.0 - 1.5)) * 100
# 2. Standard Low Water Alert Logic
if WaterPresence == 0 and alert_sent == False and not SystemHalted:
print("\n[ALERT] Water is low! Sending Discord notification...")
payload = {"content": "⚠️ **Plant System Alert:** The water reservoir is empty!"}
headers = {'Content-Type': 'application/json'}
try:
urequests.post(WEBHOOK_URL, data=ujson.dumps(payload).encode('utf-8'), headers=headers).close()
alert_sent = True
except Exception as e:
print("Failed to send webhook:", e)
elif WaterPresence == 1 and alert_sent == True:
print("\n[INFO] Water refilled. Resetting alert flag.")
alert_sent = False
# 3. SAFETY FEATURE: Sensor Stagnation Check
if not SystemHalted:
if abs(moisture_percentage - SavedMoisture) < 2.0:
MoistureStagnationCount += 1
else:
SavedMoisture = moisture_percentage
MoistureStagnationCount = 0
if MoistureStagnationCount >= MoistureBuffer:
print("\n[CRITICAL ERROR] Moisture sensor stuck. Halting system.")
payload = {"content": "🚨 **CRITICAL ERROR:** Moisture sensor has stagnated. Check wiring! System Halted."}
headers = {'Content-Type': 'application/json'}
try:
urequests.post(WEBHOOK_URL, data=ujson.dumps(payload).encode('utf-8'), headers=headers).close()
except:
pass
SystemHalted = True
pump.value(0)
pump_status = "HALTED"
# 4. SAFETY FEATURE: Pump & Watering Logic
if moisture_percentage < 50 and WaterPresence == 1 and not SystemHalted:
print("\n[PUMP] Moisture low. Watering plant for up to", PumpRunTime, "seconds...")
pump.value(1)
pump_status = "ON"
elapsed_pump_time = 0
while elapsed_pump_time < PumpRunTime:
current_switch_voltage = (water_switch.read() / 4095.0) * 3.3
print(f"[PUMPING] {elapsed_pump_time} of {PumpRunTime} seconds...")
if current_switch_voltage < 0.5:
print("\n[EMERGENCY STOP] Water tank emptied during pumping!")
WaterPresence = 0
break
time.sleep(0.5)
elapsed_pump_time += 0.5
PumpRunCount += 1
print("[PUMP] Watering phase ended. Pausing for", PostPumpWaitTime, "seconds...")
pump.value(0)
pump_status = "OFF"
time.sleep(PostPumpWaitTime)
if PumpRunCount >= PumpRunBuffer:
print("\n[CRITICAL ERROR] Pump run limit reached without moisture increase. Halting system.")
payload = {"content": "🚨 **CRITICAL ERROR:** Pump triggered 10 times with no soil moisture increase. Check tubing! System Halted."}
headers = {'Content-Type': 'application/json'}
try:
urequests.post(WEBHOOK_URL, data=ujson.dumps(payload).encode('utf-8'), headers=headers).close()
except:
pass
SystemHalted = True
pump_status = "HALTED"
elif moisture_percentage >= 50 and not SystemHalted:
PumpRunCount = 0
pump.value(0)
pump_status = "OFF"
time.sleep(0.5)
elif SystemHalted:
time.sleep(2)
# 5. Terminal Readout
if not SystemHalted:
print("Moisture:", round(moisture_percentage), "% | Stagnation:", MoistureStagnationCount, "| Pump Runs:", PumpRunCount, "| Pump:", pump_status)
else:
print("[SYSTEM HALTED] Waiting for manual reset (Tap button on D4).")