Example sketches for the new Arduino IDE for ESP8266

Moderator: igrr

User avatar
By BeeGee
#40139 I was looking into a solution to send push notifications from an ESP8266 module to an Android application. I know that this is possible with the Google Cloud Messaging service.

But what I found on the internet is using an external webserver, able to run PHP (or Python) scripts and using a MySQL server to store registration IDs.
ImageImage
So far so good, but why do I need to setup an external server with MySQL and PHP just to send messages to the Android devices. The ESP8266 has server capabilities build-in and has enough storage to save registration IDs in the Flash memory.
What I wanted is:
ImageImage

As I could not find any tutorial or example on the Internet how to achieve this, I started to write the code by myself.
And here is the result:
ESP8266 - Google Cloud Messaging without external server
Of course the code is open source and stored in my Github repository

Hope it helps someone.
User avatar
By BeeGee
#45207 Hi JP, I saw your comment on my website:
freedom2000 wrote:Fantastic tutorial.

I have got it work, but have been obliged to increase the DeviceId to 162

if (newDeviceID.length() != 162) {

140 seems to be no longer supported by Google ?

However it works now.
I can hadle the message intent in my Android App following Basic4Android tutorial here : https://www.b4x.com/android/forum/threa ... ork.35635/

I have also seen that it should be possible to directly send a notification to the device :

Here is a JSON-formatted message can containing both notification and data:

{
“to” : “APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx…”,
“notification” : {
“body” : “great match!”,
“title” : “Portugal vs. Denmark”,
“icon” : “myicon”
},
“data” : {
“Nick” : “Mario”,
“Room” : “PortugalVSDenmark”
}
}

But I am not tottally “fluent” with your code and Json…
so I don’t know where to add thes “notification” key.

I believe it should be somewhere here :
void loop() {
// Handle new client request on HTTP server if available
WiFiClient client = server.available();
if (client) {
webServer(client);
}

if (doPush) {
doPush = false;
// Create messages & keys as JSON arrays
DynamicJsonBuffer jsonBufferKeys;
DynamicJsonBuffer jsonBufferMsgs;
JsonArray& msgKeysJSON = jsonBufferKeys.createArray();
JsonArray& msgsJSON = jsonBufferMsgs.createArray();
char buf[4];
char msgOne[24] = “Test message number “;
itoa(msgCnt,buf,10);
strcat(msgOne,buf);
msgKeysJSON.add(“message”);
msgKeysJSON.add(“timestamp”);
msgsJSON.add(msgOne);
msgsJSON.add(buf);
gcmSendMsg(msgKeysJSON, msgsJSON);
msgCnt++;
}

Any help please ?
Thanks
JP


In case you didn't get my reply there:
Hello JP,

To create the message with both data and notification you can do like following:
Code: Select all      /***********************************************
       Create JSON object to send GCM with data and notification
      ***********************************************/
      /* This is the GCM message example:   
         {
            “to” : “APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx…”,
            “notification” : {
               “body” : “great match!”,
               “title” : “Portugal vs. Denmark”,
               “icon” : “myicon”
            },
            “data” : {
               “Nick” : “Mario”,
               “Room” : “PortugalVSDenmark”
            }
         }
      */

      /** Buffer for Json object with complete GCM message */
      DynamicJsonBuffer jsonBuffer;
      /** Buffer for Json object with data */
      DynamicJsonBuffer jsonDataBuffer;
      /** Buffer for Json object with notification */
      DynamicJsonBuffer jsonNotifBuffer;

      // Prepare "data" object
      JsonObject& dataJSON = jsonDataBuffer.createObject();
      dataJSON["Nick"] = "Mario";
      dataJSON["Room"] = "PortugalVSDenmark";
      
      // Prepare "notification" object
      JsonObject& notifJSON = jsonNotifBuffer.createObject();
      notifJSON["body"] = "great match!";
      notifJSON["title"] = "Portugal vs. Denmark";
      notifJSON["icon"] = "myicon";
      
      // Prepare GCM JSON object
      JsonObject& msgJSON = jsonBuffer.createObject();

      // Add the device ID you want to push a message to
      msgJSON["to"] = "YourAndroidMessageIDHere";; // put your Android device ID here
      
      // Add the notification data to the message
      msgJSON["notification"] = notifJSON;
      
      // Add the data to the message
      msgJSON["data"] = dataJSON;
      
      // Convert the JSON to a String
      String gcmMessage;
      msgJSON.printTo(gcmMessage);

      // Just for testing, print out the message on serial port
      Serial.println("GCM message as JSON");
      msgJSON.prettyPrintTo(Serial);
      Serial.println("");
      
      // Send the message by calling gcmSendOut instead of gcmSendMsg !!!!
      gcmSendOut(gcmMessage);


Here is the debug output from serial port:
Code: Select allGCM message as JSON
{
  "to": "APA91bG27MAZZpfiWsA..............",
  "notification": {
    "body": "great match!",
    "title": "Portugal vs. Denmark",
    "icon": "myicon"
  },
  "data": {
    "Nick": "Mario",
    "Room": "PortugalVSDenmark"
  }
}
Connecting to http://android.googleapis.com
Connected to GCM server
This is the Request to http://android.googleapis.com :
POST /gcm/send HTTP/1.1
Host: android.googleapis.com
Accept: */*
Authorization: key=AIzaSyAuzBZpPRzI...................
Content-Type: application/json
Content-Length: 286

{"to":"APA91bG27MAZZpfiWsAISmulOO.........................................","notification":{"body":"great match!","title":"Portugal vs. Denmark","icon":"myicon"},"data":{"Nick":"Mario","Room":"PortugalVSDenmark"}}


Response from GCM server:
Found JSON result: {"multicast_id":7921150450792951525,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1460270944874316%a03653e3f9fd7ecd"}]}

Message successfully sent!!!!!!!!!!!!!!!!!!!!!!!!!!!

And on my Android tablet I received:
Code: Select all04-10 15:25:04.520 3775-20569/tk.giesecke.myhomecontrol D/MHC-GCM: Got GCM = Bundle[{gcm.notification.title=Portugal vs. Denmark, Nick=Mario, Room=PortugalVSDenmark, from=928633261430, gcm.notification.body=great match!, gcm.notification.icon=myicon, android.support.content.wakelockid=1061, collapse_key=do_not_collapse}]

Hope this helps for your specific question.