forked from community/device-mgt-plugins
parent
7350de10fe
commit
90843729a7
@ -1,65 +0,0 @@
|
||||
apply plugin: 'com.android.application'
|
||||
|
||||
android {
|
||||
compileSdkVersion 22
|
||||
buildToolsVersion '22.0.1'
|
||||
defaultConfig {
|
||||
applicationId "agent.sense.android.iot.carbon.wso2.org.wso2_senseagent"
|
||||
minSdkVersion 19
|
||||
targetSdkVersion 22
|
||||
versionCode 1
|
||||
versionName "1.0"
|
||||
|
||||
}
|
||||
repositories {
|
||||
maven {
|
||||
url "https://dl.bintray.com/alt236/maven"
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
minifyEnabled false
|
||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
||||
applicationVariants.all { variant ->
|
||||
variant.outputs.each { output ->
|
||||
def newName = output.outputFile.name
|
||||
newName = newName.replace("app-", "androidsense")
|
||||
newName = newName.replace("release", "")
|
||||
//noinspection GroovyAssignabilityCheck
|
||||
output.outputFile = new File(output.outputFile.parent, newName)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
packagingOptions {
|
||||
exclude 'META-INF/NOTICE'
|
||||
exclude 'META-INF/LICENSE'
|
||||
exclude 'META-INF/DEPENDENCIES'
|
||||
exclude 'META-INF/NOTICE'
|
||||
exclude 'META-INF/LICENSE'
|
||||
exclude 'META-INF/LICENSE.txt'
|
||||
exclude 'META-INF/NOTICE.txt'
|
||||
}
|
||||
productFlavors {
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_1_7
|
||||
targetCompatibility JavaVersion.VERSION_1_7
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compile fileTree(include: ['*.jar'], dir: 'libs')
|
||||
compile 'com.android.support:appcompat-v7:22.2.1'
|
||||
compile 'com.android.support:design:22.2.1'
|
||||
compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.2'
|
||||
compile 'com.github.rholder:snowball-stemmer:1.3.0.581.1'
|
||||
compile 'commons-codec:commons-codec:1.4'
|
||||
compile 'com.netflix.feign:feign-jaxrs:8.16.0'
|
||||
compile 'com.netflix.feign:feign-jackson:8.16.0'
|
||||
compile 'org.altbeacon:android-beacon-library:2.8.1'
|
||||
compile 'uk.co.alt236:easycursor-android:1.0.0'
|
||||
compile 'uk.co.alt236:bluetooth-le-library-android:1.0.0'
|
||||
compile 'com.google.android.gms:play-services-location:9.4.0'
|
||||
}
|
@ -1,95 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="agent.sense.android.iot.carbon.wso2.org.wso2_senseagent" >
|
||||
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
|
||||
<uses-permission android:name="android.permission.BATTERY_STATS" />
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
|
||||
<uses-permission android:name="android.permission.READ_SMS" />
|
||||
|
||||
<uses-sdk android:minSdkVersion="19" />
|
||||
|
||||
<application
|
||||
android:allowBackup="true"
|
||||
android:icon="@mipmap/wso2logo"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/AppTheme" >
|
||||
<activity
|
||||
android:name="org.wso2.carbon.iot.android.sense.RegisterActivity"
|
||||
android:label="@string/app_name"
|
||||
android:windowSoftInputMode="adjustResize|stateVisible" >
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<service
|
||||
android:name="org.wso2.carbon.iot.android.sense.event.SenseService"
|
||||
android:enabled="true"
|
||||
android:label="@string/app_name" >
|
||||
</service>
|
||||
|
||||
<service
|
||||
android:name="org.wso2.carbon.iot.android.sense.data.publisher.DataPublisherService"
|
||||
android:enabled="true"
|
||||
android:label="@string/app_name" >
|
||||
</service>
|
||||
|
||||
<service
|
||||
android:name="org.wso2.carbon.iot.android.sense.event.streams.battery.BatteryReaderService"
|
||||
android:enabled="true"
|
||||
android:label="@string/app_name" >
|
||||
</service>
|
||||
|
||||
<service android:name="org.wso2.carbon.iot.android.sense.event.streams.activity.ActivityReceiver"/>
|
||||
|
||||
<receiver android:name="org.wso2.carbon.iot.android.sense.event.SenseScheduleReceiver" >
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
|
||||
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
<activity
|
||||
android:name="org.wso2.carbon.iot.android.sense.realtimeviewer.ActivitySelectSensor"
|
||||
android:label="My Sensors"
|
||||
android:configChanges="keyboardHidden|orientation|screenSize"
|
||||
android:theme="@style/AppTheme.NoActionBar" >
|
||||
</activity>
|
||||
<activity
|
||||
android:name="org.wso2.carbon.iot.android.sense.speech.detector.WordRecognitionActivity"
|
||||
android:label="Speech Recongnizer"
|
||||
android:theme="@style/AppTheme.NoActionBar" >
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name="org.wso2.carbon.iot.android.sense.beacon.MonitoringActivity"
|
||||
android:label="Beacon Monitor"
|
||||
android:theme="@style/AppTheme.NoActionBar" >
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name="org.wso2.carbon.iot.android.sense.bmonitor.BeaconMonitoringActivity"
|
||||
android:label="Beacon Monitor"
|
||||
android:theme="@style/AppTheme.NoActionBar" >
|
||||
</activity>
|
||||
</application>
|
||||
|
||||
</manifest>
|
@ -1,8 +0,0 @@
|
||||
/*___Generated_by_IDEA___*/
|
||||
|
||||
package agent.sense.android.iot.carbon.wso2.org.wso2_senseagent;
|
||||
|
||||
/* This stub is only used by the IDE. It is NOT the BuildConfig class actually packed into the APK */
|
||||
public final class BuildConfig {
|
||||
public final static boolean DEBUG = Boolean.parseBoolean(null);
|
||||
}
|
@ -1,7 +0,0 @@
|
||||
/*___Generated_by_IDEA___*/
|
||||
|
||||
package agent.sense.android.iot.carbon.wso2.org.wso2_senseagent;
|
||||
|
||||
/* This stub is only used by the IDE. It is NOT the Manifest class actually packed into the APK */
|
||||
public final class Manifest {
|
||||
}
|
@ -1,7 +0,0 @@
|
||||
/*___Generated_by_IDEA___*/
|
||||
|
||||
package agent.sense.android.iot.carbon.wso2.org.wso2_senseagent;
|
||||
|
||||
/* This stub is only used by the IDE. It is NOT the R class actually packed into the APK */
|
||||
public final class R {
|
||||
}
|
@ -1,207 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense;
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.animation.AnimatorListenerAdapter;
|
||||
import android.annotation.TargetApi;
|
||||
import android.app.Activity;
|
||||
import android.content.Intent;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.text.TextUtils;
|
||||
import android.view.KeyEvent;
|
||||
import android.view.View;
|
||||
import android.view.View.OnClickListener;
|
||||
import android.widget.Button;
|
||||
import android.widget.EditText;
|
||||
import android.widget.Toast;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.data.publisher.DataPublisherReceiver;
|
||||
import org.wso2.carbon.iot.android.sense.data.publisher.mqtt.AndroidSenseMQTTHandler;
|
||||
import org.wso2.carbon.iot.android.sense.data.publisher.mqtt.transport.MQTTTransportHandler;
|
||||
import org.wso2.carbon.iot.android.sense.event.SenseScheduleReceiver;
|
||||
import org.wso2.carbon.iot.android.sense.realtimeviewer.ActivitySelectSensor;
|
||||
import org.wso2.carbon.iot.android.sense.realtimeviewer.sensorlisting.AvailableSensorsInDevice;
|
||||
import org.wso2.carbon.iot.android.sense.realtimeviewer.sensorlisting.SupportedSensors;
|
||||
import org.wso2.carbon.iot.android.sense.util.LocalRegistry;
|
||||
import org.wso2.carbon.iot.android.sense.util.SenseClient;
|
||||
import org.wso2.carbon.iot.android.sense.util.SenseUtils;
|
||||
import org.wso2.carbon.iot.android.sense.util.dto.RegisterInfo;
|
||||
|
||||
import agent.sense.android.iot.carbon.wso2.org.wso2_senseagent.R;
|
||||
|
||||
/**
|
||||
* A login screen that offers to register the device.
|
||||
*/
|
||||
public class RegisterActivity extends Activity {
|
||||
|
||||
private EditText mUsernameView;
|
||||
private EditText mPasswordView;
|
||||
private EditText mHostView;
|
||||
private View mProgressView;
|
||||
private View mLoginFormView;
|
||||
private Button deviceRegisterButton;
|
||||
private Handler mUiHandler = new Handler();
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
getSharedPreferences(SupportedSensors.SELECTED_SENSORS, 0).edit().clear().apply();
|
||||
|
||||
if (LocalRegistry.isExist(getApplicationContext())) {
|
||||
Intent intent = new Intent(getApplicationContext(), ActivitySelectSensor.class);
|
||||
startActivity(intent);
|
||||
}
|
||||
setContentView(R.layout.activity_register);
|
||||
mUsernameView = (EditText) findViewById(R.id.username);
|
||||
mPasswordView = (EditText) findViewById(R.id.password);
|
||||
mHostView = (EditText) findViewById(R.id.hostname);
|
||||
AvailableSensorsInDevice availableSensorsInDevice = new AvailableSensorsInDevice(getApplicationContext());
|
||||
availableSensorsInDevice.setContent();
|
||||
|
||||
deviceRegisterButton = (Button) findViewById(R.id.device_register_button);
|
||||
|
||||
|
||||
deviceRegisterButton.setOnClickListener(new OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View view) {
|
||||
attemptLogin();
|
||||
}
|
||||
});
|
||||
|
||||
mLoginFormView = findViewById(R.id.login_form);
|
||||
mProgressView = findViewById(R.id.login_progress);
|
||||
}
|
||||
|
||||
public void attemptLogin() {
|
||||
showProgress(true);
|
||||
// Reset errors.
|
||||
mUsernameView.setError(null);
|
||||
mPasswordView.setError(null);
|
||||
|
||||
// Store values at the time of the login attempt.
|
||||
final String username = mUsernameView.getText().toString();
|
||||
final String password = mPasswordView.getText().toString();
|
||||
final String hostname = mHostView.getText().toString();
|
||||
boolean cancel = false;
|
||||
View focusView = null;
|
||||
|
||||
// Check for a valid password, if the user entered one.
|
||||
if (!TextUtils.isEmpty(password)) {
|
||||
// mPasswordView.setError(getString(R.string.error_invalid_password));
|
||||
focusView = mPasswordView;
|
||||
//cancel = true;
|
||||
}
|
||||
// Check for a valid username .
|
||||
if (TextUtils.isEmpty(username)) {
|
||||
mUsernameView.setError(getString(R.string.error_field_required));
|
||||
focusView = mUsernameView;
|
||||
cancel = true;
|
||||
}
|
||||
if (TextUtils.isEmpty(username)) {
|
||||
mHostView.setError(getString(R.string.error_field_required));
|
||||
focusView = mHostView;
|
||||
cancel = true;
|
||||
}
|
||||
|
||||
if (cancel) {
|
||||
focusView.requestFocus();
|
||||
} else {
|
||||
Thread myThread = new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
SenseClient client = new SenseClient(getApplicationContext());
|
||||
LocalRegistry.addServerURL(getBaseContext(), hostname);
|
||||
String deviceId = SenseUtils.generateDeviceId(getBaseContext(), getContentResolver());
|
||||
final RegisterInfo registerStatus = client.register(username, password, deviceId, mUiHandler);
|
||||
mUiHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Toast.makeText(getApplicationContext(), registerStatus.getMsg(), Toast.LENGTH_LONG).show();
|
||||
}
|
||||
});
|
||||
|
||||
if (registerStatus.isRegistered()) {
|
||||
LocalRegistry.setEnrolled(getApplicationContext(), true);
|
||||
LocalRegistry.addUsername(getApplicationContext(), username);
|
||||
LocalRegistry.addDeviceId(getApplicationContext(), deviceId);
|
||||
MQTTTransportHandler mqttTransportHandler = AndroidSenseMQTTHandler.getInstance(getApplicationContext());
|
||||
if (!mqttTransportHandler.isConnected()) {
|
||||
mqttTransportHandler.connect();
|
||||
}
|
||||
SenseScheduleReceiver senseScheduleReceiver = new SenseScheduleReceiver();
|
||||
senseScheduleReceiver.clearAbortBroadcast();
|
||||
senseScheduleReceiver.onReceive(getApplicationContext(), null);
|
||||
|
||||
DataPublisherReceiver dataUploaderReceiver = new DataPublisherReceiver();
|
||||
dataUploaderReceiver.clearAbortBroadcast();
|
||||
dataUploaderReceiver.onReceive(getApplicationContext(), null);
|
||||
|
||||
mUiHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Intent intent = new Intent(getApplicationContext(), ActivitySelectSensor.class);
|
||||
startActivity(intent);
|
||||
}
|
||||
});
|
||||
}
|
||||
mUiHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
showProgress(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
myThread.start();
|
||||
}
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
|
||||
public void showProgress(final boolean show) {
|
||||
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
|
||||
// for very easy animations. If available, use these APIs to fade-in
|
||||
// the progress spinner.
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
|
||||
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
|
||||
|
||||
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
|
||||
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
|
||||
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
|
||||
@Override
|
||||
public void onAnimationEnd(Animator animation) {
|
||||
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
|
||||
}
|
||||
});
|
||||
|
||||
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
|
||||
mProgressView.animate().setDuration(shortAnimTime).alpha(
|
||||
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
|
||||
@Override
|
||||
public void onAnimationEnd(Animator animation) {
|
||||
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// The ViewPropertyAnimator APIs are not available, so simply show
|
||||
// and hide the relevant UI components.
|
||||
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
|
||||
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
|
||||
deviceRegisterButton.setVisibility(show? View.VISIBLE : View.GONE);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,131 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.beacon;
|
||||
|
||||
import android.app.NotificationManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.app.Service;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Handler;
|
||||
import android.os.IBinder;
|
||||
import android.os.RemoteException;
|
||||
import android.support.v4.app.NotificationCompat;
|
||||
import android.util.Log;
|
||||
import agent.sense.android.iot.carbon.wso2.org.wso2_senseagent.R;
|
||||
|
||||
import org.altbeacon.beacon.BeaconConsumer;
|
||||
import org.altbeacon.beacon.BeaconManager;
|
||||
import org.altbeacon.beacon.MonitorNotifier;
|
||||
import org.altbeacon.beacon.Region;
|
||||
|
||||
public class BeaconDetactorService extends Service implements BeaconConsumer {
|
||||
|
||||
private BeaconManager iBeaconManager = BeaconManager.getInstanceForApplication(this);
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent arg0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
|
||||
new Thread(){
|
||||
@Override
|
||||
public void run() {
|
||||
iBeaconManager.bind(BeaconDetactorService.this);
|
||||
}
|
||||
}.start();
|
||||
|
||||
|
||||
return START_STICKY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
|
||||
|
||||
final Handler handler = new Handler();
|
||||
final Runnable runnable = new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
//stopSelf();
|
||||
}
|
||||
};
|
||||
handler.postDelayed(runnable, 10000);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
iBeaconManager.unbind(this);
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBeaconServiceConnect() {
|
||||
iBeaconManager.setMonitorNotifier(new MonitorNotifier() {
|
||||
@Override
|
||||
public void didEnterRegion(Region region) {
|
||||
Log.e("BeaconDetactorService", "didEnterRegion");
|
||||
generateNotification(BeaconDetactorService.this, region.getUniqueId()
|
||||
+ ": just saw this iBeacon for the first time");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void didExitRegion(Region region) {
|
||||
Log.e("BeaconDetactorService", "didExitRegion");
|
||||
generateNotification(BeaconDetactorService.this, region.getUniqueId() + ": is no longer visible");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void didDetermineStateForRegion(int state, Region region) {
|
||||
Log.e("BeaconDetactorService", "didDetermineStateForRegion:" + state);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
try {
|
||||
iBeaconManager.startMonitoringBeaconsInRegion(new Region("myMonitoringUniqueId", null, null, null));
|
||||
} catch (RemoteException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Issues a notification to inform the user that server has sent a message.
|
||||
*/
|
||||
private static void generateNotification(Context context, String message) {
|
||||
|
||||
Intent launchIntent = new Intent(context, MonitoringActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||||
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
|
||||
|
||||
((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).notify(
|
||||
0,
|
||||
new NotificationCompat.Builder(context).setWhen(System.currentTimeMillis())
|
||||
.setSmallIcon(R.drawable.beacon).setTicker(message)
|
||||
.setContentTitle(context.getString(R.string.app_name)).setContentText(message)
|
||||
.setContentIntent(PendingIntent.getActivity(context, 0, launchIntent, 0)).setAutoCancel(true)
|
||||
.build());
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -1,80 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.beacon;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
|
||||
public class BeaconScanedData {
|
||||
|
||||
|
||||
private int beaconMajor;// Major
|
||||
private int beaconMinor;//Minor
|
||||
private String beaconProximity;// Proximity
|
||||
private int beaconUuid;// Uuid
|
||||
private long timestamp;// Timestamp
|
||||
|
||||
BeaconScanedData(int beaconMajor, int beaconMinor,String beaconProximity,int beaconUuid) {
|
||||
this.beaconMajor = beaconMajor;
|
||||
this.beaconMinor = beaconMinor;
|
||||
this.beaconProximity = beaconProximity;
|
||||
this.beaconUuid = beaconUuid;
|
||||
timestamp = new Date().getTime();
|
||||
|
||||
}
|
||||
|
||||
public int getBeaconMajor() {
|
||||
return beaconMajor;
|
||||
}
|
||||
|
||||
public void setBeaconMajor(int beaconMajor) {
|
||||
this.beaconMajor = beaconMajor;
|
||||
}
|
||||
|
||||
public int getBeaconMinor() {
|
||||
return beaconMinor;
|
||||
}
|
||||
|
||||
public void setBeaconMinor(int beaconMinor) {
|
||||
this.beaconMinor = beaconMinor;
|
||||
}
|
||||
|
||||
public String getBeaconProximity() {
|
||||
return beaconProximity;
|
||||
}
|
||||
|
||||
public void setBeaconProximity(String beaconProximity) {
|
||||
this.beaconProximity = beaconProximity;
|
||||
}
|
||||
|
||||
public int getBeaconUuid() {
|
||||
return beaconUuid;
|
||||
}
|
||||
|
||||
public void setBeaconUuid(int beaconUuid) {
|
||||
this.beaconUuid = beaconUuid;
|
||||
}
|
||||
|
||||
public long getTimeStamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public void setTimeStamp(long timeStamp) {
|
||||
timestamp = timeStamp;
|
||||
}
|
||||
}
|
@ -1,71 +0,0 @@
|
||||
package org.wso2.carbon.iot.android.sense.beacon;
|
||||
|
||||
import java.util.Calendar;
|
||||
|
||||
import android.app.AlarmManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import org.altbeacon.beacon.BeaconConsumer;
|
||||
import org.altbeacon.beacon.BeaconManager;
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
public class BeaconServiceUtility {
|
||||
|
||||
private Context context;
|
||||
private PendingIntent pintent;
|
||||
private AlarmManager alarm;
|
||||
private Intent iService;
|
||||
|
||||
public BeaconServiceUtility(Context context) {
|
||||
super();
|
||||
this.context = context;
|
||||
iService = new Intent(context, BeaconDetactorService.class);
|
||||
alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
|
||||
pintent = PendingIntent.getService(context, 0, iService, 0);
|
||||
}
|
||||
|
||||
public void onStart(BeaconManager iBeaconManager, BeaconConsumer consumer) {
|
||||
|
||||
stopBackgroundScan();
|
||||
iBeaconManager.bind(consumer);
|
||||
|
||||
}
|
||||
|
||||
public void onStop(BeaconManager iBeaconManager, BeaconConsumer consumer) {
|
||||
|
||||
iBeaconManager.unbind(consumer);
|
||||
startBackgroundScan();
|
||||
|
||||
}
|
||||
|
||||
private void stopBackgroundScan() {
|
||||
|
||||
alarm.cancel(pintent);
|
||||
context.stopService(iService);
|
||||
}
|
||||
|
||||
private void startBackgroundScan() {
|
||||
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.add(Calendar.SECOND, 2);
|
||||
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 360000, pintent); // 6*60 * 1000
|
||||
context.startService(iService);
|
||||
}
|
||||
|
||||
}
|
@ -1,252 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.beacon;
|
||||
|
||||
|
||||
import android.Manifest;
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.Context;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.RemoteException;
|
||||
import android.app.Activity;
|
||||
import android.app.AlertDialog;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.Intent;
|
||||
import android.util.Log;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.EditText;
|
||||
import android.view.LayoutInflater;
|
||||
import android.widget.BaseAdapter;
|
||||
import org.altbeacon.beacon.BeaconConsumer;
|
||||
import org.altbeacon.beacon.BeaconManager;
|
||||
import org.altbeacon.beacon.Beacon;
|
||||
import org.altbeacon.beacon.RangeNotifier;
|
||||
import android.widget.ListView;
|
||||
import android.widget.TextView;
|
||||
import org.altbeacon.beacon.BeaconParser;
|
||||
import org.altbeacon.beacon.MonitorNotifier;
|
||||
import org.altbeacon.beacon.Region;
|
||||
import org.wso2.carbon.iot.android.sense.beacon.BeaconScanedData;
|
||||
import org.wso2.carbon.iot.android.sense.util.SenseDataHolder;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.logging.Handler;
|
||||
import agent.sense.android.iot.carbon.wso2.org.wso2_senseagent.R;
|
||||
|
||||
public class MonitoringActivity extends Activity implements BeaconConsumer {
|
||||
protected static final String TAG = MonitoringActivity.class.getName();
|
||||
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
|
||||
private ListView list = null;
|
||||
private BeaconAdapter adapter;
|
||||
private ArrayList<Beacon> arrayL = new ArrayList<>();
|
||||
private LayoutInflater inflater;
|
||||
|
||||
private BeaconServiceUtility beaconUtill = null;
|
||||
private BeaconManager iBeaconManager = BeaconManager.getInstanceForApplication(this);
|
||||
|
||||
BeaconScanedData beaconData;
|
||||
|
||||
@Override
|
||||
public void onBeaconServiceConnect() {
|
||||
|
||||
iBeaconManager.setBackgroundMode(true);
|
||||
|
||||
|
||||
iBeaconManager.setRangeNotifier(new RangeNotifier() {
|
||||
@Override
|
||||
public void didRangeBeaconsInRegion(Collection<Beacon> iBeacons, Region region) {
|
||||
for (Beacon beacon: iBeacons) {
|
||||
Log.i(TAG, "This beacon has identifiers:"+beacon.getId1()+", "+beacon.getId2()+", "+beacon.getId3());
|
||||
|
||||
|
||||
}
|
||||
|
||||
arrayL.clear();
|
||||
arrayL.addAll(iBeacons);
|
||||
//adapter.notifyDataSetChanged();
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
iBeaconManager.setMonitorNotifier(new MonitorNotifier() {
|
||||
@Override
|
||||
public void didEnterRegion(Region region) {
|
||||
Log.e("BeaconDetactorService", "didEnterRegion");
|
||||
// logStatus("I just saw an iBeacon for the first time!");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void didExitRegion(Region region) {
|
||||
Log.e("BeaconDetactorService", "didExitRegion");
|
||||
// logStatus("I no longer see an iBeacon");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void didDetermineStateForRegion(int state, Region region) {
|
||||
Log.e("BeaconDetactorService", "didDetermineStateForRegion");
|
||||
// logStatus("I have just switched from seeing/not seeing iBeacons: " + state);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
try {
|
||||
iBeaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
|
||||
} catch (RemoteException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
try {
|
||||
iBeaconManager.startMonitoringBeaconsInRegion(new Region("myMonitoringUniqueId", null, null, null));
|
||||
} catch (RemoteException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_monitor);
|
||||
beaconUtill = new BeaconServiceUtility(this);
|
||||
list = (ListView) findViewById(R.id.list);
|
||||
adapter = new BeaconAdapter();
|
||||
list.setAdapter(adapter);
|
||||
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
|
||||
|
||||
//iBeaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
|
||||
iBeaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
|
||||
|
||||
iBeaconManager.bind(this);
|
||||
|
||||
iBeaconManager.setRangeNotifier(new RangeNotifier() {
|
||||
@Override
|
||||
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
|
||||
for(Beacon beacon : beacons) {
|
||||
Log.d(TAG, "UUID:" + beacon.getId1() + ", major:" + beacon.getId2() + ", minor:" + beacon.getId3() + ", Distance:" + beacon.getDistance() + ",RSSI" + beacon.getRssi() + ", TxPower" + beacon.getTxPower());
|
||||
}
|
||||
arrayL.clear();
|
||||
arrayL.addAll(beacons);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStart() {
|
||||
super.onStart();
|
||||
beaconUtill.onStart(iBeaconManager, this);
|
||||
beaconUtill = new BeaconServiceUtility(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStop() {
|
||||
beaconUtill.onStop(iBeaconManager, this);
|
||||
super.onStop();
|
||||
}
|
||||
|
||||
|
||||
private class BeaconAdapter extends BaseAdapter {
|
||||
|
||||
@Override
|
||||
public int getCount() {
|
||||
if (arrayL != null && arrayL.size() > 0)
|
||||
return arrayL.size();
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Beacon getItem(int arg0) {
|
||||
return arrayL.get(arg0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getItemId(int arg0) {
|
||||
return arg0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public View getView(int position, View convertView, ViewGroup parent) {
|
||||
try {
|
||||
ViewHolder holder;
|
||||
|
||||
if (convertView != null) {
|
||||
holder = (ViewHolder) convertView.getTag();
|
||||
} else {
|
||||
holder = new ViewHolder(convertView = inflater.inflate(R.layout.tupple_monitoring, null));
|
||||
}
|
||||
holder.beacon_uuid.setText("UUID: " + arrayL.get(position).getId1().toString().toUpperCase());
|
||||
|
||||
holder.beacon_major.setText("Major: " + arrayL.get(position).getId2());
|
||||
|
||||
holder.beacon_minor.setText(" Minor: " + arrayL.get(position).getId3());
|
||||
|
||||
double proximity = arrayL.get(position).getDistance();
|
||||
holder.beacon_proximity.setText("Proximity: " + (new BigDecimal(proximity).setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));
|
||||
|
||||
holder.beacon_rssi.setText(" Rssi: " + arrayL.get(position).getRssi());
|
||||
|
||||
holder.beacon_txpower.setText(" TxPower: " + arrayL.get(position).getTxPower());
|
||||
|
||||
holder.beacon_range.setText("" + arrayL.get(position).getDistance());
|
||||
|
||||
beaconData = new BeaconScanedData(arrayL.get(position).getId2().toInt(), arrayL.get(position).getId3().toInt(),holder.beacon_uuid.toString(),arrayL.get(position).getRssi());
|
||||
SenseDataHolder.getBeaconScanedDataHolder().add(beaconData);
|
||||
|
||||
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return convertView;
|
||||
}
|
||||
|
||||
private class ViewHolder {
|
||||
private TextView beacon_uuid;
|
||||
private TextView beacon_major;
|
||||
private TextView beacon_minor;
|
||||
private TextView beacon_proximity;
|
||||
private TextView beacon_rssi;
|
||||
private TextView beacon_txpower;
|
||||
private TextView beacon_range;
|
||||
|
||||
|
||||
public ViewHolder(View view) {
|
||||
beacon_uuid = (TextView) view.findViewById(R.id.BEACON_uuid);
|
||||
beacon_major = (TextView) view.findViewById(R.id.BEACON_major);
|
||||
beacon_minor = (TextView) view.findViewById(R.id.BEACON_minor);
|
||||
beacon_proximity = (TextView) view.findViewById(R.id.BEACON_proximity);
|
||||
beacon_rssi = (TextView) view.findViewById(R.id.BEACON_rssi);
|
||||
beacon_txpower = (TextView) view.findViewById(R.id.BEACON_txpower);
|
||||
beacon_range = (TextView) view.findViewById(R.id.BEACON_range);
|
||||
|
||||
|
||||
view.setTag(this);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -1,121 +0,0 @@
|
||||
/*
|
||||
*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.bmonitor;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.app.Activity;
|
||||
import android.bluetooth.BluetoothAdapter;
|
||||
import android.bluetooth.BluetoothDevice;
|
||||
import android.os.AsyncTask;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.support.v7.app.AppCompatActivity;
|
||||
import android.widget.ListView;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import agent.sense.android.iot.carbon.wso2.org.wso2_senseagent.R;
|
||||
import uk.co.alt236.bluetoothlelib.device.BluetoothLeDevice;
|
||||
import uk.co.alt236.easycursor.objectcursor.EasyObjectCursor;
|
||||
|
||||
public class BeaconMonitoringActivity extends AppCompatActivity {
|
||||
|
||||
private BluetoothLeScanner mScanner;
|
||||
private BluetoothUtils mBluetoothUtils;
|
||||
private LeDeviceListAdapter mLeDeviceListAdapter;
|
||||
private BluetoothLeDeviceStore mDeviceStore;
|
||||
|
||||
protected ListView mList;
|
||||
|
||||
public static final int MINIMUM_DISTANCE = -70;
|
||||
|
||||
public static Map itemMap;
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_beacon_monitoring);
|
||||
|
||||
itemMap = new HashMap<String, String>();
|
||||
itemMap.put("DC:5F:BD:68:88:D5", "Noodles");
|
||||
itemMap.put("EF:0F:50:D5:BA:A1", "Vegetables");
|
||||
itemMap.put("FA:F2:CF:84:C2:F7", "Oil");
|
||||
|
||||
mList = (ListView) this.findViewById(android.R.id.list);
|
||||
|
||||
mDeviceStore = new BluetoothLeDeviceStore();
|
||||
mBluetoothUtils = new BluetoothUtils(this);
|
||||
mScanner = new BluetoothLeScanner(mLeScanCallback, mBluetoothUtils);
|
||||
startScan();
|
||||
}
|
||||
|
||||
private final BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
|
||||
@Override
|
||||
public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
|
||||
final BluetoothLeDevice deviceLe = new BluetoothLeDevice(device, rssi, scanRecord, System.currentTimeMillis());
|
||||
if(deviceLe!= null && deviceLe.getName()!= null && !deviceLe.getName().equals("Unknown Device")){
|
||||
mDeviceStore.addDevice(deviceLe);
|
||||
|
||||
if(deviceLe.getRssi() > MINIMUM_DISTANCE){
|
||||
Object[] objects = new Object[4];
|
||||
objects[0] = deviceLe.getName();
|
||||
objects[1] = deviceLe.getAddress();
|
||||
objects[2] = deviceLe.getRssi();
|
||||
objects[3] = itemMap.get(device.getAddress());
|
||||
|
||||
new SendToSiddi().execute(objects);
|
||||
}
|
||||
|
||||
|
||||
final EasyObjectCursor<BluetoothLeDevice> c = mDeviceStore.getDeviceCursor();
|
||||
runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
mLeDeviceListAdapter.swapCursor(c);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private void startScan() {
|
||||
|
||||
mLeDeviceListAdapter = new LeDeviceListAdapter(this, mDeviceStore.getDeviceCursor());
|
||||
mList.setAdapter(mLeDeviceListAdapter);
|
||||
|
||||
final boolean mIsBluetoothOn = mBluetoothUtils.isBluetoothOn();
|
||||
final boolean mIsBluetoothLePresent = mBluetoothUtils.isBluetoothLeSupported();
|
||||
mBluetoothUtils.askUserToEnableBluetoothIfNeeded();
|
||||
if (mIsBluetoothOn && mIsBluetoothLePresent) {
|
||||
mScanner.scanLeDevice(-1, true);
|
||||
invalidateOptionsMenu();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class SendToSiddi extends AsyncTask<Object, Object, Void>{
|
||||
|
||||
@Override
|
||||
protected Void doInBackground(Object... objects) {
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,193 +0,0 @@
|
||||
/*
|
||||
*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.bmonitor;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import uk.co.alt236.bluetoothlelib.device.BluetoothLeDevice;
|
||||
import uk.co.alt236.bluetoothlelib.device.beacon.BeaconType;
|
||||
import uk.co.alt236.bluetoothlelib.device.beacon.BeaconUtils;
|
||||
import uk.co.alt236.bluetoothlelib.device.beacon.ibeacon.IBeaconDevice;
|
||||
import uk.co.alt236.bluetoothlelib.util.ByteUtils;
|
||||
import uk.co.alt236.easycursor.objectcursor.EasyObjectCursor;
|
||||
|
||||
public class BluetoothLeDeviceStore {
|
||||
private final Map<String, BluetoothLeDevice> mDeviceMap;
|
||||
|
||||
|
||||
public BluetoothLeDeviceStore() {
|
||||
mDeviceMap = new HashMap<>();
|
||||
}
|
||||
|
||||
public void addDevice(final BluetoothLeDevice device) {
|
||||
if (mDeviceMap.containsKey(device.getAddress())) {
|
||||
mDeviceMap.get(device.getAddress()).updateRssiReading(device.getTimestamp(), device.getRssi());
|
||||
} else {
|
||||
mDeviceMap.put(device.getAddress(), device);
|
||||
}
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
mDeviceMap.clear();
|
||||
}
|
||||
|
||||
public EasyObjectCursor<BluetoothLeDevice> getDeviceCursor() {
|
||||
return new EasyObjectCursor<>(
|
||||
BluetoothLeDevice.class,
|
||||
getDeviceList(),
|
||||
"address");
|
||||
}
|
||||
|
||||
public List<BluetoothLeDevice> getDeviceList() {
|
||||
final List<BluetoothLeDevice> methodResult = new ArrayList<>(mDeviceMap.values());
|
||||
|
||||
Collections.sort(methodResult, new Comparator<BluetoothLeDevice>() {
|
||||
|
||||
@Override
|
||||
public int compare(final BluetoothLeDevice arg0, final BluetoothLeDevice arg1) {
|
||||
return arg0.getAddress().compareToIgnoreCase(arg1.getAddress());
|
||||
}
|
||||
});
|
||||
|
||||
return methodResult;
|
||||
}
|
||||
|
||||
private String getListAsCsv() {
|
||||
final List<BluetoothLeDevice> list = getDeviceList();
|
||||
final StringBuilder sb = new StringBuilder();
|
||||
sb.append(CsvWriterHelper.addStuff("mac"));
|
||||
sb.append(CsvWriterHelper.addStuff("name"));
|
||||
sb.append(CsvWriterHelper.addStuff("firstTimestamp"));
|
||||
sb.append(CsvWriterHelper.addStuff("firstRssi"));
|
||||
sb.append(CsvWriterHelper.addStuff("currentTimestamp"));
|
||||
sb.append(CsvWriterHelper.addStuff("currentRssi"));
|
||||
sb.append(CsvWriterHelper.addStuff("adRecord"));
|
||||
sb.append(CsvWriterHelper.addStuff("iBeacon"));
|
||||
sb.append(CsvWriterHelper.addStuff("uuid"));
|
||||
sb.append(CsvWriterHelper.addStuff("major"));
|
||||
sb.append(CsvWriterHelper.addStuff("minor"));
|
||||
sb.append(CsvWriterHelper.addStuff("txPower"));
|
||||
sb.append(CsvWriterHelper.addStuff("distance"));
|
||||
sb.append(CsvWriterHelper.addStuff("accuracy"));
|
||||
sb.append('\n');
|
||||
|
||||
for (final BluetoothLeDevice device : list) {
|
||||
sb.append(CsvWriterHelper.addStuff(device.getAddress()));
|
||||
sb.append(CsvWriterHelper.addStuff(device.getName()));
|
||||
sb.append(CsvWriterHelper.addStuff(TimeFormatter.getIsoDateTime(device.getFirstTimestamp())));
|
||||
sb.append(CsvWriterHelper.addStuff(device.getFirstRssi()));
|
||||
sb.append(CsvWriterHelper.addStuff(TimeFormatter.getIsoDateTime(device.getTimestamp())));
|
||||
sb.append(CsvWriterHelper.addStuff(device.getRssi()));
|
||||
sb.append(CsvWriterHelper.addStuff(ByteUtils.byteArrayToHexString(device.getScanRecord())));
|
||||
final boolean isIBeacon = BeaconUtils.getBeaconType(device) == BeaconType.IBEACON;
|
||||
final String uuid;
|
||||
final String minor;
|
||||
final String major;
|
||||
final String txPower;
|
||||
final String distance;
|
||||
final String accuracy;
|
||||
|
||||
if (isIBeacon) {
|
||||
final IBeaconDevice beacon = new IBeaconDevice(device);
|
||||
uuid = String.valueOf(beacon.getUUID());
|
||||
minor = String.valueOf(beacon.getMinor());
|
||||
major = String.valueOf(beacon.getMajor());
|
||||
txPower = String.valueOf(beacon.getCalibratedTxPower());
|
||||
distance = beacon.getDistanceDescriptor().toString().toLowerCase(Locale.US);
|
||||
accuracy = String.valueOf(beacon.getAccuracy());
|
||||
} else {
|
||||
uuid = "";
|
||||
minor = "";
|
||||
major = "";
|
||||
txPower = "";
|
||||
distance = "";
|
||||
accuracy = "";
|
||||
}
|
||||
|
||||
sb.append(CsvWriterHelper.addStuff(isIBeacon));
|
||||
sb.append(CsvWriterHelper.addStuff(uuid));
|
||||
sb.append(CsvWriterHelper.addStuff(minor));
|
||||
sb.append(CsvWriterHelper.addStuff(major));
|
||||
sb.append(CsvWriterHelper.addStuff(txPower));
|
||||
sb.append(CsvWriterHelper.addStuff(distance));
|
||||
sb.append(CsvWriterHelper.addStuff(accuracy));
|
||||
|
||||
sb.append('\n');
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public void shareDataAsEmail(final Context context) {
|
||||
final long timeInMillis = System.currentTimeMillis();
|
||||
|
||||
final String to = null;
|
||||
final String subject = "";
|
||||
|
||||
final String message = "";
|
||||
|
||||
final Intent i = new Intent(Intent.ACTION_SEND);
|
||||
i.setType("plain/text");
|
||||
try {
|
||||
final File outputDir = context.getCacheDir();
|
||||
final File outputFile = File.createTempFile("bluetooth_le_" + timeInMillis, ".csv", outputDir);
|
||||
outputFile.setReadable(true, false);
|
||||
generateFile(outputFile, getListAsCsv());
|
||||
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(outputFile));
|
||||
i.putExtra(Intent.EXTRA_EMAIL, new String[]{to});
|
||||
i.putExtra(Intent.EXTRA_SUBJECT, subject);
|
||||
i.putExtra(Intent.EXTRA_TEXT, message);
|
||||
context.startActivity(Intent.createChooser(i, "Email Subject"));
|
||||
|
||||
} catch (final IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static FileWriter generateFile(final File file, final String contents) {
|
||||
FileWriter writer = null;
|
||||
try {
|
||||
writer = new FileWriter(file);
|
||||
writer.append(contents);
|
||||
writer.flush();
|
||||
|
||||
} catch (final IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
try {
|
||||
writer.close();
|
||||
} catch (final IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return writer;
|
||||
}
|
||||
}
|
@ -1,65 +0,0 @@
|
||||
/*
|
||||
*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.bmonitor;
|
||||
|
||||
import android.bluetooth.BluetoothAdapter;
|
||||
import android.os.Handler;
|
||||
import android.util.Log;
|
||||
|
||||
public class BluetoothLeScanner {
|
||||
private final Handler mHandler;
|
||||
private final BluetoothAdapter.LeScanCallback mLeScanCallback;
|
||||
private final BluetoothUtils mBluetoothUtils;
|
||||
private boolean mScanning;
|
||||
|
||||
public BluetoothLeScanner(final BluetoothAdapter.LeScanCallback leScanCallback, final BluetoothUtils bluetoothUtils) {
|
||||
mHandler = new Handler();
|
||||
mLeScanCallback = leScanCallback;
|
||||
mBluetoothUtils = bluetoothUtils;
|
||||
}
|
||||
|
||||
public boolean isScanning() {
|
||||
return mScanning;
|
||||
}
|
||||
|
||||
public void scanLeDevice(final int duration, final boolean enable) {
|
||||
if (enable) {
|
||||
if (mScanning) {
|
||||
return;
|
||||
}
|
||||
Log.d("TAG", "~ Starting Scan");
|
||||
// Stops scanning after a pre-defined scan period.
|
||||
if (duration > 0) {
|
||||
mHandler.postDelayed(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Log.d("TAG", "~ Stopping Scan (timeout)");
|
||||
mScanning = false;
|
||||
mBluetoothUtils.getBluetoothAdapter().stopLeScan(mLeScanCallback);
|
||||
}
|
||||
}, duration);
|
||||
}
|
||||
mScanning = true;
|
||||
mBluetoothUtils.getBluetoothAdapter().startLeScan(mLeScanCallback);
|
||||
} else {
|
||||
Log.d("TAG", "~ Stopping Scan");
|
||||
mScanning = false;
|
||||
mBluetoothUtils.getBluetoothAdapter().stopLeScan(mLeScanCallback);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,60 +0,0 @@
|
||||
/*
|
||||
*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.bmonitor;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.bluetooth.BluetoothAdapter;
|
||||
import android.bluetooth.BluetoothManager;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.PackageManager;
|
||||
|
||||
public final class BluetoothUtils {
|
||||
public final static int REQUEST_ENABLE_BT = 2001;
|
||||
private final Activity mActivity;
|
||||
private final BluetoothAdapter mBluetoothAdapter;
|
||||
|
||||
public BluetoothUtils(final Activity activity) {
|
||||
mActivity = activity;
|
||||
final BluetoothManager btManager = (BluetoothManager) mActivity.getSystemService(Context.BLUETOOTH_SERVICE);
|
||||
mBluetoothAdapter = btManager.getAdapter();
|
||||
}
|
||||
|
||||
public void askUserToEnableBluetoothIfNeeded() {
|
||||
if (isBluetoothLeSupported() && (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled())) {
|
||||
final Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
|
||||
mActivity.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
|
||||
}
|
||||
}
|
||||
|
||||
public BluetoothAdapter getBluetoothAdapter() {
|
||||
return mBluetoothAdapter;
|
||||
}
|
||||
|
||||
public boolean isBluetoothLeSupported() {
|
||||
return mActivity.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
|
||||
}
|
||||
|
||||
public boolean isBluetoothOn() {
|
||||
if (mBluetoothAdapter == null) {
|
||||
return false;
|
||||
} else {
|
||||
return mBluetoothAdapter.isEnabled();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,43 +0,0 @@
|
||||
/*
|
||||
*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.bmonitor;
|
||||
|
||||
public class CsvWriterHelper {
|
||||
private static final String QUOTE = "\"";
|
||||
|
||||
public static String addStuff(final Integer text) {
|
||||
return QUOTE + text + QUOTE + ",";
|
||||
}
|
||||
|
||||
public static String addStuff(final Long text) {
|
||||
return QUOTE + text + QUOTE + ",";
|
||||
}
|
||||
|
||||
public static String addStuff(final boolean value) {
|
||||
return QUOTE + value + QUOTE + ",";
|
||||
}
|
||||
|
||||
public static String addStuff(String text) {
|
||||
if (text == null) {
|
||||
text = "<blank>";
|
||||
}
|
||||
text = text.replace(QUOTE, "'");
|
||||
|
||||
return QUOTE + text.trim() + QUOTE + ",";
|
||||
}
|
||||
}
|
@ -1,154 +0,0 @@
|
||||
/*
|
||||
*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.bmonitor;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.support.v4.widget.SimpleCursorAdapter;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.TextView;
|
||||
|
||||
import java.text.DecimalFormat;
|
||||
|
||||
import agent.sense.android.iot.carbon.wso2.org.wso2_senseagent.R;
|
||||
import uk.co.alt236.bluetoothlelib.device.BluetoothLeDevice;
|
||||
import uk.co.alt236.bluetoothlelib.device.beacon.BeaconType;
|
||||
import uk.co.alt236.bluetoothlelib.device.beacon.BeaconUtils;
|
||||
import uk.co.alt236.bluetoothlelib.device.beacon.ibeacon.IBeaconDevice;
|
||||
import uk.co.alt236.easycursor.objectcursor.EasyObjectCursor;
|
||||
|
||||
public class LeDeviceListAdapter extends SimpleCursorAdapter {
|
||||
private final LayoutInflater mInflator;
|
||||
private final Activity mActivity;
|
||||
|
||||
public static final DecimalFormat DOUBLE_TWO_DIGIT_ACCURACY = new DecimalFormat("#.##");
|
||||
public static final String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
|
||||
|
||||
public LeDeviceListAdapter(final Activity activity, final EasyObjectCursor<BluetoothLeDevice> cursor) {
|
||||
super(activity, R.layout.list_item_device, cursor, new String[0], new int[0], 0);
|
||||
mInflator = activity.getLayoutInflater();
|
||||
mActivity = activity;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public EasyObjectCursor<BluetoothLeDevice> getCursor() {
|
||||
return ((EasyObjectCursor<BluetoothLeDevice>) super.getCursor());
|
||||
}
|
||||
|
||||
@Override
|
||||
public BluetoothLeDevice getItem(final int i) {
|
||||
return getCursor().getItem(i);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getItemId(final int i) {
|
||||
return i;
|
||||
}
|
||||
|
||||
@Override
|
||||
public View getView(final int i, View view, final ViewGroup viewGroup) {
|
||||
final ViewHolder viewHolder;
|
||||
// General ListView optimization code.
|
||||
if (view == null) {
|
||||
view = mInflator.inflate(R.layout.list_item_device, null);
|
||||
viewHolder = new ViewHolder();
|
||||
viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
|
||||
viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
|
||||
viewHolder.deviceRssi = (TextView) view.findViewById(R.id.device_rssi);
|
||||
viewHolder.deviceIcon = (ImageView) view.findViewById(R.id.device_icon);
|
||||
viewHolder.deviceLastUpdated = (TextView) view.findViewById(R.id.device_last_update);
|
||||
viewHolder.ibeaconMajor = (TextView) view.findViewById(R.id.ibeacon_major);
|
||||
viewHolder.ibeaconMinor = (TextView) view.findViewById(R.id.ibeacon_minor);
|
||||
viewHolder.ibeaconDistance = (TextView) view.findViewById(R.id.ibeacon_distance);
|
||||
viewHolder.ibeaconUUID = (TextView) view.findViewById(R.id.ibeacon_uuid);
|
||||
viewHolder.ibeaconTxPower = (TextView) view.findViewById(R.id.ibeacon_tx_power);
|
||||
viewHolder.ibeaconSection = view.findViewById(R.id.ibeacon_section);
|
||||
viewHolder.ibeaconDistanceDescriptor = (TextView) view.findViewById(R.id.ibeacon_distance_descriptor);
|
||||
view.setTag(viewHolder);
|
||||
} else {
|
||||
viewHolder = (ViewHolder) view.getTag();
|
||||
}
|
||||
|
||||
final BluetoothLeDevice device = getCursor().getItem(i);
|
||||
final String deviceName = device.getName();
|
||||
|
||||
final double rssi = device.getRssi();
|
||||
|
||||
if (deviceName != null && deviceName.length() > 0) {
|
||||
viewHolder.deviceName.setText(deviceName + " (" + BeaconMonitoringActivity.itemMap.get(device.getAddress()) + ")");
|
||||
} else {
|
||||
viewHolder.deviceName.setText(R.string.unknown_device);
|
||||
}
|
||||
|
||||
|
||||
if (BeaconUtils.getBeaconType(device) == BeaconType.IBEACON) {
|
||||
final IBeaconDevice iBeacon = new IBeaconDevice(device);
|
||||
final String accuracy = DOUBLE_TWO_DIGIT_ACCURACY.format(iBeacon.getAccuracy());
|
||||
|
||||
viewHolder.deviceIcon.setImageResource(R.drawable.beacon);
|
||||
viewHolder.ibeaconSection.setVisibility(View.VISIBLE);
|
||||
viewHolder.ibeaconMajor.setText(String.valueOf(iBeacon.getMajor()));
|
||||
viewHolder.ibeaconMinor.setText(String.valueOf(iBeacon.getMinor()));
|
||||
viewHolder.ibeaconTxPower.setText(String.valueOf(iBeacon.getCalibratedTxPower()));
|
||||
viewHolder.ibeaconUUID.setText(iBeacon.getUUID());
|
||||
viewHolder.ibeaconDistance.setText(
|
||||
mActivity.getString(R.string.formatter_meters, accuracy));
|
||||
viewHolder.ibeaconDistanceDescriptor.setText(iBeacon.getDistanceDescriptor().toString());
|
||||
} else {
|
||||
if(device.getRssi() > BeaconMonitoringActivity.MINIMUM_DISTANCE){
|
||||
viewHolder.deviceIcon.setImageResource(R.drawable.beacon_red);
|
||||
}else{
|
||||
viewHolder.deviceIcon.setImageResource(R.drawable.beacon);
|
||||
}
|
||||
|
||||
viewHolder.ibeaconSection.setVisibility(View.GONE);
|
||||
}
|
||||
|
||||
|
||||
final String rssiString =
|
||||
mActivity.getString(R.string.formatter_db, String.valueOf(rssi));
|
||||
final String runningAverageRssiString =
|
||||
mActivity.getString(R.string.formatter_db, String.valueOf(device.getRunningAverageRssi()));
|
||||
|
||||
viewHolder.deviceLastUpdated.setText(
|
||||
android.text.format.DateFormat.format(
|
||||
TIME_FORMAT, new java.util.Date(device.getTimestamp())));
|
||||
viewHolder.deviceAddress.setText(device.getAddress());
|
||||
viewHolder.deviceRssi.setText(rssiString + " / " + runningAverageRssiString);
|
||||
return view;
|
||||
}
|
||||
|
||||
static class ViewHolder {
|
||||
TextView deviceName;
|
||||
TextView deviceAddress;
|
||||
TextView deviceRssi;
|
||||
TextView ibeaconUUID;
|
||||
TextView ibeaconMajor;
|
||||
TextView ibeaconMinor;
|
||||
TextView ibeaconTxPower;
|
||||
TextView ibeaconDistance;
|
||||
TextView ibeaconDistanceDescriptor;
|
||||
TextView deviceLastUpdated;
|
||||
View ibeaconSection;
|
||||
ImageView deviceIcon;
|
||||
}
|
||||
|
||||
}
|
@ -1,35 +0,0 @@
|
||||
/*
|
||||
*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.bmonitor;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
|
||||
public class TimeFormatter {
|
||||
private final static String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS zzz";
|
||||
private final static SimpleDateFormat ISO_FORMATTER = new UtcDateFormatter(ISO_FORMAT, Locale.US);
|
||||
|
||||
public static String getIsoDateTime(final Date date) {
|
||||
return ISO_FORMATTER.format(date);
|
||||
}
|
||||
|
||||
public static String getIsoDateTime(final long millis) {
|
||||
return getIsoDateTime(new Date(millis));
|
||||
}
|
||||
}
|
@ -1,74 +0,0 @@
|
||||
/**
|
||||
* ****************************************************************************
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
|
||||
* <p/>
|
||||
* GenieConnect Ltd. ("COMPANY") CONFIDENTIAL
|
||||
* Unpublished Copyright (c) 2010-2013 GenieConnect Ltd., All Rights Reserved.
|
||||
* <p/>
|
||||
* NOTICE:
|
||||
* All information contained herein is, and remains the property of COMPANY.
|
||||
* The intellectual and technical concepts contained herein are proprietary to
|
||||
* COMPANY and may be covered by U.S. and Foreign Patents, patents in process, and
|
||||
* are protected by trade secret or copyright law. Dissemination of this
|
||||
* information or reproduction of this material is strictly forbidden unless prior
|
||||
* written permission is obtained from COMPANY. Access to the source code
|
||||
* contained herein is hereby forbidden to anyone except current COMPANY employees,
|
||||
* managers or contractors who have executed Confidentiality and Non-disclosure
|
||||
* agreements explicitly covering such access.
|
||||
* <p/>
|
||||
* The copyright notice above does not evidence any actual or intended publication
|
||||
* or disclosure of this source code, which includes information that is
|
||||
* confidential and/or proprietary, and is a trade secret, of COMPANY.
|
||||
* <p/>
|
||||
* ANY REPRODUCTION, MODIFICATION, DISTRIBUTION, PUBLIC PERFORMANCE, OR PUBLIC
|
||||
* DISPLAY OF OR THROUGH USE OF THIS SOURCE CODE WITHOUT THE EXPRESS WRITTEN
|
||||
* CONSENT OF COMPANY IS STRICTLY PROHIBITED, AND IN VIOLATION OF APPLICABLE LAWS
|
||||
* AND INTERNATIONAL TREATIES. THE RECEIPT OR POSSESSION OF THIS SOURCE CODE
|
||||
* AND/OR RELATED INFORMATION DOES NOT CONVEY OR IMPLY ANY RIGHTS TO REPRODUCE,
|
||||
* DISCLOSE OR DISTRIBUTE ITS CONTENTS, OR TO MANUFACTURE, USE, OR SELL ANYTHING
|
||||
* THAT IT MAY DESCRIBE, IN WHOLE OR IN PART.
|
||||
* ****************************************************************************
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.bmonitor;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
|
||||
import java.text.DateFormatSymbols;
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
|
||||
public class UtcDateFormatter extends java.text.SimpleDateFormat {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private static final String TIME_ZONE_STRING = "UTC";
|
||||
private static final TimeZone TIME_ZONE_UTC = TimeZone.getTimeZone(TIME_ZONE_STRING);
|
||||
|
||||
@SuppressLint("SimpleDateFormat")
|
||||
public UtcDateFormatter(final String template) {
|
||||
super(template);
|
||||
super.setTimeZone(TIME_ZONE_UTC);
|
||||
}
|
||||
|
||||
@SuppressLint("SimpleDateFormat")
|
||||
public UtcDateFormatter(final String template, final DateFormatSymbols symbols) {
|
||||
super(template, symbols);
|
||||
super.setTimeZone(TIME_ZONE_UTC);
|
||||
}
|
||||
|
||||
public UtcDateFormatter(final String template, final Locale locale) {
|
||||
super(template, locale);
|
||||
super.setTimeZone(TIME_ZONE_UTC);
|
||||
}
|
||||
|
||||
/*
|
||||
* This function will throw an UnsupportedOperationException.
|
||||
* You are not be able to change the TimeZone of this object
|
||||
*
|
||||
* (non-Javadoc)
|
||||
* @see java.text.DateFormat#setTimeZone(java.util.TimeZone)
|
||||
*/
|
||||
@Override
|
||||
public void setTimeZone(final TimeZone timezone) {
|
||||
throw new UnsupportedOperationException("This SimpleDateFormat can only be in " + TIME_ZONE_STRING);
|
||||
}
|
||||
}
|
@ -1,34 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.constants;
|
||||
|
||||
/**
|
||||
* This hold constants related to android_sense.
|
||||
*/
|
||||
public class SenseConstants {
|
||||
public final static String DEVICE_TYPE = "android_sense";
|
||||
public final static String REGISTER_CONTEXT = "/android_sense";
|
||||
public final static String DCR_CONTEXT = "/dynamic-client-web";
|
||||
public final static String TOKEN_ISSUER_CONTEXT = "/oauth2";
|
||||
public final static String API_APPLICATION_REGISTRATION_CONTEXT = "/api-application-registration";
|
||||
|
||||
public static final String EVENT_LISTENER_STARTED = "xxStartedxx";
|
||||
public static final String EVENT_LISTENER_FINISHED = "xxFinishedxx";
|
||||
public static final String EVENT_LISTENER_ONGOING = "xxOngoingxx";
|
||||
|
||||
public final class Request {
|
||||
public final static String REQUEST_SUCCESSFUL = "200";
|
||||
public final static int MAX_ATTEMPTS = 2;
|
||||
}
|
||||
}
|
@ -1,37 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.data.publisher;
|
||||
|
||||
import android.app.AlarmManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.util.Log;
|
||||
|
||||
/**
|
||||
* This creates and AlarmManagerService that triggers the data uploader service with a 30 seconds interval.
|
||||
*/
|
||||
public class DataPublisherReceiver extends BroadcastReceiver {
|
||||
private static int ALARM_INTERVAL = 1000;
|
||||
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
|
||||
Log.i("Data Publisher", "triggered");
|
||||
Intent i = new Intent(context, DataPublisherService.class);
|
||||
PendingIntent pending = PendingIntent.getService(context, 0, i, 0);
|
||||
service.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), ALARM_INTERVAL, pending);
|
||||
}
|
||||
}
|
@ -1,313 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.data.publisher;
|
||||
|
||||
import android.app.Service;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.hardware.Sensor;
|
||||
import android.os.IBinder;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.util.Log;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import org.wso2.carbon.iot.android.sense.beacon.BeaconScanedData;
|
||||
import org.wso2.carbon.iot.android.sense.constants.SenseConstants;
|
||||
import org.wso2.carbon.iot.android.sense.data.publisher.mqtt.AndroidSenseMQTTHandler;
|
||||
import org.wso2.carbon.iot.android.sense.data.publisher.mqtt.transport.MQTTTransportHandler;
|
||||
import org.wso2.carbon.iot.android.sense.data.publisher.mqtt.transport.TransportHandlerException;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.activity.ActivityData;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.application.ApplicationData;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.audio.AudioData;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.battery.BatteryData;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.call.CallData;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.data.NetworkData;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.location.LocationData;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.screen.ScreenData;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.sensor.SensorData;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.sms.SmsData;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.speed.SpeedData;
|
||||
import org.wso2.carbon.iot.android.sense.speech.detector.util.ProcessWords;
|
||||
import org.wso2.carbon.iot.android.sense.speech.detector.util.WordData;
|
||||
import org.wso2.carbon.iot.android.sense.util.LocalRegistry;
|
||||
import org.wso2.carbon.iot.android.sense.util.SenseDataHolder;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* This is an android service which publishes the data to the server.
|
||||
*/
|
||||
public class DataPublisherService extends Service {
|
||||
private final String TAG = DataPublisherService.class.getName();
|
||||
private Context context;
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
context = this;
|
||||
Log.d(TAG, "service started");
|
||||
try {
|
||||
List<Event> events = new ArrayList<>();
|
||||
//retrieve sensor data.
|
||||
List<SensorData> sensorDataMap = SenseDataHolder.getSensorDataHolder();
|
||||
if (!sensorDataMap.isEmpty()) {
|
||||
for (SensorData sensorData : sensorDataMap) {
|
||||
Event event = new Event();
|
||||
event.setTimestamp(sensorData.getTimestamp());
|
||||
switch (sensorData.getSensorType()) {
|
||||
case Sensor.TYPE_ACCELEROMETER:
|
||||
event.setAccelerometer(sensorData.getSensorValues());
|
||||
events.add(event);
|
||||
break;
|
||||
case Sensor.TYPE_MAGNETIC_FIELD:
|
||||
event.setMagnetic(sensorData.getSensorValues());
|
||||
events.add(event);
|
||||
break;
|
||||
case Sensor.TYPE_GYROSCOPE:
|
||||
event.setGyroscope(sensorData.getSensorValues());
|
||||
events.add(event);
|
||||
break;
|
||||
case Sensor.TYPE_LIGHT:
|
||||
event.setLight(sensorData.getSensorValues()[0]);
|
||||
break;
|
||||
case Sensor.TYPE_PRESSURE:
|
||||
event.setPressure(sensorData.getSensorValues()[0]);
|
||||
events.add(event);
|
||||
break;
|
||||
case Sensor.TYPE_PROXIMITY:
|
||||
event.setProximity(sensorData.getSensorValues()[0]);
|
||||
events.add(event);
|
||||
break;
|
||||
case Sensor.TYPE_GRAVITY:
|
||||
event.setGravity(sensorData.getSensorValues());
|
||||
events.add(event);
|
||||
break;
|
||||
case Sensor.TYPE_GAME_ROTATION_VECTOR:
|
||||
event.setRotation(sensorData.getSensorValues());
|
||||
events.add(event);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
SenseDataHolder.resetSensorDataHolder();
|
||||
|
||||
//retrieve battery data.
|
||||
List<BatteryData> batteryDataMap = SenseDataHolder.getBatteryDataHolder();
|
||||
if (!batteryDataMap.isEmpty()) {
|
||||
for (BatteryData batteryData : batteryDataMap) {
|
||||
Event event = new Event();
|
||||
event.setTimestamp(batteryData.getTimestamp());
|
||||
event.setBattery(batteryData.getLevel());
|
||||
event.setBatteryTemperature(batteryData.getTemperature());
|
||||
event.setBatteryStatus(batteryData.getStatus());
|
||||
event.setBatteryState(batteryData.getState().toString());
|
||||
events.add(event);
|
||||
}
|
||||
}
|
||||
SenseDataHolder.resetBatteryDataHolder();
|
||||
|
||||
//retrieve location data.
|
||||
List<LocationData> locationDataMap = SenseDataHolder.getLocationDataHolder();
|
||||
|
||||
if (!locationDataMap.isEmpty()) {
|
||||
for (LocationData locationData : locationDataMap) {
|
||||
Event event = new Event();
|
||||
event.setTimestamp(locationData.getTimeStamp());
|
||||
event.setGps(new double[]{locationData.getLatitude(), locationData.getLongitude()});
|
||||
events.add(event);
|
||||
}
|
||||
}
|
||||
SenseDataHolder.resetLocationDataHolder();
|
||||
|
||||
//retrieve speed data.
|
||||
List<SpeedData> speedDataMap = SenseDataHolder.getSpeedDataHolder();
|
||||
if (!speedDataMap.isEmpty()) {
|
||||
for (SpeedData speedData : speedDataMap) {
|
||||
Event event = new Event();
|
||||
event.setTimestamp(speedData.getTimeStamp());
|
||||
event.setTurns(speedData.getTurns());
|
||||
event.setSpeed(speedData.getSpeed());
|
||||
|
||||
events.add(event);
|
||||
}
|
||||
}
|
||||
SenseDataHolder.resetSpeedDataHolder();
|
||||
|
||||
//retrieve speed data.
|
||||
List<BeaconScanedData> beaconDataMap = SenseDataHolder.getBeaconScanedDataHolder();
|
||||
if (!speedDataMap.isEmpty()) {
|
||||
for (BeaconScanedData beaconData : beaconDataMap) {
|
||||
Event event = new Event();
|
||||
event.setBeaconMajor(beaconData.getBeaconMajor());
|
||||
event.setBeaconMinor(beaconData.getBeaconMinor());
|
||||
event.setBeaconProximity(beaconData.getBeaconProximity());
|
||||
event.setBeaconUuid(beaconData.getBeaconUuid());
|
||||
|
||||
events.add(event);
|
||||
}
|
||||
}
|
||||
SenseDataHolder.resetSpeedDataHolder();
|
||||
|
||||
//retrieve words
|
||||
ProcessWords.cleanAndPushToWordMap();
|
||||
List<WordData> wordDatMap = SenseDataHolder.getWordDataHolder();
|
||||
for (WordData wordData : wordDatMap) {
|
||||
if (wordData.getOccurences() == 0) {
|
||||
continue;
|
||||
}
|
||||
for (int i = 0; i < wordData.getOccurences(); i++) {
|
||||
Event event = new Event();
|
||||
event.setTimestamp(wordData.getTimestamp());
|
||||
event.setWord(wordData.getWord());
|
||||
String word = wordData.getWord();
|
||||
String status = word;
|
||||
if ((!word.equals(SenseConstants.EVENT_LISTENER_STARTED)) && (!word.equals(SenseConstants
|
||||
.EVENT_LISTENER_FINISHED))) {
|
||||
status = SenseConstants.EVENT_LISTENER_ONGOING;
|
||||
}
|
||||
event.setWordStatus(status);
|
||||
events.add(event);
|
||||
}
|
||||
}
|
||||
SenseDataHolder.resetWordDataHolder();
|
||||
|
||||
// retrieve call data.
|
||||
List<CallData> callDataList = SenseDataHolder.getCallDataHolder();
|
||||
if (!callDataList.isEmpty()) {
|
||||
for (CallData callData : callDataList) {
|
||||
Event event = new Event();
|
||||
event.setCallNumber(callData.getPhoneNumber());
|
||||
event.setCallType(callData.getType().toString().toLowerCase());
|
||||
event.setCallStartTime(callData.getStartTime());
|
||||
event.setCallEndTime(callData.getEndTime());
|
||||
event.setTimestamp(callData.getStartTime());
|
||||
|
||||
events.add(event);
|
||||
}
|
||||
}
|
||||
SenseDataHolder.resetCallDataHolder();
|
||||
|
||||
// retrieve screen data.
|
||||
List<ScreenData> screenDataList = SenseDataHolder.getScreenDataHolder();
|
||||
if (!screenDataList.isEmpty()) {
|
||||
for (ScreenData screenData : screenDataList) {
|
||||
Event event = new Event();
|
||||
event.setScreenState(screenData.getAction());
|
||||
event.setTimestamp(screenData.getTimestamp());
|
||||
|
||||
events.add(event);
|
||||
}
|
||||
}
|
||||
SenseDataHolder.resetScreenDataHolder();
|
||||
|
||||
// retrieve audio data.
|
||||
List<AudioData> audioDataList = SenseDataHolder.getAudioDataHolder();
|
||||
if (!audioDataList.isEmpty()) {
|
||||
for (AudioData audioData : audioDataList) {
|
||||
Event event = new Event();
|
||||
event.setTimestamp(audioData.getTimestamp());
|
||||
event.setAudioPlaying(audioData.isPlaying());
|
||||
event.setHeadsetOn(audioData.isHeadsetOn());
|
||||
event.setMusicVolume(audioData.getMusicVolume());
|
||||
events.add(event);
|
||||
}
|
||||
}
|
||||
SenseDataHolder.resetAudioDataHolder();
|
||||
|
||||
// retrieve activity data.
|
||||
List<ActivityData> activityDataList = SenseDataHolder.getActivityDataHolder();
|
||||
if (!activityDataList.isEmpty()) {
|
||||
for (ActivityData activityData : activityDataList) {
|
||||
Event event = new Event();
|
||||
event.setTimestamp(activityData.getTimestamp());
|
||||
event.setActivityType(activityData.getActivity());
|
||||
event.setConfidence(activityData.getConfidence());
|
||||
events.add(event);
|
||||
}
|
||||
}
|
||||
SenseDataHolder.resetActivityDataHolder();
|
||||
|
||||
// retrieve sms data.
|
||||
List<SmsData> smsDataList = SenseDataHolder.getSmsDataHolder();
|
||||
if (!smsDataList.isEmpty()) {
|
||||
for (SmsData smsData : smsDataList) {
|
||||
Event event = new Event();
|
||||
event.setTimestamp(smsData.getTimestamp());
|
||||
event.setSmsNumber(smsData.getPhoneNumber());
|
||||
events.add(event);
|
||||
}
|
||||
}
|
||||
SenseDataHolder.resetSmsDataHolder();
|
||||
|
||||
|
||||
// retrieve application data.
|
||||
List<ApplicationData> appDataList = SenseDataHolder.getApplicationDataHolder();
|
||||
if (!appDataList.isEmpty()) {
|
||||
for (ApplicationData appData : appDataList) {
|
||||
Event event = new Event();
|
||||
event.setTimestamp(appData.getTimestamp());
|
||||
event.setPackageName(appData.getPackageName());
|
||||
event.setAction(appData.getAction().toString());
|
||||
events.add(event);
|
||||
}
|
||||
}
|
||||
SenseDataHolder.resetApplicationDataHolder();
|
||||
|
||||
//Retrieve network data
|
||||
List<NetworkData> networkDataList = SenseDataHolder.getNetworkDataHolder();
|
||||
if (!networkDataList.isEmpty()) {
|
||||
for (NetworkData networkData : networkDataList) {
|
||||
Event event = new Event();
|
||||
event.setTimestamp(networkData.getTimeStamp());
|
||||
event.setDataType(networkData.getDataType());
|
||||
event.setDataReceived(networkData.getDataReceived());
|
||||
event.setDataSent(networkData.getDataSent());
|
||||
events.add(event);
|
||||
}
|
||||
}
|
||||
SenseDataHolder.resetNetworkDataHolder();
|
||||
|
||||
//publish the data
|
||||
if (events.size() > 0 && LocalRegistry.isEnrolled(context)) {
|
||||
String user = LocalRegistry.getUsername(context);
|
||||
String deviceId = LocalRegistry.getDeviceId(context);
|
||||
JSONArray jsonArray = new JSONArray();
|
||||
for (Event event : events) {
|
||||
event.setOwner(user);
|
||||
event.setDeviceId(deviceId);
|
||||
jsonArray.put(new JSONObject().put("event", event.getEvent()));
|
||||
}
|
||||
|
||||
MQTTTransportHandler mqttTransportHandler = AndroidSenseMQTTHandler.getInstance(context);
|
||||
if (!mqttTransportHandler.isConnected()) {
|
||||
mqttTransportHandler.connect();
|
||||
}
|
||||
String topic = LocalRegistry.getTenantDomain(context) + "/" + SenseConstants.DEVICE_TYPE + "/" + deviceId + "/data";
|
||||
mqttTransportHandler.publishDeviceData(user, deviceId, jsonArray.toString(), topic);
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
Log.e(TAG, "Json Data Parsing Exception", e);
|
||||
} catch (TransportHandlerException e) {
|
||||
Log.e(TAG, "Data Publish Failed", e);
|
||||
}
|
||||
return Service.START_NOT_STICKY;
|
||||
}
|
||||
}
|
@ -1,555 +0,0 @@
|
||||
package org.wso2.carbon.iot.android.sense.data.publisher;
|
||||
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
/**
|
||||
* This hold the definition of the stream that android sense is publishing to.
|
||||
*/
|
||||
public class Event {
|
||||
|
||||
private String owner;
|
||||
private String deviceId;
|
||||
private String type;
|
||||
private int battery;
|
||||
private double gps[] = new double[]{0, 0}; //lat,long
|
||||
private float accelerometer[] = new float[]{0, 0, 0}; //x,y,z
|
||||
private float magnetic[] = new float[]{0, 0, 0};; //x,y,z
|
||||
private float gyroscope[] = new float[]{0, 0, 0};; //x,y,z
|
||||
private int batteryTemperature;
|
||||
private int batteryStatus;
|
||||
/**
|
||||
* LOW or OK
|
||||
*/
|
||||
private String batteryState;
|
||||
private float light;
|
||||
private float pressure;
|
||||
private float proximity;
|
||||
private float gravity[] = new float[]{0, 0, 0};;
|
||||
private float rotation[] = new float[]{0, 0, 0};;
|
||||
private String wordSessionId;
|
||||
private String word;
|
||||
private String wordStatus;
|
||||
private long timestamp;
|
||||
private static float speed;
|
||||
private String turn;
|
||||
public static final float SPEED_LIMIT = 60;
|
||||
private int beaconMajor;
|
||||
private int beaconMinor;
|
||||
private int beaconUuid;
|
||||
private String beaconProximity;
|
||||
private String callNumber;
|
||||
private String callType;
|
||||
private long callStartTime;
|
||||
private long callEndTime;
|
||||
|
||||
/**
|
||||
* State of the phone display.
|
||||
* Possible values are:
|
||||
* on
|
||||
* off
|
||||
* unknown
|
||||
*/
|
||||
private String screenState;
|
||||
|
||||
private boolean audioPlaying;
|
||||
private boolean headsetOn;
|
||||
private int musicVolume;
|
||||
private int activityType;
|
||||
private int confidence;
|
||||
private String smsNumber;
|
||||
private String packageName;
|
||||
private String action;
|
||||
|
||||
/**
|
||||
* Network data
|
||||
* Time stamp
|
||||
* Data type
|
||||
* Data sent
|
||||
* Data received.
|
||||
* */
|
||||
private String dataType;
|
||||
private long dataSent;
|
||||
private long dataReceived;
|
||||
|
||||
private int getBattery() {
|
||||
return battery;
|
||||
}
|
||||
|
||||
public void setBattery(int battery) {
|
||||
this.type = "battery";
|
||||
this.battery = battery;
|
||||
}
|
||||
|
||||
public int getBatteryTemperature() {
|
||||
return batteryTemperature;
|
||||
}
|
||||
|
||||
public void setBatteryTemperature(int batteryTemperature) {
|
||||
this.type = "battery"; // Type is battery
|
||||
this.batteryTemperature = batteryTemperature;
|
||||
}
|
||||
|
||||
public int getBatteryStatus() {
|
||||
return batteryStatus;
|
||||
}
|
||||
|
||||
public void setBatteryStatus(int batteryStatus) {
|
||||
this.type = "battery"; // Type is battery
|
||||
this.batteryStatus = batteryStatus;
|
||||
}
|
||||
|
||||
public String getBatteryState() {
|
||||
return batteryState != null ? batteryState : "";
|
||||
}
|
||||
|
||||
public void setBatteryState(String batteryState) {
|
||||
this.type = "battery"; // Type is battery
|
||||
this.batteryState = batteryState;
|
||||
}
|
||||
|
||||
private double[] getGps() {
|
||||
return gps;
|
||||
}
|
||||
|
||||
public void setGps(double[] gps) {
|
||||
this.type = "gps";
|
||||
this.gps = gps;
|
||||
}
|
||||
|
||||
private float[] getAccelerometer() {
|
||||
return accelerometer;
|
||||
}
|
||||
|
||||
public void setAccelerometer(float[] accelerometer) {
|
||||
this.type = "accelerometer";
|
||||
this.accelerometer = accelerometer;
|
||||
}
|
||||
|
||||
private float[] getMagnetic() {
|
||||
return magnetic;
|
||||
}
|
||||
|
||||
public void setMagnetic(float[] magnetic) {
|
||||
this.type = "magnetic";
|
||||
this.magnetic = magnetic;
|
||||
}
|
||||
|
||||
private float[] getGyroscope() {
|
||||
return gyroscope;
|
||||
}
|
||||
|
||||
public void setGyroscope(float[] gyroscope) {
|
||||
this.type = "gyroscope";
|
||||
this.gyroscope = gyroscope;
|
||||
}
|
||||
|
||||
public float getLight() {
|
||||
return light;
|
||||
}
|
||||
|
||||
public void setLight(float light) {
|
||||
this.type = "light";
|
||||
this.light = light;
|
||||
}
|
||||
|
||||
public float getPressure() {
|
||||
return pressure;
|
||||
}
|
||||
|
||||
public void setPressure(float pressure) {
|
||||
this.type = "pressure";
|
||||
this.pressure = pressure;
|
||||
}
|
||||
|
||||
public float getProximity() {
|
||||
return proximity;
|
||||
}
|
||||
|
||||
public void setProximity(float proximity) {
|
||||
this.type = "proximity";
|
||||
this.proximity = proximity;
|
||||
}
|
||||
|
||||
private float[] getGravity() {
|
||||
return gravity;
|
||||
}
|
||||
|
||||
public void setGravity(float gravity[]) {
|
||||
this.type = "gravity";
|
||||
this.gravity = gravity;
|
||||
}
|
||||
|
||||
private float[] getRotation() {
|
||||
return rotation;
|
||||
}
|
||||
|
||||
public void setRotation(float rotation[]) {
|
||||
this.type = "rotation";
|
||||
this.rotation = rotation;
|
||||
}
|
||||
|
||||
public void setSmsNumber(String smsNumber) {
|
||||
this.type = "sms";
|
||||
this.smsNumber = smsNumber;
|
||||
}
|
||||
|
||||
public String getSmsNumber() {
|
||||
return smsNumber;
|
||||
}
|
||||
|
||||
private String getWordSessionId() {
|
||||
return wordSessionId != null ? wordSessionId : "";
|
||||
}
|
||||
|
||||
public void setWordSessionId(String wordSessionId) {
|
||||
this.wordSessionId = wordSessionId;
|
||||
}
|
||||
|
||||
private String getWord() {
|
||||
return word != null ? word : "";
|
||||
}
|
||||
|
||||
public void setWord(String word) {
|
||||
this.type = "word";
|
||||
this.word = word;
|
||||
}
|
||||
|
||||
public String getPackageName() {
|
||||
return packageName;
|
||||
}
|
||||
|
||||
public void setPackageName(String packageName) {
|
||||
this.type = "application";
|
||||
this.packageName = packageName;
|
||||
}
|
||||
|
||||
public String getAction() {
|
||||
return action;
|
||||
}
|
||||
|
||||
public void setAction(String action) {
|
||||
this.type = "application";
|
||||
this.action = action;
|
||||
}
|
||||
|
||||
private long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public void setTimestamp(long timestamp) {
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
|
||||
private String getDeviceId() {
|
||||
return deviceId;
|
||||
}
|
||||
|
||||
public void setDeviceId(String deviceId) {
|
||||
this.deviceId = deviceId;
|
||||
}
|
||||
|
||||
private String getOwner() {
|
||||
return owner;
|
||||
}
|
||||
|
||||
public void setOwner(String owner) {
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
public String getWordStatus() {
|
||||
return wordStatus != null ? wordStatus : "";
|
||||
}
|
||||
|
||||
public void setWordStatus(String wordStatus) {
|
||||
this.wordStatus = wordStatus;
|
||||
}
|
||||
|
||||
public void setSpeed(float speed) {
|
||||
this.type = "speed";
|
||||
this.speed = speed;
|
||||
}
|
||||
|
||||
public float getSpeed() {
|
||||
this.type = "speed";
|
||||
if (Float.isInfinite(speed) || Float.isNaN(speed)) {
|
||||
return -1.0f;
|
||||
}
|
||||
return speed;
|
||||
}
|
||||
|
||||
public void setTurns(String turn) {
|
||||
|
||||
this.type = "turn";
|
||||
this.turn = turn;
|
||||
}
|
||||
|
||||
public String getTurns() {
|
||||
|
||||
if (turn == null || turn.isEmpty() || turn.equals("null")) {
|
||||
turn = "No Turns";
|
||||
}
|
||||
return turn;
|
||||
}
|
||||
|
||||
public void setBeaconMajor(int beaconMajor) {
|
||||
this.type = "beaconMajor";
|
||||
this.beaconMajor = beaconMajor;
|
||||
}
|
||||
|
||||
public int getBeaconMajor() {
|
||||
this.type = "beaconMajor";
|
||||
return beaconMajor;
|
||||
}
|
||||
|
||||
public void setBeaconMinor(int beaconMinor) {
|
||||
this.type = "beaconMinor";
|
||||
this.beaconMinor = beaconMinor;
|
||||
}
|
||||
|
||||
public int getBeaconMinor() {
|
||||
this.type = "beaconMinor";
|
||||
return beaconMinor;
|
||||
}
|
||||
|
||||
public void setBeaconUuid(int beaconUuid) {
|
||||
this.type = "beaconUuid";
|
||||
this.beaconUuid = beaconUuid;
|
||||
}
|
||||
|
||||
public int getBeaconUuid() {
|
||||
this.type = "beaconUuid";
|
||||
return beaconUuid;
|
||||
}
|
||||
|
||||
public void setBeaconProximity(String beaconProximity) {
|
||||
this.type = "beaconProximity";
|
||||
this.beaconProximity = beaconProximity;
|
||||
}
|
||||
|
||||
public String getBeaconProximity() {
|
||||
return beaconProximity != null ? beaconProximity : "";
|
||||
}
|
||||
|
||||
public String getCallNumber() {
|
||||
return callNumber != null ? callNumber : "";
|
||||
}
|
||||
|
||||
public void setCallNumber(String callNumber) {
|
||||
this.type = "call";
|
||||
this.callNumber = callNumber;
|
||||
}
|
||||
|
||||
public String getCallType() {
|
||||
return callType != null ? callType : "";
|
||||
}
|
||||
|
||||
public void setCallType(String callType) {
|
||||
this.type = "call";
|
||||
this.callType = callType;
|
||||
}
|
||||
|
||||
public long getCallStartTime() {
|
||||
return callStartTime;
|
||||
}
|
||||
|
||||
public void setCallStartTime(long callStartTime) {
|
||||
this.type = "call";
|
||||
this.callStartTime = callStartTime;
|
||||
}
|
||||
|
||||
public long getCallEndTime() {
|
||||
return callEndTime;
|
||||
}
|
||||
|
||||
public void setCallEndTime(long callEndTime) {
|
||||
this.type = "call";
|
||||
this.callEndTime = callEndTime;
|
||||
}
|
||||
|
||||
public String getScreenState() {
|
||||
return screenState != null ? screenState : "";
|
||||
}
|
||||
|
||||
public void setScreenState(String screenState) {
|
||||
this.type = "screen";
|
||||
this.screenState = screenState;
|
||||
}
|
||||
|
||||
public boolean isAudioPlaying() {
|
||||
return audioPlaying;
|
||||
}
|
||||
|
||||
public void setAudioPlaying(boolean audioPlaying) {
|
||||
this.type = "audio";
|
||||
this.audioPlaying = audioPlaying;
|
||||
}
|
||||
|
||||
public boolean isHeadsetOn() {
|
||||
return headsetOn;
|
||||
}
|
||||
|
||||
public void setHeadsetOn(boolean headsetOn) {
|
||||
this.type = "audio";
|
||||
this.headsetOn = headsetOn;
|
||||
}
|
||||
|
||||
public int getMusicVolume() {
|
||||
return musicVolume;
|
||||
}
|
||||
|
||||
public void setMusicVolume(int musicVolume) {
|
||||
this.type = "audio";
|
||||
this.musicVolume = musicVolume;
|
||||
}
|
||||
|
||||
public int getActivityType() {
|
||||
return activityType;
|
||||
}
|
||||
|
||||
public void setActivityType(int activityType) {
|
||||
this.type = "activity";
|
||||
this.activityType = activityType;
|
||||
}
|
||||
|
||||
public int getConfidence() {
|
||||
return confidence;
|
||||
}
|
||||
|
||||
public void setConfidence(int confidence) {
|
||||
// Do not set type here since it can be used for various types.
|
||||
// However, now it is being used by activity only
|
||||
this.confidence = confidence;
|
||||
}
|
||||
|
||||
public String getDataType() {
|
||||
this.type = "data";
|
||||
return dataType;
|
||||
}
|
||||
|
||||
public void setDataType(String dataType) {
|
||||
this.type = "data";
|
||||
this.dataType = dataType;
|
||||
}
|
||||
|
||||
public long getDataSent() {
|
||||
this.type = "data";
|
||||
return dataSent;
|
||||
}
|
||||
|
||||
public void setDataSent(long dataSent) {
|
||||
this.type = "data";
|
||||
this.dataSent = dataSent;
|
||||
}
|
||||
|
||||
public long getDataReceived() {
|
||||
this.type = "data";
|
||||
return dataReceived;
|
||||
}
|
||||
|
||||
public void setDataReceived(long dataReceived) {
|
||||
this.type = "data";
|
||||
this.dataReceived = dataReceived;
|
||||
}
|
||||
|
||||
public JSONObject getEvent() throws JSONException {
|
||||
JSONObject jsonEvent = new JSONObject();
|
||||
JSONObject jsonMetaData = new JSONObject();
|
||||
jsonMetaData.put("owner", getOwner());
|
||||
jsonMetaData.put("deviceId", getDeviceId());
|
||||
jsonMetaData.put("type", type);
|
||||
jsonMetaData.put("timestamp", getTimestamp());
|
||||
jsonEvent.put("metaData", jsonMetaData);
|
||||
|
||||
JSONObject jsonPayloadData = new JSONObject();
|
||||
// battery
|
||||
jsonPayloadData.put("battery", getBattery());
|
||||
jsonPayloadData.put("battery_state", getBatteryState());
|
||||
jsonPayloadData.put("battery_status", getBatteryStatus());
|
||||
jsonPayloadData.put("battery_temperature", getBatteryTemperature());
|
||||
|
||||
|
||||
//gps
|
||||
double gpsEvents[] = getGps();
|
||||
jsonPayloadData.put("gps_lat", gpsEvents[0]);
|
||||
jsonPayloadData.put("gps_long", gpsEvents[1]);
|
||||
//accelerometer
|
||||
float events[] = getAccelerometer();
|
||||
jsonPayloadData.put("accelerometer_x", events[0]);
|
||||
jsonPayloadData.put("accelerometer_y", events[1]);
|
||||
jsonPayloadData.put("accelerometer_z", events[2]);
|
||||
|
||||
//speed
|
||||
//if (getSpeed()>SPEED_LIMIT) {
|
||||
jsonPayloadData.put("speed_limit", getSpeed());
|
||||
//}
|
||||
|
||||
//Beacon Data
|
||||
jsonPayloadData.put("beacon_major", getBeaconMajor());
|
||||
jsonPayloadData.put("beacon_minor", getBeaconMinor());
|
||||
jsonPayloadData.put("beacon_proximity", getBeaconProximity());
|
||||
jsonPayloadData.put("beacon_uuid", getBeaconUuid());
|
||||
|
||||
//turn
|
||||
jsonPayloadData.put("turn_way", getTurns());
|
||||
//magnetic
|
||||
events = getMagnetic();
|
||||
jsonPayloadData.put("magnetic_x", events[0]);
|
||||
jsonPayloadData.put("magnetic_y", events[1]);
|
||||
jsonPayloadData.put("magnetic_z", events[2]);
|
||||
//gyroscope
|
||||
events = getGyroscope();
|
||||
jsonPayloadData.put("gyroscope_x", events[0]);
|
||||
jsonPayloadData.put("gyroscope_y", events[1]);
|
||||
jsonPayloadData.put("gyroscope_z", events[2]);
|
||||
|
||||
jsonPayloadData.put("light", getLight());
|
||||
jsonPayloadData.put("pressure", getPressure());
|
||||
jsonPayloadData.put("proximity", getProximity());
|
||||
//gravity
|
||||
events = getGravity();
|
||||
jsonPayloadData.put("gravity_x", events[0]);
|
||||
jsonPayloadData.put("gravity_y", events[1]);
|
||||
jsonPayloadData.put("gravity_z", events[2]);
|
||||
//rotation
|
||||
events = getRotation();
|
||||
jsonPayloadData.put("rotation_x", events[0]);
|
||||
jsonPayloadData.put("rotation_y", events[1]);
|
||||
jsonPayloadData.put("rotation_z", events[2]);
|
||||
//word
|
||||
jsonPayloadData.put("word", getWord());
|
||||
jsonPayloadData.put("word_sessionId", getWordSessionId());
|
||||
jsonPayloadData.put("word_status", getWordStatus());
|
||||
|
||||
// call
|
||||
jsonPayloadData.put("call_number", getCallNumber());
|
||||
jsonPayloadData.put("call_type", getCallType());
|
||||
jsonPayloadData.put("call_start_time", getCallStartTime());
|
||||
jsonPayloadData.put("call_end_time", getCallEndTime());
|
||||
|
||||
// screen
|
||||
jsonPayloadData.put("screen_state", getScreenState());
|
||||
|
||||
// headset
|
||||
jsonPayloadData.put("audio_playing", isAudioPlaying());
|
||||
jsonPayloadData.put("headset_on", isHeadsetOn());
|
||||
jsonPayloadData.put("music_volume", getMusicVolume());
|
||||
|
||||
jsonPayloadData.put("activity_type", getActivityType());
|
||||
jsonPayloadData.put("confidence", getConfidence());
|
||||
|
||||
jsonPayloadData.put("sms_number", getSmsNumber());
|
||||
|
||||
jsonPayloadData.put("application_name", getPackageName());
|
||||
jsonPayloadData.put("action", getAction());
|
||||
|
||||
//Network data
|
||||
jsonPayloadData.put("data_type", getDataType());
|
||||
jsonPayloadData.put("data_received", getDataReceived());
|
||||
jsonPayloadData.put("data_sent", getDataSent());
|
||||
|
||||
jsonEvent.put("payloadData", jsonPayloadData);
|
||||
|
||||
return jsonEvent;
|
||||
}
|
||||
}
|
@ -1,240 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.data.publisher.mqtt;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.Log;
|
||||
|
||||
import org.eclipse.paho.client.mqttv3.MqttException;
|
||||
import org.eclipse.paho.client.mqttv3.MqttMessage;
|
||||
import org.wso2.carbon.iot.android.sense.data.publisher.mqtt.transport.MQTTTransportHandler;
|
||||
import org.wso2.carbon.iot.android.sense.data.publisher.mqtt.transport.TransportHandlerException;
|
||||
import org.wso2.carbon.iot.android.sense.constants.SenseConstants;
|
||||
import org.wso2.carbon.iot.android.sense.speech.detector.util.ProcessWords;
|
||||
import org.wso2.carbon.iot.android.sense.util.LocalRegistry;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* This is an example for the use of the MQTT capabilities provided by the IoT-Server. This example depicts the use
|
||||
* of MQTT Transport for the Android Sense device-type. This class extends the abstract class
|
||||
* "MQTTTransportHandler". "MQTTTransportHandler" consists of the MQTT client specific functionality and implements
|
||||
* the "TransportHandler" interface. The actual functionality related to the "TransportHandler" interface is
|
||||
* implemented here, in this concrete class. Whilst the abstract class "MQTTTransportHandler" is intended to provide
|
||||
* the common MQTT functionality, this class (which is its extension) provides the implementation specific to the
|
||||
* MQTT communication of the Device-Type (Android Sense) in concern.
|
||||
* <p/>
|
||||
* Hence, the methods of this class are implementation of the "TransportHandler" interface which handles the device
|
||||
* specific logic to connect-to, publish-to, process-incoming-messages-from and disconnect-from the MQTT broker
|
||||
* listed in the configurations.
|
||||
*/
|
||||
public class AndroidSenseMQTTHandler extends MQTTTransportHandler {
|
||||
private static final String TAG = "AndroidSenseMQTTHandler";
|
||||
private static volatile AndroidSenseMQTTHandler mInstance;
|
||||
private Context context;
|
||||
|
||||
/**
|
||||
* return a sigleton Instance
|
||||
* @param context is the android context object.
|
||||
* @return AndroidSenseMQTTHandler.
|
||||
*/
|
||||
public static AndroidSenseMQTTHandler getInstance(Context context) {
|
||||
context = context;
|
||||
if (mInstance == null) {
|
||||
Class clazz = AndroidSenseMQTTHandler.class;
|
||||
synchronized (clazz) {
|
||||
if (mInstance == null) {
|
||||
mInstance = new AndroidSenseMQTTHandler(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
return mInstance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Default constructor for the AndroidSenseMQTTHandler.
|
||||
*/
|
||||
private AndroidSenseMQTTHandler(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* AndroidSense device-type specific implementation to connect to the MQTT broker and subscribe to a topic.
|
||||
* This method is called to initiate a MQTT communication.
|
||||
*/
|
||||
@Override
|
||||
public void connect() {
|
||||
Runnable connector = new Runnable() {
|
||||
public void run() {
|
||||
while (!isConnected()) {
|
||||
try {
|
||||
connectToQueue();
|
||||
} catch (TransportHandlerException e) {
|
||||
Log.e(TAG, "Connection to MQTT Broker at: " + mqttBrokerEndPoint + " failed", e);
|
||||
try {
|
||||
Thread.sleep(timeoutInterval);
|
||||
} catch (InterruptedException ex) {
|
||||
Thread.currentThread().interrupt();
|
||||
Log.e(TAG, "MQTT-Connector: Thread Sleep Interrupt Exception.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
subscribeToQueue();
|
||||
} catch (TransportHandlerException e) {
|
||||
Log.w(TAG, "Subscription to MQTT Broker at: " + mqttBrokerEndPoint + " failed", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Thread connectorThread = new Thread(connector);
|
||||
connectorThread.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* AndroidSense device-type specific implementation to process incoming messages. This is the specific
|
||||
* method signature of the overloaded "processIncomingMessage" method that gets called from the messageArrived()
|
||||
* callback of the "MQTTTransportHandler".
|
||||
*/
|
||||
@Override
|
||||
public void processIncomingMessage(MqttMessage mqttMessage, String... messageParams) {
|
||||
if (messageParams.length != 0) {
|
||||
// owner and the deviceId are extracted from the MQTT topic to which the message was received.
|
||||
// <Topic> = [ServerName/Owner/DeviceType/DeviceId/#]
|
||||
String topic = messageParams[0];
|
||||
String[] topicParams = topic.split("/");
|
||||
String owner = topicParams[1];
|
||||
String deviceId = topicParams[3];
|
||||
|
||||
Log.d(TAG, "Received MQTT message for: [OWNER-" + owner + "] & [DEVICE.ID-" + deviceId + "]");
|
||||
|
||||
String msg;
|
||||
msg = mqttMessage.toString();
|
||||
Log.d(TAG, "MQTT: Received Message [" + msg + "] topic: [" + topic + "]");
|
||||
if (topic.contains("threshold")) {
|
||||
try {
|
||||
ProcessWords.setThreshold(Integer.parseInt(msg));
|
||||
} catch (NumberFormatException e) {
|
||||
Log.e(TAG, "Invalid threshold value " + msg);
|
||||
}
|
||||
} else if (topic.contains("words")) {
|
||||
String words[] = msg.split(" ");
|
||||
ProcessWords.addWords(Arrays.asList(words));
|
||||
} else if (topic.contains("remove")) {
|
||||
String words[] = msg.split(" ");
|
||||
for (String word: words) {
|
||||
ProcessWords.removeWord(word);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
String errorMsg =
|
||||
"MQTT message [" + mqttMessage.toString() + "] was received without the topic information.";
|
||||
Log.w(TAG, errorMsg);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* AndroidSense device-type specific implementation to publish data to the device. This method calls the
|
||||
* {@link #publishToQueue(String, MqttMessage)} method of the "MQTTTransportHandler" class.
|
||||
*/
|
||||
@Override
|
||||
public void publishDeviceData(String... publishData) throws TransportHandlerException {
|
||||
if (publishData.length != 4) {
|
||||
String errorMsg = "Incorrect number of arguments received to SEND-MQTT Message. " +
|
||||
"Need to be [owner, deviceId, content]";
|
||||
Log.e(TAG, errorMsg);
|
||||
throw new TransportHandlerException(errorMsg);
|
||||
}
|
||||
|
||||
String deviceOwner = publishData[0];
|
||||
String deviceId = publishData[1];
|
||||
String resource = publishData[2];
|
||||
|
||||
MqttMessage pushMessage = new MqttMessage();
|
||||
String publishTopic = publishData[3];
|
||||
String actualMessage = resource;
|
||||
pushMessage.setPayload(actualMessage.getBytes(StandardCharsets.UTF_8));
|
||||
pushMessage.setQos(DEFAULT_MQTT_QUALITY_OF_SERVICE);
|
||||
pushMessage.setRetained(false);
|
||||
publishToQueue(publishTopic, pushMessage);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* Android Sense device-type specific implementation to disconnect from the MQTT broker.
|
||||
*/
|
||||
@Override
|
||||
public void disconnect() {
|
||||
Runnable stopConnection = new Runnable() {
|
||||
public void run() {
|
||||
while (isConnected()) {
|
||||
try {
|
||||
closeConnection();
|
||||
} catch (MqttException e) {
|
||||
Log.w(TAG, "Unable to 'STOP' MQTT connection at broker at: " + mqttBrokerEndPoint
|
||||
+ " for device-type - " + SenseConstants.DEVICE_TYPE, e);
|
||||
|
||||
try {
|
||||
Thread.sleep(timeoutInterval);
|
||||
} catch (InterruptedException e1) {
|
||||
Thread.currentThread().interrupt();
|
||||
Log.e(TAG, "MQTT-Terminator: Thread Sleep Interrupt Exception at device-type - " +
|
||||
SenseConstants.DEVICE_TYPE, e1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Thread terminatorThread = new Thread(stopConnection);
|
||||
terminatorThread.start();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void publishDeviceData() {
|
||||
// nothing to do
|
||||
}
|
||||
|
||||
@Override
|
||||
public void publishDeviceData(MqttMessage publishData) throws TransportHandlerException {
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void processIncomingMessage() {
|
||||
// nothing to do
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processIncomingMessage(MqttMessage message) throws TransportHandlerException {
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -1,384 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.data.publisher.mqtt.transport;
|
||||
import android.content.Context;
|
||||
import android.util.Log;
|
||||
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
|
||||
import org.eclipse.paho.client.mqttv3.MqttCallback;
|
||||
import org.eclipse.paho.client.mqttv3.MqttClient;
|
||||
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
|
||||
import org.eclipse.paho.client.mqttv3.MqttException;
|
||||
import org.eclipse.paho.client.mqttv3.MqttMessage;
|
||||
import org.wso2.carbon.iot.android.sense.constants.SenseConstants;
|
||||
import org.wso2.carbon.iot.android.sense.util.LocalRegistry;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* This is an abstract class that implements the "TransportHandler" interface. The interface is an abstraction for
|
||||
* the core functionality with regards to device-server communication regardless of the Transport protocol. This
|
||||
* specific class contains the MQTT-Transport specific implementations. The class implements utility methods for the
|
||||
* case of a MQTT communication. However, this "abstract class", even-though it implements the "TransportHandler"
|
||||
* interface, does not contain the logic relevant to the interface methods. The specific functionality of the
|
||||
* interface methods are intended to be implemented by the concrete class that extends this abstract class and
|
||||
* utilizes the MQTT specific functionality (ideally a device API writer who would like to communicate to the device
|
||||
* via MQTT Protocol).
|
||||
* <p/>
|
||||
* This class contains the Device-Management specific implementation for all the MQTT functionality. This includes
|
||||
* connecting to a MQTT Broker & subscribing to the appropriate MQTT-topic, action plan upon losing connection or
|
||||
* successfully delivering a message to the broker and upon receiving a MQTT message. Makes use of the 'Paho-MQTT'
|
||||
* library provided by Eclipse Org.
|
||||
*/
|
||||
public abstract class MQTTTransportHandler implements MqttCallback, TransportHandler<MqttMessage> {
|
||||
private static final String TAG = "MQTTTransportHandler";
|
||||
|
||||
private MqttClient client;
|
||||
private String clientId;
|
||||
private MqttConnectOptions options; // options to be set to the client-connection.
|
||||
// topic to which a will-message is automatically published by the broker upon the device losing its connection.
|
||||
private String clientWillTopic;
|
||||
|
||||
protected String mqttBrokerEndPoint;
|
||||
protected int timeoutInterval; // interval to use for reconnection attempts etc.
|
||||
protected String subscribeTopic;
|
||||
|
||||
// Quality of Service Levels for MQTT Subscription and Publishing.
|
||||
public static final int QoS_0 = 0; // At-Most Once
|
||||
@SuppressWarnings("unused")
|
||||
public static final int QoS_1 = 1; // At-Least Once
|
||||
public static final int QoS_2 = 2; // Exactly Once
|
||||
|
||||
public static final int DEFAULT_MQTT_QUALITY_OF_SERVICE = QoS_0;
|
||||
// Prefix to the Will-Topic to which a message is published if client loses its connection.
|
||||
private static final String DISCONNECTION_WILL_TOPIC_PREFIX = "Disconnection/";
|
||||
// Will-Message of the client to be published if connection is lost.
|
||||
private static final String DISCONNECTION_WILL_MSG = "Lost-Connection";
|
||||
/**
|
||||
* Constructor for the MQTTTransportHandler which takes in the owner, type of the device and the MQTT Broker URL
|
||||
* and the topic to subscribe.
|
||||
* @param context activity context.
|
||||
*/
|
||||
protected MQTTTransportHandler(Context context) {
|
||||
String username = LocalRegistry.getUsername(context);
|
||||
String deviceId = LocalRegistry.getDeviceId(context);
|
||||
this.clientId = deviceId + ":" + SenseConstants.DEVICE_TYPE;
|
||||
this.subscribeTopic = LocalRegistry.getTenantDomain(context)+ "/" + SenseConstants.DEVICE_TYPE + "/" +
|
||||
deviceId + "/command/#";
|
||||
this.clientWillTopic = DISCONNECTION_WILL_TOPIC_PREFIX + SenseConstants.DEVICE_TYPE;
|
||||
this.mqttBrokerEndPoint = LocalRegistry.getMqttEndpoint(context);
|
||||
this.timeoutInterval = DEFAULT_TIMEOUT_INTERVAL;
|
||||
this.initMQTTClient();
|
||||
setUsernameAndPassword(LocalRegistry.getAccessToken(context), "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor for the MQTTTransportHandler which takes in the owner, type of the device and the MQTT Broker URL
|
||||
* and the topic to subscribe. Additionally this constructor takes in the reconnection-time interval between
|
||||
* successive attempts to connect to the broker.
|
||||
*
|
||||
* @param deviceOwner the owner of the device.
|
||||
* @param deviceType the CDMF Device-Type of the device.
|
||||
* @param mqttBrokerEndPoint the IP/URL of the MQTT broker endpoint.
|
||||
* @param subscribeTopic the MQTT topic to which the client is to be subscribed
|
||||
* @param intervalInMillis the time interval in MILLI-SECONDS between attempts to connect to the broker.
|
||||
*/
|
||||
protected MQTTTransportHandler(String deviceOwner, String deviceType,
|
||||
String mqttBrokerEndPoint, String subscribeTopic, int intervalInMillis) {
|
||||
this.clientId = deviceOwner + ":" + deviceType;
|
||||
this.subscribeTopic = subscribeTopic;
|
||||
this.clientWillTopic = DISCONNECTION_WILL_TOPIC_PREFIX + deviceType;
|
||||
this.mqttBrokerEndPoint = mqttBrokerEndPoint;
|
||||
this.timeoutInterval = intervalInMillis;
|
||||
this.initMQTTClient();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Initializes the MQTT-Client. Creates a client using the given MQTT-broker endpoint and the clientId (which is
|
||||
* constructed by a concatenation of [deviceOwner]:[deviceType]). Also sets the client's options parameter with
|
||||
* the clientWillTopic (in-case of connection failure) and other info. Also sets the callback to this current class.
|
||||
*/
|
||||
private void initMQTTClient() {
|
||||
try {
|
||||
client = new MqttClient(this.mqttBrokerEndPoint, clientId, null);
|
||||
Log.i(TAG, "MQTT client was created with ClientID : " + clientId);
|
||||
} catch (MqttException ex) {
|
||||
String errorMsg = "Initializing the MQTT Client failed.";
|
||||
Log.e(TAG, errorMsg, ex);
|
||||
}
|
||||
|
||||
options = new MqttConnectOptions();
|
||||
options.setKeepAliveInterval(120); // set the keep alive interval to 120 seconds by default.
|
||||
options.setCleanSession(true); // sets clean session to true by default.
|
||||
setDisconnectionWillForClient(QoS_2, true); // sets default will-topic & msg with QoS 2 and retained true.
|
||||
client.setCallback(this); // callback for MQTT events are set to `this` object.
|
||||
}
|
||||
|
||||
/**
|
||||
* @param qos the Quality of Service at which the last-will-message is to be published.
|
||||
* @param isRetained indicate whether to retain the last-will-message.
|
||||
* @see MQTTTransportHandler#setDisconnectionWillForClient(String, String, int, boolean). Uses the default values
|
||||
* for Will-Topic and Will-Message.
|
||||
*/
|
||||
protected void setDisconnectionWillForClient(int qos, boolean isRetained) {
|
||||
this.setDisconnectionWillForClient(clientWillTopic, DISCONNECTION_WILL_MSG, qos, isRetained);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the [Will] option in the default options-set of the MQTT Client. A will-topic, will-message is parsed
|
||||
* along with the QoS and the retained flag. When the client loses its connection to the broker, the broker
|
||||
* publishes the will-message to the will-topic, to itself.
|
||||
*
|
||||
* @param willTopic the topic to which the last will message is to be published when client exists ungracefully.
|
||||
* @param willMsg the message to be published upon client's ungraceful exit from the broker.
|
||||
* @param qos the Quality of Service at which the last-will-message is to be published.
|
||||
* @param isRetained indicate whether to retain the last-will-message.
|
||||
*/
|
||||
protected void setDisconnectionWillForClient(String willTopic, String willMsg, int qos, boolean isRetained) {
|
||||
this.options.setWill(willTopic, willMsg.getBytes(StandardCharsets.UTF_8), qos, isRetained);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the [Clean-Session] option in the default options-set of the MQTT Client. It is set to `true` by default.
|
||||
*
|
||||
* @param setCleanSession `true` indicates that the session details can be cleared/cleaned upon disconnection,
|
||||
* `false` indicates that the session details are to be persisted if the client disconnects.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
protected void setClientCleanSession(boolean setCleanSession) {
|
||||
this.options.setCleanSession(setCleanSession);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the [Username] & [Password] options in the default options-set of the MQTT Client. By default these
|
||||
* values are not set.
|
||||
*
|
||||
* @param username the username to be used by the client to connect to the broker.
|
||||
* @param password the password to be used by the client to connect to the broker.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
protected void setUsernameAndPassword(String username, String password) {
|
||||
this.options.setUserName(username);
|
||||
this.options.setPassword(password.toCharArray());
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects to the MQTT-Broker at the endpoint specified in the constructor to this class using default the
|
||||
* MQTT-options.
|
||||
*
|
||||
* @throws TransportHandlerException in the event of 'Connecting to' the MQTT broker fails.
|
||||
*/
|
||||
protected void connectToQueue() throws TransportHandlerException {
|
||||
this.connectToQueue(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects to the MQTT-Broker at the endpoint specified in the constructor to this class using the MQTT-Options
|
||||
* passed.
|
||||
*
|
||||
* @param options options to be used by the client for this connection. (username, password, clean-session, etc)
|
||||
* @throws TransportHandlerException in the event of 'Connecting to' the MQTT broker fails.
|
||||
*/
|
||||
protected void connectToQueue(MqttConnectOptions options) throws TransportHandlerException {
|
||||
try {
|
||||
client.connect(options);
|
||||
Log.d(TAG, "MQTT Client connected to queue at: " + this.mqttBrokerEndPoint);
|
||||
} catch (MqttException ex) {
|
||||
String errorMsg = "MQTT Exception occured whilst connecting to queue at [" + this.mqttBrokerEndPoint + "]";
|
||||
Log.e(TAG, errorMsg);
|
||||
throw new TransportHandlerException(errorMsg, ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws TransportHandlerException in the event of 'Subscribing to' the MQTT broker fails.
|
||||
* @see MQTTTransportHandler#subscribeToQueue(int). Uses default QoS of 1.
|
||||
*/
|
||||
protected void subscribeToQueue() throws TransportHandlerException {
|
||||
this.subscribeToQueue(QoS_0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribes to the MQTT-Topic specified in the constructor to this class.
|
||||
*
|
||||
* @throws TransportHandlerException in the event of 'Subscribing to' the MQTT broker fails.
|
||||
*/
|
||||
protected void subscribeToQueue(int qos) throws TransportHandlerException {
|
||||
try {
|
||||
client.subscribe(subscribeTopic, qos);
|
||||
Log.d(TAG, "Client [" + clientId + "] subscribed to topic: " + subscribeTopic);
|
||||
} catch (MqttException ex) {
|
||||
String errorMsg = "MQTT Exception occurred whilst client [" + clientId + "] tried to subscribe to " +
|
||||
"topic: [" + subscribeTopic + "]";
|
||||
Log.e(TAG, errorMsg);
|
||||
throw new TransportHandlerException(errorMsg, ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param topic the topic to which the message is to be published.
|
||||
* @param payLoad the message (payload) of the MQTT publish action.
|
||||
* @see MQTTTransportHandler#publishToQueue(String, String, int, boolean)
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
protected void publishToQueue(String topic, String payLoad) throws TransportHandlerException {
|
||||
publishToQueue(topic, payLoad, DEFAULT_MQTT_QUALITY_OF_SERVICE, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param topic the topic to which the message is to be published.
|
||||
* @param message the message (payload) of the MQTT publish action as a `MQTTMessage`.
|
||||
* @throws TransportHandlerException if any error occurs whilst trying to publish to the MQTT Queue.
|
||||
* @see MQTTTransportHandler#publishToQueue(String, String, int, boolean)
|
||||
*/
|
||||
protected void publishToQueue(String topic, MqttMessage message) throws TransportHandlerException {
|
||||
try {
|
||||
client.publish(topic, message);
|
||||
Log.d(TAG, "Message: " + message.toString() + " to MQTT topic [" + topic + "] published successfully");
|
||||
} catch (MqttException ex) {
|
||||
String errorMsg = "MQTT Client Error whilst client [" + clientId + "] tried to publish to queue at " +
|
||||
"[" + mqttBrokerEndPoint + "] under topic [" + topic + "]";
|
||||
Log.e(TAG, errorMsg);
|
||||
throw new TransportHandlerException(errorMsg, ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is used to publish messages to the MQTT-Endpoint to which this client is connected to. It is via
|
||||
* publishing to this broker that the messages are communicated to the device. This is an overloaded method with
|
||||
* different parameter combinations. This method invokes the publish method provided by the MQTT-Client library.
|
||||
*
|
||||
* @param topic the topic to which the message is to be published.
|
||||
* @param payLoad the message (payload) of the MQTT publish action.
|
||||
* @param qos the Quality-of-Service of the current publish action.
|
||||
* Could be 0(At-most once), 1(At-least once) or 2(Exactly once)
|
||||
* @param retained indicate whether to retain the publish-message in the event of no subscribers.
|
||||
* @throws TransportHandlerException if any error occurs whilst trying to publish to the MQTT Queue.
|
||||
*/
|
||||
protected void publishToQueue(String topic, String payLoad, int qos, boolean retained)
|
||||
throws TransportHandlerException {
|
||||
try {
|
||||
client.publish(topic, payLoad.getBytes(StandardCharsets.UTF_8), qos, retained);
|
||||
Log.d(TAG, "Message: " + payLoad + " to MQTT topic [" + topic + "] published successfully");
|
||||
|
||||
} catch (MqttException ex) {
|
||||
String errorMsg = "MQTT Client Error whilst client [" + clientId + "] tried to publish to queue at " +
|
||||
"[" + mqttBrokerEndPoint + "] under topic [" + topic + "]";
|
||||
Log.e(TAG, errorMsg);
|
||||
throw new TransportHandlerException(errorMsg, ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the connection to the MQTT-Broker exists.
|
||||
*
|
||||
* @return `true` if the client is connected to the MQTT-Broker, else `false`.
|
||||
*/
|
||||
@Override
|
||||
public boolean isConnected() {
|
||||
return client.isConnected();
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback method which is triggered once the MQTT client losers its connection to the broker. Spawns a new
|
||||
* thread that executes necessary actions to try and reconnect to the endpoint.
|
||||
*
|
||||
* @param throwable a Throwable Object containing the details as to why the failure occurred.
|
||||
*/
|
||||
@Override
|
||||
public void connectionLost(Throwable throwable) {
|
||||
Log.w(TAG, "Connection for client: " + this.clientId + " to " + this.mqttBrokerEndPoint + " was lost." +
|
||||
"\nThis was due to - " + throwable.getMessage());
|
||||
Thread reconnectThread = new Thread() {
|
||||
public void run() {
|
||||
connect();
|
||||
}
|
||||
};
|
||||
reconnectThread.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback method which is triggered upon receiving a MQTT Message from the broker. Spawns a new thread that
|
||||
* executes any actions to be taken with the received message.
|
||||
*
|
||||
* @param topic the MQTT-Topic to which the received message was published to and the client subscribed to.
|
||||
* @param mqttMessage the actual MQTT-Message that was received from the broker.
|
||||
*/
|
||||
@Override
|
||||
public void messageArrived(final String topic, final MqttMessage mqttMessage) {
|
||||
Log.d(TAG, "Got an MQTT message '" + mqttMessage.toString() + "' for topic '" + topic + "'.");
|
||||
|
||||
Thread messageProcessorThread = new Thread() {
|
||||
public void run() {
|
||||
try {
|
||||
processIncomingMessage(mqttMessage, topic);
|
||||
} catch (TransportHandlerException e) {
|
||||
Log.e(TAG, "An error occurred when trying to process received MQTT message [" + mqttMessage + "] " +
|
||||
"for topic [" + topic + "].", e);
|
||||
}
|
||||
}
|
||||
};
|
||||
messageProcessorThread.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback method which gets triggered upon successful completion of a message delivery to the broker.
|
||||
*
|
||||
* @param iMqttDeliveryToken the MQTT-DeliveryToken which includes the details about the specific message delivery.
|
||||
*/
|
||||
@Override
|
||||
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
|
||||
String topic = iMqttDeliveryToken.getTopics()[0];
|
||||
String client = iMqttDeliveryToken.getClient().getClientId();
|
||||
|
||||
try {
|
||||
if (iMqttDeliveryToken.isComplete()) {
|
||||
if (iMqttDeliveryToken.getMessage() != null) {
|
||||
String message = iMqttDeliveryToken.getMessage().toString();
|
||||
Log.d(TAG, "Message to client [" + client + "] under topic (" + topic +
|
||||
") was delivered successfully with the delivery message: '" + message + "'");
|
||||
} else {
|
||||
Log.d(TAG, "Message to client [" + client + "] under topic (" + topic +
|
||||
") was delivered successfully.");
|
||||
}
|
||||
} else {
|
||||
Log.w(TAG, "FAILED: Delivery of MQTT message to [" + client + "] under topic [" + topic + "] failed.");
|
||||
}
|
||||
} catch (MqttException e) {
|
||||
Log.w(TAG, "Error occurred whilst trying to read the message from the MQTT delivery token.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the connection to the MQTT Broker.
|
||||
*/
|
||||
public void closeConnection() throws MqttException {
|
||||
if (client != null && isConnected()) {
|
||||
client.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the default options set for the MQTT Client
|
||||
*
|
||||
* @return the options that are currently set for the client.
|
||||
*/
|
||||
public MqttConnectOptions getOptions() {
|
||||
return options;
|
||||
}
|
||||
}
|
@ -1,108 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.data.publisher.mqtt.transport;
|
||||
|
||||
/**
|
||||
* This interface consists of the core functionality related to the transport between any device and the server. The
|
||||
* interface is an abstraction, regardless of the underlying protocol used for the transport. Implementation of this
|
||||
* interface by any class that caters a specific protocol (ex: HTTP, XMPP, MQTT, CoAP) would ideally have methods
|
||||
* specific to the protocol used for communication and other methods that implement the logic related to the devices
|
||||
* using the protocol. The methods of the interface are identified as generic ones for implementing transport
|
||||
* protocols for device communication. The implementation can utilize the appropriate method signatures applicable for
|
||||
* intended protocol.
|
||||
*
|
||||
* @param <T> an object of the message type specific to the protocol implemented. To be set to 'String' if there
|
||||
* isn't anything specific.
|
||||
*/
|
||||
public interface TransportHandler<T> {
|
||||
// a default timeout interval to be used for the protocol specific connections
|
||||
int DEFAULT_TIMEOUT_INTERVAL = 5000; // millis ~ 5 sec
|
||||
|
||||
/**
|
||||
* Implements the underlying connect mechanism specific to the protocol enabled by the interface. An object of a
|
||||
* class that implements this interface would call this method before any communication is started via the
|
||||
* intended protocol.
|
||||
*/
|
||||
void connect();
|
||||
|
||||
/**
|
||||
* Used to check whether a connection (via the implemented protocol) to the external-endpoint exists. Ideally
|
||||
* used to verify that the connection persists and to spawn a reconnection attempt if not.
|
||||
*
|
||||
* @return 'true' if connection is already made & exists, else 'false'.
|
||||
*/
|
||||
boolean isConnected();
|
||||
|
||||
/**
|
||||
* @throws TransportHandlerException in the event of any exceptions that occur whilst processing the message.
|
||||
* @see TransportHandler#processIncomingMessage(Object, String...)
|
||||
*/
|
||||
void processIncomingMessage() throws TransportHandlerException;
|
||||
|
||||
/**
|
||||
* @param message the message (of the type specific to the protocol) received from the device.
|
||||
* @throws TransportHandlerException
|
||||
* @see TransportHandler#processIncomingMessage(Object, String...)
|
||||
*/
|
||||
void processIncomingMessage(T message) throws TransportHandlerException;
|
||||
|
||||
/**
|
||||
* This is an overloaded method with three different method-signatures. This method is used to process any
|
||||
* incoming messages via the implemented protocol. It would ideally be invoked at a point where a message
|
||||
* received event is activated (Ex: `MessageArrived` callback in Eclipse-Paho-MQTT Client & `PacketListener`(s)
|
||||
* in XMPP).
|
||||
* <p/>
|
||||
*
|
||||
* @param message the message (of the type specific to the protocol) received from the device.
|
||||
* @param messageParams one or more other parameters received as part-of & relevant-to the message (Ex: MQTT Topic).
|
||||
* @throws TransportHandlerException in the event of any exceptions that occur whilst processing the message.
|
||||
*/
|
||||
void processIncomingMessage(T message, String... messageParams) throws TransportHandlerException;
|
||||
|
||||
/**
|
||||
* @throws TransportHandlerException in the event of any exceptions that occur whilst sending the message.
|
||||
* @see TransportHandler#publishDeviceData(String...)
|
||||
*/
|
||||
void publishDeviceData() throws TransportHandlerException;
|
||||
|
||||
/**
|
||||
* @param publishData the message (of the type specific to the protocol) to be sent to the device.
|
||||
* @throws TransportHandlerException in the event of any exceptions that occur whilst sending the message.
|
||||
* @see TransportHandler#publishDeviceData(String...)
|
||||
*/
|
||||
void publishDeviceData(T publishData) throws TransportHandlerException;
|
||||
|
||||
/**
|
||||
* This is an overloaded method with three different method-signatures. This method is used to publish messages
|
||||
* to an external-endpoint/device via the implemented protocol. It could in itself call the (communicating)
|
||||
* external-endpoint or invoke any method provided by the protocol specific library.
|
||||
* <p/>
|
||||
*
|
||||
* @param publishData one or more parameters specific to the message and the data to be sent.
|
||||
* @throws TransportHandlerException in the event of any exceptions that occur whilst sending the message.
|
||||
*/
|
||||
void publishDeviceData(String... publishData) throws TransportHandlerException;
|
||||
|
||||
/**
|
||||
* Implements the underlying disconnect mechanism specific to the protocol enabled by the interface. An object of a
|
||||
* class that implements this interface would call this method upon completion of all communication. In the case of
|
||||
* the IoT-Server invoking this would only be required if the server shuts-down.
|
||||
*/
|
||||
void disconnect();
|
||||
}
|
@ -1,59 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.data.publisher.mqtt.transport;
|
||||
|
||||
/**
|
||||
* This exception will be thrown when the mqtt transport fails.
|
||||
*/
|
||||
public class TransportHandlerException extends Exception {
|
||||
private static final long serialVersionUID = 2736466230451105440L;
|
||||
|
||||
private String errorMessage;
|
||||
|
||||
public String getErrorMessage() {
|
||||
return errorMessage;
|
||||
}
|
||||
|
||||
public void setErrorMessage(String errorMessage) {
|
||||
this.errorMessage = errorMessage;
|
||||
}
|
||||
|
||||
public TransportHandlerException(String msg, Exception nestedEx) {
|
||||
super(msg, nestedEx);
|
||||
setErrorMessage(msg);
|
||||
}
|
||||
|
||||
public TransportHandlerException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
setErrorMessage(message);
|
||||
}
|
||||
|
||||
public TransportHandlerException(String msg) {
|
||||
super(msg);
|
||||
setErrorMessage(msg);
|
||||
}
|
||||
|
||||
public TransportHandlerException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public TransportHandlerException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
}
|
@ -1,41 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.event;
|
||||
|
||||
import android.app.AlarmManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
|
||||
import java.util.Calendar;
|
||||
|
||||
/**
|
||||
* This is a service which triggers to collect
|
||||
*/
|
||||
public class SenseScheduleReceiver extends BroadcastReceiver {
|
||||
private static final int ALARM_INTERVAL = 1000;
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
|
||||
AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
|
||||
Intent i = new Intent(context, SenseService.class);
|
||||
PendingIntent pending = PendingIntent.getService(context, 0, i, 0);
|
||||
|
||||
Calendar cal = Calendar.getInstance();
|
||||
|
||||
cal.add(Calendar.SECOND, 10);
|
||||
service.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), ALARM_INTERVAL, pending);
|
||||
}
|
||||
}
|
@ -1,77 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.event;
|
||||
|
||||
import android.app.Service;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.IBinder;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.SenseDataCollector;
|
||||
import org.wso2.carbon.iot.android.sense.util.LocalRegistry;
|
||||
import org.wso2.carbon.iot.android.sense.util.SenseDataReceiverManager;
|
||||
import org.wso2.carbon.iot.android.sense.util.SenseWakeLock;
|
||||
|
||||
/**
|
||||
* This service caters to initiate the data collection.
|
||||
*/
|
||||
public class SenseService extends Service {
|
||||
|
||||
public static Context context;
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
SenseWakeLock.acquireWakeLock(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent arg0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
context = this;
|
||||
if (!LocalRegistry.isExist(context)) return Service.START_NOT_STICKY;
|
||||
//Below triggers the data collection for sensors,location and battery.
|
||||
SenseDataCollector Sensor = new SenseDataCollector(this, SenseDataCollector.DataType.SENSOR);
|
||||
SenseDataCollector Location = new SenseDataCollector(this, SenseDataCollector.DataType.LOCATION);
|
||||
SenseDataCollector speed = new SenseDataCollector(this, SenseDataCollector.DataType.SPEED);
|
||||
SenseDataCollector audio = new SenseDataCollector(this, SenseDataCollector.DataType.AUDIO);
|
||||
SenseDataReceiverManager.registerBatteryDataReceiver(this);
|
||||
SenseDataReceiverManager.registerScreenDataReceiver(this);
|
||||
SenseDataReceiverManager.registerCallDataReceiver(this);
|
||||
SenseDataReceiverManager.registerActivityDataReceiver(this);
|
||||
SenseDataReceiverManager.registerSmsDataReceiver(this);
|
||||
SenseDataReceiverManager.registerAppDataReceiver(this);
|
||||
SenseDataReceiverManager.registerNetworkDataReader(this);
|
||||
//service will not be stopped until we manually stop the service
|
||||
return Service.START_NOT_STICKY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
SenseDataReceiverManager.unregisterBatteryDataReceiver(this);
|
||||
SenseDataReceiverManager.unregisterScreenDataReceiver(this);
|
||||
SenseDataReceiverManager.unregisterCallDataReceiver(this);
|
||||
SenseDataReceiverManager.unregisterActivityDataReceiver(this);
|
||||
SenseDataReceiverManager.unregisterSmsDataReceiver(this);
|
||||
SenseDataReceiverManager.unregisterAppDataReceiver(this);
|
||||
SenseDataReceiverManager.unregisterNetworkDataReader();
|
||||
|
||||
SenseWakeLock.releaseCPUWakeLock();
|
||||
super.onDestroy();
|
||||
}
|
||||
}
|
@ -1,21 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.event.streams;
|
||||
|
||||
/**
|
||||
* this class extended by each data reader implementation, where the data store logic is implemented in thread.
|
||||
*/
|
||||
public abstract class DataReader implements Runnable {
|
||||
}
|
@ -1,53 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.event.streams;
|
||||
|
||||
import android.content.Context;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.location.LocationDataReader;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.sensor.SensorDataReader;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.speed.SpeedDataReader;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.audio.AudioDataReader;
|
||||
|
||||
/**
|
||||
* This class triggered by service to collect the sensor data.
|
||||
*/
|
||||
public class SenseDataCollector {
|
||||
public enum DataType {
|
||||
SENSOR, LOCATION,SPEED, AUDIO
|
||||
}
|
||||
|
||||
public SenseDataCollector(Context ctx, DataType dt) {
|
||||
DataReader dr = null;
|
||||
switch (dt) {
|
||||
case SENSOR:
|
||||
dr = new SensorDataReader(ctx);
|
||||
break;
|
||||
case LOCATION:
|
||||
dr = new LocationDataReader(ctx);
|
||||
break;
|
||||
case SPEED:
|
||||
dr = new SpeedDataReader(ctx);
|
||||
break;
|
||||
case AUDIO:
|
||||
dr = new AudioDataReader(ctx);
|
||||
break;
|
||||
|
||||
}
|
||||
if (dr != null) {
|
||||
Thread DataCollector = new Thread(dr);
|
||||
DataCollector.start();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,67 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.activity;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class ActivityData {
|
||||
/**
|
||||
* 0 - In vehicle
|
||||
* 1 - Bicycle
|
||||
* 2 - Foot
|
||||
* 3 - Still
|
||||
* 4 - Unknown
|
||||
* 5 - Tilting
|
||||
* 7 - Walking
|
||||
* 8 - Running
|
||||
*/
|
||||
private int activity;
|
||||
private int confidence;
|
||||
private long timestamp;
|
||||
|
||||
ActivityData(int activity, int confidence) {
|
||||
this.activity = activity;
|
||||
this.confidence = confidence;
|
||||
this.timestamp = new Date().getTime();
|
||||
}
|
||||
|
||||
public int getActivity() {
|
||||
return activity;
|
||||
}
|
||||
|
||||
public void setActivity(int activity) {
|
||||
this.activity = activity;
|
||||
}
|
||||
|
||||
public int getConfidence() {
|
||||
return confidence;
|
||||
}
|
||||
|
||||
public void setConfidence(int confidence) {
|
||||
this.confidence = confidence;
|
||||
}
|
||||
|
||||
public long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public void setTimestamp(long timestamp) {
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
}
|
@ -1,54 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.activity;
|
||||
|
||||
import android.app.IntentService;
|
||||
import android.content.Intent;
|
||||
|
||||
import com.google.android.gms.location.ActivityRecognitionResult;
|
||||
import com.google.android.gms.location.DetectedActivity;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.util.SenseDataHolder;
|
||||
|
||||
public class ActivityReceiver extends IntentService {
|
||||
public static final int MINIMUM_CONFIDENCE = 75;
|
||||
|
||||
/**
|
||||
* Retrieve the information for every 10 seconds.
|
||||
*/
|
||||
public static final long UPDATE_INTERVAL = 10000;
|
||||
|
||||
public ActivityReceiver() {
|
||||
super(ActivityReceiver.class.getName());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onHandleIntent(Intent intent) {
|
||||
if (ActivityRecognitionResult.hasResult(intent)) {
|
||||
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
|
||||
|
||||
for (DetectedActivity activity : result.getProbableActivities()) {
|
||||
if (activity.getConfidence() >= MINIMUM_CONFIDENCE) {
|
||||
ActivityData data = new ActivityData(activity.getType(), activity.getConfidence());
|
||||
SenseDataHolder.getActivityDataHolder().add(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,61 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.application;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class ApplicationData {
|
||||
public enum Action {
|
||||
INSTALL, REMOVE
|
||||
}
|
||||
|
||||
private long timestamp;
|
||||
private String packageName;
|
||||
private Action action;
|
||||
|
||||
ApplicationData(String packageName, Action action) {
|
||||
this.packageName = packageName;
|
||||
this.action = action;
|
||||
this.timestamp = new Date().getTime();
|
||||
}
|
||||
|
||||
public long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public void setTimestamp(long timestamp) {
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
|
||||
public String getPackageName() {
|
||||
return packageName;
|
||||
}
|
||||
|
||||
public void setPackageName(String packageName) {
|
||||
this.packageName = packageName;
|
||||
}
|
||||
|
||||
public Action getAction() {
|
||||
return action;
|
||||
}
|
||||
|
||||
public void setAction(Action action) {
|
||||
this.action = action;
|
||||
}
|
||||
}
|
@ -1,45 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.application;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.util.SenseDataHolder;
|
||||
|
||||
/**
|
||||
* Currently interested on package add and remove only. Can be extended for modification.
|
||||
*/
|
||||
public class ApplicationDataReceiver extends BroadcastReceiver {
|
||||
|
||||
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
String packageName = intent.getData().toString().substring(8);
|
||||
ApplicationData appData;
|
||||
if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
|
||||
appData = new ApplicationData(packageName, ApplicationData.Action.INSTALL);
|
||||
} else {
|
||||
// Removed
|
||||
appData = new ApplicationData(packageName, ApplicationData.Action.REMOVE);
|
||||
}
|
||||
SenseDataHolder.getApplicationDataHolder().add(appData);
|
||||
}
|
||||
}
|
@ -1,58 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.audio;
|
||||
|
||||
public class AudioData {
|
||||
private long timestamp;
|
||||
private boolean headsetOn;
|
||||
private int musicVolume;
|
||||
private boolean playing;
|
||||
|
||||
public long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public void setTimestamp(long timestamp) {
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
|
||||
public boolean isHeadsetOn() {
|
||||
return headsetOn;
|
||||
}
|
||||
|
||||
public void setHeadsetOn(boolean headsetOn) {
|
||||
this.headsetOn = headsetOn;
|
||||
}
|
||||
|
||||
public int getMusicVolume() {
|
||||
return musicVolume;
|
||||
}
|
||||
|
||||
public void setMusicVolume(int musicVolume) {
|
||||
this.musicVolume = musicVolume;
|
||||
}
|
||||
|
||||
public boolean isPlaying() {
|
||||
return playing;
|
||||
}
|
||||
|
||||
public void setPlaying(boolean playing) {
|
||||
this.playing = playing;
|
||||
}
|
||||
}
|
@ -1,50 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.audio;
|
||||
|
||||
import android.content.Context;
|
||||
import android.media.AudioManager;
|
||||
import android.util.Log;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.DataReader;
|
||||
import org.wso2.carbon.iot.android.sense.util.SenseDataHolder;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class AudioDataReader extends DataReader {
|
||||
|
||||
private static final String TAG = AudioDataReader.class.getName();
|
||||
private Context context;
|
||||
|
||||
public AudioDataReader(Context context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
Log.d(TAG, "Running AudioDataReader");
|
||||
AudioManager manager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
|
||||
AudioData audioData = new AudioData();
|
||||
audioData.setTimestamp(new Date().getTime());
|
||||
audioData.setPlaying(manager.isMusicActive());
|
||||
audioData.setHeadsetOn(manager.isWiredHeadsetOn());
|
||||
audioData.setMusicVolume(manager.getStreamVolume(AudioManager.STREAM_MUSIC));
|
||||
SenseDataHolder.getAudioDataHolder().add(audioData);
|
||||
}
|
||||
}
|
@ -1,142 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.battery;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.os.BatteryManager;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* This defines the data structure of the battery data that is been collected.
|
||||
* look at http://developer.android.com/reference/android/os/BatteryManager.html for field description.
|
||||
*/
|
||||
public class BatteryData {
|
||||
|
||||
public enum State {
|
||||
LOW, OK
|
||||
}
|
||||
|
||||
private int health;
|
||||
private int level;
|
||||
private int plugged;
|
||||
private int present;
|
||||
private int scale;
|
||||
private int status;
|
||||
private int temperature;
|
||||
private int voltage;
|
||||
private long timestamp;
|
||||
private State state;
|
||||
|
||||
BatteryData(Intent intent) {
|
||||
timestamp = new Date().getTime();
|
||||
health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, 0);
|
||||
level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
|
||||
plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
|
||||
present = intent.getExtras().getBoolean(BatteryManager.EXTRA_PRESENT) ? 1 : 0;
|
||||
scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);
|
||||
status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0);
|
||||
String technology = intent.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY);
|
||||
temperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);
|
||||
voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
|
||||
state = State.OK;
|
||||
}
|
||||
|
||||
BatteryData(State state) {
|
||||
this.timestamp = new Date().getTime();
|
||||
this.state = state;
|
||||
}
|
||||
|
||||
public int getHealth() {
|
||||
return health;
|
||||
}
|
||||
|
||||
public void setHealth(int health) {
|
||||
this.health = health;
|
||||
}
|
||||
|
||||
public int getLevel() {
|
||||
return level;
|
||||
}
|
||||
|
||||
public void setLevel(int level) {
|
||||
this.level = level;
|
||||
}
|
||||
|
||||
public int getPlugged() {
|
||||
return plugged;
|
||||
}
|
||||
|
||||
public void setPlugged(int plugged) {
|
||||
this.plugged = plugged;
|
||||
}
|
||||
|
||||
public int getPresent() {
|
||||
return present;
|
||||
}
|
||||
|
||||
public void setPresent(int present) {
|
||||
this.present = present;
|
||||
}
|
||||
|
||||
public int getScale() {
|
||||
return scale;
|
||||
}
|
||||
|
||||
public void setScale(int scale) {
|
||||
this.scale = scale;
|
||||
}
|
||||
|
||||
public int getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(int status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public int getTemperature() {
|
||||
return temperature;
|
||||
}
|
||||
|
||||
public void setTemperature(int temperature) {
|
||||
this.temperature = temperature;
|
||||
}
|
||||
|
||||
public int getVoltage() {
|
||||
return voltage;
|
||||
}
|
||||
|
||||
public void setVoltage(int voltage) {
|
||||
this.voltage = voltage;
|
||||
}
|
||||
|
||||
|
||||
public long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public void setTimestamp(long timestamp) {
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
|
||||
public State getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
public void setState(State state) {
|
||||
this.state = state;
|
||||
}
|
||||
}
|
@ -1,48 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.battery;
|
||||
|
||||
import android.app.AlarmManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.BatteryManager;
|
||||
import android.util.Log;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.data.publisher.DataPublisherService;
|
||||
import org.wso2.carbon.iot.android.sense.util.SenseDataHolder;
|
||||
|
||||
/**
|
||||
* Whenever the battery level changes This receiver will be triggered.
|
||||
*/
|
||||
public class BatteryDataReceiver extends BroadcastReceiver {
|
||||
|
||||
private final long ALARM_INTERVAL = 1000;
|
||||
/**
|
||||
* When the data is retrieved then its added to a in memory map.
|
||||
*
|
||||
* @param context of the receiver.
|
||||
* @param intent of the receiver
|
||||
*/
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
|
||||
Log.i("Battery Data Receiver", "Triggered");
|
||||
Intent i = new Intent(context, BatteryReaderService.class);
|
||||
PendingIntent pending = PendingIntent.getService(context, 0, i, 0);
|
||||
service.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), ALARM_INTERVAL, pending);
|
||||
}
|
||||
|
||||
}
|
@ -1,63 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.battery;
|
||||
|
||||
import android.app.IntentService;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.os.BatteryManager;
|
||||
import android.os.IBinder;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.util.Log;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.util.SenseDataHolder;
|
||||
|
||||
public class BatteryReaderService extends IntentService {
|
||||
|
||||
private Context context;
|
||||
|
||||
public BatteryReaderService() {
|
||||
super("BatteryReaderService");
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onHandleIntent(Intent intent) {
|
||||
IntentFilter intentFilter = new IntentFilter();
|
||||
intentFilter.addAction(Intent.ACTION_BATTERY_LOW);
|
||||
intentFilter.addAction(Intent.ACTION_BATTERY_OKAY);
|
||||
intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
|
||||
Intent intent1 = registerReceiver(null, intentFilter);
|
||||
|
||||
Log.i("Battery Data", String.valueOf(intent1.getIntExtra(BatteryManager.EXTRA_LEVEL, 0)));
|
||||
if (Intent.ACTION_BATTERY_OKAY.equals(intent.getAction())) {
|
||||
SenseDataHolder.getBatteryDataHolder().add(new BatteryData(BatteryData.State.OK));
|
||||
} else if (Intent.ACTION_BATTERY_LOW.equals(intent.getAction())) {
|
||||
SenseDataHolder.getBatteryDataHolder().add(new BatteryData(BatteryData.State.LOW));
|
||||
} else {
|
||||
SenseDataHolder.getBatteryDataHolder().add(new BatteryData(intent1));
|
||||
}
|
||||
}
|
||||
}
|
@ -1,70 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.call;
|
||||
|
||||
public class CallData {
|
||||
|
||||
public enum Type {
|
||||
INCOMING, OUTGOING, MISSED;
|
||||
}
|
||||
|
||||
private Type type;
|
||||
private String phoneNumber;
|
||||
private long startTime;
|
||||
private long endTime;
|
||||
|
||||
public CallData(Type type, String phoneNumber, long startTime, long endTime) {
|
||||
this.type = type;
|
||||
this.phoneNumber = phoneNumber;
|
||||
this.startTime = startTime;
|
||||
this.endTime = endTime;
|
||||
}
|
||||
|
||||
public Type getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(Type type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getPhoneNumber() {
|
||||
return phoneNumber;
|
||||
}
|
||||
|
||||
public void setPhoneNumber(String phoneNumber) {
|
||||
this.phoneNumber = phoneNumber;
|
||||
}
|
||||
|
||||
public long getStartTime() {
|
||||
return startTime;
|
||||
}
|
||||
|
||||
public void setStartTime(long startTime) {
|
||||
this.startTime = startTime;
|
||||
}
|
||||
|
||||
public long getEndTime() {
|
||||
return endTime;
|
||||
}
|
||||
|
||||
public void setEndTime(long endTime) {
|
||||
this.endTime = endTime;
|
||||
}
|
||||
}
|
@ -1,87 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.call;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.telephony.TelephonyManager;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.util.SenseDataHolder;
|
||||
|
||||
public class CallDataReceiver extends BroadcastReceiver {
|
||||
private static int lastState = TelephonyManager.CALL_STATE_IDLE;
|
||||
private static long startTime;
|
||||
private static boolean isIncoming;
|
||||
private static String lastNotifiedNumber;
|
||||
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
|
||||
lastNotifiedNumber = intent.getExtras().getString(Intent.EXTRA_PHONE_NUMBER);
|
||||
} else {
|
||||
String extraState = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
|
||||
int state = 0;
|
||||
if (extraState.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
|
||||
state = TelephonyManager.CALL_STATE_IDLE;
|
||||
} else if (extraState.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
|
||||
state = TelephonyManager.CALL_STATE_OFFHOOK;
|
||||
} else if (extraState.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
|
||||
state = TelephonyManager.CALL_STATE_RINGING;
|
||||
}
|
||||
|
||||
if (lastState == state) {
|
||||
return; // Nothing has been changed
|
||||
}
|
||||
switch (state) {
|
||||
case TelephonyManager.CALL_STATE_RINGING:
|
||||
// Receiving a call
|
||||
isIncoming = true;
|
||||
startTime = System.currentTimeMillis();
|
||||
// If incoming call, get the incoming number
|
||||
lastNotifiedNumber = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
|
||||
break;
|
||||
case TelephonyManager.CALL_STATE_OFFHOOK:
|
||||
if (lastState == TelephonyManager.CALL_STATE_RINGING) {
|
||||
// RINGING -> OFFHOOK = ANSWERED
|
||||
isIncoming = true;
|
||||
startTime = System.currentTimeMillis();
|
||||
} else {
|
||||
// NOT RINGING -> OFFHOOK = OUTGOING
|
||||
isIncoming = false;
|
||||
startTime = System.currentTimeMillis();
|
||||
}
|
||||
break;
|
||||
case TelephonyManager.CALL_STATE_IDLE:
|
||||
if (lastState == TelephonyManager.CALL_STATE_RINGING) {
|
||||
// RINGING -> IDLE = MISSED
|
||||
SenseDataHolder.getCallDataHolder().add(new CallData(CallData.Type.MISSED, lastNotifiedNumber, startTime, System.currentTimeMillis()));
|
||||
} else if (isIncoming) {
|
||||
// Incoming (OFFHOOK) -> IDLE = INCOMING CALL ENDED
|
||||
SenseDataHolder.getCallDataHolder().add(new CallData(CallData.Type.INCOMING, lastNotifiedNumber, startTime, System.currentTimeMillis()));
|
||||
} else {
|
||||
// Not Incoming -> IDLE = OUTGOING CALL ENDED
|
||||
SenseDataHolder.getCallDataHolder().add(new CallData(CallData.Type.OUTGOING, lastNotifiedNumber, startTime, System.currentTimeMillis()));
|
||||
}
|
||||
break;
|
||||
}
|
||||
lastState = state;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,67 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.data;
|
||||
|
||||
public class NetworkData {
|
||||
|
||||
//Mobile or Wifi
|
||||
private String type;
|
||||
private long dataReceived;
|
||||
private long dataSent;
|
||||
private long timeStamp;
|
||||
|
||||
public NetworkData() {
|
||||
}
|
||||
|
||||
public String getDataType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public long getDataReceived() {
|
||||
return dataReceived;
|
||||
}
|
||||
|
||||
public void setDataReceived(long dataReceived) {
|
||||
this.dataReceived = dataReceived;
|
||||
}
|
||||
|
||||
public long getDataSent() {
|
||||
return dataSent;
|
||||
}
|
||||
|
||||
public void setDataSent(long dataSent) {
|
||||
this.dataSent = dataSent;
|
||||
}
|
||||
|
||||
public long getTimeStamp() {
|
||||
return timeStamp;
|
||||
}
|
||||
|
||||
public void setTimeStamp(long timeStamp) {
|
||||
this.timeStamp = timeStamp;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
}
|
@ -1,96 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.data;
|
||||
|
||||
import android.content.Context;
|
||||
import android.net.ConnectivityManager;
|
||||
import android.net.NetworkInfo;
|
||||
import android.net.TrafficStats;
|
||||
import android.os.AsyncTask;
|
||||
import android.os.Handler;
|
||||
import android.util.Log;
|
||||
import org.wso2.carbon.iot.android.sense.util.SenseDataHolder;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Class to read data sent and received by the device.
|
||||
*/
|
||||
public class NetworkDataReader extends AsyncTask<Void, Void, Long> {
|
||||
|
||||
private NetworkData networkData;
|
||||
private Context context;
|
||||
private Handler mHandler = new Handler();
|
||||
private long mStartRX = 0;
|
||||
private long mStartTX = 0;
|
||||
private final String WIFI = "WIFI";
|
||||
private final String MOBILE = "MOBILE";
|
||||
private String connectionType;
|
||||
|
||||
public NetworkDataReader(Context context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Long doInBackground(Void... voids) {
|
||||
|
||||
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||
networkData = new NetworkData();
|
||||
|
||||
if (getConnectionType(connectivityManager, ConnectivityManager.TYPE_WIFI)) {
|
||||
connectionType = WIFI;
|
||||
} else if (getConnectionType(connectivityManager, ConnectivityManager.TYPE_MOBILE)) {
|
||||
connectionType = MOBILE;
|
||||
}
|
||||
|
||||
mStartRX = TrafficStats.getTotalRxBytes();
|
||||
mStartTX = TrafficStats.getTotalTxBytes();
|
||||
if (mStartRX == TrafficStats.UNSUPPORTED || mStartTX == TrafficStats.UNSUPPORTED) {
|
||||
Log.e("ERROR", "Not connected.");
|
||||
} else {
|
||||
mHandler.postDelayed(mRunnable, 10000);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect data sent and received with in 10 second time frames.
|
||||
*/
|
||||
private final Runnable mRunnable = new Runnable() {
|
||||
public void run() {
|
||||
long rxBytes = TrafficStats.getTotalRxBytes() - mStartRX;
|
||||
long txBytes = TrafficStats.getTotalTxBytes() - mStartTX;
|
||||
Log.i("Usage: ", String.valueOf(rxBytes) + " " + String.valueOf(txBytes) + " " + System.currentTimeMillis());
|
||||
networkData.setType(connectionType);
|
||||
networkData.setTimeStamp(new Date().getTime());
|
||||
networkData.setDataSent(txBytes);
|
||||
networkData.setDataReceived(rxBytes);
|
||||
SenseDataHolder.getNetworkDataHolder().add(networkData);
|
||||
mHandler.postDelayed(mRunnable, 10000);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the type of the connection currently have.
|
||||
*/
|
||||
private boolean getConnectionType(ConnectivityManager manager, Integer type) {
|
||||
NetworkInfo networkInfo = manager.getNetworkInfo(type);
|
||||
return networkInfo.isConnected();
|
||||
}
|
||||
}
|
@ -1,56 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.location;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* This defines the data structure of the location data that is been collected.
|
||||
*/
|
||||
public class LocationData {
|
||||
private double latitude; // latitude
|
||||
private double longitude; // longitude
|
||||
private long timestamp;
|
||||
|
||||
LocationData(double latitude, double longitude) {
|
||||
this.latitude = latitude;
|
||||
this.longitude = longitude;
|
||||
timestamp = new Date().getTime();
|
||||
|
||||
}
|
||||
|
||||
public double getLatitude() {
|
||||
return latitude;
|
||||
}
|
||||
|
||||
public void setLatitude(double latitude) {
|
||||
this.latitude = latitude;
|
||||
}
|
||||
|
||||
public double getLongitude() {
|
||||
return longitude;
|
||||
}
|
||||
|
||||
public void setLongitude(double longitude) {
|
||||
this.longitude = longitude;
|
||||
}
|
||||
|
||||
public long getTimeStamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public void setTimeStamp(long timeStamp) {
|
||||
timestamp = timeStamp;
|
||||
}
|
||||
}
|
@ -1,251 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.location;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.location.Location;
|
||||
import android.location.LocationListener;
|
||||
import android.location.LocationManager;
|
||||
import android.os.Bundle;
|
||||
import android.support.v4.content.LocalBroadcastManager;
|
||||
import android.util.Log;
|
||||
import android.widget.Toast;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.DataReader;
|
||||
import org.wso2.carbon.iot.android.sense.util.SenseDataHolder;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* This is used to retrieve the location data using GPS and used Network connection to increase the accuracy.
|
||||
*/
|
||||
public class LocationDataReader extends DataReader implements LocationListener {
|
||||
protected LocationManager locationManager;
|
||||
private final Context mContext;
|
||||
|
||||
LocationData gps;
|
||||
|
||||
static final Double EARTH_RADIUS = 6371.00;
|
||||
|
||||
// flag for GPS status
|
||||
private boolean isGPSEnabled = false;
|
||||
|
||||
// flag for network status
|
||||
private boolean isNetworkEnabled = false;
|
||||
|
||||
// flag for GPS status
|
||||
private boolean canGetLocation = false;
|
||||
//private boolean canGetLocation = false;
|
||||
private static final String TAG = LocationDataReader.class.getName();
|
||||
|
||||
Location location; // location
|
||||
double latitude; // latitude
|
||||
double longitude; // longitude
|
||||
|
||||
double lat_old=0.0;
|
||||
double lon_old=0.0;
|
||||
double time;
|
||||
float speed = 0.0f;
|
||||
private long lastUpdate;
|
||||
|
||||
// The minimum distance to change Updates in meters
|
||||
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
|
||||
|
||||
// The minimum time between updates in milliseconds
|
||||
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
|
||||
|
||||
public LocationDataReader(Context context) {
|
||||
this.mContext = context;
|
||||
getLocation();
|
||||
}
|
||||
|
||||
public Location getLocation() {
|
||||
try {
|
||||
|
||||
locationManager = (LocationManager) mContext
|
||||
.getSystemService(mContext.LOCATION_SERVICE);
|
||||
|
||||
// getting GPS status
|
||||
isGPSEnabled = locationManager
|
||||
.isProviderEnabled(LocationManager.GPS_PROVIDER);
|
||||
|
||||
// getting network status
|
||||
isNetworkEnabled = locationManager
|
||||
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
|
||||
|
||||
if (!isGPSEnabled && !isNetworkEnabled) {
|
||||
// no network provider is enabled
|
||||
} else {
|
||||
this.canGetLocation = true;
|
||||
if (isNetworkEnabled) {
|
||||
locationManager.requestLocationUpdates(
|
||||
LocationManager.NETWORK_PROVIDER,
|
||||
MIN_TIME_BW_UPDATES,
|
||||
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
|
||||
Log.d("Network", "Network");
|
||||
if (locationManager != null) {
|
||||
location = locationManager
|
||||
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
|
||||
if (location != null) {
|
||||
latitude = location.getLatitude();
|
||||
longitude = location.getLongitude();
|
||||
}
|
||||
}
|
||||
}
|
||||
// if GPS Enabled get lat/long using GPS Services
|
||||
if (isGPSEnabled) {
|
||||
if (location == null) {
|
||||
locationManager.requestLocationUpdates(
|
||||
LocationManager.GPS_PROVIDER,
|
||||
MIN_TIME_BW_UPDATES,
|
||||
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
|
||||
Log.d("GPS Enabled", "GPS Enabled");
|
||||
if (locationManager != null) {
|
||||
location = locationManager
|
||||
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
|
||||
if (location != null) {
|
||||
latitude = location.getLatitude();
|
||||
longitude = location.getLongitude();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Failed to capture location data.");
|
||||
}
|
||||
|
||||
return location;
|
||||
}
|
||||
|
||||
public boolean canGetLocation() {
|
||||
return this.canGetLocation;
|
||||
}
|
||||
|
||||
public void stopUsingGPS() {
|
||||
if (locationManager != null) {
|
||||
locationManager.removeUpdates(LocationDataReader.this);
|
||||
}
|
||||
}
|
||||
|
||||
public double getLatitude() {
|
||||
if (location != null) {
|
||||
latitude = location.getLatitude();
|
||||
}
|
||||
// return latitude
|
||||
return latitude;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to get longitude
|
||||
*/
|
||||
public double getLongitude() {
|
||||
if (location != null) {
|
||||
longitude = location.getLongitude();
|
||||
}
|
||||
// return longitude
|
||||
return longitude;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLocationChanged(Location arg0) {
|
||||
// TODO Auto-generated method stub
|
||||
Log.v("Debug", "in onLocation changed..");
|
||||
if(location!=null){
|
||||
long curTime = System.currentTimeMillis();
|
||||
|
||||
long diffTime = (curTime - lastUpdate);
|
||||
lastUpdate = curTime;
|
||||
Calendar c=Calendar.getInstance();
|
||||
c.setTimeInMillis(diffTime);
|
||||
|
||||
time=c.get(Calendar.HOUR);
|
||||
|
||||
locationManager.removeUpdates(LocationDataReader.this);
|
||||
//String Speed = "Device Speed: " +location.getSpeed();
|
||||
latitude=location.getLongitude();
|
||||
longitude =location.getLatitude();
|
||||
|
||||
double distance =CalculationByDistance(latitude, longitude, lat_old, lon_old)/1000;
|
||||
|
||||
speed = (float)distance/(float)time;
|
||||
// Toast.makeText(mContext, longitude+"\n"+latitude+"\nDistance is: "
|
||||
// +distance+"\nSpeed is: "+speed , Toast.LENGTH_SHORT).show();
|
||||
|
||||
|
||||
Intent intent = new Intent("speedUpdate");
|
||||
intent.putExtra("speed", speed);
|
||||
LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
|
||||
|
||||
lat_old=latitude;
|
||||
lon_old=longitude;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onProviderDisabled(String arg0) {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onProviderEnabled(String arg0) {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
Log.d(TAG, "running -Location");
|
||||
try {
|
||||
TimeUnit.MILLISECONDS.sleep(10000);
|
||||
double lat = getLatitude();
|
||||
double longit = getLongitude();
|
||||
if (lat != 0 && longit != 0) {
|
||||
Log.d(TAG, "YYY " + getLatitude() + ", XXX " + getLongitude());
|
||||
gps = new LocationData(getLatitude(), getLongitude());
|
||||
SenseDataHolder.getLocationDataHolder().add(gps);
|
||||
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
// Restore the interrupted status
|
||||
Thread.currentThread().interrupt();
|
||||
Log.e(TAG, " Location Data Retrieval Failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
public double CalculationByDistance(double lat1, double lon1, double lat2, double lon2) {
|
||||
double Radius = EARTH_RADIUS;
|
||||
double dLat = Math.toRadians(lat2-lat1);
|
||||
double dLon = Math.toRadians(lon2-lon1);
|
||||
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
|
||||
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
|
||||
Math.sin(dLon/2) * Math.sin(dLon/2);
|
||||
double c = 2 * Math.asin(Math.sqrt(a));
|
||||
return Radius * c;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
@ -1,55 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.screen;
|
||||
|
||||
import android.content.Intent;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class ScreenData {
|
||||
private String action;
|
||||
private long timestamp;
|
||||
|
||||
ScreenData(Intent intent) {
|
||||
if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
|
||||
this.action = "on";
|
||||
} else if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
|
||||
this.action = "off";
|
||||
} else {
|
||||
this.action = "unknown";
|
||||
}
|
||||
this.timestamp = new Date().getTime();
|
||||
}
|
||||
|
||||
public String getAction() {
|
||||
return action;
|
||||
}
|
||||
|
||||
public void setAction(String action) {
|
||||
this.action = action;
|
||||
}
|
||||
|
||||
public long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public void setTimestamp(long timestamp) {
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
}
|
@ -1,32 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.screen;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.util.SenseDataHolder;
|
||||
|
||||
public class ScreenDataReceiver extends BroadcastReceiver {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
SenseDataHolder.getScreenDataHolder().add(new ScreenData(intent));
|
||||
}
|
||||
}
|
@ -1,102 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.sensor;
|
||||
|
||||
import android.hardware.SensorEvent;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.realtimeviewer.sensorlisting.SupportedSensors;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* This defines the data structure of the sensor data that is been collected.
|
||||
* look at http://developer.android.com/guide/topics/sensors/sensors_overview.html for field description.
|
||||
*/
|
||||
public class SensorData {
|
||||
private int sensorType;
|
||||
private String sensorName;
|
||||
private String sensorVendor;
|
||||
private float sensorValues[];
|
||||
private int accuracyStatus;
|
||||
private long timestamp;
|
||||
private String collectTimestamp;
|
||||
private SupportedSensors supportedSensors = SupportedSensors.getInstance();
|
||||
|
||||
SensorData(SensorEvent event) {
|
||||
sensorValues = event.values;
|
||||
accuracyStatus = event.accuracy;
|
||||
collectTimestamp = String.valueOf(event.timestamp);
|
||||
timestamp = new Date().getTime();
|
||||
sensorName = supportedSensors.getType(event.sensor.getType()).toUpperCase();
|
||||
sensorVendor = event.sensor.getVendor();
|
||||
sensorType = event.sensor.getType();
|
||||
}
|
||||
|
||||
public int getSensorType() {
|
||||
return sensorType;
|
||||
}
|
||||
|
||||
public void setSensorType(int sensorType) {
|
||||
this.sensorType = sensorType;
|
||||
}
|
||||
|
||||
public String getSensorName() {
|
||||
return sensorName;
|
||||
}
|
||||
|
||||
public void setSensorName(String sensorName) {
|
||||
this.sensorName = sensorName;
|
||||
}
|
||||
|
||||
public String getSensorVendor() {
|
||||
return sensorVendor;
|
||||
}
|
||||
|
||||
public void setSensorVendor(String sensorVendor) {
|
||||
this.sensorVendor = sensorVendor;
|
||||
}
|
||||
|
||||
public float[] getSensorValues() {
|
||||
return sensorValues;
|
||||
}
|
||||
|
||||
public void setSensorValues(float sensorValues[]) {
|
||||
this.sensorValues = sensorValues;
|
||||
}
|
||||
|
||||
public int getAccuracyStatus() {
|
||||
return accuracyStatus;
|
||||
}
|
||||
|
||||
public void setAccuracyStatus(int accuracyStatus) {
|
||||
this.accuracyStatus = accuracyStatus;
|
||||
}
|
||||
|
||||
public long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public void setTimestamp(long timestamp) {
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
|
||||
public String getCollectTimestamp() {
|
||||
return collectTimestamp;
|
||||
}
|
||||
|
||||
public void setCollectTimestamp(String collectTimestamp) {
|
||||
this.collectTimestamp = collectTimestamp;
|
||||
}
|
||||
}
|
@ -1,114 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.sensor;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.hardware.Sensor;
|
||||
import android.hardware.SensorEvent;
|
||||
import android.hardware.SensorEventListener;
|
||||
import android.hardware.SensorManager;
|
||||
import android.util.Log;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.DataReader;
|
||||
import org.wso2.carbon.iot.android.sense.realtimeviewer.sensorlisting.SupportedSensors;
|
||||
import org.wso2.carbon.iot.android.sense.util.SenseDataHolder;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.Vector;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* This is used to retrieve the sensor data.
|
||||
*/
|
||||
public class SensorDataReader extends DataReader implements SensorEventListener {
|
||||
private SensorManager mSensorManager;
|
||||
private Map<String, SensorData> senseDataStruct = new HashMap<>();
|
||||
private Vector<SensorData> sensorVector = new Vector<>();
|
||||
Context ctx;
|
||||
private List<Sensor> sensorList = new ArrayList<>();
|
||||
private SupportedSensors supportedSensors = SupportedSensors.getInstance();
|
||||
private static final String TAG = SensorDataReader.class.getName();
|
||||
|
||||
public SensorDataReader(Context context) {
|
||||
ctx = context;
|
||||
SharedPreferences sharedPreferences = ctx.getSharedPreferences(SupportedSensors.SELECTED_SENSORS, Context
|
||||
.MODE_MULTI_PROCESS);
|
||||
Set<String> selectedSet = sharedPreferences.getStringSet(SupportedSensors.SELECTED_SENSORS_BY_USER, null);
|
||||
mSensorManager = (SensorManager) ctx.getSystemService(Context.SENSOR_SERVICE);
|
||||
selectedSensorList(selectedSet);
|
||||
for (Sensor sensor : sensorList) {
|
||||
mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
|
||||
}
|
||||
}
|
||||
|
||||
private void collectSensorData() {
|
||||
for (Sensor sensor : sensorList) {
|
||||
try {
|
||||
if (senseDataStruct.containsKey(sensor.getName())) {
|
||||
SensorData sensorInfo = senseDataStruct.get(sensor.getName());
|
||||
sensorVector.add(sensorInfo);
|
||||
Log.d(TAG, "Sensor Name " + sensor.getName() + ", Type " + sensor.getType() + " " +
|
||||
", sensorValue :" + Arrays.toString(sensorInfo.getSensorValues()));
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
Log.d(TAG, "error on sensors");
|
||||
}
|
||||
}
|
||||
mSensorManager.unregisterListener(this);
|
||||
}
|
||||
|
||||
public Vector<SensorData> getSensorData() {
|
||||
try {
|
||||
TimeUnit.MILLISECONDS.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
Log.e(TAG, e.getMessage());
|
||||
}
|
||||
collectSensorData();
|
||||
return sensorVector;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAccuracyChanged(Sensor sensor, int accuracy) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSensorChanged(SensorEvent event) {
|
||||
senseDataStruct.put(event.sensor.getName(), new SensorData(event));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
Log.d(TAG, "running -sensorDataMap");
|
||||
Vector<SensorData> sensorDetails = getSensorData();
|
||||
for (SensorData data : sensorDetails) {
|
||||
SenseDataHolder.getSensorDataHolder().add(data);
|
||||
}
|
||||
}
|
||||
|
||||
public void selectedSensorList(Set<String> set) {
|
||||
if (set != null) {
|
||||
String[] sensorsSet = set.toArray(new String[set.size()]);
|
||||
for (String s : sensorsSet) {
|
||||
sensorList.add(mSensorManager.getDefaultSensor(supportedSensors.getType(s.toLowerCase())));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,58 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.sms;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class SmsData {
|
||||
|
||||
private String phoneNumber;
|
||||
private long timestamp;
|
||||
private String message;
|
||||
|
||||
SmsData(String phoneNumber, String message) {
|
||||
this.phoneNumber = phoneNumber;
|
||||
this.message = message;
|
||||
this.timestamp = new Date().getTime();
|
||||
}
|
||||
|
||||
public String getPhoneNumber() {
|
||||
return phoneNumber;
|
||||
}
|
||||
|
||||
public void setPhoneNumber(String phoneNumber) {
|
||||
this.phoneNumber = phoneNumber;
|
||||
}
|
||||
|
||||
public long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public void setTimestamp(long timestamp) {
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
}
|
@ -1,48 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.sms;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.telephony.SmsMessage;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.util.SenseDataHolder;
|
||||
|
||||
public class SmsDataReceiver extends BroadcastReceiver {
|
||||
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
final Bundle bundle = intent.getExtras();
|
||||
|
||||
if (bundle != null) {
|
||||
final Object[] pdusObj = (Object[]) bundle.get("pdus");
|
||||
|
||||
for (int i = 0; i < pdusObj.length; i++) {
|
||||
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
|
||||
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
|
||||
String message = currentMessage.getDisplayMessageBody();
|
||||
|
||||
SmsData smsData = new SmsData(phoneNumber, message);
|
||||
SenseDataHolder.getSmsDataHolder().add(smsData);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,56 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.speed;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class SpeedData {
|
||||
private float speed; // speed
|
||||
private String turnAxis; // turns
|
||||
private long timestamp;
|
||||
|
||||
SpeedData(float speed, String turnAxis) {
|
||||
this.speed = speed;
|
||||
this.turnAxis = turnAxis;
|
||||
timestamp = new Date().getTime();
|
||||
|
||||
}
|
||||
|
||||
public float getSpeed() {
|
||||
return speed;
|
||||
}
|
||||
|
||||
public void setSpeed(float speed) {
|
||||
this.speed = speed;
|
||||
}
|
||||
|
||||
public String getTurns() {
|
||||
return turnAxis;
|
||||
}
|
||||
|
||||
public void setTurns(String turnAxis) {
|
||||
this.turnAxis = turnAxis;
|
||||
}
|
||||
|
||||
public long getTimeStamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public void setTimeStamp(long timeStamp) {
|
||||
timestamp = timeStamp;
|
||||
}
|
||||
|
||||
}
|
@ -1,180 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.event.streams.speed;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.DataReader;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.sensor.SensorData;
|
||||
import org.wso2.carbon.iot.android.sense.realtimeviewer.sensorlisting.SupportedSensors;
|
||||
import org.wso2.carbon.iot.android.sense.util.SenseDataHolder;
|
||||
import android.content.Context;
|
||||
import android.content.IntentFilter;
|
||||
import android.content.SharedPreferences;
|
||||
import android.hardware.Sensor;
|
||||
import android.hardware.SensorEvent;
|
||||
import android.hardware.SensorEventListener;
|
||||
import android.hardware.SensorManager;
|
||||
import android.support.v4.content.LocalBroadcastManager;
|
||||
import android.util.Log;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.Vector;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import android.content.BroadcastReceiver;
|
||||
|
||||
import android.content.Intent;
|
||||
|
||||
|
||||
public class SpeedDataReader extends DataReader implements SensorEventListener {
|
||||
|
||||
SpeedData data;
|
||||
private SensorManager mSensorManager;
|
||||
private Map<String, SensorData> senseDataStruct = new HashMap<>();
|
||||
private Vector<SensorData> sensorVector = new Vector<>();
|
||||
private static final String TAG = SpeedDataReader.class.getName();
|
||||
private float last_x, last_y, last_z;
|
||||
private long lastUpdate;
|
||||
private String xTurnAxis;
|
||||
float speed;
|
||||
private float x,y,z;
|
||||
Context ctx;
|
||||
private List<Sensor> sensorList = new ArrayList<>();
|
||||
private SupportedSensors supportedSensors = SupportedSensors.getInstance();
|
||||
|
||||
@Override
|
||||
public void onSensorChanged(SensorEvent event) {
|
||||
|
||||
Sensor devSensor = event.sensor;
|
||||
|
||||
if (devSensor.getType() == Sensor.TYPE_ACCELEROMETER) {
|
||||
x = event.values[0];
|
||||
y = event.values[1];
|
||||
z = event.values[2];
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public SpeedDataReader(Context context) {
|
||||
ctx = context;
|
||||
SharedPreferences sharedPreferences = ctx.getSharedPreferences(SupportedSensors.SELECTED_SENSORS, Context
|
||||
.MODE_MULTI_PROCESS);
|
||||
Set<String> selectedSet = sharedPreferences.getStringSet(SupportedSensors.SELECTED_SENSORS_BY_USER, null);
|
||||
mSensorManager = (SensorManager) ctx.getSystemService(Context.SENSOR_SERVICE);
|
||||
selectedSensorList(selectedSet);
|
||||
for (Sensor sensor : sensorList) {
|
||||
mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
|
||||
}
|
||||
|
||||
LocalBroadcastManager.getInstance(ctx).registerReceiver(mMessageReceiver,
|
||||
new IntentFilter("speedUpdate"));
|
||||
|
||||
}
|
||||
|
||||
private void collectSensorData() {
|
||||
for (Sensor sensor : sensorList) {
|
||||
try {
|
||||
if (senseDataStruct.containsKey(sensor.getName())) {
|
||||
SensorData sensorInfo = senseDataStruct.get(sensor.getName());
|
||||
sensorVector.add(sensorInfo);
|
||||
Log.d(TAG, "Sensor Name " + sensor.getName() + ", Type " + sensor.getType() + " " +
|
||||
", sensorValue :" + sensorInfo.getSensorValues());
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
Log.d(TAG, "error on sensors");
|
||||
}
|
||||
}
|
||||
mSensorManager.unregisterListener(this);
|
||||
}
|
||||
|
||||
|
||||
public String getTurns() {
|
||||
|
||||
if(Round(x,4)>10.0000){
|
||||
Log.d("sensor", "X Right axis: " + x);
|
||||
xTurnAxis = "Right";
|
||||
return xTurnAxis;
|
||||
}else if(Round(x,4)<-10.0000){
|
||||
Log.d("sensor", "X Left axis: " + x);
|
||||
xTurnAxis = "Left";
|
||||
return xTurnAxis;
|
||||
}else {
|
||||
xTurnAxis = "No Turns";
|
||||
|
||||
}
|
||||
return xTurnAxis;
|
||||
}
|
||||
|
||||
public float getSpeed(){
|
||||
|
||||
return speed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAccuracyChanged(Sensor sensor, int accuracy) {
|
||||
// can be safely ignored for this demo
|
||||
}
|
||||
|
||||
public static float Round(float Rval, int Rpl) {
|
||||
float p = (float)Math.pow(10,Rpl);
|
||||
Rval = Rval * p;
|
||||
float tmp = Math.round(Rval);
|
||||
Log.d("round", "round: " + tmp/p);
|
||||
|
||||
return tmp/p;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
Log.d(TAG, "running - Device Speed");
|
||||
try {
|
||||
TimeUnit.MILLISECONDS.sleep(10000);
|
||||
// String trn = getTurns();
|
||||
// double spd = getSpeed();
|
||||
//if (trn != 0 && spd != 0) {
|
||||
data = new SpeedData(getSpeed(), getTurns());
|
||||
SenseDataHolder.getSpeedDataHolder().add(data);
|
||||
collectSensorData();
|
||||
|
||||
//}
|
||||
} catch (InterruptedException e) {
|
||||
// Restore the interrupted status
|
||||
Thread.currentThread().interrupt();
|
||||
Log.e(TAG, " Speed Data Retrieval Failed");
|
||||
}
|
||||
}
|
||||
|
||||
public void selectedSensorList(Set<String> set) {
|
||||
if (set != null) {
|
||||
String[] sensorsSet = set.toArray(new String[set.size()]);
|
||||
for (String s : sensorsSet) {
|
||||
sensorList.add(mSensorManager.getDefaultSensor(supportedSensors.getType(s.toLowerCase())));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
// Get extra data included in the Intent
|
||||
speed = intent.getFloatExtra("speed",speed);
|
||||
|
||||
Log.d("receiver", "Got message: " + speed);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
}
|
@ -1,270 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.realtimeviewer;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.content.SharedPreferences;
|
||||
import android.hardware.Sensor;
|
||||
import android.hardware.SensorManager;
|
||||
import android.os.Bundle;
|
||||
import android.support.design.widget.FloatingActionButton;
|
||||
import android.support.design.widget.NavigationView;
|
||||
import android.support.design.widget.Snackbar;
|
||||
import android.support.v4.view.GravityCompat;
|
||||
import android.support.v4.widget.DrawerLayout;
|
||||
import android.support.v7.app.ActionBarDrawerToggle;
|
||||
import android.support.v7.app.AppCompatActivity;
|
||||
import android.support.v7.widget.Toolbar;
|
||||
import android.util.Log;
|
||||
import android.view.Menu;
|
||||
import android.view.MenuItem;
|
||||
import android.view.View;
|
||||
import android.widget.EditText;
|
||||
import android.widget.ListView;
|
||||
import android.widget.Toast;
|
||||
import android.app.AlertDialog;
|
||||
import android.content.DialogInterface;
|
||||
import org.wso2.carbon.iot.android.sense.RegisterActivity;
|
||||
import org.wso2.carbon.iot.android.sense.bmonitor.BeaconMonitoringActivity;
|
||||
import org.wso2.carbon.iot.android.sense.data.publisher.DataPublisherReceiver;
|
||||
import org.wso2.carbon.iot.android.sense.data.publisher.DataPublisherService;
|
||||
import org.wso2.carbon.iot.android.sense.event.SenseScheduleReceiver;
|
||||
import org.wso2.carbon.iot.android.sense.event.SenseService;
|
||||
import org.wso2.carbon.iot.android.sense.realtimeviewer.datastore.TempStore;
|
||||
import org.wso2.carbon.iot.android.sense.realtimeviewer.event.RealTimeSensorChangeReceiver;
|
||||
import org.wso2.carbon.iot.android.sense.realtimeviewer.event.realtimesensor.RealTimeSensorReader;
|
||||
import org.wso2.carbon.iot.android.sense.realtimeviewer.sensorlisting.SupportedSensors;
|
||||
import org.wso2.carbon.iot.android.sense.realtimeviewer.view.adaptor.SensorViewAdaptor;
|
||||
import org.wso2.carbon.iot.android.sense.realtimeviewer.view.sensor.selector.SelectSensorDialog;
|
||||
import org.wso2.carbon.iot.android.sense.speech.detector.WordRecognitionActivity;
|
||||
import org.wso2.carbon.iot.android.sense.beacon.MonitoringActivity;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.util.LocalRegistry;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import org.altbeacon.beacon.BeaconManager;
|
||||
|
||||
import agent.sense.android.iot.carbon.wso2.org.wso2_senseagent.R;
|
||||
|
||||
/**
|
||||
* Activity for selecting sensors available in the device
|
||||
*/
|
||||
|
||||
public class ActivitySelectSensor extends AppCompatActivity
|
||||
implements NavigationView.OnNavigationItemSelectedListener, SelectSensorDialog.SensorListListener {
|
||||
|
||||
private SharedPreferences sharedPreferences;
|
||||
private SelectSensorDialog sensorDialog = new SelectSensorDialog();
|
||||
private Set<String> selectedSensorSet = new HashSet<>();
|
||||
private ListView listView;
|
||||
private SensorManager sensorManager;
|
||||
private ArrayList<Sensor> sensors = new ArrayList<>();
|
||||
private RealTimeSensorReader sensorReader = null;
|
||||
private RealTimeSensorChangeReceiver realTimeSensorChangeReceiver = new RealTimeSensorChangeReceiver();
|
||||
private SupportedSensors supportedSensors = SupportedSensors.getInstance();
|
||||
protected static final String TAG = ActivitySelectSensor.class.getName();
|
||||
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_activity_select_sensor);
|
||||
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
|
||||
setSupportActionBar(toolbar);
|
||||
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
|
||||
listView = (ListView) findViewById(R.id.senseListContainer);
|
||||
|
||||
registerReceiver(realTimeSensorChangeReceiver, new IntentFilter("sensorDataMap"));
|
||||
|
||||
//Publish data
|
||||
FloatingActionButton fbtnPublishData = (FloatingActionButton) findViewById(R.id.publish);
|
||||
|
||||
fbtnPublishData.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View view) {
|
||||
Snackbar.make(view, "Publishing data started", Snackbar.LENGTH_LONG)
|
||||
.setAction("Action", null).show();
|
||||
|
||||
DataPublisherReceiver dataPublisherReceiver = new DataPublisherReceiver();
|
||||
dataPublisherReceiver.clearAbortBroadcast();
|
||||
dataPublisherReceiver.onReceive(getApplicationContext(), null);
|
||||
}
|
||||
});
|
||||
|
||||
FloatingActionButton fbtnAddSensors = (FloatingActionButton) findViewById(R.id.addSensors);
|
||||
fbtnAddSensors.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
sensorDialog.show(getFragmentManager(), "Sensor List");
|
||||
}
|
||||
});
|
||||
|
||||
sharedPreferences = getSharedPreferences(SupportedSensors.SELECTED_SENSORS, 0);
|
||||
|
||||
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
|
||||
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
|
||||
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
|
||||
drawer.setDrawerListener(toggle);
|
||||
toggle.syncState();
|
||||
|
||||
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
|
||||
navigationView.setNavigationItemSelectedListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBackPressed() {
|
||||
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
|
||||
if (drawer.isDrawerOpen(GravityCompat.START)) {
|
||||
drawer.closeDrawer(GravityCompat.START);
|
||||
} else {
|
||||
super.onBackPressed();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCreateOptionsMenu(Menu menu) {
|
||||
// Inflate the menu; this adds items to the action bar if it is present.
|
||||
getMenuInflater().inflate(R.menu.activity_select_sensor, menu);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(MenuItem item) {
|
||||
// Handle action bar item clicks here. The action bar will
|
||||
// automatically handle clicks on the Home/Up button, so long
|
||||
// as you specify a parent activity in AndroidManifest.xml.
|
||||
int id = item.getItemId();
|
||||
|
||||
//noinspection SimplifiableIfStatement
|
||||
if (id == R.id.action_deEnroll) {
|
||||
|
||||
/**
|
||||
* unregister the sensors and broadcast receivers.
|
||||
* */
|
||||
unregisterSensors();
|
||||
unregisterReceivers();
|
||||
|
||||
if (!LocalRegistry.isExist(getApplicationContext())) {
|
||||
Intent activity = new Intent(getApplicationContext(), RegisterActivity.class);
|
||||
startActivity(activity);
|
||||
}
|
||||
LocalRegistry.setEnrolled(getApplicationContext(), false);
|
||||
LocalRegistry.removeUsername(getApplicationContext());
|
||||
LocalRegistry.removeDeviceId(getApplicationContext());
|
||||
LocalRegistry.removeServerURL(getApplicationContext());
|
||||
LocalRegistry.removeAccessToken(getApplicationContext());
|
||||
LocalRegistry.removeRefreshToken(getApplicationContext());
|
||||
LocalRegistry.removeMqttEndpoint(getApplicationContext());
|
||||
LocalRegistry.removeTenantDomain(getApplicationContext());
|
||||
LocalRegistry.setExist(false);
|
||||
//Stop the current running background services.
|
||||
stopService(new Intent(this, SenseService.class)); //Stop sensor reading service
|
||||
stopService(new Intent(this, DataPublisherService.class)); //Stop data uploader service
|
||||
|
||||
Intent registerActivity = new Intent(getApplicationContext(), RegisterActivity.class);
|
||||
registerActivity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
|
||||
startActivity(registerActivity);
|
||||
finish();
|
||||
return true;
|
||||
}
|
||||
return super.onOptionsItemSelected(item);
|
||||
}
|
||||
|
||||
@SuppressWarnings("StatementWithEmptyBody")
|
||||
@Override
|
||||
public boolean onNavigationItemSelected(MenuItem item) {
|
||||
// Handle navigation view item clicks here.
|
||||
int id = item.getItemId();
|
||||
|
||||
if (id == R.id.select) {
|
||||
sensorDialog.show(getFragmentManager(), "Sensor List");
|
||||
}
|
||||
|
||||
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
|
||||
drawer.closeDrawer(GravityCompat.START);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void onDialogPositiveClick(SelectSensorDialog dialog) {
|
||||
|
||||
Log.d("Selected sensors", dialog.getSet().toString());
|
||||
selectedSensorSet = dialog.getSet();
|
||||
update();
|
||||
unregisterSensors();
|
||||
|
||||
SenseScheduleReceiver senseScheduleReceiver = new SenseScheduleReceiver();
|
||||
senseScheduleReceiver.clearAbortBroadcast();
|
||||
senseScheduleReceiver.onReceive(this, null);
|
||||
|
||||
/**
|
||||
* Get the selected sensors
|
||||
* Register them
|
||||
* */
|
||||
SensorViewAdaptor adaptor1 = new SensorViewAdaptor(getApplicationContext(), TempStore.sensorArrayList);
|
||||
adaptor1.notifyDataSetChanged();
|
||||
|
||||
sensorReader = new RealTimeSensorReader(this, adaptor1);
|
||||
getSensors();
|
||||
|
||||
for (Sensor s : sensors) {
|
||||
sensorManager.registerListener(sensorReader, s, SensorManager.SENSOR_DELAY_NORMAL);
|
||||
}
|
||||
|
||||
realTimeSensorChangeReceiver.updateOnChange(adaptor1);
|
||||
listView.setAdapter(adaptor1);
|
||||
}
|
||||
|
||||
public void update() {
|
||||
Log.d("Update", "Set the values to Shared Preferences");
|
||||
|
||||
TempStore.sensorArrayList.clear();
|
||||
TempStore.sensorDataMap.clear();
|
||||
|
||||
SharedPreferences.Editor editor = sharedPreferences.edit();
|
||||
editor.putStringSet(SupportedSensors.SELECTED_SENSORS_BY_USER, selectedSensorSet);
|
||||
editor.apply();
|
||||
}
|
||||
|
||||
public void getSensors() {
|
||||
sensors.clear();
|
||||
for (String sensor : selectedSensorSet.toArray(new String[selectedSensorSet.size()])) {
|
||||
sensors.add(sensorManager.getDefaultSensor(supportedSensors.getType(sensor.toLowerCase())));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method will unregister all the registered sensors.
|
||||
*/
|
||||
public void unregisterSensors() {
|
||||
if (sensors.size() > 0) {
|
||||
for (Sensor s : sensors) {
|
||||
System.out.println(s.getName() + " Unregistered!");
|
||||
sensorManager.unregisterListener(sensorReader, s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method unregisters the real-time broadcast receiver.
|
||||
*/
|
||||
public void unregisterReceivers() {
|
||||
unregisterReceiver(realTimeSensorChangeReceiver);
|
||||
}
|
||||
}
|
@ -1,36 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.realtimeviewer.datastore;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.realtimeviewer.event.realtimesensor.RealTimeSensor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
/**
|
||||
* Class to store the real time sensor readings.
|
||||
*/
|
||||
public class TempStore {
|
||||
|
||||
/**
|
||||
* Hash map which is used to store sensor values with the sensor names.
|
||||
*/
|
||||
public static ConcurrentMap<String, RealTimeSensor> sensorDataMap = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* Array List which is used to populate the List view.
|
||||
*/
|
||||
public static ArrayList<RealTimeSensor> sensorArrayList = new ArrayList<>();
|
||||
}
|
@ -1,40 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.realtimeviewer.event;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.realtimeviewer.datastore.TempStore;
|
||||
import org.wso2.carbon.iot.android.sense.realtimeviewer.view.adaptor.SensorViewAdaptor;
|
||||
|
||||
/**
|
||||
* This class is to detect the sensor change event and update the sensor array list.
|
||||
* And update the view adaptor which is used to show the sensors list in the Android List view.
|
||||
*/
|
||||
public class RealTimeSensorChangeReceiver extends BroadcastReceiver {
|
||||
|
||||
SensorViewAdaptor adaptor;
|
||||
|
||||
public void updateOnChange(SensorViewAdaptor adaptor) {
|
||||
this.adaptor = adaptor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
TempStore.sensorArrayList.clear();
|
||||
TempStore.sensorArrayList.addAll(TempStore.sensorDataMap.values());
|
||||
}
|
||||
}
|
@ -1,88 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.realtimeviewer.event.realtimesensor;
|
||||
|
||||
import android.support.annotation.NonNull;
|
||||
|
||||
/**
|
||||
* The class to store the sensor data captured by the RealTimeSensorReader.
|
||||
*/
|
||||
public class RealTimeSensor implements Comparable {
|
||||
|
||||
|
||||
/**
|
||||
* Name of the sensor.
|
||||
*/
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* The X value reading of the sensor.
|
||||
*/
|
||||
private String valueX;
|
||||
|
||||
/**
|
||||
* The Y value reading of the sensor.
|
||||
*/
|
||||
private String valueY;
|
||||
|
||||
/**
|
||||
* The Y value reading of the sensor.
|
||||
*/
|
||||
private String valueZ;
|
||||
|
||||
public RealTimeSensor() {
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getValueX() {
|
||||
return valueX;
|
||||
}
|
||||
|
||||
public void setValueX(String valueX) {
|
||||
this.valueX = valueX;
|
||||
}
|
||||
|
||||
public String getValueY() {
|
||||
return valueY;
|
||||
}
|
||||
|
||||
public void setValueY(String valueY) {
|
||||
this.valueY = valueY;
|
||||
}
|
||||
|
||||
public String getValueZ() {
|
||||
return valueZ;
|
||||
}
|
||||
|
||||
public void setValueZ(String valueZ) {
|
||||
this.valueZ = valueZ;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.valueX + ", " + valueY + ", " + valueZ;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(@NonNull Object another) {
|
||||
return this.toString().contains(another.toString()) ? 1 : 0;
|
||||
}
|
||||
}
|
@ -1,61 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.realtimeviewer.event.realtimesensor;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.hardware.Sensor;
|
||||
import android.hardware.SensorEvent;
|
||||
import android.hardware.SensorEventListener;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.realtimeviewer.datastore.TempStore;
|
||||
import org.wso2.carbon.iot.android.sense.realtimeviewer.sensorlisting.SupportedSensors;
|
||||
import org.wso2.carbon.iot.android.sense.realtimeviewer.view.adaptor.SensorViewAdaptor;
|
||||
|
||||
/**
|
||||
* This class reads the sensor values in real time.
|
||||
*/
|
||||
public class RealTimeSensorReader implements SensorEventListener {
|
||||
|
||||
private Context context;
|
||||
private SensorViewAdaptor adaptor;
|
||||
private SupportedSensors supportedSensors = SupportedSensors.getInstance();
|
||||
|
||||
public RealTimeSensorReader(Context context, SensorViewAdaptor adaptor) {
|
||||
this.context = context;
|
||||
this.adaptor = adaptor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSensorChanged(SensorEvent event) {
|
||||
RealTimeSensor realTimeSensor = new RealTimeSensor();
|
||||
realTimeSensor.setName(supportedSensors.getType(event.sensor.getType()).toUpperCase());
|
||||
|
||||
realTimeSensor.setValueX(event.values == null ? "" : event.values[0] + "");
|
||||
realTimeSensor.setValueY(event.values == null || event.values.length <= 1 ? "" : event.values[1] + "");
|
||||
realTimeSensor.setValueZ(event.values == null || event.values.length <= 1 ? "" : event.values[2] + "");
|
||||
|
||||
TempStore.sensorDataMap.put(supportedSensors.getType(event.sensor.getType()), realTimeSensor);
|
||||
|
||||
Intent intent = new Intent();
|
||||
intent.setAction("sensorDataMap");
|
||||
context.sendBroadcast(intent);
|
||||
|
||||
adaptor.notifyDataSetChanged();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAccuracyChanged(Sensor sensor, int accuracy) {
|
||||
}
|
||||
}
|
@ -1,63 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.realtimeviewer.sensorlisting;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.hardware.Sensor;
|
||||
import android.hardware.SensorManager;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Class to save the list of sensors that are available in the device, which are supported by the iot server.
|
||||
* This list will be saved in Shared preferences so that app can use this data when needed.
|
||||
*/
|
||||
public class AvailableSensorsInDevice {
|
||||
|
||||
private SharedPreferences sensorPreference;
|
||||
|
||||
/**
|
||||
* The Android sensor manager which is used to get the sensors available in device.
|
||||
*/
|
||||
private SensorManager mSensorManager;
|
||||
|
||||
public AvailableSensorsInDevice(Context context) {
|
||||
this.sensorPreference = context.getSharedPreferences(SupportedSensors.AVAILABLE_SENSORS, 0);
|
||||
this.mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method filters the pre defined sensor types from sensors available in device and sets them in Shared
|
||||
* preferences.
|
||||
*/
|
||||
public void setContent() {
|
||||
SupportedSensors supportedSensors = SupportedSensors.getInstance();
|
||||
List<String> sensor_List = supportedSensors.getSensorList();
|
||||
Set<String> sensorSet = new HashSet<>();
|
||||
List<Sensor> sensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);
|
||||
|
||||
for (String sen : sensor_List) {
|
||||
if (sensors.contains(mSensorManager.getDefaultSensor(supportedSensors.getType(sen.toLowerCase())))) {
|
||||
sensorSet.add(sen);
|
||||
}
|
||||
}
|
||||
|
||||
SharedPreferences.Editor editor = this.sensorPreference.edit();
|
||||
editor.putStringSet(SupportedSensors.GET_AVAILABLE_SENSORS, sensorSet);
|
||||
editor.apply();
|
||||
}
|
||||
}
|
@ -1,122 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.realtimeviewer.sensorlisting;
|
||||
|
||||
import android.hardware.Sensor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Class to store the supported sensorDataMap types.
|
||||
*/
|
||||
public class SupportedSensors {
|
||||
|
||||
//For set user selected sensors. Will be used by sensorDataMap reading and dialog
|
||||
public static String SELECTED_SENSORS = "Selected";
|
||||
public static String SELECTED_SENSORS_BY_USER = "userSelection";
|
||||
|
||||
//For setting the available sensors in the device in dialog and AvailableSensorsInDevice
|
||||
public static String AVAILABLE_SENSORS = "Sensors";
|
||||
public static String GET_AVAILABLE_SENSORS = "getAvailableSensors";
|
||||
|
||||
public static final int SUPPORTED_SENSOR_COUNT = 10;
|
||||
private static List<String> sensorList = new ArrayList<>();
|
||||
private static HashMap<String, Integer> sensorTypeMap = new HashMap<>();
|
||||
private static HashMap<Integer, String> typeSensorMap = new HashMap<>();
|
||||
private static SupportedSensors supportedSensors = new SupportedSensors();
|
||||
|
||||
private SupportedSensors() {
|
||||
this.setList();
|
||||
this.setSensorTypeMap();
|
||||
this.setTypeSensorMap();
|
||||
}
|
||||
|
||||
public static SupportedSensors getInstance() {
|
||||
return supportedSensors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the supported sensor types by the IOT server.
|
||||
*/
|
||||
private void setList() {
|
||||
sensorList.add("Accelerometer");
|
||||
sensorList.add("Magnetometer");
|
||||
sensorList.add("Gravity");
|
||||
sensorList.add("Rotation Vector");
|
||||
sensorList.add("Pressure");
|
||||
sensorList.add("Light");
|
||||
sensorList.add("Gyroscope");
|
||||
sensorList.add("Proximity");
|
||||
sensorList.add("Pedometer");
|
||||
}
|
||||
|
||||
/**
|
||||
* Populate the hash map which has Sensor name as the key and the sensor type as the value.
|
||||
*/
|
||||
private void setSensorTypeMap() {
|
||||
sensorTypeMap.put("accelerometer", Sensor.TYPE_ACCELEROMETER);
|
||||
sensorTypeMap.put("magnetometer", Sensor.TYPE_MAGNETIC_FIELD);
|
||||
sensorTypeMap.put("gravity", Sensor.TYPE_GRAVITY);
|
||||
sensorTypeMap.put("rotation vector", Sensor.TYPE_GAME_ROTATION_VECTOR);
|
||||
sensorTypeMap.put("pressure", Sensor.TYPE_PRESSURE);
|
||||
sensorTypeMap.put("gyroscope", Sensor.TYPE_GYROSCOPE);
|
||||
sensorTypeMap.put("light", Sensor.TYPE_LIGHT);
|
||||
sensorTypeMap.put("proximity", Sensor.TYPE_PROXIMITY);
|
||||
sensorTypeMap.put("pedometer", Sensor.TYPE_STEP_COUNTER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Populates the hash map which has Sensor type as the key and sensor name as the value.
|
||||
*/
|
||||
private void setTypeSensorMap() {
|
||||
typeSensorMap.put(Sensor.TYPE_ACCELEROMETER, "accelerometer");
|
||||
typeSensorMap.put(Sensor.TYPE_MAGNETIC_FIELD, "magnetometer");
|
||||
typeSensorMap.put(Sensor.TYPE_GRAVITY, "gravity");
|
||||
typeSensorMap.put(Sensor.TYPE_GAME_ROTATION_VECTOR, "rotation vector");
|
||||
typeSensorMap.put(Sensor.TYPE_PRESSURE, "pressure");
|
||||
typeSensorMap.put(Sensor.TYPE_GYROSCOPE, "gyroscope");
|
||||
typeSensorMap.put(Sensor.TYPE_LIGHT, "light");
|
||||
typeSensorMap.put(Sensor.TYPE_PROXIMITY, "proximity");
|
||||
typeSensorMap.put(Sensor.TYPE_STEP_COUNTER, "pedometer");
|
||||
}
|
||||
|
||||
/**
|
||||
* Method to get the supported sensor list.
|
||||
*
|
||||
* @return the list of sensors supported by the iot server.
|
||||
*/
|
||||
public List<String> getSensorList() {
|
||||
return sensorList;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param sensor The name of the sensor.
|
||||
* @return The integer representing the type of the sensor,
|
||||
*/
|
||||
public int getType(String sensor) {
|
||||
return sensorTypeMap.get(sensor);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param type The type of the sensor.
|
||||
* @return The sensor name related to the given sensor type.
|
||||
*/
|
||||
public String getType(int type) {
|
||||
return typeSensorMap.get(type);
|
||||
}
|
||||
}
|
@ -1,94 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.realtimeviewer.view.adaptor;
|
||||
|
||||
import android.content.Context;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.BaseAdapter;
|
||||
import android.widget.TextView;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.realtimeviewer.event.realtimesensor.RealTimeSensor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import agent.sense.android.iot.carbon.wso2.org.wso2_senseagent.R;
|
||||
|
||||
/**
|
||||
* Adaptor for populate the ListView.
|
||||
* Takes list of Sensor readings
|
||||
*/
|
||||
public class SensorViewAdaptor extends BaseAdapter {
|
||||
|
||||
private Context context;
|
||||
private List<RealTimeSensor> data;
|
||||
|
||||
public SensorViewAdaptor(Context context, List<RealTimeSensor> data) {
|
||||
this.context = context;
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getCount() {
|
||||
return data.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getItem(int position) {
|
||||
return data.get(position);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getItemId(int position) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public View getView(int position, View convertView, ViewGroup parent) {
|
||||
ViewHolder holder;
|
||||
|
||||
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
|
||||
View view;
|
||||
|
||||
if (convertView == null) {
|
||||
view = inflater.inflate(R.layout.display_sensor_values, parent, false);
|
||||
holder = new ViewHolder();
|
||||
holder.name = (TextView) view.findViewById(R.id.name);
|
||||
holder.valuesX = (TextView) view.findViewById(R.id.X);
|
||||
holder.valuesY = (TextView) view.findViewById(R.id.Y);
|
||||
holder.valuesZ = (TextView) view.findViewById(R.id.Z);
|
||||
view.setTag(holder);
|
||||
} else {
|
||||
view = convertView;
|
||||
holder = (ViewHolder) view.getTag();
|
||||
}
|
||||
|
||||
RealTimeSensor data = this.data.get(position);
|
||||
|
||||
holder.name.setText(data.getName());
|
||||
holder.valuesX.setText(data.getValueX());
|
||||
holder.valuesY.setText(data.getValueY());
|
||||
holder.valuesZ.setText(data.getValueZ());
|
||||
|
||||
return view;
|
||||
}
|
||||
|
||||
private class ViewHolder {
|
||||
public TextView name;
|
||||
public TextView valuesX;
|
||||
public TextView valuesY;
|
||||
public TextView valuesZ;
|
||||
}
|
||||
}
|
@ -1,143 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.realtimeviewer.view.sensor.selector;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.Dialog;
|
||||
import android.app.DialogFragment;
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.Bundle;
|
||||
import android.support.v7.app.AlertDialog;
|
||||
import android.util.Log;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.realtimeviewer.sensorlisting.SupportedSensors;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Functionality
|
||||
* <p/>
|
||||
* Show the list of available sensors in a list
|
||||
* Get the user selections
|
||||
* Put them in to shared preferences
|
||||
*/
|
||||
public class SelectSensorDialog extends DialogFragment {
|
||||
|
||||
protected boolean[] selections = new boolean[SupportedSensors.SUPPORTED_SENSOR_COUNT];
|
||||
Activity activity;
|
||||
SensorListListener sensorListListener;
|
||||
private Set<String> selectedSensorSet = new HashSet<>();
|
||||
|
||||
@Override
|
||||
public Dialog onCreateDialog(Bundle savedInstanceState) {
|
||||
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
|
||||
builder.setTitle("Select Sensors");
|
||||
activity = getActivity();
|
||||
|
||||
SharedPreferences preferences = getActivity().getSharedPreferences(SupportedSensors.AVAILABLE_SENSORS, Context.
|
||||
MODE_MULTI_PROCESS);
|
||||
|
||||
Set<String> set = preferences.getStringSet(SupportedSensors.GET_AVAILABLE_SENSORS, null);
|
||||
final CharSequence[] sequence = getSequence(set);
|
||||
|
||||
final boolean[] pos = new boolean[selections.length];
|
||||
final boolean[] neg = new boolean[selections.length];
|
||||
|
||||
builder.setMultiChoiceItems(sequence, selections, new DialogInterface.OnMultiChoiceClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
|
||||
if (isChecked) {
|
||||
selectedSensorSet.add(sequence[which].toString());
|
||||
|
||||
pos[which] = true;
|
||||
} else {
|
||||
selectedSensorSet.remove(sequence[which].toString());
|
||||
neg[which] = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
Log.d("Click", "Ok");
|
||||
//call sensorDataMap reading class
|
||||
sensorListListener.onDialogPositiveClick(SelectSensorDialog.this);
|
||||
}
|
||||
});
|
||||
|
||||
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
Log.d("Click", "Cancel");
|
||||
for (int i = 0; i < SupportedSensors.SUPPORTED_SENSOR_COUNT; i++) {
|
||||
|
||||
if (pos[i])
|
||||
selections[i] = false;
|
||||
if (neg[i])
|
||||
selections[i] = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
return builder.create();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDetach() {
|
||||
super.onDetach();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAttach(Activity activity) {
|
||||
super.onAttach(activity);
|
||||
|
||||
try {
|
||||
sensorListListener = (SensorListListener) getActivity();
|
||||
} catch (ClassCastException ex) {
|
||||
throw new ClassCastException(activity.toString() + " must implement the SensorListener");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStart() {
|
||||
super.onStart();
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface to be implemented by the parent
|
||||
*/
|
||||
public CharSequence[] getSequence(Set<String> sensorset) {
|
||||
CharSequence[] seq;
|
||||
String[] seq2 = sensorset.toArray(new String[sensorset.size()]);
|
||||
seq = Arrays.copyOf(seq2, seq2.length);
|
||||
return seq;
|
||||
}
|
||||
|
||||
public Set<String> getSet() {
|
||||
return this.selectedSensorSet;
|
||||
}
|
||||
|
||||
public interface SensorListListener {
|
||||
void onDialogPositiveClick(SelectSensorDialog dialog);
|
||||
}
|
||||
}
|
@ -1,32 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.speech.detector;
|
||||
|
||||
/**
|
||||
* This interface is used to retrieve the voice commands and restart the listenting service
|
||||
*/
|
||||
public interface IVoiceControl {
|
||||
/**
|
||||
* This will be executed when a voice command was found
|
||||
* @param voiceCommands
|
||||
*/
|
||||
public abstract void processVoiceCommands(String... voiceCommands);
|
||||
|
||||
/**
|
||||
* This will be executed after a voice command was processed to keep the recognition service activated
|
||||
*/
|
||||
public void restartListeningService();
|
||||
|
||||
public void finish();
|
||||
}
|
@ -1,148 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.speech.detector;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.support.design.widget.FloatingActionButton;
|
||||
import android.view.Menu;
|
||||
import android.view.MenuItem;
|
||||
import android.view.View;
|
||||
import android.view.WindowManager;
|
||||
import android.widget.Button;
|
||||
import android.widget.EditText;
|
||||
import android.widget.Toast;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.constants.SenseConstants;
|
||||
import org.wso2.carbon.iot.android.sense.realtimeviewer.ActivitySelectSensor;
|
||||
import org.wso2.carbon.iot.android.sense.speech.detector.util.ListeningActivity;
|
||||
import org.wso2.carbon.iot.android.sense.speech.detector.util.ProcessWords;
|
||||
import org.wso2.carbon.iot.android.sense.speech.detector.util.VoiceRecognitionListener;
|
||||
import org.wso2.carbon.iot.android.sense.speech.detector.util.WordData;
|
||||
import org.wso2.carbon.iot.android.sense.util.SenseDataHolder;
|
||||
|
||||
import agent.sense.android.iot.carbon.wso2.org.wso2_senseagent.R;
|
||||
|
||||
/**
|
||||
* This is main activity for word recognition.
|
||||
*/
|
||||
public class WordRecognitionActivity extends ListeningActivity {
|
||||
Button setThreasholdButton;
|
||||
Button addWordButton;
|
||||
Button removeWordButton;
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_speech_sense_main);
|
||||
context = getApplicationContext(); // Needs to be set
|
||||
|
||||
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
VoiceRecognitionListener.getInstance().setListener(this); // Here we set the current listener
|
||||
addListenerOnSetThreasholdButton();
|
||||
addListenerOnAddWordButton();
|
||||
addListenerOnRemoveWordButton();
|
||||
String sessionId = getIntent().getStringExtra("sessionId");
|
||||
ProcessWords.setSessionId(sessionId);
|
||||
FloatingActionButton fbtnSpeechRecongnizer = (FloatingActionButton) findViewById(R.id.sensorChange);
|
||||
fbtnSpeechRecongnizer.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
WordData wordData = new WordData(ProcessWords.getSessionId(), SenseConstants.EVENT_LISTENER_FINISHED, 1);
|
||||
SenseDataHolder.getWordDataHolder().add(wordData);
|
||||
stopListening();
|
||||
Intent intent = new Intent(getApplicationContext(), ActivitySelectSensor.class);
|
||||
startActivity(intent);
|
||||
}
|
||||
});
|
||||
Long tsLong = System.currentTimeMillis() / 1000;
|
||||
WordData wordData = new WordData(sessionId, SenseConstants.EVENT_LISTENER_STARTED, 1);
|
||||
SenseDataHolder.getWordDataHolder().add(wordData);
|
||||
startListening(); // starts listening
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBackPressed() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processVoiceCommands(String... voiceCommands) {
|
||||
if(voiceCommands==null || voiceCommands.length==0){
|
||||
return;
|
||||
}
|
||||
ProcessWords processWords = new ProcessWords(this);
|
||||
processWords.execute(voiceCommands);
|
||||
restartListeningService();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCreateOptionsMenu(Menu menu) {
|
||||
// Inflate the menu; this adds items to the action bar if it is present.
|
||||
// getMenuInflater().inflate(R.menu.menu_main, menu);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(MenuItem item) {
|
||||
// Handle action bar item clicks here. The action bar will
|
||||
// automatically handle clicks on the Home/Up button, so long
|
||||
// as you specify a parent activity in AndroidManifest.xml.
|
||||
int id = item.getItemId();
|
||||
|
||||
//noinspection SimplifiableIfStatement
|
||||
if (id == R.id.action_deEnroll) {
|
||||
return true;
|
||||
}
|
||||
return super.onOptionsItemSelected(item);
|
||||
}
|
||||
|
||||
public void addListenerOnSetThreasholdButton() {
|
||||
setThreasholdButton = (Button) findViewById(R.id.setThreshold);
|
||||
setThreasholdButton.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View arg0) {
|
||||
String thresholdString = ((EditText) findViewById(R.id.editThreashold)).getText().toString();
|
||||
try{
|
||||
ProcessWords.setThreshold(Integer.parseInt(thresholdString));
|
||||
} catch (NumberFormatException e) {
|
||||
Toast.makeText(WordRecognitionActivity.this, "Invalid Threshold - " + thresholdString, Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void addListenerOnAddWordButton() {
|
||||
addWordButton = (Button) findViewById(R.id.addWord);
|
||||
addWordButton.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View arg0) {
|
||||
String word = ((EditText) findViewById(R.id.wordText)).getText().toString();
|
||||
ProcessWords.addWord(word);
|
||||
Toast.makeText(WordRecognitionActivity.this, word + " is added to the list", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void addListenerOnRemoveWordButton() {
|
||||
removeWordButton = (Button) findViewById(R.id.removeWord);
|
||||
removeWordButton.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View arg0) {
|
||||
String word = ((EditText) findViewById(R.id.wordText)).getText().toString();
|
||||
Toast.makeText(WordRecognitionActivity.this, word + " is removed from the list", Toast.LENGTH_SHORT).show();
|
||||
ProcessWords.removeWord(word);
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
}
|
@ -1,125 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.speech.detector.util;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.speech.RecognizerIntent;
|
||||
import android.speech.SpeechRecognizer;
|
||||
import android.widget.Toast;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.speech.detector.IVoiceControl;
|
||||
|
||||
/**
|
||||
* This Activity Contols the Speech Recognizer Activity.
|
||||
*/
|
||||
public abstract class ListeningActivity extends Activity implements IVoiceControl {
|
||||
|
||||
protected SpeechRecognizer sr;
|
||||
protected Context context;
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the listening service.
|
||||
*/
|
||||
protected void startListening() {
|
||||
initSpeech();
|
||||
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
|
||||
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
|
||||
sr.startListening(intent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop the listening service.
|
||||
*/
|
||||
protected void stopListening() {
|
||||
if (sr != null) {
|
||||
sr.stopListening();
|
||||
sr.cancel();
|
||||
sr.destroy();
|
||||
}
|
||||
sr = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the speech.
|
||||
*/
|
||||
protected void initSpeech() {
|
||||
if (sr == null) {
|
||||
sr = SpeechRecognizer.createSpeechRecognizer(this);
|
||||
if (!SpeechRecognizer.isRecognitionAvailable(context)) {
|
||||
Toast.makeText(context, "Speech Recognition is not available",
|
||||
Toast.LENGTH_LONG).show();
|
||||
finish();
|
||||
}
|
||||
sr.setRecognitionListener(VoiceRecognitionListener.getInstance());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void finish() {
|
||||
stopListening();
|
||||
super.finish();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStop() {
|
||||
stopListening();
|
||||
super.onStop();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
if (sr != null) {
|
||||
sr.stopListening();
|
||||
sr.cancel();
|
||||
sr.destroy();
|
||||
}
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPause() {
|
||||
if(sr!=null){
|
||||
sr.stopListening();
|
||||
sr.cancel();
|
||||
sr.destroy();
|
||||
|
||||
}
|
||||
sr = null;
|
||||
|
||||
super.onPause();
|
||||
}
|
||||
|
||||
/**
|
||||
* Is abstract so the inheriting classes need to implement it. Here you put your code which should be executed once
|
||||
* a command was found
|
||||
*/
|
||||
@Override
|
||||
public abstract void processVoiceCommands(String ... voiceCommands);
|
||||
|
||||
@Override
|
||||
public void restartListeningService() {
|
||||
stopListening();
|
||||
startListening();
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,192 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.speech.detector.util;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.os.AsyncTask;
|
||||
import android.widget.EditText;
|
||||
|
||||
import org.apache.commons.codec.language.Soundex;
|
||||
import org.wso2.carbon.iot.android.sense.util.SenseDataHolder;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import org.tartarus.snowball.ext.englishStemmer;
|
||||
|
||||
import agent.sense.android.iot.carbon.wso2.org.wso2_senseagent.R;
|
||||
|
||||
/**
|
||||
* This class process the words form required words with the recongnized words to check whether it matches with the
|
||||
* certain threshold.
|
||||
*/
|
||||
public class ProcessWords extends AsyncTask<String, Void, String> {
|
||||
private static volatile double threshold = 80;
|
||||
private static volatile Map<String, WordData> wordDataMap = new ConcurrentHashMap<>();
|
||||
private static String sessionId = "default";
|
||||
private static Soundex soundex = new Soundex();
|
||||
Activity activity;
|
||||
|
||||
public ProcessWords(Activity activity) {
|
||||
this.activity = activity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the list of words which are used for reference.
|
||||
* @param wordlist that needs to be looked upon in the speech
|
||||
*/
|
||||
public static void addWords(List<String> wordlist) {
|
||||
for (String word : wordlist) {
|
||||
if (!wordDataMap.keySet().contains(word) && !word.isEmpty()) {
|
||||
wordDataMap.put(word, new WordData(sessionId, word, 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the recognized word list.
|
||||
* @param voiceCommands word lists.
|
||||
*/
|
||||
private void processTexts(String... voiceCommands) {
|
||||
for (String requiredWord : wordDataMap.keySet()) {
|
||||
int maxOccurunce = 0;
|
||||
for (String command : voiceCommands) {
|
||||
int occurence = 0;
|
||||
for (String word : command.split(" ")) {
|
||||
if (StringSimilarity.similarity(requiredWord, word) > threshold) {
|
||||
occurence++;
|
||||
continue;
|
||||
}
|
||||
if (soundex.encode(requiredWord).equals(soundex.encode(word))) {
|
||||
occurence++;
|
||||
continue;
|
||||
}
|
||||
if (StringSimilarity.similarity(requiredWord, stem(word)) > threshold) {
|
||||
occurence++;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (maxOccurunce < occurence) {
|
||||
maxOccurunce = occurence;
|
||||
}
|
||||
}
|
||||
if (maxOccurunce > 0) {
|
||||
WordData wordData = wordDataMap.get(requiredWord);
|
||||
wordData.addOccurences(maxOccurunce);
|
||||
wordDataMap.put(requiredWord, wordData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for distance between the referenced and recognized words.
|
||||
* @param params
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
protected String doInBackground(String... params) {
|
||||
processTexts(params);
|
||||
publishProgress();
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* update it in the UI.
|
||||
* @param values words list.
|
||||
*/
|
||||
@Override
|
||||
protected void onProgressUpdate(Void... values) {
|
||||
super.onProgressUpdate(values);
|
||||
EditText content = (EditText) activity.findViewById(R.id.command);
|
||||
String text = "";
|
||||
for (String key : ProcessWords.wordDataMap.keySet()) {
|
||||
text = text + key + " - " + ProcessWords.wordDataMap.get(key).getOccurences() + "\n";
|
||||
}
|
||||
content.setText(text);
|
||||
EditText thresholdText = (EditText) activity.findViewById(R.id.editThreashold);
|
||||
thresholdText.setText("" + threshold);
|
||||
}
|
||||
|
||||
/**
|
||||
* set the threshold to determine the distance.
|
||||
* @param threshold to determine the distance.
|
||||
*/
|
||||
public static synchronized void setThreshold(int threshold) {
|
||||
ProcessWords.threshold = threshold;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param sessionId for each listening session.
|
||||
*/
|
||||
public static synchronized void setSessionId(String sessionId) {
|
||||
ProcessWords.sessionId = sessionId;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* retrieve sessionId for each listening session.
|
||||
*/
|
||||
public static synchronized String getSessionId() {
|
||||
return ProcessWords.sessionId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param word that is used for refrerence.
|
||||
*/
|
||||
public static synchronized void addWord(String word) {
|
||||
if (!wordDataMap.keySet().contains(word) && !word.isEmpty()) {
|
||||
wordDataMap.put(word, new WordData(sessionId, word, 0));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param word that needs to be removed from the reference list.
|
||||
*/
|
||||
public static synchronized void removeWord(String word) {
|
||||
cleanAndPushToWordMap();
|
||||
wordDataMap.remove(word);
|
||||
}
|
||||
|
||||
/**
|
||||
* clean in memory content and pubish it to the server.
|
||||
*/
|
||||
public static synchronized void cleanAndPushToWordMap() {
|
||||
for (String word : wordDataMap.keySet()) {
|
||||
WordData wordData = wordDataMap.get(word);
|
||||
SenseDataHolder.getWordDataHolder().add(wordData);
|
||||
wordDataMap.put(word, new WordData(sessionId, word, 0));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* apply porter stem algorithm
|
||||
* @param word to be stemmed.
|
||||
* @return
|
||||
*/
|
||||
private static String stem(String word)
|
||||
{
|
||||
englishStemmer stemmer = new englishStemmer();
|
||||
stemmer.setCurrent(word);
|
||||
boolean result = stemmer.stem();
|
||||
if (!result)
|
||||
{
|
||||
return word;
|
||||
}
|
||||
return stemmer.getCurrent();
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -1,67 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.speech.detector.util;
|
||||
|
||||
/**
|
||||
* Calculates the similarity of strings.
|
||||
*/
|
||||
public class StringSimilarity {
|
||||
|
||||
/**
|
||||
* Calculates the similarity (a number within 0 and 1) between two strings.
|
||||
*/
|
||||
public static double similarity(String s1, String s2) {
|
||||
String longer = s1, shorter = s2;
|
||||
if (s1.length() < s2.length()) { // longer should always have greater length
|
||||
longer = s2;
|
||||
shorter = s1;
|
||||
}
|
||||
int longerLength = longer.length();
|
||||
if (longerLength == 0) {
|
||||
return 1.0; /* both strings are zero length */
|
||||
}
|
||||
return ((longerLength - editDistance(longer, shorter)) / (double) longerLength) * 100;
|
||||
}
|
||||
|
||||
// Example implementation of the Levenshtein Edit Distance
|
||||
// See http://rosettacode.org/wiki/Levenshtein_distance#Java
|
||||
private static int editDistance(String s1, String s2) {
|
||||
s1 = s1.toLowerCase();
|
||||
s2 = s2.toLowerCase();
|
||||
|
||||
int[] costs = new int[s2.length() + 1];
|
||||
for (int i = 0; i <= s1.length(); i++) {
|
||||
int lastValue = i;
|
||||
for (int j = 0; j <= s2.length(); j++) {
|
||||
if (i == 0)
|
||||
costs[j] = j;
|
||||
else {
|
||||
if (j > 0) {
|
||||
int newValue = costs[j - 1];
|
||||
if (s1.charAt(i - 1) != s2.charAt(j - 1))
|
||||
newValue = Math.min(Math.min(newValue, lastValue),
|
||||
costs[j]) + 1;
|
||||
costs[j - 1] = lastValue;
|
||||
lastValue = newValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (i > 0)
|
||||
costs[s2.length()] = lastValue;
|
||||
}
|
||||
return costs[s2.length()];
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -1,80 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.speech.detector.util;
|
||||
|
||||
import android.os.Bundle;
|
||||
import android.speech.RecognitionListener;
|
||||
import android.speech.SpeechRecognizer;
|
||||
import org.wso2.carbon.iot.android.sense.speech.detector.IVoiceControl;
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* This triggers android voice recognition listener.
|
||||
*/
|
||||
public class VoiceRecognitionListener implements RecognitionListener {
|
||||
private static VoiceRecognitionListener instance = null;
|
||||
|
||||
IVoiceControl listener; // This is your running activity (we will initialize it later)
|
||||
|
||||
public static VoiceRecognitionListener getInstance() {
|
||||
if (instance == null) {
|
||||
instance = new VoiceRecognitionListener();
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
private VoiceRecognitionListener() { }
|
||||
|
||||
public void setListener(IVoiceControl listener) {
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
public void processVoiceCommands(String... voiceCommands) {
|
||||
listener.processVoiceCommands(voiceCommands);
|
||||
}
|
||||
|
||||
// This method will be executed when voice commands were found
|
||||
public void onResults(Bundle data) {
|
||||
ArrayList<String> matches = data.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
|
||||
String[] commands = new String[matches.size()];
|
||||
commands = matches.toArray(commands);
|
||||
processVoiceCommands(commands);
|
||||
}
|
||||
|
||||
// User starts speaking
|
||||
public void onBeginningOfSpeech() {
|
||||
System.out.println("Starting to listen");
|
||||
}
|
||||
|
||||
public void onBufferReceived(byte[] buffer) { }
|
||||
|
||||
// User finished speaking
|
||||
public void onEndOfSpeech() {
|
||||
System.out.println("Waiting for result...");
|
||||
}
|
||||
|
||||
// If the user said nothing the service will be restarted
|
||||
public void onError(int error) {
|
||||
if (listener != null) {
|
||||
listener.restartListeningService();
|
||||
}
|
||||
}
|
||||
public void onEvent(int eventType, Bundle params) { }
|
||||
|
||||
public void onPartialResults(Bundle partialResults) { }
|
||||
|
||||
public void onReadyForSpeech(Bundle params) { }
|
||||
|
||||
public void onRmsChanged(float rmsdB) { }
|
||||
}
|
@ -1,60 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.speech.detector.util;
|
||||
|
||||
/**
|
||||
* This defines the data structure of the word data.
|
||||
*/
|
||||
public class WordData {
|
||||
/**
|
||||
* timestamp for all the occurences
|
||||
*/
|
||||
private long timestamp;
|
||||
private int occurences;
|
||||
private String word;
|
||||
private String sessionId;
|
||||
|
||||
public WordData(String sessionId, String word, int occurences) {
|
||||
this.timestamp = System.currentTimeMillis() / 1000;
|
||||
this.occurences = occurences;
|
||||
this.word = word;
|
||||
this.sessionId = sessionId;
|
||||
}
|
||||
|
||||
public long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public int getOccurences() {
|
||||
return occurences;
|
||||
}
|
||||
|
||||
public String getWord() {
|
||||
return word;
|
||||
}
|
||||
|
||||
public String getSessionId() {
|
||||
return sessionId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param occurences for the word and then add the timestamp for each occurences.
|
||||
*/
|
||||
public void addOccurences(int occurences) {
|
||||
this.occurences = this.occurences + occurences;
|
||||
this.timestamp = System.currentTimeMillis() / 1000;
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -1,270 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.util;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.util.Log;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.constants.SenseConstants;
|
||||
import org.wso2.carbon.iot.android.sense.data.publisher.mqtt.transport.MQTTTransportHandler;
|
||||
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
|
||||
/**
|
||||
* This is used to store the values in either in memory or in shared preferences.
|
||||
*/
|
||||
public class LocalRegistry {
|
||||
|
||||
private static final String SENSE_SHARED_PREFERENCES = "senseSharedPreferences";
|
||||
private static final String USERNAME_KEY = "usernameKey";
|
||||
private static final String DEVICE_ID_KEY = "deviceIdKey";
|
||||
private static final String SERVER_HOST_KEY = "serverHostKey";
|
||||
private static final String ACCESS_TOKEN_KEY = "accessTokenKey";
|
||||
private static final String REFRESH_TOKEN_KEY = "refreshTokenKey";
|
||||
private static final String MQTT_ENDPOINT_KEY = "mqttEndpointKey";
|
||||
private static final String IS_ENROLLED_KEY = "enrolledKey";
|
||||
private static final String TENANT_DOMAIN_KEY = "tenantDomainKey";
|
||||
private static boolean exists = false;
|
||||
private static String username;
|
||||
private static String deviceId;
|
||||
private static String serverURL;
|
||||
private static MQTTTransportHandler mqttTransportHandler;
|
||||
private static String accessToken;
|
||||
private static String refreshToken;
|
||||
private static String mqttEndpoint;
|
||||
private static boolean enrolled;
|
||||
private static String tenantDomain;
|
||||
|
||||
public static boolean isExist(Context context) {
|
||||
if (!exists) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
String username = sharedpreferences.getString(USERNAME_KEY, "");
|
||||
String deviceId = sharedpreferences.getString(DEVICE_ID_KEY, "");
|
||||
exists = (username != null && !username.isEmpty() && deviceId != null && !deviceId.isEmpty());
|
||||
}
|
||||
return exists;
|
||||
}
|
||||
|
||||
public static void setExist(boolean status) {
|
||||
exists = status;
|
||||
}
|
||||
|
||||
|
||||
public static void addUsername(Context context, String username) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
SharedPreferences.Editor editor = sharedpreferences.edit();
|
||||
editor.putString(USERNAME_KEY, username);
|
||||
editor.commit();
|
||||
LocalRegistry.username = username;
|
||||
}
|
||||
|
||||
public static String getUsername(Context context) {
|
||||
if (LocalRegistry.username == null || username.isEmpty()) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
LocalRegistry.username = sharedpreferences.getString(USERNAME_KEY, "");
|
||||
}
|
||||
return LocalRegistry.username;
|
||||
}
|
||||
|
||||
public static void removeUsername(Context context) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
SharedPreferences.Editor editor = sharedpreferences.edit();
|
||||
editor.clear();
|
||||
editor.remove(USERNAME_KEY);
|
||||
editor.commit();
|
||||
LocalRegistry.username = null;
|
||||
}
|
||||
|
||||
public static void addDeviceId(Context context, String deviceId) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
SharedPreferences.Editor editor = sharedpreferences.edit();
|
||||
editor.putString(DEVICE_ID_KEY, deviceId);
|
||||
editor.commit();
|
||||
LocalRegistry.deviceId = deviceId;
|
||||
}
|
||||
|
||||
public static void removeDeviceId(Context context) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
SharedPreferences.Editor editor = sharedpreferences.edit();
|
||||
editor.remove(DEVICE_ID_KEY);
|
||||
editor.clear();
|
||||
editor.commit();
|
||||
LocalRegistry.deviceId = null;
|
||||
}
|
||||
|
||||
public static String getDeviceId(Context context) {
|
||||
if (LocalRegistry.deviceId == null || LocalRegistry.deviceId.isEmpty()) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
LocalRegistry.deviceId = sharedpreferences.getString(DEVICE_ID_KEY, "");
|
||||
}
|
||||
return LocalRegistry.deviceId;
|
||||
}
|
||||
|
||||
public static void addServerURL(Context context, String host) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
SharedPreferences.Editor editor = sharedpreferences.edit();
|
||||
editor.putString(SERVER_HOST_KEY, host);
|
||||
editor.commit();
|
||||
LocalRegistry.serverURL = host;
|
||||
}
|
||||
|
||||
public static void removeServerURL(Context context) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
SharedPreferences.Editor editor = sharedpreferences.edit();
|
||||
editor.remove(SERVER_HOST_KEY);
|
||||
editor.clear();
|
||||
editor.commit();
|
||||
LocalRegistry.serverURL = null;
|
||||
}
|
||||
|
||||
public static String getServerURL(Context context) {
|
||||
if (LocalRegistry.serverURL == null || LocalRegistry.serverURL.isEmpty()) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
LocalRegistry.serverURL = sharedpreferences.getString(SERVER_HOST_KEY, "");
|
||||
}
|
||||
return LocalRegistry.serverURL;
|
||||
}
|
||||
|
||||
public static void addAccessToken(Context context, String accessToken) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
SharedPreferences.Editor editor = sharedpreferences.edit();
|
||||
editor.putString(ACCESS_TOKEN_KEY, accessToken);
|
||||
editor.commit();
|
||||
LocalRegistry.accessToken = accessToken;
|
||||
}
|
||||
|
||||
public static void removeAccessToken(Context context) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
SharedPreferences.Editor editor = sharedpreferences.edit();
|
||||
editor.remove(ACCESS_TOKEN_KEY);
|
||||
editor.clear();
|
||||
editor.commit();
|
||||
LocalRegistry.accessToken = null;
|
||||
}
|
||||
|
||||
public static String getAccessToken(Context context) {
|
||||
if (LocalRegistry.accessToken == null || LocalRegistry.accessToken.isEmpty()) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
LocalRegistry.accessToken = sharedpreferences.getString(ACCESS_TOKEN_KEY, "");
|
||||
}
|
||||
return LocalRegistry.accessToken;
|
||||
}
|
||||
|
||||
public static void addRefreshToken(Context context, String refreshToken) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
SharedPreferences.Editor editor = sharedpreferences.edit();
|
||||
editor.putString(REFRESH_TOKEN_KEY, refreshToken);
|
||||
editor.commit();
|
||||
LocalRegistry.refreshToken = refreshToken;
|
||||
}
|
||||
|
||||
public static void removeRefreshToken(Context context) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
SharedPreferences.Editor editor = sharedpreferences.edit();
|
||||
editor.remove(REFRESH_TOKEN_KEY);
|
||||
editor.clear();
|
||||
editor.commit();
|
||||
LocalRegistry.refreshToken = null;
|
||||
}
|
||||
|
||||
public static String getRefreshToken(Context context) {
|
||||
if (LocalRegistry.refreshToken == null || LocalRegistry.refreshToken.isEmpty()) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
LocalRegistry.refreshToken = sharedpreferences.getString(REFRESH_TOKEN_KEY, "");
|
||||
}
|
||||
return LocalRegistry.refreshToken;
|
||||
}
|
||||
|
||||
public static void addMqttEndpoint(Context context, String endpoint) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
SharedPreferences.Editor editor = sharedpreferences.edit();
|
||||
editor.putString(MQTT_ENDPOINT_KEY, endpoint);
|
||||
editor.commit();
|
||||
LocalRegistry.mqttEndpoint = endpoint;
|
||||
}
|
||||
|
||||
public static void removeMqttEndpoint(Context context) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
SharedPreferences.Editor editor = sharedpreferences.edit();
|
||||
editor.remove(MQTT_ENDPOINT_KEY);
|
||||
editor.clear();
|
||||
editor.commit();
|
||||
LocalRegistry.mqttEndpoint = null;
|
||||
}
|
||||
|
||||
public static String getMqttEndpoint(Context context) {
|
||||
if (LocalRegistry.mqttEndpoint == null) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
LocalRegistry.mqttEndpoint = sharedpreferences.getString(MQTT_ENDPOINT_KEY, "");
|
||||
}
|
||||
return LocalRegistry.mqttEndpoint;
|
||||
}
|
||||
|
||||
public static void setEnrolled(Context context, boolean enrolled) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
SharedPreferences.Editor editor = sharedpreferences.edit();
|
||||
editor.putBoolean(IS_ENROLLED_KEY, enrolled);
|
||||
editor.commit();
|
||||
LocalRegistry.enrolled = enrolled;
|
||||
}
|
||||
|
||||
public static boolean isEnrolled(Context context) {
|
||||
if (!LocalRegistry.enrolled) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
return LocalRegistry.enrolled = sharedpreferences.getBoolean(IS_ENROLLED_KEY, false);
|
||||
}
|
||||
return LocalRegistry.enrolled;
|
||||
}
|
||||
|
||||
public static void addTenantDomain(Context context, String tenantDomain) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
SharedPreferences.Editor editor = sharedpreferences.edit();
|
||||
editor.putString(TENANT_DOMAIN_KEY, tenantDomain);
|
||||
editor.commit();
|
||||
LocalRegistry.tenantDomain = tenantDomain;
|
||||
}
|
||||
|
||||
public static void removeTenantDomain(Context context) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
SharedPreferences.Editor editor = sharedpreferences.edit();
|
||||
editor.remove(TENANT_DOMAIN_KEY);
|
||||
editor.clear();
|
||||
editor.commit();
|
||||
LocalRegistry.tenantDomain = null;
|
||||
}
|
||||
|
||||
public static String getTenantDomain(Context context) {
|
||||
if (LocalRegistry.tenantDomain == null) {
|
||||
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
LocalRegistry.tenantDomain = sharedpreferences.getString(TENANT_DOMAIN_KEY, "");
|
||||
}
|
||||
return LocalRegistry.tenantDomain;
|
||||
}
|
||||
|
||||
public static String getServerHost(Context context) {
|
||||
|
||||
URL url = null;
|
||||
String urlString = getServerURL(context);
|
||||
try {
|
||||
url = new URL(urlString);
|
||||
return url.getHost();
|
||||
} catch (MalformedURLException e) {
|
||||
Log.e("Host ", "Invalid urlString :" + urlString);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,82 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.util;
|
||||
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
import android.widget.Toast;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.constants.SenseConstants;
|
||||
import org.wso2.carbon.iot.android.sense.util.dto.RegisterInfo;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.logging.Handler;
|
||||
|
||||
/**
|
||||
* This Client is used for http communication with the server.
|
||||
*/
|
||||
public class SenseClient {
|
||||
private final static String TAG = "SenseService Client";
|
||||
|
||||
private Context context;
|
||||
|
||||
public SenseClient(Context context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enroll the device.
|
||||
*
|
||||
* @param username
|
||||
* @param password
|
||||
* @param deviceId
|
||||
* @return
|
||||
*/
|
||||
public RegisterInfo register(String username, String password, String deviceId, android.os.Handler mUiHandler) {
|
||||
Map<String, String> response = registerWithTimeWait(username, password, deviceId);
|
||||
String responseStatus = response.get("status");
|
||||
RegisterInfo registerInfo = new RegisterInfo();
|
||||
if (responseStatus.trim().contains(SenseConstants.Request.REQUEST_SUCCESSFUL)) {
|
||||
registerInfo.setMsg("Login Successful");
|
||||
registerInfo.setIsRegistered(true);
|
||||
return registerInfo;
|
||||
} else {
|
||||
registerInfo.setMsg("Authentication failed, please check your credentials and try again.");
|
||||
registerInfo.setIsRegistered(false);
|
||||
return registerInfo;
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, String> registerWithTimeWait(String username, String password, String deviceId) {
|
||||
try {
|
||||
SenseClientAsyncExecutor senseClientAsyncExecutor = new SenseClientAsyncExecutor(context);
|
||||
String endpoint = LocalRegistry.getServerURL(context);
|
||||
senseClientAsyncExecutor.execute(username, password, deviceId, endpoint);
|
||||
Map<String, String> response = senseClientAsyncExecutor.get();
|
||||
if (response != null) {
|
||||
return response;
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
Log.e("Send Sensor Data", "Thread Interruption for endpoint " + LocalRegistry.getServerURL(context));
|
||||
} catch (ExecutionException e) {
|
||||
Log.e("Send Sensor Data", "Failed to push data to the endpoint " + LocalRegistry.getServerURL(context));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
@ -1,154 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.util;
|
||||
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.AsyncTask;
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.constants.SenseConstants;
|
||||
import org.wso2.carbon.iot.android.sense.util.dto.AccessTokenInfo;
|
||||
import org.wso2.carbon.iot.android.sense.util.dto.AndroidConfiguration;
|
||||
import org.wso2.carbon.iot.android.sense.util.dto.AndroidSenseManagerService;
|
||||
import org.wso2.carbon.iot.android.sense.util.dto.ApiApplicationKey;
|
||||
import org.wso2.carbon.iot.android.sense.util.dto.ApiApplicationRegistrationService;
|
||||
import org.wso2.carbon.iot.android.sense.util.dto.ApiRegistrationProfile;
|
||||
import org.wso2.carbon.iot.android.sense.util.dto.DynamicClientRegistrationService;
|
||||
import org.wso2.carbon.iot.android.sense.util.dto.OAuthApplicationInfo;
|
||||
import org.wso2.carbon.iot.android.sense.util.dto.OAuthRequestInterceptor;
|
||||
import org.wso2.carbon.iot.android.sense.util.dto.RegistrationProfile;
|
||||
import org.wso2.carbon.iot.android.sense.util.dto.TokenIssuerService;
|
||||
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.net.ssl.HostnameVerifier;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLSession;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
|
||||
import feign.Client;
|
||||
import feign.Feign;
|
||||
import feign.FeignException;
|
||||
import feign.auth.BasicAuthRequestInterceptor;
|
||||
import feign.jackson.JacksonDecoder;
|
||||
import feign.jackson.JacksonEncoder;
|
||||
import feign.jaxrs.JAXRSContract;
|
||||
|
||||
public class SenseClientAsyncExecutor extends AsyncTask<String, Void, Map<String, String>> {
|
||||
|
||||
private final static String TAG = "SenseService Client";
|
||||
private static final String STATUS = "status";
|
||||
private final String PASSWORD_GRANT_TYPE = "password";
|
||||
private final String SCOPE = "perm:android-sense:enroll";
|
||||
private final static String DEVICE_NAME = Build.MANUFACTURER + " " + Build.MODEL;
|
||||
private Context context;
|
||||
|
||||
public SenseClientAsyncExecutor(Context context) {
|
||||
this.context = context;
|
||||
|
||||
}
|
||||
|
||||
TrustManager[] trustAllCerts = new TrustManager[]{
|
||||
new X509TrustManager() {
|
||||
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
|
||||
return null;
|
||||
}
|
||||
public void checkClientTrusted(
|
||||
java.security.cert.X509Certificate[] certs, String authType) {
|
||||
}
|
||||
public void checkServerTrusted(
|
||||
java.security.cert.X509Certificate[] certs, String authType) {
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Client disableHostnameVerification = new Client.Default(getTrustedSSLSocketFactory(), new HostnameVerifier() {
|
||||
@Override
|
||||
public boolean verify(String s, SSLSession sslSession) {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
@Override
|
||||
protected Map<String, String> doInBackground(String... parameters) {
|
||||
if (android.os.Debug.isDebuggerConnected())
|
||||
android.os.Debug.waitForDebugger();
|
||||
String response;
|
||||
Map<String, String> response_params = new HashMap<>();
|
||||
String username = parameters[0];
|
||||
String password = parameters[1];
|
||||
String deviceId = parameters[2];
|
||||
String endpoint = parameters[3];
|
||||
Map<String, String> responseMap = new HashMap<>();
|
||||
responseMap.put(STATUS, "200");
|
||||
AccessTokenInfo accessTokenInfo = null;
|
||||
try {
|
||||
//ApiApplicationRegistration
|
||||
ApiApplicationRegistrationService apiApplicationRegistrationService = Feign.builder().client(disableHostnameVerification)
|
||||
.requestInterceptor(new BasicAuthRequestInterceptor(username, password))
|
||||
.contract(new JAXRSContract()).encoder(new JacksonEncoder()).decoder(new JacksonDecoder())
|
||||
.target(ApiApplicationRegistrationService.class, endpoint + SenseConstants.API_APPLICATION_REGISTRATION_CONTEXT);
|
||||
ApiRegistrationProfile apiRegistrationProfile = new ApiRegistrationProfile();
|
||||
apiRegistrationProfile.setApplicationName("android_sense_" + deviceId);
|
||||
apiRegistrationProfile.setIsAllowedToAllDomains(false);
|
||||
apiRegistrationProfile.setIsMappingAnExistingOAuthApp(false);
|
||||
apiRegistrationProfile.setTags(new String[]{SenseConstants.DEVICE_TYPE});
|
||||
ApiApplicationKey apiApplicationKey = apiApplicationRegistrationService.register(apiRegistrationProfile);
|
||||
|
||||
//PasswordGrantType
|
||||
TokenIssuerService tokenIssuerService = Feign.builder().client(disableHostnameVerification).requestInterceptor(
|
||||
new BasicAuthRequestInterceptor(apiApplicationKey.getConsumerKey(), apiApplicationKey.getConsumerSecret()))
|
||||
.contract(new JAXRSContract()).encoder(new JacksonEncoder()).decoder(new JacksonDecoder())
|
||||
.target(TokenIssuerService.class, endpoint);
|
||||
accessTokenInfo = tokenIssuerService.getToken(PASSWORD_GRANT_TYPE, username, password, "device_"
|
||||
+ deviceId + " " + SCOPE);
|
||||
|
||||
//DeviceRegister
|
||||
AndroidSenseManagerService androidSenseManagerService = Feign.builder().client(disableHostnameVerification)
|
||||
.requestInterceptor(new OAuthRequestInterceptor(accessTokenInfo.getAccess_token()))
|
||||
.contract(new JAXRSContract()).encoder(new JacksonEncoder()).decoder(new JacksonDecoder())
|
||||
.target(AndroidSenseManagerService.class, endpoint + SenseConstants.REGISTER_CONTEXT);
|
||||
AndroidConfiguration androidConfiguration = androidSenseManagerService.register(deviceId, DEVICE_NAME);
|
||||
if (androidConfiguration != null) {
|
||||
LocalRegistry.addAccessToken(context, accessTokenInfo.getAccess_token());
|
||||
LocalRegistry.addRefreshToken(context, accessTokenInfo.getRefresh_token());
|
||||
LocalRegistry.addMqttEndpoint(context, androidConfiguration.getMqttEndpoint());
|
||||
LocalRegistry.addTenantDomain(context, androidConfiguration.getTenantDomain());
|
||||
}
|
||||
return responseMap;
|
||||
} catch (FeignException e) {
|
||||
responseMap.put(STATUS, "" + e.status());
|
||||
return responseMap;
|
||||
}
|
||||
}
|
||||
|
||||
private SSLSocketFactory getTrustedSSLSocketFactory() {
|
||||
try {
|
||||
SSLContext sc = SSLContext.getInstance("SSL");
|
||||
sc.init(null, trustAllCerts, new java.security.SecureRandom());
|
||||
return sc.getSocketFactory();
|
||||
} catch (KeyManagementException | NoSuchAlgorithmException e) {
|
||||
Log.e(SenseClientAsyncExecutor.class.getName(), "Invalid Certificate");
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -1,204 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.util;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.beacon.BeaconScanedData;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.location.LocationData;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.sensor.SensorData;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.speed.SpeedData;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.activity.ActivityData;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.application.ApplicationData;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.audio.AudioData;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.battery.BatteryData;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.call.CallData;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.data.NetworkData;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.screen.ScreenData;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.sms.SmsData;
|
||||
import org.wso2.carbon.iot.android.sense.speech.detector.util.WordData;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
|
||||
/**
|
||||
* This holds the sensor,battery and location data inmemory.
|
||||
*/
|
||||
public class SenseDataHolder {
|
||||
|
||||
private static List<SensorData> sensorDataHolder;
|
||||
private static List<BatteryData> batteryDataHolder;
|
||||
private static List<CallData> callDataHolder;
|
||||
private static List<LocationData> locationDataHolder;
|
||||
private static List<WordData> wordDataHolder;
|
||||
private static List<SpeedData> speedDataHolder;
|
||||
private static List<BeaconScanedData> beaconScanedDataHolder;
|
||||
private static List<ScreenData> screenDataHolder;
|
||||
private static List<AudioData> audioDataHolder;
|
||||
private static List<ActivityData> activityDataHolder;
|
||||
private static List<SmsData> smsDataHolder;
|
||||
private static List<ApplicationData> applicationDataHolder;
|
||||
private static List<NetworkData> networkDataHolder;
|
||||
//LocationData gps;
|
||||
|
||||
|
||||
private static final String TAG = SenseDataHolder.class.getName();
|
||||
|
||||
|
||||
public static List<SensorData> getSensorDataHolder() {
|
||||
if (sensorDataHolder == null) {
|
||||
sensorDataHolder = new CopyOnWriteArrayList<>();
|
||||
}
|
||||
return sensorDataHolder;
|
||||
}
|
||||
|
||||
public static List<BatteryData> getBatteryDataHolder() {
|
||||
if (batteryDataHolder == null) {
|
||||
batteryDataHolder = new CopyOnWriteArrayList<>();
|
||||
}
|
||||
return batteryDataHolder;
|
||||
}
|
||||
|
||||
public static List<CallData> getCallDataHolder() {
|
||||
if (callDataHolder == null) {
|
||||
callDataHolder = new CopyOnWriteArrayList<>();
|
||||
}
|
||||
return callDataHolder;
|
||||
}
|
||||
|
||||
public static List<LocationData> getLocationDataHolder() {
|
||||
|
||||
|
||||
if (locationDataHolder == null) {
|
||||
|
||||
locationDataHolder = new CopyOnWriteArrayList<>();
|
||||
}
|
||||
return locationDataHolder;
|
||||
|
||||
}
|
||||
|
||||
public static List<WordData> getWordDataHolder() {
|
||||
if (wordDataHolder == null) {
|
||||
wordDataHolder = new CopyOnWriteArrayList<>();
|
||||
}
|
||||
return wordDataHolder;
|
||||
}
|
||||
|
||||
public static List<SpeedData> getSpeedDataHolder() {
|
||||
if (speedDataHolder == null) {
|
||||
speedDataHolder = new CopyOnWriteArrayList<>();
|
||||
}
|
||||
return speedDataHolder;
|
||||
}
|
||||
|
||||
public static List<BeaconScanedData> getBeaconScanedDataHolder() {
|
||||
if (beaconScanedDataHolder == null) {
|
||||
beaconScanedDataHolder = new CopyOnWriteArrayList<>();
|
||||
}
|
||||
return beaconScanedDataHolder;
|
||||
}
|
||||
|
||||
public static List<ScreenData> getScreenDataHolder() {
|
||||
if (screenDataHolder == null) {
|
||||
screenDataHolder = new CopyOnWriteArrayList<>();
|
||||
}
|
||||
return screenDataHolder;
|
||||
}
|
||||
|
||||
public static List<AudioData> getAudioDataHolder() {
|
||||
if (audioDataHolder == null) {
|
||||
audioDataHolder = new CopyOnWriteArrayList<>();
|
||||
}
|
||||
return audioDataHolder;
|
||||
}
|
||||
|
||||
public static List<ActivityData> getActivityDataHolder() {
|
||||
if (activityDataHolder == null) {
|
||||
activityDataHolder = new CopyOnWriteArrayList<>();
|
||||
}
|
||||
return activityDataHolder;
|
||||
}
|
||||
|
||||
public static List<SmsData> getSmsDataHolder() {
|
||||
if (smsDataHolder == null) {
|
||||
smsDataHolder = new CopyOnWriteArrayList<>();
|
||||
}
|
||||
return smsDataHolder;
|
||||
}
|
||||
|
||||
public static List<ApplicationData> getApplicationDataHolder() {
|
||||
if (applicationDataHolder == null) {
|
||||
applicationDataHolder = new CopyOnWriteArrayList<>();
|
||||
}
|
||||
return applicationDataHolder;
|
||||
}
|
||||
|
||||
public static List<NetworkData> getNetworkDataHolder() {
|
||||
if (networkDataHolder == null) {
|
||||
networkDataHolder = new CopyOnWriteArrayList<>();
|
||||
}
|
||||
return networkDataHolder;
|
||||
}
|
||||
|
||||
public static void resetSensorDataHolder() {
|
||||
sensorDataHolder = null;
|
||||
}
|
||||
|
||||
public static void resetBatteryDataHolder() {
|
||||
batteryDataHolder = null;
|
||||
}
|
||||
|
||||
public static void resetCallDataHolder() {
|
||||
callDataHolder = null;
|
||||
}
|
||||
|
||||
public static void resetLocationDataHolder() {
|
||||
locationDataHolder = null;
|
||||
}
|
||||
|
||||
public static void resetWordDataHolder() {
|
||||
wordDataHolder = null;
|
||||
}
|
||||
|
||||
public static void resetSpeedDataHolder() {
|
||||
speedDataHolder = null;
|
||||
}
|
||||
|
||||
public static void resetBeaconScanedDataHolder() {
|
||||
beaconScanedDataHolder = null;
|
||||
}
|
||||
|
||||
public static void resetScreenDataHolder() {
|
||||
screenDataHolder = null;
|
||||
}
|
||||
|
||||
public static void resetAudioDataHolder() {
|
||||
audioDataHolder = null;
|
||||
}
|
||||
|
||||
public static void resetActivityDataHolder() {
|
||||
activityDataHolder = null;
|
||||
}
|
||||
|
||||
public static void resetSmsDataHolder() {
|
||||
smsDataHolder = null;
|
||||
}
|
||||
|
||||
public static void resetApplicationDataHolder() {
|
||||
applicationDataHolder = null;
|
||||
}
|
||||
|
||||
public static void resetNetworkDataHolder() {
|
||||
networkDataHolder = null;
|
||||
}
|
||||
}
|
@ -1,197 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.util;
|
||||
|
||||
import android.app.PendingIntent;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.os.Bundle;
|
||||
import android.provider.Telephony;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.telephony.TelephonyManager;
|
||||
|
||||
import com.google.android.gms.common.api.GoogleApiClient;
|
||||
import com.google.android.gms.location.ActivityRecognition;
|
||||
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.activity.ActivityReceiver;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.application.ApplicationDataReceiver;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.battery.BatteryDataReceiver;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.call.CallDataReceiver;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.data.NetworkDataReader;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.screen.ScreenDataReceiver;
|
||||
import org.wso2.carbon.iot.android.sense.event.streams.sms.SmsDataReceiver;
|
||||
|
||||
public class SenseDataReceiverManager {
|
||||
private static BroadcastReceiver batteryDataReceiver;
|
||||
|
||||
private static BroadcastReceiver screenDataReceiver;
|
||||
|
||||
private static BroadcastReceiver callDataReceiver;
|
||||
|
||||
private static GoogleApiClient apiClient;
|
||||
|
||||
private static SmsDataReceiver smsDataReceiver;
|
||||
|
||||
private static ApplicationDataReceiver appDataReceiver;
|
||||
|
||||
private static NetworkDataReader networkDataReader;
|
||||
|
||||
private SenseDataReceiverManager() {
|
||||
|
||||
}
|
||||
|
||||
public static void registerBatteryDataReceiver(Context context) {
|
||||
if (batteryDataReceiver == null) {
|
||||
batteryDataReceiver = new BatteryDataReceiver();
|
||||
IntentFilter intentFilter = new IntentFilter();
|
||||
intentFilter.addAction(Intent.ACTION_BATTERY_LOW);
|
||||
intentFilter.addAction(Intent.ACTION_BATTERY_OKAY);
|
||||
intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
|
||||
|
||||
context.registerReceiver(batteryDataReceiver, intentFilter);
|
||||
}
|
||||
}
|
||||
|
||||
public static void unregisterBatteryDataReceiver(Context context) {
|
||||
if (batteryDataReceiver != null) {
|
||||
context.unregisterReceiver(batteryDataReceiver);
|
||||
batteryDataReceiver = null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void registerScreenDataReceiver(Context context) {
|
||||
if (screenDataReceiver == null) {
|
||||
screenDataReceiver = new ScreenDataReceiver();
|
||||
IntentFilter intentFilter = new IntentFilter();
|
||||
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
|
||||
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
|
||||
|
||||
context.registerReceiver(screenDataReceiver, intentFilter);
|
||||
}
|
||||
}
|
||||
|
||||
public static void unregisterScreenDataReceiver(Context context) {
|
||||
if (screenDataReceiver != null) {
|
||||
context.unregisterReceiver(screenDataReceiver);
|
||||
screenDataReceiver = null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void registerCallDataReceiver(Context context) {
|
||||
if (callDataReceiver == null) {
|
||||
callDataReceiver = new CallDataReceiver();
|
||||
IntentFilter intentFilter = new IntentFilter();
|
||||
intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
|
||||
intentFilter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);
|
||||
intentFilter.setPriority(1000);
|
||||
|
||||
context.registerReceiver(callDataReceiver, intentFilter);
|
||||
}
|
||||
}
|
||||
|
||||
public static void unregisterCallDataReceiver(Context context) {
|
||||
if (callDataReceiver != null) {
|
||||
context.unregisterReceiver(callDataReceiver);
|
||||
callDataReceiver = null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void registerActivityDataReceiver(Context context) {
|
||||
if (apiClient == null) {
|
||||
Intent intent = new Intent(context, ActivityReceiver.class);
|
||||
final PendingIntent pendingIntent = PendingIntent.getService(context, 888971, intent, PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
apiClient = new GoogleApiClient.Builder(context)
|
||||
.addApi(ActivityRecognition.API)
|
||||
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
|
||||
@Override
|
||||
public void onConnected(@Nullable Bundle bundle) {
|
||||
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(apiClient, ActivityReceiver.UPDATE_INTERVAL, pendingIntent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onConnectionSuspended(int i) {
|
||||
ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates(apiClient, pendingIntent);
|
||||
}
|
||||
})
|
||||
.build();
|
||||
|
||||
apiClient.connect();
|
||||
}
|
||||
}
|
||||
|
||||
public static void unregisterActivityDataReceiver(Context context) {
|
||||
if (apiClient != null) {
|
||||
apiClient.disconnect();
|
||||
apiClient = null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void registerSmsDataReceiver(Context context) {
|
||||
if (smsDataReceiver == null) {
|
||||
smsDataReceiver = new SmsDataReceiver();
|
||||
IntentFilter intentFilter = new IntentFilter();
|
||||
intentFilter.addAction(Telephony.Sms.Intents.SMS_RECEIVED_ACTION);
|
||||
intentFilter.addAction(Telephony.Sms.Intents.SMS_DELIVER_ACTION);
|
||||
intentFilter.setPriority(1000);
|
||||
context.registerReceiver(smsDataReceiver, intentFilter);
|
||||
}
|
||||
}
|
||||
|
||||
public static void unregisterSmsDataReceiver(Context context) {
|
||||
if (smsDataReceiver != null) {
|
||||
context.unregisterReceiver(smsDataReceiver);
|
||||
smsDataReceiver = null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void registerAppDataReceiver(Context context) {
|
||||
if (appDataReceiver == null) {
|
||||
appDataReceiver = new ApplicationDataReceiver();
|
||||
IntentFilter intentFilter = new IntentFilter();
|
||||
intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
|
||||
intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
|
||||
context.registerReceiver(appDataReceiver, intentFilter);
|
||||
}
|
||||
}
|
||||
|
||||
public static void unregisterAppDataReceiver(Context context) {
|
||||
if (appDataReceiver != null) {
|
||||
context.unregisterReceiver(appDataReceiver);
|
||||
appDataReceiver = null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void registerNetworkDataReader(Context context) {
|
||||
if (networkDataReader == null) {
|
||||
networkDataReader = new NetworkDataReader(context);
|
||||
networkDataReader.execute();
|
||||
}
|
||||
}
|
||||
|
||||
public static void unregisterNetworkDataReader() {
|
||||
if (networkDataReader != null) {
|
||||
networkDataReader.cancel(true);
|
||||
}
|
||||
networkDataReader = null;
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -1,46 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.util;
|
||||
|
||||
|
||||
import android.content.ContentResolver;
|
||||
import android.content.Context;
|
||||
import android.telephony.TelephonyManager;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class SenseUtils {
|
||||
|
||||
/**
|
||||
* this generate the device Id
|
||||
*
|
||||
* @param baseContext
|
||||
* @param contentResolver
|
||||
* @return
|
||||
*/
|
||||
//http://stackoverflow.com/questions/2785485/is-there-a-unique-android-device-id
|
||||
public static String generateDeviceId(Context baseContext, ContentResolver contentResolver) {
|
||||
|
||||
final TelephonyManager tm = (TelephonyManager) baseContext.getSystemService(Context.TELEPHONY_SERVICE);
|
||||
|
||||
final String tmDevice, tmSerial, androidId;
|
||||
tmDevice = String.valueOf(tm.getDeviceId());
|
||||
tmSerial = String.valueOf(tm.getSimSerialNumber());
|
||||
androidId = String.valueOf(android.provider.Settings.Secure.getString(contentResolver, android.provider.Settings.Secure.ANDROID_ID));
|
||||
|
||||
UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
|
||||
return deviceUuid.toString();
|
||||
|
||||
}
|
||||
}
|
@ -1,47 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.util;
|
||||
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.PowerManager;
|
||||
import android.util.Log;
|
||||
|
||||
/**
|
||||
* It doesnt let the phone goto sleep.
|
||||
*/
|
||||
public class SenseWakeLock {
|
||||
|
||||
private static PowerManager.WakeLock wakeLock;
|
||||
private static String TAG = "Wake Lock";
|
||||
|
||||
public static void acquireWakeLock(Context context) {
|
||||
Log.i(SenseWakeLock.class.getSimpleName(), "Acquire CPU wakeup lock start");
|
||||
if (wakeLock == null) {
|
||||
Log.i(TAG, "CPU wakeUp log is not null");
|
||||
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
|
||||
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "SenseWakeLock");
|
||||
}
|
||||
wakeLock.acquire();
|
||||
}
|
||||
|
||||
public static void releaseCPUWakeLock() {
|
||||
if (wakeLock != null) {
|
||||
wakeLock.release();
|
||||
wakeLock = null;
|
||||
}
|
||||
Log.i(TAG, "Release wakeup");
|
||||
}
|
||||
|
||||
}
|
@ -1,57 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.util.dto;
|
||||
|
||||
/**
|
||||
* This hold access token info that returned from the api call
|
||||
*/
|
||||
public class AccessTokenInfo {
|
||||
public String token_type;
|
||||
public String expires_in;
|
||||
public String refresh_token;
|
||||
public String access_token;
|
||||
|
||||
public String getToken_type() {
|
||||
return token_type;
|
||||
}
|
||||
|
||||
public void setToken_type(String token_type) {
|
||||
this.token_type = token_type;
|
||||
}
|
||||
|
||||
public String getExpires_in() {
|
||||
return expires_in;
|
||||
}
|
||||
|
||||
public void setExpires_in(String expires_in) {
|
||||
this.expires_in = expires_in;
|
||||
}
|
||||
|
||||
public String getRefresh_token() {
|
||||
return refresh_token;
|
||||
}
|
||||
|
||||
public void setRefresh_token(String refresh_token) {
|
||||
this.refresh_token = refresh_token;
|
||||
}
|
||||
|
||||
public String getAccess_token() {
|
||||
return access_token;
|
||||
}
|
||||
|
||||
public void setAccess_token(String access_token) {
|
||||
this.access_token = access_token;
|
||||
}
|
||||
}
|
@ -1,43 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.util.dto;
|
||||
|
||||
/**
|
||||
* This holds the required configuration for agent to connect to the server.
|
||||
*/
|
||||
public class AndroidConfiguration {
|
||||
|
||||
public String tenantDomain;
|
||||
public String mqttEndpoint;
|
||||
|
||||
public String getTenantDomain() {
|
||||
return tenantDomain;
|
||||
}
|
||||
|
||||
public void setTenantDomain(String tenantDomain) {
|
||||
this.tenantDomain = tenantDomain;
|
||||
}
|
||||
|
||||
public String getMqttEndpoint() {
|
||||
return mqttEndpoint;
|
||||
}
|
||||
|
||||
public void setMqttEndpoint(String mqttEndpoint) {
|
||||
this.mqttEndpoint = mqttEndpoint;
|
||||
}
|
||||
}
|
@ -1,30 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.util.dto;
|
||||
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.QueryParam;
|
||||
|
||||
/**
|
||||
* This holds the android manager service definition that is used with netflix feign.
|
||||
*/
|
||||
public interface AndroidSenseManagerService {
|
||||
|
||||
@Path("/device/{device_id}/register")
|
||||
@POST
|
||||
AndroidConfiguration register(@PathParam("device_id") String deviceId, @QueryParam("deviceName") String deviceName);
|
||||
}
|
@ -1,43 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.util.dto;
|
||||
|
||||
/**
|
||||
* This holds api application consumer key and secret.
|
||||
*/
|
||||
public class ApiApplicationKey {
|
||||
private String client_id;
|
||||
private String client_secret;
|
||||
|
||||
public String getConsumerKey() {
|
||||
return this.client_id;
|
||||
}
|
||||
|
||||
public void setClient_id(String consumerKey) {
|
||||
this.client_id = consumerKey;
|
||||
}
|
||||
|
||||
public String getConsumerSecret() {
|
||||
return this.client_secret;
|
||||
}
|
||||
|
||||
public void setClient_secret(String consumerSecret) {
|
||||
this.client_secret = consumerSecret;
|
||||
}
|
||||
}
|
@ -1,25 +0,0 @@
|
||||
package org.wso2.carbon.iot.android.sense.util.dto;
|
||||
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
|
||||
/**
|
||||
* This is the application registration service that exposed for apimApplicationRegistration
|
||||
*/
|
||||
|
||||
@Path("/register")
|
||||
public interface ApiApplicationRegistrationService {
|
||||
|
||||
/**
|
||||
* This method is used to register api application
|
||||
*
|
||||
* @param registrationProfile contains the necessary attributes that are needed in order to register an app.
|
||||
*/
|
||||
@POST
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
ApiApplicationKey register(ApiRegistrationProfile registrationProfile);
|
||||
}
|
@ -1,78 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.util.dto;
|
||||
|
||||
|
||||
/**
|
||||
* This class represents the data that are required to register
|
||||
* the oauth application.
|
||||
*/
|
||||
public class ApiRegistrationProfile {
|
||||
|
||||
public String applicationName;
|
||||
public String tags[];
|
||||
public boolean isAllowedToAllDomains;
|
||||
public String consumerKey;
|
||||
public String consumerSecret;
|
||||
public boolean isMappingAnExistingOAuthApp;
|
||||
|
||||
public String getApplicationName() {
|
||||
return applicationName;
|
||||
}
|
||||
|
||||
public void setApplicationName(String applicationName) {
|
||||
this.applicationName = applicationName;
|
||||
}
|
||||
|
||||
public String[] getTags() {
|
||||
return tags;
|
||||
}
|
||||
|
||||
public void setTags(String[] tags) {
|
||||
this.tags = tags;
|
||||
}
|
||||
|
||||
public boolean isAllowedToAllDomains() {
|
||||
return isAllowedToAllDomains;
|
||||
}
|
||||
|
||||
public void setIsAllowedToAllDomains(boolean isAllowedToAllDomains) {
|
||||
this.isAllowedToAllDomains = isAllowedToAllDomains;
|
||||
}
|
||||
|
||||
public boolean isMappingAnExistingOAuthApp() {
|
||||
return isMappingAnExistingOAuthApp;
|
||||
}
|
||||
|
||||
public void setIsMappingAnExistingOAuthApp(boolean isMappingAnExistingOAuthApp) {
|
||||
this.isMappingAnExistingOAuthApp = isMappingAnExistingOAuthApp;
|
||||
}
|
||||
|
||||
public String getConsumerKey() {
|
||||
return consumerKey;
|
||||
}
|
||||
|
||||
public void setConsumerKey(String consumerKey) {
|
||||
this.consumerKey = consumerKey;
|
||||
}
|
||||
|
||||
public String getConsumerSecret() {
|
||||
return consumerSecret;
|
||||
}
|
||||
|
||||
public void setConsumerSecret(String consumerSecret) {
|
||||
this.consumerSecret = consumerSecret;
|
||||
}
|
||||
}
|
@ -1,40 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* you may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.wso2.carbon.iot.android.sense.util.dto;
|
||||
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
|
||||
@Path("/register")
|
||||
public interface DynamicClientRegistrationService {
|
||||
|
||||
/**
|
||||
* This method is used to register an Oauth application.
|
||||
*
|
||||
* @param profile contains the necessary attributes that are
|
||||
* needed in order to register an app.
|
||||
* @return Status 200 if success including consumerKey and consumerSecret.
|
||||
*/
|
||||
@POST
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
OAuthApplicationInfo register(RegistrationProfile profile);
|
||||
}
|
@ -1,58 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.util.dto;
|
||||
|
||||
/**
|
||||
* This class represents an OAuth application populated with necessary data.
|
||||
*/
|
||||
public class OAuthApplicationInfo {
|
||||
|
||||
public String client_id;
|
||||
public String client_name;
|
||||
public String callback_url;
|
||||
public String client_secret;
|
||||
|
||||
public String getClient_id() {
|
||||
return client_id;
|
||||
}
|
||||
|
||||
public void setClient_id(String client_id) {
|
||||
this.client_id = client_id;
|
||||
}
|
||||
|
||||
public String getClient_name() {
|
||||
return client_name;
|
||||
}
|
||||
|
||||
public void setClient_name(String client_name) {
|
||||
this.client_name = client_name;
|
||||
}
|
||||
|
||||
public String getCallback_url() {
|
||||
return callback_url;
|
||||
}
|
||||
|
||||
public void setCallback_url(String callback_url) {
|
||||
this.callback_url = callback_url;
|
||||
}
|
||||
|
||||
public String getClient_secret() {
|
||||
return client_secret;
|
||||
}
|
||||
|
||||
public void setClient_secret(String client_secret) {
|
||||
this.client_secret = client_secret;
|
||||
}
|
||||
}
|
@ -1,43 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.util.dto;
|
||||
|
||||
|
||||
import feign.RequestInterceptor;
|
||||
import feign.RequestTemplate;
|
||||
|
||||
import static feign.Util.checkNotNull;
|
||||
|
||||
/**
|
||||
* This is a request interceptor to add oauth token header.
|
||||
*/
|
||||
public class OAuthRequestInterceptor implements RequestInterceptor {
|
||||
|
||||
private final String headerValue;
|
||||
|
||||
/**
|
||||
* Creates an interceptor that authenticates all requests with the specified OAUTH token
|
||||
*
|
||||
* @param token the access token to use for authentication
|
||||
*/
|
||||
public OAuthRequestInterceptor(String token) {
|
||||
checkNotNull(token, "access_token");
|
||||
headerValue = "Bearer " + token;
|
||||
}
|
||||
@Override
|
||||
public void apply(RequestTemplate template) {
|
||||
template.header("Authorization", headerValue);
|
||||
}
|
||||
}
|
@ -1,40 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.util.dto;
|
||||
|
||||
/**
|
||||
* This holds the data related to registration.
|
||||
*/
|
||||
public class RegisterInfo {
|
||||
|
||||
private boolean isRegistered;
|
||||
private String msg;
|
||||
|
||||
public boolean isRegistered() {
|
||||
return isRegistered;
|
||||
}
|
||||
|
||||
public void setIsRegistered(boolean isRegistered) {
|
||||
this.isRegistered = isRegistered;
|
||||
}
|
||||
|
||||
public String getMsg() {
|
||||
return msg;
|
||||
}
|
||||
|
||||
public void setMsg(String msg) {
|
||||
this.msg = msg;
|
||||
}
|
||||
}
|
@ -1,67 +0,0 @@
|
||||
package org.wso2.carbon.iot.android.sense.util.dto;
|
||||
|
||||
|
||||
/**
|
||||
* This class represents the data that are required to register
|
||||
* the oauth application.
|
||||
*/
|
||||
public class RegistrationProfile {
|
||||
|
||||
public String callbackUrl;
|
||||
public String clientName;
|
||||
public String tokenScope;
|
||||
public String owner;
|
||||
public String grantType;
|
||||
public String applicationType;
|
||||
|
||||
private static final String TAG = RegistrationProfile.class.getSimpleName();
|
||||
|
||||
public String getCallbackUrl() {
|
||||
return callbackUrl;
|
||||
}
|
||||
|
||||
public void setCallbackUrl(String callBackUrl) {
|
||||
this.callbackUrl = callBackUrl;
|
||||
}
|
||||
|
||||
public String getClientName() {
|
||||
return clientName;
|
||||
}
|
||||
|
||||
public void setClientName(String clientName) {
|
||||
this.clientName = clientName;
|
||||
}
|
||||
|
||||
public String getTokenScope() {
|
||||
return tokenScope;
|
||||
}
|
||||
|
||||
public void setTokenScope(String tokenScope) {
|
||||
this.tokenScope = tokenScope;
|
||||
}
|
||||
|
||||
public String getOwner() {
|
||||
return owner;
|
||||
}
|
||||
|
||||
public void setOwner(String owner) {
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
public String getGrantType() {
|
||||
return grantType;
|
||||
}
|
||||
|
||||
public void setGrantType(String grantType) {
|
||||
this.grantType = grantType;
|
||||
}
|
||||
|
||||
public String getApplicationType() {
|
||||
return applicationType;
|
||||
}
|
||||
|
||||
public void setApplicationType(String applicationType) {
|
||||
this.applicationType = applicationType;
|
||||
}
|
||||
|
||||
}
|
@ -1,39 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.iot.android.sense.util.dto;
|
||||
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
|
||||
/**
|
||||
* This hold the api definition that is used as a contract with netflix feign.
|
||||
*/
|
||||
@Path("/token")
|
||||
public interface TokenIssuerService {
|
||||
|
||||
@POST
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
AccessTokenInfo getToken(@QueryParam("grant_type") String grant, @QueryParam("username") String username,
|
||||
@QueryParam("password") String password, @QueryParam("scope") String scope);
|
||||
|
||||
@POST
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
AccessTokenInfo getRefreshToken(@QueryParam("grant_type") String grantType, @QueryParam("refreshToken") String refreshToken);
|
||||
|
||||
|
||||
}
|
Before Width: | Height: | Size: 23 KiB |
Before Width: | Height: | Size: 19 KiB |
Before Width: | Height: | Size: 26 KiB |
Before Width: | Height: | Size: 56 KiB |
@ -1,13 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<selector xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item android:state_pressed="false">
|
||||
<shape android:shape="oval">
|
||||
<solid android:color="#fa09ad"/>
|
||||
</shape>
|
||||
</item>
|
||||
<item android:state_pressed="true">
|
||||
<shape android:shape="oval">
|
||||
<solid android:color="#c20586"/>
|
||||
</shape>
|
||||
</item>
|
||||
</selector>
|
Before Width: | Height: | Size: 14 KiB |
@ -1,9 +0,0 @@
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:shape="rectangle" >
|
||||
<gradient
|
||||
android:startColor="#c7b681"
|
||||
android:centerColor="#bc8d43"
|
||||
android:endColor="#da800c"
|
||||
android:type="linear"
|
||||
android:angle="135"/>
|
||||
</shape>
|
Before Width: | Height: | Size: 30 KiB |
@ -1,18 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout"
|
||||
android:layout_width="match_parent" android:layout_height="match_parent"
|
||||
android:fitsSystemWindows="true" tools:openDrawer="start">
|
||||
|
||||
|
||||
<include layout="@layout/app_bar_activity_select_sensor" android:layout_width="match_parent"
|
||||
android:layout_height="match_parent" />
|
||||
|
||||
<android.support.design.widget.NavigationView android:id="@+id/nav_view"
|
||||
android:layout_width="wrap_content" android:layout_height="match_parent"
|
||||
android:layout_gravity="start" android:fitsSystemWindows="true"
|
||||
app:headerLayout="@layout/nav_header_activity_select_sensor"
|
||||
app:menu="@menu/activity_activity_select_sensor_drawer" />
|
||||
|
||||
</android.support.v4.widget.DrawerLayout>
|
@ -1,34 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:orientation="vertical" android:layout_width="match_parent"
|
||||
android:layout_height="match_parent">
|
||||
|
||||
|
||||
<RelativeLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:orientation="vertical">
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/listContainer"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:layout_alignParentTop="true"
|
||||
android:orientation="vertical">
|
||||
|
||||
<ListView
|
||||
android:id="@android:id/list"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"/>
|
||||
|
||||
<TextView
|
||||
android:id="@android:id/empty"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:gravity="center_vertical|center_horizontal"
|
||||
android:text="@string/no_data"/>
|
||||
</LinearLayout>
|
||||
</RelativeLayout>
|
||||
|
||||
|
||||
</LinearLayout>
|
@ -1,21 +0,0 @@
|
||||
<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:padding="5dip" >
|
||||
|
||||
<TextView
|
||||
android:layout_width="fill_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_alignParentTop="true"
|
||||
android:gravity="center_horizontal"
|
||||
android:text="Scanning..." />
|
||||
|
||||
<ListView
|
||||
android:id="@+id/list"
|
||||
android:layout_width="fill_parent"
|
||||
android:layout_height="fill_parent"
|
||||
android:divider="@android:color/darker_gray"
|
||||
android:dividerHeight="1dip" />
|
||||
|
||||
</RelativeLayout>
|
@ -1,56 +0,0 @@
|
||||
<LinearLayout 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:gravity="center_horizontal"
|
||||
android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin"
|
||||
android:paddingLeft="@dimen/activity_horizontal_margin"
|
||||
android:paddingRight="@dimen/activity_horizontal_margin"
|
||||
android:paddingTop="@dimen/activity_vertical_margin" tools:context="org.wso2.carbon.iot.android.sense.RegisterActivity"
|
||||
android:weightSum="1">
|
||||
|
||||
<!-- Login progress -->
|
||||
|
||||
<ProgressBar android:id="@+id/login_progress" style="?android:attr/progressBarStyleLarge"
|
||||
android:layout_width="wrap_content" android:layout_height="wrap_content"
|
||||
android:layout_marginBottom="8dp" android:visibility="gone" />
|
||||
|
||||
<ScrollView android:id="@+id/login_form" android:layout_width="match_parent"
|
||||
android:layout_height="153dp"
|
||||
android:fillViewport="false"
|
||||
>
|
||||
|
||||
<LinearLayout android:id="@+id/email_login_form" android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content" android:orientation="vertical">
|
||||
|
||||
<EditText
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content" android:hint="@string/prompt_username"
|
||||
android:id="@+id/username"
|
||||
android:inputType="text"
|
||||
android:maxLines="1" android:singleLine="true"
|
||||
/>
|
||||
|
||||
<EditText android:id="@+id/password" android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content" android:hint="@string/prompt_password"
|
||||
android:inputType="textPassword"
|
||||
android:maxLines="1" android:singleLine="true"
|
||||
/>
|
||||
|
||||
<EditText
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content" android:hint="@string/hostname"
|
||||
android:id="@+id/hostname"
|
||||
android:text="https://localhost:8243"
|
||||
android:inputType="text"
|
||||
android:maxLines="1" android:singleLine="true"/>
|
||||
|
||||
</LinearLayout>
|
||||
</ScrollView>
|
||||
|
||||
<Button android:id="@+id/device_register_button" style="?android:textAppearanceSmall"
|
||||
android:layout_width="wrap_content" android:layout_height="wrap_content"
|
||||
android:layout_marginTop="16dp" android:text="@string/action_sign_in"
|
||||
android:textStyle="bold"
|
||||
android:layout_gravity="center_horizontal"/>
|
||||
|
||||
</LinearLayout>
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue