android – How to fix this Firebase message format sent from ESP32 (Arduino, ESP-IDF – all text, no Firebase library used)-ThrowExceptions

Exception or error:

I’m trying to get this code below to work which was working perfectly a year ago the last time I tried it. After running it I receive no notification in my app. Using in Arduino IDE on ESP32 module. No changes were made at all to the sketch that was once working other than updating the token. I do not get the “firebase error” message in the serial output so assuming no error.

WiFiClient client;
String serve = "MY SERVER KEY";
String appToken = "MY APP TOKEN";
String data = "{";
data = data + "\"to\": \"" + appToken + "\",";
data = data + "\"notification\": {";
data = data + "\"body\": \"example body\",";
data = data + "\"title\" : \"my title\" ";
data = data + "} }";

Serial.println("Send data...");
if (client.connect("fcm.googleapis.com", 80)) {
  Serial.println("Connected to the server..");
  client.println("POST /fcm/send HTTP/1.1");
  client.println("Authorization: key=" + serve + "");
  client.println("Content-Type: application/json");
  client.println("Host: fcm.googleapis.com");
  client.print("Content-Length: ");
  client.println(data.length());
  client.print("\n");
  client.print(data);
  Serial.println("data");
  Serial.println(data);

}
else {
  Serial.println("firebase error");
}
Serial.println("Data sent...Reading response..");
while (client.available()) {
  char c = client.read();
  Serial.print(c);
}
Serial.println("Finished!");
client.flush();
client.stop();
}

I just updated Firebase in my app and migrated to AndroidX and can receive messages sent from the Firebase console and I’m currently using this library successfully to send and receive the notifications in my app. Below is the example I’m using and it’s working perfectly.

#include <WiFi.h>
#include <FirebaseESP32.h>

#define WIFI_SSID "YOUR_WIFI_AP"
#define WIFI_PASSWORD "YOUR_WIFI_PASSWORD"
#define FIREBASE_HOST "YOUR_FIREBASE_PROJECT.firebaseio.com" //Do not include https:// in FIREBASE_HOST
#define FIREBASE_AUTH "YOUR_FIREBASE_DATABASE_SECRET"

#define FIREBASE_FCM_SERVER_KEY "YOUR_FIREBASE_PROJECT_CLOUD_MESSAGING_SERVER_KEY"
#define FIREBASE_FCM_DEVICE_TOKEN_1 "RECIPIENT_DEVICE_TOKEN"
#define FIREBASE_FCM_DEVICE_TOKEN_2 "ANOTHER_RECIPIENT_DEVICE_TOKEN"

FirebaseData firebaseData1;

unsigned long lastTime = 0;

int count = 0;

void sendMessage();

void setup()
{

    Serial.begin(115200);

    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    Serial.print("Connecting to Wi-Fi");
    while (WiFi.status() != WL_CONNECTED)
    {
        Serial.print(".");
        delay(300);
    }
    Serial.println();
    Serial.print("Connected with IP: ");
    Serial.println(WiFi.localIP());
    Serial.println();

    Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
    Firebase.reconnectWiFi(true);

    firebaseData1.fcm.begin(FIREBASE_FCM_SERVER_KEY);

    firebaseData1.fcm.addDeviceToken(FIREBASE_FCM_DEVICE_TOKEN_1);

    firebaseData1.fcm.addDeviceToken(FIREBASE_FCM_DEVICE_TOKEN_2);

    firebaseData1.fcm.setPriority("high");

    firebaseData1.fcm.setTimeToLive(1000);

    sendMessage();
}

void loop()
{

    if (millis() - lastTime > 60 * 1000)
    {
        lastTime = millis();

        sendMessage();
    }
}

void sendMessage()
{

    Serial.println("------------------------------------");
    Serial.println("Send Firebase Cloud Messaging...");

    firebaseData1.fcm.setNotifyMessage("Notification", "Hello World! " + String(count));

    firebaseData1.fcm.setDataMessage("{\"myData\":" + String(count) + "}");

    //if (Firebase.broadcastMessage(firebaseData1))
    //if (Firebase.sendTopic(firebaseData1))
    if (Firebase.sendMessage(firebaseData1, 0))//send message to recipient index 0
    {

        Serial.println("PASSED");
        Serial.println(firebaseData1.fcm.getSendResult());
        Serial.println("------------------------------------");
        Serial.println();
    }
    else
    {
        Serial.println("FAILED");
        Serial.println("REASON: " + firebaseData1.errorReason());
        Serial.println("------------------------------------");
        Serial.println();
    }

    count++;
}

I’ve tried sending the code at the top in data and notification message format with app in foreground and background and cannot receive a message. I’m wondering if something in the Firebase format or rules or such has changed within the last year. I need to use the code at the top instead of the library because I can just add a few more key value pairs in the message body and also send to iOS which I have done successfully in the past using the same code. I’m sure the key pairs could be added with the library actually which I’m working on now but would really prefer the simplicity of the top code. Would appreciate any advice.

How to solve:

I’m not certain but I believe the problem may be that the Arduino code is sending via HTTP and not HTTPS, which I read in the FB docs HTTPS is required. Maybe they changed that because this same code was working perfectly for me a year ago. But I was in the process of migrating my code over to ESP-IDF and this function below is working on that with no problem which has slight mods to comply with C++ I’m using in PlatformIO / VS Code IDE. This was the only thing changed:

esp_http_client_config_t config;
config.url = "https://fcm.googleapis.com/fcm/send";
config.event_handler = _http_event_handler;

I didn’t need any type of SSL certificate, I just sent the code as shown. I didn’t try messing around too much with the Arduino code for HTTPS.

static void firebasePost() {
    esp_http_client_config_t config;
    config.url = "https://fcm.googleapis.com/fcm/send";
    config.event_handler = _http_event_handler;
    esp_http_client_handle_t client = esp_http_client_init(&config);
    esp_err_t err = esp_http_client_perform(client);
    const char *post_data = "{\"to\": \"eCiC-20m8Zw:APA91bE4i1rkC(SHORTENED)9JZpbW3gFe5Qfz9BhOFmqua3aeZoDZEQ\",\"notification\": {\"body\": \"Sample Body\",\"title\" : \"Sample Title\"} }";
    esp_http_client_set_header(client, "Authorization", "key=AAAAZrM4XXXX:APA91bFnSr_U15y6mX(SHORTENED)WqaWECxYWaCf_rVPE");
    esp_http_client_set_header(client, "Content-Type", "application/json");
    esp_http_client_set_method(client, HTTP_METHOD_POST);
    esp_http_client_set_post_field(client, post_data, strlen(post_data));
    err = esp_http_client_perform(client);
    if (err == ESP_OK) {
        ESP_LOGI(TAG, "HTTP POST Status = %d, content_length = %d",
                 esp_http_client_get_status_code(client),
                 esp_http_client_get_content_length(client));
    } else {
        ESP_LOGE(TAG, "HTTP POST request failed: %s", esp_err_to_name(err));
    }
    esp_http_client_cleanup(client);
} 

Leave a Reply

Your email address will not be published. Required fields are marked *