Main Content

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

Raspberry Pi ボードを使用した一括更新

この例では、Python 2.7 を実行している Wi-Fi 接続された Raspberry Pi ボードを使用してデータを収集する方法を示します。CPU 温度と CPU 使用率を 15 秒ごとに継続的に収集し、 ThingSpeakチャネルを2 分ごとに一括更新できます。この例では、Bulk-Write JSON Data API を使用してデータをバッチとして収集し、 ThingSpeakチャネルに送信します。一括更新を使用すると、デバイスの電力消費を削減できます。Raspberry Pi ボードにはリアルタイム クロックが付属していないため、一括更新メッセージには相対タイムスタンプを使用できます。

設定

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

コード

1) スクリプトに必要なライブラリをインポートします。

import json
import time
import os
import psutil
import requests

2) 最終接続時刻と最終更新時刻を追跡するグローバル変数を定義します。データを更新する時間間隔を定義し、データをThingSpeakに投稿します。

last_connection_time = time.time() # Track the last connection time
last_update_time = time.time()     # Track the last update time
posting_interval = 120             # Post data once every 2 minutes
update_interval = 15               # Update once every 15 seconds

3) ThingSpeak書き込み API キーとチャネルID 設定、およびThingSpeakサーバー設定を定義します。

write_api_key = "YOUR-CHANNEL-WRITEAPIKEY" # Replace YOUR-CHANNEL-write_api_key with your channel write API key
channel_ID = "YOUR-CHANNELID"              # Replace YOUR-channel_ID with your channel ID
url = "https://api.thingspeak.com/channels/" + channel_ID + "/bulk_update.json" # ThingSpeak server settings
message_buffer = []

4) ThingSpeakにデータを送信し、サーバーからの応答コードを出力する関数httpRequestを定義します。応答コード202 は、サーバーが要求を受け入れ、処理することを示します。

def httpRequest():
    # Function to send the POST request to ThingSpeak channel for bulk update.
        global message_buffer
        bulk_data = json.dumps({'write_api_key':write_api_key,'updates':message_buffer}) # Format the json data buffer
        request_headers = {"User-Agent":"mw.doc.bulk-update (Raspberry Pi)","Content-Type":"application/json","Content-Length":str(len(bulk_data))}
    # Make the request to ThingSpeak
        try:
            print(request_headers)
            response = requests.post(url,headers=request_headers,data=bulk_data)
            print (response) # A 202 indicates that the server has accepted the request
        except e:
            print(e.code) # Print the error code
        message_buffer = [] # Reinitialize the message buffer
        global last_connection_time
        last_connection_time = time.time() # Update the connection time

5) CPU 温度を摂氏で返し、CPU 使用率をパーセンテージで返す関数getDataを定義します。

def getData():
    # Function that returns the CPU temperature and percentage of CPU utilization
        cmd = '/opt/vc/bin/vcgencmd measure_temp'
        process = os.popen(cmd).readline().strip()
        cpu_temp = process.split('=')[1].split("'")[0]
        cpu_usage = psutil.cpu_percent(interval=2)
        return cpu_temp,cpu_usage

6) 関数updatesJsonを定義して、15 秒ごとにメッセージ バッファを継続的に更新します。

def updatesJson():
    # Function to update the message buffer every 15 seconds with data. 
    # And then call the httpRequest function every 2 minutes. 
    # This examples uses the relative timestamp as it uses the "delta_t" parameter.
    # If your device has a real-time clock, you can also provide the absolute timestamp 
    # using the "created_at" parameter.

        global last_update_time
        message = {}
        message['delta_t'] = int(round(time.time() - last_update_time))
        Temp,Usage = getData()
        message['field1'] = Temp
        message['field2'] = Usage
        global message_buffer
        message_buffer.append(message)
    # If posting interval time has crossed 2 minutes update the ThingSpeak channel with your data
        if time.time() - last_connection_time >= posting_interval:
                httpRequest()
                last_update_time = time.time()

7) 無限ループを実行して、関数updatesJsonを 15 秒ごとに継続的に呼び出します。

if __name__ == "__main__":  # To ensure that this is run directly and does not run when imported
        while True:
                # If update interval time has crossed 15 seconds update the message buffer with data
            if time.time() - last_update_time >= update_interval:
                updatesJson()

関連する例

詳細