??在这个智能硬件和物联网时代,MicroPython和树莓派PICO正以其独特的优势引领着嵌入式开发的新潮流。MicroPython作为一种精简优化的Python 3语言,为微控制器和嵌入式设备提供了高效开发和简易调试的
??当我们结合WIZnet W5100S/W5500网络模块,MicroPython和树莓派PICO的开发潜力被进一步放大。这两款模块都内置了TCP/IP协议栈,使得在嵌入式设备上实现网络连接变得更加容易。无论是进行数据传输、远程控制,还是构建物联网应用,它们都提供了强大的支持。
??本章我们将以WIZnet W5100S为例,以MicroPython的开发方式,连接至OneNET新版MQTT上,并定时上报DHT11传感器的温湿度信息以及通过平台下发指令控制板载LED灯亮灭。
第一步:创建产品
第二步:创建物模型定义
第三步:创建设备
第四步:计算参数
需要将主题的{device-name}替换为设备名(或设备ID)
密码生成工具:https://open.iot.10086.cn/doc/iot_platform/images/tools/token.exe
参数名 | 参数值 |
---|---|
mqttHostUrl | mqtts.heclouds.com(固定不变) |
port | 1883(固定不变) |
clientId | W5100S_W5500(设备ID) |
username | 75w4NMRceb(产品ID) |
passwd | version=2018-10-31&res=products%2F75w4NMRceb%2Fdevices%2FW5100S_W5500&et=1791400694&method=md5&sign=FTnZrF14Pqy%2F3CXggctheg%3D%3D(工具计算) |
上报温湿度主题 | $sys/75w4NMRceb/W5100S_W5500/thing/property/post(发布权限) |
上报回复主题 | $sys/75w4NMRceb/W5100S_W5500/thing/property/post/reply(订阅权限) |
设置LED状态 | $sys/75w4NMRceb/W5100S_W5500/thing/property/set(订阅权限) |
设置状态回复 | $sys/75w4NMRceb/W5100S_W5500/thing/property/set_reply(发布权限) |
WIZnet 主流硬件协议栈以太网芯片参数对比
Model | Embedded Core | Host I/F | TX/RX Buffer | HW Socket | Network Performance |
---|---|---|---|---|---|
W5100S | TCP/IPv4, MAC & PHY | 8bit BUS, SPI | 16KB | 4 | Max 25Mbps |
W6100 | TCP/IPv4/IPv6, MAC & PHY | 8bit BUS, Fast SPI | 32KB | 8 | Max 25Mbps |
W5500 | TCP/IPv4, MAC & PHY | Fast SPI | 32KB | 8 | Max 15Mbps |
相较于软件协议栈,WIZnet的硬件协议栈以太网芯片有以下优点:
软件:
硬件:
??我们直接打开mqtt_onenet_new.py文件。
第一步:可以看到在w5x00_init()函数中,进行了SPI的初始化。以及将spi相关引脚和复位引脚注册到库中,后续则是激活网络,并使用DHCP配置网络地址信息,当DHCP失败时,则配置静态网络地址信息。当未配置成功时,会打印出网络地址相关寄存器的信息,可以帮助我们更好的排查问题。
第二步:连接OneNET的MQTT服务器,连接失败则进入复位程序。
第三步:开启定时器定时上报温湿度信息,订阅主题并在主循环中等待接收消息。
需注意:要将MQTT参数定义改为您的OneNET的MQTT参数
必须订阅上报回复主题(可以不做处理),收到消息设置主题必须回复消息,否则会报错。
#import library
from umqttsimple import MQTTClient
from usocket import socket
from machine import Pin,SPI,Timer
import dht
import network
import time
import json
#mqtt config
mqtt_params = {}
mqtt_params['url'] = "mqtts.heclouds.com"
mqtt_params['port'] = 1883
mqtt_params['clientid'] = 'W5100S_W5500'
mqtt_params['username'] = '75w4NMRceb'
mqtt_params['passwd'] = 'version=2018-10-31&res=products%2F75w4NMRceb%2Fdevices%2FW5100S_W5500&et=1791400694&method=md5&sign=FTnZrF14Pqy%2F3CXggctheg%3D%3D'
mqtt_params['pubtopic'] = '$sys/' + mqtt_params['username'] + '/' + mqtt_params['clientid'] + '/thing/property/post'
mqtt_params['pubtopic_reply'] = '$sys/' + mqtt_params['username'] + '/'+mqtt_params['clientid'] + '/thing/property/post/reply'
mqtt_params['subtopic'] = '$sys/' + mqtt_params['username'] + '/' + mqtt_params['clientid'] + '/thing/property/set'
mqtt_params['subtopic_reply'] = '$sys/' + mqtt_params['username'] + '/' + mqtt_params['clientid'] + '/thing/property/set_reply'
message_interval = 5
timer_1s_count = 0
tim = Timer()
#DHT11 definitions
pin = Pin(2,Pin.OUT)
sensor = dht.DHT11(pin)
led = Pin(25, Pin.OUT)
#mqtt client
client = None
"""
W5x00 chip initialization.
param: None
returns: None
"""
def w5x00_init():
#spi init
spi=SPI(0,2_000_000, mosi=Pin(19),miso=Pin(16),sck=Pin(18))
nic = network.WIZNET5K(spi,Pin(17),Pin(20)) #spi,cs,reset pin
nic.active(True)#network active
try:
#DHCP
print("\r\nConfiguring DHCP")
nic.ifconfig('dhcp')
except:
#None DHCP
print("\r\nDHCP fails, use static configuration")
nic.ifconfig(('192.168.1.20','255.255.255.0','192.168.1.1','8.8.8.8'))#Set static network address information
#Print network address information
print("IP :",nic.ifconfig()[0])
print("Subnet Mask:",nic.ifconfig()[1])
print("Gateway :",nic.ifconfig()[2])
print("DNS :",nic.ifconfig()[3],"\r\n")
#If there is no network connection, the register address information is printed
while not nic.isconnected():
time.sleep(1)
print(nic.regs())
"""
1-second timer callback function.
param1: class timer
returns: None
"""
def tick(timer):
global timer_1s_count
global client
timer_1s_count += 1
if timer_1s_count >= message_interval:
sensor.measure()
timer_1s_count = 0
sendmsg = '{"id": "123","version": "1.0","params": {"CurrentTemperature": {"value":%s},"CurrentHumidity":{"value":%s}}}'%(str(sensor.temperature()),str(sensor.humidity()))
client.publish(mqtt_params['pubtopic'],sendmsg,qos = 0)
print("send:",sendmsg)
"""
Connect to the MQTT server.
param: None
returns: None
"""
def mqtt_connect():
client = MQTTClient(mqtt_params['clientid'], mqtt_params['url'], mqtt_params['port'],mqtt_params['username'],mqtt_params['passwd'],keepalive=60)
client.connect()
print('Connected to %s MQTT Broker'%(mqtt_params['url']))
return client
"""
Connection error handler.
param: None
returns: None
"""
def reconnect():
print('Failed to connected to Broker. Reconnecting...')
time.sleep(5)
machine.reset()
"""
Subscribe to the topic message callback function. This function is entered when a message is received from a subscribed topic.
param1: The topic on which the callback is triggered
param2: Message content
returns: None
"""
def sub_cb(topic, msg):
topic = topic.decode('utf-8')
msg = msg.decode('utf-8')
if topic == mqtt_params['subtopic']:
print("\r\ntopic:",topic,"\r\nrecv:", msg)
try:
parsed = json.loads(msg)
if(parsed["params"]["LEDSwitch"] == True):
print("LED ON!")
led.value(1)
else:
print("LED OFF!")
led.value(0)
sendmsg = '{"id": "%s","code": "200","msg": "success"}'%str(parsed["id"])
client.publish(mqtt_params['subtopic_reply'],sendmsg,qos = 0)
print("send:",sendmsg)
sendmsg = '{"id": "123","version": "1.0","params": {"LEDSwitch": {"value":%s}}}'%str(parsed["params"]["LEDSwitch"]).lower()
client.publish(mqtt_params['pubtopic'],sendmsg,qos = 0)
print("send:",sendmsg)
except:
print("json load error!")
"""
Subscribe to Topics.
param: None
returns: None
"""
def subscribe():
client.set_callback(sub_cb)
client.subscribe(mqtt_params['subtopic'],0)
print('subscribed to %s'%mqtt_params['subtopic'])
client.subscribe(mqtt_params['pubtopic_reply'],0)
print('subscribed to %s'%mqtt_params['pubtopic_reply'])
def main():
global client
print("WIZnet chip MQTT of OneNET(new version MQTT) example")
w5x00_init()
try:
client = mqtt_connect()
except OSError as e:
reconnect()
tim.init(freq=1, callback=tick)
subscribe()
while True:
client.wait_msg()
if __name__ == "__main__":
main()
要测试以太网示例,必须将开发环境配置为使用Raspberry Pi Pico。
注意:因为MicroPython的print函数是启用了stdout缓冲的,所以有时候并不会第一时间打印出内容。
运行该脚本必须要有umqttsimple.py库支持,如何添加umqttsimple.py库请查看MQTT协议示例
第一步:将程序复制到Thonny中,然后选择环境为Raspberry Pi Pico,再运行
第二步:可以看到此时每间隔5秒上报了一次温湿度信息,并且平台上也会实时更新。
第三步:可以通过云平台设置板载LED的状态
想了解更多,评论留言哦!