このページは機械翻訳を使用して翻訳されました。最新版の英語を参照するには、ここをクリックします。
Particle Photon Board を使って ThingSpeakチャネルを一括更新
この例では、Wi-Fi® ネットワークに接続されたParticle Photonボードを使用して、ThingSpeak ™チャネルを一括更新方法を示します。Bulk-Write JSON
Data
API を使用すると、データを一括収集し、ThingSpeakチャネルに送信できます。一括更新を使用すると、デバイスの電力消費を削減できます。この例では、 Particle Photonボードを使用して 15 秒ごとにデータを収集し、2 分ごとにチャネルを更新します。Particle Photon にはリアルタイム クロックが搭載されているため、一括更新メッセージに絶対タイムスタンプを使用できます。
設定
1) 「新しいチャネルでデータを収集する」に示すように、チャネルを作成します。
コード
1) Particle Cloudからの時間を同期するための 1 日の制限を定義します。
#define ONE_DAY_MILLIS (24 * 60 * 60 * 1000) // Define 1 day limit for time synchronization unsigned long lastSync = millis();
2) データを保持するために data
バッファを初期化します。
char data[800] = ""; // Initialize the data buffer
3) TCP クライアント ライブラリを初期化します。
TCPClient client; // Initialize the TCP client library
4) ThingSpeak サーバー、チャネル書き込み API キー、およびチャネルID を定義します。
String server = "api.thingspeak.com"; // ThingSpeak Server. String WriteAPIKey = "YOUR-CHANNEL-WRITEAPIKEY"; // Replace YOUR-CHANNEL-WRITEAPIKEY with your channel write API key. String ChannelID = "YOUR-CHANNEL-ID"; // Replace YOUR-CHANNEL-ID with your channel ID.
5) 最後の接続時間と最後の更新時間を追跡するグローバル変数を作成します。次に、データを更新する時間間隔を定義し、データを ThingSpeak に投稿します。
/* Collect data once every 15 seconds and post data to ThingSpeak channel once every 2 minutes. */ unsigned long lastConnectionTime = 0; // Track the last connection time. unsigned long lastUpdateTime = 0; // Track the last update time. const unsigned long postingInterval = 120L * 1000L; // Post data every 2 minutes. const unsigned long updateInterval = 15L * 1000L; // Update once every 15 seconds. size_t state = 0; // Keep note of first time the updateData() is called.
6) デフォルトの setup
メソッドを変更しないでください。
void setup() { }
7) loop
メソッドを使用して updateData
メソッドを呼び出し、15 秒ごとに data
バッファをデータで更新します。また、1 日に 1 回、 Particle Cloudに時刻同期を要求。
void loop() { // If update time has reached 15 seconds, then update the data buffer if (millis() - lastUpdateTime >= updateInterval) { updateData(); } // If last time synchronization is more than one day if (millis() - lastSync > ONE_DAY_MILLIS) { // Request time synchronization from the Particle Cloud Particle.syncTime(); lastSync = millis(); } }
8) data
バッファをデータで継続的に更新するための updateData
メソッドを定義します。Particle Photonにはリアルタイム クロックが組み込まれているため、API 呼び出しで絶対時間を使用できます。連続するメッセージ間の絶対タイムスタンプを定義するには、time_format=absolute
パラメーターを使用します。デバイスにリアルタイム クロックが搭載されていない場合は、相対タイムスタンプを使用できます。相対タイムスタンプを使用するには、time_format=absolute
を time_format=relative
に置き換えます。Bulk-Write JSON Data
で説明されているように、メッセージを CSV 形式でフォーマットします。httpRequest
メソッドを呼び出して、2 分ごとに ThingSpeak にデータを送信します。
// Update the data buffer void updateData(){ /* CSV format to bulk update. * This function uses the absolute timestamp as it uses the "time_format=absolute" parameter. If your device does not have a real-time clock, * you can also provide the relative timestamp in seconds using the "time_format=relative" parameter. */ if(state==0){ strcpy(data,"write_api_key="+WriteAPIKey+"&time_format=absolute&updates="); } strcat(data,String(Time.local())); // Absolute time stamp. strcat(data,"%2C"); // URL encoding for "," long randNumber = random(1,300); strcat(data,String(randNumber)); // Data to post to field 1. strcat(data,"%2C"); randNumber = random(1,300); strcat(data,String(randNumber)); // Data to post to field 2. strcat(data,"%2C%2C%2C%2C%2C%2C%2C%2C"); //Include commas after fields 2-8 and lattitude for 8 commas. randNumber = random(1,300); strcat(data,String(randNumber)); // Mock data to post to longitude. strcat(data,"%2C%7C"); // URL encoding for ",|". End with | at the end of a message. state = 1; // If posting interval time has reached 2 minutes, then update the ThingSpeak channel with your data. if (millis() - lastConnectionTime >= postingInterval) { state = 0; size_t len = strlen(data); data[len-3] = '\0'; // Remove the | from the last message. httpRequest(data); // Call httpRequest to send the data to ThingSpeak. data[0] = '\0'; // Reinitialise the data buffer. } lastUpdateTime = millis(); // Update the last update time. }
9) ThingSpeak にデータを送信し、サーバーからの応答コードを印刷するための httpRequest
メソッドを定義します。応答コード 202
は、サーバーが要求を受け入れ、データを処理していることを示します。
// Update the ThingSpeakchannel with data. void httpRequest(char* csvBuffer) { /* CSV format to bulk update. * This function posts the data to ThingSpeak server. */ // Compute the data buffer length. String data_length = String(strlen(csvBuffer)); // Close any connection before sending a new request. client.stop(); // POST data to ThingSpeak if (client.connect(server, 80)) { client.println("POST /channels/"+ChannelID+"/bulk_update HTTP/1.1"); client.println("Host: "+server); client.println("User-Agent: mw.doc.bulk-update (Particle Photon)"); client.println("Connection: close"); client.println("Content-Type: application/x-www-form-urlencoded"); client.println("Content-Length: "+data_length); client.println(); client.println(csvBuffer); } else { Particle.publish("Failure","Failed to update ThingSpeak channel"); } delay(1000); // Wait to receive the response. client.parseFloat(); String resp = String(client.parseInt()); Particle.publish("Response code",resp); // Print the response code. 202 indicates that the server has accepted the response. lastConnectionTime = millis(); // Update the last conenction time. }