Main Content

このページは機械翻訳を使用して翻訳されました。元の英語を参照するには、ここをクリックします。

Raspberry Pi 上の Python で WebSocket を使用してパブリッシュする

この例では、ポート 80 で WebSocket を使用し、Python を実行する Raspberry Pi ボードを使用してThingSpeakチャネルに公開する方法を示します。ThingSpeakに送信したいセンサー値が複数ある場合は、複数の値をチャネルフィードに公開できます。この例では、Raspberry Pi ボードの CPU と RAM の使用率データが 20 秒ごとに収集され、その値がチャネルフィードに公開されます。また、更新する値が 1 つのみの場合は、単一の値をチャネル フィールドにパブリッシュできます。

設定

1) Collect Data in a New Channelに示すように、新しいチャネルを作成します。

2) ThingSpeakページの上部にある デバイス > MQTT をクリックし、次に デバイスの追加 をクリックして、MQTT デバイスを作成します。デバイスをセットアップし、新しいチャネルを認証リストに追加するときに、Download Credentials > Plain Text をクリックします。詳細については、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) ライブラリpaho.mqtt.publish as publishpsutil、およびstringを Python コードに含めます。

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) 指定されたチャネルのフィールド 1 とフィールド 2 を同時に更新するPublish to a Channel Feedに示す形式でトピック文字列を作成します。

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

5) システム RAM と CPU パフォーマンスを 20 秒ごとに計算し、計算された値を公開するループを実行します。WebSocket を使用して、指定されたチャネルのフィールド 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) 

プログラムを実行し、デバイスから定期的に更新されるチャネルを監視します。

参考

|

関連する例

詳細