このページは機械翻訳を使用して翻訳されました。ここをクリックして、元の英語を参照してください。
Particle Photon Board を使用したThingSpeakチャネルの一括更新
この例では、Wi-Fi® ネットワークに接続されたParticle Photonボードを使用してThingSpeak™チャネルを一括更新方法を示します。Bulk-Write JSON
Data
API を使用してデータをバッチで収集し、 ThingSpeakチャネルに送信できます。一括アップデートを使用すると、デバイスの電力消費を削減できます。この例では、Particle Photon ボードを使用して 15 秒ごとにデータを収集し、2 分に 1 回チャネルを更新します。Particle Photonにはリアルタイム クロックが付属しているため、一括更新メッセージに絶対タイム スタンプを使用できます。
設定
1) Collect Data in a New Channel に示すように、チャネルを作成します。
コード
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
メソッドを呼び出し、data
バッファを 15 秒ごとにデータで更新します。さらに、毎日 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) updateData
メソッドを定義して、data
バッファをデータで継続的に更新します。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. }