Advertisement
TolentinoCotesta

Google API library, double-core

Jan 9th, 2021
1,514
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 7.68 KB | None | 0 0
  1. #include <time.h>
  2. #include <sys/time.h>  
  3. #include <Ticker.h>
  4. #include <FS.h>            
  5. #include <GoogleDrive.h>
  6. #include "soc/rtc_wdt.h"
  7.  
  8. // Timezone definition to get properly time from NTP server
  9. #define MYTZ "CET-1CEST,M3.5.0,M10.5.0/3"
  10.  
  11. #include <SPIFFS.h>
  12. const char* fsName = "SPIFFS";
  13. #define fileSystem SPIFFS
  14.  
  15. /*
  16. #include <FFat.h>
  17. const char* fsName = "FFat";
  18. #define fileSystem FFat
  19. */
  20.  
  21. // WiFi setup
  22. const char* ssid        =  "xxxxxxxxxxx";     // SSID WiFi network
  23. const char* password    =  "xxxxxxxxxxx";     // Password  WiFi network      
  24.  
  25. /* https://developers.google.com/identity/protocols/OAuth2ForDevices#creatingcred */
  26. const char* CLIENT_ID     =  "xxxxxxxxxx-6d2s2ne5v1eoapxxxxxxxxxxxxgp5gk7.apps.googleusercontent.com";
  27. const char* CLIENT_SECRET =  "JqfXMxxxxxxxBr_4unmi4jEmS";
  28. const char* SCOPES        =  "https://www.googleapis.com/auth/drive.file email profile";
  29.  
  30. struct tm timeinfo;
  31. const char * getUpdatedtime(const uint32_t timeout);
  32. bool fsOK = false;
  33. #define FORMAT_IF_FAILED true   // Format filesystem if needed
  34.  
  35. const char *hostname = "espfs";
  36. #include "espWebserver.h"
  37.  
  38. GoogleDriveAPI myDrive(&fileSystem, NULL );
  39.  
  40. // With Google Drive, we need the id of folder and files in order to access and work with
  41. // In this example, all files managed from the device will be stored in folder APP_FOLDERNAME
  42. const char* APP_FOLDERNAME = "AppData";   // Google Drive online folder name
  43.  
  44. bool startUpload = false;
  45.  
  46. void setup(){
  47.     Serial.begin(115200);
  48.  
  49.     String taskMessage = "Setup running on core ";
  50.     taskMessage = taskMessage + xPortGetCoreID();
  51.     Serial.println(taskMessage);
  52.  
  53.     TaskHandle_t TaskUpload;
  54.     xTaskCreatePinnedToCore(
  55.                     coreTask,              /* Function to implement the task */
  56.                     "coreTask",            /* Name of the task */
  57.                     20000,                /* Stack size in words */
  58.                     (void*)&startUpload,   /* Task input parameter */
  59.                     0,                     /* Priority of the task */
  60.                     &TaskUpload,           /* Task handle. */
  61.                     0);                    /* Core where the task should run */
  62.  
  63.     Serial.println("Task created...");
  64.  
  65.     // WiFi INIT
  66.     startWiFi();
  67.  
  68.     // FILESYSTEM INIT
  69.     startFilesystem();
  70.  
  71.     // Sync time with NTP. Blocking, but with timeout (0 == no timeout)
  72.     const char* nowTime = getUpdatedtime(5000);    
  73.     Serial.printf("Time: %s\n", nowTime);
  74.  
  75.     // Add custom handler for webserver
  76.     server.on("/sendToDrive", HTTP_GET, [](){
  77.         server.send(200, "text/plain", "Start uploading file to Drive");
  78.         startUpload = true;
  79.     });
  80.  
  81.     // WEB SERVER INIT
  82.     startWebServer();
  83.  
  84.     // Print some information about heap memory before use init the library
  85.     printHeapStats();
  86.  
  87.     // Begin, after wait authorize if necessary (with 60s timeout)
  88.     if (myDrive.begin(CLIENT_ID, CLIENT_SECRET, SCOPES)){
  89.         uint32_t timeout = millis();
  90.         while (myDrive.getState() != GoogleDriveAPI::GOT_TOKEN){
  91.  
  92.             // Notify user about pending authorization required https//www.google.come/device with user_code
  93.             if(myDrive.getState() == GoogleDriveAPI::REQUEST_AUTH){
  94.                 Serial.println(F("\nApplication need to be authorized!"));
  95.                 Serial.print(F("Open with a browser the address < https//www.google.come/device > and insert this confirmation code "));
  96.                 Serial.println(myDrive.getUserCode());
  97.             }
  98.            
  99.             // Wait for user authorization on https//www.google.come/device
  100.             delay(10000);
  101.             if(millis() - timeout > 60000) break;
  102.         }
  103.  
  104.  
  105.         // Check if the "app folder" is present in your Drive
  106.         if (myDrive.getState() == GoogleDriveAPI::GOT_TOKEN){
  107.             String appFolderId =  myDrive.searchFile(APP_FOLDERNAME);
  108.  
  109.             if (appFolderId.length() < 30 ) {  
  110.                 Serial.println("Folder APP not present. Now it will be created.");
  111.                 myDrive.createFolder(APP_FOLDERNAME, "root");
  112.             }
  113.             else {
  114.                 // Save the folder id for easy retrieve when needed
  115.                 myDrive.setAppFolderId(appFolderId);
  116.                 Serial.printf("App folder id: %s\n", appFolderId.c_str());
  117.             }
  118.         }
  119.     }
  120.  
  121. }
  122.  
  123.    
  124.  
  125. void loop(){
  126.     server.handleClient();
  127.  
  128.     // Print information about memory state
  129.     static uint32_t printTime;
  130.     if(millis() - printTime > 5000){
  131.         printTime = millis();
  132.         printHeapStats();
  133.     }
  134. }
  135.  
  136.  
  137. // This task will run on core 0, while loop() default task is number 1
  138. // Once the bool global var startUpload == true, upload will start without interfer to other things
  139. void coreTask( void * pvParam ){
  140.  
  141.     String taskMessage = "Task running on core ";
  142.     taskMessage = taskMessage + xPortGetCoreID();
  143.  
  144.     while(true){
  145.         if(startUpload){
  146.             // Disable temporarily watchdog for core 0
  147.             disableCore0WDT();
  148.             uploadToDrive();
  149.             enableCore0WDT();
  150.             startUpload = false;
  151.         }
  152.         vTaskDelay(10);
  153.     }
  154.     vTaskDelete(NULL);
  155. }
  156.  
  157.  
  158. void uploadToDrive(){    
  159.     Serial.println(F("\n\nUploading a new file to Drive \"/audio.wav\""));
  160.     uint32_t startTime = millis();
  161.  
  162.     // If uploadedId is a valid Google ID, upload was succesfull
  163.     String uploadedId = myDrive.uploadFile("/audio.wav", myDrive.getAppFolderId(), false);    
  164.  
  165.     if(uploadedId.length()){  
  166.         String text =  F("File uploaded to Drive with id ");
  167.         text += uploadedId;
  168.         Serial.println(text);        
  169.     }
  170.     else{
  171.         server.send(200, "text/plain", "Error");  
  172.         Serial.print(F("\nError. File not uploaded correctly."));
  173.     }
  174.  
  175.     Serial.printf("Upload time %d ms\n",  millis() - startTime);
  176. }
  177.  
  178.  
  179. void startFilesystem(){
  180.     // FILESYSTEM INIT
  181.  
  182.     //fileSystem.format();
  183.     fsOK = fileSystem.begin(FORMAT_IF_FAILED);
  184.     if (fsOK){
  185.         File root = fileSystem.open("/", "r");
  186.         File file = root.openNextFile();
  187.         while (file){
  188.             const char* fileName = file.name();
  189.             size_t fileSize = file.size();
  190.             Serial.printf("FS File: %s, size: %lu\n", fileName, (long unsigned)fileSize);
  191.             file = root.openNextFile();
  192.         }
  193.         Serial.println();
  194.     }
  195. }
  196.  
  197.  
  198.  
  199. void startWiFi(){
  200.     Serial.printf("Connecting to %s\n", ssid);
  201.     if (String(WiFi.SSID()) != String(ssid)){
  202.         WiFi.mode(WIFI_STA);
  203.         WiFi.begin(ssid, password);
  204.     }
  205.     while (WiFi.status() != WL_CONNECTED){
  206.         delay(500);
  207.         Serial.print(".");
  208.     }
  209.     Serial.print("\nConnected! IP address: ");
  210.     Serial.println(WiFi.localIP());
  211.  
  212.     WiFi.setHostname(hostname);
  213.     MDNS.begin(hostname);
  214.     Serial.printf("Open http://%s.local/edit to edit or upload files\n", hostname);
  215.  
  216.     // Set timezone and NTP servers
  217.     configTzTime(MYTZ, "time.google.com", "time.windows.com", "pool.ntp.org");
  218. }
  219.  
  220.  
  221. const char * getUpdatedtime(const uint32_t timeout) {
  222. #define BUF_SIZE 40
  223.     uint32_t start = millis();
  224.     Serial.print("Sync time...");
  225.     do {
  226.         time_t now = time(nullptr);
  227.         timeinfo = *localtime(&now);
  228.         delay(1);
  229.     } while(millis() - start < timeout  && timeinfo.tm_year <= (1970 - 1900));
  230.  
  231.     Serial.println(" done.");
  232.  
  233.     char * buffer = new char[BUF_SIZE];
  234.     buffer[BUF_SIZE] = '\0';
  235.  
  236.     strftime (buffer, 40, "%A, %d/%m/%Y %H:%M:%S", &timeinfo);
  237.     return (const char*) buffer;
  238. }
  239.  
  240.  
  241. void printHeapStats(){
  242.     Serial.printf("\nTotal free: %6d - Max block: %6d\n", heap_caps_get_free_size(0), heap_caps_get_largest_free_block(0));
  243. }
  244.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement