Main Content

このページの翻訳は最新ではありません。ここをクリックして、英語の最新版を参照してください。

Raspberry Pi ボードを使用してデータを継続的に収集し、ThingSpeak チャネルを一括更新

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

 チャネル フィードを一括更新するPython 2.7 コード

  1. 新しいチャネルでデータの収集での説明に従ってチャネルを作成します。

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

    import urllib2 as ul
    import json
    import time
    import os
    import psutil
    

  3. グローバル変数を定義して、最終接続日時と最終更新日時を追跡します。また、データを更新する時間間隔を定義し、データを ThingSpeak にポストします。

    lastConnectionTime = time.time() # Track the last connection time
    lastUpdateTime = time.time() # Track the last update time
    postingInterval = 120 # Post data once every 2 minutes
    updateInterval = 15 # Update once every 15 seconds

  4. ThingSpeak サーバー設定と共に、Write API キーやチャネル ID などの ThingSpeak チャネル設定を定義します。

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

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

    def httpRequest():
    	'''Function to send the POST request to 
    	ThingSpeak channel for bulk update.'''
    
    	global messageBuffer
    	data = json.dumps({'write_api_key':writeAPIkey,'updates':messageBuffer}) # Format the json data buffer
    	req = ul.Request(url = url)
    	requestHeaders = {"User-Agent":"mw.doc.bulk-update (Raspberry Pi)","Content-Type":"application/json","Content-Length":str(len(data))}
    	for key,val in requestHeaders.iteritems(): # Set the headers
    		req.add_header(key,val)
    	req.add_data(data) # Add the data to the request
        # Make the request to ThingSpeak
    	try:
    		response = ul.urlopen(req) # Make the request
    		print response.getcode() # A 202 indicates that the server has accepted the request
    	except ul.HTTPError as e:
    		print e.code # Print the error code
    	messageBuffer = [] # Reinitialize the message buffer
    	global lastConnectionTime
    	lastConnectionTime = time.time() # Update the connection time
    

  6. 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()
    	cpuTemp = process.split('=')[1].split("'")[0]
    	cpuUsage = psutil.cpu_percent(interval=2)
    	return cpuTemp,cpuUsage
    

  7. メッセージ バッファーを 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 lastUpdateTime
    	message = {}
    	message['delta_t'] = time.time() - lastUpdateTime
    	Temp,Usage = getData()
    	message['field1'] = Temp
    	message['field2'] = Usage
    	global messageBuffer
    	messageBuffer.append(message)
        # If posting interval time has crossed 2 minutes update the ThingSpeak channel with your data
    	if time.time() - lastConnectionTime >= postingInterval:
    		httpRequest()
    	lastUpdateTime = time.time()
        
    
  8. 無限ループを実行して、関数 updatesJson を 15 秒に 1 回、継続的に呼び出します。

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

関連する例

詳細