Main Content

Questa pagina è stata tradotta con la traduzione automatica. Fai clic qui per vedere l’originale in inglese.

Aggiornamento in blocco di un canale ThingSpeak utilizzando una scheda fotonica a particelle

Questo esempio mostra come utilizzare una scheda Particle Photon connessa a una rete Wi-Fi® per aggiornare in blocco un canale ThingSpeak™ . È possibile utilizzare l'API Bulk-Write JSON Data per raccogliere dati in un batch e inviarli ai canali ThingSpeak . Utilizzando l'aggiornamento collettivo, puoi ridurre il consumo energetico dei tuoi dispositivi. In questo esempio, raccogli dati ogni 15 secondi e aggiorni il tuo canale una volta ogni 2 minuti utilizzando una scheda Particle Photon. Poiché Particle Photon è dotato di un orologio in tempo reale, è possibile utilizzare l'indicazione temporale assoluta per i messaggi di aggiornamento collettivo.

Impostazione

1) Creare un canale, come mostrato in Collect Data in a New Channel.

Codice

1) Definire un limite di un giorno per sincronizzare l'ora da Particle Cloud.

#define ONE_DAY_MILLIS (24 * 60 * 60 * 1000) // Define 1 day limit for time synchronization
unsigned long lastSync = millis(); 

2) Inizializzare il buffer data per contenere i dati.

char data[800] = ""; // Initialize the data buffer

3) Inizializzare la libreria client TCP.

TCPClient client; // Initialize the TCP client library

4) Definire il server ThingSpeak , la chiave API di scrittura del canale e l'ID del canale.

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) Creare variabili globali che tengano traccia dell'ora dell'ultima connessione e dell'ora dell'ultimo aggiornamento. Quindi definire gli intervalli di tempo per aggiornare i dati e pubblicare i dati su 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) Non modificare il metodo setup predefinito.

void setup() {
}

7) Utilizzare il metodo loop per chiamare il metodo updateData per aggiornare il buffer data con i dati una volta ogni 15 secondi. Inoltre, richiedi la sincronizzazione dell'ora da Particle Cloud una volta al giorno.

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) Definire il metodo updateData per aggiornare continuamente il buffer data con i dati. Poiché Particle Photon ha un orologio in tempo reale integrato, puoi utilizzare l'ora assoluta nella chiamata API. Utilizzare il parametro time_format=absolute per definire timestamp assoluti tra messaggi successivi. Se il tuo dispositivo non dispone di un orologio in tempo reale, puoi utilizzare un timestamp relativo. Per utilizzare timestamp relativi, sostituire time_format=absolute con time_format=relative. Formatta i messaggi in formato CSV come menzionato in Bulk-Write JSON Data. Chiamare il metodo httpRequest per inviare dati a ThingSpeak ogni due minuti.

// 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) Definire il metodo httpRequest per inviare dati a ThingSpeak e stampare il codice di risposta dal server. Il codice di risposta 202 indica che il server ha accettato la richiesta e sta elaborando i dati.

// 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.
}

Esempi correlati

Ulteriori informazioni