import machine
import dht
import time
import random # Simulated LoRa communication
# ----------------- IA DECISION MODULE -----------------
def ia_decision(temp, hum_air, hum_soil):
"""
Simple rule-based expert system for irrigation decision.
"""
if temp > 35 and hum_air < 50 and hum_soil < 30:
return "Arrosage immédiat"
if temp < 30 and hum_air > 50 and hum_soil > 50:
return "Pas d’arrosage"
if temp > 32 and hum_air < 55 and hum_soil < 40:
return "Arrosage recommandé"
return "Conditions normales — Aucune action"
# ----------------- LORA SIMULATION -----------------
class LoRaSX1278:
"""Simulated LoRa SX1278 module for Wokwi"""
def __init__(self, miso=19, mosi=23, sck=18, nss=5, rst=14, dio0=26):
self.spi = machine.SPI(1, baudrate=5000000, polarity=0, phase=0,
sck=machine.Pin(sck), mosi=machine.Pin(mosi), miso=machine.Pin(miso))
self.nss = machine.Pin(nss, machine.Pin.OUT)
self.rst = machine.Pin(rst, machine.Pin.OUT)
self.dio0 = machine.Pin(dio0, machine.Pin.IN)
self.reset()
print("[LoRa] Module Initialized")
def reset(self):
"""Reset the LoRa module"""
self.rst.value(0)
time.sleep(0.01)
self.rst.value(1)
time.sleep(0.01)
def send(self, message):
"""Simulate sending data over LoRa"""
print(f"[LoRa TX] Sent: {message}")
def recv(self):
"""Simulate receiving data over LoRa"""
if random.random() > 0.2: # 80% chance to receive
return f"{random.uniform(25, 30):.1f},{random.uniform(50, 70):.1f}"
return None
# ----------------- SETUP -----------------
DHT_PIN = 18
sensor = dht.DHT22(machine.Pin(DHT_PIN))
lora = LoRaSX1278()
print("ESP32 LoRa System Ready...")
# ----------------- MAIN LOOP -----------------
while True:
try:
# -------- TRANSMIT DATA --------
sensor.measure()
temp = sensor.temperature()
humidity = sensor.humidity()
data = f"{temp:.1f},{humidity:.1f}"
print("[ESP32 TX] Sending:", data)
lora.send(data)
# -------- RECEIVE DATA --------
received_data = None
for _ in range(5):
received_data = lora.recv()
if received_data:
break
time.sleep(1)
if received_data:
temp, humidity = received_data.split(",")
print(f"[ESP32 RX] Temperature: {temp}°C, Humidity: {humidity}%")
else:
print("[ESP32 RX] No Data Received (After Retries)")
time.sleep(5)
continue
# -------- IA MODULE --------
hum_soil = random.uniform(20, 60) # simulate soil humidity
temp = float(temp)
humidity = float(humidity)
decision = ia_decision(temp, humidity, hum_soil)
print(f"[IA] Temp={temp}°C | Hum Air={humidity}% | Hum Sol={hum_soil:.1f}% → Décision : {decision}")
except Exception as e:
print("Error:", e)
time.sleep(5)