import network
import time
import machine
import ubinascii
from umqtt.simple import MQTTClient
# --- ตั้งค่า Wi-Fi ---
SSID = "Wokwi-GUEST"
PASSWORD = ""
# --- ตั้งค่า MQTT ---
#MQTT_BROKER = 'mqtt-dashboard.com'
# สร้าง ID ไม่ซ้ำ
MQTT_BROKER = 'mqtt-dashboard.com'
MQTT_CLIENT_ID = 'elec03/saa'
MQTT_TOPIC_BASE = 'elec03/sa'
# --- ตั้งค่าขา GPIO สำหรับรีเลย์ 4 ตัว ---
# เลือกขา Pin ที่ต้องการใช้งาน (ตรวจสอบกับบอร์ดของคุณ)
# ตัวอย่าง: GPIO 15, 2, 4, 5
RELAY_PINS = [14, 12, 4, 5]
relays = []
# วนลูปเพื่อตั้งค่า Pin ทั้งหมด
for pin in RELAY_PINS:
r = machine.Pin(pin, machine.Pin.OUT)
r.value(0) # เริ่มต้นปิดทุกตัว
relays.append(r)
def connect_to_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('Connecting to Wi-Fi...')
wlan.connect(SSID, PASSWORD)
while not wlan.isconnected():
time.sleep(1)
print('WiFi Connected! IP:', wlan.ifconfig()[0])
return True
def mqtt_callback(topic, msg):
# topic และ msg ที่ได้มาเป็น bytes ต้องแปลงเป็น string ก่อน
topic_str = topic.decode()
msg_str = msg.decode()
print(f'Received: Topic={topic_str}, Msg={msg_str}')
# รูปแบบ Topic คาดหวัง: relay/0, relay/1, relay/2, relay/3
# เราจะตัดคำด้วยเครื่องหมาย / เพื่อเอาเลขตัวหลัง
try:
parts = topic_str.split('/')
# ตรวจสอบว่ามีรูปแบบถูกต้องไหม (ต้องมี 2 ส่วน และส่วนแรกคือ relay)
if len(parts) == 2 and parts[0] == 'relay':
relay_index = int(parts[1]) # แปลงเลขตัวหลังเป็น int
# ตรวจสอบว่าเลข Index อยู่ในช่วง 0-3 หรือไม่
if 0 <= relay_index < len(relays):
if msg_str == 'on':
relays[relay_index].value(1)
print(f'Relay {relay_index} -> ON')
elif msg_str == 'off':
relays[relay_index].value(0)
print(f'Relay {relay_index} -> OFF')
else:
print(f'Error: Relay index {relay_index} not found')
except Exception as e:
print(f'Error parsing topic: {e}')
def connect_mqtt():
try:
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, port=1883)
client.set_callback(mqtt_callback)
client.connect()
# Subscribe แบบ Wildcard (+) เพื่อรับทุกช่องที่ขึ้นต้นด้วย relay/
client.subscribe(MQTT_TOPIC_BASE)
print('MQTT Connected & Subscribed to relay/+')
return client
except Exception as e:
print('MQTT Connection failed:', e)
return None
def main():
if not connect_to_wifi():
return
client = connect_mqtt()
while True:
try:
if client is None:
time.sleep(5)
client = connect_mqtt()
continue
client.check_msg()
time.sleep(0.1)
except OSError as e:
print('Connection error. Reconnecting...')
try:
client.disconnect()
except:
pass
client = None
time.sleep(2)
if __name__ == '__main__':
main()