Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FirebaseCloudMessaging example #250

Closed
kiralikbeyin opened this issue Feb 28, 2017 · 12 comments
Closed

FirebaseCloudMessaging example #250

kiralikbeyin opened this issue Feb 28, 2017 · 12 comments

Comments

@kiralikbeyin
Copy link

CLIENT_REGISTRATION_ID "key_from_client_after_registration"

How to register? I think this example need an update.

@kiralikbeyin
Copy link
Author

kiralikbeyin commented Feb 28, 2017

Working example without <FirebaseCloudMessaging.h>
CLIENT_REG_ID and TOPIC works fine.

How to register? You can only reg with a mobile device like android emulator


#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

#include <FirebaseCloudMessaging.h> 
 
#define WIFI_SSID     "WWW"
#define WIFI_PASSWORD "MMM"

//FOR FirebaseCloudMessaging.h which is not working
#define SERVER_KEY "PUT YOUR GCM KEY"
#define CLIENT_REGISTRATION_ID "YOU HAVE TO MAKE A LOT WORK TO FIND YOUR ANDROID REG ID"
//THIS WILL GIVE AN IDEA https://github.com/arnesson/cordova-plugin-firebase
#define TOPIK     "TOPIK"
//FOR FirebaseCloudMessaging.h which is not working

WiFiClient client;
String serve = "PUT YOUR GCM KEY";
String reg = "YOU HAVE TO MAKE A LOT WORK TO FIND YOUR ANDROID REG ID";
//THIS WILL GIVE AN IDEA https://github.com/arnesson/cordova-plugin-firebase
String top = "TOPIK";


void setup() {
  Serial.begin(9600);
  Serial.setDebugOutput(true);
  // connect to wifi.
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.print("connected: ");
  Serial.println(WiFi.localIP());
 
  //NO NEED
  FirebaseCloudMessaging fcm(SERVER_KEY);
  //NO CHANCE
  FirebaseCloudMessage message =
    FirebaseCloudMessage::SimpleNotification("Hello World!", "What's happening?");
  FirebaseError error = fcm.SendMessageToUser(CLIENT_REGISTRATION_ID, message);
  if (error) {
    Serial.print("Error:");
    Serial.print(error.code());
    Serial.print(" :: ");
    Serial.println(error.message().c_str());
  } else {
    Serial.println("Sent OK!");
  }
  //NO CHANCE
  FirebaseCloudMessage messageTOPIK =
    FirebaseCloudMessage::SimpleNotification("Hello World!TOPIK", "What's happening?TOPIK");
  FirebaseError errorTOPIK = fcm.SendMessageToTopic(TOPIK, message);
  if (errorTOPIK) {
    Serial.print("ErrorError:");
    Serial.print(errorTOPIK.code());
    Serial.print(" :: ");
    Serial.println(errorTOPIK.message().c_str());
  } else {
    Serial.println("Sent OKOK!");
  }
  //NO CHANCE


}


HTTPClient http;
void doit(String paytitle, String pay) {
  //more info @ https://firebase.google.com/docs/cloud-messaging/http-server-ref

  String data = "{";
  data = data + "\"to\": \"" + reg + "\",";
  data = data + "\"notification\": {";
  data = data + "\"body\": \"" + pay + "\",";
  data = data + "\"title\" : \"" + paytitle + "\" ";
  data = data + "} }";

  http.begin("http://fcm.googleapis.com/fcm/send");
  http.addHeader("Authorization", "key=" + serve);
  http.addHeader("Content-Type", "application/json");
  http.addHeader("Host", "fcm.googleapis.com");
  http.addHeader("Content-Length", String(pay.length()));
  http.POST(data);
  http.writeToStream(&Serial);
  http.end();
  Serial.println();

}

HTTPClient httpTOPIK;
void doitTOPIC(String paytitle, String pay, String top) {
  //more info @ https://firebase.google.com/docs/cloud-messaging/http-server-ref


  String data = "{";
  data = data + "\"to\": \"/topics/" + top + "\",";
  data = data + "\"notification\": {";
  data = data + "\"body\": \"" + pay + "\",";
  data = data + "\"title\" : \"" + paytitle + "\" ";
  data = data + "} }";

  httpTOPIK.begin("http://fcm.googleapis.com/fcm/send");
  httpTOPIK.addHeader("Authorization", "key=" + serve);
  httpTOPIK.addHeader("Content-Type", "application/json");
  httpTOPIK.addHeader("Host", "fcm.googleapis.com");
  httpTOPIK.addHeader("Content-Length", String(pay.length()));
  httpTOPIK.POST(data);
  httpTOPIK.writeToStream(&Serial);
  httpTOPIK.end();
  Serial.println();

}

//DIRTY WAY
void sendDataToFirebase() {
  String data = "{";
  data = data + "\"to\": \"" + reg + "\",";
  data = data + "\"notification\": {";
  data = data + "\"body\": \"orAway\",";
  data = data + "\"title\" : \"Non\" ";
  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 sent...Reading response..");
  while (client.available()) {
    char c = client.read();
    Serial.print(c);
  }
  Serial.println("Finished!");
  client.flush();
  client.stop();
}
void loop() {
  // doit("quick", "silver"); //clear way with reg_id
  doitTOPIC("Mr&Mrs", "Brown", top); //clear way with topic
  // doitTOPIC("title", "body", "yourverycustomtopic");

  delay(13000);

  //sendDataToFirebase(); dirty way

}


//TOPIC HELP YOU CAN MAKE IT WITH POSTMAN  @http://stackoverflow.com/questions/37367292/how-to-create-topic-in-fcm-notifications/37422938#37422938
//You can create a topic with http api:
//
//https://iid.googleapis.com/iid/v1/IID_TOKEN/rel/topics/TOPIC_NAME
//
//1. IID_TOKEN = Device registration token, you can find it with following command on your android device :
//
//String IID_TOKEN = FirebaseInstanceId.getInstance().getToken();
//2.TOPIC_NAME = new a topic name
//
//3.Authorization: key=YOUR_API_KEY. Set this parameter in the header. Look to screenshot: Creating new topic via Advanced rest client
//
//YOUR_API_KEY: console.firebase.google.com
//
//and send request and you will be receive http status "OK".
//
//Then you can get infos about all your topics in your current project with following api :
//
//https://iid.googleapis.com/iid/info/IID_TOKEN?details=true
//here need add Authorization key to header of request and you will be receive your topics list: response info topics
//
//I recommend read this article about Instance ID/Server by Google




////TO DO - SUBSCRIBE TO TOPIC FROM ESP WITH doit() method
//@https://firebase.google.com/docs/cloud-messaging/js/send-multiple
//
//Subscribe the client app to a topic
//
//Given a registration token and a topic name, you can create a mapping using the Google Instance ID server API. Call the Instance ID service at this endpoint, providing the app instance's registration token and the topic name:
//
// https://iid.googleapis.com/iid/v1/REGISTRATION_TOKEN/rel/topics/TOPIC_NAME
//To subscribe an app instance to a topic named "movies," for example, send the following POST request to the endpoint, adding your server API key in the authorizaton header as shown:
//
//https://iid.googleapis.com/iid/v1/nKctODamlM4:CKrh_PC8kIb7O...clJONHoA/rel/topics/movies
//Content-Type:application/json
//Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
//

//{ "notification": {
//    "title": "Background Message Title",
//    "body": "Background message body",
//    "click_action" : "https://dummypage.com"
//  },
//
//  "to" : "/topics/matchday"
//
//}

//FOR ONLY A DEVICE //  "to" : "CLIENT_REG_ID"

@xxporkoxx
Copy link

@kiralikbeyin I think you just saved my life!! Thank you very much! I was stucked with this for a long time (2 months probability).... And also saved my graduation =D =D

Your solution works and its probably better then the example that they made to the library...

1 similar comment
@xxporkoxx
Copy link

@kiralikbeyin I think you just saved my life!! Thank you very much! I was stucked with this for a long time (2 months probability).... And also saved my graduation =D =D

Your solution works and its probably better then the example that they made to the library...

@kiralikbeyin
Copy link
Author

@xxporkoxx well there is always another solution for coding. I am happy if it solved a real world problem like graduation :) You can donate with PayPal kiralikbeyin@gmail.com :)

@brubraz
Copy link

brubraz commented Jun 3, 2017

@kiralikbeyin Thank you for your contribution, very useful! ;)

@Jozx
Copy link

Jozx commented Jun 24, 2017

@kiralikbeyin save my final college job; thank so much... 👍

@fcleal
Copy link

fcleal commented Jul 19, 2017

Thank!

However, does anyone know why FirebaseCloudMessaging is not working on ESP8266?

@Leandro-G-Ribeiro
Copy link

sou novo aqui (brazil).
se não estiver executando o som das notificações podem usar este json:
String data = "{";
data = data + ""to": "token_aplication",";
data = data + ""notification": {";
data = data + ""body": "temperatura alta!!!",";
data = data + ""title" : "Alarm" ";
data = data + ""sound": "default","; // executa o som do sistema padrão de notificações..
data = data + ""priority" : "high" ";
data = data + "} }";

Também se tiverem problemas com Exception (29) podem executar o código da seguinte forma:
a parte de envio do do request http fica dentro de uma função:

void send_dados() {
WiFiClientSecure client;
String data = "{";
data = data + ""to": "token_aplication",";
data = data + ""notification": {";
data = data + ""body": "temperatura alta!!!",";
data = data + ""title" : "Alarm" ";
data = data + ""sound": "default",";
data = data + ""priority" : "high" ";
data = data + "} }";

Serial.println("Send data...");

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

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

Colocar este código dentro de uma função que instância WiFiClientSecure client e depois detroir esta instância, possibilitou exito no meu projeto. pois o código original do post causava Exception (29) depois de uma requisição de envio de mensagem, ou seja, a primeira mensagem era enviada mas da segunda em diante não.

@jameschen00
Copy link

Why the module FirebaseCloudMessaging of ESP8266 failed?
Reason: the internal Fingerprint of Firebase is out-of-date!
Action: forget the fingerprint!
==> Open the file FirebaseHttpClient_ESP8266.cpp, then modify Line 47 to be "http_.begin(url.c_str());"
Of course, there is more than one line should be modified for the same reason.

Enjoy.

James

@proppy
Copy link
Collaborator

proppy commented Jun 15, 2018

Sorry for the late reply filed #347 to track we need to update the fingerprint.

@proppy proppy closed this as completed Jun 15, 2018
@riskiadi
Copy link

riskiadi commented Oct 27, 2020

2020, you cant use http to firebase cloud messaging, you must use https.

Forbidden
Error 403

@ngchautg
Copy link

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

10 participants