Main Content

本页采用了机器翻译。点击此处可查看英文原文。

在 Raspberry Pi 上使用 Python 中的 WebSocket 进行发布

此示例演示如何使用运行 Python 的 Raspberry Pi 板在端口 80 上使用 WebSocket 发布到 ThingSpeak通道。如果您想要发送到 ThingSpeak 多个传感器值,您可以将多个值发布到通道源。在此示例中,每 20 秒收集一次 Raspberry Pi 板的 CPU 和 RAM 使用数据,并将这些值发布到通道源。或者,如果您只有一个值要更新,则可以将单个值发布到通道字段。

设置

1) 创建一个新通道,如Collect Data in a New Channel所示。

2) 点击“设备”创建 MQTT 设备>ThingSpeak 页面顶部的“MQTT”,然后是“添加设备”。设置设备并将新通道添加到其授权列表时,点击“下载凭据”> “ 纯文本 ” 。详情请参见创建 ThingSpeak MQTT 设备。使用下面代码部分中保存的凭据。

3) 下载 Python 的 Paho MQTT 客户端库。您可以使用命令行来安装库。如果您使用的是 Python 2,请使用以下代码:

sudo pip install paho-mqtt
sudo pip install psutil

如果您使用 Python 3,请使用以下代码:

sudo pip3 install paho-mqtt
sudo pip3 install psutil

代码

1) 在您的 Python 代码中包含 paho.mqtt.publish as publishpsutilstring 库。

import paho.mqtt.publish as publish
import psutil
import string

2) 定义与 ThingSpeak 通信的变量。编辑通道ID 和 MQTT 设备凭据。

# The ThingSpeak Channel ID.
# Replace <YOUR-CHANNEL-ID> with your channel ID.
channel_ID = "<YOUR-CHANNEL-ID>"

# The hostname of the ThingSpeak MQTT broker.
mqtt_host = "mqtt3.thingspeak.com"

# Your MQTT credentials for the device
mqtt_client_ID = "<YOUR-CLIENT-ID>"
mqtt_username  = "<YOUR-USERNAME>"
mqtt_password  = "<YOUR-MQTT-PASSWORD>"

3) 定义连接类型为websockets,端口设置为80

t_transport = "websockets"
t_port = 80

4) 创建主题字符串,格式如Publish to a Channel Feed,同时更新指定通道的字段1和字段2。

# Create the topic string.
topic = "channels/" + channel_ID + "/publish"

5) 运行一个循环,每 20 秒计算一次系统 RAM 和 CPU 性能并发布计算值。使用 WebSockets 同时发布到指定通道的字段 1 和字段 2。

while (True):

    # get the system performance data over 20 seconds.
    cpu_percent = psutil.cpu_percent(interval=20)
    ram_percent = psutil.virtual_memory().percent

    # build the payload string.
    payload = "field1=" + str(cpu_percent) + "&field2=" + str(ram_percent)

    # attempt to publish this data to the topic.
    try:
        print ("Writing Payload = ", payload," to host: ", mqtt_host, " clientID= ", mqtt_client_ID, " User ", mqtt_username, " PWD ", mqtt_password)
        publish.single(topic, payload, hostname=mqtt_host, transport=t_transport, port=t_port, client_id=mqtt_client_ID, auth={'username':mqtt_username,'password':mqtt_password})
    except (keyboardInterrupt)
        break
    except Exception as e:
        print (e) 

运行程序并观看通道以获取设备上的定期更新。

另请参阅

|

相关示例

详细信息