import network
import time
import urequests
from machine import Pin
import dht
from umqtt_simple import MQTTClient
# Initialize components
dht_sensor = dht.DHT22(Pin(28))
red_led = Pin(0, Pin.OUT)
# WiFi credentials for Wokwi simulation
SSID = "Wokwi-GUEST"
PASSWORD = ""
# ThingSpeak API configuration
THINGSPEAK_API_KEY = "4I753E4DZLSUVEF8"
Channel_ID = 3497764
URL = "http://api.thingspeak.com/update"
# --- MQTT Cloud Configuration (HiveMQ) ---
MQTT_BROKER = "a23483c32a494c009e64526fff6b8fff.s1.eu.hivemq.cloud"
MQTT_PORT = 8883
MQTT_USER = "alaamohammed"
MQTT_PASSWORD = "123456@20"
MQTT_TOPIC = b"pico/dht22_data"
# Connect to WiFi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
print("Connecting to WiFi.....")
while not wlan.isconnected():
time.sleep(0.5)
print("Connected to WiFi!")
# Connect to HiveMQ Cloud Broker via MQTT (Secure SSL)
client = MQTTClient(
client_id="pico_dht_client_cloud",
server=MQTT_BROKER,
port=MQTT_PORT,
user=MQTT_USER,
password=MQTT_PASSWORD,
ssl=True,
ssl_params={'server_hostname': MQTT_BROKER}
)
try:
client.connect()
print("Connected to HiveMQ Cloud Broker!")
except Exception as e:
print("MQTT Connection failed:", e)
# Main loop
while True:
try:
# Read temperature and humidity from DHT22
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
print(f"Temperature: {temp}°C | Humidity: {hum}%")
# Turn LED ON if temperature is above 40°C, otherwise OFF
if temp > 40:
red_led.value(1)
print("Status: High Temperature! LED ON")
else:
red_led.value(0)
print("Status: Temperature Normal. LED OFF")
# 1. Send data to ThingSpeak via HTTP GET request
request_url = f"{URL}?api_key={THINGSPEAK_API_KEY}&field1={temp}&field2={hum}"
response = urequests.get(request_url)
print("ThingSpeak Response:", response.text)
response.close()
# 2. Send data to Node-RED via HiveMQ Cloud MQTT
try:
payload = f'{{ "temperature": {temp}, "humidity": {hum} }}'
client.publish(MQTT_TOPIC, payload)
print("MQTT Sent to HiveMQ Cloud:", payload)
except Exception as e:
print("MQTT Publish Error:", e)
except Exception as e:
print("Error:", e)
# ThingSpeak requires a 15-second delay between updates
time.sleep(15)
# //THE SAME PROJECT BUT WITH PASPBERR PI4 AND PTHON
# import time
# import logging
# import requests
# from gpiozero import LED
# import Adafruit_DHT
# # إعداد نوع الحساس ورقم طرف GPIO المتصل به (مثلاً GPIO 26 أو حسب توصيلك)
# DHT_SENSOR = Adafruit_DHT.DHT22
# DHT_PIN = 26 # رقم الـ GPIO (Broadcom numbering)
# # إعداد الليد باستخدام مكتبة gpiozero الحديثة على طرف GPIO 17
# red_led = LED(17)
# # إعدادات ThingSpeak
# THINGSPEAK_API_KEY = "4I753E4DZLSUVEF8"
# URL = "http://api.thingspeak.com/update"
# TEMP_THRESHOLD = 40.0
# # إعداد نظام التسجيل (Logging) لتتبع الحالة والأخطاء بشكل احترافي
# logging.basicConfig(
# level=logging.INFO,
# format='%(asctime)s - %(levelname)s - %(message)s'
# )
# class RaspberryPiMonitor:
# def __init__(self, api_key, url, threshold):
# self.api_key = api_key
# self.url = url
# self.threshold = threshold
# def fetch_sensor_data(self):
# """قراءة البيانات الحقيقية من حساس DHT22 عبر Raspberry Pi"""
# humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
# return temperature, humidity
# def manage_hardware(self, temp):
# """التحكم في الأجهزة الملحقة بناءً على درجة الحرارة"""
# if temp is not None:
# if temp > self.threshold:
# red_led.on()
# logging.warning(f"High Temperature Alert! ({temp}°C) -> LED ON")
# else:
# red_led.off()
# logging.info(f"Temperature Normal ({temp}°C) -> LED OFF")
# else:
# logging.error("Failed to retrieve data from sensor")
# def upload_to_thingspeak(self, temp, hum):
# """رفع البيانات إلى منصة ThingSpeak عبر بروتوكول HTTP"""
# if temp is not None and hum is not None:
# try:
# payload = {
# 'api_key': self.api_key,
# 'field1': temp,
# 'field2': hum
# }
# response = requests.get(self.url, params=payload, timeout=10)
# if response.status_code == 200:
# logging.info(f"ThingSpeak Response Success: {response.text.strip()}")
# else:
# logging.error(f"Failed to send data. Status code: {response.status_code}")
# response.close()
# except requests.exceptions.RequestException as e:
# logging.error(f"Network error occurred: {e}")
# def run(self):
# """حلقة التشغيل الرئيسية للمراقبة"""
# logging.info("Starting Raspberry Pi 4 Environmental Monitoring System...")
# while True:
# try:
# # 1. قراءة الحساس
# temp, hum = self.fetch_sensor_data()
# if temp is not None and hum is not None:
# logging.info(f"Temperature: {temp}°C | Humidity: {hum}%")
# # 2. تشغيل أو إيقاف الأجهزة
# self.manage_hardware(temp)
# # 3. الإرسال إلى السحابة
# self.upload_to_thingspeak(temp, hum)
# else:
# logging.warning("Sensor reading error. Retrying in next cycle...")
# except Exception as e:
# logging.critical(f"Unexpected error in main loop: {e}")
# # ThingSpeak يتطلب فاصل زمني لا يقل عن 15 ثانية بين التحديثات
# time.sleep(15)
# if __name__ == "__main__":
# monitor = RaspberryPiMonitor(
# api_key=THINGSPEAK_API_KEY,
# url=URL,
# threshold=TEMP_THRESHOLD
# )
# try:
# monitor.run()
# except KeyboardInterrupt:
# # إيقاف آمن لليد عند الخروج من البرامج
# red_led.off()
# logging.info("Program stopped safely by user.")