instructions of sending push notification using iot foundation...

18
Instructions of Sending Push Notification Using IoT Foundation on Bluemix This page is about obtaining the temperature from a sensor and pushing a notification to an Android device with the usage of IBM Bluemix services. To do this system, you need the following requirements: 1. Arduino Yun Pack(Cables, Board, etc.) 2. DHT11 Temperature Sensor 3. An Android Device Below, you can see the steps one by one how to do this system. PART I - Setup the Board 1. Download the Arduino Application from http:// www.arduino.cc/en/Main/Software and install. Run it as administrator. 2. Connect the pins as shown in the figure below.

Upload: others

Post on 29-May-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Instructions of Sending Push Notification Using IoT Foundation …erciyestto.com/user/files/instructions-of-ibm-project.pdf · 2015-12-16 · Instructions of Sending Push Notification

Instructions of Sending Push Notification Using IoT Foundation on Bluemix

This page is about obtaining the temperature from a sensor and pushing a notification to an Android device with the usage of IBM Bluemix services. To do this system, you need the following requirements:

1. Arduino Yun Pack(Cables, Board, etc.)2. DHT11 Temperature Sensor3. An Android DeviceBelow, you can see the steps one by one how to do this system.

PART I - Setup the Board

1. Download the Arduino Application from http://www.arduino.cc/en/Main/Software and install. Run it as administrator.

2. Connect the pins as shown in the figure below.

Page 2: Instructions of Sending Push Notification Using IoT Foundation …erciyestto.com/user/files/instructions-of-ibm-project.pdf · 2015-12-16 · Instructions of Sending Push Notification

3. Connect your PC to your Arduino Yun with wi-fi network.Then open “192.168.240.1” local address in browser. Default password is: “arduino”. Configure your wireless network and password. Then click “CONFIGURE & RESTART”.

4. On Arduino application click Sketch/Include Library/Manage Libraries… after that make sure that these ones are installed:

-DHT sensor library by Adafruit Version 1.1.1-SD Built-In by Arduino, SparkFun Version 1.0.5-Bridge Built-In by Arduino Version 1.0.7-Adafruit MQTT Library by Adafruit Version 0.10.0

Page 3: Instructions of Sending Push Notification Using IoT Foundation …erciyestto.com/user/files/instructions-of-ibm-project.pdf · 2015-12-16 · Instructions of Sending Push Notification

5. Copy this code below to your sketch and change only “YOUR MAC ADDRESS”(like 12ab34cd56ef):“#include <DHT.h>#include <SPI.h>#include <Bridge.h>#include <YunClient.h>#include <MQTTClient.h>#include <IPStack.h>#include <Countdown.h>#define MS_PROXY "quickstart.messaging.internetofthings.ibmcloud.com"#define MQTT_PORT 1883#define MQTT_MAX_PACKET_SIZE 100byte mac[] = { 0x00, 0xFF, 0xBB, 0xCC, 0xDE, 0x02 };#define MQTT_CLIENTID “d:quickstart:iotsample-arduino:YOUR MAC ADDRESS“#define MQTT_TOPIC "iot-2/evt/status/fmt/json"YunClient c; IPStack ipstack(c);MQTT::Client<IPStack, Countdown, 100, 1> client = MQTT::Client<IPStack, Countdown, 100, 1>(ipstack);String deviceEvent;#define DHTPIN A0#define DHTTYPE DHT11 // DHT 11 DHT dht(DHTPIN, DHTTYPE);void setup() {

Serial.begin(115200); while (!Serial) ; Bridge.begin(); //For Arduino Yun, use Bridge.begin() delay(2000); dht.begin(); Serial.println("DHT11 test!");}void loop() { int rc = -1; if (!client.isConnected()) { Serial.println("Connecting"); while (rc != 1) { rc = ipstack.connect(MS_PROXY, MQTT_PORT); Serial.println(rc); } MQTTPacket_connectData data = MQTTPacket_connectData_initializer; data.MQTTVersion = 3; data.clientID.cstring = MQTT_CLIENTID; rc = -1; while ((rc = client.connect(data)) != 0); Serial.println("Connected \n"); Serial.println("Temperature(in C)\tDevice Event (JSON)"); } MQTT::Message message; message.qos = MQTT::QOS0; message.retained = false; deviceEvent = String("{\"d\":{\"myName\":\"Arduino Yun\",\"temperature\":"); char buffer[60]; dtostrf(getTemp(), 1, 2, buffer); deviceEvent += buffer; deviceEvent += "}}"; Serial.print("\t"); Serial.print(buffer); Serial.print("\t\t");

Page 4: Instructions of Sending Push Notification Using IoT Foundation …erciyestto.com/user/files/instructions-of-ibm-project.pdf · 2015-12-16 · Instructions of Sending Push Notification

deviceEvent.toCharArray(buffer, 60); Serial.println(buffer); message.payload = buffer; message.payloadlen = strlen(buffer); rc = client.publish(MQTT_TOPIC, message); if (rc != 0) { Serial.print("return code from publish was "); Serial.println(rc); } client.yield(1000);}float getTemp(){ float t = dht.readTemperature(); return t;

}”

6. Click Sketch/Upload and wait until “Done Uploading” is written on the console. After that, click Tools/Serial Monitor and check your temperature value and JSON message.

Page 5: Instructions of Sending Push Notification Using IoT Foundation …erciyestto.com/user/files/instructions-of-ibm-project.pdf · 2015-12-16 · Instructions of Sending Push Notification

7. Check if the temperature values are sent to the IoT Foundation or not by writing your device id(your mac address you entered the code) at the following link: “quickstart.internetofthings.ibmcloud.com”

PART II - Configure the Bluemix, NodeRed and Google Services

1. Create an IBM account on this page: https://console.ng.bluemix.net/registration/ and login. Click “+Create a Space” on the left panel. Enter a project name. Click “Catalog” on the top panel, then click “Internet of Things Foundation Starter” in items that are opened. On the right panel click on “Create an app” and enter your application name to the “Name” text box(it can be same with your space name). Then click “CREATE”. Return to the “Dashboard” from the top

Page 6: Instructions of Sending Push Notification Using IoT Foundation …erciyestto.com/user/files/instructions-of-ibm-project.pdf · 2015-12-16 · Instructions of Sending Push Notification

panel and click on “Applications” tab in your application which is at the middle of the page. Click “+Add a Service or API” and add “Mobile Application Security” and “Push” services from the catalog.

Page 7: Instructions of Sending Push Notification Using IoT Foundation …erciyestto.com/user/files/instructions-of-ibm-project.pdf · 2015-12-16 · Instructions of Sending Push Notification
Page 8: Instructions of Sending Push Notification Using IoT Foundation …erciyestto.com/user/files/instructions-of-ibm-project.pdf · 2015-12-16 · Instructions of Sending Push Notification

2. Now let’s start working with the NodeRed Editor. Enter this page http://YOUR_PROJECT_NAME.mybluemix.net/red/# and change your project name. Select all with your mouse and delete all graph items. After the page is blank, click the tab on top right and then Import/Clipboard. Copy paste the following node and select “OK”:[{"id":"3e77d543.c1882a","type":"ibmiot in","authentication":"quickstart","apiKey":"","inputType":"evt","deviceId":"90a2dafa0daa","applicationId":"","deviceType":"+","eventType":"+","commandType":"","format":"json","name":"IBM IoT App In","service":"quickstart","allDevices":false,"allApplications":false,"allDeviceTypes":true,"allEvents":true,"allCommands":false,"allFormats":false,"x":147,"y":183,"z":"76458682.89ba78","wires":[["90afbbb1.6f5048"]]},{"id":"ff6ad0d9.00953","type":"switch","name":"condition","property":"payload","rules":[{"t":"lte","v":"26"},{"t":"else"}],"checkall":"false","outputs":2,"x":441.5,"y":183,"z":"76458682.89ba78","wires":[["80621eff.7f9de"],["8e1706a.f71e8f8","50e69ec4.af196"]]},{"id":"5dad02b7.a252fc","type":"debug","name":"current status","active":true,"console":"true","complete":"payload","x":792.5,"y":189,"z":"76458682.89ba78","wires":[]},{"id":"80621eff.7f9de","type":"template","name":"safe","field":"","template":"Temperature ({{payload}}) within safe limits","x":602.5,"y":141,"z":"76458682.89ba78","wires":[["5dad02b7.a252fc"]]},{"id":"8e1706a.f71e8f8","type":"template","name":"danger","field":"","template":"Temperature ({{payload}}) critical","x":602.5,"y":189,"z":"76458682.89ba78","wires":[["5dad02b7.a252fc"]]},{"id":"50e69ec4.af196","type":"ibmpush","name":"Push Notification","ApplicationID":"6b6da03a-2376-4a48-852e-44530a081827","ApplicationRoute":"http://IBM-Project.mybluemix.net","identifiers":"","notification":"broadcast","x":637,"y":281,"z":"76458682.89ba78","wires":[]},{"id":"90afbbb1.6f5048","type":"function","name":"temp","func":"var newMsg = {payload:msg.payload.d.temperature};\nreturn newMsg;”,”outputs”:"1","noerr":0,"x":303,"y":183,"z":"76458682.89ba78","wires":[["ff6ad0d9.00953"]]}]

Page 9: Instructions of Sending Push Notification Using IoT Foundation …erciyestto.com/user/files/instructions-of-ibm-project.pdf · 2015-12-16 · Instructions of Sending Push Notification

3. Create a Google account on this page: https://console.developers.google.com and login. Click “Create a Project” and enter your “Project name”. Click “APIs & auth/Credentials” on the left panel. Below the tab, select the “Add credentials” and API key. You need Server key so select it. Then click “Create”. A key must be added on this page.

4. At this part, you will be doing some configurations so don’t close the previous pages you had opened. Let’s start with NodeRed. Double click “IBM IoT App In” and change “Device Id” with your mac address of your Arduino and close it. Return to the dashboard of Bluemix and select your application which is running. Click “Mobile Options” on the top right of the page. Copy the “App Secret” from the opened tab. Open NodeRed again and double click on the “Push Notification”. Paste it to the “Secret” in the “MBaaS Application Properties”. Click Deploy on the top right of the page and NodeRed is ready now.

Page 10: Instructions of Sending Push Notification Using IoT Foundation …erciyestto.com/user/files/instructions-of-ibm-project.pdf · 2015-12-16 · Instructions of Sending Push Notification

5. Let’s configure Bluemix application. Open the running application again and click “Mobile Application Security” below the “Services” on the left panel. On the “Registered Clients” tab, turn on the “Enable Client List” and click “Add Client”. The type must be Android and Package ID must be like this format: “YOUR_NAMEYOUR_SURNAME.PROJECT_NAME”(Example: burakaykan.ibmproject).

Page 11: Instructions of Sending Push Notification Using IoT Foundation …erciyestto.com/user/files/instructions-of-ibm-project.pdf · 2015-12-16 · Instructions of Sending Push Notification

6. Enter “Push” this time below the “Services” from the left panel. At the “Configuration” tab, click “Edit” under the Google Cloud Messaging. As you see we need “Sender Auth Token” and “Sender Id”. You will earn these values from console of Google. Copy the key that you had created at the “APIs & auth/Credentials” and paste it to the both “Sender Auth Token” blanks. Click Home from the console of Google at the left panel. Copy the “Project Number” at the middle top of the page and paste it to the both “Sender Id” blanks.

PART III - Android

1. Download the Android Studio application from https://developer.android.com/sdk/index.html and install it. After that, run the application. Select “Start a new Android Studio project”. Application name must the same with your Bluemix project name and Company Domain must be your first name and last name. Copy the package name, you will use in next step. Click next button until the finish button without changing anything.

Page 12: Instructions of Sending Push Notification Using IoT Foundation …erciyestto.com/user/files/instructions-of-ibm-project.pdf · 2015-12-16 · Instructions of Sending Push Notification
Page 13: Instructions of Sending Push Notification Using IoT Foundation …erciyestto.com/user/files/instructions-of-ibm-project.pdf · 2015-12-16 · Instructions of Sending Push Notification

2. You can see the directory of your files on the left of the application.

Open “app/manifest/AndroidManifest.xml” from there and copy this code: “<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package=“PACKAGE_NAME" > <permission android:name="com.ibm.mbaas.push.android.sample.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="com.ibm.mbaas.push.android.sample.permission.C2D_MESSAGE" />

Page 14: Instructions of Sending Push Notification Using IoT Foundation …erciyestto.com/user/files/instructions-of-ibm-project.pdf · 2015-12-16 · Instructions of Sending Push Notification

<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.USE_CREDENTIALS" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="com.ibm.mbaas.push.android.sample.IBMPushNotification" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <service android:name="com.ibm.mobile.services.push.IBMPushIntentService" /> <receiver android:name="com.ibm.mobile.services.push.IBMPushBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND"> <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <category android:name="com.ibm.mbaas.push.android.sample" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <category android:name="com.ibm.mbaas.push.android.sample" /> </intent-filter> </receiver> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> </application>

</manifest>”In this code, change only the package name which you

had copied at the previous step.

3. Now, open again the directory panel “app/java/(packagename)/MainActivity” and copy this code: “package YOUR_PACKAGE_NAME;

import android.content.DialogInterface;import android.os.Bundle;import android.support.v7.app.AlertDialog;import android.support.v7.app.AppCompatActivity;import android.view.Menu;import android.view.MenuItem;

import com.ibm.mobile.services.core.IBMBluemix;

Page 15: Instructions of Sending Push Notification Using IoT Foundation …erciyestto.com/user/files/instructions-of-ibm-project.pdf · 2015-12-16 · Instructions of Sending Push Notification

import com.ibm.mobile.services.push.IBMPush;import com.ibm.mobile.services.push.IBMPushNotificationListener;import com.ibm.mobile.services.push.IBMSimplePushNotification;

import java.util.List;

import bolts.Continuation;import bolts.Task;

public class MainActivity extends AppCompatActivity {

private IBMPush push; private IBMPushNotificationListener notificationListener;

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);

IBMBluemix.initialize(this, getString(APP_KEY), getString(APP_SECRET), getString(ROUTE));

push = IBMPush.initializeService();

push.register("Test", "1234").continueWith(new Continuation<String, Void>() { @Override public Void then(Task<String> task) throws Exception {

if (task.isFaulted()) { Exception e = task.getError(); } else { String deviceId = task.getResult(); }

return null; } });

notificationListener = new IBMPushNotificationListener() { @Override public void onReceive(final IBMSimplePushNotification message) { showSimplePushMessage(message); }

};

push.getTags().continueWith(new Continuation<List<String>, Void>() { @Override public Void then(Task<List<String>> task) throws Exception {

if (task.isFaulted()) { System.out.println("Error getting tags..." + task.getError().getMessage()); } else { List<String> tags = task.getResult(); System.out.println("Retrieved Tags : " + tags); } return null; } });

Page 16: Instructions of Sending Push Notification Using IoT Foundation …erciyestto.com/user/files/instructions-of-ibm-project.pdf · 2015-12-16 · Instructions of Sending Push Notification

}

void showSimplePushMessage(final IBMSimplePushNotification message) { runOnUiThread(new Runnable() { @Override public void run() {

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setMessage("Notification Received : " + "Temperature is high!"); builder.setCancelable(true); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int s) { } });

AlertDialog dialog = builder.create(); dialog.show(); } }); }

@Override protected void onResume() { super.onResume(); if (push != null) { push.listen(notificationListener); } }

@Override protected void onPause() { super.onPause();

if (push != null) { push.hold(); } }

@Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; }

@Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId();

if (id == R.id.action_settings) { return true; }

return super.onOptionsItemSelected(item); }

}”

Page 17: Instructions of Sending Push Notification Using IoT Foundation …erciyestto.com/user/files/instructions-of-ibm-project.pdf · 2015-12-16 · Instructions of Sending Push Notification

In this part, you are going to change package and mobile informations which are written in red. You already know package name so change it. After that open the Bluemix console and click your running application. At the middle top panel, click “Mobile Options”. From the opened tab, you can see all three values that are needed in the code(route,key and secret). Then change them.

4. Let’s open the last file from Android Studio which is “app/res/layout/activity_main.xml”. Copy and paste this code: “<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<WebView android:id="@+id/richWebView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" /></RelativeLayout>

”5. Take your phone and enter the settings/DeveloperSettings. Turn on the USB Debugging and connect to your computer via USB cable. Then run the application on Android Studio, after a short delay select your Android device.

Page 18: Instructions of Sending Push Notification Using IoT Foundation …erciyestto.com/user/files/instructions-of-ibm-project.pdf · 2015-12-16 · Instructions of Sending Push Notification

Now your system is working.

When your sensor detect greater than 26 Celsius temperature, your device will take push notification which is: “Notification Received : Temperature is high!” in few seconds.