image upload on AWS s3

Giovanni
Posts: 2
Joined: Thu Aug 22, 2024 12:24 pm

image upload on AWS s3

Postby Giovanni » Tue Jan 14, 2025 4:33 pm

Hi,
I am using an esp32s3 and esp idf 5.3.2 as a framework. I developed the following code for an application of mine. The goal is to capture frames and send them to AWS to simulate a live streaming.
I managed to upload them to the drive but when i go to check the image it turns out to be corrupted. even if the base64 print out is true using an online decoder.


Code: Select all

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "freertos/idf_additions.h"
#include "string.h"
#include "esp_log.h"
#include "board.h"
#include "audio_mem.h"
#include "esp_jpeg_common.h"
#include "img_convert.h"
#include "driver/gpio.h"

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_mac.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "nvs_flash.h"
#if CONFIG_BT_CONTROLLER_ENABLED || !CONFIG_BT_NIMBLE_ENABLED
#include "esp_bt.h"
#endif

#include "esp_bt_device.h"
#include "esp_blufi_api.h"
#include "blufi_example.h"
#include "esp_blufi.h"
#include "base64.h"
#include "esp_http_server.h"


static const char *TAG = "Camera";

#include "esp_camera.h"
#include "esp_http_client.h"

#define SD_MISO_PIN      40
#define SD_MOSI_PIN      38
#define SD_SCLK_PIN      39
#define SD_CS_PIN        47

#define PCIE_PWR_PIN     48
#define PCIE_TX_PIN      45
#define PCIE_RX_PIN      46
#define PCIE_LED_PIN     21
#define MIC_IIS_WS_PIN   42
#define MIC_IIS_SCK_PIN  41
#define MIC_IIS_DATA_PIN 2
#define CAM_PWDN_PIN     -1
#define CAM_RESET_PIN    -1
#define CAM_XCLK_PIN     14
#define CAM_SIOD_PIN     4
#define CAM_SIOC_PIN     5
#define CAM_Y9_PIN       15
#define CAM_Y8_PIN       16
#define CAM_Y7_PIN       17
#define CAM_Y6_PIN       12
#define CAM_Y5_PIN       10
#define CAM_Y4_PIN       8
#define CAM_Y3_PIN       9
#define CAM_Y2_PIN       11
#define CAM_VSYNC_PIN    6
#define CAM_HREF_PIN     7
#define CAM_PCLK_PIN     13
#define BUTTON_PIN       0
#define PWR_ON_PIN       1
#define SERIAL_RX_PIN    44
#define SERIAL_TX_PIN    43
#define BAT_VOLT_PIN     -1

#define CAM_IR_PIN       18
#define CAM_RESET_PIN    -1


#define EXAMPLE_WIFI_CONNECTION_MAXIMUM_RETRY CONFIG_EXAMPLE_WIFI_CONNECTION_MAXIMUM_RETRY
#define EXAMPLE_INVALID_REASON                255
#define EXAMPLE_INVALID_RSSI                  -128

#define PREFIX                                  "TXT"
#define PREFIXAPN                               "APN_"

#define GPSWIFI                                 1           // DA COMMENTARE SE NON VUOI USARE L'APP CHE TRASMETTE L'INDIRIZZO

#define GOOGLE_DRIVE_UPLOAD_URL "https://script.google.com/macros/sxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

static void example_event_callback(esp_blufi_cb_event_t event, esp_blufi_cb_param_t *param);

static void start_websocket_server();

#define WIFI_LIST_NUM   10

static wifi_config_t sta_config;
static wifi_config_t ap_config;

static EventGroupHandle_t wifi_event_group;

const int CONNECTED_BIT = BIT0;

static uint8_t example_wifi_retry = 0;

static camera_config_t camera_config = {
    .pin_pwdn = CAM_PWDN_PIN,
    .pin_reset = CAM_RESET_PIN,
    .pin_xclk = CAM_XCLK_PIN,
    .pin_pclk = CAM_PCLK_PIN,
    .pin_vsync = CAM_VSYNC_PIN,
    .pin_href = CAM_HREF_PIN,
    .pin_sccb_sda = CAM_SIOD_PIN,
    .pin_sccb_scl = CAM_SIOC_PIN,
    .pin_d7 = CAM_Y9_PIN,
    .pin_d6 = CAM_Y8_PIN,
    .pin_d5 = CAM_Y7_PIN,
    .pin_d4 = CAM_Y6_PIN,
    .pin_d3 = CAM_Y5_PIN,
    .pin_d2 = CAM_Y4_PIN,
    .pin_d1 = CAM_Y3_PIN,
    .pin_d0 = CAM_Y2_PIN,       
    .xclk_freq_hz = 20000000,
    .ledc_timer = LEDC_TIMER_0,
    .ledc_channel = LEDC_CHANNEL_0,
    .pixel_format = PIXFORMAT_JPEG, //YUV422,GRAYSCALE,RGB565,JPEG
    .frame_size = FRAMESIZE_QVGA,    
    //QQVGA-UXGA, For ESP32, do not use sizes above QVGA when not JPEG. The performance of the ESP32-S series has improved a lot,
    // but JPEG mode always gives better frame rates.

    .jpeg_quality = 5, //0-63, for OV series camera sensors, lower number means higher quality
    .fb_count = 2,       //When jpeg mode is used, if fb_count more than one, the driver will work in continuous mode.
    .fb_location = CAMERA_FB_IN_DRAM,
    .grab_mode = CAMERA_GRAB_WHEN_EMPTY,
};

static bool gl_sta_connected = false;
static bool gl_sta_got_ip = false;
static bool ble_is_connected = false;
static uint8_t gl_sta_bssid[6];
static uint8_t gl_sta_ssid[32];
static int gl_sta_ssid_len;
static wifi_sta_list_t gl_sta_list;
static bool gl_sta_is_connecting = false;
static esp_blufi_extra_info_t gl_sta_conn_info;
int wifi_retry= 10;
bool trywifi = false;
bool tryGSM_LTE = false;
double latitude = 0.0, longitude = 0.0;

static void example_record_wifi_conn_info(int rssi, uint8_t reason)
{
    memset(&gl_sta_conn_info, 0, sizeof(esp_blufi_extra_info_t));
    if (gl_sta_is_connecting) 
    {
        gl_sta_conn_info.sta_max_conn_retry_set = true;
        gl_sta_conn_info.sta_max_conn_retry = EXAMPLE_WIFI_CONNECTION_MAXIMUM_RETRY;
    } 
    else
    {
        gl_sta_conn_info.sta_conn_rssi_set = true;
        gl_sta_conn_info.sta_conn_rssi = rssi;
        gl_sta_conn_info.sta_conn_end_reason_set = true;
        gl_sta_conn_info.sta_conn_end_reason = reason;
    }
}


static void example_wifi_connect(void)
{
    example_wifi_retry = 0;
    gl_sta_is_connecting = (esp_wifi_connect() == ESP_OK);
    example_record_wifi_conn_info(EXAMPLE_INVALID_RSSI, EXAMPLE_INVALID_REASON);
}

static bool example_wifi_reconnect(void)
{
    bool ret;
    if (gl_sta_is_connecting && example_wifi_retry++ < wifi_retry) 
    {
        trywifi = true;
        BLUFI_INFO("BLUFI WiFi starts reconnection  %d\n", example_wifi_retry);
        gl_sta_is_connecting = (esp_wifi_connect() == ESP_OK);
        example_record_wifi_conn_info(EXAMPLE_INVALID_RSSI, EXAMPLE_INVALID_REASON);
        ret = true;
    } 
    else  
    {
        trywifi=false;
        printf("Provo con la connessione GSM/LTE\n");
        tryGSM_LTE=true;
        ret = false;    
    }
    return ret;
}

static int softap_get_current_connection_number(void)
{
    esp_err_t ret;
    ret = esp_wifi_ap_get_sta_list(&gl_sta_list);
    if (ret == ESP_OK) return gl_sta_list.num;
    return 0;
}

static void ip_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data)
{
    wifi_mode_t mode;
    switch (event_id) 
    {
        case IP_EVENT_STA_GOT_IP: 
        {
            esp_blufi_extra_info_t info;
            xEventGroupSetBits(wifi_event_group, CONNECTED_BIT);
            esp_wifi_get_mode(&mode);
            memset(&info, 0, sizeof(esp_blufi_extra_info_t));
            memcpy(info.sta_bssid, gl_sta_bssid, 6);
            info.sta_bssid_set = true;
            info.sta_ssid = gl_sta_ssid;
            info.sta_ssid_len = gl_sta_ssid_len;
            gl_sta_got_ip = true;
            if (ble_is_connected == true)  esp_blufi_send_wifi_conn_report(mode, ESP_BLUFI_STA_CONN_SUCCESS, softap_get_current_connection_number(), &info);
            else  BLUFI_INFO("BLUFI BLE is not connected yet\n");  
            printf("Connesso al wifi \n");             
            esp_bt_controller_disable();  // Disabilita il Bluetooth         
            // ucansend=true;

#ifdef GPSWIFI          
            // latitude_str = Read_Partition(Lat,true);
            // latitude = strtod(latitude_str, NULL);  // Converte la latitudine in un double   
            // longitude_str = Read_Partition(Lon,true);
            // longitude = strtod(longitude_str, NULL);  // Converte la latitudine in un double
            // printf("Float Extracted Longitude: %f, Extracted Latitude: %f\n ", longitude, latitude);              
            // printf("Stringhe Extracted Longitude: %s, Extracted Latitude: %s\n", longitude_str, latitude_str); // Stampa le coordinate grezze come stringhe
            // char temp[50]; // Buffer temporaneo per formattare la stringa            
            // snprintf(temp, sizeof(temp), "%f,%f", latitude, longitude);  // Formatta la stringa come "latitudine,longitudine"    
            // Location = strdup(temp); // Usa strdup per creare una copia della stringa       
            // printf("Location: %s\n", Location);  
#endif           
            break;
        }
        default:
            break;
    }
    return;
}

static void wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data)
{
    wifi_event_sta_connected_t *event;
    wifi_event_sta_disconnected_t *disconnected_event;
    wifi_mode_t mode;
    switch (event_id) 
    {
        case WIFI_EVENT_STA_START:
        {
            example_wifi_connect();
            break;
        }
        case WIFI_EVENT_STA_CONNECTED:
        {
            gl_sta_connected = true;
            gl_sta_is_connecting = false;
            event = (wifi_event_sta_connected_t*) event_data;
            memcpy(gl_sta_bssid, event->bssid, 6);
            memcpy(gl_sta_ssid, event->ssid, event->ssid_len);
            gl_sta_ssid_len = event->ssid_len;
            break;
        }
        case WIFI_EVENT_STA_DISCONNECTED:
        {
            if (gl_sta_connected == false && example_wifi_reconnect() == false) 
            {
                gl_sta_is_connecting = false;
                disconnected_event = (wifi_event_sta_disconnected_t*) event_data;
                example_record_wifi_conn_info(disconnected_event->rssi, disconnected_event->reason);
            }
            gl_sta_connected = false;
            gl_sta_got_ip = false;
            memset(gl_sta_ssid, 0, 32);
            memset(gl_sta_bssid, 0, 6);
            gl_sta_ssid_len = 0;            
            xEventGroupClearBits(wifi_event_group, CONNECTED_BIT);   
            // if(tryGSM_LTE) 
            // {
            //    if (mqtt_client != NULL)  
            //     {
            //         vTaskDelete(NULL);  // Stop the MQTT task            
            //         mqtt_client = NULL;
            //     }
            //     StartGSMLTE();
            // }
            break;
        }
        case WIFI_EVENT_AP_START:
        {
            esp_wifi_get_mode(&mode);
            if (ble_is_connected == true) 
            {
                if (gl_sta_connected) 
                {
                    esp_blufi_extra_info_t info;
                    memset(&info, 0, sizeof(esp_blufi_extra_info_t));
                    memcpy(info.sta_bssid, gl_sta_bssid, 6);
                    info.sta_bssid_set = true;
                    info.sta_ssid = gl_sta_ssid;
                    info.sta_ssid_len = gl_sta_ssid_len;
                    esp_blufi_send_wifi_conn_report(mode, gl_sta_got_ip ? ESP_BLUFI_STA_CONN_SUCCESS : ESP_BLUFI_STA_NO_IP, softap_get_current_connection_number(), &info);
                } 
                else if (gl_sta_is_connecting) esp_blufi_send_wifi_conn_report(mode, ESP_BLUFI_STA_CONNECTING, softap_get_current_connection_number(), &gl_sta_conn_info);
                else  esp_blufi_send_wifi_conn_report(mode, ESP_BLUFI_STA_CONN_FAIL, softap_get_current_connection_number(), &gl_sta_conn_info);
            } 
            else  BLUFI_INFO("BLUFI BLE is not connected yet\n");        
            break;
        }
        case WIFI_EVENT_SCAN_DONE: 
        {
            uint16_t apCount = 0;
            esp_wifi_scan_get_ap_num(&apCount);
            if (apCount == 0) 
            {
                BLUFI_INFO("Nothing AP found");
                break;
            }
            wifi_ap_record_t *ap_list = (wifi_ap_record_t *)malloc(sizeof(wifi_ap_record_t) * apCount);
            if (!ap_list) 
            {
                BLUFI_ERROR("malloc error, ap_list is NULL");
                break;
            }
            ESP_ERROR_CHECK(esp_wifi_scan_get_ap_records(&apCount, ap_list));
            esp_blufi_ap_record_t * blufi_ap_list = (esp_blufi_ap_record_t *)malloc(apCount * sizeof(esp_blufi_ap_record_t));
            if (!blufi_ap_list) 
            {
                if (ap_list)  free(ap_list);
                BLUFI_ERROR("malloc error, blufi_ap_list is NULL");
                break;
            }
            for (int i = 0; i < apCount; ++i)
            {
                blufi_ap_list[i].rssi = ap_list[i].rssi;
                memcpy(blufi_ap_list[i].ssid, ap_list[i].ssid, sizeof(ap_list[i].ssid));
            }
            if (ble_is_connected == true)  esp_blufi_send_wifi_list(apCount, blufi_ap_list);
            else  BLUFI_INFO("BLUFI BLE is not connected yet\n");
            esp_wifi_scan_stop();
            free(ap_list);
            free(blufi_ap_list);
            break;
        }
        case WIFI_EVENT_AP_STACONNECTED: 
        {
            wifi_event_ap_staconnected_t* event = (wifi_event_ap_staconnected_t*) event_data;
            BLUFI_INFO("station "MACSTR" join, AID=%d", MAC2STR(event->mac), event->aid);
            break;
        }
        case WIFI_EVENT_AP_STADISCONNECTED: 
        {
            wifi_event_ap_stadisconnected_t* event = (wifi_event_ap_stadisconnected_t*) event_data;
            BLUFI_INFO("station "MACSTR" leave, AID=%d", MAC2STR(event->mac), event->aid);
            break;
        }
        default:
            break;
    }
    return;
}

static void initialise_wifi(void)
{
    ESP_ERROR_CHECK(esp_netif_init());
    wifi_event_group = xEventGroupCreate();
    ESP_ERROR_CHECK(esp_event_loop_create_default());
    esp_netif_t *sta_netif = esp_netif_create_default_wifi_sta();
    assert(sta_netif);
    esp_netif_t *ap_netif = esp_netif_create_default_wifi_ap();
    assert(ap_netif);
    ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL));
    ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &ip_event_handler, NULL));
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK( esp_wifi_init(&cfg) );
    ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_STA) );
    example_record_wifi_conn_info(EXAMPLE_INVALID_RSSI, EXAMPLE_INVALID_REASON);
    ESP_ERROR_CHECK( esp_wifi_start() );
    printf("Wifi Init\n");
}

static esp_blufi_callbacks_t example_callbacks = {
    .event_cb = example_event_callback,
    .negotiate_data_handler = blufi_dh_negotiate_data_handler,
    .encrypt_func = blufi_aes_encrypt,
    .decrypt_func = blufi_aes_decrypt,
    .checksum_func = blufi_crc_checksum,
};

static void example_event_callback(esp_blufi_cb_event_t event, esp_blufi_cb_param_t *param)
{   
    switch (event) 
    {
        case ESP_BLUFI_EVENT_INIT_FINISH:
        {
            BLUFI_INFO("BLUFI init finish\n");
            esp_blufi_adv_start();
            break;
        }
        case ESP_BLUFI_EVENT_DEINIT_FINISH:
        {
            BLUFI_INFO("BLUFI deinit finish\n");
            break;
        }
        case ESP_BLUFI_EVENT_BLE_CONNECT:
        {
            BLUFI_INFO("BLUFI ble connect\n");
            ble_is_connected = true;
            esp_blufi_adv_stop();
            blufi_security_init();     
            break;
        }
        case ESP_BLUFI_EVENT_BLE_DISCONNECT:
        {
            BLUFI_INFO("BLUFI ble disconnect\n");
            ble_is_connected = false;
            blufi_security_deinit();
            esp_blufi_adv_start();
            break;
        }
        case ESP_BLUFI_EVENT_SET_WIFI_OPMODE:
        {
        #ifndef APN
            BLUFI_INFO("BLUFI Set WIFI opmode %d\n", param->wifi_mode.op_mode);
            ESP_ERROR_CHECK( esp_wifi_set_mode(param->wifi_mode.op_mode));
        #endif
            break;
        }
        case ESP_BLUFI_EVENT_REQ_CONNECT_TO_AP:
        {
            BLUFI_INFO("BLUFI requset wifi connect to AP\n");          
            esp_wifi_disconnect();
            example_wifi_connect();
            break;
        }
        case ESP_BLUFI_EVENT_REQ_DISCONNECT_FROM_AP:
        {
            BLUFI_INFO("BLUFI requset wifi disconnect from AP\n");
            esp_wifi_disconnect();
            break;
        }
        case ESP_BLUFI_EVENT_REPORT_ERROR:
        {
            BLUFI_ERROR("BLUFI report error, error code %d\n", param->report_error.state);
            esp_blufi_send_error_info(param->report_error.state);
            break;
        }
        case ESP_BLUFI_EVENT_GET_WIFI_STATUS: 
        {
            wifi_mode_t mode;
            esp_blufi_extra_info_t info;
            esp_wifi_get_mode(&mode);
            if (gl_sta_connected) 
            {
                memset(&info, 0, sizeof(esp_blufi_extra_info_t));
                memcpy(info.sta_bssid, gl_sta_bssid, 6);
                info.sta_bssid_set = true;
                info.sta_ssid = gl_sta_ssid;
                info.sta_ssid_len = gl_sta_ssid_len;
                esp_blufi_send_wifi_conn_report(mode, gl_sta_got_ip ? ESP_BLUFI_STA_CONN_SUCCESS : ESP_BLUFI_STA_NO_IP, softap_get_current_connection_number(), &info);
            } 
            else if (gl_sta_is_connecting)  esp_blufi_send_wifi_conn_report(mode, ESP_BLUFI_STA_CONNECTING, softap_get_current_connection_number(), &gl_sta_conn_info);
            else  esp_blufi_send_wifi_conn_report(mode, ESP_BLUFI_STA_CONN_FAIL, softap_get_current_connection_number(), &gl_sta_conn_info);            
            BLUFI_INFO("BLUFI get wifi status from AP\n");
            break;
        }
        case ESP_BLUFI_EVENT_RECV_SLAVE_DISCONNECT_BLE:
        {
            BLUFI_INFO("blufi close a gatt connection");
            esp_blufi_disconnect();
            break;
        }
        case ESP_BLUFI_EVENT_DEAUTHENTICATE_STA:
            break;
        case ESP_BLUFI_EVENT_RECV_STA_BSSID:
        {
            memcpy(sta_config.sta.bssid, param->sta_bssid.bssid, 6);
            sta_config.sta.bssid_set = 1;
            esp_wifi_set_config(WIFI_IF_STA, &sta_config);
            BLUFI_INFO("Recv STA BSSID %s\n", sta_config.sta.ssid);
            break;
        }
        case ESP_BLUFI_EVENT_RECV_STA_SSID:   // modifica alla rete
        {            
            BLUFI_INFO("Original SSID: %s\n", param->sta_ssid.ssid); // Stampa la SSID originale prima di modificarla
            #ifndef GPSWIFI           
                if (param->sta_ssid.ssid_len >= 3 && strncmp((char *)param->sta_ssid.ssid, PREFIX, strlen(PREFIX)) == 0) // Controlla che i primi tre caratteri siano "GDR"
                {
                    BLUFI_INFO("SSID starts with '%s', proceeding with modification\n",PREFIX);
                    if (param->sta_ssid.ssid_len > 3) // Verifica che la lunghezza sia maggiore di 3
                    {                
                        strncpy((char *)sta_config.sta.ssid, (char *)(param->sta_ssid.ssid + 3), param->sta_ssid.ssid_len - 3); // Copia la stringa a partire dal quarto carattere            
                        sta_config.sta.ssid[param->sta_ssid.ssid_len - 3] = '\0'; // Aggiungi il terminatore null alla fine della stringa copiata
                    }
                    else sta_config.sta.ssid[0] = '\0'; // Se la stringa è più corta di 3 caratteri, imposta la SSID come stringa vuota 
                    BLUFI_INFO("Modified SSID: %s\n", sta_config.sta.ssid); // Stampa la SSID dopo la modifica
                    esp_wifi_set_config(WIFI_IF_STA, &sta_config); // Imposta la configurazione WiFi
                    
                }
                else BLUFI_INFO("SSID does not start with 'GDR', no modification applied\n");
            #else                      
                if (param->sta_ssid.ssid_len >= 3 && strncmp((char *)param->sta_ssid.ssid, PREFIX,strlen(PREFIX)) == 0)  // Verifica che l'SSID inizi con "AMI"
                {
                    BLUFI_INFO("SSID starts with '%s', proceeding with parsing\n",PREFIX);                
                    char *latitude_start = (char *)param->sta_ssid.ssid + strlen(PREFIX) + 1;  // Salta il prefisso "AMI,"
                    char *latitude_end = strchr(latitude_start, ','); // Cerca la virgola dopo la latitudine
                    if (latitude_end != NULL)
                    {                    
                        size_t latitude_len = latitude_end - latitude_start; // Calcola la lunghezza della latitudine come stringa  
                        char latitude_str[latitude_len + 1]; // Estrai la latitudine come stringa
                        strncpy(latitude_str, latitude_start, latitude_len);
                        latitude_str[latitude_len] = '\0'; // Terminatore null                   
                        latitude = strtod(latitude_str, NULL);  // Converte la latitudine in un double
                        BLUFI_INFO("Extracted Latitude: %f\n", latitude);    
                        //Write_Partition(Lat, latitude_str); //SALVA LA LATITUDINE IN MEMORIA   
                        char *real_ssid_start = latitude_end + 1; // Estrai l'SSID reale dopo la seconda virgola
                        size_t real_ssid_len = param->sta_ssid.ssid_len - (real_ssid_start - (char *)param->sta_ssid.ssid);                    
                        strncpy((char *)sta_config.sta.ssid, real_ssid_start, real_ssid_len); // Copia l'SSID reale nella configurazione WiFi
                        sta_config.sta.ssid[real_ssid_len] = '\0'; // Aggiungi terminatore null
                        BLUFI_INFO("Modified SSID: %s\n", sta_config.sta.ssid);                    
                        esp_wifi_set_config(WIFI_IF_STA, &sta_config); // Applica la configurazione WiFi
                    }
                    else BLUFI_INFO("Malformed SSID: Second comma not found, no modification applied\n");                
                }
                else BLUFI_INFO("SSID does not start with '%s', no modification applied\n", PREFIX);           
            #endif
            break;

        }
        case ESP_BLUFI_EVENT_RECV_STA_PASSWD: //modifica alla pass
        {     
            BLUFI_INFO("Original Password: %s\n", param->sta_passwd.passwd); // Stampa la password originale prima di modificarla
            #ifndef GPSWIFI            
                if (param->sta_passwd.passwd_len >= 3 && 
                    strncmp((char *)param->sta_passwd.passwd, PREFIX, strlen(PREFIX)) == 0) // Controlla che i primi tre caratteri siano "AMI"
                {
                    BLUFI_INFO("Password starts with '%s', proceeding with modification\n", PREFIX);
                    if (param->sta_passwd.passwd_len > 3) // Verifica che la lunghezza sia maggiore di 3
                    {                
                        strncpy((char *)sta_config.sta.password, (char *)(param->sta_passwd.passwd + 3), param->sta_passwd.passwd_len - 3); // Copia la password a partire dal quarto carattere
                        sta_config.sta.password[param->sta_passwd.passwd_len - 3] = '\0'; // Aggiungi il terminatore null alla fine della password copiata
                    }
                    else sta_config.sta.password[0] = '\0'; // Se la password è più corta di 3 caratteri, imposta la password come stringa vuota       
                    BLUFI_INFO("Modified Password: %s\n", sta_config.sta.password); // Stampa la password dopo la modifica
                    esp_wifi_set_config(WIFI_IF_STA, &sta_config); // Imposta la configurazione WiFi                
                }
                else BLUFI_INFO("Password does not start with '%s', no modification applied\n",PREFIX);  
            #else            
                if (param->sta_passwd.passwd_len >= 3 &&  strncmp((char *)param->sta_passwd.passwd, PREFIX, strlen(PREFIX)) == 0) // Controlla che i primi tre caratteri siano "AMI"
                {
                    BLUFI_INFO("Password starts with '%s', proceeding with modification\n", PREFIX);                
                    char *longitude_start = strchr((char *)param->sta_passwd.passwd, ','); // Trova la prima virgola dopo il prefisso "AMI"
                    if (longitude_start != NULL) 
                    {                    
                        char *longitude_end = strchr(longitude_start + 1, ','); // Trova la seconda virgola (fine della latitudine)
                        if (longitude_end != NULL) 
                        {                        
                            size_t longitude_len = longitude_end - (longitude_start + 1); // Calcola la lunghezza della latitudine come stringa
                            char longitude_str[longitude_len + 1];
                            strncpy(longitude_str, longitude_start + 1, longitude_len);
                            longitude_str[longitude_len] = '\0'; // Aggiungi terminatore null                        
                            longitude = strtod(longitude_str, NULL); // Converte la longitude in double
                            BLUFI_INFO("Extracted Longitude: %f\n", longitude);                                      
                            //Write_Partition(Lon, longitude_str); // SALVA LA LONGITUDINE IN MEMORIA 
                            char *real_password_start = longitude_end + 1; // Estrai la password effettiva dopo la seconda virgola
                            size_t real_password_len = param->sta_passwd.passwd_len - (real_password_start - (char *)param->sta_passwd.passwd);                        
                            strncpy((char *)sta_config.sta.password, real_password_start, real_password_len); // Copia la password effettiva nella configurazione WiFi
                            sta_config.sta.password[real_password_len] = '\0'; // Aggiungi terminatore null
                            BLUFI_INFO("Modified Password: %s\n", sta_config.sta.password); // Stampa la password dopo la modifica                        
                            esp_wifi_set_config(WIFI_IF_STA, &sta_config); // Applica la configurazione WiFi
                        } 
                        else BLUFI_INFO("No second comma found, password modification aborted\n");                    
                    }
                    else BLUFI_INFO("No comma found after '%s', password modification aborted\n", PREFIX);               
                } 
                else BLUFI_INFO("Password does not start with '%s', no modification applied\n", PREFIX);     
            #endif       
            break;
        }
        case ESP_BLUFI_EVENT_RECV_SOFTAP_SSID:
        {
            #ifdef APN                      
                strncpy((char *)ap_config.ap.ssid, (char *)param->softap_ssid.ssid, param->softap_ssid.ssid_len);
                ap_config.ap.ssid[param->softap_ssid.ssid_len] = '\0';
                ap_config.ap.ssid_len = param->softap_ssid.ssid_len;          
                BLUFI_INFO("Recv SOFTAP SSID %s, ssid len %d\n", ap_config.ap.ssid, ap_config.ap.ssid_len);
                // Controlla se i primi caratteri corrispondono a PREFIXAPN
                if (ap_config.ap.ssid_len >= 3 && strncmp((char *)ap_config.ap.ssid, PREFIXAPN, strlen(PREFIXAPN)) == 0) 
                {                 
                    // Copia l'APN nella variabile locale, rimuovendo il prefisso PREFIXAPN
                    strncpy(global_apn, (char *)ap_config.ap.ssid + strlen(PREFIXAPN), ap_config.ap.ssid_len - strlen(PREFIXAPN));
                    global_apn[ap_config.ap.ssid_len - strlen(PREFIXAPN)] = '\0'; // Aggiungi il terminatore di stringa
                    // Ora local_apn contiene il valore dell'APN senza il prefisso
                    BLUFI_INFO("APN salvato: %s\n", global_apn);
                    Write_Partition(Apn,global_apn);
                    local_apn = global_apn;
                }
            #endif
            break;
        }
        #ifndef APN
        case ESP_BLUFI_EVENT_RECV_SOFTAP_PASSWD:
        {    strncpy((char *)ap_config.ap.password, (char *)param->softap_passwd.passwd, param->softap_passwd.passwd_len);
            ap_config.ap.password[param->softap_passwd.passwd_len] = '\0';
            esp_wifi_set_config(WIFI_IF_AP, &ap_config);
            BLUFI_INFO("Recv SOFTAP PASSWORD %s len = %d\n", ap_config.ap.password, param->softap_passwd.passwd_len);
            break;
        }
        case ESP_BLUFI_EVENT_RECV_SOFTAP_MAX_CONN_NUM:
        {
            if (param->softap_max_conn_num.max_conn_num > 4) return;
            ap_config.ap.max_connection = param->softap_max_conn_num.max_conn_num;
            esp_wifi_set_config(WIFI_IF_AP, &ap_config);
            BLUFI_INFO("Recv SOFTAP MAX CONN NUM %d\n", ap_config.ap.max_connection);
            break;
        }
        case ESP_BLUFI_EVENT_RECV_SOFTAP_AUTH_MODE:
        {
            if (param->softap_auth_mode.auth_mode >= WIFI_AUTH_MAX) return;
            ap_config.ap.authmode = param->softap_auth_mode.auth_mode;
            esp_wifi_set_config(WIFI_IF_AP, &ap_config);
            BLUFI_INFO("Recv SOFTAP AUTH MODE %d\n", ap_config.ap.authmode);
            break;
        }
        case ESP_BLUFI_EVENT_RECV_SOFTAP_CHANNEL:
        {
            if (param->softap_channel.channel > 13)  return;
            ap_config.ap.channel = param->softap_channel.channel;
            esp_wifi_set_config(WIFI_IF_AP, &ap_config);
            BLUFI_INFO("Recv SOFTAP CHANNEL %d\n", ap_config.ap.channel);
            break;
        }
        #endif
        case ESP_BLUFI_EVENT_GET_WIFI_LIST:
        {
            wifi_scan_config_t scanConf = {
                .ssid = NULL,
                .bssid = NULL,
                .channel = 0,
                .show_hidden = false
            };
            esp_err_t ret = esp_wifi_scan_start(&scanConf, true);
            if (ret != ESP_OK)  esp_blufi_send_error_info(ESP_BLUFI_WIFI_SCAN_FAIL);
            break;
        }
        case ESP_BLUFI_EVENT_RECV_CUSTOM_DATA:
        {
            BLUFI_INFO("Recv Custom Data %" PRIu32 "\n", param->custom_data.data_len);
            esp_log_buffer_hex("Custom Data", param->custom_data.data, param->custom_data.data_len);
            break;
        }
        case ESP_BLUFI_EVENT_RECV_USERNAME:
            break;
        case ESP_BLUFI_EVENT_RECV_CA_CERT:
            break;
        case ESP_BLUFI_EVENT_RECV_CLIENT_CERT:
            break;
        case ESP_BLUFI_EVENT_RECV_SERVER_CERT:
            break;
        case ESP_BLUFI_EVENT_RECV_CLIENT_PRIV_KEY:
            break;;
        case ESP_BLUFI_EVENT_RECV_SERVER_PRIV_KEY:           
            break;
        default:
            break;
    }
}

static esp_err_t init_camera()  //initialize the camera
{   
    printf("Inizializzazione Camera\n");
    esp_err_t err = esp_camera_init(&camera_config);
    if (err != ESP_OK) 
    {
        ESP_LOGE(TAG, "Camera Init Failed with err 0x%x", err);
        return err;
    }
    return ESP_OK;
}

void Init_Gpio()
{
    gpio_set_direction(PWR_ON_PIN, GPIO_MODE_OUTPUT);
    gpio_set_level(PWR_ON_PIN, 1); 
     gpio_config_t io_conf = {
        .pin_bit_mask = (1ULL << CAM_IR_PIN),  // Seleziona il pin
        .mode = GPIO_MODE_OUTPUT,             // Imposta come uscita
        .pull_up_en = GPIO_PULLUP_DISABLE,    // Disabilita pull-up
        .pull_down_en = GPIO_PULLDOWN_DISABLE,// Disabilita pull-down
        .intr_type = GPIO_INTR_DISABLE        // Nessuna interruzione
    };
    gpio_config(&io_conf);
    printf("Test IR Filter\n");  
    for (int i = 0; i < 3; i++)    // Alterna lo stato del pin tre volte
    {       
        int current_state = gpio_get_level(CAM_IR_PIN); // Leggi lo stato corrente del pin e alternalo
        gpio_set_level(CAM_IR_PIN, !current_state);  // Cambia lo stato       
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }  
}
#include "mbedtls/base64.h"  // Includi la libreria mbedTLS per la codifica Base64

void send_image_to_drive(camera_fb_t *fb)
{
    esp_http_client_config_t config = {
        .url = GOOGLE_DRIVE_UPLOAD_URL,
        .method = HTTP_METHOD_POST,
        .timeout_ms = 30000,
    };
    esp_http_client_handle_t client = esp_http_client_init(&config);

    // Calcola la lunghezza dell'output codificato
    size_t encoded_len = (fb->len * 4) / 3 + 4;  // La lunghezza di un buffer Base64 è 4/3 della dimensione dell'input
    char *encoded_image = malloc(encoded_len + 1); // +1 per terminazione null

    // Codifica i dati dell'immagine in Base64 utilizzando mbedTLS
    int ret = mbedtls_base64_encode((unsigned char *)encoded_image, encoded_len, &encoded_len, fb->buf, fb->len);
    if (ret != 0) 
    {
        ESP_LOGE(TAG, "Base64 encoding failed: -0x%04x", -ret);
        free(encoded_image);
        esp_http_client_cleanup(client);
        return;
    }

    // Log della stringa Base64 (aggiungi un controllo per evitare overflow nel log)
    ESP_LOGI(TAG, "Encoded Base64 Image: %s", encoded_image);

    // Prepara i dati per l'invio HTTP
    char *post_data = malloc(strlen(encoded_image) + 128);
    sprintf(post_data, "filename=ESP32-CAM.jpg&mimetype=image/jpeg&data=%s", encoded_image);

    // Imposta gli header e il corpo della richiesta POST
    esp_http_client_set_header(client, "Content-Type", "application/x-www-form-urlencoded");
    esp_http_client_set_post_field(client, post_data, strlen(post_data));

    // Invia la richiesta HTTP
    esp_err_t err = esp_http_client_perform(client);
    if (err == ESP_OK)  
    {
        ESP_LOGI(TAG, "Image sent successfully: %d", esp_http_client_get_status_code(client));   
    }
    else 
    {
        ESP_LOGE(TAG, "Failed to send image: %s", esp_err_to_name(err));   
    }
    // Libera la memoria allocata
    free(encoded_image);
    free(post_data);
    esp_http_client_cleanup(client);
}


// void send_image_to_drive(camera_fb_t *fb)
// {
//     esp_http_client_config_t config = {
//         .url = "https://14uvn3umka.execute-api.us-east-1.amazonaws.com/dev",
//         .method = HTTP_METHOD_POST,
//         .timeout_ms = 500,
//     };
//     esp_http_client_handle_t client = esp_http_client_init(&config);

//     // Imposta i dettagli dell'header
//     esp_http_client_set_header(client, "Content-Type", "image/jpg");
//     esp_http_client_set_header(client, "Content-Disposition", "attachment; filename=ESP32-CAM.jpg");

//     // Imposta il contenuto della richiesta come dati binari
//     esp_http_client_set_post_field(client, (char *)fb->buf, fb->len);

//     // Invia la richiesta
//     esp_err_t err = esp_http_client_perform(client);
//     if (err == ESP_OK) ESP_LOGI(TAG, "Image sent successfully: %d", esp_http_client_get_status_code(client));
//     else ESP_LOGE(TAG, "Failed to send image: %s", esp_err_to_name(err));
//     esp_http_client_cleanup(client);
   
// }


void app_main(void)
{   
    nvs_flash_init(); // Initialize NVS   
    initialise_wifi(); // Inizializza la connessione WiFi  
    ESP_ERROR_CHECK(esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT));
    esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
    esp_bt_controller_init(&bt_cfg);
    esp_bt_controller_enable(ESP_BT_MODE_BLE);        
    esp_blufi_host_and_cb_init(&example_callbacks);    // Inizializza la libreria per la gestione del Bluetooth   
    BLUFI_INFO("BLUFI VERSION %04x\n", esp_blufi_get_version());  
    Init_Gpio();        
    ESP_LOGI(TAG, "Initialising camera...");
    if (esp_camera_init(&camera_config) != ESP_OK) 
    {
        ESP_LOGE(TAG, "Camera initialisation failed");
        return;
    }
    int i =0;
    while(1)
    {
        i++;
        printf("Immagine n %d\n", i);
        // Acquisisci un'immagine dalla fotocamera
        camera_fb_t *fb = esp_camera_fb_get();
        if (!fb) 
        {
            ESP_LOGE(TAG, "Failed to capture image");
            return;
        }
        // Invia l'immagine al bucket S3
        ESP_LOGI(TAG, "Sending image to S3...");
        send_image_to_drive(fb);
        printf("Stampa dopo invio\n");
        // Libera il frame buffer dopo l'invio
        esp_camera_fb_return(fb);
        printf("Stampa dopo ritorno camera\n");
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}
Thanks for the support,
Giovanni

nopnop2002
Posts: 138
Joined: Thu Oct 03, 2019 10:52 pm
Contact:

Re: image upload on AWS s3

Postby nopnop2002 » Sun Jan 19, 2025 8:06 am

Code: Select all

sprintf(post_data, "filename=ESP32-CAM.jpg&mimetype=image/jpeg&data=%s", encoded_image);
I think the mimetype of the data converted using base64 is application/octet-stream.

Who is online

Users browsing this forum: ram_0000 and 111 guests