メインコンテンツ

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

Raspberry Pi で Python の WebSocket を使用して公開する

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

設定

1) 新しいチャネルでデータを収集する に示すように、新しいチャネルを作成します。

2) ThingSpeak ページの上部にある [Devices] > [MQTT] をクリックし、[Add Device] をクリックして 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) 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) 指定されたチャネルのフィールド 1 とフィールド 2 を同時に更新する、チャネルフィードに公開 に示す形式のトピック文字列を作成します。

# 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) 

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

参考

|

トピック