ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

MircoPython接入巴法云,esp8266和esp32环境

2022-01-13 23:35:48  阅读:243  来源: 互联网

标签:esp8266 巴法云 esp32 network client connect print import sta


第一、搭建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() 

标签:esp8266,巴法云,esp32,network,client,connect,print,import,sta
来源: https://www.cnblogs.com/bemfa/p/15800121.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有