このページは機械翻訳を使用して翻訳されました。最新版の英語を参照するには、ここをクリックします。
Raspberry Piボードを使った一括更新
この例では、Python 2.7 を実行している Wi-Fi 接続の Raspberry Pi ボードを使用してデータを収集する方法を示します。15 秒ごとに CPU 温度と CPU 使用率を継続的に収集し、2 分ごとに ThingSpeakチャネルを一括更新。この例では、Bulk-Write JSON Data API を使用してデータをバッチとして収集し、ThingSpeakチャネルに送信します。一括更新を使用すると、デバイスの電力消費を削減できます。Raspberry Pi ボードにはリアルタイム クロックが搭載されていないため、一括更新メッセージには相対タイムスタンプを使用できます。
設定
新しいチャネルでデータを収集するに示すようにチャネルを作成します。
コード
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) メッセージ バッファーを 15 秒ごとに継続的に更新する関数 updatesJson を定義します。
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()