micro python发送 MQTT 心跳包

micro python发送 MQTT 心跳包

为什么要发心跳包?

keep alive机制

在建立连接的时候,我们可以传递一个 Keep Alive 参数,它的单位为秒,MQTT 协议中规定:在 1.5*Keep Alive 的时间间隔内,如果 Broker 没有收到来自 Client 的任何数据包,那么 Broker 认为它和 Client 之间的连接已经断开;同样地, 如果 Client 没有收到来自 Broker 的任何数据包,那么 Client 认为它和 Broker 之间的连接已经断开。

  • Keep Alive 的最大值为 18 小时 12 分 15 秒;
  • Keep Alive 值如果设为 0 的话,代表不使用 Keep Alive 机制。

解决方法: 客户端每隔keep alive时间, 就向服务端发送心跳包, 相当于告诉服务端我还活着

怎样发送心跳包

基于micro python语言的umqtt库, 在库中发现一个ping()函数, 该函数就是发送心跳包的函数

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import time
import network
from umqttsimple import MQTTClient

t = 0
keepalive = 60

def do_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect('ID', 'password')
i = 1
while not wlan.isconnected():
print("正在链接...{}".format(i))
i += 1
time.sleep(1)
print('network config:', wlan.ifconfig())


def sub_cb(topic, msg):
print(topic, msg)

do_connect()
c = MQTTClient("umqtt_client", "address", keepalive=keepalive)
c.set_callback(sub_cb)
c.connect()
c.subscribe(b"test")
while True:
gloabl t
t = t + 1
print(i)
c.check_msg()
time.sleep(1)
if t == keepalive:
c.ping()
t = 0
print('发送心跳包')

这样客户端就能一直保持连接状态啦