import network
import time
import json
from machine import Pin
from umqtt.simple import MQTTClient
# ===== 配置参数 =====
# WiFi配置 (Wokwi专用)
SSID = "Wokwi-GUEST"
PASSWORD = ""
# ThingSpeak MQTT配置
MQTT_SERVER = "mqtt3.thingspeak.com"
MQTT_PORT = 1883
# 从ThingSpeak获取的凭证
CHANNEL_ID = "你的CHANNEL_ID" # 替换为你的Channel ID
WRITE_API_KEY = "你的WRITE_API_KEY" # 替换为你的Write API Key
MQTT_USER = "你的MQTT_USER" # 替换为你的MQTT Username
MQTT_PASS = "你的MQTT_PASS" # 替换为你的MQTT Password
# MQTT Topic格式
topic = f"channels/{CHANNEL_ID}/publish/{WRITE_API_KEY}"
# CSV文件模拟数据 (实际项目中从文件读取)
# 这里用数组模拟IoTSensorStream.csv的内容
sensor_data = [
{"volt": 220.5, "rotate": 1480, "pressure": 5.02, "vibration": 0.21, "label": 0},
{"volt": 219.8, "rotate": 1478, "pressure": 5.01, "vibration": 0.23, "label": 0},
{"volt": 215.2, "rotate": 1420, "pressure": 4.75, "vibration": 0.82, "label": 1},
{"volt": 205.1, "rotate": 1350, "pressure": 4.21, "vibration": 1.52, "label": 1},
{"volt": 221.3, "rotate": 1490, "pressure": 5.03, "vibration": 0.19, "label": 0},
{"volt": 218.5, "rotate": 1475, "pressure": 4.98, "vibration": 0.25, "label": 0},
{"volt": 210.8, "rotate": 1390, "pressure": 4.52, "vibration": 1.12, "label": 1},
{"volt": 208.3, "rotate": 1365, "pressure": 4.35, "vibration": 1.35, "label": 1},
{"volt": 222.0, "rotate": 1495, "pressure": 5.05, "vibration": 0.18, "label": 0},
{"volt": 217.2, "rotate": 1465, "pressure": 4.95, "vibration": 0.28, "label": 0},
]
# ===== WiFi连接函数 =====
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
print("Connecting to WiFi...", end="")
timeout = 10
while not wlan.isconnected() and timeout > 0:
print(".", end="")
time.sleep(1)
timeout -= 1
if wlan.isconnected():
print("\n✅ WiFi Connected!")
print(f"IP: {wlan.ifconfig()[0]}")
return True
else:
print("\n❌ WiFi Connection Failed")
return False
# ===== MQTT连接函数 =====
def connect_mqtt():
try:
# 创建MQTT客户端
client_id = f"esp32_{int(time.time())}"
client = MQTTClient(client_id,
MQTT_SERVER,
port=MQTT_PORT,
user=MQTT_USER,
password=MQTT_PASS,
keepalive=60)
client.connect()
print("📡 Connected to ThingSpeak MQTT")
return client
except Exception as e:
print(f"❌ MQTT Connection Error: {e}")
return None
# ===== 发送数据到ThingSpeak =====
def send_to_thingspeak(client, volt, rotate, pressure, vibration):
try:
# 格式化数据:field1=volt&field2=rotate&field3=pressure&field4=vibration
payload = f"field1={volt}&field2={rotate}&field3={pressure}&field4={vibration}"
# 发布消息
client.publish(topic, payload)
print(f"📤 Sent: V={volt}, R={rotate}, P={pressure}, Vib={vibration}")
return True
except Exception as e:
print(f"❌ Send Error: {e}")
return False
# ===== 从CSV模拟文件读取数据 =====
def read_sensor_data(index):
"""模拟从CSV文件读取一行数据"""
if index < len(sensor_data):
data = sensor_data[index]
# 注意:label不发送,只用于内部参考
print(f"📋 Label: {data['label']} (0=normal, 1=anomaly) - not sent to cloud")
return data
else:
return None
# ===== 主程序 =====
def main():
print("=" * 50)
print("CEG5103 - Industrial IoT Sensor Node")
print("Machine Failure Prediction System")
print("=" * 50)
# 连接WiFi
if not connect_wifi():
print("Cannot proceed without WiFi. Restarting...")
time.sleep(5)
return
# 连接MQTT
mqtt_client = connect_mqtt()
if not mqtt_client:
print("Cannot proceed without MQTT. Restarting...")
time.sleep(5)
return
# 主循环:每10秒发送一组数据
data_index = 0
while True:
try:
# 从模拟数据文件读取
sensor = read_sensor_data(data_index)
if sensor:
# 发送到ThingSpeak
success = send_to_thingspeak(
mqtt_client,
sensor["volt"],
sensor["rotate"],
sensor["pressure"],
sensor["vibration"]
)
# 更新索引(循环使用数据)
data_index = (data_index + 1) % len(sensor_data)
else:
print("No more data, resetting...")
data_index = 0
# 检查MQTT连接状态
try:
mqtt_client.ping()
except:
print("MQTT connection lost. Reconnecting...")
mqtt_client = connect_mqtt()
if not mqtt_client:
break
# 等待10秒
print(f"⏱️ Waiting 10 seconds...")
time.sleep(10)
except KeyboardInterrupt:
print("\n🛑 Program stopped by user")
break
except Exception as e:
print(f"❌ Error in main loop: {e}")
time.sleep(5)
# 断开连接
if mqtt_client:
mqtt_client.disconnect()
print("Program ended")
# 启动程序
if __name__ == "__main__":
main()