Facebook
From Aleksey Khachatryan, 1 Month ago, written in C++.
Embed
Download Paste or View Raw
Hits: 148
  1. #include "esp_camera.h"
  2. #include <WiFi.h>
  3. #include <HTTPClient.h>
  4. #include <FS.h>
  5. #include "SD_MMC.h"
  6.  
  7. // Define your WiFi credentials
  8. const char* ssid = "MYSSID";
  9. const char* password = "MYPASS";
  10.  
  11. // Google Drive upload parameters
  12. const char* gdrive_upload_url = "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable";
  13. const char* parentFolderId = "MYFOLDERID";
  14. String metadata = "{"parents":["" + String(parentFolderId) + ""]}";
  15.  
  16. uint8_t *videoBuffer = NULL;
  17. size_t bufferSize = 0;
  18. size_t maxBufferSize = 0;
  19.  
  20. // Function to connect to WiFi
  21. void connectToWiFi() {
  22.   Serial.println("Connecting to WiFi...");
  23.   WiFi.begin(ssid, password);
  24.   while (WiFi.status() != WL_CONNECTED) {
  25.     delay(1000);
  26.     Serial.println("Connecting...");
  27.   }
  28.   Serial.println("Connected to WiFi");
  29. }
  30.  
  31.  
  32. void captureAndWriteVideoToSD(uint16_t videoDurationInSeconds) {
  33.   Serial.println("Starting video capture...");
  34.  
  35.   File videoFile = SD_MMC.open("/video.mp4", FILE_WRITE);
  36.   if (!videoFile) {
  37.     Serial.println("Failed to open/create file for writing");
  38.     return;
  39.   }
  40.  
  41.   uint32_t startTime = millis();
  42.   uint32_t endTime = startTime + (videoDurationInSeconds * 1000);
  43.  
  44.   while (millis() < endTime) {
  45.  
  46.     camera_fb_t *fb = esp_camera_fb_get();
  47.  
  48.     if (fb) {
  49.       // Write frame data to the file
  50.       if (videoFile.write(fb->buf, fb->len) != fb->len) {
  51.         Serial.println("Write error occurred");
  52.         esp_camera_fb_return(fb);
  53.         break;
  54.       }
  55.       esp_camera_fb_return(fb);
  56.     } else {
  57.       Serial.println("Failed to capture frame");
  58.       break;
  59.     }
  60.   }
  61.  
  62.   // Close the file
  63.   if (videoFile) {
  64.     videoFile.close();
  65.     Serial.println("Video capture complete.");
  66.   } else {
  67.     Serial.println("Error: File not open.");
  68.   }
  69. }
  70.  
  71.  
  72. void uploadVideoToDrive() {
  73.   Serial.println("Uploading video to Google Drive...");
  74.  
  75.   // Open the file
  76.   File videoFile = SD_MMC.open("/video.mp4", FILE_READ);
  77.   if (!videoFile) {
  78.     Serial.println("Error opening video file!");
  79.     return;
  80.   }
  81.  
  82.   const size_t chunkSize = 1024; // Define the chunk size
  83.   uint8_t chunk[chunkSize]; // Declare the chunk buffer
  84.   size_t totalPayloadSize = 0; // Initialize total payload size
  85.  
  86.   // Calculate total payload size
  87.   while (videoFile.available()) {
  88.     size_t bytesRead = videoFile.readBytes((char*)chunk, chunkSize);
  89.     totalPayloadSize += bytesRead;
  90.   }
  91.   videoFile.seek(0); // Reset file pointer to the beginning
  92.  
  93.   // Make the initial POST request to get the upload session URL
  94.   HTTPClient http;
  95.   http.begin("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable");
  96.   http.addHeader("Authorization", "Bearer " + gdrive_token);
  97.   http.addHeader("Content-Type", "video/mp4");
  98.   http.addHeader("Content-Length", "0"); // Set initial Content-Length to 0
  99.  
  100.   int httpResponseCode = http.POST(""); // Send the initial POST request
  101.  
  102.   Serial.println("Initial POST request response:");
  103.   Serial.println(http.getString()); // Print response body
  104.  
  105.   if (httpResponseCode != HTTP_CODE_OK) {
  106.     Serial.print("Error initiating upload. HTTP response code: ");
  107.     Serial.println(httpResponseCode);
  108.     http.end();
  109.     videoFile.close();
  110.     return;
  111.   }
  112.  
  113.   String location = http.header("Location"); // Get the upload session URL
  114.   http.end(); // Close the connection
  115.  
  116.   Serial.print("Upload session URL: ");
  117.   Serial.println(location);
  118.  
  119.   // Check if location is empty or null
  120.   if (location.isEmpty()) {
  121.     Serial.println("Error: Upload session URL not found.");
  122.     videoFile.close();
  123.     return;
  124.   }
  125.  
  126.   // Send the file contents in chunks with the correct range headers
  127.   size_t totalBytesSent = 0; // Initialize totalBytesSent
  128.   while (videoFile.available()) {
  129.     size_t bytesRead = videoFile.readBytes((char*)chunk, chunkSize);
  130.     http.begin(location); // Use the upload session URL
  131.     http.addHeader("Authorization", "Bearer " + gdrive_token);
  132.     http.addHeader("Content-Range", "bytes " + String(totalBytesSent) + "-" + String(totalBytesSent + bytesRead - 1) + "/" + String(totalPayloadSize));
  133.    
  134.     httpResponseCode = http.sendRequest("PUT", chunk, bytesRead);
  135.     if (httpResponseCode != HTTP_CODE_OK && httpResponseCode != HTTP_CODE_CREATED) {
  136.       Serial.print("Error uploading chunk. HTTP response code: ");
  137.       Serial.println(httpResponseCode);
  138.       Serial.println(http.getString());
  139.       http.end();
  140.       videoFile.close();
  141.       return;
  142.     }
  143.    
  144.     totalBytesSent += bytesRead;
  145.     Serial.print("Uploaded ");
  146.     Serial.print(totalBytesSent);
  147.     Serial.print(" bytes out of ");
  148.     Serial.println(totalPayloadSize);
  149.    
  150.     http.end();
  151.     delay(10); // Small delay between requests
  152.   }
  153.  
  154.   Serial.println("Upload complete.");
  155.  
  156.   // Close the file
  157.   videoFile.close();
  158. }
  159.  
  160. void setup() {
  161.   Serial.begin(115200);
  162.  
  163.   // Initialize camera
  164.   camera_config_t config;
  165.   config.ledc_channel = LEDC_CHANNEL_0;
  166.   config.ledc_timer = LEDC_TIMER_0;
  167.   config.pin_d0 = 5; // Y2
  168.   config.pin_d1 = 18; // Y3
  169.   config.pin_d2 = 19; // Y4
  170.   config.pin_d3 = 21; // Y5
  171.   config.pin_d4 = 36; // Y6
  172.   config.pin_d5 = 39; // Y7
  173.   config.pin_d6 = 34; // Y8
  174.   config.pin_d7 = 35; // Y9
  175.   config.pin_xclk = 0; // XCLK_GPIO_NUM
  176.   config.pin_pclk = 22; // PCLK_GPIO_NUM
  177.   config.pin_vsync = 25; // VSYNC_GPIO_NUM
  178.   config.pin_href = 23; // HREF_GPIO_NUM
  179.   config.pin_sscb_sda = 26; // SIOD_GPIO_NUM
  180.   config.pin_sscb_scl = 27; // SIOC_GPIO_NUM
  181.   config.pin_pwdn = 32; // PWDN_GPIO_NUM
  182.   config.pin_reset = -1; // RESET_GPIO_NUM, -1 if not used
  183.   config.xclk_freq_hz = 20000000;
  184.   config.pixel_format = PIXFORMAT_JPEG;
  185.  
  186.   // Init with high specs to pre-allocate larger buffers
  187.   if (psramFound()) {
  188.     config.frame_size = FRAMESIZE_UXGA;
  189.     config.jpeg_quality = 10;
  190.     config.fb_count = 2;
  191.   } else {
  192.     config.frame_size = FRAMESIZE_SVGA;
  193.     config.jpeg_quality = 12;
  194.     config.fb_count = 1;
  195.   }
  196.  
  197.   // Initialize camera
  198.   esp_err_t err = esp_camera_init(&config;);
  199.   if (err != ESP_OK) {
  200.     Serial.printf("Camera init failed with error 0x%x", err);
  201.     return;
  202.   }
  203.  
  204.    while (!SD_MMC.begin()) {}
  205.  
  206.   connectToWiFi();
  207.   captureAndWriteVideoToSD(10);
  208.   uploadVideoToDrive();
  209. }
  210.  
  211. void loop() {
  212. //  captureAndWriteVideoToSD(10);
  213. //  // Check if video capture was successful
  214. //   if (bufferSize > 0) {
  215.  
  216. //     uploadVideoToDrive(videoBuffer, bufferSize, gdrive_upload_url, gdrive_token);
  217.  
  218. //     // Free the memory allocated for videoBuffer
  219. //     videoBuffer = NULL;
  220. //     bufferSize = 0;
  221. //     maxBufferSize = 0;
  222. //   }
  223.  
  224.   delay(1000);
  225. }