SConscript(build_dir + 'examples/OICMiddle/SConscript')
# Build 'service' sub-project
-# if target_os != 'android':
SConscript(build_dir + 'service/SConscript')
# Append targets information to the help information, to see help info, execute command line:
Alias(name, i_n)
env.AppendUnique(TS = [name])
-def __append_target(ienv, target):
- env.AppendUnique(TS = [target])
+def __append_target(ienv, name, targets = None):
+ if targets:
+ env.Alias(name, targets)
+ env.AppendUnique(TS = [name])
def __print_targets(env):
Help('''
return os.str();
}
+ std::string to_string(long t) {
+ std::ostringstream os;
+ os << t;
+ return os.str();
+ }
+
std::string to_string(double t) {
std::ostringstream os;
os << t;
long double stold(const string& s);
std::string to_string(int i);
+ std::string to_string(long t);
std::string to_string(uint32_t i);
std::string to_string(double d);
}
# Install header file(s) to <src_dir>/deps/<target_os>/include
def __install_head_file(ienv, file):
- return ienv.Install(os.path.join(env.get('SRC_DIR'), 'deps', target_os, 'include'), file)
+ return ienv.Install(os.path.join(env.get('SRC_DIR'), 'dep', target_os, target_arch, 'usr', 'include'), file)
# Install library binaries to <src_dir>/deps/<target_os>/lib/<arch>
def __install_lib(ienv, lib):
- return ienv.Install(os.path.join(env.get('SRC_DIR'), 'deps', target_os, 'lib', target_arch), lib)
+ return ienv.Install(os.path.join(env.get('SRC_DIR'), 'dep', target_os, target_arch, 'usr', 'lib'), lib)
SConscript('tools/UnpackAll.py')
extern "C" {
#endif // __cplusplus
#define WITH_PRESENCE
+#define USE_RANDOM_PORT (0)
//-----------------------------------------------------------------------------
// Function prototypes
if target_os not in ['arduino','darwin']:
# Build things manager project
- if target_os != 'android':
- SConscript('things-manager/SConscript')
+ SConscript('things-manager/SConscript')
# Build soft sensor manager project
SConscript('soft-sensor-manager/SConscript')
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+extern "C" {
+#include "hosting.h"
+}
+#include "resourceCoordinator_JNI.h"
+#include "android_cpp11_compat.h"
+
+using namespace std;
+
+atomic_bool threadRun;
+thread ocProcessThread;
+/*
+ * To execute OCProcess when threadRun value is only true
+ */
+void ocProcessFunc()
+{
+ while (threadRun)
+ {
+
+ if (OCProcess() != OC_STACK_OK)
+ {
+ //OCProcess ERROR
+ }
+
+ sleep(2);
+ }
+}
+/*
+ * To callback log message from C++ to Java for android
+ */
+void messageCallback(JNIEnv *env, jobject obj, const char *c_str)
+{
+ jstring jstr = (env)->NewStringUTF(c_str);
+ jclass cls = env->GetObjectClass(obj);
+ jmethodID cbMessage = env->GetMethodID(cls, "cbMessage", "(Ljava/lang/String;)V");
+ env->CallVoidMethod(obj,cbMessage, jstr);
+}
+/*
+ * for Hosting Device Side
+ */
+JNIEXPORT jint JNICALL Java_com_example_resourcehostingsampleapp_ResourceHosting_OICCoordinatorStart
+(JNIEnv *env, jobject obj)
+{
+ jint result = 0;
+ if(threadRun==true)
+ {
+
+ messageCallback(env,obj,"already execute OICCoordinatorStart");
+ result = (jint)HOSTING_THREAD_ERROR;
+ return result;
+ }
+ else
+ {
+ messageCallback(env,obj,"OICCoordinatorStart");
+ result = (jint)OICStartCoordinate();
+ string str = "OICStartCoordinate result : ";
+ string result_str = std::to_string(result);
+ str += result_str;
+ messageCallback(env,obj,str.c_str());
+ threadRun = true;
+ ocProcessThread = thread(ocProcessFunc);
+ return result;
+ }
+}
+
+JNIEXPORT jint JNICALL Java_com_example_resourcehostingsampleapp_ResourceHosting_OICCoordinatorStop
+(JNIEnv *env, jobject obj)
+{
+ messageCallback(env,obj,"OICCoordinatorStop");
+ jint result = 0;
+ //terminate Thread
+ if (ocProcessThread.joinable())
+ {
+ threadRun = false;
+ ocProcessThread.join();
+ }
+ else
+ {
+ messageCallback(env,obj,"The thread may be not running.");
+ result = (jint)HOSTING_THREAD_ERROR;
+ return result;
+ }
+ result = (jint)OICStopCoordinate();
+ string str = "OICStopCoordinate result : ";
+ string result_str = std::to_string(result);
+ str += result_str;
+ messageCallback(env,obj,str.c_str());
+ return result;
+}
+
+JNIEXPORT jint JNICALL Java_com_example_resourcehostingsampleapp_ResourceHosting_ResourceHostingInit
+(JNIEnv *env, jobject obj,jstring j_addr)
+{
+ messageCallback(env,obj,"ResourceHostingInit");
+ const char* addr = env->GetStringUTFChars(j_addr,NULL);
+
+ if (NULL == j_addr)
+ return (jint)OCSTACK_ERROR;
+
+ if(OCInit(addr,USE_RANDOM_PORT,OC_CLIENT_SERVER)!=OC_STACK_OK)
+ {
+ messageCallback(env,obj,"OCStack init Error");
+ return (jint)OCSTACK_ERROR;
+ }
+
+ env->ReleaseStringUTFChars(j_addr,addr);
+ return (jint)OCSTACK_OK;
+}
+
+JNIEXPORT jint JNICALL Java_com_example_resourcehostingsampleapp_ResourceHosting_ResourceHostingTerminate
+(JNIEnv *env, jobject obj)
+{
+ messageCallback(env,obj,"ResourceHostingTerminate");
+ if (OCStop() != OC_STACK_OK)
+ {
+
+ messageCallback(env,obj,"OCStack stop error");
+ return (jint)OCSTACK_ERROR;
+ }
+ //terminate Thread
+ if (ocProcessThread.joinable())
+ {
+ threadRun = false;
+ ocProcessThread.join();
+ }
+ else
+ {
+ messageCallback(env,obj,"The thread may be not running.");
+ return (jint)HOSTING_THREAD_ERROR;
+ }
+
+ return (jint)OCSTACK_OK;
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+
+#ifndef RESOURCECOORDINATOR_JNI_H_
+#define RESOURCECOORDINATOR_JNI_H_
+
+#include <jni.h>
+#include <thread>
+#include <atomic>
+#include <unistd.h>
+
+#define TAG "OIC-JNI"
+
+#define JNI_CURRENT_VERSION JNI_VERSION_1_6
+#define OCSTACK_OK 0
+#define OCSTACK_ERROR 255
+#define HOSTING_THREAD_ERROR -2
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Class: org_iotivity_service_resourcehostingsampleapp_ResourceHosting
+ * Method: OICCoordinatorStart
+ * Signature: ()V
+ */
+JNIEXPORT jint JNICALL Java_com_example_resourcehostingsampleapp_ResourceHosting_OICCoordinatorStart
+(JNIEnv *, jobject);
+/*
+ * @Class: org_iotivity_service_resourcehostingsampleapp_ResourceHosting
+ * @Method: OICCoordinatorStop
+ * @Signature: ()V
+ */
+
+JNIEXPORT jint JNICALL Java_com_example_resourcehostingsampleapp_ResourceHosting_OICCoordinatorStop
+(JNIEnv *, jobject);
+/*
+ * Class: org_iotivity_service_resourcehostingsampleapp_ResourceHosting
+ * Method: ResourceHostingInit
+ * Signature: ()V
+ */
+JNIEXPORT jint JNICALL Java_com_example_resourcehostingsampleapp_ResourceHosting_ResourceHostingInit
+(JNIEnv *env, jobject obj,jstring j_addr);
+/*
+ * Class: org_iotivity_service_resourcehostingsampleapp_ResourceHosting
+ * Method: ResourceHostingTerminate
+ * Signature: (Ljava/lang/String;)V
+ */
+JNIEXPORT jint JNICALL Java_com_example_resourcehostingsampleapp_ResourceHosting_ResourceHostingTerminate
+(JNIEnv *env, jobject obj);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* RESOURCECOORDINATOR_JNI_H_ */
notimgr_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'libcoap'])
if target_os not in ['windows', 'winrt']:
- notimgr_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0'])
+ notimgr_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
if target_os == 'linux':
notimgr_env.AppendUnique(LIBS = ['pthread'])
if target_os == 'android':
notimgr_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
- notimgr_env.AppendUnique(LIBS = ['gnustl_static'])
+ notimgr_env.AppendUnique(LIBS = ['gnustl_shared','log'])
if not env.get('RELEASE'):
notimgr_env.AppendUnique(LIBS = ['log'])
NOTI_SRC_DIR + 'requestHandler.c',
NOTI_SRC_DIR + 'virtualResource.c']
-if target_os in ['tizen'] :
- notificationsdk = notimgr_env.SharedLibrary('NOTISDKLibrary', notimgr_src)
+if target_os == 'android':
+ notimgr_src.append(NOTI_SRC_DIR + 'resourceCoordinator_JNI.cpp')
+
+if target_os in ['tizen','android'] :
+ notificationsdk = notimgr_env.SharedLibrary('NotificationManager', notimgr_src)
else :
- notificationsdk = notimgr_env.StaticLibrary('NOTISDKLibrary', notimgr_src)
+ notificationsdk = notimgr_env.StaticLibrary('NotificationManager', notimgr_src)
-notimgr_env.InstallTarget(notificationsdk, 'libNMSDK')
+notimgr_env.InstallTarget(notificationsdk, 'libResouceHosting')
# Go to build sample apps
SConscript('SampleApp/SConscript')
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+ <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
+ <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="src" path="gen"/>
+ <classpathentry exported="true" kind="lib" path="C:/Users/jay.sharma/Desktop/master_19_may/iotivity/android/android_api/base/build/intermediates/bundles/release/classes.jar"/>
+ <classpathentry kind="output" path="bin/classes"/>
+</classpath>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>ResourceHosting</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.ApkBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>com.android.ide.eclipse.adt.AndroidNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.example.resourcehostingsampleapp"
+ android:versionCode="1"
+ android:versionName="1.0" >
+
+ <uses-sdk
+ android:minSdkVersion="19"
+ android:targetSdkVersion="19" />
+
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
+ <uses-permission android:name="android.permission.READ_PHONE_STATE" />
+ <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.INTERNET_ACCESS" />
+ <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+ <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
+ <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
+ <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
+ <uses-permission android:name="android.permission.GET_TASKS"/>
+ <uses-permission android:name="com.samsung.wmanager.ENABLE_NOTIFICATION"/>
+ <uses-permission android:name="com.samsung.android.providers.context.permission.WRITE_USE_APP_FEATURE_SURVEY"/>
+
+ <application
+ android:allowBackup="true"
+ android:icon="@drawable/ic_launcher"
+ android:label="@string/app_name"
+ android:theme="@style/AppTheme" >
+ <activity
+ android:name="com.example.resourcehostingsampleapp.ResourceHosting"
+ android:label="@string/app_name" >
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+ </application>
+
+</manifest>
--- /dev/null
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := coap
+LOCAL_SRC_FILES := ../libs/libcoap.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := oc_logger_core
+LOCAL_SRC_FILES := ../libs/liboc_logger_core.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := oc_logger
+LOCAL_SRC_FILES := ../libs/liboc_logger.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := octbstack
+LOCAL_SRC_FILES := ../libs/liboctbstack.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := oc
+LOCAL_SRC_FILES := ../libs/liboc.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := libNotificationManager
+LOCAL_SRC_FILES := ../libs/libNotificationManager.so
+include $(PREBUILT_SHARED_LIBRARY)
--- /dev/null
+APP_STL:=gnustl_shared
+NDK_TOOLCHAIN_VERSION := 4.9
--- /dev/null
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-19
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics 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 com.example.resourcehostingsampleapp;
+
+import java.net.Inet4Address;
+import java.net.InetAddress;
+import java.net.NetworkInterface;
+import java.net.SocketException;
+import java.util.Enumeration;
+
+import org.iotivity.base.OcResourceHandle;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.TextView;
+import android.widget.Toast;
+
+/**
+ * To execute resource hosting function for android sample application .
+ * @author Copyright 2015 Samsung Electronics All Rights Reserved.
+ * @see className class : ResourceHosting</br>
+ *
+ */
+
+public class ResourceHosting extends Activity implements OnClickListener
+{
+ private final int OCSTACK_OK = 0;
+ private final int OCSTACK_ERROR = 255;
+ private final int RESOURCEHOSTING_DO_NOT_THREADRUNNING = -2;
+
+ private String TAG = "ResourceHosting";
+ private OcResourceHandle mResourceHandle;
+ private String mIpAddress;
+ private TextView mLogTextView;
+ private String mLog = "";
+ /**
+ * To initialize UI Function Setting.
+ * @see Class class : com_example_resourcehostingsampleapp_ResourceHosting</br>
+ * @see Method method : onCreate</br>
+ */
+ protected void onCreate(Bundle savedInstanceState)
+ {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_main);
+ mLogTextView = (TextView) findViewById(R.id.txtLog);
+ findViewById(R.id.btnStartHosting).setOnClickListener(this);
+ findViewById(R.id.btnStopHosting).setOnClickListener(this);
+ findViewById(R.id.btLogClear).setOnClickListener(this);
+ }
+
+ /**
+ * To execute initOICStack for running Resource hosting.
+ * @see Class class : com_example_resourcehostingsampleapp_ResourceHosting</br>
+ * @see Method method : onStart</br>
+ */
+ @Override
+ protected void onStart()
+ {
+ super.onStart();
+ initOICStack();
+ }
+
+ /**
+ * To terminate Resource hosting.
+ * @see Class class : com_example_resourcehostingsampleapp_ResourceHosting</br>
+ * @see Method method : onStop</br>
+ */
+ @Override
+ protected void onStop()
+ {
+ super.onStop();
+ int result;
+ result = ResourceHostingTerminate();
+ Log.d(TAG, "ResourceHostingTerminate : "+ result);
+ }
+
+ protected void onResume()
+ {
+ super.onResume();
+ }
+
+ /**
+ * To execute initOICStack for running Resource hosting.
+ * @see Class class : com_example_resourcehostingsampleapp_ResourceHosting</br>
+ * @see Method method : onRestart</br>
+ */
+ @Override
+ protected void onRestart()
+ {
+ super.onRestart();
+ initOICStack();
+ }
+
+ /**
+ * @see Class class : com_example_resourcehostingsampleapp_ResourceHosting</br>
+ * @see Method method : onDestroy</br>
+ */
+ protected void onDestroy()
+ {
+ super.onDestroy();
+ }
+
+ /**
+ * get IpAddress and execute resourceHostingInit() method.
+ * @see Class class : com_example_resourcehostingsampleapp_ResourceHosting</br>
+ * @see Method method : initOICStack</br>
+ */
+ private void initOICStack()
+ {
+ try
+ {
+ mIpAddress = getIpAddress();
+ int result;
+ result = ResourceHostingInit(mIpAddress);
+ Log.d(TAG, "ResourceHostingInit : " + result);
+ }
+ catch (Exception e)
+ {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * @see Class class : com_example_resourcehostingsampleapp_ResourceHosting</br>
+ * @see Method method : getIpAddress</br>
+ */
+ private String getIpAddress()
+ {
+ try
+ {
+ for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
+ en.hasMoreElements();)
+ {
+ NetworkInterface intf = (NetworkInterface) en.nextElement();
+ for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
+ {
+ InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
+ if (!inetAddress.isLoopbackAddress())
+ {
+ if (inetAddress instanceof Inet4Address)
+ return inetAddress.getHostAddress().toString();
+ }
+ }
+ }
+ }
+ catch (SocketException e)
+ {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ /**
+ * @see Class class : com_example_resourcehostingsampleapp_ResourceHosting</br>
+ * @see Method method : onClick</br>
+ * @param v view to choice
+ */
+ public void onClick(View v)
+ {
+ int getId = v.getId();
+
+ switch (getId)
+ {
+ case R.id.btnStartHosting:
+ try
+ {
+ int result;
+ result = OICCoordinatorStart();
+ Log.d(TAG, "OICCoordinatorStart : " + result);
+ }
+ catch (Exception e)
+ {
+ Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
+ }
+ break;
+ case R.id.btnStopHosting:
+ int result;
+ result = OICCoordinatorStop();
+ Log.d(TAG, "OICCoordinatorStop : "+ result);
+ break;
+ case R.id.btLogClear:
+ clearLog();
+ default:
+ break;
+ }
+ }
+
+ /**
+ * all clear log view
+ * @see Class class : com_example_resourcehostingsampleapp_ResourceHosting</br>
+ * @see Method method : clearLog</br>
+ */
+ private void clearLog()
+ {
+ mLog = "";
+ mLogTextView.setText(mLog);
+ }
+
+ /**
+ * recieve the callback log message.
+ * @see Class class : com_example_resourcehostingsampleapp_ResourceHosting</br>
+ * @see Method method : cbMessage</br>
+ * @param msg callback log message
+ */
+ public void cbMessage(String msg)
+ {
+ mLog += msg + "\n";
+ mLogTextView.setText(mLog);
+ }
+
+ /**
+ * jni function - OicCorrdinatorstart() method.
+ * @see Class class : com_example_resourcehostingsampleapp_ResourceHosting</br>
+ * @see Method method : OICCoordinatorStart</br>
+ * @see Signature signature : ()V</br>
+ */
+ public native int OICCoordinatorStart();
+
+ /**
+ * jni function - OICCoordinatorStop() method.
+ * @see Class class : com_example_resourcehostingsampleapp_ResourceHosting</br>
+ * @see Method method : OICCoordinatorStop</br>
+ * @see signature signature : ()V</br>
+ */
+ public native int OICCoordinatorStop();
+
+ /**
+ * jni function - ResourceHostingInit() method in order to execute OICCoordinatorStart() method.
+ * @see Class class : com_example_resourcehostingsampleapp_ResourceHosting</br>
+ * @see Method method : ResourceHostingInit</br>
+ * @param addr ipAddress
+ * @see signature signature : (Ljava/lang/String;)V</br>
+ */
+ public native int ResourceHostingInit(String addr);
+
+ /**
+ * jni function - ResourceHostingTerminate() method in order to terminate resource hosting
+ * @see Class class : com_example_resourcehostingsampleapp_ResourceHosting</br>
+ * @see Method method : ResourceHostingTerminate</br>
+ * @see signature signature : ()V</br>
+ */
+ public native int ResourceHostingTerminate();
+
+ static
+ {
+ System.loadLibrary("gnustl_shared");
+ System.loadLibrary("oc_logger");
+ System.loadLibrary("connectivity_abstraction");
+ System.loadLibrary("octbstack");
+ System.loadLibrary("oc");
+ System.loadLibrary("ocstack-jni");
+ System.loadLibrary("NotificationManager");
+ }
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+ <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
+ <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="src" path="gen"/>
+ <classpathentry exported="true" kind="lib" path="C:/Users/jay.sharma/Desktop/master_19_may/iotivity/android/android_api/base/build/intermediates/bundles/release/classes.jar"/>
+ <classpathentry kind="output" path="bin/classes"/>
+</classpath>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>SampleConsumer</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.ApkBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>com.android.ide.eclipse.adt.AndroidNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.sec.android.iot.sampleconsumer"
+ android:versionCode="1"
+ android:versionName="1.0" >
+
+ <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="19" />
+
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
+ <uses-permission android:name="android.permission.READ_PHONE_STATE" />
+ <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+ <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
+ <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
+ <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
+ <uses-permission android:name="android.permission.GET_TASKS"/>
+ <uses-permission android:name="com.samsung.wmanager.ENABLE_NOTIFICATION"/>
+ <uses-permission android:name="com.samsung.android.providers.context.permission.WRITE_USE_APP_FEATURE_SURVEY"/>
+
+ <application android:label="@string/app_name" >
+ <activity
+ android:name="com.example.sample.consumer.SampleConsumer"
+ android:label="@string/app_name" >
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+ </application>
+
+</manifest>
\ No newline at end of file
--- /dev/null
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-19
--- /dev/null
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="fill_parent"
+ android:layout_height="fill_parent"
+ android:orientation="vertical"
+ android:paddingBottom="5dp"
+ android:paddingLeft="10dp"
+ android:paddingRight="10dp"
+ android:paddingTop="10dp" >
+
+ <LinearLayout
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:orientation="vertical" >
+
+ <TextView
+ android:id="@+id/tv_found_resource"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:text="@string/found_resource"
+ android:textAppearance="?android:attr/textAppearanceLarge" />
+
+ <TextView
+ android:id="@+id/tv_found_resource_result"
+ android:layout_width="200dp"
+ android:layout_height="wrap_content"
+ android:layout_below="@+id/tv_found_resource"
+ android:hint="@string/none" />
+
+ <LinearLayout
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal" >
+
+ <Button
+ android:id="@+id/btn_observe"
+ android:layout_width="60dp"
+ android:layout_height="50dp"
+ android:layout_below="@+id/tv_found_resource_result"
+ android:layout_marginLeft="5dp"
+ android:layout_marginTop="5dp"
+ android:text="@string/observe"
+ android:textSize="12sp" />
+
+ <Button
+ android:id="@+id/btn_get"
+ android:layout_width="60dp"
+ android:layout_height="50dp"
+ android:layout_alignBottom="@+id/btn_observe"
+ android:layout_below="@+id/tv_found_resource_result"
+ android:layout_marginLeft="5dp"
+ android:layout_marginTop="5dp"
+ android:text="@string/get"
+ android:textSize="12sp" />
+
+ <Button
+ android:id="@+id/btn_put"
+ android:layout_width="60dp"
+ android:layout_height="50dp"
+ android:layout_alignBottom="@+id/btn_observe"
+ android:layout_below="@+id/tv_found_resource_result"
+ android:layout_marginLeft="5dp"
+ android:layout_marginTop="5dp"
+ android:text="@string/put"
+ android:textSize="12sp" />
+
+ <Button
+ android:id="@+id/btn_post"
+ android:layout_width="60dp"
+ android:layout_height="50dp"
+ android:layout_alignBottom="@+id/btn_observe"
+ android:layout_below="@+id/tv_found_resource_result"
+ android:layout_marginLeft="5dp"
+ android:layout_marginTop="5dp"
+ android:text="@string/post"
+ android:textSize="12sp" />
+
+ <Button
+ android:id="@+id/btn_delete"
+ android:layout_width="60dp"
+ android:layout_height="50dp"
+ android:layout_alignBottom="@+id/btn_observe"
+ android:layout_below="@+id/tv_found_resource_result"
+ android:layout_marginLeft="5dp"
+ android:layout_marginTop="5dp"
+ android:text="@string/delete"
+ android:textSize="12sp" />
+ </LinearLayout>
+
+ <TextView
+ android:id="@+id/tv_selected_method_type"
+ android:layout_width="200dp"
+ android:layout_height="wrap_content"
+ android:layout_below="@+id/btn_observe"
+ android:layout_marginTop="10dp"
+ android:hint="@string/select_method_type" />
+
+ <TextView
+ android:id="@+id/tv_receive"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_alignParentLeft="true"
+ android:layout_below="@+id/tv_selected_method_type"
+ android:layout_marginLeft="10dp"
+ android:layout_marginTop="10dp"
+ android:text="@string/received"
+ android:textAppearance="?android:attr/textAppearanceLarge" />
+
+ <TextView
+ android:id="@+id/tv_receive_result"
+ android:layout_width="200dp"
+ android:layout_height="wrap_content"
+ android:layout_alignParentLeft="true"
+ android:layout_below="@+id/tv_receive"
+ android:layout_marginLeft="10dp"
+ android:layout_marginTop="10dp"
+ android:hint="@string/none" />
+
+ <LinearLayout
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal" >
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="vertical">
+
+ <Button
+ android:id="@+id/btn_clean"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:text="@string/clean"
+ android:textSize="18sp" />
+
+ <ScrollView
+ android:id="@+id/sclLog"
+ android:layout_width="match_parent"
+ android:layout_height="0dp"
+ android:layout_weight="1"
+ android:fillViewport="true"
+ >
+
+ <TextView
+ android:id="@+id/tv_current_log_result"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:gravity="bottom"
+ android:text="@string/current_log"
+ android:textSize="15sp" />
+ </ScrollView>
+ </LinearLayout>
+ </LinearLayout>
+ -
+ </LinearLayout>
+
+</LinearLayout>
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">SampleConsumer</string>
+ <string name="observe">Obv</string>
+ <string name="get">Get</string>
+ <string name="put">Put</string>
+ <string name="post">Post</string>
+ <string name="delete">Del</string>
+ <string name="select_method_type">Select Method Type</string>
+ <string name="received">Received</string>
+ <string name="current_log">Current Log</string>
+ <string name="none">None</string>
+ <string name="quit">Quit</string>
+ <string name="clean">Clear Log</string>
+ <string name="found_resource">Found Resource</string>
+</resources>
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics 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 com.example.sample.consumer;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.ObserveType;
+import org.iotivity.base.OcConnectivityType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.OcResource.OnDeleteListener;
+import org.iotivity.base.OcResource.OnGetListener;
+import org.iotivity.base.OcResource.OnObserveListener;
+import org.iotivity.base.OcResource.OnPutListener;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+import com.sec.android.iot.sampleconsumer.R;
+
+import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.View;
+import android.widget.Button;
+import android.widget.TextView;
+import android.widget.Toast;
+
+public class SampleConsumer extends Activity implements View.OnClickListener,
+ OcPlatform.OnResourceFoundListener, OnGetListener, OnDeleteListener,
+ OnObserveListener, OnPutListener
+{
+ private final String TAG = "sample_consumer";
+
+ public static final int OC_STACK_OK = 0;
+ public static final String OBSERVE = "Observe";
+ public static final String GET = "Get";
+ public static final String PUT = "Put";
+ public static final String DELETE = "Delete";
+ public static final String POST = "Post";
+ public static final String MESSAGE = "message";
+ public static String outputString = "";
+
+ private Button btn_observe;
+ private Button btn_get;
+ private Button btn_put;
+ private Button btn_post;
+ private Button btn_delete;
+ private Button btn_clean;
+
+ public TextView tv_found_uri;
+ public TextView tv_select_method_type;
+ public TextView tv_receive_result;
+ public TextView tv_current_log_result;
+
+ public String current_log_result = "";
+ public String found_uri = "";
+ public String select_method_type = "";
+ public String receive_result = "";
+
+ public static OcResource curResource;
+ public OcPlatform.OnResourceFoundListener OnResourceFoundListener;
+
+ public static int oc = 0;
+ /*
+ * To initialize UI Function Setting
+ * To execute initOICStack for running find resource
+ */
+ @Override
+ public void onCreate(Bundle savedInstanceState)
+ {
+ super.onCreate(savedInstanceState);
+
+ setContentView(R.layout.sampleconsumer_layout);
+
+ btn_observe = (Button) findViewById(R.id.btn_observe);
+ btn_get = (Button) findViewById(R.id.btn_get);
+ btn_put = (Button) findViewById(R.id.btn_put);
+ btn_post = (Button) findViewById(R.id.btn_post);
+ btn_delete = (Button) findViewById(R.id.btn_delete);
+ btn_clean = (Button) findViewById(R.id.btn_clean);
+ tv_found_uri = (TextView) findViewById(R.id.tv_found_resource_result);
+ tv_select_method_type = (TextView) findViewById(R.id.tv_selected_method_type);
+ tv_receive_result = (TextView) findViewById(R.id.tv_receive_result);
+ tv_current_log_result = (TextView) findViewById(R.id.tv_current_log_result);
+ btn_observe.setOnClickListener(this);
+ btn_get.setOnClickListener(this);
+ btn_put.setOnClickListener(this);
+ btn_post.setOnClickListener(this);
+ btn_delete.setOnClickListener(this);
+ btn_clean.setOnClickListener(this);
+
+ initOICStack();
+ }
+
+ @Override
+ protected void onDestroy()
+ {
+ super.onDestroy();
+ onStop();
+ }
+ /*
+ * To reset text String is null for cleaning log
+ *
+ */
+ @Override
+ protected void onStop()
+ {
+ super.onStop();
+
+ tv_found_uri = null;
+ tv_select_method_type = null;
+ tv_receive_result = null;
+ tv_current_log_result = null;
+
+ current_log_result = "";
+ found_uri = "";
+ select_method_type = "";
+ receive_result = "";
+ btn_observe.setClickable(true);
+ btn_get.setClickable(true);
+ btn_put.setClickable(true);
+ btn_delete.setClickable(true);
+ }
+
+ public void cleanLogString()
+ {
+ current_log_result = "";
+ found_uri = "";
+ select_method_type = "";
+ receive_result = "";
+
+ tv_current_log_result.setText(current_log_result);
+ tv_found_uri.setText(found_uri);
+ tv_select_method_type.setText(select_method_type);
+ tv_receive_result.setText(receive_result);
+ }
+
+ public void initOICStack()
+ {
+ PlatformConfig cfg = new PlatformConfig(this,ServiceType.IN_PROC,
+ ModeType.CLIENT, "0.0.0.0", 0, QualityOfService.HIGH);
+ OcPlatform.Configure(cfg);
+ current_log_result += "Created Platform...\n";
+ tv_current_log_result.setText(current_log_result);
+ findResourceCandidate();
+ PRINT();
+ }
+
+ public void findResourceCandidate()
+ {
+ nmfindResource("", "coap://224.0.1.187/oc/core?rt=Resource.Hosting");
+ current_log_result += "Finding Resource... \n";
+ tv_current_log_result.setText(current_log_result);
+ }
+
+ public void nmfindResource(String host, String resourceName)
+ {
+ try
+ {
+ OcPlatform.findResource(host, resourceName, OcConnectivityType.ALL,this);
+
+ }
+ catch (OcException e)
+ {
+ e.printStackTrace();
+ current_log_result += e.getMessage() + "\n";
+ tv_current_log_result.setText(current_log_result);
+ }
+ }
+
+ /*
+ * No Use until Yet
+ */
+ public void getRepresentation(OcResource resource)
+ {
+ if (resource != null)
+ {
+ current_log_result += "Getting Light Representation...\n";
+ tv_current_log_result.setText(current_log_result);
+ }
+ }
+
+ /*
+ * No Use until Yet
+ */
+ public void getLightRepresentation(OcResource resource)
+ {
+ if (resource != null)
+ {
+ current_log_result += "Getting Light Representation...\n";
+ tv_current_log_result.setText(current_log_result);
+
+ try
+ {
+ Map<String, String> queryParamsMap = new HashMap<String, String>();
+ resource.get(queryParamsMap, this);
+ }
+ catch (OcException e)
+ {
+ e.printStackTrace();
+ current_log_result += e.getMessage() + "\n";
+ tv_current_log_result.setText(current_log_result);
+ }
+ }
+ }
+
+ public void PRINT()
+ {
+ current_log_result += "********************************************\n";
+ current_log_result += "* method Type : 1 - Observe *\n";
+ current_log_result += "* method Type : 2 - Get *\n";
+ current_log_result += "* method Type : 3 - Put *\n";
+ current_log_result += "* method Type : 4 - Delete *\n";
+ current_log_result += "********************************************\n";
+ }
+
+ public void startObserve(OcResource resource)
+ {
+ if (resource != null)
+ {
+ Map<String, String> queryParamsMap = new HashMap<String, String>();
+ current_log_result += "startObserve\n";
+ tv_current_log_result.setText(current_log_result);
+
+ try
+ {
+ resource.observe(ObserveType.OBSERVE, queryParamsMap, this);
+ }
+ catch (OcException e)
+ {
+ e.printStackTrace();
+ current_log_result += e.getMessage() + "\n";
+ tv_current_log_result.setText(current_log_result);
+ }
+ }
+ }
+
+ public void startGet(OcResource resource)
+ {
+ if (resource != null)
+ {
+ Map<String, String> queryParamsMap = new HashMap<String, String>();
+ current_log_result += "startGet\n";
+ tv_current_log_result.setText(current_log_result);
+
+ try
+ {
+ resource.get(queryParamsMap, this);
+ }
+ catch (OcException e)
+ {
+ e.printStackTrace();
+ current_log_result += e.getMessage() + "\n";
+ tv_current_log_result.setText(current_log_result);
+ }
+ }
+ }
+
+ public void startPut(OcResource resource)
+ {
+ if (resource != null)
+ {
+ curResource = resource;
+ OcRepresentation rep = new OcRepresentation();
+ rep.setValueInt("temperature", 25);
+ rep.setValueInt("humidity", 10);
+ Map<String, String> queryParamsMap = new HashMap<String, String>();
+ current_log_result += "startPut\n";
+ tv_current_log_result.setText(current_log_result);
+
+ try
+ {
+ resource.put(rep, queryParamsMap, this);
+ }
+ catch (OcException e)
+ {
+ e.printStackTrace();
+ current_log_result += e.getMessage() + "\n";
+ tv_current_log_result.setText(current_log_result);
+ }
+ }
+ }
+
+ public void startDelete(OcResource resource) throws OcException
+ {
+ curResource = resource;
+ if (resource != null)
+ {
+ resource.deleteResource(this);
+ }
+ }
+
+ @Override
+ public void onClick(View v)
+ {
+ switch (v.getId())
+ {
+ case R.id.btn_observe:
+ tv_select_method_type.setText(OBSERVE);
+ startObserve(curResource);
+ btn_observe.setClickable(false);
+ break;
+ case R.id.btn_get:
+ tv_select_method_type.setText(GET);
+ startGet(curResource);
+ btn_get.setClickable(false);
+ break;
+ case R.id.btn_put:
+ tv_select_method_type.setText(PUT);
+ startPut(curResource);
+ btn_put.setClickable(false);
+ break;
+ case R.id.btn_post:
+ tv_select_method_type.setText(POST);
+ Toast.makeText(this, "Not Supported Yet", Toast.LENGTH_SHORT)
+ .show();
+ break;
+ case R.id.btn_delete:
+ tv_select_method_type.setText(DELETE);
+ try {
+ startDelete(curResource);
+ } catch (OcException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ btn_delete.setClickable(false);
+ break;
+ case R.id.btn_clean:
+ cleanLogString();
+ break;
+
+ default:
+ break;
+ }
+
+ }
+
+ protected static int observe_count()
+ {
+ return ++oc;
+ }
+
+ public void viewText()
+ {
+ SampleConsumer.this.runOnUiThread(new Runnable()
+ {
+ public void run()
+ {
+ if (receive_result != null)
+ {
+ tv_receive_result.setText(receive_result);
+ }
+ if (found_uri != null)
+ {
+ tv_found_uri.setText(found_uri);
+ }
+ if (current_log_result != null)
+ {
+ tv_current_log_result.setText(current_log_result);
+ }
+
+ }
+ });
+ }
+
+ @Override
+ public synchronized void onResourceFound(OcResource resource)
+ {
+ // synchronized (this) {
+ receive_result = "FoundResource";
+ String resourceURI;
+ String hostAddress;
+ if (SampleConsumer.curResource != null)
+ {
+ current_log_result += "Found another resource, ignoring\n";
+ }
+ if (resource != null)
+ {
+ if (resource.getUri().equals("/a/TempHumSensor"))
+ {
+ current_log_result += "==============================\n";
+ current_log_result += "DISCOVERED Resource(Consumer):\n";
+ resourceURI = resource.getUri();
+ hostAddress = resource.getHost();
+ current_log_result += "URI of the resource: " + resourceURI
+ + "\n";
+ current_log_result += "Host address of the resource: "
+ + hostAddress + "\n";
+ SampleConsumer.curResource = resource;
+ }
+ else
+ {
+ current_log_result += "Uri is not correct.";
+ }
+ }
+ else
+ {
+ current_log_result += "Resource is invalid\n";
+ }
+
+ viewText();
+ }
+
+ public String getCurrent_log_result()
+ {
+ return current_log_result;
+ }
+
+ public void setCurrent_log_result(String current_log_result)
+ {
+ this.current_log_result = current_log_result;
+ }
+
+ public String getFound_uri()
+ {
+ return found_uri;
+ }
+
+ public void setFound_uri(String found_uri)
+ {
+ this.found_uri = found_uri;
+ }
+
+ public String getSelect_method_type()
+ {
+ return select_method_type;
+ }
+
+ public void setSelect_method_type(String select_method_type)
+ {
+ this.select_method_type = select_method_type;
+ }
+
+ public String getReceive_result()
+ {
+ return receive_result;
+ }
+
+ public void setReceive_result(String recieve_result)
+ {
+ this.receive_result = recieve_result;
+ }
+ public class MessageReceiver extends BroadcastReceiver
+ {
+ @Override
+ public void onReceive(Context context, Intent intent)
+ {
+ final String message = intent
+ .getStringExtra(MESSAGE);
+ tv_current_log_result.setText(message);
+ viewText();
+ }
+ }
+
+ @Override
+ public void onGetCompleted(List<OcHeaderOption> options,
+ OcRepresentation rep)
+ {
+ setReceive_result("onGet");
+ setCurrent_log_result(getCurrent_log_result()
+ + "GET request was successful\n"
+ + "GET request was successful\n"
+ + "URI: " + rep.getUri() + "\n"
+ + "Temperature: " + rep.getValueInt("temperature") + "\n"
+ + "Humidity: " + rep.getValueInt("humidity") + "\n");
+ viewText();
+ btn_get.setClickable(true);
+ }
+
+ @Override
+ public void onPutCompleted(List<OcHeaderOption> options,
+ OcRepresentation rep)
+ {
+ setReceive_result("onPut");
+ current_log_result += "PUT request was successful\n";
+
+ int humidity;
+ int temperature;
+ humidity = rep.getValueInt("humidity");
+ temperature = rep.getValueInt("temperature");
+
+ setCurrent_log_result(getCurrent_log_result() + "temperature: "
+ + temperature + "\n");
+ setCurrent_log_result(getCurrent_log_result() + "humidity: " + humidity
+ + "\n");
+ viewText();
+ btn_put.setClickable(true);
+ }
+
+ @Override
+ public void onObserveCompleted(List<OcHeaderOption> options,
+ OcRepresentation rep, int seqNum)
+ {
+ setReceive_result("onObserve");
+ setCurrent_log_result(getCurrent_log_result() + "SequenceNumber : "
+ + seqNum + "\n");
+ setCurrent_log_result("========================================================\n"
+ + "Receive OBSERVE RESULT:\n"
+ + "URI: "
+ + rep.getUri()
+ + "\n"
+ + "SequenceNumber: "
+ + seqNum
+ + "\n"
+ + "Temperature: "
+ + rep.getValueInt("temperature")
+ + "\n"
+ + "Humidity: "
+ + rep.getValueInt("humidity") + "\n");
+ if (SampleConsumer.observe_count() > 30)
+ {
+ setCurrent_log_result(getCurrent_log_result()
+ + "Cancelling Observe...\n");
+ try
+ {
+ SampleConsumer.curResource.cancelObserve();
+ }
+ catch (OcException e)
+ {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ setCurrent_log_result(getCurrent_log_result()
+ + "Cancel result :" + e.getMessage() + "\n");
+ }
+ }
+ viewText();
+ }
+
+ @Override
+ public void onDeleteCompleted(List<OcHeaderOption> options)
+ {
+ setReceive_result("onDelete");
+ viewText();
+ btn_delete.setClickable(true);
+ }
+
+ @Override
+ public void onPutFailed(Throwable arg0) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void onObserveFailed(Throwable arg0) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void onDeleteFailed(Throwable arg0) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void onGetFailed(Throwable arg0) {
+ // TODO Auto-generated method stub
+
+ }
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+ <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
+ <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="src" path="gen"/>
+ <classpathentry exported="true" kind="lib" path="C:/Users/jay.sharma/Desktop/master_19_may/iotivity/android/android_api/base/build/intermediates/bundles/release/classes.jar"/>
+ <classpathentry exported="true" kind="lib" path="C:/Users/jay.sharma/Desktop/master_19_may/android-support-v4.jar"/>
+ <classpathentry kind="output" path="bin/classes"/>
+</classpath>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>SampleProvider</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.ApkBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>com.android.ide.eclipse.adt.AndroidNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.example.sample.provider"
+ android:versionCode="1"
+ android:versionName="1.0" >
+
+ <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="19" />
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
+ <uses-permission android:name="android.permission.READ_PHONE_STATE" />
+ <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+ <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
+ <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
+ <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
+ <uses-permission android:name="android.permission.GET_TASKS"/>
+ <uses-permission android:name="com.samsung.wmanager.ENABLE_NOTIFICATION"/>
+ <uses-permission android:name="com.samsung.android.providers.context.permission.WRITE_USE_APP_FEATURE_SURVEY"/>
+
+ <application android:label="@string/app_name">
+ <activity
+ android:name="com.example.sample.provider.SampleProvider"
+ android:label="@string/app_name" >
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+ </application>
+
+</manifest>
\ No newline at end of file
--- /dev/null
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../out/android/$(TARGET_ARCH_ABI)/release
+LOCAL_MODULE := libandroid-oc_logger
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboc_logger.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../out/android/$(TARGET_ARCH_ABI)/release
+LOCAL_MODULE := libandroid-octbstack
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboctbstack.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../out/android/$(TARGET_ARCH_ABI)/release
+LOCAL_MODULE := libandroid-oc
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboc.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../out/android/$(TARGET_ARCH_ABI)/release
+LOCAL_MODULE := libandroid-coap
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libcoap.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+OIC_SRC_PATH := ../../../resource
+OIC_OUT_PATH := ../../../out
+LOCAL_MODULE := ocstack-jni
+LOCAL_SRC_FILES := JniOcStack.cpp \
+ JniUtils.cpp \
+ JniEntityHandler.cpp \
+ JniOnResourceFoundListener.cpp \
+ JniOnDeviceInfoListener.cpp \
+ JniOnPresenceListener.cpp \
+ JniOnGetListener.cpp \
+ JniOnPutListener.cpp \
+ JniOnPostListener.cpp \
+ JniOnDeleteListener.cpp \
+ JniOnObserveListener.cpp \
+ JniOcRepresentation.cpp \
+ JniOcResourceHandle.cpp \
+ JniOcPresenceHandle.cpp \
+ JniOcRequestHandle.cpp \
+ JniOcResourceRequest.cpp \
+ JniOcResourceResponse.cpp \
+ JniOcPlatform.cpp \
+ JniOcResource.cpp
+
+LOCAL_LDLIBS := -llog
+LOCAL_STATIC_LIBRARIES := android-oc
+LOCAL_STATIC_LIBRARIES += android-octbstack
+LOCAL_STATIC_LIBRARIES += android-coap
+LOCAL_STATIC_LIBRARIES += android-oc_logger
+LOCAL_CPPFLAGS += -std=c++0x
+LOCAL_CPP_FEATURES := rtti exceptions
+LOCAL_C_INCLUDES := $(OIC_SRC_PATH)/include
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/stack/include
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/ocsocket/include
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/oc_logger/include
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/../extlibs/boost/boost_1_58_0
+
+include $(BUILD_SHARED_LIBRARY)
+
+
--- /dev/null
+NDK_TOOLCHAIN_VERSION := 4.9
+APP_STL := gnustl_shared
\ No newline at end of file
--- /dev/null
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-19
--- /dev/null
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="fill_parent"
+ android:layout_height="fill_parent"
+ android:orientation="vertical"
+ android:paddingBottom="5dp"
+ android:paddingLeft="10dp"
+ android:paddingRight="10dp"
+ android:paddingTop="10dp" >
+
+ <LinearLayout
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal" >
+
+ <LinearLayout
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginRight="20dp"
+ android:paddingTop="10dp"
+ android:orientation="horizontal">
+
+ <TextView
+ android:id="@+id/temperature"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:text="Temperature : "
+ android:textSize="20sp"
+ android:textStyle="bold" />
+
+ <TextView
+ android:id="@+id/temperatureValue"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:text="0"
+ android:textSize="15sp"
+ android:textStyle="bold" />
+ </LinearLayout>
+
+ <LinearLayout
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal" >
+
+ <Button
+ android:id="@+id/btnTemperatureUP"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="Up"
+ android:textSize="18sp" />
+
+ <Button
+ android:id="@+id/btnTemperatureDown"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginRight="0dp"
+ android:text="Down"
+ android:textSize="18sp" />
+ </LinearLayout>
+ </LinearLayout>
+
+ <LinearLayout
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal" >
+
+ <LinearLayout
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginRight="20dp"
+ android:paddingTop="10dp"
+ android:orientation="horizontal">
+
+ <TextView
+ android:id="@+id/humidity"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:text="Humidity : "
+ android:textSize="20sp"
+ android:textStyle="bold" />
+
+ <TextView
+ android:id="@+id/humidityValue"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:text="0"
+ android:textSize="15sp"
+ android:textStyle="bold" />
+ </LinearLayout>
+
+ <LinearLayout
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal" >
+
+ <Button
+ android:id="@+id/btnHumidityUP"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="Up"
+ android:textSize="18sp" />
+
+ <Button
+ android:id="@+id/btnHumidityDown"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginRight="0dp"
+ android:text="Down"
+ android:textSize="18sp" />
+ </LinearLayout>
+ </LinearLayout>
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal"
+ android:paddingTop="10dp" >
+
+ <TextView
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="Received Method Type : "
+ android:textSize="15sp"
+ android:textStyle="bold" />
+
+ <TextView
+ android:id="@+id/receivedMethodType"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="None"
+ android:textSize="15sp"
+ android:textStyle="bold" />
+ </LinearLayout>
+
+ <Space
+ android:layout_width="match_parent"
+ android:layout_height="10dp" />
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="5dp"
+ android:background="#111111"
+ android:orientation="vertical" >
+ </LinearLayout>
+
+ <Space
+ android:layout_width="match_parent"
+ android:layout_height="5dp" />
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="vertical"
+ android:paddingTop="0dp" >
+
+ <Button
+ android:id="@+id/btnLogClear"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="CLEAR LOG"
+ android:textSize="18sp" />
+
+ <ScrollView
+ android:id="@+id/sclLog"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent" >
+
+ <TextView
+ android:id="@+id/txtLog"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:layout_alignParentBottom="true"
+ android:layout_alignParentLeft="true"
+ android:textSize="15sp" />
+ </ScrollView>
+ </LinearLayout>
+
+</LinearLayout>
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">SampleProvider</string>
+ <string name="start">Start</string>
+ <string name="stop">Stop</string>
+ <string name="received">Received</string>
+ <string name="current_log">Current Log</string>
+ <string name="none">None</string>
+ <string name="quit">Quit</string>
+</resources>
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2015 Intel Corporation.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // 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 com.example.sample.provider;
+
+public interface IMessageLogger
+{
+ public void logMessage(String msg);
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics 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 com.example.sample.provider;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.os.Bundle;
+import android.os.Message;
+import android.support.v4.content.LocalBroadcastManager;
+import android.util.Log;
+import android.view.KeyEvent;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.ScrollView;
+import android.widget.TextView;
+
+
+
+public class SampleProvider extends Activity implements OnClickListener,
+ IMessageLogger
+{
+ private final static String TAG = "SampleProvider : ";
+ private TextView mLogTextView;
+ private TextView mTempValue;
+ private TextView mHumValue;
+ private TemperatureResource mySensor;
+ private boolean isExecutePresence;
+ private ScrollView sv_sclLog;
+ private MessageReceiver mMessageReceiver = new MessageReceiver();
+ /*
+ * To initialize UI Function Setting
+ * To execute initOICStack for running find resource
+ */
+ @Override
+ public void onCreate(Bundle savedInstanceState)
+ {
+
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.sampleprovider_layout);
+ registerReceiver(mMessageReceiver, new IntentFilter(
+ "com.example.sample.provider.SampleProvider"));
+
+ mLogTextView = (TextView) findViewById(R.id.txtLog);
+ mTempValue = (TextView) findViewById(R.id.temperatureValue);
+ mHumValue = (TextView) findViewById(R.id.humidityValue);
+
+ sv_sclLog = (ScrollView)findViewById(R.id.sclLog);
+ sv_sclLog.fullScroll(View.FOCUS_DOWN);
+ findViewById(R.id.btnTemperatureUP).setOnClickListener(this);
+ findViewById(R.id.btnTemperatureDown).setOnClickListener(this);
+ findViewById(R.id.btnHumidityUP).setOnClickListener(this);
+ findViewById(R.id.btnHumidityDown).setOnClickListener(this);
+ findViewById(R.id.btnLogClear).setOnClickListener(this);
+
+
+ isExecutePresence = false;
+ }
+
+ private void initOICStack()
+ {
+ // create platform config
+ PlatformConfig cfg = new PlatformConfig(this,ServiceType.IN_PROC,
+ ModeType.SERVER, "0.0.0.0", // bind to all available interfaces
+ 0, QualityOfService.HIGH);
+ OcPlatform.Configure(cfg);
+
+ try
+ {
+ OcPlatform.startPresence(30);
+ isExecutePresence = true;
+ }
+ catch (OcException e)
+ {
+ e.printStackTrace();
+ }
+
+ mySensor = new TemperatureResource(this);
+ // create and register a resource
+ mySensor.createResource();
+ }
+ /*
+ * To execute initOICStack for running find resource
+ */
+ @Override
+ protected void onStart()
+ {
+ super.onStart();
+ initOICStack();
+
+ }
+ /*
+ * To execute initOICStack for running find resource
+ */
+ @Override
+ protected void onRestart()
+ {
+ super.onRestart();
+ initOICStack();
+
+ }
+ /*
+ * To terminate presence process and unregister messageHandler(to get message from JNI Function)
+ */
+ @Override
+ protected void onDestroy()
+ {
+ super.onDestroy();
+
+ try
+ {
+ mySensor.destroyResource();
+
+ if (isExecutePresence == true)
+ {
+ OcPlatform.stopPresence();
+ isExecutePresence = false;
+ }
+ }
+ catch (OcException e)
+ {
+ e.printStackTrace();
+ }
+ LocalBroadcastManager.getInstance(this).unregisterReceiver(
+ mMessageReceiver);
+ }
+
+ public class MessageReceiver extends BroadcastReceiver
+ {
+ @Override
+ public void onReceive(Context context, Intent intent)
+ {
+ final String message = intent
+ .getStringExtra(StringConstants.MESSAGE);
+ logMessage(message);
+
+ }
+ }
+
+ public void logMessage(final String text)
+ {
+ runOnUiThread(new Runnable()
+ {
+ public void run()
+ {
+ final Message msg = new Message();
+ msg.obj = text;
+ mLogTextView.append("\n");
+ mLogTextView.append(text);
+ }
+ });
+ Log.i(TAG, text);
+ }
+ /*
+ * To terminate presence process and unregister messagehandler(to get message from JNI Function)
+ */
+ @Override
+ protected void onStop()
+ {
+ super.onStop();
+ try
+ {
+ mySensor.destroyResource();
+
+ if (isExecutePresence == true)
+ {
+ OcPlatform.stopPresence();
+ isExecutePresence = false;
+ }
+
+ }
+ catch (OcException e)
+ {
+
+ e.printStackTrace();
+ }
+ LocalBroadcastManager.getInstance(this).unregisterReceiver(
+ mMessageReceiver);
+ }
+
+ @Override
+ public void onClick(View v)
+ {
+ int getId = v.getId();
+
+ switch (getId)
+ {
+ case R.id.btnTemperatureUP:
+ logMessage(TAG + "Click temerature up btn");
+ mySensor.mtemp++;
+ mySensor.notifyObserver();
+ break;
+ case R.id.btnTemperatureDown:
+ logMessage(TAG + "Click temerature down btn");
+ mySensor.mtemp--;
+ mySensor.notifyObserver();
+ break;
+ case R.id.btnHumidityUP:
+ logMessage(TAG + "Click Humidity up btn");
+ mySensor.mhumidity++;
+ mySensor.notifyObserver();
+ break;
+ case R.id.btnHumidityDown:
+ logMessage(TAG + "Click Humidity down btn");
+ mySensor.mhumidity--;
+ mySensor.notifyObserver();
+ break;
+ case R.id.btnLogClear:
+ mLogTextView.setText("");
+ break;
+ }
+
+ mTempValue.setText(String.valueOf(mySensor.getTemp()));
+ mHumValue.setText(String.valueOf(mySensor.getHumidity()));
+
+ }
+ /*
+ * To handle event about back button
+ */
+ @Override
+ public boolean onKeyDown(int keyCode, KeyEvent event)
+ {
+ if (keyCode == KeyEvent.KEYCODE_BACK )
+ {
+ try
+ {
+ mySensor.destroyResource();
+
+ if (isExecutePresence == true)
+ {
+ OcPlatform.stopPresence();
+ isExecutePresence = false;
+ }
+ }
+ catch (OcException e)
+ {
+
+ e.printStackTrace();
+ }
+ LocalBroadcastManager.getInstance(this).unregisterReceiver(
+ mMessageReceiver);
+ }
+ return super.onKeyDown(keyCode, event);
+ }
+}
\ No newline at end of file
--- /dev/null
+package com.example.sample.provider;
+
+import org.iotivity.base.OcPlatform;
+
+public class StringConstants
+{
+ public static final String RESOURCE_URI = "/a/TempHumSensor/hosting";
+ public static final String RESOURCE_TYPENAME = "Resource.Hosting";
+ public static final String RESOURCE_INTERFACE = OcPlatform.DEFAULT_INTERFACE; //resource interface
+ public static final String HUMIDITY = "humidity";
+ public static final String TEMPERATURE = "temperature";
+ public static final String MESSAGE = "message";
+ public static final int ERROR_CODE = 200;
+
+}
\ No newline at end of file
--- /dev/null
+package com.example.sample.provider;
+
+import java.util.EnumSet;
+import java.util.LinkedList;
+import java.util.List;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.ObservationInfo;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.RequestType;
+import org.iotivity.base.ResourceProperty;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+public class TemperatureResource implements IMessageLogger
+{
+ private Context mContext;
+ public int mtemp;
+ public int mhumidity;
+ private OcRepresentation mTempRep;
+ private OcResourceHandle mResourceHandle;
+ private List<Byte> mObservationIds;
+
+ private static String TAG = "SampleProvider : ";
+
+ TemperatureResource(Context context)
+ {
+ mContext = context;
+ mtemp = 0;
+ mhumidity = 0;
+ mResourceHandle = null;
+ mObservationIds = new LinkedList<Byte>();
+ mTempRep = new OcRepresentation();
+ mTempRep.setValueInt(StringConstants.TEMPERATURE, mtemp);
+ mTempRep.setValueInt(StringConstants.HUMIDITY, mhumidity);
+ }
+
+ // accessor methods
+ protected int getTemp()
+ {
+ return mtemp;
+ }
+
+ protected void setTemp(int temp)
+ {
+ mtemp = temp;
+ }
+
+ protected int getHumidity()
+ {
+ return mhumidity;
+ }
+
+ protected void setHumidity(int humidity)
+ {
+ mhumidity = humidity;
+ }
+
+ protected OcResourceHandle getHandle()
+ {
+ return mResourceHandle;
+ }
+ protected OcResourceHandle destroyResource()
+ {
+ if (mResourceHandle != null)
+ {
+ try
+ {
+ OcPlatform.unregisterResource(mResourceHandle);
+ }
+ catch (OcException e)
+ {
+ e.printStackTrace();
+ }
+ mResourceHandle = null;
+ }
+ return null;
+ }
+ protected OcResourceHandle createResource()
+ {
+
+ OcPlatform.EntityHandler eh = new OcPlatform.EntityHandler()
+ {
+ @Override
+ public EntityHandlerResult handleEntity(
+ OcResourceRequest ocResourceRequest)
+ {
+ // this is where the main logic of simpleserver is handled as
+ // different requests (GET, PUT, POST, OBSERVE, DELETE) are
+ // handled
+ return entityHandler(ocResourceRequest);
+ }
+ };
+
+ try
+ {
+ Log.e(TAG, "before registerResource!");
+ mResourceHandle = OcPlatform.registerResource(
+ StringConstants.RESOURCE_URI,
+ StringConstants.RESOURCE_TYPENAME,
+ StringConstants.RESOURCE_INTERFACE, eh, EnumSet.of(
+ ResourceProperty.DISCOVERABLE, ResourceProperty.OBSERVABLE));
+ Log.e(TAG, "after regiterResource");
+ }
+ catch (OcException e)
+ {
+ Log.e(TAG, "go exception");
+ logMessage(TAG + "RegisterResource error. " + e.getMessage());
+ Log.e(TAG, e.getMessage());
+ }
+
+ // logMessage(TAG + "Successfully registered resource");
+ return mResourceHandle;
+ }
+
+ private void put(OcRepresentation rep)
+ {
+ mtemp = rep.getValueInt(StringConstants.TEMPERATURE);
+ mhumidity = rep.getValueInt(StringConstants.HUMIDITY);
+ logMessage(TAG + "temperature : " + mtemp + "humidity : " + mhumidity);
+ // " Power: " + mPower);
+ }
+
+ protected OcRepresentation get()
+ {
+ mTempRep.setValueInt(StringConstants.TEMPERATURE, mtemp);
+ mTempRep.setValueInt(StringConstants.HUMIDITY, mhumidity);
+ return mTempRep;
+ }
+
+ private EntityHandlerResult entityHandler(OcResourceRequest request)
+ {
+ EntityHandlerResult result = EntityHandlerResult.ERROR;
+ if (null != request)
+ {
+ RequestType requestType = request.getRequestType();
+ EnumSet<RequestHandlerFlag> requestFlag = request
+ .getRequestHandlerFlagSet();
+
+
+
+ if (requestFlag.contains(RequestHandlerFlag.INIT))
+ {
+ logMessage(TAG + "Init");
+ }
+
+ if (requestFlag.contains(RequestHandlerFlag.REQUEST))
+ {
+ try
+ {
+ logMessage(TAG + "Request");
+ OcResourceResponse ocResourceResponse = new OcResourceResponse();
+ ocResourceResponse.setRequestHandle(request
+ .getRequestHandle());
+ ocResourceResponse.setResourceHandle(request
+ .getResourceHandle());
+
+ switch (requestType)
+ {
+ // handle GET request
+ case GET:
+ logMessage("GET");
+ ocResourceResponse
+ .setResponseResult(EntityHandlerResult.OK);
+ ocResourceResponse
+ .setErrorCode(StringConstants.ERROR_CODE);
+ ocResourceResponse.setResourceRepresentation(get());
+ OcPlatform.sendResponse(ocResourceResponse);
+ break;
+ // handle PUT request
+ case PUT:
+ logMessage(TAG + "PUT");
+ OcRepresentation rep = request
+ .getResourceRepresentation();
+ put(rep);
+ ocResourceResponse
+ .setErrorCode(StringConstants.ERROR_CODE);
+ ocResourceResponse
+ .setResponseResult(EntityHandlerResult.OK);
+ ocResourceResponse.setResourceRepresentation(get());
+ OcPlatform.sendResponse(ocResourceResponse);
+ break;
+ // handle POST request
+ case POST:
+ break;
+ // handle DELETE request
+ case DELETE:
+ logMessage(TAG + "DELETE");
+ OcPlatform.unregisterResource(getHandle());
+ break;
+
+ }
+
+ result = EntityHandlerResult.OK;
+ }
+ catch (Exception e)
+ {
+ logMessage(TAG + "Error in Request " + e.getMessage());
+ Log.e(TAG, e.getMessage());
+ }
+ }
+ // handle OBSERVER request
+ if (requestFlag.contains(RequestHandlerFlag.OBSERVER))
+ {
+ logMessage(TAG + "OBSERVER");
+ ObservationInfo observationInfo = request.getObservationInfo();
+ switch (observationInfo.getObserveAction())
+ {
+ case REGISTER:
+ mObservationIds.add(observationInfo
+ .getOcObservationId());
+
+ break;
+ case UNREGISTER:
+ mObservationIds.remove(observationInfo
+ .getOcObservationId());
+ break;
+ }
+
+ result = EntityHandlerResult.OK;
+ }
+ }
+ return result;
+ }
+
+ public void logMessage(String msg)
+ {
+ logMsg(msg);
+ }
+
+ public void logMsg(final String text)
+ {
+ Intent intent = new Intent("com.example.sample.provider.SampleProvider");
+ intent.putExtra(StringConstants.MESSAGE, text);
+ mContext.sendBroadcast(intent);
+ }
+
+ public void notifyObserver()
+ {
+ try
+ {
+ // if observationList is not empty, call notifyListOfObservers
+ if (mObservationIds.size() > 0)
+ {
+ OcResourceResponse ocResourceResponse = new OcResourceResponse();
+ ocResourceResponse.setErrorCode(StringConstants.ERROR_CODE);
+ ocResourceResponse.setResponseResult(EntityHandlerResult.OK);
+ OcRepresentation r = get();
+ ocResourceResponse.setResourceRepresentation
+ (r, OcPlatform.DEFAULT_INTERFACE);
+ OcPlatform.notifyListOfObservers(getHandle(), mObservationIds, ocResourceResponse);
+ }
+ else
+ {
+ // notify all observers if mObservationList is empty
+ OcPlatform.notifyAllObservers(getHandle());
+ }
+ }
+ catch (OcException e)
+ {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+}
notimgr_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
notimgr_c_env = notimgr_env.Clone()
notimgr_env.AppendUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap', 'pthread'])
-notimgr_c_env.AppendUnique(LIBS = ['octbstack', 'oc_logger', 'connectivity_abstraction', 'coap', 'pthread','NOTISDKLibrary'])
+notimgr_c_env.AppendUnique(LIBS = ['octbstack', 'oc_logger', 'connectivity_abstraction', 'coap', 'pthread','NotificationManager'])
if env.get('SECURED') == '1':
notimgr_env.AppendUnique(LIBS = ['tinydtls'])
}
catch (std::exception &e)
{
+ std::cout << "Exception: " << e.what() << " in foundResource" << std::endl;
}
}
#include <algorithm>
#include <signal.h>
#include "hosting.h"
-#include "virtualResource.h"
using namespace std;
using namespace OC;
}
catch (OCException &e)
{
- dlog_print(DLOG_INFO, LOG_TAG, "#### Platform configuration failed!!!!");
+ dlog_print(DLOG_INFO, LOG_TAG, "#### Platform configuration Exception!!!!");
+ dlog_print(DLOG_INFO, LOG_TAG, "#### (%s)", e.what());
}
}
}
catch (OCException &e)
{
+ ERR("findResourceCandidate exception: %s" , e.what().c_str());
}
g_oicFindAd = ad;
}
}
catch (std::exception &e)
{
+ ERR("foundResource exception: %s" , e.what().c_str());
}
}
oicappItemData *it_data;
it_data = calloc(1 , sizeof(oicappItemData));
+ if (NULL == it_data)
+ {
+ DBG("calloc failed!!!!");
+ return NULL;
+ }
it_data->title = title;
it_data->ad = ad;
item = elm_genlist_item_append(ad->genlist , itc , it_data , NULL , ELM_GENLIST_ITEM_NONE ,
oicappItemData *it_data;
it_data = calloc(1 , sizeof(oicappItemData));
+ if (NULL == it_data)
+ {
+ DBG("calloc failed!!!!");
+ return;
+ }
it_data->title = title;
it_data->ad = ad;
}
catch (std::exception &e)
{
- //log(e.what());
+ std::cout << "Exception: " << e.what() << std::endl;
}
}
}
catch (OCException &e)
{
- //log(e.what());
+ std::cout << "Exception: " << e.what() << std::endl;
}
return 0;
if target_os == 'android':
soft_sensor_manager_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
- soft_sensor_manager_env.AppendUnique(LIBS = ['gnustl_static'])
+ soft_sensor_manager_env.AppendUnique(LIBS = ['gnustl_shared'])
if not env.get('RELEASE'):
soft_sensor_manager_env.AppendUnique(LIBS = ['log'])
// for android: not complete method
if (System.getProperty("os.name").toLowerCase().equals("linux")) {
+ System.loadLibrary("gnustl_shared");
System.loadLibrary("oc_logger");
+ System.loadLibrary("connectivity_abstraction");
System.loadLibrary("octbstack");
- System.loadLibrary("coap");
System.loadLibrary("oc");
System.loadLibrary("SSMCore");
} else {
OCStackResult ret = OC_STACK_ERROR;
std::ostringstream requestURI;
- requestURI << OC_WELL_KNOWN_QUERY << "?rt=SSManager.Sensor";
+ requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=SSManager.Sensor";
std::ostringstream multicastPresenceURI;
multicastPresenceURI << "coap://" << OC_MULTICAST_PREFIX;
import java.util.List;
import java.util.UUID;
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
import org.iotivity.service.ssm.DataReader;
import org.iotivity.service.ssm.IQueryEngineEvent;
import org.iotivity.service.ssm.ModelData;
import org.iotivity.service.ssm.SSMInterface;
import android.app.Activity;
+import android.app.AlertDialog;
import android.content.Context;
+import android.content.DialogInterface;
+import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.AssetManager;
+import android.net.ConnectivityManager;
+import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
private ArrayList<Integer> mRunningQueries = new ArrayList<Integer>();
private IQueryEngineEvent mQueryEngineEventListener = null;
+ private final String LOG_TAG = this.getClass().getSimpleName();
+ private static MainActivity activityObj;
void PrintLog(String log) {
Message msg = new Message();
svLog = (ScrollView) findViewById(R.id.sclLog);
edtQuery = (EditText) findViewById(R.id.editQuery);
edtUnregisterQuery = (EditText) findViewById(R.id.editUnregisterQuery);
+
+ // calling the method to check the Wi-fi connectivity and configuring
+ // the OcPlatform
+ configurePlatform();
mQueryEngineEventListener = new IQueryEngineEvent() {
@Override
Log.e("tag", e.getMessage());
}
}
+
+ private void configurePlatform() {
+ // local Variables
+ ConnectivityManager connManager;
+ NetworkInfo wifi;
+ AlertDialog dialog;
+ PlatformConfig platformConfigObj;
+
+ // Check the wifi connectivity
+ connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
+ wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
+ if (false == wifi.isConnected()) {
+ // WiFi is not connected close the application
+ AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
+ dialogBuilder.setTitle("Error");
+ dialogBuilder
+ .setMessage("WiFi is not enabled/connected! Please connect the WiFi and start application again...");
+ dialogBuilder.setCancelable(false);
+ dialogBuilder.setPositiveButton("OK", new OnClickListener() {
+ @Override
+ public void onClick(DialogInterface dialog, int which) {
+ // Closing the application
+ activityObj.finish();
+ }
+ });
+
+ dialog = dialogBuilder.create();
+ dialog.show();
+ return;
+ }
+ // If wifi is connected calling the configure method for configuring the
+ // OcPlatform
+ platformConfigObj = new PlatformConfig(this,ServiceType.IN_PROC,
+ ModeType.CLIENT_SERVER, "0.0.0.0", 0, QualityOfService.LOW);
+
+ Log.i(LOG_TAG, "Before Calling Configure of ocPlatform");
+ OcPlatform.Configure(platformConfigObj);
+ Log.i(LOG_TAG, "Configuration done Successfully");
+ }
}
}
result = (char *)malloc(sizeof(char) * (SerialCnt + 1));
+ if (NULL == result)
+ {
+ debug_printf("Debug2BLE malloc failed .\r\n");
+ break;
+ }
memcpy(result, SerialData, SerialCnt );
result[SerialCnt] = NULL;
{
cout << e.what() << endl;
}
+
+ return 0;
}
TerminateSSM();
delete SSMApp;
+
+ return 0;
}
{
cout << e.what() << endl;
}
+
+ return 0;
}
{
cout << e.what() << endl;
}
+
+ return 0;
}
{
cout << e.what() << endl;
}
+
+ return 0;
}
if target_os == 'android':
things_manager_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
- things_manager_env.PrependUnique(LIBS = ['gnustl_shared', 'compatibility', 'log'])
+ things_manager_env.PrependUnique(LIBS = ['oc', 'octbstack', 'gnustl_shared', 'android_cpp11_compat', 'log'])
######################################################################
# Source files and Targets
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="src" path="gen"/>
+ <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+ <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
+ <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
+ <classpathentry kind="output" path="bin/classes"/>
+</classpath>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>Sample</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.ApkBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>com.android.ide.eclipse.adt.AndroidNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.tm.sample"
+ android:versionCode="1"
+ android:versionName="1.0" >
+
+ <uses-sdk
+ android:minSdkVersion="8"
+ android:targetSdkVersion="21" />
+
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+
+ <application
+ android:allowBackup="true"
+ android:icon="@drawable/iot"
+ android:label="@string/app_name"
+ android:theme="@style/AppTheme" >
+ <activity
+ android:name=".MainActivity"
+ android:label="@string/app_name" >
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+ <activity
+ android:name=".GroupApiActivity"
+ android:label="@string/app_name" >
+ </activity>
+ <activity
+ android:name=".ConfigurationApiActivity"
+ android:label="@string/app_name" >
+ </activity>
+ </application>
+
+</manifest>
--- /dev/null
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-20
+android.library.reference.1=../../../sdk/java
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+
+<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">
+
+ <ListView
+ android:id="@+id/list"
+ android:layout_height="wrap_content"
+ android:layout_width="match_parent">
+ </ListView>
+</RelativeLayout>
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:orientation="vertical" >
+
+ <ListView
+ android:id="@+id/configApisList"
+ android:layout_width="wrap_content"
+ android:layout_height="320dp" >
+
+ </ListView>
+
+
+ <EditText
+ android:id="@+id/EditText"
+ android:layout_width="fill_parent"
+ android:layout_height="250dp"
+ android:layout_alignParentLeft="true"
+ android:layout_below="@+id/configApisList"
+ android:layout_marginTop="15dp"
+ android:ems="10"
+ android:editable="false" >
+
+ <requestFocus />
+ </EditText>
+
+</RelativeLayout>
+
+
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:orientation="vertical" >
+
+
+ <DatePicker
+ android:id="@+id/datePicker1"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content" >
+ </DatePicker>
+
+ <TimePicker
+ android:id="@+id/timePicker1"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_alignParentLeft="true"
+ android:layout_below="@+id/datePicker1"
+ android:layout_marginTop="63dp" />
+
+ <Button
+ android:id="@+id/ok"
+ android:layout_width="200px"
+ android:layout_height="wrap_content"
+ android:layout_alignParentLeft="true"
+ android:layout_below="@+id/timePicker1"
+ android:layout_marginLeft="16dp"
+ android:layout_marginTop="53dp"
+ android:text="OK" />
+
+ <Button
+ android:id="@+id/cancel"
+ android:layout_width="200px"
+ android:layout_height="wrap_content"
+ android:layout_alignBaseline="@+id/ok"
+ android:layout_alignBottom="@+id/ok"
+ android:layout_alignParentRight="true"
+ android:layout_marginRight="34dp"
+ android:text="Cancel" />
+
+</RelativeLayout>
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent" >
+
+ <Button
+ android:id="@+id/button1"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_alignParentLeft="true"
+ android:layout_alignParentTop="true"
+ android:text="Find Group" />
+
+
+ <ListView
+ android:id="@+id/groupaApiList"
+ android:layout_width="match_parent"
+ android:layout_height="300dp"
+ android:layout_below="@id/button1">
+ </ListView>
+
+ <EditText
+ android:id="@+id/EditText"
+ android:layout_width="fill_parent"
+ android:layout_height="250dp"
+ android:layout_alignParentLeft="true"
+ android:layout_below="@+id/groupaApiList"
+ android:layout_marginTop="15dp"
+ android:ems="10"
+ android:editable="false" >
+
+ <requestFocus />
+ </EditText>
+
+
+</RelativeLayout>
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:orientation="vertical" >
+
+ <EditText
+ android:id="@+id/region"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_alignParentTop="true"
+ android:layout_centerHorizontal="true"
+ android:layout_marginTop="28dp"
+ android:ems="10"
+ android:hint="Enter the Region Value" />
+
+ <Button
+ android:id="@+id/ok"
+ android:layout_width="150dp"
+ android:layout_height="wrap_content"
+ android:layout_alignParentLeft="true"
+ android:layout_below="@+id/region"
+ android:layout_marginTop="101dp"
+ android:text="OK" />
+
+ <Button
+ android:id="@+id/cancel"
+ android:layout_width="150dp"
+ android:layout_height="wrap_content"
+ android:layout_alignBaseline="@+id/ok"
+ android:layout_alignBottom="@+id/ok"
+ android:layout_alignParentRight="true"
+ android:text="Cancel" />
+
+</RelativeLayout>
--- /dev/null
+<menu xmlns:android="http://schemas.android.com/apk/res/android" >
+
+ <item
+ android:id="@+id/action_settings"
+ android:orderInCategory="100"
+ android:showAsAction="never"
+ android:title="@string/action_settings"/>
+
+</menu>
--- /dev/null
+<resources>
+
+ <style name="AppBaseTheme" parent="android:Theme.Holo.Light">
+ </style>
+
+</resources>
--- /dev/null
+ <resources>
+
+ <style name="AppBaseTheme" parent="android:Theme.Light">
+ </style>
+
+ <style name="AppTheme" parent="AppBaseTheme">
+ </style>
+
+</resources>
--- /dev/null
+<resources>
+
+ <!--
+ Example customization of dimensions originally defined in res/values/dimens.xml
+ (such as screen margins) for screens with more than 820dp of available width. This
+ would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively).
+ -->
+ <dimen name="activity_horizontal_margin">64dp</dimen>
+
+</resources>
--- /dev/null
+<resources>
+
+ <!-- Default screen margins, per the Android Design guidelines. -->
+ <dimen name="activity_horizontal_margin">16dp</dimen>
+ <dimen name="activity_vertical_margin">16dp</dimen>
+
+</resources>
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+
+ <string name="app_name">TMSample</string>
+ <string name="hello_world">Hello world!</string>
+ <string name="action_settings">Settings</string>
+
+</resources>
--- /dev/null
+<resources>
+
+ <style name="AppBaseTheme" parent="android:Theme.Light">
+
+ </style>
+
+ <!-- Application theme. -->
+ <style name="AppTheme" parent="AppBaseTheme">
+
+ </style>
+
+</resources>
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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 com.tm.sample;
+
+import java.util.Vector;
+
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.service.tm.Action;
+import org.iotivity.service.tm.ActionSet;
+import org.iotivity.service.tm.Capability;
+import org.iotivity.service.tm.IActionListener;
+
+import android.os.Message;
+import android.util.Log;
+
+/*
+ * For getting the put,get,observe and post Callback and updating
+ * the UI i.e. logMessage(TextBox) of GroupApiActivity.
+ */
+public class ActionListener implements IActionListener {
+
+ private final String LOG_TAG = this.getClass()
+ .getSimpleName();
+ private static Message msg;
+ private String logMessage;
+ private GroupApiActivity groupApiActivityObj = null;
+
+ @Override
+ public void onPostResponseCallback(Vector<OcHeaderOption> headerOptions,
+ OcRepresentation rep, int errorValue) {
+ Log.i(LOG_TAG, "Got Callback : onPostResponseCallback");
+
+ groupApiActivityObj = GroupApiActivity.getGroupApiActivityObj();
+ logMessage = "API Result : SUCCESS" + "\n";
+ logMessage = logMessage
+ + "Recieved Callback for called API (OnPostCallback)" + "\n";
+
+ // sending message to handler of GroupApiActivity to Update the UI
+ GroupApiActivity.setMessageLog(logMessage);
+ msg = Message.obtain();
+ msg.what = 1;
+ groupApiActivityObj.getHandler().sendMessage(msg);
+
+ }
+
+ @Override
+ public void onGetResponseCallback(Vector<OcHeaderOption> headerOptions,
+ OcRepresentation rep, int errorValue) {
+ Log.i(LOG_TAG, "Got Callback : onGetResponseCallback");
+
+ String actionSetStr = rep.getValueString("ActionSet");
+ groupApiActivityObj = GroupApiActivity.getGroupApiActivityObj();
+ logMessage = "Recieved Callback for called API (onGetResponseCallback)"
+ + "\n" + "ActionSet:" + actionSetStr;
+
+ GroupApiActivity.setMessageLog(logMessage);
+ // sending message to handler of GroupApiActivity to Update the UI
+ msg = Message.obtain();
+ msg.what = 1;
+ groupApiActivityObj.getHandler().sendMessage(msg);
+
+ if (actionSetStr != null) {
+ ActionSet actionSet = ActionSet.toActionSet(actionSetStr);
+ if (actionSet != null) {
+ System.out.println("ActionSet Name : "
+ + actionSet.actionsetName);
+ for (int i = 0; i < actionSet.listOfAction.size(); i++) {
+ Action action = actionSet.listOfAction.get(i);
+ System.out.println("Target : " + action.target);
+
+ Vector<Capability> listOfCapability = action.listOfCapability;
+ for (int j = 0; j < listOfCapability.size(); j++) {
+ Capability capability = listOfCapability.get(j);
+ System.out.println("Capability : "
+ + capability.capability);
+ System.out.println("Status : " + capability.status);
+ }
+ }
+ }
+ }
+
+ groupApiActivityObj = GroupApiActivity.getGroupApiActivityObj();
+ GroupApiActivity.setMessageLog(logMessage);
+ msg = Message.obtain();
+ msg.what = 1;
+ groupApiActivityObj.getHandler().sendMessage(msg);
+
+ }
+
+ @Override
+ public void onPutResponseCallback(Vector<OcHeaderOption> headerOptions,
+ OcRepresentation rep, int errorValue) {
+ Log.i(LOG_TAG, "Got Callback : onPutResponseCallback");
+
+ groupApiActivityObj = GroupApiActivity.getGroupApiActivityObj();
+ logMessage = "API Result : SUCCESS" + "\n";
+ logMessage = logMessage
+ + "Recieved Callback for called API (onPutResponseCallback)"
+ + "\n";
+ GroupApiActivity.setMessageLog(logMessage);
+ // sending message to handler of GroupApiActivity to Update the UI
+ msg = Message.obtain();
+ msg.what = 1;
+ groupApiActivityObj.getHandler().sendMessage(msg);
+
+ }
+
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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 com.tm.sample;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.service.tm.IConfigurationListener;
+import org.iotivity.service.tm.IDiagnosticsListener;
+import org.iotivity.service.tm.IFindCandidateResourceListener;
+import org.iotivity.service.tm.OCStackResult;
+import org.iotivity.service.tm.ThingsManager;
+
+import android.app.Activity;
+import android.app.Dialog;
+import android.content.Context;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.util.Log;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.AdapterView;
+import android.widget.AdapterView.OnItemClickListener;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.ListView;
+import android.widget.Toast;
+
+/*
+ * Activity for Handling all Configuration Apis as per user's selection on the UI.
+ * and updating of UI
+ */
+public class ConfigurationApiActivity extends Activity {
+
+ private class ResourceInformation {
+ OcResource resource = null;
+ OcResourceHandle resourceHandle = null;
+ }
+
+ private final String LOG_TAG = "[TMSample] "
+ + this.getClass()
+ .getSimpleName();
+
+ private final String CONFIGURATION_COLLECTION_RESOURCE_URI = "/core/configuration/resourceset";
+ private final String CONFIGURATION_COLLECTION_RESOURCE_TYPE = "core.configuration.resourceset";
+ private final String DIAGNOSTIC_COLLECTION_RESOURCE_URI = "/core/diagnostics/resourceset";
+ private final String DIAGNOSTIC_COLLECTION_RESOURCE_TYPE = "core.diagnostics.resourceset";
+ private final String FACTORYSET_COLLECTION_RESOURCE_URI = "/core/factoryset/resourceset";
+ private final String FACTORYSET_COLLECTION_RESOURCE_TYPE = "core.factoryset.resourceset";
+
+ private final String CONFIGURATION_RESOURCE_URI = "/oic/con";
+ private final String DIAGNOSTIC_RESOURCE_URI = "/oic/diag";
+ private final String FACTORYSET_RESOURCE_URI = "/factorySet";
+
+ private ListView list;
+ private ArrayAdapter<String> configurationApis;
+ private ArrayList<String> configurationApisList;
+
+ private static int messageCount = 0;
+ private static EditText logs;
+ private static String logMessage = "";
+ private static Handler mHandler;
+ private static Message msg;
+
+ private ThingsManager thingsManager = null;
+ private Map<String, ResourceInformation> resourceList = null;
+ private Map<String, ResourceInformation> collectionList = null;
+
+ public boolean configurationResourceFlag = false;
+ public boolean factorySetResourceFlag = false;
+ public boolean diagnosticsResourceFlag = false;
+
+ public static Context mcontext;
+ public String region = "";
+ public boolean findGroupPressedFlag = false;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.configapis);
+
+ mcontext = this;
+ thingsManager = new ThingsManager();
+
+ // set the listeners
+ setResourceListener();
+ setConfigurationListener();
+ setDiagnosticsListener();
+
+ // Create API menu list
+ configurationApisList = new ArrayList<String>();
+
+ logs = (EditText) findViewById(R.id.EditText);
+
+ list = (ListView) findViewById(R.id.configApisList);
+ configurationApisList.add("Find All Groups");
+ configurationApisList.add("Find All Resources");
+ configurationApisList.add("Get a Configuration Resource");
+ configurationApisList.add("Update Attribute (Region)");
+ configurationApisList.add("Factory Reset");
+ configurationApisList.add("Reboot");
+ configurationApisList.add("Get Supported Configuration Units");
+ configurationApis = new ArrayAdapter<String>(this,
+ android.R.layout.simple_list_item_1, configurationApisList);
+ list.setAdapter(configurationApis);
+
+ // setting the Listener for calling the APIs as per User selection
+ list.setOnItemClickListener(new OnItemClickListener() {
+
+ @Override
+ public void onItemClick(AdapterView<?> parent, View view,
+ int position, long id) {
+
+ // Find All Groups
+ if (position == 0) {
+ Vector<String> resourceTypes = new Vector<String>();
+ resourceTypes.add("core.configuration.resourceset");
+ findCandidateResources(resourceTypes);
+
+ logMessage = "";
+ messageCount = 0;
+ messageCount++;
+
+ resourceTypes.clear();
+ resourceTypes.add("core.diagnostics.resourceset");
+ findCandidateResources(resourceTypes);
+
+ messageCount++;
+
+ resourceTypes.clear();
+ resourceTypes.add("core.factoryset.resourceset");
+ findCandidateResources(resourceTypes);
+
+ messageCount++;
+
+ } else if (position == 1) { // Find All Resources
+ if (false == findGroupPressedFlag) {
+ displayToastMessage("Configuration collection resource does not exist!");
+ } else {
+ Vector<String> resourceTypes = new Vector<String>();
+ resourceTypes.add("oic.con");
+ findCandidateResources(resourceTypes);
+
+ logMessage = "";
+ messageCount = 0;
+ messageCount++;
+
+ resourceTypes.clear();
+ resourceTypes.add("oic.diag");
+ findCandidateResources(resourceTypes);
+
+ messageCount++;
+
+ resourceTypes.clear();
+ resourceTypes.add("factorySet");
+ findCandidateResources(resourceTypes);
+
+ messageCount++;
+ }
+ } else if (position == 2) { // Get Configuration
+ getConfiguration();
+ } else if (position == 3) { // Update Attribute (Region)
+ userInputDialog();
+ } else if (position == 4) { // Factory Reset
+ factoryReset();
+ } else if (position == 5) { // Reboot
+ reboot();
+ } else if (position == 6) { // Get Supported Configuration Units
+ String configurationUnits;
+ configurationUnits = getListOfSupportedConfigurationUnits();
+ Log.i(LOG_TAG, "Configuration Units:" + configurationUnits);
+ logMessage = configurationUnits;
+ logs.setText("");
+ logs.setText(logMessage);
+
+ }
+ }
+ });
+
+ resourceList = new HashMap<String, ResourceInformation>();
+ collectionList = new HashMap<String, ResourceInformation>();
+
+ try {
+ createResourceCollection(CONFIGURATION_COLLECTION_RESOURCE_URI,
+ CONFIGURATION_COLLECTION_RESOURCE_TYPE);
+ createResourceCollection(DIAGNOSTIC_COLLECTION_RESOURCE_URI,
+ DIAGNOSTIC_COLLECTION_RESOURCE_TYPE);
+ createResourceCollection(FACTORYSET_COLLECTION_RESOURCE_URI,
+ FACTORYSET_COLLECTION_RESOURCE_TYPE);
+ } catch (OcException e) {
+ Log.e(LOG_TAG, "OcException occured! " + e.toString());
+ }
+
+ // handler for updating the UI i.e. LogMessage TextBox
+ mHandler = new Handler() {
+ @Override
+ public void handleMessage(Message msg) {
+ switch (msg.what) {
+ case 0:
+ logs.setText("");
+ logs.setText(logMessage);
+ }
+ }
+ };
+
+ }
+
+ private void userInputDialog() {
+
+ ResourceInformation configurationCollection = collectionList
+ .get(CONFIGURATION_COLLECTION_RESOURCE_URI);
+ if (null == configurationCollection
+ || null == configurationCollection.resource) {
+ Log.e(LOG_TAG, "configuration collection resource doest not exist!");
+ displayToastMessage("Configuration collection resource does not exist!");
+ }
+ if (false == configurationResourceFlag) {
+ Log.e(LOG_TAG, "configuration resource doest not exist!");
+ displayToastMessage("Configuration resource does not exist!");
+ } else {
+ final Dialog dialog = new Dialog(mcontext);
+ dialog.setContentView(R.layout.userinputforregionvalue);
+ dialog.setTitle("Enter the Region Value");
+
+ dialog.setCancelable(false);
+ dialog.show();
+ Button ok = (Button) dialog.findViewById(R.id.ok);
+ Button cancel = (Button) dialog.findViewById(R.id.cancel);
+
+ ok.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View v) {
+
+ EditText regionValue = (EditText) dialog
+ .findViewById(R.id.region);
+ region = regionValue.getText().toString();
+ if (region.equalsIgnoreCase("")) {
+ String toastmessage = "Please enter the Region Value";
+ displayToastMessage(toastmessage);
+ } else {
+ dialog.dismiss();
+ updateConfiguration(region);
+ }
+ }
+ });
+ cancel.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ dialog.dismiss();
+ }
+ });
+ }
+ }
+
+ @Override
+ public void onBackPressed() {
+ super.onBackPressed();
+
+ // unregistering resource from the platform
+ deleteResources();
+ resourceList.clear();
+ resourceList = null;
+ collectionList.clear();
+ collectionList = null;
+ }
+
+ private void setResourceListener() {
+ thingsManager
+ .setFindCandidateResourceListener(new IFindCandidateResourceListener() {
+
+ @Override
+ synchronized public void onResourceCallback(
+ Vector<OcResource> resources) {
+ Log.i(LOG_TAG, "onResourceCallback: enter");
+ for (int i = 0; i < resources.size(); i++) {
+ OcResource resource = resources.get(i);
+ String uri = resource.getUri();
+ String host = resource.getHost();
+
+ // Display resource information
+ Log.i(LOG_TAG, "Resource URI:" + uri);
+ Log.i(LOG_TAG, "Resource HOST: " + host);
+ Log.i(LOG_TAG, "Resource types: ");
+ logMessage = logMessage + "Resource URI : " + uri
+ + "\n";
+ logMessage = logMessage + "Resource Host : " + host
+ + "\n";
+
+ List<String> resourcetypes = resource
+ .getResourceTypes();
+ for (int j = 0; j < resourcetypes.size(); j++) {
+ Log.i(LOG_TAG, resourcetypes.get(j));
+ logMessage = logMessage + "ResourceType "
+ + (j + 1) + " : "
+ + resourcetypes.get(j) + "\n";
+ }
+
+ Log.i(LOG_TAG, "Interface types: ");
+ List<String> interfacetypes = resource
+ .getResourceInterfaces();
+ for (int j = 0; j < interfacetypes.size(); j++) {
+ Log.i(LOG_TAG, interfacetypes.get(j));
+ logMessage = logMessage + "interfacetype "
+ + (j + 1) + " : "
+ + interfacetypes.get(j) + "\n";
+ }
+
+ try {
+ if (true == uri.contains("/resourceset")) {
+ collectionFound(resource);
+ } else {
+ resourceFound(resource);
+ }
+ } catch (OcException e) {
+ Log.e(LOG_TAG,
+ "OcExcepion occured! " + e.toString());
+ }
+ }
+ if (messageCount == 3) {
+ msg = Message.obtain();
+ msg.what = 0;
+ mHandler.sendMessage(msg);
+ }
+ }
+ });
+ }
+
+ private void setConfigurationListener() {
+ thingsManager.setConfigurationListener(new IConfigurationListener() {
+ @Override
+ public void onBootStrapCallback(
+ Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+ int errorValue) {
+ Log.i(LOG_TAG, "onBootStrapCallback: enter");
+ }
+
+ @Override
+ public void onUpdateConfigurationsCallback(
+ Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+ int errorValue) {
+ Log.i(LOG_TAG, "onUpdateConfigurationsCallback: enter");
+ Log.i(LOG_TAG, "Resource URI: " + rep.getUri());
+ if (rep.hasAttribute("loc")) {
+ logMessage = logMessage + "Location : "
+ + rep.getValueString("loc") + "\n";
+ }
+ if (rep.hasAttribute("st")) {
+ logMessage = logMessage + "System Time : "
+ + rep.getValueString("loc") + "\n";
+ }
+ if (rep.hasAttribute("c")) {
+ logMessage = logMessage + "Currency : "
+ + rep.getValueString("c") + "\n";
+ }
+ if (rep.hasAttribute("r")) {
+ logMessage = logMessage + "Region : "
+ + rep.getValueString("r") + "\n";
+ }
+
+ }
+
+ @Override
+ public void onGetConfigurationsCallback(
+ Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+ int errorValue) {
+ Log.i(LOG_TAG, "onGetConfigurationsCallback: enter");
+ Log.i(LOG_TAG, "Resource URI: " + rep.getUri());
+ logMessage = logMessage + "Resource URI : " + rep.getUri()
+ + "\n";
+
+ if (rep.hasAttribute("loc")) {
+ logMessage = logMessage + "Location : "
+ + rep.getValueString("loc") + "\n";
+ }
+ if (rep.hasAttribute("st")) {
+ logMessage = logMessage + "System Time : "
+ + rep.getValueString("st") + "\n";
+ }
+ if (rep.hasAttribute("c")) {
+ logMessage = logMessage + "Currency : "
+ + rep.getValueString("c") + "\n";
+ }
+ if (rep.hasAttribute("r")) {
+ logMessage = logMessage + "Region : "
+ + rep.getValueString("r") + "\n";
+ }
+
+ msg = Message.obtain();
+ msg.what = 0;
+ mHandler.sendMessage(msg);
+ }
+ });
+ }
+
+ private void setDiagnosticsListener() {
+ thingsManager.setDiagnosticsListener(new IDiagnosticsListener() {
+
+ @Override
+ public void onRebootCallback(Vector<OcHeaderOption> headerOptions,
+ OcRepresentation rep, int errorValue) {
+ Log.i(LOG_TAG, "onRebootCallback: enter");
+ }
+
+ @Override
+ public void onFactoryResetCallback(
+ Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+ int errorValue) {
+ Log.i(LOG_TAG, "onFactoryResetCallback: enter");
+ }
+ });
+ }
+
+ /**
+ * This method find the resources available in network.
+ */
+ private void findCandidateResources(Vector<String> resourceTypes) {
+ OCStackResult result = thingsManager.findCandidateResources(
+ resourceTypes, 5);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "Error while calling findCandidateResources");
+ String toastmessage = "findCandidateResources API returned error! ["
+ + result + "]";
+ displayToastMessage(toastmessage);
+ }
+ if (messageCount == 1)
+ logMessage = logMessage + "API RESULT : " + result.toString()
+ + "\n";
+ }
+
+ /**
+ * This method gets the configuration data from con-server.
+ */
+ private void getConfiguration() {
+ Log.i(LOG_TAG, "There are " + resourceList.size()
+ + " servers present in network");
+ ResourceInformation configurationCollection = collectionList
+ .get(CONFIGURATION_COLLECTION_RESOURCE_URI);
+ if (null == configurationCollection
+ || null == configurationCollection.resource) {
+ Log.e(LOG_TAG, "configuration collection resource doest not exist!");
+ displayToastMessage("Configuration collection resource does not exist!");
+ return;
+ }
+ if (false == configurationResourceFlag) {
+
+ Log.e(LOG_TAG, "configuration resource doest not exist!");
+ displayToastMessage("Configuration resource does not exist!");
+ return;
+ }
+
+ String name = "all";
+ Vector<String> configs = new Vector<String>();
+ configs.add(name);
+
+ OCStackResult result = OCStackResult.OC_STACK_ERROR;
+ try {
+ result = thingsManager.getConfigurations(
+ configurationCollection.resource, configs);
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "getConfigurations failed!");
+ String toastmessage = "getConfigurations API returned error! ["
+ + result + "]";
+ displayToastMessage(toastmessage);
+ }
+ logMessage = "API RESULT : " + result.toString() + "\n";
+ msg = Message.obtain();
+ msg.what = 0;
+ mHandler.sendMessage(msg);
+ }
+
+ /**
+ * This method update the configuration resource region attribute to given
+ * value.
+ *
+ * @param region
+ */
+ private void updateConfiguration(String region) {
+ ResourceInformation configurationCollection = collectionList
+ .get(CONFIGURATION_COLLECTION_RESOURCE_URI);
+ String name = "r";
+ Map<String, String> configurations = new HashMap<String, String>();
+
+ try {
+ configurations.put(name, region);
+ } catch (Exception e) {
+ Log.e(LOG_TAG, "Exception occured! " + e.toString());
+ }
+
+ OCStackResult result = OCStackResult.OC_STACK_ERROR;
+ try {
+ result = thingsManager.updateConfigurations(
+ configurationCollection.resource, configurations);
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "updateConfigurations failed!");
+ String toastmessage = "updateConfigurations API returned error! ["
+ + result + "]";
+ displayToastMessage(toastmessage);
+ }
+ logMessage = "API RESULT : " + result.toString() + "\n";
+ logMessage = logMessage + "Updating region to " + region;
+ msg = Message.obtain();
+ msg.what = 0;
+ mHandler.sendMessage(msg);
+ }
+
+ /**
+ * This method send request to reset all the configuration attribute values
+ * to default.
+ */
+ private void factoryReset() {
+ ResourceInformation diagnosticsCollection = collectionList
+ .get(DIAGNOSTIC_COLLECTION_RESOURCE_URI);
+ if (null == diagnosticsCollection
+ || null == diagnosticsCollection.resource) {
+ Log.e(LOG_TAG, "Diagnostic collection doest not exist!");
+ displayToastMessage("Diagnostic collection does not exist!");
+ return;
+ }
+
+ if (false == diagnosticsResourceFlag) {
+ Log.e(LOG_TAG, "Diagnostic resource doest not exist!");
+ displayToastMessage("Diagnostic resource does not exist!");
+ return;
+ }
+
+ OCStackResult result = OCStackResult.values()[30];
+
+ try {
+ result = thingsManager.factoryReset(diagnosticsCollection.resource);
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "factoryReset failed!");
+ String toastmessage = "factoryReset API returned error! [" + result
+ + "]";
+ displayToastMessage(toastmessage);
+
+ }
+ logMessage = "API RESULT : " + result.toString() + "\n";
+ msg = Message.obtain();
+ msg.what = 0;
+ mHandler.sendMessage(msg);
+ }
+
+ /**
+ * This method send request to reboot server.
+ */
+ private void reboot() {
+ ResourceInformation diagnosticsCollection = collectionList
+ .get(DIAGNOSTIC_COLLECTION_RESOURCE_URI);
+ if (null == diagnosticsCollection
+ || null == diagnosticsCollection.resource) {
+ Log.e(LOG_TAG, "Diagnostic collection doest not exist!");
+ displayToastMessage("Diagnostic collection does not exist!");
+ return;
+ }
+ if (false == diagnosticsResourceFlag) {
+ Log.e(LOG_TAG, "Diagnostic resource doest not exist!");
+ displayToastMessage("Diagnostic resource does not exist!");
+ return;
+ }
+
+ OCStackResult result = OCStackResult.OC_STACK_ERROR;
+ try {
+ result = thingsManager.reboot(diagnosticsCollection.resource);
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "reboot failed!");
+ String toastmessage = "reboot API returned error! [" + result + "]";
+ displayToastMessage(toastmessage);
+ }
+ logMessage = "API RESULT : " + result.toString() + "\n";
+ msg = Message.obtain();
+ msg.what = 0;
+ mHandler.sendMessage(msg);
+ }
+
+ /**
+ * This method is for getting list of all supported configuration values.
+ * Response will be in JSON format (key-value pair).
+ */
+ private String getListOfSupportedConfigurationUnits() {
+ return thingsManager.getListOfSupportedConfigurationUnits();
+ }
+
+ private void displayToastMessage(String message) {
+ Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
+ toast.show();
+ }
+
+ private void collectionFound(OcResource resource) {
+ String uri = resource.getUri();
+ ResourceInformation resourceInfo = collectionList.get(uri);
+ if (null == resourceInfo) {
+ Log.e(LOG_TAG, "Collection is not created!");
+ return;
+ }
+
+ if (null != resourceInfo.resource) {
+ Log.e(LOG_TAG, "Collection resource already updated!");
+ return;
+ }
+
+ resourceInfo.resource = resource;
+ if (3 == messageCount) {
+ findGroupPressedFlag = true;
+ }
+ }
+
+ /**
+ * This callback will be invoked when the interested resource discovered in
+ * network.
+ */
+ private void resourceFound(OcResource resource) throws OcException {
+ String uri = resource.getUri();
+ String host = resource.getHost();
+
+ // Check if the resource already exist in the map table
+ ResourceInformation resourceInfo = resourceList.get(uri + host);
+ if (null != resourceInfo) {
+ Log.e(LOG_TAG, "Resource already exists!");
+ return;
+ }
+
+ // Create resource
+ resourceInfo = new ResourceInformation();
+ resourceInfo.resource = resource;
+ if (uri.equalsIgnoreCase("/oic/con")) {
+ ResourceInformation collectionResource = collectionList
+ .get(CONFIGURATION_COLLECTION_RESOURCE_URI);
+ if (null == collectionResource
+ || null == collectionResource.resourceHandle) {
+ Log.e(LOG_TAG, "Invalid Configuration collection!");
+ return;
+ }
+
+ ResourceInformation resourceInfoCollection;
+ resourceInfoCollection = collectionList
+ .get(CONFIGURATION_COLLECTION_RESOURCE_URI);
+ OcResourceHandle handle;
+ handle = resourceInfoCollection.resourceHandle;
+ resourceInfo.resourceHandle = handle;
+ resourceInfo.resourceHandle = thingsManager.bindResourceToGroup(
+ resource, handle);
+
+ resourceList.put(uri + host, resourceInfo);
+ configurationResourceFlag = true;
+ } else if (uri.equalsIgnoreCase("/oic/diag")) {
+ ResourceInformation diagnosticResource = collectionList
+ .get(DIAGNOSTIC_COLLECTION_RESOURCE_URI);
+ if (null == diagnosticResource
+ || null == diagnosticResource.resourceHandle) {
+ Log.e(LOG_TAG, "Invalid Configuration collection!");
+ return;
+ }
+
+ ResourceInformation resourceInfoCollection;
+ resourceInfoCollection = collectionList
+ .get(DIAGNOSTIC_COLLECTION_RESOURCE_URI);
+ OcResourceHandle handle;
+ handle = resourceInfoCollection.resourceHandle;
+ resourceInfo.resourceHandle = handle;
+ resourceInfo.resourceHandle = thingsManager.bindResourceToGroup(
+ resource, handle);
+
+ resourceList.put(uri + host, resourceInfo);
+ diagnosticsResourceFlag = true;
+ } else if (uri.equalsIgnoreCase("/factorySet")) {
+ ResourceInformation factorysetResource = collectionList
+ .get(FACTORYSET_COLLECTION_RESOURCE_URI);
+ if (null == factorysetResource
+ || null == factorysetResource.resourceHandle) {
+ Log.e(LOG_TAG, "Invalid Configuration collection!");
+ return;
+ }
+
+ ResourceInformation resourceInfoCollection;
+ resourceInfoCollection = collectionList
+ .get(FACTORYSET_COLLECTION_RESOURCE_URI);
+ OcResourceHandle handle;
+ handle = resourceInfoCollection.resourceHandle;
+ resourceInfo.resourceHandle = handle;
+ resourceInfo.resourceHandle = thingsManager.bindResourceToGroup(
+ resource, handle);
+
+ resourceList.put(uri + host, resourceInfo);
+ factorySetResourceFlag = true;
+ } else {
+ Log.e(LOG_TAG, "Resource is of different type: " + uri);
+ return;
+ }
+ }
+
+ private void createResourceCollection(String uri, String typename)
+ throws OcException {
+
+ Map<String, OcResourceHandle> groupList = new HashMap<String, OcResourceHandle>();
+
+ Log.i(LOG_TAG, "createGroup: " + typename);
+ // Check if the resource collection is already created
+ if (null != collectionList.get(uri)) {
+ Log.e(LOG_TAG, "Collection is already exist!");
+ return;
+ }
+
+ OcResourceHandle resourceHandle = null;
+
+ // Crate group
+ OCStackResult result = thingsManager.createGroup(typename);
+ if ((OCStackResult.OC_STACK_OK != result)) {
+ Log.e(LOG_TAG, "createGroup returned error: " + result.name());
+ return;
+ } else {
+ Log.e(LOG_TAG, "createGroup returned: " + result.name());
+ }
+ groupList = thingsManager.getGroupList();
+ if (groupList.containsKey(typename)) {
+ resourceHandle = groupList.get(typename);
+ } else {
+ Log.e(LOG_TAG, "group does not contain groupResourceType: "
+ + result.name());
+ }
+
+ if (null == resourceHandle) {
+ Log.e(LOG_TAG, " createResourceCollection : resourceHandle is NULL");
+
+ }
+ // Add the collection resource to map table
+ ResourceInformation resourceInfo = new ResourceInformation();
+ resourceInfo.resourceHandle = resourceHandle;
+ collectionList.put(uri, resourceInfo);
+ Log.i(LOG_TAG, "size of collectionList : " + collectionList.size());
+ }
+
+ private void deleteResources() {
+ Log.i(LOG_TAG, "deleteResources: enter");
+ try {
+ // unregister all resources
+ for (ResourceInformation resource : resourceList.values()) {
+ if (null != resource.resourceHandle) {
+ if (resource.resource.getUri().equalsIgnoreCase(
+ CONFIGURATION_RESOURCE_URI)) {
+ ResourceInformation collectionResource = collectionList
+ .get(CONFIGURATION_COLLECTION_RESOURCE_URI);
+ if (null != collectionResource
+ && null != collectionResource.resourceHandle) {
+ OcPlatform
+ .unregisterResource(resource.resourceHandle);
+ Log.i(LOG_TAG, "unregistered resource"
+ + CONFIGURATION_COLLECTION_RESOURCE_URI);
+
+ }
+ } else if (resource.resource.getUri().equalsIgnoreCase(
+ DIAGNOSTIC_RESOURCE_URI)) {
+ ResourceInformation diagnosticResource = collectionList
+ .get(DIAGNOSTIC_COLLECTION_RESOURCE_URI);
+ if (null != diagnosticResource
+ && null != diagnosticResource.resourceHandle) {
+ OcPlatform
+ .unregisterResource(resource.resourceHandle);
+ Log.i(LOG_TAG, "unregistered resource"
+ + CONFIGURATION_COLLECTION_RESOURCE_URI);
+ }
+ } else if (resource.resource.getUri().equalsIgnoreCase(
+ FACTORYSET_RESOURCE_URI)) {
+ ResourceInformation factorysetResource = collectionList
+ .get(FACTORYSET_COLLECTION_RESOURCE_URI);
+ if (null != factorysetResource
+ && null != factorysetResource.resourceHandle) {
+ OcPlatform
+ .unregisterResource(resource.resourceHandle);
+ Log.i(LOG_TAG, "unregistered resource"
+ + CONFIGURATION_COLLECTION_RESOURCE_URI);
+
+ }
+ }
+ }
+ }
+
+ // delete all the groups
+ thingsManager.deleteGroup(CONFIGURATION_COLLECTION_RESOURCE_TYPE);
+ thingsManager.deleteGroup(DIAGNOSTIC_COLLECTION_RESOURCE_TYPE);
+ thingsManager.deleteGroup(FACTORYSET_COLLECTION_RESOURCE_TYPE);
+ } catch (OcException e) {
+ Log.e(LOG_TAG, "OcException occured! " + e.toString());
+ }
+ }
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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 com.tm.sample;
+
+import java.util.Vector;
+
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.service.tm.IConfigurationListener;
+
+import android.util.Log;
+
+/*
+ * For receiving configuration APIs callback : Update and Get
+ */
+public class ConfigurationListener implements IConfigurationListener {
+
+ private final String LOG_TAG = this.getClass().getSimpleName();
+
+ @Override
+ public void onBootStrapCallback(Vector<OcHeaderOption> headerOptions,
+ OcRepresentation rep, int errorValue) {
+ Log.i(LOG_TAG, "Got Callback : onBootStrapCallback");
+ }
+
+ @Override
+ public void onUpdateConfigurationsCallback(
+ Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+ int errorValue) {
+ Log.i(LOG_TAG, "Got Callback : onUpdateConfigurationsCallback");
+
+ }
+
+ @Override
+ public void onGetConfigurationsCallback(
+ Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+ int errorValue) {
+ Log.i(LOG_TAG, "Got Callback : onGetConfigurationsCallback");
+
+ }
+
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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 com.tm.sample;
+
+import java.util.Vector;
+
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.service.tm.IDiagnosticsListener;
+
+import android.util.Log;
+
+/**
+ * For receiving Diagnostic APIs callback : BootStrap,Reboot & FactoryReset
+ */
+public class DiagnosticListener implements IDiagnosticsListener {
+
+ private final String LOG_TAG = this.getClass().getSimpleName();
+
+ @Override
+ public void onRebootCallback(Vector<OcHeaderOption> headerOptions,
+ OcRepresentation rep, int errorValue) {
+ Log.i(LOG_TAG, "Got Callback : onRebootCallback");
+
+ }
+
+ @Override
+ public void onFactoryResetCallback(Vector<OcHeaderOption> headerOptions,
+ OcRepresentation rep, int errorValue) {
+ Log.i(LOG_TAG, "Got Callback : onFactoryResetCallback");
+
+ }
+
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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 com.tm.sample;
+
+import java.util.ArrayList;
+import java.util.Calendar;
+
+import android.app.Activity;
+import android.app.Dialog;
+import android.content.Context;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.AdapterView;
+import android.widget.AdapterView.OnItemClickListener;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.DatePicker;
+import android.widget.DatePicker.OnDateChangedListener;
+import android.widget.EditText;
+import android.widget.ListView;
+import android.widget.TimePicker;
+import android.widget.TimePicker.OnTimeChangedListener;
+import android.widget.Toast;
+
+/*
+ * Activity for handling user's selection on UI for GroupApis.
+ * & for updating UI.
+ */
+public class GroupApiActivity extends Activity {
+
+ private ListView list;
+ private Button findGroup;
+ private ArrayAdapter<String> groupApis;
+ private ArrayList<String> groupApisList;
+ private static GroupApiActivity groupApiActivityObj;
+ private GroupClient groupClientObj;
+ private static Handler mHandler;
+
+ private static EditText logs;
+ private static String logMessage;
+
+ // For Scheduled ActionSet
+ public static Context mcontext;
+ public static Calendar scheduleTime;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.groupapis);
+
+ groupApiActivityObj = this;
+ mcontext = this;
+
+ groupClientObj = new GroupClient();
+ groupApisList = new ArrayList<String>();
+ list = (ListView) findViewById(R.id.groupaApiList);
+ findGroup = (Button) findViewById(R.id.button1);
+ logs = (EditText) findViewById(R.id.EditText);
+
+ // adding the item to list that will be displayed on the UI.
+ groupApisList.add("1. Create ActionSet (ALLBULBON & ALLBULBOFF)");
+ groupApisList.add("2. Execute ActionSet (ALLBULBON)");
+ groupApisList.add("3. Execute ActionSet (AllBULBOFF)");
+
+ // Recursive GroupAction
+ groupApisList.add("4. Create ActionSet (Recursive_ALLBULBON)");
+ groupApisList.add(" 4.1 Execute ActionSet");
+ groupApisList.add(" 4.2 Cancel ActionSet");
+
+ // scheduled GroupAction
+ groupApisList.add("5. Create ActionSet (Scheduled_ALLBULBOFF)");
+ groupApisList.add(" 5.1 Execute ActionSet");
+ groupApisList.add(" 5.2 Cancel ActionSet");
+
+ groupApisList.add("6. Get ActionSet(ALLBULBOFF)");
+ groupApisList.add("7. Delete ActionSet(ALLBULBOFF)");
+ groupApisList.add("8. Find BookMark to Observe");
+
+ // handler for updating the UI i.e. MessageLog (TextBox) & ListView
+ mHandler = new Handler() {
+ @Override
+ public void handleMessage(Message msg) {
+ switch (msg.what) {
+ case 0:
+ groupApis = new ArrayAdapter<String>(
+ groupApiActivityObj,
+ android.R.layout.simple_list_item_1,
+ groupApisList);
+ list.setAdapter(groupApis);
+ list.bringToFront();
+ break;
+ case 1:
+ logs.setText("");
+ logs.setText(logMessage);
+ }
+ }
+ };
+ setHandler(mHandler);
+
+ // find group Button Listener
+ findGroup.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ groupClientObj.findGroup();
+ }
+ });
+
+ // Listener for item clicked by the user on the UI
+ list.setOnItemClickListener(new OnItemClickListener() {
+ @Override
+ public void onItemClick(AdapterView<?> parent, View view,
+ int position, long id) {
+ if (position == 0) {
+ groupClientObj.createActionSetBulbOn();
+ groupClientObj.createActionSetBulbOff();
+ } else if (position == 1) {
+ groupClientObj.executeActionSetBulbOn(0);
+ } else if (position == 2) {
+ groupClientObj.executeActionSetBulbOff(0);
+ } else if (position == 3) {
+ groupClientObj.createRecursiveActionSetBulbOn();
+ } else if (position == 4) {
+ groupClientObj.executeRecursiveActionSetBulbOn(0);
+ } else if (position == 5) {
+ groupClientObj.cancelRecursiveActionSetBulbOn();
+ } else if (position == 6) {
+ showDateAndTimeDialog();
+ } else if (position == 7) {
+ groupClientObj.executeScheduledActionSetBulbOff(0);
+ } else if (position == 8) {
+ groupClientObj.cancelScheduledActionSetBulbOff();
+ } else if (position == 9) {
+ groupClientObj.getActionSetBulbOff();
+ } else if (position == 10) {
+ groupClientObj.deleteActionSetBulbOff();
+ } else if (position == 11) {
+ groupClientObj.findBookMarkResources();
+ }
+ }
+ });
+
+ // creating group and find light resources
+ groupClientObj.createGroup();
+ groupClientObj.findLightResources();
+ }
+
+ public void showDateAndTimeDialog() {
+ // for scheduled actionSet
+ scheduleTime = Calendar.getInstance();
+
+ final Dialog dialog = new Dialog(mcontext);
+ dialog.setContentView(R.layout.custom_dialog);
+ dialog.setTitle("Choose date and time for Secheduling");
+
+ TimePicker tp = (TimePicker) dialog.findViewById(R.id.timePicker1);
+ DatePicker dp = (DatePicker) dialog.findViewById(R.id.datePicker1);
+ Button ok = (Button) dialog.findViewById(R.id.ok);
+ Button cancel = (Button) dialog.findViewById(R.id.cancel);
+
+ dialog.setCancelable(false);
+ dialog.show();
+ tp.setOnTimeChangedListener(new OnTimeChangedListener() {
+ @Override
+ public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
+ scheduleTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
+ scheduleTime.set(Calendar.MINUTE, minute);
+ }
+ });
+ dp.init(dp.getYear(), dp.getMonth(), dp.getDayOfMonth(),
+ new OnDateChangedListener() {
+ @Override
+ public void onDateChanged(DatePicker arg0, int arg1,
+ int arg2, int arg3) {
+ scheduleTime.set(arg1, arg2, arg3);
+ }
+ });
+ ok.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ dialog.dismiss();
+
+ // Calculate the time difference in delay
+ Calendar localTime = Calendar.getInstance();
+ if (scheduleTime.compareTo(localTime) != 1) {
+ groupApiActivityObj
+ .displayToastMessage("Invalid set time!");
+ return;
+ }
+
+ long delay = scheduleTime.getTimeInMillis()
+ - localTime.getTimeInMillis();
+ delay /= 1000;
+
+ groupClientObj.createScheduledActionSetBulbOff(delay);
+ }
+ });
+ cancel.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ dialog.dismiss();
+ }
+ });
+ }
+
+ public static void setMessageLog(String message) {
+ logMessage = message;
+ }
+
+ @Override
+ public void onBackPressed() {
+ super.onBackPressed();
+ // unregister the resource and set callback listener to null
+ groupClientObj.leaveGroup();
+ }
+
+ // for update UI these functions will be called from GroupClient Class
+ public static GroupApiActivity getGroupApiActivityObj() {
+ return groupApiActivityObj;
+ }
+
+ public Handler getHandler() {
+ return mHandler;
+ }
+
+ public void setHandler(Handler mHandler) {
+ GroupApiActivity.mHandler = mHandler;
+ }
+
+ public void displayToastMessage(String message) {
+ Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
+ toast.show();
+ }
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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 com.tm.sample;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import org.iotivity.base.ObserveType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.OcResource.OnObserveListener;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.service.tm.Action;
+import org.iotivity.service.tm.ActionSet;
+import org.iotivity.service.tm.Capability;
+import org.iotivity.service.tm.IFindCandidateResourceListener;
+import org.iotivity.service.tm.IFindGroupListener;
+import org.iotivity.service.tm.OCStackResult;
+import org.iotivity.service.tm.ThingsManager;
+import org.iotivity.service.tm.Time.ActionSetType;
+
+import android.os.Message;
+import android.util.Log;
+
+/**
+ * For calling the group APIs as per user selection on UI and for updating the
+ * UI
+ */
+public class GroupClient {
+
+ private static final String LOG_TAG = "GroupClient";
+ private static Message msg;
+ public String logMessage;
+
+ private final String groupResourceType = "b.collection";
+
+ private final ThingsManager thingsManagerObj;
+ private final ActionListener actionListener;
+ private final ObserveListener observeListener;
+ private OcResource groupResource;
+ private OcResourceHandle groupResourceHandle;
+ private OcResourceHandle foundLightHandle;
+ private static GroupApiActivity groupApiActivityObj = null;
+ public static Vector<String> lights = new Vector<String>();
+ public static Vector<String> bookmarks = new Vector<String>();
+
+ /**
+ * Listener for receiving observe notifications.
+ */
+ private class ObserveListener implements OnObserveListener {
+ @Override
+ public void onObserveCompleted(List<OcHeaderOption> headerOptionList,
+ OcRepresentation ocRepresentation, int sequenceNumber) {
+ Log.i(LOG_TAG, "onObserveCompleted invoked");
+ if (0 == ocRepresentation.getValueInt("level")) {
+ createActionSetBulbOn();
+ executeActionSetBulbOn(0);
+ } else if (5 == ocRepresentation.getValueInt("level")) {
+ createActionSetBulbOff();
+ executeActionSetBulbOff(0);
+ }
+ }
+
+ @Override
+ public void onObserveFailed(Throwable arg0) {
+ }
+ }
+
+ /**
+ * Listener for receiving groups discovered in network.
+ */
+ private class FindGroupListener implements IFindGroupListener {
+ @Override
+ public void onGroupFindCallback(OcResource resource) {
+ Log.i(LOG_TAG, "onGroupFindCallback invoked");
+ if (resource != null) {
+ String uri = resource.getUri();
+ if (uri.equals("/b/collection") == true) {
+ String hostAddress = resource.getHost();
+ Log.d("URI: onGroupFindCallback", uri);
+ Log.d("HOST: onGroupFindCallback", hostAddress);
+
+ groupResource = resource;
+ Message msg = Message.obtain();
+ msg.what = 0;
+ groupApiActivityObj.getHandler().sendMessage(msg);
+
+ logMessage = "onGroupFind" + "\n";
+ logMessage = logMessage + "URI : " + uri + "\n";
+ logMessage = logMessage + "Host :" + hostAddress;
+ GroupApiActivity.setMessageLog(logMessage);
+ msg = Message.obtain();
+ msg.what = 1;
+ groupApiActivityObj.getHandler().sendMessage(msg);
+ } else {
+ Log.d("onGroupFindCallback URI : ", uri);
+ }
+ } else {
+ Log.i(LOG_TAG, "Resource is NULL");
+ }
+ }
+ };
+
+ /**
+ * Listener for receiving Light resource and Observe resources discovered in
+ * network.
+ */
+ private class FindCadidateResourceListener implements
+ IFindCandidateResourceListener {
+ @Override
+ public void onResourceCallback(Vector<OcResource> resources) {
+ Log.i(LOG_TAG, "onResourceCallback invoked");
+
+ if (resources != null) {
+ for (int i = 0; i < resources.size(); i++) {
+ Log.d(LOG_TAG, "Resource information");
+ OcResource ocResource = resources.get(i);
+ String resourceURI = ocResource.getUri();
+ String hostAddress = ocResource.getHost();
+
+ logMessage = "API RESULT : " + "OC_STACK_OK" + "\n";
+ logMessage = logMessage + "URI: " + resourceURI + "\n";
+ logMessage = logMessage + "Host:" + hostAddress;
+ GroupApiActivity.setMessageLog(logMessage);
+ msg = Message.obtain();
+ msg.what = 1;
+ groupApiActivityObj.getHandler().sendMessage(msg);
+
+ if (resourceURI.equals("/a/light") == true) {
+ if (lights.contains((hostAddress + resourceURI)) == false) {
+ lights.add((hostAddress + resourceURI));
+ if (groupApiActivityObj != null) {
+
+ logMessage = "API RESULT : " + "OC_STACK_OK"
+ + "\n";
+ logMessage = logMessage + "URI: " + resourceURI
+ + "\n";
+ logMessage = logMessage + "Host:" + hostAddress;
+ GroupApiActivity.setMessageLog(logMessage);
+ msg = Message.obtain();
+ msg.what = 1;
+ groupApiActivityObj.getHandler().sendMessage(
+ msg);
+ try {
+ foundLightHandle = thingsManagerObj
+ .bindResourceToGroup(ocResource,
+ groupResourceHandle);
+
+ } catch (OcException e) {
+ Log.i(LOG_TAG,
+ "bindResourceToGroup Exception!");
+ }
+ }
+ } else {
+ Log.i(LOG_TAG, "Resource is already registered!");
+ }
+ } else if (resourceURI.equalsIgnoreCase("/core/bookmark")) {
+ if (bookmarks.contains((hostAddress + resourceURI)) == false) {
+ bookmarks.add((hostAddress + resourceURI));
+ if (groupApiActivityObj != null) {
+ logMessage = "API RESULT : " + "OC_STACK_OK"
+ + "\n";
+ logMessage = logMessage + "URI: " + resourceURI
+ + "\n";
+ logMessage = logMessage + "Host:" + hostAddress;
+ GroupApiActivity.setMessageLog(logMessage);
+ msg = Message.obtain();
+ msg.what = 1;
+ groupApiActivityObj.getHandler().sendMessage(
+ msg);
+
+ }
+ observe(ocResource);
+ }
+ }
+ }
+ }
+ }
+ };
+
+ private final FindCadidateResourceListener findCandidateResourceListener;
+ private final FindGroupListener findGroupListener;
+
+ public GroupClient() {
+ thingsManagerObj = new ThingsManager();
+ findGroupListener = new FindGroupListener();
+ actionListener = new ActionListener();
+ observeListener = new ObserveListener();
+ findCandidateResourceListener = new FindCadidateResourceListener();
+
+ thingsManagerObj.setGroupListener(findGroupListener);
+ thingsManagerObj
+ .setFindCandidateResourceListener(findCandidateResourceListener);
+ thingsManagerObj.setActionListener(actionListener);
+
+ groupApiActivityObj = GroupApiActivity.getGroupApiActivityObj();
+ }
+
+ /**
+ * This method creates group of the type "b.collection" handling light
+ * resources.
+ */
+ public void createGroup() {
+ Map<String, OcResourceHandle> groupList = new HashMap<String, OcResourceHandle>();
+
+ // creating group of type b.collection
+ OCStackResult result = thingsManagerObj.createGroup(groupResourceType);
+ if ((OCStackResult.OC_STACK_OK != result)) {
+ Log.e(LOG_TAG, "createGroup returned error: " + result.name());
+ return;
+ } else {
+ Log.e(LOG_TAG, "createGroup success: " + result.name());
+ }
+
+ // getting the Created group Handle
+ groupList = thingsManagerObj.getGroupList();
+ if (groupList.containsKey(groupResourceType)) {
+ groupResourceHandle = groupList.get(groupResourceType);
+ } else {
+ Log.e(LOG_TAG, "group does not contain groupResourceType: "
+ + result.name());
+ }
+ }
+
+ /**
+ * This method finds the group of type "b.collection".
+ */
+ public void findGroup() {
+ Log.d(LOG_TAG, "finding group");
+
+ Vector<String> resourceTypes = new Vector<String>();
+ resourceTypes.add(groupResourceType);
+ OCStackResult result = thingsManagerObj.findGroup(resourceTypes);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "findGroup returned error: " + result.name());
+ return;
+ }
+
+ logMessage = "API RESULT : " + result.toString();
+ GroupApiActivity.setMessageLog(logMessage);
+ logMessage = "";
+ if (groupApiActivityObj != null) {
+ msg = Message.obtain();
+ msg.what = 1;
+ groupApiActivityObj.getHandler().sendMessage(msg);
+ }
+ }
+
+ /**
+ * This method finds the light resources of type "core.light".
+ */
+ public void findLightResources() {
+ Log.d(LOG_TAG, "finding light resources");
+
+ Vector<String> types = new Vector<String>();
+ types.add("core.light");
+ OCStackResult result = thingsManagerObj
+ .findCandidateResources(types, 5);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG,
+ "findCandidateResources returned error: " + result.name());
+ }
+ }
+
+ /**
+ * This method finds the bookmark resources of type "core.bookmark".
+ */
+ public void findBookMarkResources() {
+ Log.d(LOG_TAG, "finding bookmark resources");
+
+ Vector<String> types = new Vector<String>();
+ types.add("core.bookmark");
+ OCStackResult result = thingsManagerObj
+ .findCandidateResources(types, 5);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG,
+ "findCandidateResources returned error: " + result.name());
+ }
+ }
+
+ /**
+ * This method creates the action set for bulb on action.
+ */
+ public void createActionSetBulbOn() {
+ Log.i(LOG_TAG, "creating action set for bulb on action");
+
+ if (lights.size() == 0) {
+ groupApiActivityObj
+ .displayToastMessage("No Light server found in network!");
+ return;
+ }
+
+ ActionSet actionSet = new ActionSet();
+ actionSet.actionsetName = "AllBulbOn";
+
+ // Create actions list
+ for (int i = 0; i < lights.size(); i++) {
+ Action action = new Action();
+ action.target = lights.get(i);
+
+ Capability capability = new Capability();
+ capability.capability = "power";
+ capability.status = "on";
+
+ action.listOfCapability.add(capability);
+ actionSet.listOfAction.add(action);
+ }
+
+ try {
+ OCStackResult result = thingsManagerObj.addActionSet(groupResource,
+ actionSet);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "addActionSet returned error: " + result.name());
+ return;
+ }
+ } catch (OcException e) {
+ e.printStackTrace();
+ return;
+ }
+ }
+
+ /**
+ * This method creates the action set for bulb off action.
+ */
+ public void createActionSetBulbOff() {
+ Log.i(LOG_TAG, "creating action set for bulb off action");
+
+ if (lights.size() == 0) {
+ groupApiActivityObj
+ .displayToastMessage("No Light server found in network!");
+ return;
+ }
+
+ ActionSet actionSet = new ActionSet();
+ actionSet.actionsetName = "AllBulbOff";
+
+ // Create actions list
+ for (int i = 0; i < lights.size(); i++) {
+ Action action = new Action();
+ action.target = lights.get(i);
+
+ Capability capability = new Capability();
+ capability.capability = "power";
+ capability.status = "off";
+
+ action.listOfCapability.add(capability);
+ actionSet.listOfAction.add(action);
+ }
+
+ try {
+ OCStackResult result = thingsManagerObj.addActionSet(groupResource,
+ actionSet);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "addActionSet returned error: " + result.name());
+ return;
+ }
+ } catch (OcException e) {
+ e.printStackTrace();
+ return;
+ }
+ }
+
+ /**
+ * This method creates the recursive action set for bulb on action.
+ */
+ public void createRecursiveActionSetBulbOn() {
+ Log.i(LOG_TAG, "creating recursive action set for bulb on action");
+
+ if (lights.size() == 0) {
+ groupApiActivityObj
+ .displayToastMessage("No Light server found in network!");
+ return;
+ }
+
+ ActionSet actionSet = new ActionSet();
+ actionSet.actionsetName = "AllBulbOnRecursive";
+ actionSet.setType(ActionSetType.RECURSIVE);
+ actionSet.mYear = 0;
+ actionSet.mMonth = 0;
+ actionSet.mDay = 0;
+ actionSet.mHour = 0;
+ actionSet.mMin = 0;
+ actionSet.mSec = 5;
+ actionSet.setDelay(actionSet.getSecAbsTime());
+
+ // Create actions list
+ for (int i = 0; i < lights.size(); i++) {
+ Action action = new Action();
+ action.target = lights.get(i);
+
+ Capability capability = new Capability();
+ capability.capability = "power";
+ capability.status = "on";
+
+ action.listOfCapability.add(capability);
+ actionSet.listOfAction.add(action);
+ }
+
+ try {
+ OCStackResult result = thingsManagerObj.addActionSet(groupResource,
+ actionSet);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "addActionSet returned error: " + result.name());
+ return;
+ }
+ } catch (OcException e) {
+ e.printStackTrace();
+ return;
+ }
+ }
+
+ /**
+ * This method creates the scheduled action set for bulb off action.
+ */
+ public void createScheduledActionSetBulbOff(long delay) {
+ Log.i(LOG_TAG, "creating scheduled action set for bulb off action");
+
+ if (lights.size() == 0) {
+ groupApiActivityObj
+ .displayToastMessage("No Light server found in network!");
+ return;
+ }
+
+ ActionSet actionSet = new ActionSet();
+ actionSet.actionsetName = "AllBulbOffScheduled";
+ actionSet.setType(ActionSetType.SCHEDULED);
+ actionSet.setDelay(delay);
+ Log.i(LOG_TAG, "Set the delay of " + delay + " seconds");
+
+ // Create actions list
+ for (int i = 0; i < lights.size(); i++) {
+ Action action = new Action();
+ action.target = lights.get(i);
+
+ Capability capability = new Capability();
+ capability.capability = "power";
+ capability.status = "off";
+
+ action.listOfCapability.add(capability);
+ actionSet.listOfAction.add(action);
+ }
+
+ try {
+ OCStackResult result = thingsManagerObj.addActionSet(groupResource,
+ actionSet);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "addActionSet returned error: " + result.name());
+ return;
+ }
+ } catch (OcException e) {
+ e.printStackTrace();
+ return;
+ }
+ }
+
+ /**
+ * This method is for executing the action Set "AllBulbOn".
+ */
+ public void executeActionSetBulbOn(long delay) {
+ Log.i(LOG_TAG, "executing the action set of bulb on action");
+
+ if (lights.size() == 0) {
+ groupApiActivityObj
+ .displayToastMessage("No Light server found in network!");
+ return;
+ }
+
+ executeActionSet("AllBulbOn", delay);
+ }
+
+ /**
+ * This method is for executing the action Set "AllBulbOff".
+ */
+ public void executeActionSetBulbOff(long delay) {
+ Log.i(LOG_TAG, "executing the action set of bulb off action");
+
+ if (lights.size() == 0) {
+ groupApiActivityObj
+ .displayToastMessage("No Light server found in network!");
+ return;
+ }
+
+ executeActionSet("AllBulbOff", delay);
+ }
+
+ /**
+ * This method is for executing the recursive action Set
+ * "AllBulbOnRecursive".
+ */
+ public void executeRecursiveActionSetBulbOn(long delay) {
+ Log.i(LOG_TAG, "executing the recursive action set of bulb on action");
+
+ if (lights.size() == 0) {
+ groupApiActivityObj
+ .displayToastMessage("No Light server found in network!");
+ return;
+ }
+
+ executeActionSet("AllBulbOnRecursive", delay);
+ }
+
+ /**
+ * This method is for executing the schedule action Set
+ * "AllBulbOffScheduled".
+ */
+ public void executeScheduledActionSetBulbOff(long delay) {
+ Log.i(LOG_TAG, "executing the schedule action set of bulb off action");
+
+ if (lights.size() == 0) {
+ groupApiActivityObj
+ .displayToastMessage("No Light server found in network!");
+ return;
+ }
+
+ executeActionSet("AllBulbOffScheduled", delay);
+ }
+
+ /**
+ * This method is for canceling the action Set "AllBulbOn".
+ */
+ public void cancelActionSetBulbOn() {
+ Log.i(LOG_TAG, "cancelling the action set of bulb on action");
+
+ if (lights.size() == 0) {
+ groupApiActivityObj
+ .displayToastMessage("No Light server found in network!");
+ return;
+ }
+
+ cancelActionSet("AllBulbOn");
+ }
+
+ /**
+ * This method is for canceling the action Set "AllBulbOff".
+ */
+ public void cancelActionSetBulbOff() {
+ Log.i(LOG_TAG, "cancelling the action set of bulb off action");
+
+ if (lights.size() == 0) {
+ groupApiActivityObj
+ .displayToastMessage("No Light server found in network!");
+ return;
+ }
+
+ cancelActionSet("AllBulbOff");
+ }
+
+ /**
+ * This method is for canceling the recursive action Set
+ * "AllBulbOnRecursive".
+ */
+ public void cancelRecursiveActionSetBulbOn() {
+ Log.i(LOG_TAG, "cancelling the recursive action set of bulb on action");
+
+ if (lights.size() == 0) {
+ groupApiActivityObj
+ .displayToastMessage("No Light server found in network!");
+ return;
+ }
+
+ cancelActionSet("AllBulbOnRecursive");
+ }
+
+ /**
+ * This method is for canceling the scheduled action Set
+ * "AllBulbOffScheduled".
+ */
+ public void cancelScheduledActionSetBulbOff() {
+ Log.i(LOG_TAG, "cancelling the scheduled action set of bulb off action");
+
+ if (lights.size() == 0) {
+ groupApiActivityObj
+ .displayToastMessage("No Light server found in network!");
+ return;
+ }
+
+ cancelActionSet("AllBulbOffScheduled");
+ }
+
+ /**
+ * This method is for getting the action Set "AllBulbOn".
+ */
+ public void getActionSetBulbOn() {
+ Log.i(LOG_TAG, "getting the action set of bulb on action");
+
+ try {
+ OCStackResult result = thingsManagerObj.getActionSet(groupResource,
+ "AllBulbOn");
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG,
+ "getActionSetOn returned error: " + result.name());
+ return;
+ }
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * This method is for getting the action Set "AllBulbOff".
+ */
+ public void getActionSetBulbOff() {
+ Log.i(LOG_TAG, "getting the action set of bulb off action");
+
+ try {
+ OCStackResult result = thingsManagerObj.getActionSet(groupResource,
+ "AllBulbOff");
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG,
+ "getActionSetOn returned error: " + result.name());
+ return;
+ }
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * This method is for deleting the action Set "AllBulbOn".
+ */
+ public void deleteActionSetBulbOn() {
+ Log.i(LOG_TAG, "deleting the action set of bulb on action");
+
+ try {
+ OCStackResult result = thingsManagerObj.deleteActionSet(
+ groupResource, "AllBulbOn");
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG,
+ "deleteActionSet returned error : " + result.name());
+ return;
+ }
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * This method is for deleting the action Set "AllBulbOff".
+ */
+ public void deleteActionSetBulbOff() {
+ Log.i(LOG_TAG, "deleting the action set of bulb off action");
+
+ try {
+ OCStackResult result = thingsManagerObj.deleteActionSet(
+ groupResource, "AllBulbOff");
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG,
+ "deleteActionSet returned error : " + result.name());
+ return;
+ }
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * This method is for observing the bulb on/off status.
+ */
+ public void observe(OcResource resource) {
+ Log.i(LOG_TAG, "Registering observer for bookmark resources status");
+
+ Map<String, String> queryMap = new HashMap<String, String>();
+ try {
+ resource.observe(ObserveType.OBSERVE, queryMap, observeListener);
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * This method is for unbinding and unregister all the found resources and
+ * groups.
+ */
+ public void leaveGroup() {
+ thingsManagerObj.setGroupListener(null);
+ thingsManagerObj.setFindCandidateResourceListener(null);
+ thingsManagerObj.setActionListener(null);
+
+ if (null != foundLightHandle) {
+ try {
+ OcPlatform.unregisterResource(foundLightHandle);
+ } catch (OcException e) {
+ e.printStackTrace();
+ Log.i(LOG_TAG, "Resource Unregister Exception");
+ }
+ } else {
+ Log.i(LOG_TAG, "foundLightHandle is NULL");
+ }
+ if (null != groupResourceHandle) {
+
+ thingsManagerObj.deleteGroup(groupResourceType);
+ } else {
+ Log.i(LOG_TAG, "groupResourceHandle is NULL");
+ }
+ }
+
+ private void executeActionSet(String actonSetName, long delay) {
+ try {
+ OCStackResult result = thingsManagerObj.executeActionSet(
+ groupResource, actonSetName, delay);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG,
+ "executeActionSet retuned error : " + result.name());
+ return;
+ }
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void cancelActionSet(String actionSetName) {
+ try {
+ OCStackResult result = thingsManagerObj.cancelActionSet(
+ groupResource, actionSetName);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG,
+ "cancelActionSet returned error : " + result.name());
+ return;
+ }
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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 com.tm.sample;
+
+import java.util.ArrayList;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+import org.iotivity.service.tm.ThingsManager;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.content.DialogInterface;
+import android.content.DialogInterface.OnClickListener;
+import android.content.Intent;
+import android.net.ConnectivityManager;
+import android.net.NetworkInfo;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.View;
+import android.widget.AdapterView;
+import android.widget.AdapterView.OnItemClickListener;
+import android.widget.ArrayAdapter;
+import android.widget.ListView;
+
+/**
+ * Starting Activity of the application responsible for configuring the
+ * OcPlatform and redirecting to other activity according to user's selection on
+ * UI.
+ */
+public class MainActivity extends Activity {
+
+ private static MainActivity activityObj;
+ private ArrayAdapter<String> apis;
+ private ArrayList<String> apisList;
+ private ListView list;
+ private final String LOG_TAG = this.getClass()
+ .getSimpleName();
+ public ThingsManager thingsManagerObj = new ThingsManager();
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_main);
+ activityObj = this;
+
+ list = (ListView) findViewById(R.id.list);
+ apisList = new ArrayList<String>();
+
+ // adding the item to list that will be displayed on the UI.
+ apisList.add("GROUP APIS");
+ apisList.add("CONFIGURATION APIS");
+ apis = new ArrayAdapter<String>(activityObj,
+ android.R.layout.simple_list_item_1, apisList);
+ list.setAdapter(apis);
+
+ // handling user's selection on the UI
+ list.setOnItemClickListener(new OnItemClickListener() {
+ @Override
+ public void onItemClick(AdapterView<?> parent, View view,
+ int position, long id) {
+
+ if (position == 0) {
+ Intent intent = new Intent(activityObj,
+ GroupApiActivity.class);
+ startActivity(intent);
+ } else if (position == 1) {
+ Intent intent = new Intent(activityObj,
+ ConfigurationApiActivity.class);
+ startActivity(intent);
+ }
+ }
+ });
+
+ // calling the method to check the Wi-fi connectivity and configuring
+ // the OcPlatform
+ configurePlatform();
+ }
+
+ @Override
+ public void onBackPressed() {
+ apisList.clear();
+ super.onBackPressed();
+ }
+
+ private void configurePlatform() {
+ // local Variables
+ ConnectivityManager connManager;
+ NetworkInfo wifi;
+ AlertDialog dialog;
+ PlatformConfig platformConfigObj;
+
+ // Check the wifi connectivity
+ connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
+ wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
+ if (false == wifi.isConnected()) {
+ // WiFi is not connected close the application
+ AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
+ dialogBuilder.setTitle("Error");
+ dialogBuilder
+ .setMessage("WiFi is not enabled/connected! Please connect the WiFi and start application again...");
+ dialogBuilder.setCancelable(false);
+ dialogBuilder.setPositiveButton("OK", new OnClickListener() {
+ @Override
+ public void onClick(DialogInterface dialog, int which) {
+ // Closing the application
+ activityObj.finish();
+ }
+ });
+
+ dialog = dialogBuilder.create();
+ dialog.show();
+ return;
+ }
+ // If wifi is connected calling the configure method for configuring the
+ // OcPlatform
+ platformConfigObj = new PlatformConfig(getApplicationContext(),ServiceType.IN_PROC,
+ ModeType.CLIENT_SERVER, "0.0.0.0", 0, QualityOfService.LOW);
+
+ Log.i(LOG_TAG, "Before Calling Configure of ocPlatform");
+ OcPlatform.Configure(platformConfigObj);
+ Log.i(LOG_TAG, "Configuration done Successfully");
+ }
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="src" path="gen"/>
+ <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+ <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
+ <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
+ <classpathentry kind="output" path="bin/classes"/>
+</classpath>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>con-server</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.ApkBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>com.android.ide.eclipse.adt.AndroidNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.example.con_server"
+ android:versionCode="1"
+ android:versionName="1.0" >
+
+ <uses-sdk
+ android:minSdkVersion="8"
+ android:targetSdkVersion="21" />
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+
+ <application
+ android:allowBackup="true"
+ android:icon="@drawable/ic_launcher"
+ android:label="@string/app_name"
+ android:theme="@style/AppTheme" >
+ <activity
+ android:name="com.example.con_server.MainActivity"
+ android:label="@string/app_name" >
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+ </application>
+
+</manifest>
--- /dev/null
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-20
+
+android.library.reference.1=../../../sdk/java
--- /dev/null
+<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: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="com.example.con_server.MainActivity" >
+
+
+ <Button
+ android:id="@+id/button1"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_alignParentTop="true"
+ android:layout_centerHorizontal="true"
+ android:text="doBootStrap" />
+
+ <Button
+ android:id="@+id/button2"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_alignParentLeft="true"
+ android:layout_below="@+id/button1"
+ android:text="Create Configuration Resources" />
+
+ <EditText
+ android:id="@+id/EditText"
+ android:layout_width="fill_parent"
+ android:layout_height="300dp"
+ android:layout_alignParentLeft="true"
+ android:layout_below="@+id/button2"
+ android:layout_marginTop="15dp"
+ android:ems="10"
+ android:editable="false">
+
+ <requestFocus />
+ </EditText>
+
+</RelativeLayout>
--- /dev/null
+<menu xmlns:android="http://schemas.android.com/apk/res/android" >
+
+ <item
+ android:id="@+id/action_settings"
+ android:orderInCategory="100"
+ android:showAsAction="never"
+ android:title="@string/action_settings"/>
+
+</menu>
\ No newline at end of file
--- /dev/null
+<resources>
+
+ <style name="AppBaseTheme" parent="android:Theme.Holo.Light">
+ </style>
+
+</resources>
\ No newline at end of file
--- /dev/null
+<resources>
+
+ <style name="AppBaseTheme" parent="android:Theme.Light">
+ </style>
+
+ <style name="AppTheme" parent="AppBaseTheme">
+ </style>
+
+</resources>
\ No newline at end of file
--- /dev/null
+<resources>
+
+ <!--
+ Example customization of dimensions originally defined in res/values/dimens.xml
+ (such as screen margins) for screens with more than 820dp of available width. This
+ would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively).
+ -->
+ <dimen name="activity_horizontal_margin">64dp</dimen>
+
+</resources>
--- /dev/null
+<resources>
+
+ <!-- Default screen margins, per the Android Design guidelines. -->
+ <dimen name="activity_horizontal_margin">16dp</dimen>
+ <dimen name="activity_vertical_margin">16dp</dimen>
+
+</resources>
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+
+ <string name="app_name">con-server</string>
+ <string name="hello_world">Hello world!</string>
+ <string name="action_settings">Settings</string>
+
+</resources>
--- /dev/null
+<resources>
+
+ <style name="AppBaseTheme" parent="android:Theme.Light">
+
+ </style>
+
+ <!-- Application theme. -->
+ <style name="AppTheme" parent="AppBaseTheme">
+
+ </style>
+
+</resources>
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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 com.example.con_server;
+
+import java.util.EnumSet;
+import java.util.Vector;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.ResourceProperty;
+
+import android.util.Log;
+
+//For creating/deleting the configuration Resource
+public class ConfigurationResource {
+ private final String LOG_TAG = "[CON-SERVER]"
+ + this.getClass()
+ .getSimpleName();
+ // Configuration resource members
+ protected String configurationUri;
+ protected String location;
+ protected String systemTime;
+ protected String currency;
+ protected String region;
+ protected Vector<String> configurationTypes = new Vector<String>();
+ protected Vector<String> configurationInterfaces = new Vector<String>();
+ protected OcRepresentation configurationRep = new OcRepresentation();
+ protected OcResourceHandle configurationHandle;
+
+ // constructors
+ public ConfigurationResource() {
+ Log.i(LOG_TAG, "ConfigurationResource: enter");
+
+ location = ConfigurationDefaultValues.defaultLocation;
+ systemTime = ConfigurationDefaultValues.defaultSystemTime;
+ currency = ConfigurationDefaultValues.defaultCurrency;
+ region = ConfigurationDefaultValues.defaultRegion;
+
+ configurationUri = ConfigurationDefaultValues.ConURIPrefix;
+ configurationTypes
+ .add(ConfigurationDefaultValues.ConResourceTypePrefix);
+ configurationInterfaces.add(OcPlatform.DEFAULT_INTERFACE);
+
+ configurationRep.setValueString("loc", location);
+ configurationRep.setValueString("st", systemTime);
+ configurationRep.setValueString("c", currency);
+ configurationRep.setValueString("r", region);
+ configurationRep.setUri(configurationUri);
+ configurationRep.setResourceTypes(configurationTypes);
+ configurationRep.setResourceInterfaces(configurationInterfaces);
+ }
+
+ // For creating Configuration Resource
+ public void createResource(OcPlatform.EntityHandler listener)
+ throws OcException {
+ Log.i(LOG_TAG, "createResource(configuration): enter");
+ EnumSet<ResourceProperty> propertySet = EnumSet.of(
+ ResourceProperty.DISCOVERABLE, ResourceProperty.OBSERVABLE);
+
+ // Register configuration resource
+ configurationHandle = OcPlatform.registerResource(configurationUri,
+ configurationTypes.elementAt(0),
+ configurationInterfaces.elementAt(0), listener, propertySet);
+
+ Log.i(LOG_TAG, "createResource(configuration): exit");
+ }
+
+ // Setters and Getters methods for Configuration resource
+ public void setConfigurationRepresentation(OcRepresentation rep) {
+ Log.i(LOG_TAG, "setConfigurationRepresentation: enter");
+
+ String loc;
+ String st;
+ String cur;
+ String reg;
+ loc = rep.getValueString("loc");
+ st = rep.getValueString("st");
+ cur = rep.getValueString("c");
+ reg = rep.getValueString("r");
+ if (!(loc.equalsIgnoreCase(""))) {
+ location = loc;
+ Log.i(LOG_TAG,
+ "setConfigurationRepresentation: New value(location): "
+ + location);
+ }
+ if (!(st.equalsIgnoreCase(""))) {
+ systemTime = st;
+ Log.i(LOG_TAG,
+ "setConfigurationRepresentation: New value(system time): "
+ + systemTime);
+ }
+ if (!(cur.equalsIgnoreCase(""))) {
+ currency = cur;
+ Log.i(LOG_TAG,
+ "setConfigurationRepresentation: New value(currency): "
+ + currency);
+ }
+ if (!(reg.equalsIgnoreCase(""))) {
+ region = reg;
+ Log.i(LOG_TAG,
+ "setConfigurationRepresentation: New value(region): "
+ + region);
+ }
+
+ Log.i(LOG_TAG, "setConfigurationRepresentation: exit");
+ }
+
+ public OcRepresentation getConfigurationRepresentation() {
+
+ configurationRep.setValueString("loc", location);
+ configurationRep.setValueString("st", systemTime);
+ configurationRep.setValueString("c", currency);
+ configurationRep.setValueString("r", region);
+ return configurationRep;
+ }
+
+ public String getUri() {
+ return configurationUri;
+ }
+
+ // For resetting the default values to configuration Resource
+ public void factoryReset() {
+
+ location = ConfigurationDefaultValues.defaultLocation;
+ systemTime = ConfigurationDefaultValues.defaultSystemTime;
+ currency = ConfigurationDefaultValues.defaultCurrency;
+ region = ConfigurationDefaultValues.defaultRegion;
+ Log.i(LOG_TAG, "ConfiguartionResource: factoryReset done");
+
+ }
+
+ // Deleting all the resources, that we have created using createResources()
+ public void deleteResource() {
+ try {
+ if (null != configurationHandle) {
+ // Unregister the Configuration resource
+ OcPlatform.unregisterResource(configurationHandle);
+ }
+
+ } catch (OcException e) {
+ Log.e(LOG_TAG, "OcException occured! " + e.toString());
+ }
+ }
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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 com.example.con_server;
+
+import java.util.EnumSet;
+import java.util.Vector;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.RequestType;
+import org.iotivity.service.tm.IConfigurationListener;
+import org.iotivity.service.tm.IDiagnosticsListener;
+import org.iotivity.service.tm.OCStackResult;
+import org.iotivity.service.tm.ThingsManager;
+
+import android.os.Message;
+import android.util.Log;
+
+/*
+ * For Creating the Resources [configurtion, Diagnostic & FactoryRest] &
+ * for Handling of the Client's Request
+ */
+public class ConfigurationServer implements IDiagnosticsListener,
+ IConfigurationListener, OcPlatform.EntityHandler {
+ private final String LOG_TAG = "[CON-SERVER]"
+ + this.getClass()
+ .getSimpleName();
+ private ThingsManager thingsmanager = null;
+ private ConfigurationResource conResource = null;
+ private DiagnosticsResource diagResource = null;
+ private FactorySetResource factorySetResource = null;
+
+ // constructor
+ public ConfigurationServer() {
+ thingsmanager = new ThingsManager();
+ thingsmanager.setDiagnosticsListener(this);
+ thingsmanager.setConfigurationListener(this);
+ }
+
+ public void DoBootStrap() {
+ Log.i(LOG_TAG, "DoBootStrap: enter");
+
+ OCStackResult result = thingsmanager.doBootstrap();
+ if (OCStackResult.OC_STACK_ERROR == result) {
+ Log.e(LOG_TAG, "doBootStrap returned error: "
+ + OCStackResult.OC_STACK_ERROR.name());
+ }
+ Log.i(LOG_TAG, "DoBootStrap: exit");
+ }
+
+ // Creating resources : configuration, diagnostics, factoryReset
+ public void CreateConfigurationResource() {
+ Log.i(LOG_TAG, "CreateConfigurationResource: enter");
+
+ try {
+ conResource = new ConfigurationResource();
+ conResource.createResource(this);
+
+ diagResource = new DiagnosticsResource();
+ diagResource.createResource(this);
+
+ factorySetResource = new FactorySetResource();
+ factorySetResource.createResource(this);
+ } catch (OcException e) {
+ Log.e(LOG_TAG, "OcException occured: " + e.toString());
+ }
+
+ Log.i(LOG_TAG, "CreateConfigurationResource: exit");
+
+ String message = "Resources Created Successfully(Server is Ready)";
+
+ Message msg = Message.obtain();
+ msg.what = 0;
+ MainActivity mainActivityObj = MainActivity.getMainActivityObject();
+ MainActivity.setmessage(message);
+ mainActivityObj.getmHandler().sendMessage(msg);
+
+ }
+
+ // For deleting all the resources
+ public void deleteResources() {
+ if (null != conResource)
+ conResource.deleteResource();
+ if (null != diagResource)
+ diagResource.deleteResource();
+ if (null != factorySetResource)
+ factorySetResource.deleteResource();
+ }
+
+ // Callback Function for doBootStrap
+ @Override
+ public void onBootStrapCallback(Vector<OcHeaderOption> headerOptions,
+ OcRepresentation rep, int errorValue) {
+ String message;
+ Log.i(LOG_TAG, "onBootStrapCallback");
+
+ // setting the default values received from bootstrap Server
+
+ ConfigurationDefaultValues.defaultRegion = rep.getValueString("r");
+ ConfigurationDefaultValues.defaultSystemTime = rep.getValueString("st");
+ ConfigurationDefaultValues.defaultCurrency = rep.getValueString("c");
+ ConfigurationDefaultValues.defaultLocation = rep.getValueString("loc");
+
+ // forming the message to display on UI
+ message = "URI : " + rep.getUri() + "\n";
+ message = message + "Region : "
+ + ConfigurationDefaultValues.defaultRegion + "\n";
+ message = message + "System Time : "
+ + ConfigurationDefaultValues.defaultSystemTime + "\n";
+ message = message + "Currency : "
+ + ConfigurationDefaultValues.defaultCurrency + "\n";
+ message = message + "Location : "
+ + ConfigurationDefaultValues.defaultLocation + "\n";
+
+ Log.i(LOG_TAG, "Resource URI: " + rep.getUri());
+ Log.i(LOG_TAG, "Region: " + ConfigurationDefaultValues.defaultRegion);
+ Log.i(LOG_TAG, "System Time: "
+ + ConfigurationDefaultValues.defaultSystemTime);
+ Log.i(LOG_TAG, "Currency: "
+ + ConfigurationDefaultValues.defaultCurrency);
+ Log.i(LOG_TAG, "Location: "
+ + ConfigurationDefaultValues.defaultLocation);
+
+ // showing the formed message on the UI
+ Message msg = Message.obtain();
+ msg.what = 0;
+ MainActivity mainActivityObj = MainActivity.getMainActivityObject();
+ MainActivity.setmessage(message);
+ mainActivityObj.getmHandler().sendMessage(msg);
+ }
+
+ // Callback Function for Reboot
+ @Override
+ public void onRebootCallback(Vector<OcHeaderOption> headerOptions,
+ OcRepresentation rep, int errorValue) {
+ Log.i(LOG_TAG, "onRebootCallback");
+ }
+
+ // Callback Function for FactoryReset
+ @Override
+ public void onFactoryResetCallback(Vector<OcHeaderOption> headerOptions,
+ OcRepresentation rep, int errorValue) {
+ Log.i(LOG_TAG, "onFactoryResetCallback");
+ }
+
+ // For Handling the Client's Request
+ @Override
+ public EntityHandlerResult handleEntity(OcResourceRequest request) {
+ Log.i(LOG_TAG, "handleEntity: enter");
+
+ EntityHandlerResult result = EntityHandlerResult.ERROR;
+ if (null == request) {
+ Log.e(LOG_TAG, "handleEntity: Invalid OcResourceRequest!");
+ return result;
+ }
+
+ RequestType requestType = request.getRequestType();
+ EnumSet<RequestHandlerFlag> requestHandlerFlag = request
+ .getRequestHandlerFlagSet();
+ Log.i(LOG_TAG, "prepareResponseForResource: request type: "
+ + requestType.name());
+ Log.i(LOG_TAG, "prepareResponseForResource: request for resource: "
+ + request.getResourceUri());
+
+ if (requestHandlerFlag.contains(RequestHandlerFlag.REQUEST)) {
+ if (RequestType.GET == requestType) {
+ sendResponse(request);
+ } else if (RequestType.PUT == requestType) {
+ OcRepresentation rep = request.getResourceRepresentation();
+ if (null == rep) {
+ Log.e(LOG_TAG,
+ "handleEntity: Invalid resource representation!");
+ return result;
+ }
+
+ if (request.getResourceUri().equalsIgnoreCase(
+ conResource.getUri())) {
+ conResource.setConfigurationRepresentation(rep);
+ } else if (request.getResourceUri().equalsIgnoreCase(
+ diagResource.getUri())) {
+
+ String factorySetAtt = rep.getValueString("fr");
+ if (factorySetAtt.equalsIgnoreCase("true")) {
+ conResource.factoryReset();
+ }
+ diagResource.setDiagnosticsRepresentation(rep);
+ }
+ sendResponse(request);
+ }
+ }
+
+ Log.i(LOG_TAG, "handleEntity: exit");
+ return result;
+ }
+
+ // For sending response to the client
+ private void sendResponse(OcResourceRequest request) {
+ Log.i(LOG_TAG, "sendResponse: enter");
+
+ OcResourceResponse response = new OcResourceResponse();
+ OcRepresentation rep = null;
+
+ response.setRequestHandle(request.getRequestHandle());
+ response.setResourceHandle(request.getResourceHandle());
+
+ if (request.getResourceUri().equalsIgnoreCase(conResource.getUri())) {
+ rep = conResource.getConfigurationRepresentation();
+ } else if (request.getResourceUri().equalsIgnoreCase(
+ diagResource.getUri())) {
+ rep = diagResource.getDiagnosticsRepresentation();
+ }
+ response.setResourceRepresentation(rep, OcPlatform.DEFAULT_INTERFACE);
+ response.setErrorCode(200);
+
+ try {
+ OcPlatform.sendResponse(response);
+ } catch (OcException e) {
+ Log.e(LOG_TAG, "sendResponse: OcException occured: " + e.toString());
+ }
+ Log.i(LOG_TAG, "sendResponse: exit");
+ }
+
+ @Override
+ public void onUpdateConfigurationsCallback(
+ Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+ int errorValue) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void onGetConfigurationsCallback(
+ Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+ int errorValue) {
+ // TODO Auto-generated method stub
+
+ }
+}
+
+// Default values for Resources
+class ConfigurationDefaultValues {
+
+ // configuration Resource default values
+ public static String defaultLocation = new String();
+ public static String defaultRegion = new String();
+ public static String defaultSystemTime = new String();
+ public static String defaultCurrency = new String();
+ public static String ConURIPrefix = "/oic/con";
+ public static String ConResourceTypePrefix = "oic.con";
+
+ // Diagnostics Resource default values
+ public static String diagURIPrefix = "/oic/diag";
+ public static String diagResourceTypePrefix = "oic.diag";
+ public static String diagnosticsValue = "false";
+ public static String defaultFactoryReset = "false";
+ public static String defaultReboot = "false";
+ public static String defaultStartCollection = "false";
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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 com.example.con_server;
+
+import java.util.EnumSet;
+import java.util.Vector;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.ResourceProperty;
+
+import android.util.Log;
+
+//For creating/deleting the Diagnostics Resource
+public class DiagnosticsResource {
+ private final String LOG_TAG = "[CON-SERVER]"
+ + this.getClass()
+ .getSimpleName();
+ // diagnostics members
+ private String diagnosticsUri;
+ private String factoryReset;
+ private String reboot;
+ private String startCollection;
+ private Vector<String> diagnosticsTypes = new Vector<String>();
+ private Vector<String> diagnosticsInterfaces = new Vector<String>();
+ private OcResourceHandle diagnosticsHandle;
+ private OcRepresentation diagnosticsRep = new OcRepresentation();
+
+ // constructor
+ public DiagnosticsResource() {
+ Log.i(LOG_TAG, "DiagnosticsCollection: enter");
+
+ factoryReset = ConfigurationDefaultValues.defaultFactoryReset;
+ reboot = ConfigurationDefaultValues.defaultReboot;
+ startCollection = ConfigurationDefaultValues.defaultStartCollection;
+
+ diagnosticsUri = ConfigurationDefaultValues.diagURIPrefix;
+ diagnosticsTypes.add(ConfigurationDefaultValues.diagResourceTypePrefix);
+ diagnosticsInterfaces.add(OcPlatform.DEFAULT_INTERFACE);
+ diagnosticsRep.setValueString("fr", factoryReset);
+ diagnosticsRep.setValueString("rb", reboot);
+ diagnosticsRep.setValueString("ssc", startCollection);
+ diagnosticsRep.setUri(diagnosticsUri);
+ diagnosticsRep.setResourceTypes(diagnosticsTypes);
+ diagnosticsRep.setResourceInterfaces(diagnosticsInterfaces);
+
+ }
+
+ // for creating Diagnostic Resource
+ public void createResource(OcPlatform.EntityHandler listener)
+ throws OcException {
+ Log.i(LOG_TAG, "createResource(Diagnostics): enter");
+ EnumSet<ResourceProperty> propertySet = EnumSet.of(
+ ResourceProperty.DISCOVERABLE, ResourceProperty.OBSERVABLE);
+ if (null == listener) {
+ Log.i(LOG_TAG, "CallBack Should be binded");
+ return;
+ }
+
+ // Register diagnostic resource
+ diagnosticsHandle = OcPlatform.registerResource(diagnosticsUri,
+ diagnosticsTypes.get(0), diagnosticsInterfaces.get(0),
+ listener, propertySet);
+ if (null == diagnosticsHandle) {
+ Log.e(LOG_TAG, "registerResource failed!");
+ return;
+ }
+
+ Thread thread = new Thread() {
+ @Override
+ public void run() {
+ try {
+ while (true) {
+ // Put this thread for sleep for 1 sec.
+ // Sleep value can be changed as per the developer
+ // convenience.
+ Thread.sleep(1000);
+ if (reboot.equalsIgnoreCase("true")) {
+ Log.i(LOG_TAG, "Reboot will be soon...");
+ MainActivity mainActivityObj = MainActivity
+ .getMainActivityObject();
+ if (null == mainActivityObj) {
+ Log.e(LOG_TAG,
+ "Mainactivity object is invalid!");
+ return;
+ }
+ try {
+ mainActivityObj.runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ MainActivity.reboot();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ });
+ } catch (Exception e) {
+ Log.e(LOG_TAG, "InterruptedException occured: "
+ + e.toString());
+ continue;
+ }
+ reboot = ConfigurationDefaultValues.defaultReboot;
+ }
+ if (factoryReset.equalsIgnoreCase("true")) {
+ factoryReset = ConfigurationDefaultValues.defaultFactoryReset;
+ factoryReset();
+ }
+ }
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ };
+ thread.start();
+ Log.i(LOG_TAG, "createResource(Diagnostics): exit");
+ }
+
+ // getters and Setters Methods for diagnostics Resource
+ public void setDiagnosticsRepresentation(OcRepresentation rep) {
+ Log.i(LOG_TAG, "setDiagnosticsRepresentation: enter");
+
+ String fr = rep.getValueString("fr");
+ String rb = rep.getValueString("rb");
+ String ssc = rep.getValueString("ssc");
+
+ if (!(fr.equalsIgnoreCase(""))) {
+ factoryReset = fr;
+ Log.i(LOG_TAG,
+ "setConfigurationRepresentation: New value(FactoryReset): "
+ + fr);
+ }
+ if (!(rb.equalsIgnoreCase(""))) {
+ reboot = rb;
+ Log.i(LOG_TAG, "setDiagnosticsRepresentation: new value:(reboot) "
+ + rb);
+ }
+
+ if (!(ssc.equalsIgnoreCase(""))) {
+ startCollection = ssc;
+ Log.i(LOG_TAG,
+ "setDiagnosticsRepresentation: new value:(startcollection) "
+ + ssc);
+ }
+
+ Log.i(LOG_TAG, "setDiagnosticsRepresentation: exit");
+ }
+
+ OcRepresentation getDiagnosticsRepresentation() {
+ diagnosticsRep.setValueString("fr", factoryReset);
+ diagnosticsRep.setValueString("rb", reboot);
+ diagnosticsRep.setValueString("ssc", startCollection);
+ return diagnosticsRep;
+ }
+
+ public String getUri() {
+ return diagnosticsUri;
+ }
+
+ // For Resetting diagnostics Resource attributes to their default values
+ public void factoryReset() {
+ factoryReset = ConfigurationDefaultValues.defaultFactoryReset;
+ reboot = ConfigurationDefaultValues.defaultReboot;
+ startCollection = ConfigurationDefaultValues.defaultStartCollection;
+ }
+
+ // For Deleting diagnostic resource
+ public void deleteResource() {
+ try {
+ if (null != diagnosticsHandle) {
+ // Unregister the collection resource
+ OcPlatform.unregisterResource(diagnosticsHandle);
+ }
+ } catch (OcException e) {
+ Log.e(LOG_TAG, "OcException occured! " + e.toString());
+ }
+ }
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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 com.example.con_server;
+
+import java.util.EnumSet;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.ResourceProperty;
+
+import android.util.Log;
+
+// For creating & deleting the FactorySet Resource
+public class FactorySetResource extends ConfigurationResource {
+ private final String LOG_TAG = "[CON-SERVER]"
+ + this.getClass().getSimpleName();
+
+ // constructor
+ public FactorySetResource() {
+ Log.i(LOG_TAG, "FactorySetCollection: enter");
+
+ configurationUri = "/factorySet"; // uri of the resource
+ configurationTypes.clear();
+ configurationTypes.add("factorySet");
+ configurationRep.setUri(configurationUri);
+ configurationRep.setResourceTypes(configurationTypes);
+ }
+
+ // for creating FactoryReset Resource
+ public void createResource(OcPlatform.EntityHandler listener)
+ throws OcException {
+ Log.i(LOG_TAG, "createResource(Factory Set): enter");
+ EnumSet<ResourceProperty> propertySet = EnumSet.of(
+ ResourceProperty.DISCOVERABLE, ResourceProperty.OBSERVABLE);
+ if (null == listener) {
+ Log.i(LOG_TAG, "CallBack Should be binded");
+ return;
+ }
+
+ // Register factoryset resource
+ configurationHandle = OcPlatform.registerResource(configurationUri,
+ configurationTypes.elementAt(0),
+ configurationInterfaces.elementAt(0), listener, propertySet);
+ if (null == configurationHandle) {
+ Log.e(LOG_TAG, "registerResource failed!");
+ return;
+ }
+ Log.i(LOG_TAG, "createResource (Factory Set): exit");
+ }
+
+ // getters and Setters Methods for FacoryReset Resource
+ public void setFactorySetRepresentation(OcRepresentation rep) {
+ Log.i(LOG_TAG, "setFactorySetRepresentation: enter");
+
+ String loc;
+ String st;
+ String cur;
+ String reg;
+ loc = rep.getValueString("loc");
+ st = rep.getValueString("st");
+ cur = rep.getValueString("c");
+ reg = rep.getValueString("r");
+ if (null != loc) {
+ location = loc;
+ Log.i(LOG_TAG, "setConfigurationRepresentation: New value: "
+ + location);
+ }
+ if (null != st) {
+ // systemTime = st;
+ Log.i(LOG_TAG, "setConfigurationRepresentation: New value: "
+ + systemTime);
+ }
+ if (null != cur) {
+ currency = cur;
+ Log.i(LOG_TAG, "setConfigurationRepresentation: New value: "
+ + currency);
+ }
+ if (null != reg) {
+ region = reg;
+ Log.i(LOG_TAG, "setConfigurationRepresentation: New value: "
+ + region);
+ }
+ Log.i(LOG_TAG, "setFactorySetRepresentation: exit");
+ }
+
+ OcRepresentation getFactorySetRepresentation() {
+
+ configurationRep.setValueString("loc", location);
+ configurationRep.setValueString("st", systemTime);
+ configurationRep.setValueString("c", currency);
+ configurationRep.setValueString("r", region);
+ return configurationRep;
+ }
+
+ public String getUri() {
+ return configurationUri;
+ }
+
+ // For deletingFactorySet Resource
+ public void deleteResource() {
+ try {
+ if (null != configurationHandle) {
+ // Unregister the collection resource
+ OcPlatform.unregisterResource(configurationHandle);
+ }
+ } catch (OcException e) {
+ Log.e(LOG_TAG, "OcException occured! " + e.toString());
+ }
+ }
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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 com.example.con_server;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.app.ProgressDialog;
+import android.content.DialogInterface;
+import android.net.ConnectivityManager;
+import android.net.NetworkInfo;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.util.Log;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.Button;
+import android.widget.EditText;
+
+/*
+ * Starting Activity of the application responsible for
+ * configuring the OcPlatform and for handling user's selection on UI.
+ */
+public class MainActivity extends Activity {
+
+ private final String LOG_TAG = this.getClass().getSimpleName();
+ private Handler mHandler;
+ private static MainActivity mainActivityObj;
+ private ConfigurationServer conServerObj;
+ private static String message;
+ private EditText editText;
+ public static ProgressDialog dialog;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_main);
+
+ mainActivityObj = this;
+ Button doBootStrap = (Button) findViewById(R.id.button1);
+ final Button createConfig = (Button) findViewById(R.id.button2);
+ editText = (EditText) findViewById(R.id.EditText);
+ conServerObj = new ConfigurationServer();
+
+ // handler for updating the UI i.e. MessageLog (TextBox)
+ mHandler = new Handler() {
+ @Override
+ public void handleMessage(Message msg) {
+ switch (msg.what) {
+ case 0:
+ editText.setText(message);
+ }
+ }
+ };
+ setmHandler(mHandler);
+
+ // listener for doBootStrap Button
+ doBootStrap.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ conServerObj.DoBootStrap();
+ createConfig.setEnabled(true);
+ }
+ });
+
+ // listener for createConfiguration Resource Button
+ createConfig.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ conServerObj.CreateConfigurationResource();
+ createConfig.setEnabled(false);
+ }
+ });
+
+ // calling the method to check the Wi-fi connectivity and configuring
+ // the OcPlatform
+ configurePlatform();
+ }
+
+ private void configurePlatform() {
+
+ // Check the wi-fi connectivity
+ ConnectivityManager connmanager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
+ NetworkInfo wifi = connmanager
+ .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
+ if (false == wifi.isConnected()) {
+ // WiFi is not connected close the application
+ AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
+ dialogBuilder.setTitle("Error");
+ dialogBuilder
+ .setMessage("WiFi is not enabled/connected! Please connect the WiFi and start application again...");
+ dialogBuilder.setCancelable(false);
+ dialogBuilder.setPositiveButton("OK",
+ new DialogInterface.OnClickListener() {
+ @Override
+ public void onClick(DialogInterface dialog, int which) {
+ // Closing the application
+ mainActivityObj.finish();
+ }
+ });
+
+ AlertDialog dialog = dialogBuilder.create();
+ dialog.show();
+ return;
+ }
+
+ // If wifi is connected calling the configure method for configuring the
+ // ocPlatform
+ PlatformConfig cfg = new PlatformConfig(getApplicationContext(),ServiceType.IN_PROC,
+ ModeType.CLIENT_SERVER, "0.0.0.0", 0, QualityOfService.LOW);
+ OcPlatform.Configure(cfg);
+ Log.i(LOG_TAG, "Configuration done Successfully");
+ }
+
+ @Override
+ public void onBackPressed() {
+ super.onBackPressed();
+
+ // deleting all the resources that we have created.
+ if (null != conServerObj)
+ conServerObj.deleteResources();
+ }
+
+ @SuppressWarnings("unused")
+ private Handler handler = new Handler() {
+ @Override
+ public void handleMessage(Message msg) {
+ dialog.dismiss();
+ }
+ };
+
+ // Function called when receive a reboot Request
+ public static void reboot() throws InterruptedException {
+
+ dialog = new ProgressDialog(mainActivityObj);
+ dialog.setMessage("Rebooting..");
+ dialog.setTitle("Please wait ...");
+ dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
+ dialog.setProgress(0);
+ dialog.setMax(100);
+ dialog.show();
+ Thread thread = new Thread() {
+ @Override
+ public void run() {
+ try {
+ sleep(5000);
+ dialog.dismiss();
+
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ };
+ thread.start();
+ }
+
+ // Functions required for updating the UI
+
+ public Handler getmHandler() {
+ return mHandler;
+ }
+
+ public void setmHandler(Handler mHandler) {
+ this.mHandler = mHandler;
+ }
+
+ public static MainActivity getMainActivityObject() {
+ return mainActivityObj;
+ }
+
+ public static void setmessage(String msg) {
+ message = msg;
+ }
+}
}
catch (std::exception& e)
{
- //log(e.what());
+ std::cout << "Exception: " << e.what() << std::endl;
}
isWaiting = 0;
}
catch (std::exception& e)
{
- //log(e.what());
+ std::cout << "Exception: " << e.what() << std::endl;
}
isWaiting = 0;
// No explicit call to stop the platform.
// When OCPlatform destructor is invoked, internally we do platform cleanup
+ return 0;
}
}
catch (OCException e)
{
- std::cout << "Exception in main: " << e.what();
+ std::cout << "Exception: " << e.what() << std::endl;
}
}
}
catch (std::exception& e)
{
- std::cout << "" << std::endl;
+ std::cout << "Exception: " << e.what() << std::endl;
}
}
if( res < 0 )
{
printf("Invalid Input. try again.");
+ delete allBulbOff;
return;
}
}
catch (OCException& e)
{
- //log(e.what());
+ std::cout << "Exception: " << e.what() << std::endl;
}
return 0;
}
catch (OCException& e)
{
- //log(e.what());
+ std::cout << "Exception: " << e.what() << std::endl;
}
return 0;
std::string resourceURI;
QueryParamsMap query;
- OCRepresentation rep;
std::string playStart;
std::string playStop;
}
catch (OCException& e)
{
- //log(e.what());
+ std::cout << "Exception: " << e.what() << std::endl;
}
return 0;
}
catch (OCException& e)
{
- //log(e.what());
+ std::cout << "Exception: " << e.what() << std::endl;
}
return 0;
}
catch (OCException &e)
{
- dlog_print(DLOG_INFO, LOG_TAG, "#### Platform configuration failed!!!!");
+ dlog_print(DLOG_ERROR, LOG_TAG, "Exception occured! (%s)", e.what());
}
}
dlog_print(DLOG_INFO, LOG_TAG, "#### NO LIGHT SERVER FOUND");
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
&logMessage);
+ delete actionSet;
return;
}
logMessage += "----------------------<br>";
dlog_print(DLOG_INFO, LOG_TAG, "#### NO LIGHT SERVER FOUND");
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
+ delete actionSet;
return;
}
{
int level;
buf = (char *)malloc(4 * sizeof(char));
+ if (NULL == buf)
+ {
+ dlog_print(DLOG_INFO, LOG_TAG, " buf malloc failed");
+ return;
+ }
sprintf(buf, "%d", sequenceNumber);
logMessage = "OBSERVE RESULT <br>";
logMessage += "Sequencenumber:" + string(buf) + "<br>";
dlog_print(DLOG_INFO, LOG_TAG, "#### FOUND URI: %s", resourceURI.c_str());
dlog_print(DLOG_INFO, LOG_TAG, "#### FOUND HOST: %s", hostAddress.c_str());
logMessage = "FOUND RESOURCE URI <br>" + resourceURI + "<br>";
- logMessage = "FOUND RESOURCE HOST <br>" + hostAddress + "<br>";
+ logMessage += "FOUND RESOURCE HOST <br>" + hostAddress + "<br>";
logMessage += "----------------------<br>";
// Show the UI list of group APIs
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))showGroupAPIs, NULL);
}
catch (OCException &e)
{
- dlog_print(DLOG_INFO, LOG_TAG, "#### Platform configuration failed!!!!");
+ dlog_print(DLOG_ERROR, LOG_TAG, "Exception occured! (%s)", e.what());
}
}
--- /dev/null
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="org.iotivity.service.tm"
+ android:versionCode="1"
+ android:versionName="1.0" >
+ <uses-sdk
+ android:minSdkVersion="8"
+ android:targetSdkVersion="21" />
+</manifest>
--- /dev/null
+LOCAL_PATH := $(call my-dir)
+
+ifeq ($(strip $(ANDROID_NDK)),)
+$(error ANDROID_NDK is not set!)
+endif
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../../dep/android/$(TARGET_ARCH_ABI)/usr/lib
+LOCAL_MODULE := libandroid-boost_system
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libboost_system.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../../out/android/$(TARGET_ARCH_ABI)/release
+LOCAL_MODULE := libandroid-thingsmanager
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libTGMSDKLibrary.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../out/android/$(TARGET_ARCH_ABI)/release
+BASE_LIB_PATH := ../../../../android/android_api/base/libs/$(TARGET_ARCH_ABI)
+OIC_RESOURCE_PATH := ../../../../resource
+OIC_SERVICE_PATH := ../../../../service
+OIC_OUT_PATH := ../../../../out
+LOCAL_MODULE := things-manager-jni
+
+LOCAL_C_INCLUDES := $(OIC_RESOURCE_PATH)/include \
+ $(OIC_RESOURCE_PATH)/csdk/stack/include \
+ $(OIC_RESOURCE_PATH)/csdk/ocsocket/include \
+ $(OIC_RESOURCE_PATH)/oc_logger/include \
+ $(OIC_RESOURCE_PATH)/android/include \
+ $(OIC_RESOURCE_PATH)/dependencies/cereal/include \
+ $(OIC_RESOURCE_PATH)/../extlibs/boost/boost_1_58_0 \
+ $(OIC_RESOURCE_PATH)/../extlibs/timer \
+ $(OIC_SERVICE_PATH)/things-manager/sdk/inc \
+ $(OIC_SERVICE_PATH)/things-manager/sdk/src \
+ $(OIC_SERVICE_PATH)/../android/android_api/base/jni \
+ $(OIC_SERVICE_PATH)/../build_common/android/compatibility \
+ $(LOCAL_PATH)/jniutil/inc \
+ $(LOCAL_PATH)/tm/inc \
+ $(LOCAL_PATH)/tm/src \
+ $(LOCAL_PATH)/tm/src/base \
+ $(ANDROID_NDK)/sources/cxx-stl/gnu-libstdc++/$(TOOLCHAIN_VERSION)/include \
+ $(ANDROID_NDK)/sources/cxx-stl/gnu-libstdc++/$(TOOLCHAIN_VERSION)/libs/$(TARGET_ARCH_ABI)/include \
+
+LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/jniutil/src/*.cpp))
+LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/tm/src/*.cpp))
+
+LOCAL_CPPFLAGS := -std=c++0x -frtti -fexceptions
+
+LOCAL_LDLIBS := -llog -L$(BASE_LIB_PATH) -locstack-jni -L$(OIC_LIB_PATH) -loc -loctbstack -lcoap -loc_logger
+LOCAL_LDLIBS += -L$(ANDROID_NDK)/sources/cxx-stl/gnu-libstdc++/$(TOOLCHAIN_VERSION)/libs/$(TARGET_ARCH_ABI) -lgnustl_shared
+LOCAL_SHARED_LIBRARIES := android-thingsmanager
+LOCAL_STATIC_LIBRARIES := android-boost_system
+
+include $(BUILD_SHARED_LIBRARY)
--- /dev/null
+NDK_TOOLCHAIN_VERSION := 4.9
+#APP_STL := gnustl_shared
--- /dev/null
+##
+# Things manager service JNI build script
+##
+
+Import('env')
+
+# Add third party libraries
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', exports = 'lib_env')
+
+tm_jni_env = lib_env.Clone()
+target_os = env.get('TARGET_OS')
+tm_sdk = env.get('SRC_DIR') + '/service/things-manager/sdk'
+base_jni = env.get('SRC_DIR') + '/android/android_api/base/jni'
+
+######################################################################
+# Build flags
+######################################################################
+tm_jni_env.AppendUnique(CXXFLAGS = ['-Wall', '-DLINUX', '-DNDEBUG'])
+tm_jni_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
+tm_jni_env.AppendUnique(LIBPATH = [base_jni+'/../libs/'+env.get('TARGET_ARCH')])
+tm_jni_env.PrependUnique(LIBS = ['ocstack-jni', 'TGMSDKLibrary', 'oc', 'octbstack', 'boost_system', 'gnustl_shared', 'compatibility', 'log'])
+
+tm_jni_env.AppendUnique(CPPPATH = [tm_sdk+'/inc', tm_sdk+'/src'])
+tm_jni_env.AppendUnique(CPPPATH = [base_jni])
+tm_jni_env.AppendUnique(CPPPATH = ['tm/inc', 'tm/src', 'jniutil/inc', 'jniutil/src', '../../../../../extlibs/timer/'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+tm_jni_src = [env.Glob('tm/src/*.cpp'), env.Glob('jniutil/src/*.cpp')]
+tm_jni = tm_jni_env.SharedLibrary('things-manager-jni', tm_jni_src)
+
+tm_jni_env.InstallTarget(tm_jni, 'libthings-manager-jni')
+
+# Install the libraries to /libs/<TARGET_ARCH> directory
+tm_jni_env.Install(tm_sdk+'/java/libs/'+env.get('TARGET_ARCH'),env.get('BUILD_DIR')+'/libTGMSDKLibrary.so')
+tm_jni_env.Install(tm_sdk+'/java/libs/'+env.get('TARGET_ARCH'),tm_jni)
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file jni_getter.h
+ *
+ * @brief This file contains the JGetter class declarations and its functions required
+ * for getting and setting basic data types in C++ and Java
+ */
+
+#ifndef __JNI_GETTER_H_
+#define __JNI_GETTER_H_
+
+
+#include <string>
+#include <jni.h>
+
+/**
+ * @class JGetter
+ * @brief This class provide utility for get/set basic data types in C++ and Java
+ *
+ */
+class JGetter
+{
+ public:
+ /**
+ * This function is called to get String field from the C++ object
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject from which string field is expected
+ * @param fieldName
+ * Name of the field to be extracted from JObject
+ * @param value
+ * reference to string value mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool getJStringField(JNIEnv *env, jobject &object, const char *fieldName,
+ std::string &value);
+
+ /**
+ * This function is called to get Boolean field from the C++ object
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject from which boolean field is expected
+ * @param fieldName
+ * Name of the field to be extracted from JObject
+ * @param value
+ * reference to boolean value mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool getJBoolField(JNIEnv *env, jobject &object, const char *fieldName,
+ bool &value);
+
+ /**
+ * This function is called to get Integer field from the C++ object
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject from which integer field is expected
+ * @param fieldName
+ * Name of the field to be extracted from JObject
+ * @param value
+ * reference to integer value mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool getJIntField(JNIEnv *env, jobject &object, const char *fieldName, int &value);
+
+ /**
+ * This function is called to get Object reference from the C++ object
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject from which Object reference is expected
+ * @param fieldName
+ * Name of the field to be extracted from JObject
+ * @param fieldType
+ * Type of the field to be extracted from JObject
+ * @param value
+ * reference to Object reference mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool getJObjectField(JNIEnv *env, jobject &object, const char *fieldName,
+ const char *fieldType, jobject &value);
+};
+#endif //__JNI_GETTER_H_
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file jni_object.h
+ *
+ * @brief This file contains the JObject class declarations and its functions required
+ * for getting and setting basic data types in C++ and Java
+ */
+
+#ifndef __JNI_OBJECT_H_
+#define __JNI_OBJECT_H_
+
+
+#include <jni.h>
+#include "JniOcResource.h"
+
+/**
+ * @class JObject
+ * @brief This class provides a set of functions for JNI object.
+ *
+ */
+class JObject
+{
+ public:
+ /**
+ * @brief constructor
+ */
+ JObject(JNIEnv *env);
+
+ /**
+ * @brief constructor
+ */
+ JObject(JNIEnv *env, jobject obj);
+
+ /**
+ * @brief constructor
+ */
+ JObject(JNIEnv *env, const char *classPath);
+
+ /**
+ * @brief destructor
+ *
+ */
+ virtual ~JObject();
+
+ /**
+ * Function to get the jobject.
+ *
+ * @return jobject, returns a new JNI object or NULL otherwise.
+ *
+ */
+ virtual jobject getObject() const;
+
+ /**
+ * Function to detach the jobject.
+ *
+ * @return void
+ *
+ */
+ void detachObject();
+
+ protected:
+ /**
+ * JNI Environment Pointer
+ */
+ JNIEnv *m_pEnv;
+ /**
+ * Java Object
+ */
+ jobject m_pObject;
+ /**
+ * Java Class
+ */
+ jclass m_pClazz;
+ /**
+ * Boolean variable to check if an object is new
+ */
+ bool m_fIsNewObject;
+};
+#endif //__JNI_OBJECT_H_
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file jni_setter.h
+ *
+ * @brief This file contains the JSetter class declarations and and its functions required
+ * to set data types in C++ object from Java object
+*/
+
+#ifndef __JNI_SETTER_H_
+#define __JNI_SETTER_H_
+
+
+#include <jni.h>
+
+/**
+ * @class JSetter
+ * @brief This class provide utility to set data types in C++ object from Java object
+ *
+ */
+class JSetter
+{
+ public:
+
+ /**
+ * This function is called to set Integer field in to C++ object.
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject to which integer field will be set.
+ * @param fieldName
+ * Name of the field to be set in JObject
+ * @param value
+ * integer value mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool setJIntField(JNIEnv *env, jobject &object, const char *fieldName, int value);
+
+ /**
+ * This function is called to set Long field in to C++ object.
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject to which Long field will be set.
+ * @param fieldName
+ * Name of the field to be set in JObject
+ * @param value
+ * Long value mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool setJLongField(JNIEnv *env, jobject &object, const char *fieldName,
+ jlong value);
+
+ /**
+ * This function is called to Set Boolean field to C++ object
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject to which boolean field has to be set
+ * @param fieldName
+ * Name of the field to be set in JObject
+ * @param value
+ * boolean value mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool setJBoolField(JNIEnv *env, jobject &object, const char *fieldName, bool value);
+ /**
+ * This function is called to Set String field from the C++ object
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject in which string value has to be set
+ * @param fieldName
+ * Name of the field to be set in JObject
+ * @param value
+ * string value mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool setJStringField(JNIEnv *env, jobject &object, const char *fieldName,
+ const char *value);
+
+ /**
+ * This function is called to set Object reference in C++ object.
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject to which Object reference is to be set.
+ * @param fieldName
+ * Name of the field to be set in JObject
+ * @param fieldType
+ * Type of the field to be set in JObject
+ * @param value
+ * value of Object mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool setJObjectField(JNIEnv *env, jobject &object, const char *fieldName,
+ const char *fieldType, const jobject value);
+};
+
+#endif //__JNI_SETTER_H_
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file jni_string.h
+ *
+ * @brief This file contains the declaration of JString class and its members related to JString.
+ *
+*/
+
+#ifndef __JNI_STRING_H_
+#define __JNI_STRING_H_
+
+
+#include <string>
+
+#include "jni_object.h"
+
+/**
+ * @class JString
+ * @brief This class inherits JObject class and provides a set of functions for JNI String.
+ *
+ */
+class JString : public JObject
+{
+ public:
+ /**
+ * @brief constructor
+ */
+ JString(JNIEnv *env, jstring value);
+ /**
+ * @brief constructor
+ */
+ JString(JNIEnv *env, const char *value);
+ /**
+ * @brief constructor
+ */
+ JString(JNIEnv *env, const std::string &value);
+ /**
+ * @brief destructor
+ */
+ ~JString();
+
+ /**
+ * Function to get the string value and set it.
+ *
+ * @param value - String value to set to a private member variable.
+ *
+ * @return bool - true on success
+ *
+ */
+ bool getValue(std::string &value);
+
+ /**
+ * Function to get the private string value.
+ *
+ * @return C String value.
+ *
+ */
+ const char *c_str();
+
+ private:
+ std::string m_cstr;
+};
+#endif //__JNI_STRING_H_
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file jni_things_manager_jvm.h
+ *
+ * @brief This file contains the essential declarations and functions required
+ * for JNI implementation
+ */
+
+#ifndef __JNI_THINGS_MANAGER_JVM_H_
+#define __JNI_THINGS_MANAGER_JVM_H_
+
+
+#include <jni.h>
+#include <thread>
+#include <mutex>
+
+#define TM_SERVICE_NATIVE_API_CLASS_PATH "org/iotivity/service/tm/ThingsManagerNativeInterface"
+#define TM_SERVICE_NATIVE_API_CLASS_TYPE "Lorg/iotivity/service/tm/ThingsManagerNativeInterface;"
+
+#define TM_SERVICE_CALLBACK_CLASS_PATH "org/iotivity/service/tm/ThingsManagerCallback"
+#define TM_SERVICE_CALLBACK_CLASS_TYPE "Lorg/iotivity/service/tm/ThingsManagerCallback;"
+
+#define TM_SERVICE_PLATFORM_CLASS_PATH "org/iotivity/base/OcPlatform"
+#define TM_SERVICE_PLATFORM_CLASS_TYPE "Lorg/iotivity/base/OcPlatform;"
+
+#define TM_SERVICE_PLATFORM_CONFIG_CLASS_PATH "org/iotivity/base/PlatformConfig"
+#define TM_SERVICE_PLATFORM_CONFIG_CLASS_TYPE "Lorg/iotivity/base/PlatformConfig;"
+
+#define TM_SERVICE_CAPABILITY_PATH "org/iotivity/service/tm/Capability"
+#define TM_SERVICE_CAPABILITY_TYPE "Lorg/iotivity/service/tm/Capability;"
+
+#define TM_SERVICE_ACTION_PATH "org/iotivity/service/tm/Action"
+#define TM_SERVICE_ACTION_TYPE "Lorg/iotivity/service/tm/Action;"
+
+#define TM_SERVICE_ACTIONSET_PATH "org/iotivity/service/tm/ActionSet"
+#define TM_SERVICE_ACTIONSET_TYPE "Lorg/iotivity/service/tm/ActionSet;"
+
+#define TM_SERVICE_OCRESOURCE_PATH "org/iotivity/base/OcResource"
+#define TM_SERVICE_OCRESOURCE_TYPE "Lorg/iotivity/base/OcResource;"
+
+#define TM_SERVICE_HEADER_OPTION_PATH "org/iotivity/base/OcHeaderOption"
+#define TM_SERVICE_HEADER_OPTION_TYPE "Lorg/iotivity/base/OcHeaderOption;"
+
+#define TM_SERVICE_OCREPRESENTATION_PATH "org/iotivity/base/OcRepresentation"
+#define TM_SERVICE_OCREPRESENTATION_TYPE "Lorg/iotivity/base/OcRepresentation;"
+
+#define TM_SERVICE_OCRESOURCEHANDLE_PATH "org/iotivity/base/OcResourceHandle"
+#define TM_SERVICE_OCRESOURCEHANDLE_TYPE "Lorg/iotivity/base/OcResourceHandle;"
+
+#define TM_SERVICE_TIME_PATH "org/iotivity/service/tm/Time"
+
+#define TM_JAVA_VECTOR_CLASS_PATH "java/util/Vector"
+#define TM_JAVA_VECTOR_TYPE "Ljava/util/Vector;"
+
+#define TM_JAVA_STRING_TYPE "Ljava/lang/String;"
+
+/**
+ * @class ThingsManagerJVM
+ * @brief This class provides functions related to JNI Environment.
+ *
+ */
+class ThingsManagerJVM
+{
+ public:
+ /**
+ * @brief destructor
+ */
+ ~ThingsManagerJVM() {};
+
+ /**
+ * @brief Get JVM instance
+ */
+ static JNIEnv *getEnv();
+
+ /**
+ * @brief Release aquired JVM instance
+ */
+ static void releaseEnv();
+
+ public:
+ /**
+ * Java VM pointer
+ */
+ static JavaVM *m_jvm;
+
+ private:
+ /**
+ * @brief constructor
+ */
+ ThingsManagerJVM();
+
+ /**
+ * Mutex for thread synchronization
+ */
+ static std::mutex m_currentThreadMutex;
+};
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+jclass GetJClass(const char *szClassPath);
+jobject GetJObjectInstance(const char *szClassPath);
+#ifdef __cplusplus
+}
+#endif
+#endif //__JNI_THINGS_MANAGER_JVM_H_
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+#include "jni_getter.h"
+
+#include <string>
+
+#include "JniOcResource.h"
+
+#define LOG_TAG "TM_JGetter"
+
+
+bool JGetter::getJStringField(JNIEnv *env, jobject &object, const char *fieldName,
+ std::string &value)
+{
+ if (NULL == env ||
+ NULL == object ||
+ NULL == fieldName)
+ {
+ LOGE("getJStringField invalid parameters");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass( object );
+ if (NULL == clazz)
+ {
+ LOGE("GetObjectClass failed [%s]", fieldName);
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID( clazz, fieldName, "Ljava/lang/String;" );
+ if (0 == fieldID)
+ {
+ LOGE("GetFieldID failed [%s]", fieldName);
+ env->DeleteLocalRef(clazz);
+ return false;
+ }
+
+ jstring jValue = (jstring)env->GetObjectField( object, fieldID );
+ if (NULL == jValue)
+ {
+ LOGE("GetObjectField failed [%s]", fieldName);
+ env->DeleteLocalRef(clazz);
+ return false;
+ }
+
+ const char *cstr = env->GetStringUTFChars(jValue, 0);
+ if (cstr == NULL)
+ {
+ LOGE("GetStringUTFChars failed");
+ }
+ else
+ {
+ value = cstr;
+ env->ReleaseStringUTFChars(jValue, cstr);
+ }
+
+ env->DeleteLocalRef(clazz);
+ env->DeleteLocalRef(jValue);
+
+ return true;
+}
+
+
+bool JGetter::getJBoolField(JNIEnv *env, jobject &object, const char *fieldName, bool &value)
+{
+ if (NULL == env ||
+ NULL == object ||
+ NULL == fieldName)
+ {
+ LOGE("getJBoolField invalid parameters");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass( object );
+ if (NULL == clazz)
+ {
+ LOGE("GetObjectClass failed");
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID( clazz, fieldName, "Z" );
+ if (0 == fieldID)
+ {
+ LOGE("GetFieldID failed [%s]", fieldName);
+ env->DeleteLocalRef( clazz );
+ return false;
+ }
+
+ value = env->GetBooleanField( object, fieldID );
+
+ env->DeleteLocalRef(clazz);
+
+ return true;
+}
+
+bool JGetter::getJIntField(JNIEnv *env, jobject &object, const char *fieldName, int &value)
+{
+ if (NULL == env ||
+ NULL == object ||
+ NULL == fieldName)
+ {
+ LOGE("getJIntField invalid parameters");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass( object );
+ if (NULL == clazz)
+ {
+ LOGE("GetObjectClass failed");
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID( clazz, fieldName, "I" );
+ if (0 == fieldID)
+ {
+ LOGE("GetFieldID failed [%s]", fieldName);
+ env->DeleteLocalRef( clazz );
+ return false;
+ }
+
+ value = env->GetIntField( object, fieldID );
+
+ env->DeleteLocalRef(clazz);
+
+ return true;
+}
+
+bool JGetter::getJObjectField(JNIEnv *env, jobject &object, const char *fieldName,
+ const char *fieldType, jobject &value)
+{
+ if (NULL == env ||
+ NULL == object ||
+ NULL == fieldName)
+ {
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass( object );
+ if (NULL == clazz)
+ {
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID( clazz, fieldName, fieldType );
+ if (0 == fieldID)
+ {
+ LOGE("GetFieldID failed [%s][%s]", fieldName, fieldType);
+ return false;
+ }
+
+ value = env->GetObjectField( object, fieldID );
+ if (NULL == value)
+ {
+ return false;
+ }
+
+ env->DeleteLocalRef(clazz);
+
+ return true;
+}
--- /dev/null
+#include "jni_object.h"
+
+//#define NULL 0
+#define LOG_TAG "TM_JObject"
+
+
+
+JObject::JObject(JNIEnv *env) : m_pEnv( env ),
+ m_pObject(NULL),
+ m_pClazz( NULL ),
+ m_fIsNewObject(true)
+{
+}
+
+JObject::JObject(JNIEnv *env, jobject obj) : m_pEnv(NULL),
+ m_pObject(NULL),
+ m_pClazz(NULL),
+ m_fIsNewObject(false)
+{
+ if ( NULL == env || NULL == obj)
+ {
+ return;
+ }
+
+ m_pEnv = env;
+ m_pObject = obj;
+ m_pClazz = m_pEnv->GetObjectClass( obj );
+}
+
+JObject::JObject(JNIEnv *env, const char *classPath) : m_pEnv(NULL),
+ m_pObject(NULL),
+ m_pClazz(NULL),
+ m_fIsNewObject(true)
+{
+ if ( NULL == env || NULL == classPath)
+ {
+ LOGI("JObject Invalid parameters");
+ return;
+ }
+
+ m_pEnv = env;
+ //m_pClazz = GetJClass( classPath );
+
+ if (NULL == m_pClazz)
+ {
+ LOGE( "GetJClass failed [%s]" , classPath);
+ return;
+ }
+
+ jmethodID mid = env->GetMethodID(m_pClazz, "<init>", "()V");
+ if (NULL == mid)
+ {
+ LOGE( "GetMethodID failed [%s]" , classPath);
+ return;
+ }
+
+ m_pObject = env->NewObject(m_pClazz, mid);
+}
+
+JObject::~JObject()
+{
+ if (m_pEnv)
+ {
+ if (m_pObject && m_fIsNewObject)
+ {
+ m_pEnv->DeleteLocalRef( m_pObject );
+ }
+
+ if (m_pClazz && !m_fIsNewObject)
+ {
+ m_pEnv->DeleteLocalRef( m_pClazz );
+ }
+ }
+}
+
+jobject JObject::getObject() const
+{
+ return m_pObject;
+}
+
+
+void JObject::detachObject()
+{
+ if (m_fIsNewObject)
+ {
+ m_fIsNewObject = false;
+ m_pClazz = NULL;
+ }
+}
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+#include "jni_setter.h"
+
+#include <string>
+
+#include "JniOcResource.h"
+
+#define LOG_TAG "TM_JSetter"
+
+
+bool JSetter::setJStringField(JNIEnv *env, jobject &object, const char *fieldName,
+ const char *value)
+{
+ if (NULL == env || NULL == fieldName)
+ {
+ LOGE("setJStringField invalid parameters");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass( object );
+ if (NULL == clazz)
+ {
+ LOGE("GetObjectClass failed");
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID( clazz, fieldName, "Ljava/lang/String;");
+ if (0 == fieldID)
+ {
+ LOGE("GetFieldID failed [%s]", fieldName);
+ env->DeleteLocalRef( clazz );
+ return false;
+ }
+
+ jstring jvalue ;
+ if (value != NULL && strlen(value) > 0)
+ {
+ jclass strClass = env->FindClass("java/lang/String");
+ jmethodID ctorID = env->GetMethodID(strClass, "<init>", "([BLjava/lang/String;)V");
+ jbyteArray bytes = env->NewByteArray(strlen(value));
+ env->SetByteArrayRegion(bytes, 0, strlen(value), (jbyte *)value);
+ jstring encoding = env->NewStringUTF("utf-8");
+ jvalue = (jstring)env->NewObject(strClass, ctorID, bytes, encoding);
+ env->DeleteLocalRef(strClass);
+ env->DeleteLocalRef(bytes);
+ env->DeleteLocalRef(encoding);
+ }
+ else
+ {
+ jvalue = env->NewStringUTF("");
+ }
+
+ env->SetObjectField(object, fieldID, jvalue);
+
+ env->DeleteLocalRef(jvalue);
+ env->DeleteLocalRef( clazz );
+
+ return true;
+}
+
+
+bool JSetter::setJIntField(JNIEnv *env, jobject &object, const char *fieldName, int value)
+{
+ if (NULL == env || NULL == fieldName)
+ {
+ LOGE("setJIntField invalid paramter");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass( object );
+ if (NULL == clazz)
+ {
+ LOGE("GetObjectClass failed");
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID( clazz, fieldName, "I");
+ if (0 == fieldID)
+ {
+ LOGE("GetFieldID failed [%s]", fieldName);
+ env->DeleteLocalRef( clazz );
+ return false;
+ }
+ env->SetIntField(object, fieldID, value);
+
+ env->DeleteLocalRef( clazz );
+
+ return true;
+}
+
+
+bool JSetter::setJLongField(JNIEnv *env, jobject &object, const char *fieldName, jlong value)
+{
+ if (NULL == env || NULL == fieldName)
+ {
+ LOGE("setJLongField invalid parameters");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass( object );
+ if (NULL == clazz)
+ {
+ LOGE("GetObjectClass failed");
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID( clazz, fieldName, "J");
+ if (0 == fieldID)
+ {
+ LOGE("GetFieldID failed [%s]", fieldName);
+ env->DeleteLocalRef( clazz );
+ return false;
+ }
+ env->SetLongField(object, fieldID, value);
+
+ env->DeleteLocalRef( clazz );
+
+ return true;
+}
+
+
+bool JSetter::setJBoolField(JNIEnv *env, jobject &object, const char *fieldName, bool value)
+{
+ if (NULL == env || NULL == fieldName)
+ {
+ LOGE("setJBoolField invalid parameters");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass( object );
+ if (NULL == clazz)
+ {
+ LOGE("GetObjectClass failed");
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID( clazz, fieldName, "Z");
+ if (0 == fieldID)
+ {
+ LOGE("GetFieldID failed [%s]", fieldName);
+ env->DeleteLocalRef( clazz );
+ return false;
+ }
+ env->SetBooleanField(object, fieldID, value);
+
+ env->DeleteLocalRef( clazz );
+
+ return true;
+}
+
+
+bool JSetter::setJObjectField(JNIEnv *env, jobject &object, const char *fieldName,
+ const char *fieldType, const jobject value)
+{
+ if (NULL == env || NULL == fieldName)
+ {
+ LOGE("setJBoolField invalid parameters");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass( object );
+ if (NULL == clazz)
+ {
+ LOGE("GetObjectClass failed");
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID( clazz, fieldName, fieldType);
+ if (0 == fieldID)
+ {
+ LOGE("GetFieldID failed [%s] [%s]", fieldName, fieldType);
+ env->DeleteLocalRef( clazz );
+ return false;
+ }
+ env->SetObjectField(object, fieldID, value);
+
+ env->DeleteLocalRef( clazz );
+
+ return true;
+}
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+#include "jni_string.h"
+
+#define LOG_TAG "TM_JString"
+
+JString::JString(JNIEnv *env, jstring value) : JObject(env, value)
+{
+ const char *buff = env->GetStringUTFChars(value, 0);
+
+ m_cstr = buff;
+
+ env->ReleaseStringUTFChars(value, buff);
+}
+
+JString::JString(JNIEnv *env, const char *value) : JObject(env)
+{
+ m_cstr = value;
+
+ if (env)
+ {
+ m_pObject = env->NewStringUTF( value );
+ }
+}
+
+JString::JString(JNIEnv *env, const std::string &value) : JObject(env)
+{
+ m_cstr = value;
+
+ if (env)
+ {
+ m_pObject = env->NewStringUTF( value.c_str() );
+ }
+}
+
+JString::~JString()
+{
+}
+
+bool JString::getValue(std::string &value)
+{
+ value = m_cstr;
+ return true;
+}
+
+const char *JString::c_str()
+{
+ return m_cstr.c_str();
+}
+
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+#include "jni_things_manager_jvm.h"
+#include <string>
+#include "jni_things_manager.h"
+#include "jni_things_manager_util.h"
+#include "JniOcResource.h"
+
+#define TM_ERROR_JNI_FOUND_CLASS_FAILED -2005
+
+/**
+ * @class JClassMap
+ * @brief This class provides functions for initializing the Java class path and Java class.
+ *
+ */
+class JClassMap
+{
+ public:
+ /**
+ * Java Class
+ */
+ jclass classRef;
+ /**
+ * Java Class Path
+ */
+ const char *szClassPath;
+
+ /**
+ * @brief constructor
+ */
+ JClassMap(const char *path)
+ : classRef(NULL)
+ {
+ szClassPath = path;
+ }
+};
+
+/**
+ * @class JObjectMap
+ * @brief This class provides functins for initializing the Java Class path and Java Class
+ * Object.
+ *
+ */
+class JObjectMap
+{
+ public:
+ /**
+ * Java Object
+ */
+ jobject object;
+ /**
+ * Java Class Path
+ */
+ const char *szClassPath;
+
+ /**
+ * @brief constructor
+ */
+ JObjectMap(const char *path)
+ : object(NULL)
+ {
+ szClassPath = path;
+ }
+};
+
+static JClassMap gJClassMapArray[] =
+{
+ JClassMap(TM_SERVICE_NATIVE_API_CLASS_PATH),
+ JClassMap(TM_SERVICE_CALLBACK_CLASS_PATH),
+ JClassMap(TM_SERVICE_OCRESOURCE_PATH),
+ JClassMap(TM_SERVICE_OCREPRESENTATION_PATH),
+ JClassMap(TM_SERVICE_HEADER_OPTION_PATH),
+ JClassMap(TM_SERVICE_ACTIONSET_PATH),
+ JClassMap(TM_SERVICE_CAPABILITY_PATH),
+ JClassMap(TM_SERVICE_ACTION_PATH),
+ JClassMap(TM_SERVICE_PLATFORM_CLASS_PATH),
+ JClassMap(TM_SERVICE_PLATFORM_CONFIG_CLASS_PATH),
+ JClassMap(TM_SERVICE_OCRESOURCEHANDLE_PATH)
+};
+
+static JObjectMap gJObjectMapArray[] =
+{
+ JObjectMap(TM_SERVICE_CALLBACK_CLASS_PATH)
+};
+
+static JNINativeMethod gThingsManagerMethodTable[] =
+{
+ { "findCandidateResources", "(Ljava/util/Vector;I)I", (void *) JNIThingsManagerFindCandidateResource},
+ { "subscribeCollectionPresence", "(Lorg/iotivity/base/OcResource;)I", (void *) JNIThingsManagerSubscribeCollectionPresence},
+ { "bindResourceToGroup", "(Lorg/iotivity/base/OcResource;Lorg/iotivity/base/OcResourceHandle;)Lorg/iotivity/base/OcResourceHandle;", (void *) JNIThingsManagerBindResourceToGroup},
+ { "findGroup", "(Ljava/util/Vector;)I", (void *) JNIThingsManagerFindGroup},
+ { "createGroup", "(Ljava/lang/String;)I", (void *) JNIThingsManagerCreateGroup},
+ { "joinGroup", "(Ljava/lang/String;Lorg/iotivity/base/OcResourceHandle;)I", (void *) JNIThingsManagerJoinGroupString},
+ { "joinGroup", "(Lorg/iotivity/base/OcResource;Lorg/iotivity/base/OcResourceHandle;)I", (void *) JNIThingsManagerJoinGroupObject},
+ { "leaveGroup", "(Ljava/lang/String;Lorg/iotivity/base/OcResourceHandle;)I", (void *) JNIThingsManagerLeaveGroup},
+ { "leaveGroup", "(Lorg/iotivity/base/OcResource;Ljava/lang/String;Lorg/iotivity/base/OcResourceHandle;)I", (void *) JNIThingsManagerLeaveGroupForResource},
+ { "deleteGroup", "(Ljava/lang/String;)V", (void *) JNIThingsManagerDeleteGroup},
+ { "getGroupList", "()Ljava/util/Map;", (void *) JNIThingsManagerGetGroupList},
+ { "updateConfigurations", "(Lorg/iotivity/base/OcResource;Ljava/util/Map;)I", (void *) JNIThingsManagerUpdateConfigurations},
+ { "getConfigurations", "(Lorg/iotivity/base/OcResource;Ljava/util/Vector;)I", (void *) JNIThingsManagerGetConfigurations},
+ { "getListOfSupportedConfigurationUnits", "()Ljava/lang/String;", (void *) JNIThingsManagerGetListOfSupportedConfigurationUnits},
+ { "doBootstrap", "()I", (void *) JNIThingsManagerDoBootstrap},
+ { "reboot", "(Lorg/iotivity/base/OcResource;)I", (void *) JNIThingsManagerReboot},
+ { "factoryReset", "(Lorg/iotivity/base/OcResource;)I", (void *) JNIThingsManagerFactoryReset},
+ { "addActionSet", "(Lorg/iotivity/base/OcResource;Lorg/iotivity/service/tm/ActionSet;)I", (void *) JNIThingsManagerAddActionSet},
+ { "executeActionSet", "(Lorg/iotivity/base/OcResource;Ljava/lang/String;)I", (void *) JNIThingsManagerExecuteActionSet},
+ { "executeActionSet", "(Lorg/iotivity/base/OcResource;Ljava/lang/String;J)I", (void *) JNIThingsManagerExecuteActionSetWithDelay},
+ { "cancelActionSet", "(Lorg/iotivity/base/OcResource;Ljava/lang/String;)I", (void *) JNIThingsManagerCancelActionSet},
+ { "getActionSet", "(Lorg/iotivity/base/OcResource;Ljava/lang/String;)I", (void *) JNIThingsManagerGetActionSet},
+ { "deleteActionSet", "(Lorg/iotivity/base/OcResource;Ljava/lang/String;)I", (void *) JNIThingsManagerDeleteActionSet},
+};
+
+static int gThingsManagerMethodTableSize = sizeof(gThingsManagerMethodTable) / sizeof(
+ gThingsManagerMethodTable[0]);
+
+
+int InitializeJClassMapArray(JNIEnv *env)
+{
+ LOGI("InitializeJClassMapArray: Enter");
+
+ unsigned int nLen = sizeof(gJClassMapArray) / sizeof(JClassMap);
+
+ for (unsigned int i = 0; i < nLen; i++)
+ {
+ jclass classRef = env->FindClass(gJClassMapArray[i].szClassPath);
+ if (NULL == classRef)
+ {
+ LOGE("FindClass failed for [%s]", gJClassMapArray[i].szClassPath);
+ return -1;
+ }
+ gJClassMapArray[i].classRef = (jclass)env->NewGlobalRef(classRef);
+ env->DeleteLocalRef(classRef);
+ }
+
+ LOGI("InitializeJClassMapArray: Exit");
+ return 0;
+}
+
+jclass GetJClass(const char *szClassPath)
+{
+ unsigned int nLen = sizeof(gJClassMapArray) / sizeof(JClassMap);
+
+ jclass classRef = NULL;
+
+ for (unsigned int i = 0; i < nLen; i++)
+ {
+ if (0 == strcmp(gJClassMapArray[i].szClassPath, szClassPath))
+ {
+ classRef = gJClassMapArray[i].classRef;
+ break;
+ }
+ }
+
+ return classRef;
+}
+
+void DeleteClassMapArray(JNIEnv *env)
+{
+ LOGI("DeleteClassMapArray: Enter");
+
+ unsigned int nLen = sizeof(gJClassMapArray) / sizeof(JClassMap);
+ for (unsigned int i = 0; i < nLen; i++)
+ {
+ if (NULL != gJClassMapArray[i].classRef)
+ {
+ env->DeleteGlobalRef(gJClassMapArray[i].classRef);
+ gJClassMapArray[i].classRef = NULL;
+ }
+ }
+
+ LOGI("DeleteClassMapArray: Exit");
+}
+
+int InitializeJObjectMapArray(JNIEnv *env)
+{
+ LOGI("InitializeJObjectMapArray: Enter");
+
+ unsigned int nLen = sizeof(gJObjectMapArray) / sizeof(JObjectMap);
+
+ for (unsigned int i = 0; i < nLen; i++)
+ {
+ jclass classRef = env->FindClass(gJObjectMapArray[i].szClassPath);
+ if (NULL == classRef)
+ {
+ LOGE("InitializeJObjectMapArray: FindClass failed for [%s]", gJObjectMapArray[i].szClassPath);
+ return -1;
+ }
+
+ std::string methodSignature = "()L";
+ methodSignature.append(gJObjectMapArray[i].szClassPath);
+ methodSignature.append(";");
+
+ // Get the object form "getInstance"
+ jmethodID methodid = env->GetStaticMethodID(classRef, "getInstance", methodSignature.c_str());
+ if (NULL == methodid)
+ {
+ LOGE("InitializeJObjectMapArray: GetStaticMethodID failed for [%s]",
+ gJObjectMapArray[i].szClassPath);
+ return -1;
+ }
+
+ // Get the singleton object
+ jobject objectRef = (jobject)env->CallStaticObjectMethod(classRef, methodid);
+ if (NULL == objectRef)
+ {
+ LOGE("InitializeJObjectMapArray: CallStaticObjectMethod failed for [%s]",
+ gJObjectMapArray[i].szClassPath);
+ return -1;
+ }
+
+ gJObjectMapArray[i].object = (jobject)env->NewGlobalRef(objectRef);
+ env->DeleteLocalRef(classRef);
+ }
+
+ LOGI("InitializeJObjectMapArray: Exit");
+ return 0;
+}
+
+jobject GetJObjectInstance(const char *szClassPath)
+{
+ unsigned int nLen = sizeof(gJObjectMapArray) / sizeof(JObjectMap);
+
+ jobject object = NULL;
+
+ for (unsigned int i = 0; i < nLen; i++)
+ {
+ if (0 == strcmp(gJObjectMapArray[i].szClassPath, szClassPath))
+ {
+ object = gJObjectMapArray[i].object;
+ break;
+ }
+ }
+
+ return object;
+}
+
+void DeleteObjectMapArray(JNIEnv *env)
+{
+ LOGI("DeleteObjectMapArray: Enter");
+
+ unsigned int nLen = sizeof(gJObjectMapArray) / sizeof(JObjectMap);
+ for (unsigned int i = 0; i < nLen; i++)
+ {
+ if (NULL != gJObjectMapArray[i].object)
+ {
+ env->DeleteGlobalRef(gJObjectMapArray[i].object);
+ gJObjectMapArray[i].object = NULL;
+ }
+ }
+
+ LOGI("DeleteObjectMapArray: Exit");
+}
+
+JavaVM *ThingsManagerJVM::m_jvm = NULL;
+std::mutex ThingsManagerJVM::m_currentThreadMutex;
+JNIEnv *ThingsManagerJVM::getEnv()
+{
+ std::unique_lock<std::mutex> scoped_lock(m_currentThreadMutex);
+
+ if (NULL == m_jvm)
+ {
+ LOGE("Failed to get JVM");
+ return NULL;
+ }
+
+ JNIEnv *env = NULL;
+ jint ret = m_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION);
+ switch (ret)
+ {
+ case JNI_OK:
+ return env;
+ case JNI_EDETACHED:
+ if (0 > m_jvm->AttachCurrentThread(&env, NULL))
+ {
+ LOGE("Failed to attach current thread to env");
+ return NULL;
+ }
+ return env;
+ case JNI_EVERSION:
+ LOGE("JNI version not supported");
+ default:
+ LOGE("Failed to get the environment");
+ return NULL;
+ }
+}
+
+void ThingsManagerJVM::releaseEnv()
+{
+ std::unique_lock<std::mutex> scoped_lock(m_currentThreadMutex);
+
+ if (0 == m_jvm)
+ {
+ LOGE("Failed to release JVM");
+ return;
+ }
+
+ m_jvm->DetachCurrentThread();
+}
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
+{
+ LOGD("JNI_OnLoad: Enter");
+
+ if (!vm)
+ {
+ LOGE("JNI_OnLoad: vm is invalid");
+ return JNI_ERR;
+ }
+
+ JNIEnv *env = NULL;
+ if (JNI_OK != vm->GetEnv((void **) &env, JNI_CURRENT_VERSION))
+ {
+ LOGE("JNI_OnLoad: Version check is failed!");
+ return JNI_ERR;
+ }
+
+ if (0 != InitializeJClassMapArray(env))
+ {
+ LOGE("JNI_OnLoad: Initialize JClass Array failed!");
+ return JNI_ERR;
+ }
+
+ if (0 != InitializeJObjectMapArray(env))
+ {
+ LOGE("JNI_OnLoad: Initialize JObject Array failed!");
+ return JNI_ERR;
+ }
+
+ jclass thingsManagerClassRef = GetJClass(TM_SERVICE_NATIVE_API_CLASS_PATH);
+ if (NULL == thingsManagerClassRef)
+ {
+ LOGE("JNI_OnLoad: GetJClass gThingsManagerClass failed !");
+ return JNI_ERR;
+ }
+ env->RegisterNatives(thingsManagerClassRef, gThingsManagerMethodTable,
+ gThingsManagerMethodTableSize);
+
+ ThingsManagerJVM::m_jvm = vm;
+
+ LOGI("JNI_OnLoad: Exit");
+ return JNI_CURRENT_VERSION;
+}
+
+JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
+{
+ LOGD("JNI_OnUnload: Enter");
+
+ JNIEnv *env = NULL;
+ if (JNI_OK != vm->GetEnv((void **)&env, JNI_CURRENT_VERSION))
+ {
+ LOGE("JNI_OnLoad: Version check is failed!");
+ return;
+ }
+
+ // delete all class references
+ DeleteClassMapArray(env);
+
+ // delete all jobject
+ DeleteObjectMapArray(env);
+
+ LOGD("JNI_OnUnload: Exit");
+}
+
+#ifdef __cplusplus
+}
+#endif
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file jni_action.h
+ *
+ * @brief This file contains the declaration of JniAction class and its members related to JniAction.
+ */
+
+#ifndef __JNI_ACTION_H_
+#define __JNI_ACTION_H_
+
+
+#include <vector>
+#include <string>
+
+#include "jni_object.h"
+#include "jni_capability.h"
+
+/**
+ * @class JniAction
+ * @brief This class provides a set of functions to get and set Action Class member variables
+ *
+ */
+class JniAction : public JObject
+{
+ public:
+ /**
+ * @brief constructor
+ */
+ JniAction(JNIEnv *env, jobject obj);
+
+ /**
+ * @brief constructor
+ */
+ JniAction(JNIEnv *env);
+
+ /**
+ * @brief destructor
+ *
+ */
+ ~JniAction();
+
+ /**
+ * Retrieves target value from JniAction class object
+ *
+ * @param target - target value
+ *
+ * @return Boolean, true on success, otherwise false
+ *
+ */
+ bool getTarget(std::string &target);
+
+ /**
+ * Sets target value of JniAction class object
+ *
+ * @param target - target value
+ *
+ * @return Boolean, true on success, otherwise false
+ *
+ */
+ bool setTarget(const std::string target);
+
+ /**
+ * Retrieves capability values from JniAction class object
+ *
+ * @param capabilityList - capability list
+ *
+ * @return Boolean, true on success, otherwise false
+ */
+ bool getJniCapabilityValues(std::vector<OIC::Capability *> &capabilityList);
+
+};
+#endif //__JNI_ACTION_H_
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file jni_action_set.h
+ *
+ * @brief This file contains the declaration of JniActionSet class
+ * and its members related to JniActionSet.
+ */
+
+#ifndef __JNI_ACTIONSET_H_
+#define __JNI_ACTIONSET_H_
+
+
+#include <vector>
+#include <string>
+
+#include "ThingsManager.h"
+#include "ActionSet.h"
+#include "jni_object.h"
+#include "jni_action.h"
+
+using namespace OC;
+using namespace OIC;
+
+/**
+ * @class JniActionSet
+ * @brief This class provides a set of functions to get and set ActionSet Class member variables
+ *
+ */
+class JniActionSet : public JObject
+{
+ public:
+ /**
+ * @brief constructor
+ */
+ JniActionSet(JNIEnv *env, jobject obj);
+
+ /**
+ * @brief constructor
+ */
+ JniActionSet(JNIEnv *env);
+
+ /**
+ * @brief destructor
+ *
+ */
+ ~JniActionSet();
+
+ /**
+ * Retrieves target value from JniActionSet class object
+ *
+ * @param name - ActionSet Name
+ *
+ * @return Boolean, true on success, otherwise false
+ *
+ */
+ bool getJniActionSetName(std::string &name);
+
+ /**
+ * Sets target value of JniActionSet class object
+ *
+ * @param name - ActionSet Name
+ *
+ * @return Boolean, true on success, otherwise false
+ *
+ */
+ bool setJniActionSetName(const std::string name);
+
+ /**
+ * Retrieves capability values from JniActionSet class object
+ *
+ * @param actionList - List of Actions
+ *
+ * @return Boolean, true on success, otherwise false
+ */
+ bool getJniListOfActions(std::vector<OIC::Action *> &actionList);
+
+ /**
+ * Converts actionSet class from java to CPP
+ *
+ * @param env - Default JNI Environment Pointer
+ * @param jnewActionSet - action set
+ *
+ * @return OIC CPP ActionSet
+ */
+ ActionSet *getActionSet(JNIEnv *env, jobject jnewActionSet);
+
+ /**
+ * Converts Time class from java to CPP
+ *
+ * @param env - Default JNI Environment Pointer
+ * @param jnewActionSet - Java action set
+ * @param pActionSet - CPP action set
+ *
+ * @return Boolean, true on success, otherwise false
+ */
+ bool setTimeInfo(JNIEnv *env, jobject jnewActionSet, OIC::ActionSet *pActionSet);
+};
+#endif //__JNI_ACTIONSET_H_
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file jni_capability.h
+ *
+ * @brief This file contains the utility functions for conversions from java to CPP
+ * and viceversa
+ */
+
+#ifndef __JNI_CAPABILITY_H_
+#define __JNI_CAPABILITY_H_
+
+
+#include <string>
+
+#include <ActionSet.h>
+#include "jni_object.h"
+
+/**
+ * @class JniCapability
+ * @brief This class provides a set of functions to get and set Capability Class member variables
+ *
+ */
+class JniCapability : public JObject
+{
+ public:
+ /**
+ * @brief constructor
+ */
+ JniCapability(JNIEnv *env, jobject obj);
+
+ /**
+ * @brief constructor
+ */
+ JniCapability(JNIEnv *env);
+
+ /**
+ * @brief destructor
+ *
+ */
+ ~JniCapability();
+
+ /**
+ * Retrieves Capability value from JniCapability class object
+ *
+ * @param capability
+ * [OUT] capability value
+ *
+ * @return Boolean, true on success, otherwise false
+ *
+ */
+ bool getJniCapabilityValue(std::string &capability);
+
+ /**
+ * Sets Capability value of JniCapability class object
+ *
+ * @param capability
+ * [IN] capability value
+ *
+ * @return Boolean, true on success, otherwise false
+ *
+ */
+ bool setJniCapabilityValue(const std::string capability);
+
+ /**
+ * Retrieves status of JniCapability class object
+ *
+ * @param status
+ * [OUT] status
+ *
+ * @return Boolean, true on success, otherwise false
+ *
+ */
+ bool getJniCapabilityStatus(std::string &status);
+
+ /**
+ * Sets status of JniCapability class object
+ *
+ * @param status
+ * [IN] status
+ *
+ * @return Boolean, true on success, otherwise false
+ *
+ */
+ bool setJniCapabilityStatus(const std::string status);
+};
+#endif //__JNI_CAPABILITY_H_
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+/** @file jni_things_manager.h
+ *
+ * @brief This file contains the declaration of Things Manager service API's
+ * for JNI implementation
+ */
+
+#ifndef __JNI_THINGS_MANAGER_H_
+#define __JNI_THINGS_MANAGER_H_
+
+
+#include <stdio.h>
+#include <string.h>
+
+#include <jni.h>
+#include <jni_string.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * API for discoverying candidate resources.
+ *
+ * @param resourceTypes - required resource types(called "candidate")
+ * @param waitSec - Delay time in seconds to add before starting to find the resources in network.
+ *
+ * @return OCStackResult - return value of this API.
+ * It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerFindCandidateResource
+(JNIEnv *env, jobject interfaceObject, jobject resourceTypes, jint waitSec);
+
+/**
+ * API for subscribing child's state.
+ *
+ * @param resource - collection resource for subscribing presence of all child resources.
+ *
+ * @return OCStackResult - return value of this API.
+ * It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerSubscribeCollectionPresence
+(JNIEnv *env, jobject interfaceObject, jobject resource);
+
+/**
+ * API for register and bind resource to group.
+ *
+ * @param resource - resource for register and bind to group. It has all data.
+ * @param collectionHandle - collection resource handle. It will be added child resource.
+ *
+ * @return childHandle - child resource handle.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jobject JNICALL JNIThingsManagerBindResourceToGroup
+(JNIEnv *env, jobject interfaceObject, jobject resource, jobject collectionHandle);
+
+/**
+ * API for finding a specific remote group when a resource tries to join a group.
+ * Callback is called when a group is found or not.
+ *
+ * @param resourceTypes - resource types of a group to find and join
+ *
+ * @return OCStackResult - return value of this API.
+ * It returns OC_STACK_OK if success.
+ *
+ * NOTE: It return OC_STACK ERROR when It was finding a group.
+ * You should call this api when the group finding process has stopped.
+ * OCStackResult is defined in ocstack.h.
+ */
+
+JNIEXPORT jint JNICALL JNIThingsManagerFindGroup
+(JNIEnv *env, jobject interfaceObject, jobject resourceTypes);
+
+/**
+ * API for creating a new group.
+ *
+ * @param resourceType - resource type of a group to create
+ *
+ * @return OCStackResult - return value of this API.
+ * It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerCreateGroup
+(JNIEnv *env, jobject interfaceObject, jstring resourceType);
+
+/**
+ * API for joining a group. This API is used when a resource that has a group tries
+ * to find a specific remote resource and makes it join a group
+ *
+ * @param resourceType - resource type of a group to join.
+ * @param resourceHandle - resource handle to join a group.
+ *
+ * @return OCStackResult - return value of this API.
+ * It returns OC_STACK_OK if success.
+ *
+ * NOTE: If you want to join the resource in the remote(other) process, use the API
+ * jniThingsManagerJoinGroupObject instead of this.
+ * OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerJoinGroupString
+(JNIEnv *env, jobject interfaceObject, jstring resourceType, jobject resourceHandle);
+
+/**
+ * API for joining a group. This API is used when a resource that
+ * doesn't have a group tries to find and join a specific remote group.
+ *
+ * @param resource - group resource pointer to join.
+ * @param resourceHandle - resource handle to join a group.
+ *
+ * @return OCStackResult - return value of this API.
+ * It returns OC_STACK_OK if success.
+ *
+ * NOTE: NOTE: If you want to join the resource in the same process, use the API
+ * jniThingsManagerJoinGroupString instead of this.
+ * OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerJoinGroupObject
+(JNIEnv *env, jobject interfaceObject, jobject resource, jobject resourceHandle);
+
+/**
+ * API for leaving a joined group.
+ *
+ * @param resourceType - resource type of a group to leave.
+ * @param resourceHandle - resource handle to join a group.
+ *
+ * @return OCStackResult - return value of this API.
+ * It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerLeaveGroup
+(JNIEnv *env, jobject interfaceObject, jstring resourceType, jobject resourceHandle);
+
+/**
+ * API for leaving a joined group.
+ *
+ * @param resource - resource of a group to leave.
+ * @param resourceType - resource type of a group to leave.
+ * @param resourceHandle - resource handle to join a group.
+ *
+ * @return OCStackResult - return value of this API.
+ * It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerLeaveGroupForResource
+(JNIEnv *env, jobject interfaceObject, jobject resource, jstring resourceType,
+ jobject resourceHandle);
+/**
+ * API for deleting a group.
+ *
+ * @param collectionResourceType - resource type of a group to delete.
+ *
+ * @return void
+ */
+JNIEXPORT void JNICALL JNIThingsManagerDeleteGroup
+(JNIEnv *env, jobject interfaceObject, jstring collectionResourceType);
+
+/**
+ * API for getting a list of joined groups.
+ *
+ * @return std::map - return value of this API.
+ * It returns group resource type and group resource handle as a map type.
+ */
+JNIEXPORT jobject JNICALL JNIThingsManagerGetGroupList
+(JNIEnv *env, jobject interfaceObject);
+
+/**
+ * API for updating configuration value of multiple things of a target group
+ * or a single thing.
+ * Before using the below function, a developer should acquire a resource pointer of
+ * (collection) resource that he wants to send a request by calling findResource() function
+ * provided in OCPlatform. And he should also notice a "Configuration Name" term which
+ * represents a nickname of a target attribute of a resource that he wants to update.
+ * The base motivation to introduce the term is to avoid a usage of URI to access a resource
+ * from a developer. Thus, a developer should know which configuration names are supported
+ * by Things Configuration class and what the configuration name means.
+ * To get a list of supported configuration names, use getListOfSupportedConfigurationUnits()
+ * function, which provides the list in JSON format.
+ *
+ * @param resource - resource pointer representing the target group or the single thing.
+ * @param configurations - ConfigurationUnit: a nickname of attribute of target resource
+ * (e.g., installedlocation, currency, (IP)address)
+ * Value : a value to be updated
+ *
+ * @return OCStackResult - return value of this API.
+ * It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerUpdateConfigurations
+(JNIEnv *env, jobject interfaceObject, jobject resource, jobject configurations);
+
+/**
+ * API for getting configuration value of multiple things of a target group
+ * or a single thing.
+ *
+ * @param resource - resource pointer representing the target group or the single thing.
+ * @param configurations - ConfigurationUnit: a nickname of attribute of target resource.
+ *
+ * @return OCStackResult - return value of this API.
+ * It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerGetConfigurations
+(JNIEnv *env, jobject interfaceObject, jobject resource, jobject configurations);
+
+/**
+ * API for showing the list of supported configuration units (configurable parameters)
+ *
+ * @return std::string - return value of this API.
+ * It returns the list in JSON format
+ */
+JNIEXPORT jstring JNICALL JNIThingsManagerGetListOfSupportedConfigurationUnits
+(JNIEnv *env, jobject interfaceObject);
+
+/**
+ * API for boostrapping system configuration parameters from a bootstrap server.
+ *
+ * @return OCStackResult - return value of this API.
+ * It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerDoBootstrap
+(JNIEnv *env, jobject interfaceObject);
+
+/**
+ * API to let thing(device) reboot.
+ * The target thing could be a group of multiple things or a single thing.
+ *
+ * @param resource - resource type representing the target group
+ *
+ * @return OCStackResult - return value of this API.
+ * It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerReboot
+(JNIEnv *env, jobject interfaceObject, jobject resource);
+
+/**
+ * API for factory reset on thing(device).
+ * The target thing could be a group of multiple things or a single thing.
+ *
+ * @param resource - resource type representing the target group
+ *
+ * @return OCStackResult - return value of this API.
+ * It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerFactoryReset
+(JNIEnv *env, jobject interfaceObject, jobject resource);
+
+/**
+ * API for adding an Action Set.
+ *
+ * @param resource - resource type representing the target group
+ * @param newActionSet - list of Action Set to be added
+ *
+ * @return OCStackResult - return value of this API.
+ * It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+
+JNIEXPORT jint JNICALL JNIThingsManagerAddActionSet
+(JNIEnv *env, jobject interfaceObject, jobject resource, jobject newActionSet);
+
+/**
+ * API for executing the Action Set.
+ *
+ * @param resource - resource type representing the target group
+ * @param actionSetName - Action Set name for executing the Action set
+ *
+ * @return OCStackResult - return value of this API.
+ * It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerExecuteActionSet
+(JNIEnv *env, jobject interfaceObject, jobject resource, jstring actionSetName);
+
+/**
+ * API for executing the Action Set.
+ *
+ * @param resource - resource type representing the target group
+ * @param actionSetName - Action Set name for executing the Action set
+ * @param delay - waiting time for until action set run.
+ *
+ * @return OCStackResult - return value of this API.
+ * It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerExecuteActionSetWithDelay
+(JNIEnv *env, jobject interfaceObject, jobject resource, jstring actionSetName, jlong delay);
+
+/**
+ * API for cancelling the Action Set.
+ *
+ * @param resource - resource type representing the target group
+ * @param actionSetName - Action Set name for cancelling the Action set
+ *
+ * @return OCStackResult - return value of this API.
+ * It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerCancelActionSet
+(JNIEnv *env, jobject interfaceObject, jobject resource, jstring actionSetName);
+
+
+/**
+ * API for reading the Action Set.
+ *
+ * @param resource - resource type representing the target group
+ * @param actionSetName - Action Set name for reading the Action set
+ *
+ * @return OCStackResult - return value of this API.
+ * It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerGetActionSet
+(JNIEnv *env, jobject interfaceObject, jobject resource, jstring actionSetName);
+
+/**
+ * API for removing the Action Set.
+ *
+ * @param resource - resource type representing the target group
+ * @param actionSetName - Action Set name for removing the Action set
+ *
+ * @return OCStackResult - return value of this API.
+ * It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerDeleteActionSet
+(JNIEnv *env, jobject interfaceObject, jobject resource, jstring actionSetName);
+
+#ifdef __cplusplus
+}
+#endif
+#endif //__JNI_THINGS_MANAGER_H_
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+/** @file jni_things_manager_callbacks.h
+ *
+ * @brief This file contains the declaration of ThingsManagerCallbacks class
+ * and its members related to ThingsManagerCallbacks.
+ */
+
+#ifndef __JNI_THINGS_MANAGER_CALLBACKS_H_
+#define __JNI_THINGS_MANAGER_CALLBACKS_H_
+
+#include <string>
+
+#include "ThingsManager.h"
+
+/**
+ * @class ThingsManagerCallbacks
+ * @brief This class provides a set of callback functions for group management,
+ * synchronization of group, configuration of things, and diagnostics about things.
+ *
+ */
+class ThingsManagerCallbacks
+{
+
+ public:
+ ThingsManagerCallbacks() {}
+ virtual ~ThingsManagerCallbacks() {}
+
+ /**
+ * This callback method is called when resources are discovered in network.
+ *
+ * @param resourceVector - List of resources discovered in the network
+ *
+ * @return void
+ */
+ static void onFoundCandidateResource(std::vector< std::shared_ptr<OC::OCResource > >
+ resourceVector);
+
+ /**
+ * This callback method is called to notify whether group is found or not.
+ *
+ * @param resource - Resource URI
+ *
+ * @return void
+ */
+ static void onFoundGroup(std::shared_ptr<OC::OCResource> resource);
+
+ /**
+ * This callback method is called for child resource presence status.
+ *
+ * @param resource - URI of resource.
+ * @param result - error code.
+ *
+ * @return void
+ */
+ static void onSubscribePresence(std::string resource, OCStackResult result);
+
+ /**
+ * This callback method is called when a response for the updateConfigurations request
+ * just arrives.
+ *
+ * @param headerOptions - It comprises of optionID and optionData as members.
+ * @param rep - Configuration parameters are carried as a pair of attribute key and value
+ * in a form of OCRepresentation instance.
+ * @param eCode - error code.
+ *
+ * @return void
+ */
+ static void onUpdateConfigurationsResponse(const OC::HeaderOptions &headerOptions,
+ const OC::OCRepresentation &rep, const int eCode);
+
+ /**
+ * This callback method is called when a response for the getConfigurations request
+ * just arrives.
+ *
+ * @param headerOptions - It comprises of optionID and optionData as members.
+ * @param rep - Configuration parameters are carried as a pair of attribute key and value
+ * in a form of OCRepresentation instance.
+ * @param eCode - error code.
+ *
+ * @return void
+ */
+ static void onGetConfigurationsResponse(const OC::HeaderOptions &headerOptions,
+ const OC::OCRepresentation &rep, const int eCode);
+
+ /**
+ * This callback method is called when a response for the doBootstrap request
+ * just arrives.
+ *
+ * @param headerOptions - It comprises of optionID and optionData as members.
+ * @param rep - Configuration parameters are carried as a pair of attribute key and value
+ * in a form of OCRepresentation instance.
+ * @param eCode - error code.
+ *
+ * @return void
+ */
+ static void onBootStrapResponse(const OC::HeaderOptions &headerOptions,
+ const OC::OCRepresentation &rep,
+ const int eCode);
+
+ /**
+ * This callback method is called when a response for the reboot request
+ * just arrives.
+ *
+ * @param headerOptions - It comprises of optionID and optionData as members.
+ * @param rep - Configuration parameters are carried as a pair of attribute key and value
+ * in a form of OCRepresentation instance.
+ * @param eCode - error code.
+ *
+ * @return void
+ */
+ static void onRebootResponse(const OC::HeaderOptions &headerOptions,
+ const OC::OCRepresentation &rep,
+ const int eCode);
+
+ /**
+ * This callback method is called when a response for the factoryReset request
+ * just arrives.
+ *
+ * @param headerOptions - It comprises of optionID and optionData as members.
+ * @param rep - Configuration parameters are carried as a pair of attribute key and value
+ * in a form of OCRepresentation instance.
+ * @param eCode - error code.
+ *
+ * @return void
+ */
+ static void onFactoryResetResponse(const OC::HeaderOptions &headerOptions,
+ const OC::OCRepresentation &rep,
+ const int eCode);
+
+ /**
+ * This callback method is called when a response for the executeActionSet
+ * or deleteActionSet request just arrives.
+ *
+ * @param headerOptions - It comprises of optionID and optionData as members.
+ * @param rep - Configuration parameters are carried as a pair of attribute key and value
+ * in a form of OCRepresentation instance.
+ * @param eCode - error code.
+ *
+ * @return void
+ */
+ static void onPostResponse(const OC::HeaderOptions &headerOptions,
+ const OC::OCRepresentation &rep, const int eCode);
+
+ /**
+ * This callback method is called when a response for the addActionSet request
+ * just arrives.
+ *
+ * @param headerOptions - It comprises of optionID and optionData as members.
+ * @param rep - Configuration parameters are carried as a pair of attribute key and value
+ * in a form of OCRepresentation instance.
+ * @param eCode - error code.
+ *
+ * @return void
+ */
+ static void onPutResponse(const OC::HeaderOptions &headerOptions,
+ const OC::OCRepresentation &rep, const int eCode);
+
+ /**
+ * This callback method is called when a response for the getActionSet request
+ * just arrives.
+ *
+ * @param headerOptions - It comprises of optionID and optionData as members.
+ * @param rep - Configuration parameters are carried as a pair of attribute key and value
+ * in a form of OCRepresentation instance.
+ * @param eCode - error code.
+ *
+ * @return void
+ */
+ static void onGetResponse(const OC::HeaderOptions &headerOptions,
+ const OC::OCRepresentation &rep, const int eCode);
+
+ /**
+ * This method invokes the Callback function with particular name and signature.
+ *
+ * @param headerOptions - It comprises of optionID and optionData as members.
+ * @param rep - Configuration parameters are carried as a pair of attribute key and value
+ * in a form of OCRepresentation instance.
+ * @param eCode - error code.
+ * @param callbackName - callbackName to be invoked.
+ * @param signature - Signature of the callback method to be called.
+ *
+ * @return void
+ */
+ static void invokeCallback(const OC::HeaderOptions &headerOptions,
+ const OC::OCRepresentation &rep, const int eCode,
+ const char *callbackName, const char *signature);
+
+};
+#endif //__JNI_THINGS_MANAGER_CALLBACKS_H_
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file jni_things_manager_util.h
+ *
+ * @brief This file contains the utility functions for conversions from java to CPP
+ * and viceversa
+ */
+
+#ifndef __JNI_THINGS_MANAGER_UTILS_H_
+#define __JNI_THINGS_MANAGER_UTILS_H_
+
+
+#include <vector>
+#include <map>
+#include "jni_things_manager_jvm.h"
+
+/**
+ * Utility function for converting a Java Vector of Strings to CPP Vector of Strings
+ *
+ * @param env - Default JNI Environment pointer
+ * @param jVectorString - Java Vector of Strings
+ *
+ * @return void
+ */
+std::vector<std::string> convertStringVector(JNIEnv *env, jobject jVectorString);
+
+/**
+ * Utility function for converting a Hash Map of Strings to CPP Map of Strings
+ *
+ * @param env - Default JNI Environment pointer
+ * @param jMapString - Java Map of Strings
+ *
+ * @return void
+ */
+std::map<std::string, std::string> convertStringMap(JNIEnv *env, jobject jMapString);
+#endif //__JNI_THINGS_MANAGER_UTILS_H_
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+#include "jni_action.h"
+
+#include <ActionSet.h>
+#include "jni_things_manager_jvm.h"
+#include "jni_getter.h"
+#include "jni_setter.h"
+
+#define JACTION_TARGET ("target")
+#define JACTION_LISTOF_CAPABILITY ("listOfCapability")
+
+
+JniAction::JniAction(JNIEnv *env, jobject obj) : JObject(env, obj)
+{
+}
+
+JniAction::JniAction(JNIEnv *env) : JObject(env, TM_SERVICE_ACTION_PATH)
+{
+}
+
+JniAction::~JniAction()
+{
+}
+
+bool JniAction::getTarget(std::string &target)
+{
+ //Retrieves target value from JniAction class object
+ return JGetter::getJStringField(m_pEnv, m_pObject, JACTION_TARGET, target);
+}
+
+bool JniAction::setTarget(const std::string target)
+{
+ //Sets target value of JniAction class object
+ return JSetter::setJStringField(m_pEnv, m_pObject, JACTION_TARGET, target.c_str());
+}
+
+bool JniAction::getJniCapabilityValues(std::vector<OIC::Capability *> &capabilityList)
+{
+ jclass jvectorClass = m_pEnv->FindClass(TM_JAVA_VECTOR_CLASS_PATH);
+ jmethodID vectorMethodID = m_pEnv->GetMethodID(jvectorClass, "get", "(I)Ljava/lang/Object;");
+ jmethodID vectorSizeMethodID = m_pEnv->GetMethodID(jvectorClass, "size", "()I");
+
+ jobject jAttrList = NULL;
+ bool res = JGetter::getJObjectField(m_pEnv, m_pObject,
+ JACTION_LISTOF_CAPABILITY, TM_JAVA_VECTOR_TYPE, jAttrList);
+
+ if (res == true)
+ {
+ capabilityList.clear();
+ int attrCount = m_pEnv->CallIntMethod(jAttrList, vectorSizeMethodID);
+ for (int i = 0; i < attrCount; i++)
+ {
+ JniCapability *attr_var = new JniCapability(m_pEnv,
+ m_pEnv->CallObjectMethod(jAttrList, vectorMethodID, i));
+
+ OIC::Capability *cap = new OIC::Capability();
+ attr_var->getJniCapabilityValue(cap->capability);
+ attr_var->getJniCapabilityStatus(cap->status);
+ delete attr_var;
+ capabilityList.push_back(cap);
+ }
+ }
+ m_pEnv->DeleteLocalRef(jvectorClass);
+ return res;
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+#include "jni_action_set.h"
+
+#include "jni_things_manager_jvm.h"
+#include "jni_getter.h"
+#include "jni_setter.h"
+#include "JniOcResource.h"
+
+#define JACTIONSET_NAME ("actionsetName")
+#define JACTIONSET_LISTOF_ACTION ("listOfAction")
+
+JniActionSet::JniActionSet(JNIEnv *env, jobject obj) : JObject(env, obj)
+{
+}
+
+JniActionSet::JniActionSet(JNIEnv *env) : JObject(env, TM_SERVICE_ACTIONSET_PATH)
+{
+}
+
+JniActionSet::~JniActionSet()
+{
+}
+
+bool JniActionSet::getJniActionSetName(std::string &name)
+{
+ //Retrieves target value from JniActionSet class object
+ return JGetter::getJStringField(m_pEnv, m_pObject, JACTIONSET_NAME, name);
+}
+
+bool JniActionSet::setJniActionSetName(const std::string name)
+{
+ //Sets target value of JniActionSet class object
+ return JSetter::setJStringField(m_pEnv, m_pObject, JACTIONSET_NAME, name.c_str());
+}
+
+bool JniActionSet::getJniListOfActions(std::vector<OIC::Action *> &actionList)
+{
+ jclass jvectorClass = m_pEnv->FindClass(TM_JAVA_VECTOR_CLASS_PATH);
+ jmethodID vectorMethodID = m_pEnv->GetMethodID(jvectorClass, "get", "(I)Ljava/lang/Object;");
+ jmethodID vectorSizeMethodID = m_pEnv->GetMethodID(jvectorClass, "size", "()I");
+ jobject jAttrList = NULL;
+ bool res = JGetter::getJObjectField(m_pEnv, m_pObject,
+ JACTIONSET_LISTOF_ACTION, TM_JAVA_VECTOR_TYPE, jAttrList);
+
+ if (res == true)
+ {
+ actionList.clear();
+ int attrCount = m_pEnv->CallIntMethod(jAttrList, vectorSizeMethodID);
+ for (int i = 0; i < attrCount; i++)
+ {
+ JniAction *attr_var = new JniAction(m_pEnv,
+ m_pEnv->CallObjectMethod(jAttrList, vectorMethodID, i));
+ OIC::Action *actionName = new OIC::Action();
+ attr_var->getTarget(actionName->target);
+ attr_var->getJniCapabilityValues(actionName->listOfCapability);
+ delete attr_var;
+ actionList.push_back(actionName);
+ }
+ }
+ m_pEnv->DeleteLocalRef(jvectorClass);
+ return true;
+}
+ActionSet *JniActionSet::getActionSet(JNIEnv *env, jobject jnewActionSet)
+{
+ LOGI("getActionSet: Enter");
+
+ if (NULL == jnewActionSet)
+ {
+ LOGE("getActionSet: jnewActionSet is NULL");
+ return NULL;
+ }
+
+ std::string actionsetName;
+ getJniActionSetName(actionsetName);
+
+ std::vector<Action *> actionVector;
+ getJniListOfActions(actionVector);
+
+ OIC::ActionSet *pActionSet = new OIC::ActionSet();
+ if (NULL == pActionSet)
+ {
+ LOGE("getActionSet: Failed to create newActionSet");
+ return NULL;
+ }
+
+ pActionSet->actionsetName = actionsetName;
+ pActionSet->listOfAction = actionVector;
+ if (false == setTimeInfo(env, jnewActionSet, pActionSet))
+ {
+ LOGE("getActionSet: setTimeInfo failed!");
+ delete pActionSet;
+ return NULL;
+ }
+
+ LOGI("getActionSet: Exit");
+ return pActionSet;
+}
+
+bool JniActionSet::setTimeInfo(JNIEnv *env, jobject jnewActionSet, OIC::ActionSet *pActionSet)
+{
+ LOGI("setTimeInfo: Entry");
+ if (NULL == jnewActionSet)
+ {
+ LOGE("setTimeInfo: jnewActionSet is NULL");
+ return NULL;
+ }
+
+ jclass classTime = env->FindClass(TM_SERVICE_TIME_PATH);
+ if (NULL == classTime)
+ {
+ LOGE("FindClass failed for [%s]", TM_SERVICE_TIME_PATH);
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID(classTime, "mYear", "I");
+ int year = env->GetIntField(jnewActionSet, fieldID);
+
+ fieldID = env->GetFieldID(classTime, "mMonth", "I");
+ int month = env->GetIntField(jnewActionSet, fieldID);
+
+ fieldID = env->GetFieldID(classTime, "mDay", "I");
+ int day = env->GetIntField(jnewActionSet, fieldID);
+
+ fieldID = env->GetFieldID(classTime, "mHour", "I");
+ int hour = env->GetIntField(jnewActionSet, fieldID);
+
+ fieldID = env->GetFieldID(classTime, "mMin", "I");
+ int min = env->GetIntField(jnewActionSet, fieldID);
+
+ fieldID = env->GetFieldID(classTime, "mSec", "I");
+ int sec = env->GetIntField(jnewActionSet, fieldID);
+
+ fieldID = env->GetFieldID(classTime, "mDayOfWeek", "I");
+ int wday = env->GetIntField(jnewActionSet, fieldID);
+
+ fieldID = env->GetFieldID(classTime, "mDelay", "J");
+ long delay = env->GetLongField(jnewActionSet, fieldID);
+
+ fieldID = env->GetFieldID(classTime, "mType", "Lorg/iotivity/service/tm/Time$ActionSetType;");
+ jobject actionSetTypeObj = env->GetObjectField(jnewActionSet, fieldID);
+ if (NULL == actionSetTypeObj)
+ {
+ LOGE("setTimeInfo: actionSetTypeObj is NULL");
+ return false;
+ }
+
+ jclass actionSetTypeClass = env->GetObjectClass(actionSetTypeObj);
+ if (NULL == actionSetTypeClass)
+ {
+ LOGE("setTimeInfo: actionSetTypeClass is NULL");
+ return false;
+ }
+
+ jmethodID actionSetTypeMethod = env->GetMethodID(actionSetTypeClass, "ordinal", "()I");
+ if (NULL == actionSetTypeMethod)
+ {
+ LOGE("setTimeInfo: actionSetTypeMethod is NULL");
+ return false;
+ }
+
+ int type = (int) env->CallIntMethod(actionSetTypeObj, actionSetTypeMethod);
+ pActionSet->setTime(year, month, day, hour, min, sec, wday);
+ pActionSet->type = static_cast<OIC::ACTIONSET_TYPE>(type);
+ pActionSet->setDelay(delay);
+
+ LOGI("setTimeInfo: Exit");
+ return true;
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+#include "jni_capability.h"
+
+#include "jni_things_manager_jvm.h"
+#include "jni_getter.h"
+#include "jni_setter.h"
+
+#define JCAPABILITY_STATUS ("status")
+#define JCAPABILITY_CAPABILITY ("capability")
+
+JniCapability::JniCapability(JNIEnv *env, jobject obj) : JObject(env, obj)
+{
+}
+
+JniCapability::JniCapability(JNIEnv *env) : JObject(env, TM_SERVICE_CAPABILITY_PATH)
+{
+}
+
+JniCapability::~JniCapability()
+{
+}
+
+bool JniCapability::getJniCapabilityValue(std::string &capability)
+{
+ //Retrieves capability value from JniCapability class object
+ return JGetter::getJStringField(m_pEnv, m_pObject, JCAPABILITY_CAPABILITY, capability);
+}
+
+bool JniCapability::setJniCapabilityValue(const std::string capability)
+{
+ //Sets capability value of JniCapability class object
+ return JSetter::setJStringField(m_pEnv, m_pObject, JCAPABILITY_CAPABILITY, capability.c_str());
+}
+
+bool JniCapability::getJniCapabilityStatus(std::string &status)
+{
+ //Retrieves status from JniCapability class object
+ return JGetter::getJStringField(m_pEnv, m_pObject, JCAPABILITY_STATUS, status);
+}
+
+bool JniCapability::setJniCapabilityStatus(const std::string status)
+{
+ //Sets status of JniCapability class object
+ return JSetter::setJStringField(m_pEnv, m_pObject, JCAPABILITY_STATUS, status.c_str());
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+#include "jni_things_manager.h"
+
+#include "JniOcResource.h"
+#include "JniOcResourceHandle.h"
+#include "ThingsManager.h"
+#include "ActionSet.h"
+#include "jni_things_manager_jvm.h"
+#include "jni_things_manager_util.h"
+#include "jni_things_manager_callbacks.h"
+#include "jni_action_set.h"
+
+using namespace OC;
+using namespace OIC;
+
+/**
+ * @var g_ThingsManager
+ * @brief ThingsManager static object
+ */
+static ThingsManager g_ThingsManager;
+
+jobject ocResourceHandleToJava(JNIEnv *env, jlong resourceHandle);
+
+JNIEXPORT jint JNICALL JNIThingsManagerFindCandidateResource(JNIEnv *env, jobject interfaceObject,
+ jobject jResourceTypes, jint waitSec)
+{
+ LOGI("JNIThingsManagerFindCandidateResource: Enter");
+
+ if (!jResourceTypes)
+ {
+ LOGE("JNIThingsManagerFindCandidateResource: jResourceTypes is NULL!");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult ocResult = OC_STACK_ERROR;
+ try
+ {
+ ocResult = g_ThingsManager.findCandidateResources(convertStringVector(env, jResourceTypes),
+ &ThingsManagerCallbacks::onFoundCandidateResource, (int)waitSec);
+
+ if (OC_STACK_OK != ocResult)
+ {
+ LOGE("JNIThingsManagerFindCandidateResource: findCandidateResources failed!");
+ return ocResult;
+ }
+ }
+ catch (InitializeException &e)
+ {
+ LOGE("JNIThingsManagerFindCandidateResource: Exception occurred! %s, %d", e.reason().c_str(),
+ e.code());
+ return ocResult;
+ }
+
+ LOGI("JNIThingsManagerFindCandidateResource: Exit");
+ return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerSubscribeCollectionPresence(JNIEnv *env,
+ jobject interfaceObject,
+ jobject jResource)
+{
+ LOGI("JNIThingsManagerSubscribeCollectionPresence: Enter");
+
+ if (!jResource)
+ {
+ LOGE("JNIThingsManagerSubscribeCollectionPresence: jResource is NULL!");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult ocResult = OC_STACK_ERROR;
+
+ JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, jResource);
+ if (NULL == jniOcResource)
+ {
+ LOGE("JNIThingsManagerSubscribeCollectionPresence: Failed to get jni OcResource!");
+ return ocResult;
+ }
+
+ std::shared_ptr<OCResource> ocResource = jniOcResource->getOCResource();
+ if (NULL == ocResource.get())
+ {
+ LOGE("JNIThingsManagerSubscribeCollectionPresence: Failed to get OCResource object!");
+ return ocResult;
+ }
+
+ ocResult = g_ThingsManager.subscribeCollectionPresence(ocResource,
+ &ThingsManagerCallbacks::onSubscribePresence);
+ if (OC_STACK_OK != ocResult)
+ {
+ LOGE("JNIThingsManagerSubscribeCollectionPresence: subscribeCollectionPresence failed!");
+ return ocResult;
+ }
+
+ LOGI("JNIThingsManagerSubscribeCollectionPresence: Exit");
+ return ocResult;
+}
+
+JNIEXPORT jobject JNICALL JNIThingsManagerBindResourceToGroup(JNIEnv *env, jobject interfaceObject,
+ jobject jResource, jobject jCollectionHandle)
+{
+ LOGI("JNIThingsManagerBindResourceToGroup: Enter");
+
+ if (!jResource || !jCollectionHandle)
+ {
+ LOGE("JNIThingsManagerBindResourceToGroup: Invalid parameter!");
+ return NULL;
+ }
+
+ std::shared_ptr<OCResource> ocResource;
+ JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, jResource);
+ if (jniOcResource)
+ {
+ ocResource = jniOcResource->getOCResource();
+ }
+
+ if (NULL == ocResource.get())
+ {
+ LOGE("JNIThingsManagerBindResourceToGroup: Failed to get OCResource object!");
+ return NULL;
+ }
+
+ JniOcResourceHandle *jniOcCollectionHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(env,
+ jCollectionHandle);
+ if (NULL == jniOcCollectionHandle)
+ {
+ LOGE("JNIThingsManagerBindResourceToGroup: collection handle is null!");
+ return NULL;
+ }
+
+ jobject jResourceHandle = NULL;
+ try
+ {
+ OCResourceHandle ocChildHandle = NULL;
+ OCResourceHandle ocCollectionHandle = jniOcCollectionHandle->getOCResourceHandle();
+ OCStackResult ocResult = g_ThingsManager.bindResourceToGroup(ocChildHandle, ocResource, ocCollectionHandle);
+ if (OC_STACK_OK != ocResult)
+ {
+ LOGE("JNIThingsManagerBindResourceToGroup: bindResourceToGroup failed!");
+ return NULL;
+ }
+
+ // Convert OCResourceHandle to java type
+ JniOcResourceHandle* jniHandle = new JniOcResourceHandle(ocChildHandle);
+ jlong handle = reinterpret_cast<jlong>(jniHandle);
+ jResourceHandle = env->NewObject(g_cls_OcResourceHandle, g_mid_OcResourceHandle_N_ctor, handle);
+ if (env->ExceptionCheck())
+ {
+ LOGE("JNIThingsManagerBindResourceToGroup: Failed to create OcResourceHandle");
+ delete jniHandle;
+ return NULL;
+ }
+ }
+ catch (InitializeException &e)
+ {
+ LOGE("JNIThingsManagerBindResourceToGroup: Exception occurred! %s, %d", e.reason().c_str(),
+ e.code());
+ return NULL;
+ }
+
+ LOGI("JNIThingsManagerBindResourceToGroup: Exit");
+ return jResourceHandle;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerFindGroup(JNIEnv *env, jobject interfaceObject,
+ jobject jResourceTypes)
+{
+ LOGI("JNIThingsManagerFindGroup: Enter");
+
+ if (!jResourceTypes)
+ {
+ LOGE("JNIThingsManagerFindGroup: jResourceTypes is NULL!");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult ocResult = OC_STACK_ERROR;
+ try
+ {
+ ocResult = g_ThingsManager.findGroup((convertStringVector(env, jResourceTypes)),
+ &ThingsManagerCallbacks::onFoundGroup);
+ if (OC_STACK_OK != ocResult)
+ {
+ LOGE("JNIThingsManagerFindGroup: findGroup failed!");
+ return ocResult;
+ }
+ }
+ catch (InitializeException &e)
+ {
+ LOGE("JNIThingsManagerFindGroup: Exception occurred! %s, %d", e.reason().c_str(),
+ e.code());
+ return ocResult;
+ }
+ LOGI("JNIThingsManagerFindGroup: Exit");
+ return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerCreateGroup(JNIEnv *env, jobject interfaceObject,
+ jstring jResourceType)
+{
+ LOGI("JNIThingsManagerCreateGroup: Enter");
+
+ if (!jResourceType)
+ {
+ LOGE("JNIThingsManagerCreateGroup: jResourceType is NULL!");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult ocResult = OC_STACK_ERROR;
+
+ const char *resourceTypePointer = env->GetStringUTFChars(jResourceType, NULL);
+ if (NULL == resourceTypePointer)
+ {
+ LOGE("JNIThingsManagerCreateGroup: Failed to convert jstring to char string!");
+ return OC_STACK_NO_MEMORY;
+ }
+
+ std::string resourceType(resourceTypePointer);
+ try
+ {
+ ocResult = g_ThingsManager.createGroup(resourceType);
+ if (OC_STACK_OK != ocResult)
+ {
+ LOGE("JNIThingsManagerCreateGroup: CreateGroup failed!");
+ }
+ }
+ catch (InitializeException &e)
+ {
+ LOGE("JNIThingsManagerCreateGroup: Exception occurred! %s, %d", e.reason().c_str(),
+ e.code());
+ }
+ env->ReleaseStringUTFChars(jResourceType, resourceTypePointer);
+ LOGI("JNIThingsManagerCreateGroup: Exit");
+ return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerJoinGroupString(JNIEnv *env, jobject interfaceObject,
+ jstring jResourceType, jobject jResourceHandle)
+{
+ LOGI("JNIThingsManagerJoinGroupString: Enter");
+
+ if ((!jResourceType) || (!jResourceHandle))
+ {
+ LOGE("JNIThingsManagerJoinGroupString: jResourceType or jResourceHandle is NULL!");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult ocResult = OC_STACK_ERROR;
+
+ const char *resourceTypePointer = env->GetStringUTFChars(jResourceType, NULL);
+ if (NULL == resourceTypePointer)
+ {
+ LOGE("JNIThingsManagerJoinGroupString: Failed to convert jstring to char string!");
+ return OC_STACK_NO_MEMORY;
+ }
+
+ std::string resourceType(resourceTypePointer);
+
+ JniOcResourceHandle *jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(env,
+ jResourceHandle);
+ try
+ {
+ OCResourceHandle ocResourceHandle = jniOcResourceHandle->getOCResourceHandle();
+ ocResult = g_ThingsManager.joinGroup(resourceType, ocResourceHandle);
+ if (OC_STACK_OK != ocResult)
+ {
+ LOGE("JNIThingsManagerJoinGroupString: joinGroup failed!");
+ }
+ }
+ catch (InitializeException &e)
+ {
+ LOGE("JNIThingsManagerJoinGroupString: Exception occurred! %s, %d", e.reason().c_str(),
+ e.code());
+ }
+ env->ReleaseStringUTFChars(jResourceType, resourceTypePointer);
+ LOGI("JNIThingsManagerJoinGroupString: Exit");
+ return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerJoinGroupObject(JNIEnv *env, jobject interfaceObject,
+ jobject jResource, jobject jResourceHandle)
+{
+ LOGI("JNIThingsManagerJoinGroupObject: Enter");
+
+ if ((!jResource) || (!jResourceHandle))
+ {
+ LOGE("JNIThingsManagerJoinGroupObject: jResource or jResourceHandle is NULL!");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult ocResult = OC_STACK_ERROR;
+
+ std::shared_ptr<OCResource> ocResource;
+ JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, jResource);
+ if (jniOcResource)
+ {
+ ocResource = jniOcResource->getOCResource();
+ }
+
+ if (NULL == ocResource.get())
+ {
+ LOGE("JNIThingsManagerJoinGroupObject: Failed to get OCResource object!");
+ return ocResult;
+ }
+
+ JniOcResourceHandle *jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(env,
+ jResourceHandle);
+
+ try
+ {
+ OCResourceHandle resHandle = jniOcResourceHandle->getOCResourceHandle();
+
+ ocResult = g_ThingsManager.joinGroup(ocResource, resHandle);
+ if (OC_STACK_OK != ocResult)
+ {
+ LOGE("JNIThingsManagerJoinGroupObject: joinGroup failed!");
+ return ocResult;
+ }
+ }
+ catch (InitializeException &e)
+ {
+ LOGE("JNIThingsManagerJoinGroupObject: Exception occurred! %s, %d", e.reason().c_str(),
+ e.code());
+ return ocResult;
+ }
+ LOGI("JNIThingsManagerJoinGroupObject: Exit");
+ return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerLeaveGroup(JNIEnv *env, jobject interfaceObject,
+ jstring jResourceType,
+ jobject jResourceHandle)
+{
+ LOGI("JNIThingsManagerLeaveGroup: Enter");
+
+ if ((!jResourceType) || (!jResourceHandle))
+ {
+ LOGE("JNIThingsManagerLeaveGroup: jResourceType or jResourceHandle is NULL!");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult ocResult = OC_STACK_ERROR;
+
+ const char *resourceTypePointer = env->GetStringUTFChars(jResourceType, NULL);
+ if (NULL == resourceTypePointer)
+ {
+ LOGE("JNIThingsManagerLeaveGroup: Failed to convert jstring to char string!");
+ return OC_STACK_NO_MEMORY;
+ }
+
+ std::string resourceType(resourceTypePointer);
+ JniOcResourceHandle *jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(env,
+ jResourceHandle);
+
+ try
+ {
+ OCResourceHandle ocResourceHandle = jniOcResourceHandle->getOCResourceHandle();
+
+ ocResult = g_ThingsManager.leaveGroup(resourceType, ocResourceHandle);
+ if (OC_STACK_OK != ocResult)
+ {
+ LOGE("JNIThingsManagerLeaveGroup: leaveGroup failed!");
+ }
+ }
+ catch (InitializeException &e)
+ {
+ LOGE("JNIThingsManagerLeaveGroup: Exception occurred! %s, %d", e.reason().c_str(),
+ e.code());
+ }
+ env->ReleaseStringUTFChars(jResourceType, resourceTypePointer);
+ LOGI("JNIThingsManagerLeaveGroup: Exit");
+ return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerLeaveGroupForResource(JNIEnv *env, jobject interfaceObject,
+ jobject jResource,
+ jstring jResourceType,
+ jobject jResourceHandle)
+{
+ LOGI("JNIThingsManagerLeaveGroupForResource: Enter");
+
+ if ((!jResource) || (!jResourceType) || (!jResourceHandle))
+ {
+ LOGE("JNIThingsManagerLeaveGroupForResource: jResourceType or jResourceHandle is NULL!");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult ocResult = OC_STACK_ERROR;
+
+ JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, jResource);
+ if (NULL == jniOcResource)
+ {
+ LOGE("JNIThingsManagerLeaveGroupForResource: Failed to get jni OcResource!");
+ return ocResult;
+ }
+
+ std::shared_ptr<OCResource> ocResource = jniOcResource->getOCResource();
+ if (NULL == ocResource.get())
+ {
+ LOGE("JNIThingsManagerLeaveGroupForResource: Failed to get OCResource object!");
+ return ocResult;
+ }
+
+ const char *resourceTypePointer = env->GetStringUTFChars(jResourceType, NULL);
+ if (NULL == resourceTypePointer)
+ {
+ LOGE("JNIThingsManagerLeaveGroupForResource: Failed to convert jstring to char string!");
+ return OC_STACK_NO_MEMORY;
+ }
+
+ std::string resourceType(resourceTypePointer);
+ JniOcResourceHandle *jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(env,
+ jResourceHandle);
+
+ try
+ {
+ OCResourceHandle ocResourceHandle = jniOcResourceHandle->getOCResourceHandle();
+
+ ocResult = g_ThingsManager.leaveGroup(ocResource, resourceType, ocResourceHandle);
+ if (OC_STACK_OK != ocResult)
+ {
+ LOGE("JNIThingsManagerLeaveGroupForResource: leaveGroup failed!");
+ }
+ }
+ catch (InitializeException &e)
+ {
+ LOGE("JNIThingsManagerLeaveGroupForResource: Exception occurred! %s, %d", e.reason().c_str(),
+ e.code());
+ }
+
+ env->ReleaseStringUTFChars(jResourceType, resourceTypePointer);
+ LOGI("JNIThingsManagerLeaveGroupForResource: Exit");
+ return ocResult;
+}
+
+JNIEXPORT void JNICALL JNIThingsManagerDeleteGroup(JNIEnv *env, jobject interfaceObject,
+ jstring jcollectionResourceType)
+{
+ LOGI("JNIThingsManagerDeleteGroup: Enter");
+
+ if (!jcollectionResourceType)
+ {
+ LOGE("JNIThingsManagerDeleteGroup: jcollectionResourceType is NULL!");
+ return;
+ }
+
+ const char *collectionResourceTypePointer = env->GetStringUTFChars(jcollectionResourceType, NULL);
+ if (NULL == collectionResourceTypePointer)
+ {
+ LOGE("JNIThingsManagerDeleteGroup: Failed to convert jstring to char string!");
+ return;
+ }
+
+ std::string collectionResourceType(collectionResourceTypePointer);
+ try
+ {
+ g_ThingsManager.deleteGroup(collectionResourceType);
+ }
+ catch (InitializeException &e)
+ {
+ LOGE("JNIThingsManagerDeleteGroup: Exception occurred! %s, %d", e.reason().c_str(),
+ e.code());
+ }
+
+ env->ReleaseStringUTFChars(jcollectionResourceType, collectionResourceTypePointer);
+ LOGI("JNIThingsManagerDeleteGroup: Exit");
+}
+
+JNIEXPORT jobject JNICALL JNIThingsManagerGetGroupList(JNIEnv *env, jobject interfaceObject)
+{
+ LOGI("JNIThingsManagerGetGroupList: Enter");
+
+ std::map< std::string, OCResourceHandle> groupListMap;
+ jobject jGroupListMap;
+
+ groupListMap = g_ThingsManager.getGroupList();
+ if (groupListMap.empty())
+ {
+ LOGD("getGroupList Map is empty");
+ return NULL;
+ }
+
+ jclass clazz = env->FindClass("java/util/HashMap");
+ jmethodID init = env->GetMethodID(clazz, "<init>", "()V");
+ jGroupListMap = env->NewObject(clazz, init);
+ jmethodID putMethod = env->GetMethodID(clazz, "put",
+ "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
+
+ for (auto it = groupListMap.begin(); it != groupListMap.end(); ++it)
+ {
+ jstring key = (*env).NewStringUTF( (*it).first.c_str() );
+ JniOcResourceHandle *jniOcResourceHandle = new JniOcResourceHandle(((*it).second));
+ jobject value = ocResourceHandleToJava(env, reinterpret_cast<jlong>(jniOcResourceHandle));
+ env->CallObjectMethod(jGroupListMap, putMethod, key, value);
+ }
+
+ LOGI("JNIThingsManagerGetGroupList: Exit");
+ return jGroupListMap;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerUpdateConfigurations(JNIEnv *env, jobject interfaceObject,
+ jobject resource, jobject configurations)
+{
+ LOGI("JNIThingsManagerUpdateConfigurations: Enter");
+
+ if ((!resource) || (!configurations))
+ {
+ LOGE("JNIThingsManagerUpdateConfigurations: resource or configurations is NULL!");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult ocResult = OC_STACK_ERROR;
+
+ std::shared_ptr<OCResource> ocResource;
+ JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, resource);
+ if (jniOcResource)
+ {
+ ocResource = jniOcResource->getOCResource();
+ }
+
+ if (NULL == ocResource.get())
+ {
+ LOGE("JNIThingsManagerUpdateConfigurations: Failed to get OCResource object!");
+ return ocResult;
+ }
+
+ std::map<std::string, std::string> configurationsMap;
+ configurationsMap = convertStringMap(env, configurations);
+ ocResult = g_ThingsManager.updateConfigurations(ocResource, configurationsMap,
+ &ThingsManagerCallbacks::onUpdateConfigurationsResponse);
+ if (OC_STACK_OK != ocResult)
+ {
+ LOGE("JNIThingsManagerUpdateConfigurations: updateConfigurations failed!");
+ return ocResult;
+ }
+
+ LOGI("JNIThingsManagerUpdateConfigurations: Exit");
+ return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerGetConfigurations(JNIEnv *env, jobject interfaceObject,
+ jobject resource, jobject configurations)
+{
+ LOGI("JNIThingsManagerGetConfigurations: Enter");
+
+ if ((!resource) || (!configurations))
+ {
+ LOGE("JNIThingsManagerGetConfigurations: resource or configurations is NULL!");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult ocResult = OC_STACK_ERROR;
+
+ std::shared_ptr<OCResource> ocResource;
+ JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, resource);
+ if (jniOcResource)
+ {
+ ocResource = jniOcResource->getOCResource();
+ }
+
+ if (NULL == ocResource.get())
+ {
+ LOGE("JNIThingsManagerGetConfigurations: Failed to get OCResource object!");
+ return ocResult;
+ }
+
+ ocResult = g_ThingsManager.getConfigurations(ocResource,
+ (convertStringVector(env, configurations)),
+ &ThingsManagerCallbacks::onGetConfigurationsResponse);
+ if (OC_STACK_OK != ocResult)
+ {
+ LOGE("JNIThingsManagerGetConfigurations: getConfigurations failed!");
+ return ocResult;
+ }
+
+ LOGI("JNIThingsManagerGetConfigurations: Exit");
+ return ocResult;
+}
+
+JNIEXPORT jstring JNICALL JNIThingsManagerGetListOfSupportedConfigurationUnits(JNIEnv *env,
+ jobject interfaceObject)
+{
+ LOGI("JNIThingsManagerGetListOfSupportedConfigurationUnits: Enter");
+
+ std::string configListString = g_ThingsManager.getListOfSupportedConfigurationUnits();
+ jstring jConfigListString = env->NewStringUTF(configListString.c_str());
+
+ LOGI("JNIThingsManagerGetListOfSupportedConfigurationUnits: Exit");
+ return jConfigListString;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerDoBootstrap(JNIEnv *env, jobject interfaceObject)
+{
+ LOGI("JNIThingsManagerDoBootstrap: Enter");
+
+ OCStackResult ocResult = OC_STACK_ERROR;
+ try
+ {
+ ocResult = g_ThingsManager.doBootstrap(&ThingsManagerCallbacks::onBootStrapResponse);
+ if (OC_STACK_OK != ocResult)
+ {
+ LOGE("JNIThingsManagerDoBootstrap: doBootstrap failed!");
+ return ocResult;
+ }
+ }
+ catch (InitializeException &e)
+ {
+ LOGE("JNIThingsManagerDoBootstrap: Exception occurred! %s, %d", e.reason().c_str(),
+ e.code());
+ return ocResult;
+ }
+
+ LOGI("JNIThingsManagerDoBootstrap: Exit");
+ return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerReboot(JNIEnv *env, jobject interfaceObject,
+ jobject resource)
+{
+ LOGI("JNIThingsManagerReboot: Enter");
+
+ if (!resource)
+ {
+ LOGE("JNIThingsManagerReboot: resource is NULL!");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult ocResult = OC_STACK_ERROR;
+
+ std::shared_ptr<OCResource> ocResource;
+ JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, resource);
+ if (jniOcResource)
+ {
+ ocResource = jniOcResource->getOCResource();
+ }
+
+ if (NULL == ocResource.get())
+ {
+ LOGE("JNIThingsManagerReboot: Failed to get OCResource object!");
+ return ocResult;
+ }
+
+ ocResult = g_ThingsManager.reboot(ocResource, &ThingsManagerCallbacks::onRebootResponse);
+ if (OC_STACK_OK != ocResult)
+ {
+ LOGE("JNIThingsManagerReboot: reboot failed!");
+ return ocResult;
+ }
+
+ LOGI("JNIThingsManagerReboot: Exit");
+ return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerFactoryReset(JNIEnv *env, jobject interfaceObject,
+ jobject resource)
+{
+ LOGI("JNIThingsManagerFactoryReset: Enter");
+
+ if (!resource)
+ {
+ LOGE("JNIThingsManagerFactoryReset: resource is NULL!");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult ocResult = OC_STACK_ERROR;
+
+ std::shared_ptr<OCResource> ocResource;
+ JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, resource);
+ if (jniOcResource)
+ {
+ ocResource = jniOcResource->getOCResource();
+ }
+
+ if (NULL == ocResource.get())
+ {
+ LOGE("JNIThingsManagerFactoryReset: Failed to get OCResource object!");
+ return ocResult;
+ }
+
+ ocResult = g_ThingsManager.factoryReset(ocResource,
+ &ThingsManagerCallbacks::onFactoryResetResponse);
+ if (OC_STACK_OK != ocResult)
+ {
+ LOGE("JNIThingsManagerFactoryReset: factoryReset failed!");
+ return ocResult;
+ }
+
+ LOGI("JNIThingsManagerFactoryReset: Exit");
+ return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerAddActionSet(JNIEnv *env, jobject interfaceObject,
+ jobject resource,
+ jobject newActionSet)
+{
+ LOGI("JNIThingsManagerAddActionSet: Entry");
+
+ if ((!resource) || (!newActionSet))
+ {
+ LOGE("JNIThingsManagerAddActionSet: resource or newActionSet is NULL!");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult ocResult = OC_STACK_ERROR;
+
+ std::shared_ptr<OCResource> ocResource;
+ JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, resource);
+ if (jniOcResource)
+ {
+ ocResource = jniOcResource->getOCResource();
+ }
+
+ if (NULL == ocResource.get())
+ {
+ LOGE("JNIThingsManageraAdActionSet: Failed to get OCResource object!");
+ return ocResult;
+ }
+
+ JniActionSet *jActionSet = new JniActionSet(env, newActionSet);
+ ActionSet *pActionSet = jActionSet->getActionSet(env, newActionSet);
+ if (NULL == pActionSet)
+ {
+ LOGE("JNIThingsManageraAdActionSet: Failed to convert ActionSet!");
+ return ocResult;
+ }
+
+ ocResult = g_ThingsManager.addActionSet(ocResource, pActionSet,
+ &ThingsManagerCallbacks::onPutResponse);
+ if (OC_STACK_OK != ocResult)
+ {
+ LOGE("JNIThingsManagerAddActionSet: addActionSet is failed!");
+ }
+
+ delete pActionSet;
+ LOGI("JNIThingsManagerAddActionSet: Exit");
+ return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerExecuteActionSet(JNIEnv *env, jobject interfaceObject,
+ jobject resource, jstring jActionSetName)
+{
+ LOGI("JNIThingsManagerExecuteActionSet: Entry");
+
+ if ((!resource) || (!jActionSetName))
+ {
+ LOGE("JNIThingsManagerExecuteActionSet: resource or jActionSetName is NULL!");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult ocResult = OC_STACK_ERROR;
+
+ std::shared_ptr<OCResource> ocResource;
+ JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, resource);
+ if (jniOcResource)
+ {
+ ocResource = jniOcResource->getOCResource();
+ }
+
+ if (NULL == ocResource.get())
+ {
+ LOGE("JNIThingsManagerExecuteActionSet: Failed to get OCResource object!");
+ return ocResult;
+ }
+
+ const char *actionSetNamePointer = env->GetStringUTFChars(jActionSetName, 0);
+ if (NULL == actionSetNamePointer)
+ {
+ LOGE("JNIThingsManagerExecuteActionSet: Failed to convert jstring to char string!");
+ return OC_STACK_NO_MEMORY;
+ }
+
+ std::string actionSetName(actionSetNamePointer);
+
+ ocResult = g_ThingsManager.executeActionSet(ocResource, actionSetName,
+ &ThingsManagerCallbacks::onPostResponse);
+ if (OC_STACK_OK != ocResult)
+ {
+ LOGE("JNIThingsManagerExecuteActionSet: executeActionSet is failed!");
+ }
+
+ env->ReleaseStringUTFChars(jActionSetName, actionSetNamePointer);
+ LOGI("JNIThingsManagerExecuteActionSet: Exit");
+ return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerExecuteActionSetWithDelay(JNIEnv *env,
+ jobject interfaceObject,
+ jobject resource, jstring jActionSetName, jlong delay)
+{
+ LOGI("JNIThingsManagerExecuteActionSet: Entry");
+
+ if ((!resource) || (!jActionSetName))
+ {
+ LOGE("JNIThingsManagerExecuteActionSet: resource or jActionSetName is NULL!");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult ocResult = OC_STACK_ERROR;
+
+ std::shared_ptr<OCResource> ocResource;
+ JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, resource);
+ if (jniOcResource)
+ {
+ ocResource = jniOcResource->getOCResource();
+ }
+
+ if (NULL == ocResource.get())
+ {
+ LOGE("JNIThingsManagerExecuteActionSet: Failed to get OCResource object!");
+ return ocResult;
+ }
+
+ const char *actionSetNamePointer = env->GetStringUTFChars(jActionSetName, 0);
+ if (NULL == actionSetNamePointer)
+ {
+ LOGE("JNIThingsManagerExecuteActionSet: Failed to convert jstring to char string!");
+ return OC_STACK_NO_MEMORY;
+ }
+
+ std::string actionSetName(actionSetNamePointer);
+ if (0 == delay)
+ {
+ ocResult = g_ThingsManager.executeActionSet(ocResource, actionSetName,
+ &ThingsManagerCallbacks::onPostResponse);
+ }
+ else
+ {
+ ocResult = g_ThingsManager.executeActionSet(ocResource, actionSetName,
+ (long int)delay,
+ &ThingsManagerCallbacks::onPostResponse);
+ }
+ if (OC_STACK_OK != ocResult)
+ {
+ LOGE("JNIThingsManagerExecuteActionSet: executeActionSet is failed!");
+ }
+
+ env->ReleaseStringUTFChars(jActionSetName, actionSetNamePointer);
+ LOGI("JNIThingsManagerExecuteActionSet: Exit");
+ return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerCancelActionSet(JNIEnv *env, jobject interfaceObject,
+ jobject resource, jstring jActionSetName)
+{
+ LOGI("JNIThingsManagerCancelActionSet: Entry");
+
+ if ((!resource) || (!jActionSetName))
+ {
+ LOGE("JNIThingsManagerCancelActionSet: resource or jActionSetName is NULL!");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult ocResult = OC_STACK_ERROR;
+
+ std::shared_ptr<OCResource> ocResource;
+ JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, resource);
+ if (jniOcResource)
+ {
+ ocResource = jniOcResource->getOCResource();
+ }
+
+ if (NULL == ocResource.get())
+ {
+ LOGE("JNIThingsManagerCancelActionSet: Failed to get OCResource object!");
+ return ocResult;
+ }
+
+ const char *actionSetNamePointer = env->GetStringUTFChars(jActionSetName, 0);
+ if (NULL == actionSetNamePointer)
+ {
+ LOGE("JNIThingsManagerCancelActionSet: Failed to get character sequence from jstring!");
+ return OC_STACK_NO_MEMORY;
+ }
+
+ std::string actionSetName(actionSetNamePointer);
+
+ ocResult = g_ThingsManager.cancelActionSet(ocResource, actionSetName,
+ &ThingsManagerCallbacks::onPostResponse);
+ if (OC_STACK_OK != ocResult)
+ {
+ LOGE("JNIThingsManagerCancelActionSet: cancelActionSet is failed!");
+ }
+
+ env->ReleaseStringUTFChars(jActionSetName, actionSetNamePointer);
+ LOGI("JNIThingsManagerCancelActionSet: Exit");
+ return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerGetActionSet(JNIEnv *env, jobject interfaceObject,
+ jobject resource,
+ jstring jActionSetName)
+{
+ LOGI("JNIThingsManagerGetActionSet: Entry");
+
+ if ((!resource) || (!jActionSetName))
+ {
+ LOGE("JNIThingsManagerGetActionSet: resource or jActionSetName is NULL!");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult ocResult = OC_STACK_ERROR;
+
+ std::shared_ptr<OCResource> ocResource;
+ JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, resource);
+ if (jniOcResource)
+ {
+ ocResource = jniOcResource->getOCResource();
+ }
+
+ if (NULL == ocResource.get())
+ {
+ LOGE("JNIThingsManagerGetActionSet: Failed to get OCResource object!");
+ return ocResult;
+ }
+
+ const char *actionSetNamePointer = env->GetStringUTFChars(jActionSetName, 0);
+ std::string actionSetName(actionSetNamePointer);
+
+ ocResult = g_ThingsManager.getActionSet(ocResource, actionSetName,
+ &ThingsManagerCallbacks::onGetResponse);
+ if (OC_STACK_OK != ocResult)
+ {
+ LOGE("JNIThingsManagerGetActionSet: getActionSet is failed!");
+ }
+
+ env->ReleaseStringUTFChars(jActionSetName, actionSetNamePointer);
+ LOGI("JNIThingsManagerGetActionSet: Exit");
+ return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerDeleteActionSet(JNIEnv *env, jobject interfaceObject,
+ jobject resource,
+ jstring jActionSetName)
+{
+ LOGI("JNIThingsManagerDeleteActionSet: Entry");
+
+ if ((!resource) || (!jActionSetName))
+ {
+ LOGE("JNIThingsManagerDeleteActionSet: resource or jActionSetName is NULL!");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult ocResult = OC_STACK_ERROR;
+
+ std::shared_ptr<OCResource> ocResource;
+ JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, resource);
+ if (jniOcResource)
+ {
+ ocResource = jniOcResource->getOCResource();
+ }
+
+ if (NULL == ocResource.get())
+ {
+ LOGE("JNIThingsManagerDeleteActionSet: Failed to get OCResource object!");
+ return ocResult;
+ }
+
+ const char *actionSetNamePointer = env->GetStringUTFChars(jActionSetName, 0);
+ std::string actionSetName(actionSetNamePointer);
+
+ ocResult = g_ThingsManager.deleteActionSet(ocResource, actionSetName,
+ &ThingsManagerCallbacks::onPutResponse);
+ if (OC_STACK_OK != ocResult)
+ {
+ LOGE("JNIThingsManagerDeleteActionSet: deleteActionSet is failed!");
+ }
+
+ env->ReleaseStringUTFChars(jActionSetName, actionSetNamePointer);
+ LOGI("JNIThingsManagerDeleteActionSet: Exit");
+ return ocResult;
+}
+
+jobject ocResourceHandleToJava(JNIEnv *env, jlong resourceHandle)
+{
+ jclass resourceClass = GetJClass(TM_SERVICE_OCRESOURCEHANDLE_PATH);
+ if (NULL == resourceClass)
+ {
+ LOGE("ocResourceHandleToJava : failed to find OCResourceHandle java class!");
+ return NULL;
+ }
+
+ jmethodID constructor = env->GetMethodID(resourceClass, "<init>", "(J)V");
+ if (NULL == constructor)
+ {
+ LOGE("ocResourceHandleToJava: Failed to get constructor method!");
+ return NULL;
+ }
+
+ jobject resourceObj = (jobject) env->NewObject(resourceClass, constructor, resourceHandle);
+ if (NULL == resourceObj)
+ {
+ LOGE("ocResourceHandleToJava: Failed to create OCResouceHandle java object!");
+ return NULL;
+ }
+
+ return resourceObj;
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+#include "jni_things_manager_callbacks.h"
+#include "JniOcResource.h"
+#include "ThingsManager.h"
+#include "jni_things_manager_jvm.h"
+#include "jni_string.h"
+
+#define LOG_TAG "ThingsManagerCallbacks"
+
+#define METHOD_ONRESOURCE_CALLBACK "(" TM_JAVA_VECTOR_TYPE")V"
+#define METHOD_ONGROUP_FIND_CALLBACK "(" TM_SERVICE_OCRESOURCE_TYPE")V"
+#define METHOD_ONPRESENCE_CALLBACK "(" TM_JAVA_STRING_TYPE"I)V"
+#define METHOD_ONUPDATE_CONF_CALLBACK "(" TM_JAVA_VECTOR_TYPE TM_SERVICE_OCREPRESENTATION_TYPE"I)V"
+#define METHOD_ONGET_CONF_CALLBACK "(" TM_JAVA_VECTOR_TYPE TM_SERVICE_OCREPRESENTATION_TYPE"I)V"
+#define METHOD_ONBOOT_STRAP_CALLBACK "(" TM_JAVA_VECTOR_TYPE TM_SERVICE_OCREPRESENTATION_TYPE"I)V"
+#define METHOD_ONFACTORY_RESET_CALLBACK "(" TM_JAVA_VECTOR_TYPE TM_SERVICE_OCREPRESENTATION_TYPE"I)V"
+#define METHOD_ONREBOOT_CALLBACK "(" TM_JAVA_VECTOR_TYPE TM_SERVICE_OCREPRESENTATION_TYPE"I)V"
+#define METHOD_ONPOST_CALLBACK "(" TM_JAVA_VECTOR_TYPE TM_SERVICE_OCREPRESENTATION_TYPE"I)V"
+#define METHOD_ONPUT_CALLBACK "(" TM_JAVA_VECTOR_TYPE TM_SERVICE_OCREPRESENTATION_TYPE"I)V"
+#define METHOD_ONGET_CALLBACK "(" TM_JAVA_VECTOR_TYPE TM_SERVICE_OCREPRESENTATION_TYPE"I)V"
+#define METHOD_TMCALLBACK_GETINSTANCE "()" TM_SERVICE_CALLBACK_CLASS_TYPE
+
+jobject OcResourceToJava(JNIEnv *env, jlong resource)
+{
+ jclass resourceClass = GetJClass(TM_SERVICE_OCRESOURCE_PATH);
+ if (NULL == resourceClass)
+ {
+ LOGE("OcResourceToJava : failed to find OCResouce java class!");
+ return NULL;
+ }
+
+ jmethodID constructor = env->GetMethodID(resourceClass, "<init>", "(J)V");
+ if (NULL == constructor)
+ {
+ LOGE("OcResourceToJava: Failed to get constructor method!");
+ return NULL;
+ }
+
+ jobject resourceObj = (jobject) env->NewObject(resourceClass, constructor, resource);
+ if (NULL == resourceObj)
+ {
+ LOGE("OcResourceToJava: Failed to create OCResouce java object!");
+ return NULL;
+ }
+
+ return resourceObj;
+}
+
+jobject OcHeaderOptionToJava(JNIEnv *env, OC::HeaderOption::OCHeaderOption headerOption)
+{
+ JString *optionData = new JString(env, headerOption.getOptionData());
+ if (!optionData)
+ {
+ LOGE("OcHeaderOptionToJava : failed to get JString!");
+ return NULL;
+ }
+
+ jclass headerOptionClass = GetJClass(TM_SERVICE_HEADER_OPTION_PATH);
+ if (NULL == headerOptionClass)
+ {
+ LOGE("OcHeaderOptionToJava : failed to find OCRepresentation java class!");
+ return NULL;
+ }
+
+ jmethodID constructor = env->GetMethodID(headerOptionClass, "<init>", "(JLjava/lang/String;)V");
+ if (NULL == constructor)
+ {
+ LOGE("OcHeaderOptionToJava: Failed to get constructor method!");
+ return NULL;
+ }
+
+ jobject headerOptionObj = (jobject) env->NewObject(headerOptionClass, constructor,
+ (jlong)headerOption.getOptionID(), optionData);
+ if (NULL == headerOptionObj)
+ {
+ LOGE("OcHeaderOptionToJava: Failed to create OCRepresentation java object!");
+ return NULL;
+ }
+
+ return headerOptionObj;
+}
+
+jobject OcRepresentationToJava(JNIEnv *env, jlong ocRepresentation)
+{
+ jclass ocRepresentationClass = GetJClass(TM_SERVICE_OCREPRESENTATION_PATH);
+ if (NULL == ocRepresentationClass)
+ {
+ LOGE("OcRepresentationToJava : failed to find OCRepresentation java class!");
+ return NULL;
+ }
+
+ jmethodID constructor = env->GetMethodID(ocRepresentationClass, "<init>", "(J)V");
+ if (NULL == constructor)
+ {
+ LOGE("OcRepresentationToJava: Failed to get constructor method!");
+ return NULL;
+ }
+
+ jobject ocRepresentationObj = (jobject) env->NewObject(ocRepresentationClass, constructor,
+ ocRepresentation);
+ if (NULL == ocRepresentationObj)
+ {
+ LOGE("OcRepresentationToJava: Failed to create OCRepresentation java object!");
+ return NULL;
+ }
+
+ return ocRepresentationObj;
+}
+
+void ThingsManagerCallbacks::onFoundCandidateResource(
+ std::vector< std::shared_ptr<OC::OCResource>> resources)
+{
+ LOGI("findCandidateResource : Enter");
+
+ if (resources.size() == 0)
+ {
+ LOGE("findCandidateResource : found resources zero");
+ return;
+ }
+
+ JNIEnv *env = ThingsManagerJVM::getEnv();
+ if (env == NULL)
+ {
+ LOGE("findCandidateResource : Getting JNIEnv failed");
+ return;
+ }
+
+ // Get ThingsManagerCallback class reference
+ jclass thingsManagerCallbacks = GetJClass(TM_SERVICE_CALLBACK_CLASS_PATH);
+ if (NULL == thingsManagerCallbacks)
+ {
+ LOGE("findCandidateResource : GetJClass TMServiceCallbackInterface failed");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ // Get the ThingsManagerCallback class instance
+ jobject jobjectCallback = GetJObjectInstance(TM_SERVICE_CALLBACK_CLASS_PATH);
+ if (NULL == jobjectCallback)
+ {
+ LOGE("getInstance( %s) failed!", TM_SERVICE_CALLBACK_CLASS_PATH);
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ // Get onResourceCallback method reference
+ jmethodID method_id = env->GetMethodID(thingsManagerCallbacks,
+ "onResourceCallback", METHOD_ONRESOURCE_CALLBACK);
+ if (NULL == method_id)
+ {
+ LOGE("findCandidateResource: onResourceCallback : GetMethodID failed");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ if ((env)->ExceptionCheck())
+ {
+ LOGE("findCandidateResource : ExceptionCheck failed");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ jclass vectorCls = env->FindClass(TM_JAVA_VECTOR_CLASS_PATH);
+ if (!vectorCls)
+ {
+ LOGE("findCandidateResource: failed to get %s class reference", TM_JAVA_VECTOR_CLASS_PATH);
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ jmethodID constr = env->GetMethodID(vectorCls, "<init>", "()V");
+ if (!constr)
+ {
+ LOGE("findCandidateResource: failed to get %s constructor", TM_JAVA_VECTOR_CLASS_PATH);
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ jobject vectorObj = env->NewObject(vectorCls, constr);
+ if (!vectorObj)
+ {
+ LOGE("findCandidateResource: failed to create a %s object", TM_JAVA_VECTOR_CLASS_PATH);
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ jmethodID addElement = env->GetMethodID(vectorCls, "addElement", "(Ljava/lang/Object;)V");
+ if (NULL == addElement)
+ {
+ LOGE("findCandidateResource: failed to create a addElement method");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ // Convert to java OCResource object
+ for (int i = 0; i < resources.size(); i++)
+ {
+ JniOcResource *jniOcResource = new JniOcResource(resources[i]);
+ if (!jniOcResource)
+ {
+ LOGE("findCandidateResource: failed to create a JniOcResource");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ jobject resource = OcResourceToJava(env, reinterpret_cast<jlong>(jniOcResource));
+ env->CallVoidMethod(vectorObj, addElement, resource);
+ }
+
+ env->CallVoidMethod(jobjectCallback, method_id, vectorObj);
+
+ if ((env)->ExceptionCheck())
+ {
+ LOGE("findCandidateResource : CallVoidMethod failed");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ ThingsManagerJVM::releaseEnv();
+ LOGI("findCandidateResource : Exit");
+}
+
+void ThingsManagerCallbacks::onFoundGroup(std::shared_ptr<OC::OCResource> groupResource)
+{
+ LOGI("FindGroup : Enter");
+
+ if (NULL == groupResource.get())
+ {
+ LOGE("FindGroup : Invalid received GroupResource!");
+ return;
+ }
+
+ JNIEnv *env = ThingsManagerJVM::getEnv();
+ if (env == NULL)
+ {
+ LOGE("FindGroup : Getting JNIEnv failed");
+ return;
+ }
+
+ // Get ThingsManagerCallback class reference
+ jclass thingsManagerCallbacks = GetJClass(TM_SERVICE_CALLBACK_CLASS_PATH);
+ if (NULL == thingsManagerCallbacks)
+ {
+ LOGE("FindGroup : GetJClass TMServiceCallbackInterface failed");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ // Get the ThingsManagerCallback class instance
+ jobject jobjectCallback = GetJObjectInstance(TM_SERVICE_CALLBACK_CLASS_PATH);
+ if (NULL == jobjectCallback)
+ {
+ LOGE("FindGroup: getInstance( %s) failed!", TM_SERVICE_CALLBACK_CLASS_PATH);
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ // Get onGroupFindCallback method reference
+ jmethodID method_id = env->GetMethodID(thingsManagerCallbacks,
+ "onGroupFindCallback",
+ METHOD_ONGROUP_FIND_CALLBACK);
+ if (NULL == method_id)
+ {
+ LOGE("FindGroup : GetMethodID failed");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ if ((env)->ExceptionCheck())
+ {
+ LOGE("FindGroup : ExceptionCheck failed");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ JniOcResource *jniOcResource = new JniOcResource(groupResource);
+ if (!jniOcResource)
+ {
+ LOGE("FindGroup : groupResource is invalid!");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ jobject resource = OcResourceToJava(env, reinterpret_cast<jlong>(jniOcResource));
+
+ env->CallVoidMethod(jobjectCallback, method_id, resource);
+
+ if ((env)->ExceptionCheck())
+ {
+ LOGE("FindGroup : CallVoidMethod failed");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ ThingsManagerJVM::releaseEnv();
+ LOGI("FindGroup : Exit");
+}
+
+void ThingsManagerCallbacks::onSubscribePresence(std::string resource, OCStackResult result)
+{
+ LOGI("SubscribePresence : Entry");
+
+ JNIEnv *env = ThingsManagerJVM::getEnv();
+ if (env == NULL)
+ {
+ LOGE("SubscribePresence : Getting JNIEnv failed");
+ return;
+ }
+
+ // Get ThingsManagerCallback class reference
+ jclass thingsManagerCallbacks = GetJClass(TM_SERVICE_CALLBACK_CLASS_PATH);
+ if (NULL == thingsManagerCallbacks)
+ {
+ LOGE("findCandidateResource : GetJClass TMServiceCallbackInterface failed");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ // Get getInstance method reference
+ jmethodID getinstance_method_id = env->GetStaticMethodID(thingsManagerCallbacks,
+ "getInstance", METHOD_TMCALLBACK_GETINSTANCE);
+ if (NULL == getinstance_method_id)
+ {
+ LOGE("getInstance : GetMethodID failed");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ // Get the ThingsManagerCallback class instance
+ jobject jobjectCallback = env->CallStaticObjectMethod(thingsManagerCallbacks,
+ getinstance_method_id);
+ if (NULL == jobjectCallback)
+ {
+ LOGE("getInstance( %s) failed!", TM_SERVICE_CALLBACK_CLASS_PATH);
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ jmethodID method_id = env->GetMethodID(thingsManagerCallbacks,
+ "onPresenceCallback",
+ METHOD_ONPRESENCE_CALLBACK);
+ if (NULL == method_id)
+ {
+ LOGE("SubscribePresence : GetMethodID failed");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ if ((env)->ExceptionCheck())
+ {
+ LOGE("SubscribePresence : ExceptionCheck failed");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ JString *jresource = new JString(env, resource);
+ if (jresource == NULL)
+ {
+ LOGE("resource value is invalid");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ env->CallVoidMethod(jobjectCallback, method_id, jresource->getObject(), (jint)result);
+
+ delete jresource;
+
+ if ((env)->ExceptionCheck())
+ {
+ LOGE("SubscribePresence : CallVoidMethod failed");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ LOGI("SubscribePresence : Exit");
+
+//METHOD_FAILURE:
+ ThingsManagerJVM::releaseEnv();
+}
+
+void ThingsManagerCallbacks::onUpdateConfigurationsResponse(const OC::HeaderOptions &headerOptions,
+ const OC::OCRepresentation &rep, const int eCode)
+{
+ LOGI("UpdateConfigurations : Enter");
+
+ ThingsManagerCallbacks::invokeCallback(headerOptions, rep, eCode, "onUpdateConfigurationsCallback",
+ METHOD_ONUPDATE_CONF_CALLBACK);
+
+ LOGI("UpdateConfigurations : Exit");
+}
+
+void ThingsManagerCallbacks::onGetConfigurationsResponse(const OC::HeaderOptions &headerOptions,
+ const OC::OCRepresentation &rep, const int eCode)
+{
+ LOGI("GetConfigurations : Enter");
+
+ ThingsManagerCallbacks::invokeCallback(headerOptions, rep, eCode, "onGetConfigurationsCallback",
+ METHOD_ONGET_CONF_CALLBACK);
+
+ LOGI("GetConfigurations : Exit");
+}
+
+void ThingsManagerCallbacks::onBootStrapResponse(const OC::HeaderOptions &headerOptions,
+ const OC::OCRepresentation &rep, const int eCode)
+{
+ LOGI("BootStrap : Enter");
+
+ ThingsManagerCallbacks::invokeCallback(headerOptions, rep, eCode, "onBootStrapCallback",
+ METHOD_ONBOOT_STRAP_CALLBACK);
+
+ LOGI("BootStrap : Exit");
+}
+
+void ThingsManagerCallbacks::onRebootResponse(const OC::HeaderOptions &headerOptions,
+ const OC::OCRepresentation &rep, const int eCode)
+{
+ LOGI("OnReboot : Enter");
+
+ ThingsManagerCallbacks::invokeCallback(headerOptions, rep, eCode, "onRebootCallback",
+ METHOD_ONREBOOT_CALLBACK);
+
+ LOGI("OnReboot : Exit");
+}
+
+void ThingsManagerCallbacks::onFactoryResetResponse(const OC::HeaderOptions &headerOptions,
+ const OC::OCRepresentation &rep, const int eCode)
+{
+ LOGI("OnFactoryReset : Enter");
+
+ ThingsManagerCallbacks::invokeCallback(headerOptions, rep, eCode, "onFactoryResetCallback",
+ METHOD_ONFACTORY_RESET_CALLBACK);
+
+ LOGI("OnFactoryReset : Exit");
+}
+
+void ThingsManagerCallbacks::onPostResponse(const OC::HeaderOptions &headerOptions,
+ const OC::OCRepresentation &rep, const int eCode)
+{
+ LOGI("PostResponse : Enter");
+
+ ThingsManagerCallbacks::invokeCallback(headerOptions, rep, eCode, "onPostResponseCallback",
+ METHOD_ONPOST_CALLBACK);
+
+ LOGI("PostResponse : Exit");
+}
+
+void ThingsManagerCallbacks::onPutResponse(const OC::HeaderOptions &headerOptions,
+ const OC::OCRepresentation &rep, const int eCode)
+{
+ LOGI("OnPutResponse : Enter");
+
+ ThingsManagerCallbacks::invokeCallback(headerOptions, rep, eCode, "onPutResponseCallback",
+ METHOD_ONPUT_CALLBACK);
+
+ LOGI("OnPutResponse : Exit");
+}
+
+
+void ThingsManagerCallbacks::onGetResponse(const OC::HeaderOptions &headerOptions,
+ const OC::OCRepresentation &rep, const int eCode)
+{
+ LOGI("OnGetResponse : Enter");
+
+ ThingsManagerCallbacks::invokeCallback(headerOptions, rep, eCode, "onGetResponseCallback",
+ METHOD_ONGET_CALLBACK);
+
+ LOGI("OnGetResponse : Exit");
+}
+
+void ThingsManagerCallbacks::invokeCallback(const OC::HeaderOptions &headerOptions,
+ const OC::OCRepresentation &rep, const int eCode, const char *callbackName,
+ const char *signature)
+{
+ LOGI("InvokeCallback : Enter %s", callbackName);
+
+ JNIEnv *env = ThingsManagerJVM::getEnv();
+ if (env == NULL)
+ {
+ LOGE("InvokeCallback : Getting JNIEnv failed");
+ return;
+ }
+
+ // Get ThingsManagerCallback class reference
+ jclass thingsManagerCallbacks = GetJClass(TM_SERVICE_CALLBACK_CLASS_PATH);
+ if (NULL == thingsManagerCallbacks)
+ {
+ LOGE("InvokeCallback : GetJClass TMServiceCallbackInterface failed");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ // Get the ThingsManagerCallback class instance
+ jobject jobjectCallback = GetJObjectInstance(TM_SERVICE_CALLBACK_CLASS_PATH);
+ if (NULL == jobjectCallback)
+ {
+ LOGE("InvokeCallback: getInstance( %s) failed!", TM_SERVICE_CALLBACK_CLASS_PATH);
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ jmethodID method_id = env->GetMethodID(thingsManagerCallbacks, callbackName, signature);
+ if (!method_id)
+ {
+ LOGE("InvokeCallback : GetMethodID failed");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ if ((env)->ExceptionCheck())
+ {
+ LOGE("InvokeCallback : ExceptionCheck failed");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ // Convert vector<OC:HeaderOption::OCHeaderOption> to java type
+ jclass vectorCls = env->FindClass(TM_JAVA_VECTOR_CLASS_PATH);
+ if (!vectorCls)
+ {
+ LOGE("InvokeCallback: failed to get %s class reference", TM_JAVA_VECTOR_CLASS_PATH);
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ jmethodID constr = env->GetMethodID(vectorCls, "<init>", "()V");
+ if (!constr)
+ {
+ LOGE("InvokeCallback: failed to get %s constructor", TM_JAVA_VECTOR_CLASS_PATH);
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ jobject vectorObj = env->NewObject(vectorCls, constr);
+ if (!vectorObj)
+ {
+ LOGE("InvokeCallback: failed to create a %s object", TM_JAVA_VECTOR_CLASS_PATH);
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ jmethodID addElement = env->GetMethodID(vectorCls, "addElement", "(Ljava/lang/Object;)V");
+ if (NULL == addElement)
+ {
+ LOGE("InvokeCallback: failed to create a addElement method");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ jobject headerOptionTemp;
+ for (int i = 0; i < headerOptions.size(); i++)
+ {
+ headerOptionTemp = OcHeaderOptionToJava(env, headerOptions[i]);
+ env->CallVoidMethod(vectorObj, addElement, headerOptionTemp);
+ }
+
+ // Convert OCRepresentation to java type
+ jobject jrepresentation = OcRepresentationToJava(env, (jlong) reinterpret_cast<jlong>(&rep));
+ if (!jrepresentation)
+ {
+ LOGE("InvokeCallback : cannot create OCRepresentation class");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ env->CallVoidMethod(jobjectCallback, method_id, vectorObj, jrepresentation, (jint)eCode);
+
+ if ((env)->ExceptionCheck())
+ {
+ LOGE("InvokeCallback : CallVoidMethod failed");
+ ThingsManagerJVM::releaseEnv();
+ return;
+ }
+
+ ThingsManagerJVM::releaseEnv();
+ LOGI("InvokeCallback : Exit %s", callbackName);
+}
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+#include "jni_things_manager_util.h"
+#include "JniOcResource.h"
+
+std::vector<std::string> convertStringVector(JNIEnv *env, jobject jVectorString)
+{
+ std::vector<std::string> vectorString;
+
+ jclass vectorClass = env->FindClass(TM_JAVA_VECTOR_CLASS_PATH);
+ if (!vectorClass)
+ {
+ LOGE("convertStringVector: Not able to find class %s", TM_JAVA_VECTOR_CLASS_PATH);
+ return vectorString;
+ }
+
+ jmethodID size = env->GetMethodID(vectorClass, "size", "()I");
+ if (NULL == size)
+ {
+ LOGE("convertStringVector: Failed to get method id for size");
+ return vectorString;
+ }
+
+ jmethodID get = env->GetMethodID(vectorClass, "get", "(I)""Ljava/lang/Object;");
+ if (NULL == get)
+ {
+ LOGE("convertStringVector: Failed to get method id for get");
+ return vectorString;
+ }
+
+ jint jSize = env->CallIntMethod(jVectorString, size);
+ int sizeOfVector = jSize;
+
+ for (int index = 0; index < sizeOfVector; index++)
+ {
+ jint jIndex = index;
+ jstring jContactInfoObj = (jstring)env->CallObjectMethod(jVectorString, get, jIndex);
+ if (jContactInfoObj == NULL)
+ {
+ LOGE("convertStringVector: Failed on CallObjectMethod");
+ return vectorString;
+ }
+ const char *buff = env->GetStringUTFChars(jContactInfoObj, 0);
+ if (NULL != buff)
+ {
+ std::string tempString = buff;
+ vectorString.push_back(tempString);
+ }
+
+ env->ReleaseStringUTFChars(jContactInfoObj, buff);
+ }
+
+ return vectorString;
+}
+
+std::map<std::string, std::string> convertStringMap(JNIEnv *env, jobject jMapString)
+{
+ // Get reference to java/util/Map class
+ jclass mapClass = env->GetObjectClass(jMapString);
+ jmethodID sizeMethodId = env->GetMethodID(mapClass, "size", "()I");
+ jmethodID entrySetMethodId = env->GetMethodID(mapClass, "entrySet", "()Ljava/util/Set;");
+
+ // Get reference to java/util/Set class
+ jclass setClass = env->FindClass("java/util/Set");
+ jmethodID iteratorMethodId = env->GetMethodID(setClass, "iterator", "()Ljava/util/Iterator;");
+
+ // Get reference to java/util/Iterator class
+ jclass iteratorClass = env->FindClass("java/util/Iterator");
+ jmethodID hasNextMethodId = env->GetMethodID(iteratorClass, "hasNext", "()Z");
+ jmethodID nextMethodId = env->GetMethodID(iteratorClass, "next", "()Ljava/lang/Object;");
+
+ // Get reference to java/util/Map/Entry class
+ jclass mapEntryClass = env->FindClass("java/util/Map$Entry");
+ jmethodID getKeyMethodId = env->GetMethodID(mapEntryClass, "getKey", "()Ljava/lang/Object;");
+ jmethodID getValueMethodId = env->GetMethodID(mapEntryClass, "getValue", "()Ljava/lang/Object;");
+
+ std::map<std::string, std::string> mapString;
+ // Get entry set from map
+ jobject entrySet = env->CallObjectMethod(jMapString, entrySetMethodId);
+ if (!entrySet)
+ {
+ LOGE("convertStringMap: Failed to get entrySet");
+ return mapString;
+ }
+
+ // Get iterator from set
+ jobject iterator = env->CallObjectMethod(entrySet, iteratorMethodId);
+ if (!iterator)
+ {
+ LOGE("convertStringMap: Failed to get iterator from set");
+ return mapString;
+ }
+
+ if (JNI_TRUE == env->CallBooleanMethod(iterator, hasNextMethodId))
+ {
+ jobject entry = env->CallObjectMethod(iterator, nextMethodId);
+ jstring jMapKeyStr = (jstring)env->CallObjectMethod(entry, getKeyMethodId);
+ jstring jMapValueStr = (jstring)env->CallObjectMethod(entry, getValueMethodId);
+
+ const char *key = env->GetStringUTFChars(jMapKeyStr, 0);
+ const char *value = env->GetStringUTFChars(jMapValueStr, 0);
+
+ if ((NULL != key) && (NULL != value))
+ {
+ std::string keyStr = key;
+ std::string valueStr = value;
+ mapString.insert(std::make_pair(keyStr, valueStr));
+ }
+ env->ReleaseStringUTFChars(jMapKeyStr, key);
+ env->ReleaseStringUTFChars(jMapValueStr, value);
+ }
+
+ return mapString;
+}
--- /dev/null
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-20
+android.library=true
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file Action.java
+ *
+ * @brief This file contains class which provides functions to retrieve the Action details from a
+ * Segment.
+ */
+
+package org.iotivity.service.tm;
+
+import java.util.StringTokenizer;
+import java.util.Vector;
+
+import android.util.Log;
+
+/**
+ * This class provides functions to retrieve the Action details from a
+ * Segment.
+ *
+ */
+public class Action {
+ private static final String LOG_TAG = "Action";
+ /**
+ * Sub Segment Value
+ */
+ public String target;
+
+ /**
+ * Capability instance stored in listOfCapability vector variable.
+ */
+ public Vector<Capability> listOfCapability = new Vector<Capability>();
+
+ /**
+ * This function generates an Action String (Example:
+ * uri=coap://10.251.44.228:49858/a/light|power=10)
+ *
+ * @return String for a specific action.
+ *
+ */
+ public String toString() {
+ StringBuilder result = new StringBuilder();
+
+ result.append("uri=" + target + "|");
+ for (int i = 0; i < listOfCapability.size(); i++) {
+ if (i != 0)
+ result.append('|');
+ result.append(listOfCapability.elementAt(i).toString());
+ }
+
+ return result.toString();
+ }
+
+ /**
+ * This function parses the Segment value to retrieve sub segments separated
+ * by a vertical bar(|): URI and a pair of attribute key and value
+ *
+ * @param actionString
+ * Segment String
+ *
+ * @return Action needed by remote devices as members of a specific group
+ *
+ */
+ public static Action toAction(String actionString) {
+ Action result = new Action();
+ StringTokenizer tokenizer = new StringTokenizer(actionString, "|");
+
+ boolean actionFlag = false;
+ while (tokenizer.hasMoreTokens()) {
+ String segment = tokenizer.nextToken();
+ if (false == actionFlag) {
+ // Parse the action string
+ StringTokenizer targetTokenizer = new StringTokenizer(segment,
+ "=");
+ if (2 != targetTokenizer.countTokens()
+ || false == targetTokenizer.nextToken()
+ .equalsIgnoreCase("uri")) {
+ Log.e(LOG_TAG, "Invalid action segment = " + segment);
+ return null;
+ }
+
+ result.target = targetTokenizer.nextToken();
+ actionFlag = true;
+ } else {
+ // Parse the capability string
+ Capability capability = Capability.toCapability(segment);
+ if (null == capability) {
+ Log.e(LOG_TAG,
+ "Failed to convert string to Capability class!");
+ return null;
+ }
+
+ // Add the parsed capability to list
+ result.listOfCapability.add(capability);
+ }
+ }
+
+ return result;
+ }
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+/**
+ * @file ActionSet.java
+ *
+ * @brief This file contains class which provides functions to retrieve ActionSet from plain text.
+ *
+ */
+package org.iotivity.service.tm;
+
+import java.util.StringTokenizer;
+import java.util.Vector;
+
+import android.util.Log;
+
+/**
+ * This class provides functions to retrieve ActionSet from plain text.
+ * An ActionSet is a set of descriptions of actions needed by remote
+ * devices as members of a specific group. To create an ActionSet, one
+ * needs to know the Delimeter serialization.
+ *
+ */
+public class ActionSet extends Time {
+ /**
+ * String Tag for Logging
+ */
+ private static final String LOG_TAG = "ActionSet";
+ /**
+ * A first segment before the first asterisk(*) in ActionSet string is an
+ * actionset name
+ */
+ public String actionsetName;
+ /**
+ * Action instance stored in listOfAction vector variable.
+ */
+ public Vector<Action> listOfAction = new Vector<Action>();
+
+ /**
+ * This function generates an ActionSet String which contains ActionSet
+ * name, delay in seconds, ActionSetType which can be 0(NONE), 1(SCHEDULED)
+ * or 2(RECURSIVE) and a list of actions. (Example: movieTime*10
+ * 1*uri=coap://10.251.44.228:49858/a/light|power=
+ * OFF*uri=coap://10.251.44.228:49858). The first segment before the first
+ * asterisk(*) is an ActionSet name. The second segment goes before the next
+ * asterisk. In the above example, 10 is the second segment which signifies
+ * time delay in seconds followed by a space and ActionSetType which
+ * signifies whether an ActionSet has to be triggered Recursively(2) or
+ * Scheduled manner(1) or immediately(0).
+ * "uri=coap://10.251.44.228:49858/a/light|power=10" is the third segment.
+ * This can be also divided into two sub segments by a vertical bar(|): URI
+ * and a pair of attribute key and value.
+ *
+ * @return String for a specific action.
+ *
+ */
+ @Override
+ public String toString() {
+ StringBuilder result = new StringBuilder();
+
+ // Append action name
+ result.append(actionsetName + "*");
+
+ // Append delay and type
+ result.append(getDelay() + " " + getType().ordinal() + "*");
+
+ // Append list of actions
+ for (int i = 0; i < listOfAction.size(); i++) {
+ if (i != 0)
+ result.append('*');
+ result.append(listOfAction.elementAt(i).toString());
+ }
+
+ return result.toString();
+ }
+
+ /**
+ * This function extracts a list of Actions from plain text and constructs
+ * an ActionSet.
+ *
+ * @param actionsetString
+ * ActionSet in String format. (Example: movieTime*10
+ * 1*uri=coap://10.251.44.228:49858/a/light|power=
+ * OFF*uri=coap://10.251.44.228:49858). The first segment before
+ * the first asterisk(*) is an ActionSet name. The second segment
+ * goes before the next asterisk. In the above example, 10 is the
+ * second segment which signifies time delay in seconds followed
+ * by a space and ActionSetType which signifies whether an
+ * ActionSet has to be triggered Recursively(2) or Scheduled
+ * manner(1) or immediately(0).
+ * "uri=coap://10.251.44.228:49858/a/light|power=10" is the third
+ * segment. This can be also divided into two sub segments by a
+ * vertical bar(|): URI and a pair of attribute key and value).
+ *
+ * @return ActionSet which is a set of descriptions of actions needed by
+ * remote devices as members of a specific group.
+ *
+ */
+ public static ActionSet toActionSet(String actionsetString) {
+ if (0 == actionsetString.length()) {
+ return null;
+ }
+
+ ActionSet result = new ActionSet();
+ StringTokenizer tokenizer = new StringTokenizer(actionsetString, "*");
+ boolean actionNameFlag = false;
+ while (tokenizer.hasMoreTokens()) {
+ String segment = tokenizer.nextToken();
+ if (false == actionNameFlag) {
+ if (true == segment.contains("|")
+ || true == segment.contains("=")) {
+ Log.e(LOG_TAG, "Invalid actionset name string!");
+ return null;
+ }
+
+ result.actionsetName = segment;
+ actionNameFlag = true;
+ } else {
+ Action action = Action.toAction(segment);
+ if (null == action) {
+ Log.e(LOG_TAG, "Failed to convert string to Action class!");
+ return null;
+ }
+
+ result.listOfAction.add(action);
+ }
+ }
+
+ return result;
+ }
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+/**
+ * @file Capability.java
+ *
+ * @brief This file contains class which provides functions to specify an attribute key and value
+ * of the target resource
+ *
+ */
+
+package org.iotivity.service.tm;
+
+import java.util.StringTokenizer;
+
+import android.util.Log;
+
+/**
+ * This class needs to be created to specify an attribute key and value
+ * of the target resource. The attribute key and value are written in
+ * capability and status variables of Capability instance class,
+ * respectively. After filling the Capability instance, store it to
+ * listOfCapability vector variable of Action instance.
+ *
+ */
+public class Capability {
+ /**
+ * String Tag for Logging
+ */
+ private static final String LOG_TAG = "Capability";
+ /**
+ * Attribute Key of target resource
+ */
+ public String capability;
+ /**
+ * Attribute Value of target resource
+ */
+ public String status;
+
+ /**
+ * This function generates a Capability String.
+ *
+ * @return String for a specific Capability.
+ *
+ */
+ public String toString() {
+ StringBuilder result = new StringBuilder();
+ result.append(capability + "=" + status);
+ return result.toString();
+ }
+
+ /**
+ * This function parses the Capability String.
+ *
+ * @param capabilityString
+ * Capability in String format.
+ *
+ * @return Capability class.
+ *
+ */
+ public static Capability toCapability(String capabilityString) {
+ StringTokenizer tokenizer = new StringTokenizer(capabilityString, "=");
+ if (2 != tokenizer.countTokens()) {
+ Log.e(LOG_TAG, "Invalid capability string = " + capabilityString);
+ return null;
+ }
+
+ Capability result = new Capability();
+
+ result.capability = tokenizer.nextToken();
+ result.status = tokenizer.nextToken();
+ return result;
+ }
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file IActionListener.java
+ *
+ * @brief This file provides interface for receiving the callback for the GET, PUT and POST requested
+ * actions.
+ *
+ */
+
+package org.iotivity.service.tm;
+
+import java.util.Vector;
+
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcRepresentation;
+
+/**
+ * Provides interface for receiving the callback for the GET, PUT and
+ * POST requested actions.
+ */
+public interface IActionListener {
+ /**
+ * This callback method is called when a asynchronous response for the getActionSet
+ * request is received.
+ *
+ * @param headerOptions
+ * It comprises of optionID and optionData as members.
+ * @param rep
+ * Configuration parameters are carried as a pair of attribute
+ * key and value in a form of OCRepresentation instance.
+ * @param errorValue
+ * error code.
+ *
+ */
+ public void onGetResponseCallback(Vector<OcHeaderOption> headerOptions,
+ OcRepresentation rep, int errorValue);
+
+ /**
+ * This callback method is called when a asynchronous response for the addActionSet
+ * request is received.
+ *
+ * @param headerOptions
+ * It comprises of optionID and optionData as members.
+ * @param rep
+ * Configuration parameters are carried as a pair of attribute
+ * key and value in a form of OCRepresentation instance.
+ * @param errorValue
+ * error code.
+ *
+ */
+ public void onPutResponseCallback(Vector<OcHeaderOption> headerOptions,
+ OcRepresentation rep, int errorValue);
+
+ /**
+ * This callback method is called when a asynchronous response for the executeActionSet
+ * or deleteActionSet request is received.
+ *
+ * @param headerOptions
+ * It comprises of optionID and optionData as members.
+ * @param rep
+ * Configuration parameters are carried as a pair of attribute
+ * key and value in a form of OCRepresentation instance.
+ * @param errorValue
+ * error code.
+ *
+ */
+ public void onPostResponseCallback(Vector<OcHeaderOption> headerOptions,
+ OcRepresentation rep, int errorValue);
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file IConfigurationListener.java
+ *
+ * @brief This file provides interface for receiving asynchronous response for
+ * configuration APIs.
+ */
+
+package org.iotivity.service.tm;
+
+import java.util.Vector;
+
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcRepresentation;
+
+/**
+ * Provides interface for receiving asynchronous response for
+ * configuration APIs.
+ */
+public interface IConfigurationListener {
+ /**
+ * Asynchronous response callback for ThingsManager::doBootstrap API.
+ */
+ public void onBootStrapCallback(Vector<OcHeaderOption> headerOptions,
+ OcRepresentation rep, int errorValue);
+
+ /**
+ * Asynchronous response callback for ThingsManager::updateConfigurations
+ * API.
+ */
+ public void onUpdateConfigurationsCallback(
+ Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+ int errorValue);
+
+ /**
+ * Asynchronous response callback for ThingsManager::getConfigurations API.
+ */
+ public void onGetConfigurationsCallback(
+ Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+ int errorValue);
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file IDiagnosticsListener.java
+ *
+ * @brief This file provides interface for receiving asynchronous response for
+ * diagnostic feature APIs.
+ */
+
+package org.iotivity.service.tm;
+
+import java.util.Vector;
+
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcRepresentation;
+
+/**
+ * Provides interface for receiving asynchronous response for diagnostic
+ * feature APIs.
+ */
+public interface IDiagnosticsListener {
+ /**
+ * Asynchronous response callback for ThingsManager::reboot API.
+ */
+ public void onRebootCallback(Vector<OcHeaderOption> headerOptions,
+ OcRepresentation rep, int errorValue);
+
+ /**
+ * Asynchronous response callback for ThingsManager::factoryReset API.
+ */
+ public void onFactoryResetCallback(Vector<OcHeaderOption> headerOptions,
+ OcRepresentation rep, int errorValue);
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+/**
+ * @file IFindCandidateResourceListener.java
+ *
+ * @brief This file provides interface for getting notification when resources are
+ * discovered in network.
+ */
+
+package org.iotivity.service.tm;
+
+import java.util.Vector;
+
+import org.iotivity.base.OcResource;
+
+/**
+ * Provides interface for getting notification when resources are
+ * discovered in network.
+ */
+public interface IFindCandidateResourceListener {
+ /**
+ * This callback method will be called whenever resource is discovered in
+ * the network.
+ *
+ * @param resources
+ * List of resources discovered in the network
+ */
+ public void onResourceCallback(Vector<OcResource> resources);
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+/**
+ * @file IFindGroupListener.java
+ *
+ * @brief This file provides interface for getting group discovery status.
+ *
+ */
+
+package org.iotivity.service.tm;
+
+import org.iotivity.base.OcResource;
+
+/**
+ * Provides interface for getting group discovery status.
+ */
+public interface IFindGroupListener {
+ /**
+ * This callback method will be called to notify whether group is found or
+ * not.
+ *
+ * @param resource
+ * URI of resource.
+ */
+ public void onGroupFindCallback(OcResource resource);
+}
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+/**
+ * @file ISubscribePresenceListener.java
+ *
+ * @brief This file provides interface for getting child resource presence status.
+ *
+ */
+
+package org.iotivity.service.tm;
+
+/**
+ * Provides interface for getting child resource presence status.
+ */
+public interface ISubscribePresenceListener {
+ /**
+ * This callback method will be called for child resource presence status.
+ *
+ * @param resource
+ * URI of resource.
+ * @param result
+ * error code.
+ */
+ public void onPresenceCallback(String resource, OCStackResult result);
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+/**
+ * @file OCStackResult.java
+ *
+ * @brief This file provides a Enum which contains Status codes for Success and Errors
+ *
+ */
+
+package org.iotivity.service.tm;
+
+/**
+ * This Enum contains Status codes for Success and Errors
+ */
+public enum OCStackResult {
+ OC_STACK_OK,
+ OC_STACK_RESOURCE_CREATED,
+ OC_STACK_RESOURCE_DELETED,
+ OC_STACK_CONTINUE,
+ OC_STACK_INVALID_URI,
+ OC_STACK_INVALID_QUERY,
+ OC_STACK_INVALID_IP,
+ OC_STACK_INVALID_PORT,
+ OC_STACK_INVALID_CALLBACK,
+ OC_STACK_INVALID_METHOD,
+ OC_STACK_INVALID_PARAM,
+ OC_STACK_INVALID_OBSERVE_PARAM,
+ OC_STACK_NO_MEMORY,
+ OC_STACK_COMM_ERROR,
+ OC_STACK_NOTIMPL,
+ OC_STACK_NO_RESOURCE,
+ OC_STACK_RESOURCE_ERROR,
+ OC_STACK_SLOW_RESOURCE,
+ OC_STACK_REPEATED_REQUEST,
+ OC_STACK_NO_OBSERVERS,
+ OC_STACK_OBSERVER_NOT_FOUND,
+ OC_STACK_VIRTUAL_DO_NOT_HANDLE,
+ OC_STACK_INVALID_OPTION,
+ OC_STACK_MALFORMED_RESPONSE,
+ OC_STACK_PERSISTENT_BUFFER_REQUIRED,
+ OC_STACK_INVALID_REQUEST_HANDLE,
+ OC_STACK_INVALID_DEVICE_INFO,
+ OC_STACK_INVALID_JSON,
+ OC_STACK_PRESENCE_STOPPED,
+ OC_STACK_PRESENCE_TIMEOUT,
+ OC_STACK_PRESENCE_DO_NOT_HANDLE,
+ OC_STACK_ERROR,
+ OC_STACK_LISTENER_NOT_SET;
+
+ public static OCStackResult conversion(int ordinal) {
+
+ OCStackResult result = OCStackResult.values()[31];
+
+ if (ordinal == 0)
+ result = OCStackResult.values()[0];
+ else if (ordinal == 1)
+ result = OCStackResult.values()[1];
+ else if (ordinal == 2)
+ result = OCStackResult.values()[2];
+ else if (ordinal == 3)
+ result = OCStackResult.values()[3];
+
+ else if (ordinal == 20)
+ result = OCStackResult.values()[4];
+ else if (ordinal == 21)
+ result = OCStackResult.values()[5];
+ else if (ordinal == 22)
+ result = OCStackResult.values()[6];
+ else if (ordinal == 23)
+ result = OCStackResult.values()[7];
+ else if (ordinal == 24)
+ result = OCStackResult.values()[8];
+ else if (ordinal == 25)
+ result = OCStackResult.values()[9];
+ else if (ordinal == 26)
+ result = OCStackResult.values()[10];
+ else if (ordinal == 27)
+ result = OCStackResult.values()[11];
+ else if (ordinal == 28)
+ result = OCStackResult.values()[12];
+ else if (ordinal == 29)
+ result = OCStackResult.values()[13];
+ else if (ordinal == 30)
+ result = OCStackResult.values()[14];
+ else if (ordinal == 31)
+ result = OCStackResult.values()[15];
+ else if (ordinal == 32)
+ result = OCStackResult.values()[16];
+ else if (ordinal == 33)
+ result = OCStackResult.values()[17];
+ else if (ordinal == 34)
+ result = OCStackResult.values()[18];
+ else if (ordinal == 35)
+ result = OCStackResult.values()[19];
+ else if (ordinal == 36)
+ result = OCStackResult.values()[20];
+ else if (ordinal == 37)
+ result = OCStackResult.values()[21];
+ else if (ordinal == 38)
+ result = OCStackResult.values()[22];
+ else if (ordinal == 39)
+ result = OCStackResult.values()[23];
+ else if (ordinal == 40)
+ result = OCStackResult.values()[24];
+ else if (ordinal == 41)
+ result = OCStackResult.values()[25];
+ else if (ordinal == 42)
+ result = OCStackResult.values()[26];
+ else if (ordinal == 43)
+ result = OCStackResult.values()[27];
+
+ else if (ordinal == 128)
+ result = OCStackResult.values()[28];
+ else if (ordinal == 129)
+ result = OCStackResult.values()[29];
+ else if (ordinal == 130)
+ result = OCStackResult.values()[30];
+
+ return result;
+ }
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+/**
+ * @file ThingsManager.java
+ *
+ * @brief This file provides a class for a set of APIs relating to group management,
+ * synchronization of group, configuration of things, and diagnostics
+ * about things.
+ *
+ */
+
+package org.iotivity.service.tm;
+
+import java.util.Map;
+import java.util.Vector;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.OcResourceHandle;
+
+import android.util.Log;
+
+/**
+ * This class provides a set of APIs relating to group management,
+ * synchronization of group, configuration of things, and diagnostics
+ * about things.
+ *
+ */
+public class ThingsManager {
+
+ private IFindCandidateResourceListener resourceListener;
+ private ISubscribePresenceListener presenceListener;
+ private IFindGroupListener groupListener;
+ private IConfigurationListener configurationListener;
+ private IDiagnosticsListener diagnosticsListener;
+ private IActionListener actionListener;
+ private final String LOG_TAG = this.getClass()
+ .getSimpleName();
+
+ private final ThingsManagerCallback thingsManagerCallbackInterfaceObj;
+ private final ThingsManagerInterface thingsManagerInterfaceObj;
+
+ static {
+ System.loadLibrary("gnustl_shared");
+ System.loadLibrary("oc_logger");
+ System.loadLibrary("connectivity_abstraction");
+ System.loadLibrary("ca-interface");
+ System.loadLibrary("octbstack");
+ System.loadLibrary("oc");
+ System.loadLibrary("TGMSDKLibrary");
+ System.loadLibrary("ocstack-jni");
+ System.loadLibrary("things-manager-jni");
+ }
+
+ /**
+ * Constructor for ThingsManager. Constructs a new ThingsManager.
+ */
+ public ThingsManager() {
+ thingsManagerCallbackInterfaceObj = ThingsManagerCallback.getInstance();
+ thingsManagerInterfaceObj = ThingsManagerInterface.getInstance();
+ }
+
+ /**
+ * Set listener for receiving notification of resource discovery.
+ *
+ * @param listener
+ * IFindCandidateResourceListener to receive the
+ * discovered resources.
+ */
+ public void setFindCandidateResourceListener(
+ IFindCandidateResourceListener listener) {
+ resourceListener = listener;
+ thingsManagerCallbackInterfaceObj
+ .registerFindCandidateResourceListener(listener);
+ thingsManagerInterfaceObj
+ .registerFindCandidateResourceListener(listener);
+ }
+
+ /**
+ * Set listener for receiving child resource presence notifications.
+ *
+ * @param listener
+ * ISubscribePresenceListener to receive child resource
+ * presence state.
+ */
+ public void setSubscribePresenceListener(ISubscribePresenceListener listener) {
+ presenceListener = listener;
+ thingsManagerCallbackInterfaceObj
+ .registerSubscribePresenceListener(listener);
+ thingsManagerInterfaceObj.registerSubscribePresenceListener(listener);
+ }
+
+ /**
+ * Set listener for receiving notification on whether the requested group is
+ * found or not.
+ *
+ * @param listener
+ * IFindGroupListener to receive group discovery status.
+ */
+ public void setGroupListener(IFindGroupListener listener) {
+ groupListener = listener;
+ thingsManagerCallbackInterfaceObj.registerGroupListener(listener);
+ thingsManagerInterfaceObj.registerGroupListener(listener);
+ }
+
+ /**
+ * Set listener for receiving asynchronous response for configuration APIs.
+ *
+ * @param listener
+ * IConfigurationListener to receive asynchronous response
+ * for configuration APIs.
+ */
+ public void setConfigurationListener(IConfigurationListener listener) {
+ configurationListener = listener;
+ thingsManagerCallbackInterfaceObj
+ .registerConfigurationListener(listener);
+ thingsManagerInterfaceObj.registerConfigurationListener(listener);
+ }
+
+ /**
+ * Set listener for receiving asynchronous response for diagnostic feature
+ * APIs.
+ *
+ * @param listener
+ * IDiagnosticsListener to receive asynchronous response
+ * for diagnostic feature APIs.
+ */
+ public void setDiagnosticsListener(IDiagnosticsListener listener) {
+ diagnosticsListener = listener;
+ thingsManagerCallbackInterfaceObj.registerDiagnosticsListener(listener);
+ }
+
+ /**
+ * Set listener for receiving responses of Get, PUT and POST requests.
+ *
+ * @param listener
+ * IActionListener to receive Get, PUT and POST request
+ * responses.
+ */
+ public void setActionListener(IActionListener listener) {
+ actionListener = listener;
+ thingsManagerCallbackInterfaceObj.registerActionListener(listener);
+ }
+
+ /**
+ * API for discovering candidate resources with waiting delay. This
+ * operation returns all resources of given type on the network service.
+ * This operation is sent via multicast to all services. However, the filter
+ * limits the responders to just those that support the resource type in the
+ * query. Currently only exact matches are supported.
+ * <p>
+ * Listener should be set using setFindCandidateResourceListener API
+ * <p>
+ * Listener IFindCandidateResourceListener::onResourceCallback
+ * will be notified when resource is discovered in network.
+ *
+ * @param resourceTypes
+ * required resource types(called "candidate")
+ * @param waitTime
+ * Delay time to add in seconds before starting to find the
+ * resources in network.
+ *
+ * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+ * code.
+ *
+ */
+ public OCStackResult findCandidateResources(Vector<String> resourceTypes,
+ int waitTime) {
+ if (null == resourceListener) {
+ Log.e(LOG_TAG,"findCandidateResources: listener not set!");
+ return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+ }
+
+ OCStackResult result = thingsManagerInterfaceObj.findCandidateResources(
+ resourceTypes, waitTime);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "findCandidateResources: returned error: " + result.name());
+ }
+
+ return result;
+ }
+
+ /**
+ * API for subscribing child's state. It subscribes the presence state of
+ * the resource. By making this subscription, every time a server
+ * adds/removes/alters a resource, starts or is intentionally stopped, a
+ * notification is sent to subscriber.
+ *
+ * <p>
+ * Listener should be set using setSubscribePresenceListener API.
+ * <p>
+ * Listener ISubscribePresenceListener::onPresenceCallback will
+ * be notified for resource presence status
+ *
+ * @param resource
+ * collection resource for subscribing presence of all child
+ * resources
+ *
+ * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+ * code.
+ *
+ */
+ public OCStackResult subscribeCollectionPresence(OcResource resource)
+ throws OcException {
+ if (null == presenceListener) {
+ Log.e(LOG_TAG,"subscribeCollectionPresence: listener not set!");
+ return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+ }
+
+ OCStackResult result = thingsManagerInterfaceObj
+ .subscribeCollectionPresence(resource);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "subscribeCollectionPresence: returned error: " + result.name());
+ }
+
+ return result;
+ }
+
+ /**
+ * API for finding a specific remote group when a resource tries to join a
+ * group.
+ * <p>
+ * Listener should be set using setGroupListener API
+ * <p>
+ * Listener IFindGroupListener::onGroupFindCallback will be
+ * called to notify whenever a requested group is found.
+ *
+ * @param collectionResourceTypes
+ * resource types of a group to find and join
+ *
+ * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+ * code.
+ *
+ *
+ */
+ public OCStackResult findGroup(Vector<String> collectionResourceTypes) {
+ if (null == groupListener) {
+ Log.e(LOG_TAG,"findGroup: listener not set!");
+ return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+ }
+
+ OCStackResult result = result = thingsManagerInterfaceObj.findGroup(collectionResourceTypes);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "findGroup: returned error: " + result.name());
+ }
+
+ return result;
+ }
+
+ /**
+ * API for creating a new group.
+ *
+ * @param collectionResourceType
+ * resource type of a group to create
+ *
+ * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+ * code.
+ */
+ public OCStackResult createGroup(String collectionResourceType) {
+ OCStackResult result = thingsManagerInterfaceObj.createGroup(collectionResourceType);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "createGroup: returned error: " + result.name());
+ }
+
+ return result;
+ }
+
+ /**
+ * API for joining a group. This API is used for joining the resource
+ * to local group which is created using @createGroup API.
+ *
+ * @param collectionResourceType
+ * resource type of a group to join.
+ * @param resourceHandle
+ * resource handle to join a group.
+ *
+ * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+ * code.
+ *
+ */
+ public OCStackResult joinGroup(String collectionResourceType,
+ OcResourceHandle resourceHandle) {
+ OCStackResult result = thingsManagerInterfaceObj.joinGroup(collectionResourceType,
+ resourceHandle);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "joinGroup: returned error: " + result.name());
+ }
+
+ return result;
+ }
+
+ /**
+ * API for joining a group. This API is used for joining the resource to
+ * remote group.
+ *
+ * @param resource
+ * group resource to join.
+ * @param resourceHandle
+ * resource handle to join a group.
+ *
+ * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+ * code.
+ *
+ */
+ public OCStackResult joinGroup(OcResource resource,
+ OcResourceHandle resourceHandle) throws OcException {
+ OCStackResult result = thingsManagerInterfaceObj.joinGroup(resource, resourceHandle);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "joinGroup: returned error: " + result.name());
+ }
+
+ return result;
+ }
+
+ /**
+ * API for leaving a joined local group.
+ *
+ * @param collectionResourceType
+ * resource type of a group to leave.
+ * @param resourceHandle
+ * resource handle to leave a group.
+ *
+ * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+ * code.
+ *
+ */
+ public OCStackResult leaveGroup(String collectionResourceType,
+ OcResourceHandle resourceHandle) {
+ OCStackResult result = thingsManagerInterfaceObj.leaveGroup(collectionResourceType,
+ resourceHandle);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "leaveGroup: returned error: " + result.name());
+ }
+
+ return result;
+ }
+
+ /**
+ * API for leaving a joined remote group.
+ *
+ * @param resource
+ * resource of a group to leave.
+ * @param collectionResourceType
+ * resource type of a group to leave.
+ * @param resourceHandle
+ * resource handle to leave a group.
+ *
+ * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+ * code.
+ *
+ */
+ public OCStackResult leaveGroup(OcResource resource, String collectionResourceType,
+ OcResourceHandle resourceHandle) {
+ OCStackResult result = thingsManagerInterfaceObj.leaveGroup(resource, collectionResourceType,
+ resourceHandle);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "leaveGroup: returned error: " + result.name());
+ }
+
+ return result;
+ }
+
+ /**
+ * API for deleting a created group.
+ *
+ * @param collectionResourceType
+ * resource type of a group to delete.
+ *
+ */
+ public void deleteGroup(String collectionResourceType) {
+ thingsManagerInterfaceObj.deleteGroup(collectionResourceType);
+ }
+
+ /**
+ * API for getting a list of local groups.
+ *
+ * @return Returns the map with the group resource type and group
+ * resource handle on successs otherwise null.
+ *
+ */
+ public Map<String, OcResourceHandle> getGroupList() {
+ return thingsManagerInterfaceObj.getGroupList();
+ }
+
+ /**
+ * API for registering and binding a resource to group.
+ *
+ * @param resource
+ * resource for register and bind to group. It has all data.
+ * @param collectionHandle
+ * collection resource handle. It will be the added child
+ * resource.
+ *
+ * @return OcResourceHandle - Child resource handle.
+ *
+ */
+ public OcResourceHandle bindResourceToGroup(OcResource resource,
+ OcResourceHandle collectionHandle)
+ throws OcException {
+ return thingsManagerInterfaceObj.bindResourceToGroup(resource,
+ collectionHandle);
+ }
+
+ /**
+ * API for updating configuration value of multiple things of a target group
+ * or a single thing to a resource server(s).
+ *
+ * <p>
+ * Listener should be set using setConfigurationListener API.
+ * <p>
+ * Listener IConfigurationListener::onUpdateConfigurationsCallback will be
+ * notified when the response of update configuration arrives.
+ *
+ * @param resource
+ * resource representing the target group or the single thing.
+ * It is a pointer of resource instance of Configuration
+ * resource. The resource pointer can be acquired by performing
+ * findResource() function with a dedicated resource type,
+ * "oic.con". Note that, the resource pointer represents not only
+ * a single simple resource but also a collection resource
+ * composing multiple simple resources. In other words, using
+ * these APIs, developers can send a series of requests to
+ * multiple things by calling the corresponding function at once.
+ * @param configurations
+ * ConfigurationUnit: a nickname of attribute of target
+ * resource (e.g., installed location, currency, (IP)address)
+ * Value : a value to be updated. It represents an indicator of
+ * which resource developers want to access and which value
+ * developers want to update. Basically, developers could use a
+ * resource URI to access a specific resource but a resource URI
+ * might be hard for all developers to memorize lots of URIs,
+ * especially in the case of long URIs. To relieve the problem,
+ * Things Configuration introduces a easy-memorizing name, called
+ * ConfigurationName, instead of URI. And ConfigurationValue used
+ * in updateConfiguration() function indicates a value to be
+ * updated. Note that, only one configuration parameter is
+ * supported in this release. Multiple configuration parameters
+ * will be supported in future release.
+ *
+ * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+ * code.
+ *
+ */
+ public OCStackResult updateConfigurations(OcResource resource,
+ Map<String, String> configurations) throws OcException {
+ if (null == configurationListener) {
+ Log.e(LOG_TAG,"updateConfigurations: listener not set!");
+ return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+ }
+
+ OCStackResult result = thingsManagerInterfaceObj.updateConfigurations(resource,
+ configurations);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "updateConfigurations: returned error: " + result.name());
+ }
+
+ return result;
+ }
+
+ /**
+ * API for getting configuration value of multiple things of a target group
+ * or a single thing.To get a value, users need to know a Configuration Name
+ * indicating the target resource. In this release, the Configuration Name
+ * is "configuration".An update value is not needed. After that, users store
+ * them in form of a Vector and then use a getConfigurations() function.
+ *
+ * @param resource
+ * resource representing the target group or the single thing.
+ * @param configurations
+ * ConfigurationUnit: a nickname of attribute of target
+ * resource.
+ *
+ * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+ * code.
+ *
+ */
+ public OCStackResult getConfigurations(OcResource resource,
+ Vector<String> configurations) throws OcException {
+ if (null == configurationListener) {
+ Log.e(LOG_TAG,"getConfigurations: listener not set!");
+ return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+ }
+
+ OCStackResult result = thingsManagerInterfaceObj.getConfigurations(resource,
+ configurations);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "getConfigurations: returned error: " + result.name());
+ }
+
+ return result;
+ }
+
+ /**
+ * API for getting the list of supported configuration units (configurable
+ * parameters). It shows which Configuration Names are supported and their
+ * brief descriptions. This information is provided in JSON format.
+ *
+ * @return Returns the configuration list in JSON format.
+ *
+ */
+ public String getListOfSupportedConfigurationUnits() {
+ return thingsManagerInterfaceObj.getListOfSupportedConfigurationUnits();
+ }
+
+ /**
+ * API for bootstrapping system configuration parameters from a bootstrap
+ * server.
+ * <p>
+ * Listener should be set using setConfigurationListener API.
+ * <p>
+ * Listener IConfigurationListener::onBootStrapCallback will be
+ * notified when the response arrives.
+ *
+ * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+ * code.
+ *
+ */
+ public OCStackResult doBootstrap() {
+ if (null == configurationListener) {
+ Log.e(LOG_TAG,"doBootstrap: listener not set!");
+ return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+ }
+
+ OCStackResult result = thingsManagerInterfaceObj.doBootstrap();
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "doBootstrap: returned error: " + result.name());
+ }
+
+ return result;
+ }
+
+ /**
+ * API to is used to send a request to a server(thing or device) to be
+ * rebooted. On receiving the request, the server attempts to reboot itself
+ * in a deterministic time. The target thing could be a group of multiple
+ * things or a single thing.
+ * <p>
+ * Listener should be set using setDiagnosticsListener API.
+ * <p>
+ * Listener IDiagnosticsListener::onRebootCallback will be
+ * notified when the response arrives.
+ * @param resource
+ * resource pointer representing the target group
+ *
+ * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+ * code.
+ *
+ */
+ public OCStackResult reboot(OcResource resource) throws OcException {
+ if (null == diagnosticsListener) {
+ Log.e(LOG_TAG,"reboot: listener not set!");
+ return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+ }
+
+ OCStackResult result = thingsManagerInterfaceObj.reboot(resource);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "reboot: returned error: " + result.name());
+ }
+
+ return result;
+ }
+
+ /**
+ * API to restore all configuration parameters to default one on
+ * thing(device). All configuration parameters refers Configuration
+ * resource, which they could have been modified for various reasons (e.g.,
+ * for a request to update a value). If developers on the client want to
+ * restore the parameters, just use the factoryReset function.The target
+ * thing could be a group of multiple things or a single thing.
+ *
+ * <p>
+ * Listener should be set using setDiagnosticsListener API.
+ * <p>
+ * Listener IDiagnosticsListener::onFactoryResetCallback will be
+ * notified when the response arrives.
+ *
+ * @param resource
+ * resource pointer representing the target group
+ *
+ * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+ * code.
+ *
+ */
+ public OCStackResult factoryReset(OcResource resource) throws OcException {
+ if (null == diagnosticsListener) {
+ Log.e(LOG_TAG,"factoryReset: listener not set!");
+ return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+ }
+
+ OCStackResult result = thingsManagerInterfaceObj.factoryReset(resource);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "factoryReset: returned error: " + result.name());
+ }
+
+ return result;
+ }
+
+ /**
+ * API for adding a new ActionSet onto a specific resource.
+ *
+ * <p>
+ * Listener should be set using setActionListener API.
+ * <p>
+ * Listener IActionListener::onPutResponseCallback will be
+ * notified when the response of PUT operation arrives.
+ * @param resource
+ * resource pointer of the group resource
+ * @param actionSet
+ * pointer of ActionSet
+ *
+ * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+ * code.
+ *
+ */
+ public OCStackResult addActionSet(OcResource resource, ActionSet actionSet)
+ throws OcException {
+ if (null == actionListener) {
+ Log.e(LOG_TAG,"addActionSet: listener not set!");
+ return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+ }
+
+ OCStackResult result = thingsManagerInterfaceObj
+ .addActionSet(resource, actionSet);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "addActionSet: returned error: " + result.name());
+ }
+
+ return result;
+ }
+
+ /**
+ * API for executing a specific ActionSet belonging to a specific resource.
+ *
+ * <p>
+ * Listener should be set using setActionListener API.
+ * <p>
+ * Listener IActionListener::onPostResponseCallback will be
+ * notified when the response of POST operation arrives.
+ *
+ * @param resource
+ * resource pointer of the group resource
+ * @param actionsetName
+ * ActionSet name for removing the ActionSet
+ *
+ * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+ * code.
+ *
+ */
+ public OCStackResult executeActionSet(OcResource resource,
+ String actionsetName) throws OcException {
+ if (null == actionListener) {
+ Log.e(LOG_TAG,"executeActionSet: listener not set!");
+ return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+ }
+
+ OCStackResult result = thingsManagerInterfaceObj
+ .executeActionSet(resource, actionsetName);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "executeActionSet: returned error: " + result.name());
+ }
+
+ return result;
+ }
+
+ /**
+ * API for executing a specific ActionSet belonging to a specific resource.
+ *
+ * <p>
+ * Listener should be set using setActionListener API.
+ * <p>
+ * Listener IActionListener::onPostResponseCallback will be
+ * notified when the response of POST operation arrives.
+ *
+ * @param resource
+ * resource pointer of the group resource
+ * @param actionsetName
+ * ActionSet name for removing the ActionSet
+ * @param delay
+ * Wait time for the ActionSet execution
+ *
+ * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+ * code.
+ *
+ */
+ public OCStackResult executeActionSet(OcResource resource,
+ String actionsetName, long delay) throws OcException {
+ if (null == actionListener) {
+ Log.e(LOG_TAG,"executeActionSet: listener not set!");
+ return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+ }
+
+ OCStackResult result = thingsManagerInterfaceObj
+ .executeActionSet(resource, actionsetName, delay);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "executeActionSet: returned error: " + result.name());
+ }
+
+ return result;
+ }
+
+ /**
+ * API to cancel the existing ActionSet.
+ *
+ * <p>
+ * Listener should be set using setActionListener API.
+ * <p>
+ * Listener IActionListener::onPostResponseCallback will be
+ * notified when the response of POST operation arrives.
+ * @param resource
+ * resource pointer of the group resource.
+ * @param actionsetName
+ * ActionSet name that has to be cancelled.
+ *
+ * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+ * code.
+ *
+ */
+
+ public OCStackResult cancelActionSet(OcResource resource,
+ String actionsetName) throws OcException {
+ if (null == actionListener) {
+ Log.e(LOG_TAG,"cancelActionSet: listener not set!");
+ return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+ }
+
+ OCStackResult result = thingsManagerInterfaceObj.cancelActionSet(resource,
+ actionsetName);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "cancelActionSet: returned error: " + result.name());
+ }
+
+ return result;
+ }
+
+ /**
+ * API to to get an existing ActionSet belonging to a specific resource.
+ *
+ * <p>
+ * Listener should be set using setActionListener API.
+ * <p>
+ * Listener IActionListener::onPostResponseCallback will be
+ * notified when the response of POST operation arrives.
+ * @param resource
+ * resource pointer of the group resource
+ * @param actionsetName
+ * ActionSet name for removing the ActionSet
+ *
+ * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+ * code.
+ *
+ */
+ public OCStackResult getActionSet(OcResource resource, String actionsetName)
+ throws OcException {
+ if (null == actionListener) {
+ Log.e(LOG_TAG,"getActionSet: listener not set!");
+ return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+ }
+
+ OCStackResult result = thingsManagerInterfaceObj.getActionSet(resource,
+ actionsetName);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "getActionSet: returned error: " + result.name());
+ }
+
+ return result;
+ }
+
+ /**
+ * API to delete an existing ActionSet belonging to a specific resource.
+ *
+ * <p>
+ * Listener should be set using setActionListener API.
+ * <p>
+ * Listener IActionListener::onPutResponseCallback will be
+ * notified when the response of PUT operation arrives.
+ *
+ * @param resource
+ * resource pointer of the group resource
+ * @param actionsetName
+ * ActionSet name for removing the ActionSet
+ *
+ * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+ * code.
+ *
+ */
+ public OCStackResult deleteActionSet(OcResource resource,
+ String actionsetName) throws OcException {
+ if (null == actionListener) {
+ Log.e(LOG_TAG,"deleteActionSet: listener not set!");
+ return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+ }
+
+ OCStackResult result = thingsManagerInterfaceObj.deleteActionSet(resource,
+ actionsetName);
+ if (OCStackResult.OC_STACK_OK != result) {
+ Log.e(LOG_TAG, "deleteActionSet: returned error: " + result.name());
+ }
+
+ return result;
+ }
+
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file ThingsManagerCallback.java
+ *
+ * @brief This file provides a class for a set of callback functions for group management,
+ * synchronization of group, configuration of things, and diagnostics
+ * about things.
+ *
+ */
+
+package org.iotivity.service.tm;
+
+import java.util.Vector;
+
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+
+import android.util.Log;
+
+/**
+ * This class provides a set of callback functions for group management,
+ * synchronization of group, configuration of things, and diagnostics
+ * about things.
+ *
+ */
+class ThingsManagerCallback {
+
+ private IFindCandidateResourceListener resourceListener;
+ private ISubscribePresenceListener presenceListener;
+ private IFindGroupListener groupListener;
+ private IConfigurationListener configurationListener;
+ private IDiagnosticsListener diagnosticsListener;
+ private IActionListener actionListener;
+ private static ThingsManagerCallback thingsManagerCallbackInterfaceObj;
+
+ private ThingsManagerCallback() {
+ }
+
+ /**
+ * Function for Getting instance of ThingsManagerCallback object.
+ *
+ * @return ThingsManagerCallback instance.
+ *
+ */
+ public static synchronized ThingsManagerCallback getInstance() {
+ if (null == thingsManagerCallbackInterfaceObj) {
+ thingsManagerCallbackInterfaceObj = new ThingsManagerCallback();
+ }
+ return thingsManagerCallbackInterfaceObj;
+ }
+
+ /**
+ * Register listener for findCandidateResource callback.
+ *
+ * @param listener
+ * interface for getting notification when resources are
+ * discovered in network.
+ *
+ */
+ public void registerFindCandidateResourceListener(
+ IFindCandidateResourceListener listener) {
+ resourceListener = listener;
+ }
+
+ /**
+ * Register listener for subscribeCollectionPresence callback.
+ *
+ * @param listener
+ * interface for getting notification regarding child resource
+ * presence status.
+ *
+ */
+ public void registerSubscribePresenceListener(
+ ISubscribePresenceListener listener) {
+ presenceListener = listener;
+ }
+
+ /**
+ * Register listener for find group callback.
+ *
+ * @param listener
+ * interface for getting notification on whether the group is
+ * found or not.
+ *
+ */
+ public void registerGroupListener(IFindGroupListener listener) {
+ groupListener = listener;
+ }
+
+ /**
+ * Register listener for updateConfigurations and getConfigurations
+ * callback.
+ *
+ * @param listener
+ * interface for getting notification on configuration values
+ * information or when configuration value is updated for
+ * multiple things of a target group or a single thing.
+ *
+ */
+ public void registerConfigurationListener(IConfigurationListener listener) {
+ configurationListener = listener;
+ }
+
+ /**
+ * Register listener for doBootstrap, reboot and factoryReset callbacks.
+ *
+ * @param listener
+ * interface for receiving asynchronous response for diagnostic
+ * feature APIs.
+ *
+ */
+ public void registerDiagnosticsListener(IDiagnosticsListener listener) {
+ diagnosticsListener = listener;
+ }
+
+ /**
+ * Register listener for getActionSet, executeActionSet and deleteActionSet
+ * callback.
+ *
+ * @param listener
+ * interface for receiving the callback for the GET, PUT and
+ * POST requested actions.
+ *
+ */
+ public void registerActionListener(IActionListener listener) {
+ actionListener = listener;
+ }
+
+ /**
+ * Unregister listener for findCandidateResource callback.
+ *
+ */
+ public void unregisterFindCandidateResourceListener() {
+ resourceListener = null;
+ }
+
+ /**
+ * Unregister listener for subscribeCollectionPresence callback.
+ *
+ */
+ public void unregisterSubscribePresenceListener() {
+ presenceListener = null;
+ }
+
+ /**
+ * Unregister listener for find group callback.
+ *
+ */
+ public void unregisterGroupListener() {
+ groupListener = null;
+ }
+
+ /**
+ * Unregister listener for updateConfigurations and getConfigurations
+ * callback.
+ *
+ */
+ public void unregisterConfigurationListener() {
+ configurationListener = null;
+ }
+
+ /**
+ * Unregister listener for doBootstrap, reboot and factoryReset callbacks.
+ *
+ */
+ public void unregisterDiagnosticsListener() {
+ diagnosticsListener = null;
+ }
+
+ /**
+ * Unregister listener for getActionSet, executeActionSet and
+ * deleteActionSet callback.
+ *
+ */
+ public void unregisterActionListener() {
+ actionListener = null;
+ }
+
+ /**
+ * This callback method will be called whenever resource is discovered in
+ * the network.
+ *
+ * @param resources
+ * List of resources discovered in the network
+ *
+ */
+ public void onResourceCallback(Vector<OcResource> resources) {
+ if (null != resourceListener)
+ resourceListener.onResourceCallback(resources);
+ }
+
+ /**
+ * This callback method is called when a response for the executeActionSet
+ * or deleteActionSet request just arrives.
+ *
+ * @param headerOptions
+ * It comprises of optionID and optionData as members.
+ * @param rep
+ * Configuration parameters are carried as a pair of attribute
+ * key and value in a form of OCRepresentation instance.
+ * @param errorValue
+ * error code.
+ *
+ */
+ public void onPostResponseCallback(Vector<OcHeaderOption> headerOptions,
+ OcRepresentation rep, int errorValue) {
+ if (null != actionListener)
+ actionListener.onPostResponseCallback(headerOptions, rep,
+ errorValue);
+ }
+
+ /**
+ * This callback method is called when a response for the addActionSet
+ * request just arrives.
+ *
+ * @param headerOptions
+ * It comprises of optionID and optionData as members.
+ * @param rep
+ * Configuration parameters are carried as a pair of attribute
+ * key and value in a form of OCRepresentation instance.
+ * @param errorValue
+ * error code.
+ *
+ */
+ public void onPutResponseCallback(Vector<OcHeaderOption> headerOptions,
+ OcRepresentation rep, int errorValue) {
+ if (null != actionListener)
+ actionListener
+ .onPutResponseCallback(headerOptions, rep, errorValue);
+ }
+
+ /**
+ * This callback method is called when a response for the getActionSet
+ * request just arrives.
+ *
+ * @param headerOptions
+ * It comprises of optionID and optionData as members.
+ * @param rep
+ * Configuration parameters are carried as a pair of attribute
+ * key and value in a form of OCRepresentation instance.
+ * @param errorValue
+ * error code.
+ *
+ */
+ public void onGetResponseCallback(Vector<OcHeaderOption> headerOptions,
+ OcRepresentation rep, int errorValue) {
+ if (null != actionListener)
+ actionListener
+ .onGetResponseCallback(headerOptions, rep, errorValue);
+ }
+
+ /**
+ * This callback method is called when a response for the
+ * updateConfigurations request just arrives.
+ *
+ * @param headerOptions
+ * It comprises of optionID and optionData as members.
+ * @param rep
+ * Configuration parameters are carried as a pair of attribute
+ * key and value in a form of OCRepresentation instance.
+ * @param errorValue
+ * error code.
+ *
+ */
+ public void onUpdateConfigurationsCallback(
+ Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+ int errorValue) {
+ if (null != configurationListener)
+ configurationListener.onUpdateConfigurationsCallback(headerOptions,
+ rep, errorValue);
+ }
+
+ /**
+ * This callback method is called when a response for the getConfigurations
+ * request just arrives.
+ *
+ * @param headerOptions
+ * It comprises of optionID and optionData as members.
+ * @param rep
+ * Configuration parameters are carried as a pair of attribute
+ * key and value in a form of OCRepresentation instance.
+ * @param errorValue
+ * error code.
+ *
+ */
+ public void onGetConfigurationsCallback(
+ Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+ int errorValue) {
+ if (null != configurationListener)
+ configurationListener.onGetConfigurationsCallback(headerOptions,
+ rep, errorValue);
+ }
+
+ /**
+ * This callback method is called when a response for the doBootstrap
+ * request just arrives.
+ *
+ * @param headerOptions
+ * It comprises of optionID and optionData as members.
+ * @param rep
+ * Configuration parameters are carried as a pair of attribute
+ * key and value in a form of OCRepresentation instance.
+ * @param errorValue
+ * error code.
+ *
+ */
+ public void onBootStrapCallback(Vector<OcHeaderOption> headerOptions,
+ OcRepresentation rep, int errorValue) {
+ if (null != configurationListener) {
+ Log.i("ThingsManagerCallback : onBootStrapCallback",
+ "Received Callback from JNI");
+ configurationListener.onBootStrapCallback(headerOptions, rep,
+ errorValue);
+ }
+ }
+
+ /**
+ * This callback method is called when a response for the reboot request
+ * just arrives.
+ *
+ * @param headerOptions
+ * It comprises of optionID and optionData as members.
+ * @param rep
+ * Configuration parameters are carried as a pair of attribute
+ * key and value in a form of OCRepresentation instance.
+ * @param errorValue
+ * error code.
+ *
+ */
+ public void onRebootCallback(Vector<OcHeaderOption> headerOptions,
+ OcRepresentation rep, int errorValue) {
+ if (null != diagnosticsListener) {
+ Log.i("ThingsManagerCallback : onRebootCallback",
+ "Received Callback from JNI");
+ diagnosticsListener
+ .onRebootCallback(headerOptions, rep, errorValue);
+ }
+ }
+
+ /**
+ * This callback method is called when a response for the factoryReset
+ * request just arrives.
+ *
+ * @param headerOptions
+ * It comprises of optionID and optionData as members.
+ * @param rep
+ * Configuration parameters are carried as a pair of attribute
+ * key and value in a form of OCRepresentation instance.
+ * @param errorValue
+ * error code.
+ *
+ */
+ public void onFactoryResetCallback(Vector<OcHeaderOption> headerOptions,
+ OcRepresentation rep, int errorValue) {
+ if (null != diagnosticsListener) {
+ Log.i("ThingsManagerCallback : onFactoryResetCallback",
+ "Received Callback from JNI");
+ diagnosticsListener.onFactoryResetCallback(headerOptions, rep,
+ errorValue);
+ }
+ }
+
+ /**
+ * This callback method is called to notify whether group is found or not.
+ *
+ * @param resource
+ * Resource URI
+ *
+ */
+ public void onGroupFindCallback(OcResource resource) {
+ if (null != groupListener) {
+ Log.i("ThingsManagerCallback : onGroupFindCallback",
+ "Received Callback from JNI");
+ groupListener.onGroupFindCallback(resource);
+ }
+ }
+
+ /**
+ * This callback method is called for child resource presence status.
+ *
+ * @param resource
+ * URI of resource.
+ * @param result
+ * error code.
+ *
+ */
+ public void onPresenceCallback(String resource, OCStackResult result) {
+ if (null != presenceListener) {
+ Log.i("ThingsManagerCallback : onPresenceCallback",
+ "Received Callback from JNI");
+ presenceListener.onPresenceCallback(resource, result);
+ }
+ }
+
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+/**
+ * @file ThingsManagerInterface.java
+ *
+ * @brief This file provides a class which acts as an interface for Things Manager API calls between
+ * ThingsManager and ThingsManagerNativeInterface
+ *
+ */
+
+package org.iotivity.service.tm;
+
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Vector;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.OcResourceHandle;
+
+import android.util.Log;
+
+/**
+ * This class acts as an interface for Things Manager API calls between
+ * ThingsManager and ThingsManagerNativeInterface
+ *
+ */
+class ThingsManagerInterface {
+
+ private IFindCandidateResourceListener resourceListener;
+ private ISubscribePresenceListener presenceListener;
+ private IFindGroupListener groupListener;
+ private IConfigurationListener configurationListener;
+ private static ThingsManagerInterface thingsManagerInterfaceObj;
+
+ private ThingsManagerInterface() {
+ }
+
+ /**
+ * Function for Getting instance of ThingsManagerInterface object.
+ *
+ * @return ThingsManagerInterface instance.
+ *
+ */
+ public static synchronized ThingsManagerInterface getInstance() {
+ if (null == thingsManagerInterfaceObj) {
+ thingsManagerInterfaceObj = new ThingsManagerInterface();
+ }
+ return thingsManagerInterfaceObj;
+ }
+
+ /**
+ * Register listener for findCandidateResource callback.
+ *
+ * @param listener
+ * interface for getting notification when resources are
+ * discovered in network.
+ *
+ */
+ public void registerFindCandidateResourceListener(
+ IFindCandidateResourceListener listener) {
+ resourceListener = listener;
+ }
+
+ /**
+ * Register listener for subscribeCollectionPresence callback.
+ *
+ * @param listener
+ * interface for getting notification regarding child resource
+ * presence status.
+ *
+ */
+ public void registerSubscribePresenceListener(
+ ISubscribePresenceListener listener) {
+ presenceListener = listener;
+ }
+
+ /**
+ * Register listener for register group and find group callback.
+ *
+ * @param listener
+ * interface for getting notification on whether the group is
+ * found or not.
+ *
+ */
+ public void registerGroupListener(IFindGroupListener listener) {
+ groupListener = listener;
+ }
+
+ /**
+ * Register listener for updateConfigurations and getConfigurations
+ * callback.
+ *
+ * @param listener
+ * interface for getting notification on configuration values
+ * information or when configuration value is updated for
+ * multiple things of a target group or a single thing.
+ *
+ */
+ public void registerConfigurationListener(IConfigurationListener listener) {
+ configurationListener = listener;
+ }
+
+ /**
+ * Unregister listener for findCandidateResource callback.
+ *
+ */
+ public void unregisterFindCandidateResourceListener() {
+ resourceListener = null;
+ }
+
+ /**
+ * Unregister listener for subscribeCollectionPresence callback.
+ *
+ */
+ public void unregisterSubscribePresenceListener() {
+ presenceListener = null;
+ }
+
+ /**
+ * Unregister listener for registerGroup and findGroup callback.
+ *
+ */
+ public void unregisterGroupListener() {
+ groupListener = null;
+ }
+
+ /**
+ * Unregister listener for updateConfigurations and getConfigurations
+ * callback.
+ *
+ */
+ public void unregisterConfigurationListener() {
+ configurationListener = null;
+ }
+
+ /**
+ * API for discovering candidate resources with waiting delay. Listener
+ * <p>
+ * IFindCandidateResourceListener::onResourceCallback will be notified
+ * when resource is discovered in network.
+ * </p>
+ *
+ * @param resourceTypes
+ * required resource types(called "candidate")
+ * @param waitTime
+ * Time duration in seconds to find the resources in network
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ *
+ */
+ public OCStackResult findCandidateResources(Vector<String> resourceTypes,
+ int waitTime) {
+ OCStackResult result;
+ if (null == resourceListener) {
+ result = OCStackResult.OC_STACK_ERROR;
+ } else {
+ int ordinal = ThingsManagerNativeInterface.findCandidateResources(
+ resourceTypes, waitTime);
+ result = OCStackResult.conversion(ordinal);
+ }
+ return result;
+ }
+
+ /**
+ * API for subscribing child's state. Listener
+ * <p>
+ * ISubscribePresenceListener::onPresenceCallback will be notified for
+ * resource presence status
+ * </p>
+ *
+ * @param resource
+ * collection resource for subscribing presence of all child
+ * resources
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ *
+ */
+ public OCStackResult subscribeCollectionPresence(OcResource resource)
+ throws OcException {
+ String LOG_TAG = this.getClass().getSimpleName();
+
+ OCStackResult result;
+ if (null == presenceListener) {
+ result = OCStackResult.OC_STACK_ERROR;
+ } else {
+
+ int ordinal = ThingsManagerNativeInterface
+ .subscribeCollectionPresence(resource);
+ Log.i(LOG_TAG, "Ordinal value = : " + ordinal);
+ result = OCStackResult.conversion(ordinal);
+ }
+ return result;
+ }
+
+ /**
+ * API for finding a specific remote group when a resource tries to join a
+ * group.
+ * <p>
+ * IFindGroupListener::onGroupFindCallback will be called to notify
+ * whether requested group found or not.
+ * </p>
+ *
+ * @param resourceTypes
+ * resource types of a group to find and join
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ *
+ */
+ public OCStackResult findGroup(Vector<String> resourceTypes) {
+ OCStackResult result;
+ if (null == groupListener) {
+ result = OCStackResult.OC_STACK_ERROR;
+ } else {
+ int ordinal = ThingsManagerNativeInterface.findGroup(resourceTypes);
+ result = OCStackResult.conversion(ordinal);
+ }
+ return result;
+ }
+
+ /**
+ * API for creating a new group.
+ *
+ * @param resourceType
+ * resource type of a group to create
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ *
+ */
+ public OCStackResult createGroup(String resourceType) {
+ OCStackResult result;
+ int ordinal = ThingsManagerNativeInterface.createGroup(resourceType);
+ result = OCStackResult.conversion(ordinal);
+ return result;
+ }
+
+ /**
+ * API for joining a group. This API is used when a resource that has a
+ * group tries to find a specific remote resource and makes it join a group.
+ *
+ * @param resourceType
+ * resource type of a group to join.
+ * @param resourceHandle
+ * resource handle to join a group.
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ *
+ */
+ public OCStackResult joinGroup(String resourceType,
+ OcResourceHandle resourceHandle) {
+ OCStackResult result;
+
+ int ordinal = ThingsManagerNativeInterface.joinGroup(resourceType,
+ resourceHandle);
+ result = OCStackResult.conversion(ordinal);
+
+ return result;
+ }
+
+ /**
+ * API for joining a group. This API is used when a resource that doesn't
+ * have a group tries to find and join a specific remote group.
+ *
+ * @param resource
+ * group resource to join.
+ * @param resourceHandle
+ * resource handle to join a group.
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ *
+ */
+ public OCStackResult joinGroup(OcResource resource,
+ OcResourceHandle resourceHandle) throws OcException {
+
+ OCStackResult result;
+ int ordinal = ThingsManagerNativeInterface.joinGroup(resource,
+ resourceHandle);
+ result = OCStackResult.conversion(ordinal);
+
+ return result;
+ }
+
+ /**
+ * API for leaving a joined group.
+ *
+ * @param resourceType
+ * resource type of a group to leave.
+ * @param resourceHandle
+ * resource handle to leave a group.
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ *
+ */
+ public OCStackResult leaveGroup(String resourceType,
+ OcResourceHandle resourceHandle) {
+
+ OCStackResult result;
+ int ordinal = ThingsManagerNativeInterface.leaveGroup(resourceType,
+ resourceHandle);
+ result = OCStackResult.conversion(ordinal);
+
+ return result;
+ }
+
+ /**
+ * API for leaving a joined group.
+ *
+ * @param resource
+ * resource of a group to leave.
+ * @param resourceType
+ * resource type of a group to leave.
+ * @param resourceHandle
+ * resource handle to leave a group.
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ *
+ */
+ public OCStackResult leaveGroup(OcResource resource, String resourceType,
+ OcResourceHandle resourceHandle) {
+
+ OCStackResult result;
+ int ordinal = ThingsManagerNativeInterface.leaveGroup(resource,
+ resourceType, resourceHandle);
+ result = OCStackResult.conversion(ordinal);
+
+ return result;
+ }
+
+ /**
+ * API for deleting a group.
+ *
+ * @param collectionResourceType
+ * resource type of a group to delete.
+ *
+ */
+ public void deleteGroup(String collectionResourceType) {
+ ThingsManagerNativeInterface.deleteGroup(collectionResourceType);
+ }
+
+ /**
+ * API for getting a list of joined groups.
+ *
+ * @return Returns group resource type and group resource handle as a map
+ * table.
+ *
+ */
+ public Map<String, OcResourceHandle> getGroupList() {
+ return ThingsManagerNativeInterface.getGroupList();
+ }
+
+ /**
+ * API for register and bind resource to group.
+ *
+ * @param resource
+ * resource for register and bind to group. It has all data.
+ * @param collectionHandle
+ * collection resource handle. It will be added child resource.
+ *
+ * @return OcResourceHandle - Child resource handle.
+ */
+ public OcResourceHandle bindResourceToGroup(OcResource resource,
+ OcResourceHandle collectionHandle)
+ throws OcException {
+ return ThingsManagerNativeInterface.bindResourceToGroup(
+ resource, collectionHandle);
+ }
+
+ /**
+ * API for updating configuration value of multiple things of a target group
+ * or a single thing.
+ *
+ * @param resource
+ * resource representing the target group or the single thing.
+ * @param configurations
+ * ConfigurationUnit: a nickname of attribute of target
+ * resource (e.g., installed location, currency, (IP)address)
+ * Value : a value to be updated
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ *
+ */
+ public OCStackResult updateConfigurations(OcResource resource,
+ Map<String, String> configurations) throws OcException {
+ OCStackResult result;
+ if (null == configurationListener) {
+ result = OCStackResult.OC_STACK_ERROR;
+ } else {
+ int ordinal = ThingsManagerNativeInterface.updateConfigurations(
+ resource, configurations);
+ result = OCStackResult.conversion(ordinal);
+ }
+ return result;
+
+ }
+
+ /**
+ * API for getting configuration value of multiple things of a target group
+ * or a single thing.
+ *
+ * @param resource
+ * resource representing the target group or the single thing.
+ * @param configurations
+ * ConfigurationUnit: a nickname of attribute of target
+ * resource.
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ *
+ */
+ public OCStackResult getConfigurations(OcResource resource,
+ Vector<String> configurations) throws OcException {
+ OCStackResult result;
+ if (null == configurationListener) {
+ result = OCStackResult.OC_STACK_ERROR;
+ } else {
+ int ordinal = ThingsManagerNativeInterface.getConfigurations(
+ resource, configurations);
+ result = OCStackResult.conversion(ordinal);
+ }
+ return result;
+ }
+
+ /**
+ * API for showing the list of supported configuration units (configurable
+ * parameters)
+ *
+ * @return Returns the configuration list in JSON format.
+ *
+ */
+ public String getListOfSupportedConfigurationUnits() {
+
+ return ThingsManagerNativeInterface
+ .getListOfSupportedConfigurationUnits();
+ }
+
+ /**
+ * API for bootstrapping system configuration parameters from a bootstrap
+ * server.
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ */
+ public OCStackResult doBootstrap() {
+
+ OCStackResult result;
+ int ordinal = ThingsManagerNativeInterface.doBootstrap();
+ result = OCStackResult.conversion(ordinal);
+
+ return result;
+ }
+
+ /**
+ * API to let thing(device) reboot. The target thing could be a group of
+ * multiple things or a single thing.
+ *
+ * @param resource
+ * resource pointer representing the target group
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success
+ */
+ public OCStackResult reboot(OcResource resource) throws OcException {
+
+ OCStackResult result;
+ int ordinal = ThingsManagerNativeInterface.reboot(resource);
+ result = OCStackResult.conversion(ordinal);
+
+ return result;
+ }
+
+ /**
+ * API for factory reset on thing(device). The target thing could be a group
+ * of multiple things or a single thing.
+ *
+ * @param resource
+ * resource pointer representing the target group
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ */
+ public OCStackResult factoryReset(OcResource resource) throws OcException {
+
+ OCStackResult result;
+ int ordinal = ThingsManagerNativeInterface.factoryReset(resource);
+ result = OCStackResult.conversion(ordinal);
+
+ return result;
+ }
+
+ /**
+ * API for adding an Action Set. Callback is called when the response of PUT
+ * operation arrives.
+ *
+ * @param resource
+ * resource pointer of the group resource
+ * @param actionSet
+ * pointer of Action Set
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ */
+ public OCStackResult addActionSet(OcResource resource, ActionSet actionSet)
+ throws OcException {
+
+ int ordinal = ThingsManagerNativeInterface.addActionSet(resource,
+ actionSet);
+
+ return OCStackResult.conversion(ordinal);
+ }
+
+ /**
+ * API for executing the Action Set. Callback is called when the response of
+ * POST operation arrives.
+ *
+ * @param resource
+ * resource pointer of the group resource
+ * @param actionsetName
+ * Action Set name for removing the Action set
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ */
+ public OCStackResult executeActionSet(OcResource resource,
+ String actionsetName) throws OcException {
+
+ int ordinal = ThingsManagerNativeInterface.executeActionSet(resource,
+ actionsetName);
+
+ return OCStackResult.conversion(ordinal);
+ }
+
+ /**
+ * API for executing the Action Set. Callback is called when the response of
+ * POST operation arrives.
+ *
+ * @param resource
+ * resource pointer of the group resource
+ * @param actionsetName
+ * Action Set name for removing the Action set
+ * @param delay
+ * waiting time for until action set run.
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ */
+ public OCStackResult executeActionSet(OcResource resource,
+ String actionsetName, long delay) throws OcException {
+
+ OCStackResult result;
+ int ordinal = ThingsManagerNativeInterface.executeActionSet(resource,
+ actionsetName, delay);
+ result = OCStackResult.conversion(ordinal);
+
+ return result;
+ }
+
+ /**
+ * API for cancelling the Action Set. Callback is called when the response
+ * of POST operation arrives.
+ *
+ * @param resource
+ * resource pointer of the group resource
+ * @param actionsetName
+ * Action Set name for removing the Action set
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ */
+ public OCStackResult cancelActionSet(OcResource resource,
+ String actionsetName) throws OcException {
+
+ OCStackResult result;
+ int ordinal = ThingsManagerNativeInterface.cancelActionSet(resource,
+ actionsetName);
+ result = OCStackResult.conversion(ordinal);
+
+ return result;
+ }
+
+ /**
+ * API for reading the Action Set. Callback is called when the response of
+ * GET operation arrives.
+ *
+ * @param resource
+ * resource pointer of the group resource
+ * @param actionsetName
+ * Action Set name for removing the Action set
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ */
+ public OCStackResult getActionSet(OcResource resource, String actionsetName)
+ throws OcException {
+
+ OCStackResult result;
+ int ordinal = ThingsManagerNativeInterface.getActionSet(resource,
+ actionsetName);
+ result = OCStackResult.conversion(ordinal);
+
+ return result;
+ }
+
+ /**
+ * API for removing the action set. Callback is called when the response of
+ * POST operation arrives.
+ *
+ * @param resource
+ * resource pointer of the group resource
+ * @param actionsetName
+ * Action Set name for removing the Action set
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ */
+ public OCStackResult deleteActionSet(OcResource resource,
+ String actionsetName) throws OcException {
+
+ OCStackResult result;
+ int ordinal = ThingsManagerNativeInterface.deleteActionSet(resource,
+ actionsetName);
+ result = OCStackResult.conversion(ordinal);
+
+ return result;
+ }
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics 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.
+ *
+ ******************************************************************/
+/**
+ * @file ThingsManagerNativeInterface.java
+ *
+ * @brief This file provides a class which provides a set of native functions relating to group
+ * management, synchronization of group, configuration of things, and
+ * diagnostics about things.
+ */
+
+package org.iotivity.service.tm;
+
+import java.util.Map;
+import java.util.Vector;
+
+import org.iotivity.base.OcResource;
+import org.iotivity.base.OcResourceHandle;
+
+/**
+ * This class provides a set of native functions relating to group
+ * management, synchronization of group, configuration of things, and
+ * diagnostics about things.
+ *
+ */
+class ThingsManagerNativeInterface {
+ /**
+ * Native function for discoverying candidate resources.
+ *
+ * @param resourceTypes
+ * - required resource types(called "candidate")
+ * @param waitTime
+ * - Delay time in seconds to add before starting to find the
+ * resources in network.
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ *
+ */
+ public static native int findCandidateResources(
+ Vector<String> resourceTypes, int waitTime);
+
+ /**
+ * Native function for subscribing child's state.
+ *
+ * @param resource
+ * - collection resource for subscribing presence of all child
+ * resources.
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ *
+ */
+ public static native int subscribeCollectionPresence(OcResource resource);
+
+ /**
+ * Native function for register and bind resource to group.
+ *
+ * @param resource
+ * - resource for register and bind to group. It has all data.
+ * @param collectionHandle
+ * - collection resource handle. It will be added child resource.
+ *
+ * @return OcResourceHandle - Child resource handle.
+ *
+ */
+ public static native OcResourceHandle bindResourceToGroup(OcResource resource,
+ OcResourceHandle collectionHandle);
+
+ /**
+ * Native function for finding a specific remote group when a resource tries
+ * to join a group. Callback is called when a group is found or not.
+ *
+ * @param collectionResourceTypes
+ * - resource types of a group to find and join
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ *
+ */
+ public static native int findGroup(Vector<String> collectionResourceTypes);
+
+ /**
+ * Native function for creating a new group.
+ *
+ * @param collectionResourceType
+ * - resource type of a group to create
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ */
+ public static native int createGroup(String collectionResourceType);
+
+ /**
+ * Native function for joining a group. This API is used when a resource
+ * that has a group tries to find a specific remote resource and makes it
+ * join a group.
+ *
+ * @param collectionResourceType
+ * - resource type of a group to join.
+ * @param resourceHandle
+ * - resource handle to join a group.
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ *
+ */
+ public static native int joinGroup(String collectionResourceType,
+ OcResourceHandle resourceHandle);
+
+ /**
+ * Native function for joining a group. This is used when a resource that
+ * doesn't have a group tries to find and join a specific remote group.
+ *
+ * @param resource
+ * - group resource to join.
+ * @param resourceHandle
+ * - resource handle to join a group.
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ *
+ */
+ public static native int joinGroup(OcResource resource,
+ OcResourceHandle resourceHandle);
+
+ /**
+ * Native function for leaving a joined group.
+ *
+ * @param collectionResourceType
+ * - resource type of a group to leave.
+ * @param resourceHandle
+ * - resource handle to leave a group.
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ *
+ */
+ public static native int leaveGroup(String collectionResourceType,
+ OcResourceHandle resourceHandle);
+
+ /**
+ * Native function for leaving a joined group.
+ *
+ * @param resource
+ * - resource of a group to leave.
+ * @param collectionResourceType
+ * - resource type of a group to leave.
+ * @param resourceHandle
+ * - resource handle to leave a group.
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ *
+ */
+ public static native int leaveGroup(OcResource resource,
+ String collectionResourceType, OcResourceHandle resourceHandle);
+
+ /**
+ * Native function for deleting a group.
+ *
+ * @param collectionResourceType
+ * - resource type of a group to delete.
+ *
+ *
+ */
+ public static native void deleteGroup(String collectionResourceType);
+
+ /**
+ * Native function for getting a list of joined groups.
+ *
+ * @return Returns group resource type and group resource handle as a map
+ * table.
+ *
+ */
+ public static native Map<String, OcResourceHandle> getGroupList();
+
+ /**
+ * Native function for updating configuration value of multiple things of a
+ * target group or a single thing.
+ *
+ * @param resource
+ * - resource representing the target group or the single thing.
+ * @param configurations
+ * - ConfigurationUnit: a nickname of attribute of target
+ * resource (e.g., installed location, currency, (IP)address)
+ * Value : a value to be updated
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ *
+ */
+ public static native int updateConfigurations(OcResource resource,
+ Map<String, String> configurations);
+
+ /**
+ * Native function for getting configuration value of multiple things of a
+ * target group or a single thing.
+ *
+ * @param resource
+ * - resource representing the target group or the single thing.
+ * @param configurations
+ * - ConfigurationUnit: a nickname of attribute of target
+ * resource.
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ *
+ */
+ public static native int getConfigurations(OcResource resource,
+ Vector<String> configurations);
+
+ /**
+ * Native function for showing the list of supported configuration units
+ * (configurable parameters)
+ *
+ * @return Returns the configuration list in JSON format.
+ *
+ */
+ public static native String getListOfSupportedConfigurationUnits();
+
+ /**
+ * Native function for bootstrapping system configuration parameters from a
+ * bootstrap server.
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ */
+ public static native int doBootstrap();
+
+ /**
+ * Native function to let thing(device) reboot. The target thing could be a
+ * group of multiple things or a single thing.
+ *
+ * @param resource
+ * - resource pointer representing the target group
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success
+ */
+ public static native int reboot(OcResource resource);
+
+ /**
+ * Native function for factory reset on thing(device). The target thing
+ * could be a group of multiple things or a single thing.
+ *
+ * @param resource
+ * - resource pointer representing the target group
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ */
+ public static native int factoryReset(OcResource resource);
+
+ /**
+ * Native function for adding an Action Set. Callback is called when the
+ * response of PUT operation arrives.
+ *
+ * @param resource
+ * - resource pointer of the group resource
+ * @param actionSet
+ * - pointer of Action Set
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ */
+ public static native int addActionSet(OcResource resource,
+ ActionSet actionSet);
+
+ /**
+ * Native function for executing the Action Set. Callback is called when the
+ * response of POST operation arrives.
+ *
+ * @param resource
+ * - resource pointer of the group resource
+ * @param actionsetName
+ * - Action Set name for removing the Action set
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ */
+ public static native int executeActionSet(OcResource resource,
+ String actionsetName);
+
+ /**
+ * Native function for executing the Action Set. Callback is called when the
+ * response of POST operation arrives.
+ *
+ * @param resource
+ * - resource pointer of the group resource
+ * @param actionsetName
+ * - Action Set name for removing the Action set
+ * @param delay
+ * - waiting time for until action set run.
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ */
+ public static native int executeActionSet(OcResource resource,
+ String actionsetName, long delay);
+
+ /**
+ * Native function for cancelling the Action Set. Callback is called when
+ * the response of POST operation arrives.
+ *
+ * @param resource
+ * - resource pointer of the group resource
+ * @param actionsetName
+ * - Action Set name for removing the Action set
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ */
+ public static native int cancelActionSet(OcResource resource,
+ String actionsetName);
+
+ /**
+ * Native function for reading the Action Set. Callback is called when the
+ * response of GET operation arrives.
+ *
+ * @param resource
+ * - resource pointer of the group resource
+ * @param actionsetName
+ * - Action Set name for removing the Action set
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ */
+ public static native int getActionSet(OcResource resource,
+ String actionsetName);
+
+ /**
+ * Native function for removing the action set. Callback is called when the
+ * response of POST operation arrives.
+ *
+ * @param resource
+ * - resource pointer of the group resource
+ * @param actionsetName
+ * - Action Set name for removing the Action set
+ *
+ * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+ * if success.
+ */
+ public static native int deleteActionSet(OcResource resource,
+ String actionsetName);
+}
--- /dev/null
+package org.iotivity.service.tm;
+
+import android.util.Log;
+
+/**
+ * This class provides time-related information used for
+ * scheduled/recursive group action features. Along with time-related
+ * variables, it also provides various useful functionality including
+ * translating time to second unit
+ */
+public class Time {
+
+ public enum ActionSetType {
+ NONE, SCHEDULED, RECURSIVE
+ }
+
+ public int mYear = 0;
+ public int mMonth = 0;
+ public int mDay = 0;
+ public int mHour = 0;
+ public int mMin = 0;
+ public int mSec = 0;
+ public int mDayOfWeek = 0;
+
+ private ActionSetType mType = ActionSetType.NONE;
+ private long mDelay = 0;
+
+ private final String LOG_TAG = this.getClass().getSimpleName();
+
+ /**
+ * Set the time for executing ActionSet.
+ *
+ * @param year
+ * Year to be set
+ * @param month
+ * Month of the year to be set
+ * @param day
+ * Day of the month to be set
+ * @param hour
+ * Hour to be set
+ * @param min
+ * Minute to be set
+ * @param sec
+ * Second to be set
+ * @param dayOfTheWeek
+ * Day of the week to be set
+ *
+ */
+ public void setTime(int year, int month, int day, int hour, int min,
+ int sec, int dayOfTheWeek) {
+ if (year < 0 || month < 0 || day < 0 || hour < 0 || min < 0 || sec < 0
+ || dayOfTheWeek < 0) {
+ Log.e(LOG_TAG, "Input time is invalid");
+ return;
+ }
+
+ year -= 1900;
+ month -= 1;
+
+ mDelay = 0;
+ mYear = year;
+ mMonth = month;
+ mDay = day;
+ mHour = hour;
+ mMin = month;
+ mSec = sec;
+ mDayOfWeek = dayOfTheWeek;
+ mType = ActionSetType.NONE;
+ }
+
+ /**
+ * Set type of ActionSet.
+ *
+ * @param type
+ * Type of ActionSet
+ */
+ public void setType(ActionSetType type) {
+ mType = type;
+ }
+
+ /**
+ * Set day of the week for recursively executing ActionSet.
+ *
+ * @param day
+ * day of the week
+ */
+ public void setDayOfWeekForRecursive(int day) {
+ if (day != -1) {
+ mType = ActionSetType.RECURSIVE;
+ setTime(0, 0, 0, 0, 0, 0, day);
+ }
+ }
+
+ /**
+ * Set the time delay in seconds for executing ActionSet.
+ *
+ * @param seconds
+ * time delay in seconds
+ *
+ */
+ public void setDelay(long seconds) {
+ if (mType != ActionSetType.NONE) {
+ mDelay = seconds;
+ }
+ }
+
+ /**
+ * Get absolute time in seconds.
+ *
+ * @return long - Absolute time in seconds.
+ *
+ */
+ public long getSecAbsTime() {
+ long interval;
+
+ interval = (mHour * 60 * 60);
+ interval += (mMin * 60);
+ interval += (mSec * 1);
+
+ return interval;
+ }
+
+ /**
+ * Get the type of ActionSet.
+ *
+ * @return ActionSetType - Type of ActionSet.
+ *
+ */
+ public ActionSetType getType() {
+ return mType;
+ }
+
+ /**
+ * Get the time delay in seconds set in the ActionSet.
+ *
+ * @return long - Delay in seconds.
+ *
+ */
+ public long getDelay() {
+ return mDelay;
+ }
+}