import network
import time
import json
import dht
from machine import Pin, PWM
from umqtt import MQTTClient
# -------------------------------
# WiFi Configuration
# -------------------------------
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASS = ""
# -------------------------------
# MQTT Configuration
# -------------------------------
MQTT_BROKER = "broker.hivemq.com"
CLIENT_ID = "LokeshNaik_128"
TOPIC_PUB = b"smartfactory/node1/data"
TOPIC_SUB = b"smartfactory/node1/control"
# -------------------------------
# Hardware Setup
# -------------------------------
sensor = dht.DHT22(Pin(15))
servo = PWM(Pin(16)) # Servo / Fan control
servo.freq(50) # 50Hz for servo
led = Pin(14, Pin.OUT) # Status LED
buzzer = PWM(Pin(13)) # Alarm buzzer
buzzer.freq(1000)
# -------------------------------
# Servo Control Function
# -------------------------------
def set_servo(angle):
angle = max(0, min(180, angle))
duty = int(1638 + (angle / 180) * 6553) # Correct Pico servo mapping
servo.duty_u16(duty)
def reset_actuators():
set_servo(0)
led.value(0)
buzzer.duty_u16(0)
# -------------------------------
# MQTT Callback Function
# -------------------------------
def on_message(topic, msg):
command = msg.decode().strip()
print("Command Received:", command)
if command == "FAN_ON":
set_servo(90)
led.value(1)
elif command == "FAN_OFF":
set_servo(0)
led.value(0)
elif command == "ALARM":
buzzer.duty_u16(30000)
elif command == "RESET":
reset_actuators()
# -------------------------------
# WiFi Connection
# -------------------------------
print("Connecting to WiFi...")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASS)
while not wlan.isconnected():
time.sleep(1)
print("WiFi Connected:", wlan.ifconfig())
# -------------------------------
# MQTT Connection
# -------------------------------
client = MQTTClient(CLIENT_ID, MQTT_BROKER)
client.set_callback(on_message)
client.connect()
client.subscribe(TOPIC_SUB)
print("MQTT Connected")
print("Smart Factory Node Online")
# -------------------------------
# Main Loop
# -------------------------------
last_publish = time.time()
while True:
# Listen for MQTT commands
client.check_msg()
# Publish sensor data every 10 seconds
if time.time() - last_publish >= 10:
try:
sensor.measure()
payload = json.dumps({
"temperature": sensor.temperature(),
"humidity": sensor.humidity(),
"fan_status": "ON" if led.value() else "OFF"
})
client.publish(TOPIC_PUB, payload)
print("Telemetry Sent:", payload)
last_publish = time.time()
except OSError:
print("DHT22 Sensor Error")
time.sleep(0.1)