例程讲解14-mqtt_sub mqtt订阅

# MQTT示例
# 这个示例展示了如何使用MQTT库订阅主题。
#
# 1) 将mqtt.py库复制到OpenMV存储。
# 2)在OpenMV相机上运行这个脚本。
# 3) 将mosquito客户端安装在PC上,并运行以下命令:
#    mosquitto_pub -t "openmv/test" -m "Hello World!" -h test.mosquitto.org -p 1883
#
# 注意: 如果无法访问mosquito,请尝试另一个代理(例如:broker.hivemq.com)
import time, network
from mqtt import MQTTClient

SSID='' # Network SSID
KEY=''  # Network key

# 初始化wlan模块并连接到网络
print("Trying to connect... (may take a while)...")

wlan = network.WINC()
wlan.connect(SSID, key=KEY, security=wlan.WPA_PSK)

# 我们现在应该有一个通过DHCP的有效IP了
print(wlan.ifconfig())

client = MQTTClient("openmv", "test.mosquitto.org", port=1883)
client.connect()

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

# 必须先设置回调
client.set_callback(callback)
client.subscribe("openmv/test")

while (True):
    client.check_msg() # 轮询消息。
    time.sleep(1000)

results matching ""

    No results matching ""