MircoPython接入巴法云,esp8266和esp32

第一、搭建MircoPython开发环境

下载 micropython 环境包:点击下载

下载后解压,首先双击打开 uPyCraft 软件,刷入固件,首先点击 tools–>BurnFirmware ,再选择esp8266或者esp32,选择开发板端口,选择需要刷入的固件,固件在下载的环境包中,点击ok即可刷入,如下图所示:

在这里插入图片描述

等待进度条走完就刷入成功了。

附,其他链接:
单片机串口驱动:点击下载
micropython官方文档:点击跳转

第二、hello world 程序测试

点击file–new 新建文件,命名main,点击ok保存,如下图所示

在这里插入图片描述
点击tools,再点击serial和board分别选择端口、开发板类型esp8266或者esp32,如下图

在这里插入图片描述

输入print(“hello word”) ,点击下载图标,即可下载成功,在下方会输出打印的hello world,如下图

print("hello word")

在这里插入图片描述

第三 TCP示例程序

注意:每次下载程序后都需要重启开发板,例如按开发板上的reset按键重启

import time
from machine import Timer
import socket

#需要修改的地方
wifiName = "newhtc"                   #wifi 名称,不支持5G wifi
wifiPassword = "qq123456"       #wifi 密码
clientID = "7d54f85af42976ee3c2693e692a6bb59"            # Client ID ,密钥,巴法云控制台获取
myTopic='myled002'                     # 需要订阅的主题值,巴法MQTT控制台创建

#默认设置
serverIP = 'bemfa.com'    # mqtt 服务器地址
port = 8344

# WIFI 连接函数
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)   # 创建TCP的套接字,也可以不给定参数。默认为TCP通讯方式
  client.connect(addr)                                 # 设置要连接的服务器端的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):
    # 发送心跳
    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()
 
 #开启定时器,定时发送心跳
tim = Timer(-1)
tim.init(period=30000, mode=Timer.PERIODIC, callback=Ping)

while True:
  try:
    data = client.recv(256)                         # 从服务器端套接字中读取1024字节数据
    if(len(data) != 0):                                 # 如果接收数据为0字节时,关闭套接字
        data=data.decode('utf-8')              
        print(data.strip())                              # 去掉尾部回车换行符,并打印接收到的字符
  except OSError as e:                            # 如果出错就重新启动
    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 ,密钥,巴法云控制台获取
myTopic='light002'                     # 需要订阅的主题值,巴法MQTT控制台创建

#默认设置
serverIP = "bemfa.com"    # mqtt 服务器地址
port = 9501

# WIFI 连接函数
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):          # 回调函数,用于收到消息
        print((topic, msg))             # 打印主题值和消息值
        if topic == myTopic.encode():     # 判断是不是发给myTopic的消息
            if msg == b"on":                # 当收到on
                print("rec on")
            elif msg == b"off":             #  当收到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: #如果出错就重新启动
    print('Failed to connect to MQTT broker. Reconnecting...')
    restart_and_reconnect() 

猜你喜欢

转载自blog.csdn.net/bemfa/article/details/122472808