"""
CEG5103/EE5024 - Industrial IoT for Machine Failure Prediction
Student 5: Response Node (Basic Implementation)
- Subscribes to ThingSpeak Field 5 for predictions
- Green LED for normal status (Pin 2)
- Red LED + Buzzer for anomaly alert (Pin 4, Pin 15)
Hardware:
- ESP32 Development Board
- Green LED -> Pin 2
- Red LED -> Pin 4
- Buzzer -> Pin 15
"""
import network
import time
from umqtt.simple import MQTTClient
from machine import Pin, PWM
import gc
# ===== HARDWARE CONFIGURATION =====
LED_GREEN = Pin(2, Pin.OUT)
LED_RED = Pin(4, Pin.OUT)
BUZZER = PWM(Pin(15))
BUZZER.freq(1000)
BUZZER.duty(0)
# ===== ACTUATION FUNCTIONS =====
def set_normal_mode():
"""Normal operation: Green LED ON, Red LED OFF, Buzzer OFF"""
LED_GREEN.value(1)
LED_RED.value(0)
BUZZER.duty(0)
print(" [ACTUATOR] Green LED ON - Machine NORMAL")
def set_anomaly_mode():
"""Anomaly detected: Green LED OFF, Red LED ON, Buzzer sounds"""
LED_GREEN.value(0)
LED_RED.value(1)
BUZZER.duty(512)
time.sleep(0.5)
BUZZER.duty(0)
print(" [ACTUATOR] Red LED ON - ANOMALY DETECTED")
print(" [ACTUATOR] Buzzer SOUNDING - ALERT!")
def set_idle_mode():
"""Idle state: All LEDs OFF, Buzzer OFF"""
LED_GREEN.value(0)
LED_RED.value(0)
BUZZER.duty(0)
print(" [ACTUATOR] System IDLE")
def flash_led(led, times=3, duration=0.2):
for _ in range(times):
led.value(1)
time.sleep(duration)
led.value(0)
time.sleep(duration)
# ===== WIFI & MQTT CONFIGURATION =====
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
CHANNEL_ID = "3293129"
MQTT_CLIENT_ID = "ORwNMAYKEg0kCiUsLxk4LSY"
MQTT_USER = "ORwNMAYKEg0kCiUsLxk4LSY"
MQTT_PASS = "oniySoxRWcSviO9bvemQbAE1"
MQTT_SERVER = "mqtt3.thingspeak.com"
MQTT_PORT = 1883
MQTT_TOPIC = f"channels/{CHANNEL_ID}/subscribe/fields/field5"
STATUS_NORMAL = 0
STATUS_ANOMALY = 1
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
print(f"\nConnecting to WiFi: {WIFI_SSID}", end="")
for i in range(30):
if wlan.isconnected():
print("\nWiFi Connected Successfully")
print("IP Address: " + wlan.ifconfig()[0])
flash_led(LED_GREEN, times=2, duration=0.1)
return wlan
print(".", end="")
time.sleep(1)
print("\nWiFi Connection Failed")
return None
def connect_mqtt():
try:
gc.collect()
print(f"\nConnecting to ThingSpeak MQTT...")
print(f" Server: {MQTT_SERVER}:{MQTT_PORT}")
print(f" Client ID: {MQTT_CLIENT_ID}")
print(f" Subscribing to: {MQTT_TOPIC}")
client = MQTTClient(
client_id=MQTT_CLIENT_ID,
server=MQTT_SERVER,
port=MQTT_PORT,
user=MQTT_USER,
password=MQTT_PASS,
keepalive=60
)
client.connect()
print("MQTT Connected Successfully")
flash_led(LED_GREEN, times=1, duration=0.2)
return client
except Exception as e:
print("MQTT Connection Failed: " + str(e))
return None
def mqtt_callback(topic, msg):
try:
prediction = int(msg.decode('utf-8'))
print(f"\n{'='*50}")
print(f"MQTT Message Received")
print(f" Topic: {topic}")
print(f" Prediction: {prediction}")
if prediction == STATUS_NORMAL:
print(f"\nSTATUS: NORMAL OPERATION")
set_normal_mode()
elif prediction == STATUS_ANOMALY:
print(f"\nSTATUS: ANOMALY DETECTED!")
set_anomaly_mode()
flash_led(LED_RED, times=3, duration=0.2)
print(f"{'='*50}\n")
except Exception as e:
print(f"Callback error: {e}")
def main():
print("="*60)
print("CEG5103/EE5024 - Industrial IoT System")
print("Student 5: Response Node")
print("="*60)
print("\nHardware Configuration:")
print(" - Green LED : Pin 2")
print(" - Red LED : Pin 4")
print(" - Buzzer : Pin 15")
print("="*60)
set_idle_mode()
wlan = connect_wifi()
if not wlan:
return
mqtt_client = connect_mqtt()
if not mqtt_client:
return
mqtt_client.set_callback(mqtt_callback)
mqtt_client.subscribe(MQTT_TOPIC)
print(f"\nSubscribed to: {MQTT_TOPIC}")
print("\nSystem READY! Waiting for predictions...")
print("Press Ctrl+C to stop\n")
flash_led(LED_GREEN, times=3, duration=0.1)
last_connection_check = time.time()
try:
while True:
mqtt_client.check_msg()
current_time = time.time()
if current_time - last_connection_check > 30:
try:
mqtt_client.ping()
except:
print("\nMQTT connection lost. Reconnecting...")
mqtt_client = connect_mqtt()
if mqtt_client:
mqtt_client.set_callback(mqtt_callback)
mqtt_client.subscribe(MQTT_TOPIC)
last_connection_check = current_time
time.sleep(0.05)
except KeyboardInterrupt:
print("\n\nProgram stopped by user")
finally:
set_idle_mode()
if mqtt_client:
mqtt_client.disconnect()
BUZZER.deinit()
print("System shutdown complete")
if __name__ == "__main__":
main()