import machine
import network
import time
from umqtt.simple import MQTTClient
import ubinascii
import urandom as random # 測試用隨機數據
MQTT_RECONNECT_INTERVAL = 10000 # millisecond
# WiFi AP 設定
WIFI_SSID1 = '1234' # "Your network name";
WIFI_PASS1 = '5678' # "Your network password";
WIFI_SSID2 = "2345" # Your WiFi SSID
WIFI_PASS2 = "6789" # Your WiFi Password
WIFI_SSID3 = "3456" # Your WiFi SSID
WIFI_PASS3 = "7890" # Your WiFi Password
# Thinger.io configuration
BROKER = "mqtt.thinger.io"
USERNAME = "raylee0106" # "你的Thinger.io 帳號名稱"
DEVICE_ID = "nodmcu" # 你在 Thinger.io 建立的裝置 ID
DEVICE_CREDENTIAL = "Agx1qJORGB6zf910"
PORT = 1883 # 如果要 TLS 改用 8883,但需要加載證書
def randint(min, max):
span = max - min + 1
div = 0x3FFFFFFF // span
offset = random.getrandbits(30) // div
val = min + offset
return val
# === 連線 WiFi ===
def connect_wifi():
print("Scanning for WiFi networks, please wait...")
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
num = 0
for (ssid, bssid, channel, RSSI, authmode, hidden) in wifi.scan():
if WIFI_SSID1 in ssid:
WIFI_SSID = WIFI_SSID1 # Your WiFi SSID
WIFI_PASS = WIFI_PASS1 # Your WiFi Password
num=1
break
elif WIFI_SSID2 in ssid:
WIFI_SSID = WIFI_SSID2 # Your WiFi SSID
WIFI_PASS = WIFI_PASS2 # Your WiFi Password
num=2
break
elif WIFI_SSID3 in ssid:
WIFI_SSID = WIFI_SSID3 # Your WiFi SSID
WIFI_PASS = WIFI_PASS3 # Your WiFi Password
num=3
break
elif "Wokwi-GUEST" in ssid:
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASS = ""
num=4
break
if (num == 0):
print("Couldn't get a wifi connection")
while True:
pass
# authmodes = ['Open', 'WEP', 'WPA-PSK' 'WPA2-PSK4', 'WPA/WPA2-PSK']
print("* {:s}".format(ssid))
# print(" - Auth: {} {}".format(authmodes[authmode], '(hidden)' if hidden else ''))
print(" - Channel: {}".format(channel))
print(" - RSSI: {}".format(RSSI))
print(" - BSSID: {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}".format(*bssid))
if not wifi.isconnected():
print('Connecting to network...')
wifi.connect(WIFI_SSID, WIFI_PASS)
while not wifi.isconnected():
time.sleep(1)
print('Network config:', wifi.ifconfig())
return
# ===== 連線 thinger IO MQTT =====
def connect_to_thinger():
# MQTT Client 設定
client = MQTTClient(client_id=DEVICE_ID,
server=BROKER,
user=USERNAME,
password=DEVICE_CREDENTIAL,
port=PORT,
keepalive=60,
ssl=False) # 若改 8883,設為 True
try:
client.connect()
print("Connected to Thinger.io MQTT")
except Exception as e:
print("Failed to connect to Adafruit IO:", e)
machine.reset()
return client
# Start Function
if __name__ == '__main__':
connect_wifi() # Connecting to WiFi Router
client = connect_to_thinger()
# 定義要傳送的 Topic
topic = b"v3/users/%s/devices/%s/data" % (USERNAME.encode(), DEVICE_ID.encode())
lastTime=0
# ===== 發布資料 =====
while True:
currTime = time.ticks_ms()
if (currTime - lastTime > MQTT_RECONNECT_INTERVAL):
lastTime = currTime
value = random.getrandbits(8)
payload = '{"temperature": %d}' % value
print("Published:", payload)
client.publish(topic, payload)
time.sleep(10)