メインコンテンツ

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

MQTT 経由で Particle Device Client を使用して ThingSpeakチャネルにパブリッシュする

この例では、ホウ素、アルゴン、光子、電子などの粒子デバイスを使用して、MQTT 経由で測定値を ThingSpeakチャネルに公開する方法を示します。ThingSpeak に送信する値が複数ある場合は、複数の値をチャネルフィードに公開できます。あるいは、センサーが 1 つしかない場合は、チャネルフィールドに 1 つの値を公開できます。

セットアップ

1) 新しいチャネルでデータを収集する に示すように、新しいチャネルを作成します。使用する予定のすべてのフィールドを必ず有効にしてください。

2) ThingSpeak ページの上部にある [Devices] > [MQTT] をクリックし、[Add Device] をクリックして MQTT デバイスを作成します。デバイスをセットアップし、新しいチャネルを承認済みリストに追加するときに、[Download Credentials] > [Plain Text] をクリックします。以下のコード セクションで保存した資格情報を使用します。詳細は、ThingSpeak MQTTデバイスを作成するを参照してください。

3) Particle IDE にライブラリ MQTT/MQTT.h を含めます。

コード

1) ThingSpeak との通信に使用する変数を定義します。独自の ID と資格情報のコードを編集します。

// This #include statement is automatically added by the Particle IDE.
#include <MQTT.h>

const long channelId = YOUR_THINGSPEAK_CHANNEL_NUMBER; // Change this to your ThingSpeak channel number.
String clientId = "MQTT_CLIENDID_FROM_THINGSPEAK";
String username = "MQTT_USERNAME_FROM_THINGSPEAK";
String password = "MQTT_PASSWORD_FROM_THINGSPEAK";
char server[] = "mqtt3.thingspeak.com";

2) 最後の接続時間を追跡し、グローバル変数を使用して公開データの時間間隔を定義します。MQTT クライアントを初期化します。

unsigned long lastConnectionTime = 0;
const unsigned long postingInterval = 20L * 1000L; // Post data every 20 seconds. 

int strength = WiFi.RSSI();
int power = 10^(strength/10);

MQTT client(server, 1883, callback);               // Initialize the MQTT client.

3) MQTT クライアントのコールバック関数を定義します。この場合、setup 関数は意図的に空になります。

// Define a callback function to initialize the MQTT client.
void callback(char* topic, byte* payload, unsigned int length) {
}
void setup() {
}

4) メインの loop 関数で MQTT 接続を確立し、一定の間隔でチャネルにデータを公開します。

void loop() {
    // If MQTT client is not connected then reconnect.
    if (!client.isConnected()) {
      reconnect();
    }
    
    // Call the loop continuously to establish connection to the server.
    client.loop();  
    
    if (millis() - lastConnectionTime > postingInterval) {
        mqttpublish();
    }
}

5) mqttpublish メソッドを使用して、センサー データを ThingSpeakチャネルフィードに公開します。チャネルフィードに公開する場合は、一度に複数のフィールドに公開できます。センサーが 1 つしかない場合は、単一のフィールドに直接公開できます。必要に応じて、次のコードのコメント行を変更します。

void mqttpublish() {
    
    //Get SSID signal strength
    strength = WiFi.RSSI();
    
    //Power in milliwatts
    power = 10^(strength/10);
    
    // Create a data string to send data to ThingSpeak.
    // Use these lines to publish to a channel feed, which allows multiple fields to be updated simultaneously.
    // String data = String("field1=" + String(strength) + "&field2=" + String(power) );
    // String topic = String("channels/"+String(channelId)+ "/publish");
    
    // Use the next two to publish to a single channel field directly.
    String data = String(strength);
    String topic = String("channels/"+String(channelId)+ "/publish/fields/field1");
    
    client.publish(topic,data);
    
    lastConnectionTime = millis();
}

6) 一意のクライアント ID を生成し、reconnect 関数を使用してParticle Photon MQTT クライアントを ThingSpeak MQTT ブローカーに接続します。

void reconnect(){
    
    Particle.publish("Attempting MQTT connection");
        
    // Connect to the ThingSpeak MQTT broker.
    if (client.connect(clientId,username,password))  {
        // Track the connection with particle console.
        Particle.publish("Conn:"+ String(server) + " cl: " + String(clientId)+ " Uname:" + String(username));
    } else {
        Particle.publish("Failed to connect. Trying to reconnect in 2 seconds");
        delay(2000);
    } 
}

参考

|

トピック