MircoPython接入巴法云tcp和mqtt

第一、搭建MircoPython開發(fā)環(huán)境

下載 micropython 環(huán)境包:點(diǎn)擊下載

下載后解壓,首先雙擊打開 uPyCraft 軟件,刷入固件,首先點(diǎn)擊 tools-->BurnFirmware ,再選擇esp8266或者esp32,選擇開發(fā)板端口,選擇需要刷入的固件,固件在下載的環(huán)境包中,點(diǎn)擊ok即可刷入,如下圖所示:

02.png

等待進(jìn)度條走完就刷入成功了。

附,其他鏈接:
單片機(jī)串口驅(qū)動(dòng):點(diǎn)擊下載
micropython官方文檔:點(diǎn)擊跳轉(zhuǎn)

第二、hello world 程序測(cè)試

點(diǎn)擊file--new 新建文件,命名main,點(diǎn)擊ok保存,如下圖所示

點(diǎn)擊tools,再點(diǎn)擊serial和board分別選擇端口、開發(fā)板類型esp8266或者esp32,如下圖

03.png

輸入print("hello word") ,點(diǎn)擊下載圖標(biāo),即可下載成功,在下方會(huì)輸出打印的hello world,如下圖

print("hello word")
04.png

第三 TCP示例程序

注意:每次下載程序后都需要重啟開發(fā)板,例如按開發(fā)板上的reset按鍵重啟

import time
from machine import Timer
import socket

#需要修改的地方
wifiName = "newhtc"                   #wifi 名稱,不支持5G wifi
wifiPassword = "qq123456"       #wifi 密碼
clientID = "7d54f85af42976ee3c2693e692a6bb59"            # Client ID ,密鑰,巴法云控制臺(tái)獲取
myTopic='myled002'                     # 需要訂閱的主題值,巴法MQTT控制臺(tái)創(chuàng)建

#默認(rèn)設(shè)置
serverIP = 'bemfa.com'    # mqtt 服務(wù)器地址
port = 8344

# WIFI 連接函數(shù)
def do_connect():
    import network
    sta_if = network.WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)
        sta_if.connect(wifiName, wifiPassword)
        while not sta_if.isconnected():
            pass
    print('connect  WiFi ok')


    
# tcp 客戶端初始化        
def connect_and_subscribe():
  addr_info = socket.getaddrinfo(serverIP, port)
  addr = addr_info[0][-1]
  client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)   # 創(chuàng)建TCP的套接字,也可以不給定參數(shù)。默認(rèn)為TCP通訊方式
  client.connect(addr)                                 # 設(shè)置要連接的服務(wù)器端的IP和端口,并連接
  substr = 'cmd=1&uid='+clientID+'&topic='+myTopic+'\r\n'
  client.send(substr.encode("utf-8"))
  print("Connected to %s" % serverIP)
  return client
  
#心跳
def Ping(self):
    # 發(fā)送心跳
    try:
        keeplive = 'ping\r\n'
        client.send(keeplive.encode("utf-8"))
    except:
        restart_and_reconnect()

# 重新連接
def restart_and_reconnect():
  print('Failed to connect to TCP  broker. Reconnecting...')
  time.sleep(10)
  machine.reset()
 
 #開始連接WIFI
do_connect() 

#開始連接TCP
try:
  client = connect_and_subscribe()
except OSError as e:
  restart_and_reconnect()
 
 #開啟定時(shí)器,定時(shí)發(fā)送心跳
tim = Timer(-1)
tim.init(period=30000, mode=Timer.PERIODIC, callback=Ping)

while True:
  try:
    data = client.recv(256)                         # 從服務(wù)器端套接字中讀取1024字節(jié)數(shù)據(jù)
    if(len(data) != 0):                                 # 如果接收數(shù)據(jù)為0字節(jié)時(shí),關(guān)閉套接字
        data=data.decode('utf-8')              
        print(data.strip())                              # 去掉尾部回車換行符,并打印接收到的字符
  except OSError as e:                            # 如果出錯(cuò)就重新啟動(dòng)
    print('Failed to connect to  broker. Reconnecting...')
    restart_and_reconnect() 

第四 MQTT示例程序

from umqtt.simple import MQTTClient
import time
from machine import Timer

#需要修改的地方
wifiName = "newhtc"                   #wifi 名稱,不支持5G wifi
wifiPassword = "qq123456"       #wifi 密碼
clientID = "7d54f85af42976ee3c2693e692a6bb59"            # Client ID ,密鑰,巴法云控制臺(tái)獲取
myTopic='light002'                     # 需要訂閱的主題值,巴法MQTT控制臺(tái)創(chuàng)建

#默認(rèn)設(shè)置
serverIP = "bemfa.com"    # mqtt 服務(wù)器地址
port = 9501

# WIFI 連接函數(shù)
def do_connect():
    import network
    sta_if = network.WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)
        sta_if.connect(wifiName, wifiPassword)
        while not sta_if.isconnected():
            pass
    print('connect  WiFi ok')
    

# 接收消息,并處理
def MsgOK(topic, msg):          # 回調(diào)函數(shù),用于收到消息
        print((topic, msg))             # 打印主題值和消息值
        if topic == myTopic.encode():     # 判斷是不是發(fā)給myTopic的消息
            if msg == b"on":                # 當(dāng)收到on
                print("rec on")
            elif msg == b"off":             #  當(dāng)收到off
                print("rec off")


#初始化mqtt連接配置
def connect_and_subscribe():
  client = MQTTClient(clientID, serverIP,port)  
  client.set_callback(MsgOK)
  client.connect()
  client.subscribe(myTopic)
  print("Connected to %s" % serverIP)
  return client
  
def restart_and_reconnect():
  print('Failed to connect to MQTT broker. Reconnecting...')
  time.sleep(10)
  machine.reset()
  
  

#開始連接WIFI
do_connect() 

#開始連接MQTT
try:
  client = connect_and_subscribe()
except OSError as e:
  restart_and_reconnect()
 

while True:
  try:
    client.check_msg() 
  except OSError as e: #如果出錯(cuò)就重新啟動(dòng)
    print('Failed to connect to MQTT broker. Reconnecting...')
    restart_and_reconnect() 
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容