「树莓派玩转物联网」之树莓派连接「百度天工」测试

版权声明:欢迎转载,注明出处就好!如果不喜欢请留言说明原因再踩哦,谢谢,我也可以知道原因,不断进步!! https://blog.csdn.net/wzhqazcscs/article/details/79604836

预安装环境

本工程需要使用Python 3以上版本。本工程在Windows、Linux和Mac上均可运行。

下载项目文件

http://iot-demo.cdn.bcebos.com/SampleCode/TestMQTTPython.zip处下载工程文件,并解压至磁盘。

  • 问题1
    pi@raspberrypi:~/TestMQTTPython$ python server.py
    Traceback (most recent call last):
    File “server.py”, line 1, in
    import paho.mqtt.client as mqtt
    ImportError: No module named paho.mqtt.client
  • 解决办法:pip install paho-mqtt==1.2

  • 问题2
    这里写图片描述

  • 解决办法:msg = str(msg.payload, ‘utf-8’),改为msg = str(msg.payload),再次运行python server.py ,如下图这里写图片描述

总结

通过MQTT.FX客户端给云端百度云天工发送消息,能够转发至Raspberry Pi。
这里写图片描述
这里写图片描述

以下代码,实现了对百度云天工-该主题(demoTopic)的subscribe。

import paho.mqtt.client as mqtt
import sys
import uuid

broker = 'iotfreetest.mqtt.iot.gz.baidubce.com'
port = 1883
username = 'iotfreetest/thing01'
password = 'YU7Tov8zFW+WuaLx9s9I3MKyclie9SGDuuNkl6o9LXo='
clientid = 'test_mqtt_python_' + str(uuid.uuid4())
topic = 'demoTopic'

def on_connect(client, userdata, rc):
    print('Connected. Client id is: ' + clientid)
    client.subscribe(topic)
    print('Subscribed to topic: ' + topic)

    client.publish(topic, 'Message from Baidu IoT demo')
    print('MQTT message published.')

def on_message(client, userdata, msg):
    msg = str(msg.payload, 'utf-8')
    print('MQTT message received: ' + msg)
    if msg == 'exit':
        sys.exit()

client = mqtt.Client(clientid)
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(username, password)

print('Connecting to broker: ' + broker)
client.connect(broker, port)

client.loop_forever()

猜你喜欢

转载自blog.csdn.net/wzhqazcscs/article/details/79604836