Skip to content

Commit

Permalink
FCM messaging 2:38 PM 10/11/17
Browse files Browse the repository at this point in the history
  • Loading branch information
Mayank Narula committed Nov 10, 2017
1 parent 57b175a commit bdb3a55
Show file tree
Hide file tree
Showing 8 changed files with 154 additions and 20 deletions.
18 changes: 1 addition & 17 deletions App/SmartHome/.idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions App/SmartHome/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ dependencies {
compile 'com.android.support:support-v4:26.0.0-alpha1'
compile 'com.google.firebase:firebase-core:11.4.2'
compile 'com.google.firebase:firebase-database:11.4.2'
compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.google.firebase:firebase-messaging:11.4.2'
testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
Expand Down
9 changes: 9 additions & 0 deletions App/SmartHome/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,15 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<service
android:enabled="true"
android:name=".DeviceTokenUpdater">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>

</application>

</manifest>
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ class Constants {
static final int SENSOR_OP_CODE = 2;
static final String[] OptionTitles = new String[]{"SMART HOME", "SENSORS"};
static final String ARG_OPTION_NUMBER = "OPTION_INDEX";
static final String DEVICE_REG_SERVER = "isecpowify-server.herokuapp.com/u/device";
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package com.solutions.isecpowify.smarthome;

import android.support.annotation.NonNull;
import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
* Created by mayank on 10/11/17.
*/

public class DeviceTokenUpdater extends FirebaseInstanceIdService {

private static Map <String,String> queryParams;
private static String currentToken = null;
private static OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build();

private static final Callback resCB = new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
Log.v(Constants.TAG,e.getMessage());
call.cancel();
}

@Override
public void onResponse(@NonNull Call call, @NonNull Response response)
throws IOException {

if (response.isSuccessful()){
Log.v(Constants.TAG, String.valueOf(response.body()));
}
}
};


@Override
public void onTokenRefresh() {

// Get updated InstanceID token.
currentToken = FirebaseInstanceId.getInstance().getToken();
}

private static String getDeviceFCMToken(){
return currentToken;
}

static void sendDetailsToServer(final String otrk){

new Thread(new Runnable() {
@Override
public void run() {
while(getDeviceFCMToken()==null)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queryParams = Collections.emptyMap();
queryParams.put("fcm_token",getDeviceFCMToken());
queryParams.put("id_otr",otrk);
get(Constants.DEVICE_REG_SERVER,queryParams,resCB);
}
}).start();
}

public static void get(String url, Map<String,String> params, Callback responseCallback) {

try{
HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder();

if (params != null) {
for(Map.Entry<String, String> param : params.entrySet()) {
httpBuilder.addQueryParameter(param.getKey(),param.getValue());
}
}
Request request = new Request.Builder().url(httpBuilder.build()).build();
client.newCall(request).enqueue(responseCallback);

} catch (NullPointerException obj){
Log.v(Constants.TAG,"Object is null : " + obj.getMessage());
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.solutions.isecpowify.smarthome;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
Expand All @@ -12,8 +13,6 @@
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
Expand Down Expand Up @@ -57,6 +56,20 @@ static void restartApplication(Activity current) {

static void configSmartHome(View rootView, MainActivity current) {

try {
if( !alreadyRunningService(Class.forName("com.solutions.isecpowify.smarthome.DeviceTokenUpdater"),current)){
DeviceTokenUpdater
.sendDetailsToServer(
getSharedPreferences(current.getApplicationContext())
.getString(current.getString(R.string.OTRK),null)
);
}
} catch (ClassNotFoundException e) {
Log.v("Service Class Missing: ",e.getMessage());
} catch (Exception e){
Log.v(Constants.TAG,"Token Service Updater Exception Occurred : " + e.getMessage());
}

current.tv = rootView.findViewById(R.id.welcome);
current.tv.setText("NO INTERNET CONNECTION");
current.statusCard = rootView.findViewById(R.id.statusCard);
Expand Down Expand Up @@ -93,7 +106,18 @@ public void onCancelled(DatabaseError databaseError) {
});
}

private static boolean alreadyRunningService(Class<?> serviceClass,Context ctx) {

ActivityManager manager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.i ("Check Service Running: "+serviceClass.getName(), true+"");
return true;
}
}
Log.i ("Check Service Running: "+serviceClass.getName(), false+"");
return false;
}

private static void setRoomEvent(View rootView, MainActivity curr) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ protected void onCreate(Bundle savedInstanceState) {

setContentView(R.layout.activity_main);
selectItem(Constants.SMART_HOME_OP);

} else {
setContentView(R.layout.key_spec_layout);
findViewById(R.id.keySpecLayout)
Expand Down
17 changes: 17 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,23 @@ app.get("/u/state",function(req,response){
pushSensorData(q.temp,q.humidity,q.light,q.inDoorMotion,q.outDoorMotion,q.ax,q.ay,q.az);
}
});

app.get("/u/device",function(req,response){
response.writeHead(200, {'Content-type':'text/plain'});
response.write('Smart Home Device Registartion End Point\n');
response.end();
var q = req.query;

if( !isEmpty(q) ){

if( allValid(q.fcm_token,q.id_otr) ){
usersRef.child(q.id_otr).update({
"deviceToken" : q.fcm_token || null
});
}
}
});

app.listen(app.get('port'),function(){
console.log('Node app is running on port',app.get('port'));
});

0 comments on commit bdb3a55

Please sign in to comment.