/*
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp32-datalogging-google-sheets/
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
Adapted from the examples of the Library Google Sheet Client Library for Arduino devices: https://github.com/mobizt/ESP-Google-Sheet-Client
*/
#include <Arduino.h>
#include <WiFi.h>
#include "time.h"
#include <ESP_Google_Sheet_Client.h>
// For SD/SD_MMC mounting helper
#include <GS_SDHelper.h>
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// Google Project ID
#define PROJECT_ID "testwokwi-414503"
// Service Account's client email
#define CLIENT_EMAIL "[email protected]"
// Service Account's private key
const char PRIVATE_KEY[] PROGMEM = "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCqfetEg42qTjgi\nOXkZMSzUWx2kLH73Iku8wBMDXiV4tqc58qF65Cf6IXJ+dmjlXC8cqrq+emh7XKV3\ny6bA5ggJgFlhUq1aJMBCI6x6ODJ+PQIapexzXYIa5E0g0lx+sBGCnkniMt34ijKq\nQapGn+bhLsYEf93zIF8yimhaLXXzNsA1gDBVL70TZCg4uj0QbBQUgd0OEmOCsrEJ\nmae5tHhJBu3wR34jeTm3yr4fut+tqKJrnlMQItnUu5kg6CsSQfOSl/M4zeNd0oGZ\nsrKEICNy5t24hwiQcQ9WWNemwy+dVPo2hT0pwgMImrVo44j2ppAR8Lr8oD023bAt\nXkNlQBoHAgMBAAECggEAOJtBQ4jIPvzkf1yEvBwLLeCoyUsqxqQg8GT3ix01pMxE\nXqWT/ukE6vQy/xESh+ChFcwL39Vlnlvm5oz76z0U+w6d3oXkX7MnEG6mxBenkCly\nauWfSbiIy6P0hcrCgh+0WKF0l4FbGLvN0aCmx/csYaS1g2XvC9u6L94rgpFogZ0n\nguco7n1Gtg4KuJz9yu5YpbOkHq+aZ/pDRmHo3VpxRbksUPhvBmPWVW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data
const char spreadsheetId[] = "1uw2-SINiyTh3d0-5kewrhqvque7_WiytMm61uEDkxKI";
// Timer variables
unsigned long lastTime = 0;
unsigned long timerDelay = 1000;
// Token Callback function
void tokenStatusCallback(TokenInfo info);
// NTP server to request epoch time
const char* ntpServer = "pool.ntp.org";
// Variable to save current epoch time
unsigned long epochTime;
// Function that gets current epoch time
unsigned long getTime() {
time_t now;
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
//Serial.println("Failed to obtain time");
return(0);
}
time(&now);
return now;
}
void setup(){
pinMode(22,INPUT_PULLUP);
pinMode(16,INPUT_PULLUP);
Serial.begin(115200);
Serial.println();
Serial.println();
//Configure time
configTime(0, 0, ntpServer);
GSheet.printf("ESP Google Sheet Client v%s\n\n", ESP_GOOGLE_SHEET_CLIENT_VERSION);
// Connect to Wi-Fi
WiFi.setAutoReconnect(true);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(1000);
}
Serial.println();
Serial.print("Connected with IP: ");
Serial.println(WiFi.localIP());
Serial.println();
// Set the callback for Google API access token generation status (for debug only)
GSheet.setTokenCallback(tokenStatusCallback);
// Set the seconds to refresh the auth token before expire (60 to 3540, default is 300 seconds)
GSheet.setPrerefreshSeconds(10 * 60);
// Begin the access token generation for Google API authentication
GSheet.begin(CLIENT_EMAIL, PROJECT_ID, PRIVATE_KEY);
}
void loop(){
// Call ready() repeatedly in loop for authentication checking and processing
bool ready = GSheet.ready();
// if (ready && millis() - lastTime > timerDelay){
// lastTime = millis();
FirebaseJson response;
Serial.println("\nAppend spreadsheet values...");
Serial.println("----------------------------");
FirebaseJson valueRange;
// // New BME280 sensor readings
// temp = bme.readTemperature();
// //temp = 1.8*bme.readTemperature() + 32;
// hum = bme.readHumidity();
// pres = bme.readPressure()/100.0F;
// Get timestamp
epochTime = getTime();
int pb1 = digitalRead(22);
int pb2 = digitalRead(16);
valueRange.add("majorDimension", "COLUMNS");
valueRange.set("values/[0]/[0]", epochTime);
valueRange.set("values/[1]/[0]", pb1);
valueRange.set("values/[2]/[0]", pb2);
// valueRange.set("values/[3]/[0]", pres);
// For Google Sheet API ref doc, go to https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append
// Append values to the spreadsheet
bool success = GSheet.values.append(&response /* returned response */, spreadsheetId /* spreadsheet Id to append */, "Sheet1!A1" /* range to append */, &valueRange /* data range to append */);
if (success){
response.toString(Serial, true);
valueRange.clear();
}
else{
Serial.println(GSheet.errorReason());
}
Serial.println();
Serial.println(ESP.getFreeHeap());
// }
delay(500);
}
void tokenStatusCallback(TokenInfo info){
if (info.status == token_status_error){
GSheet.printf("Token info: type = %s, status = %s\n", GSheet.getTokenType(info).c_str(), GSheet.getTokenStatus(info).c_str());
GSheet.printf("Token error: %s\n", GSheet.getTokenError(info).c_str());
}
else{
GSheet.printf("Token info: type = %s, status = %s\n", GSheet.getTokenType(info).c_str(), GSheet.getTokenStatus(info).c_str());
}
}