Merge branch 'master' into easysetup & CBOR changes
authorVinil Jain <vinil.gj@samsung.com>
Thu, 27 Aug 2015 12:53:33 +0000 (18:23 +0530)
committerVinil Jain <vinil.gj@samsung.com>
Thu, 27 Aug 2015 13:00:27 +0000 (18:30 +0530)
Signed-off-by: Vinil Jain <vinil.gj@samsung.com>
Change-Id: I7c3e7fc8a234388aab3c02e33a6010edd4eca04d

81 files changed:
android/android_api/base/src/main/java/org/iotivity/ca/CaIpInterface.java
resource/csdk/connectivity/SConscript
resource/csdk/stack/src/ocstack.c
service/SConscript
service/easy-setup/SConscript [new file with mode: 0644]
service/easy-setup/readme.txt [new file with mode: 0644]
service/easy-setup/sampleapp/SConscript [new file with mode: 0644]
service/easy-setup/sampleapp/android/.gitignore [new file with mode: 0644]
service/easy-setup/sampleapp/android/EasySetup/EasySetupGradle.iml [new file with mode: 0644]
service/easy-setup/sampleapp/android/EasySetup/app/app.iml [new file with mode: 0644]
service/easy-setup/sampleapp/android/EasySetup/app/build.gradle [new file with mode: 0644]
service/easy-setup/sampleapp/android/EasySetup/app/src/main/AndroidManifest.xml [new file with mode: 0644]
service/easy-setup/sampleapp/android/EasySetup/app/src/main/java/org/iotivity/service/easysetup/MainActivity.java [new file with mode: 0644]
service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/drawable-hdpi/background.png [new file with mode: 0644]
service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/drawable-hdpi/cancel.png [new file with mode: 0644]
service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/drawable-hdpi/ic_launcher.png [new file with mode: 0644]
service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/drawable-hdpi/icon.png [new file with mode: 0644]
service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/layout/activity_main.xml [new file with mode: 0644]
service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/menu/main.xml [new file with mode: 0644]
service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/values/dimens.xml [new file with mode: 0644]
service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/values/strings.xml [new file with mode: 0644]
service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/values/styles.xml [new file with mode: 0644]
service/easy-setup/sampleapp/android/EasySetup/build.gradle [new file with mode: 0644]
service/easy-setup/sampleapp/android/EasySetup/easySetupCore-debug/build.gradle [new file with mode: 0644]
service/easy-setup/sampleapp/android/EasySetup/easySetupCore-debug/easySetupCore-debug.iml [new file with mode: 0644]
service/easy-setup/sampleapp/android/EasySetup/iotivity-armeabi-base-debug/build.gradle [new file with mode: 0644]
service/easy-setup/sampleapp/android/EasySetup/iotivity-armeabi-base-debug/iotivity-armeabi-base-debug.iml [new file with mode: 0644]
service/easy-setup/sampleapp/android/EasySetup/settings.gradle [new file with mode: 0644]
service/easy-setup/sampleapp/arduino/thinserver/SConscript [new file with mode: 0644]
service/easy-setup/sampleapp/arduino/thinserver/thinserver.cpp [new file with mode: 0644]
service/easy-setup/sampleapp/linux/richclient/SConscript [new file with mode: 0644]
service/easy-setup/sampleapp/linux/richclient/easysetupsample.cpp [new file with mode: 0644]
service/easy-setup/sdk/common/common.h [new file with mode: 0644]
service/easy-setup/sdk/enrollee/arduino/wifi/networkHandler.cpp [new file with mode: 0644]
service/easy-setup/sdk/enrollee/arduino/wifi/networkHandler.h [new file with mode: 0644]
service/easy-setup/sdk/enrollee/common/inc/easysetup.h [new file with mode: 0644]
service/easy-setup/sdk/enrollee/common/inc/resourceHandler.h [new file with mode: 0644]
service/easy-setup/sdk/enrollee/common/src/easysetup.cpp [new file with mode: 0644]
service/easy-setup/sdk/enrollee/common/src/resourceHandler.cpp [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/.gitignore [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/EasySetupCore/build.gradle [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/EasySetupCore/easySetupCore.iml [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/EasySetupCore/settings.gradle [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/AndroidManifest.xml [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EasySetupCallbackHandler.java [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EasySetupManager.java [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeOnBoardingInfo.java [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/IOnBoardingStatus.java [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/IProvisioningListener.java [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/OnBoardEnrollee.java [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ProvisionEnrollee.java [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/common/EnrolleeDevice.java [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/common/EnrolleeDeviceFactory.java [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/common/OnBoardingConfig.java [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/common/ProvisioningInfo.java [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ip/IPEnrolleeDevice.java [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ip/IPProvisioningInfo.java [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ip/WiFiSoftAPManager.java [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ip/WiFiSoftAPOnBoardingConfig.java [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/res/drawable-hdpi/ic_launcher.png [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/res/values/strings.xml [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/res/values/styles.xml [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/jni/Android.mk [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/jni/Application.mk [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/jni/jni_easy_setup.cpp [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/jni/jni_easy_setup.h [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_easy_setup_jvm.h [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_getter.h [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_object.h [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_setter.h [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_string.h [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_easy_setup_jvm.cpp [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_getter.cpp [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_object.cpp [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_setter.cpp [new file with mode: 0644]
service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_string.cpp [new file with mode: 0644]
service/easy-setup/sdk/mediator/inc/easysetupmgr.h [new file with mode: 0644]
service/easy-setup/sdk/mediator/inc/provisioninghandler.h [new file with mode: 0644]
service/easy-setup/sdk/mediator/src/camutex_pthreads.c [new file with mode: 0644]
service/easy-setup/sdk/mediator/src/easysetupmgr.cpp [new file with mode: 0644]
service/easy-setup/sdk/mediator/src/provisioninghandler.cpp [new file with mode: 0644]

index 040ebbd..a011dfe 100644 (file)
-/******************************************************************
- *
- * Copyright 2014 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 org.iotivity.ca;
-
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.net.ConnectivityManager;
-import android.net.NetworkInfo;
-import android.net.wifi.WifiManager;
-
-public class CaIpInterface {
-    private static Context mContext;
-
-    private CaIpInterface(Context context) {
-        mContext = context;
-        registerIpStateReceiver();
-    }
-
-    private void registerIpStateReceiver() {
-        IntentFilter intentFilter = new IntentFilter();
-        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
-        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
-
-        mContext.registerReceiver(mReceiver, intentFilter);
-    }
-
-    private static BroadcastReceiver mReceiver = new BroadcastReceiver() {
-        @Override
-        public void onReceive(Context context, Intent intent) {
-            if (intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
-                WifiManager.WIFI_STATE_UNKNOWN) == WifiManager.WIFI_STATE_DISABLED) {
-                caIpStateDisabled();
-            } else if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
-                ConnectivityManager manager = (ConnectivityManager)
-                        mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
-                NetworkInfo nwInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
-
-                if(nwInfo.isConnected()) {
-                    caIpStateEnabled();
-                }
-            }
-        }
-    };
-
-    private native static void caIpStateEnabled();
-
-    private native static void caIpStateDisabled();
-}
+/******************************************************************\r
+ *\r
+ * Copyright 2014 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+package org.iotivity.ca;\r
+\r
+import android.content.BroadcastReceiver;\r
+import android.content.Context;\r
+import android.content.Intent;\r
+import android.content.IntentFilter;\r
+import android.net.ConnectivityManager;\r
+import android.net.NetworkInfo;\r
+import android.net.wifi.WifiManager;\r
+import android.util.Log;\r
+\r
+public class CaIpInterface {\r
+    private static Context mContext;\r
+\r
+    public enum WifiAPState{\r
+        WIFI_AP_STATE_DISABLING (10),\r
+        WIFI_AP_STATE_DISABLED (11),\r
+        WIFI_AP_STATE_ENABLING (12),\r
+        WIFI_AP_STATE_ENABLED (13),\r
+        WIFI_AP_STATE_FAILED (14)\r
+        ; // semicolon needed when fields / methods follow\r
+\r
+\r
+        private final int apstate;\r
+\r
+        WifiAPState(int apstate)\r
+        {\r
+            this.apstate = apstate;\r
+        }\r
+        public int getIntValue() {\r
+           return this.apstate;\r
+        }\r
+    }\r
+\r
+    private CaIpInterface(Context context) {\r
+        mContext = context;\r
+        registerIpStateReceiver();\r
+    }\r
+\r
+    private void registerIpStateReceiver() {\r
+        IntentFilter intentFilter = new IntentFilter();\r
+        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);\r
+        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);\r
+        intentFilter.addAction("android.net.wifi.WIFI_AP_STATE_CHANGED");\r
+\r
+        mContext.registerReceiver(mReceiver, intentFilter);\r
+    }\r
+\r
+    private static BroadcastReceiver mReceiver = new BroadcastReceiver() {\r
+        @Override\r
+        public void onReceive(Context context, Intent intent) {\r
+            if (intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,\r
+                WifiManager.WIFI_STATE_UNKNOWN) == WifiManager.WIFI_STATE_DISABLED) {\r
+                caIpStateDisabled();\r
+            } else if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {\r
+                ConnectivityManager manager = (ConnectivityManager)\r
+                        mContext.getSystemService(Context.CONNECTIVITY_SERVICE);\r
+                NetworkInfo nwInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);\r
+\r
+                if(nwInfo.isConnected()) {\r
+                    caIpStateEnabled();\r
+                }\r
+            }\r
+\r
+            if (intent.getAction().equals("android.net.wifi.WIFI_AP_STATE_CHANGED")) {\r
+                if (intent.getIntExtra("wifi_state",\r
+                    WifiAPState.WIFI_AP_STATE_DISABLED.getIntValue())\r
+                    == WifiAPState.WIFI_AP_STATE_DISABLED.getIntValue())\r
+                {\r
+                    caIpStateDisabled();\r
+                }else if(intent.getIntExtra("wifi_state",\r
+                    WifiAPState.WIFI_AP_STATE_DISABLED.getIntValue())\r
+                    == WifiAPState.WIFI_AP_STATE_ENABLED.getIntValue())\r
+                {\r
+                    try {\r
+                        Thread.sleep(1000);\r
+                    } catch (InterruptedException e) {\r
+                        // TODO Auto-generated catch block\r
+                        e.printStackTrace();\r
+                    }\r
+                    caIpStateEnabled();\r
+                }\r
+           }\r
+        }\r
+    };\r
+\r
+    private native static void caIpStateEnabled();\r
+\r
+    private native static void caIpStateDisabled();\r
+}\r
index e68924f..777f7d9 100644 (file)
@@ -57,7 +57,9 @@ else:
                env.AppendUnique(CPPDEFINES = ['NO_IP_ADAPTER'])
 
 env.SConscript('./src/SConscript')
-
+#if build_sample == 'ON':
+#      if target_os in ['linux', 'arduino', 'android']:
+#              env.SConscript('./samples/' + target_os + '/SConscript')
 if build_sample == 'ON':
        if target_os in ['linux', 'arduino', 'darwin']:
                target_path = target_os
index f34cf8c..f6f43e5 100644 (file)
@@ -1855,6 +1855,8 @@ static OCStackResult ParseRequestUri(const char *fullUri,
             }
         }
 
+        da = (OCDevAddr *)OICCalloc(1, sizeof (OCDevAddr));
+
         len = end - start;
         if (len >= sizeof(da->addr))
         {
@@ -1862,6 +1864,7 @@ static OCStackResult ParseRequestUri(const char *fullUri,
         }
 
         da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
+
         if (!da)
         {
             return OC_STACK_NO_MEMORY;
index 75270d7..34df3ab 100644 (file)
@@ -26,24 +26,31 @@ Import('env')
 
 target_os = env.get('TARGET_OS')
 
-if target_os not in ['arduino','darwin','ios']:
+#if target_os not in ['arduino','darwin']:
        # Build things manager project
-       SConscript('things-manager/SConscript')
+       #SConscript('things-manager/SConscript')
 
        # Build soft sensor manager project
-       SConscript('soft-sensor-manager/SConscript')
+       #SConscript('soft-sensor-manager/SConscript')
 
        # Build protocol plugin project
        # protocol-plugin use 'inotify', this feature isn't support by MAC OSX
-       if target_os not in ['darwin', 'ios']:
-               SConscript('protocol-plugin/SConscript')
+       #if target_os not in ['darwin', 'ios', 'android']:
+       #       SConscript('protocol-plugin/SConscript')
 
        # Build notification manager project
-       if target_os not in ['android', 'tizen']:
-               SConscript('notification-manager/SConscript')
+       #SConscript('notification-manager/SConscript')
+       
+if target_os in ['arduino','android', 'linux']:
+       SConscript('easy-setup/SConscript')
+       #if target_os not in ['android', 'tizen']:
+               #SConscript('notification-manager/SConscript')
 
        # Build resource-encapsulation project
-       SConscript('resource-encapsulation/SConscript')
+       #if target_os not in ['tizen']:
+               #SConscript('resource-encapsulation/SConscript')
 #else:
 #      SConscript('notification-manager/SampleApp/arduino/SConscript')
 
+#if target_os in ['arduino','android', 'linux']:
+        #SConscript('easy-setup/SConscript')
diff --git a/service/easy-setup/SConscript b/service/easy-setup/SConscript
new file mode 100644 (file)
index 0000000..36096c2
--- /dev/null
@@ -0,0 +1,110 @@
+#******************************************************************
+#
+# Copyright 2014 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+##
+# easy-setup project build script
+##
+
+import os
+
+Import('env')
+
+env.AppendUnique(CPPDEFINES = ['EASY_SETUP_CA_INIT'])
+
+easy_setup_env = env.Clone()
+target_os = env.get('TARGET_OS')
+
+lib_env = env.Clone()
+if target_os == 'android':
+       SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', exports = 'lib_env')
+
+######################################################################
+# Build flags
+######################################################################
+easy_setup_env.AppendUnique(CPPPATH = ['sdk/inc', 'sdk/src', 'sdk/common'])
+
+if target_os not in ['windows', 'winrt']:
+    easy_setup_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
+    if target_os not in ['android', 'arduino']:
+        easy_setup_env.AppendUnique(CXXFLAGS = ['-pthread'])
+
+if target_os in ['android', 'linux']:
+       easy_setup_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+       easy_setup_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
+       easy_setup_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
+       if target_os not in ['linux', 'arduino']:
+               easy_setup_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'gnustl_shared'])      
+               if not env.get('RELEASE'):
+                       easy_setup_env.AppendUnique(LIBS = ['log'])
+       else:
+               easy_setup_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction'])
+
+if target_os == 'arduino':
+       easy_setup_env.AppendUnique(CPPPATH = [
+                                      '../../resource/oc_logger/include',
+                                      '../../resource/csdk/logger/include',
+                                      '../../resource/csdk/stack/include',
+                                      '../../extlibs/cjson',
+                                      'sdk/enrollee/arduino/wifi',
+                                      'sdk/enrollee/common/src',
+                                      'sdk/enrollee/common/inc'])
+
+if target_os in ['android','linux']:                                      
+       easy_setup_env.PrependUnique(CPPPATH = [
+               env.get('SRC_DIR') + '/resource/c_common/oic_malloc/include',           
+               env.get('SRC_DIR') + '/resource/csdk/connectivity/common/inc',
+               env.get('SRC_DIR') + '/resource/csdk/connectivity/api',
+        env.get('SRC_DIR') + '/resource/csdk/stack/include',
+        env.get('SRC_DIR') + '/resource/csdk/logger/include',
+               env.get('SRC_DIR') + '/resource/csdk/security/include',
+               env.get('SRC_DIR') + '/extlibs/cjson',
+               'sdk/common',
+               'sdk/mediator/inc'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+
+if target_os == 'arduino':
+       es_sdk_static = easy_setup_env.StaticLibrary('ESSDKLibrary',
+                                       ['sdk/enrollee/common/src/easysetup.cpp',
+                                       'sdk/enrollee/common/src/resourceHandler.cpp',
+                                       'sdk/enrollee/arduino/wifi/networkHandler.cpp'])
+       easy_setup_env.InstallTarget(es_sdk_static, 'libESSDK')
+
+
+if target_os == 'android':
+       es_sdk_shared = easy_setup_env.StaticLibrary('libESSDK',
+                                       ['sdk/mediator/src/easysetupmgr.cpp',
+                                       'sdk/mediator/src/camutex_pthreads.c',
+                                       'sdk/mediator/src/provisioninghandler.cpp'])
+       easy_setup_env.InstallTarget(es_sdk_shared, 'libESSDK')
+
+if target_os == 'linux':
+       es_sdk_shared = easy_setup_env.SharedLibrary('ESSDKLibrary',
+                                       ['sdk/mediator/src/easysetupmgr.cpp',
+                                       'sdk/mediator/src/camutex_pthreads.c',
+                                       'sdk/mediator/src/provisioninghandler.cpp'])
+       easy_setup_env.InstallTarget(es_sdk_shared, 'libESSDK')
+
+#Go to build sample apps
+SConscript('sampleapp/SConscript')
+
+
diff --git a/service/easy-setup/readme.txt b/service/easy-setup/readme.txt
new file mode 100644 (file)
index 0000000..19cce5b
--- /dev/null
@@ -0,0 +1,77 @@
+
+Steps to build and deploy Easysetup Mediator in Android platform
+
+1) Compilation using Scons
+       0) Prerequisite exports for Android
+               export ANDROID_HOME=<ANDROID_HOME>
+               export ANDROID_NDK=<ANDROID_NDK>
+       a) In the IoTivity root source folder execute
+                scons TARGET_OS=android TARGET_ARCH=armeabi TARGET_TRANSPORT=IP RELEASE=0
+       
+       b) If the project is setup correctly, you should see a BUILD SUCCESSFUL message on the terminal
+               You should see the .aar files generated inside of '<iotivity>/android/android_api/base/build/outputs/aar' directory. The .aar files contain jni directory and also a .jar file
+               
+       c) Now navigate to the Easysetup NDK folder 
+               <iotivity-root>/service/easy-setup/sdk/mediator/android
+               
+       d) Execute NDK-Build with the following command to cross compiled Easysetup JNI .so files
+                ~/madan/android-ndk-r10d/ndk-build
+                
+       e) Step (d) will generate cross compiled Easysetup JNI .so files in the following folder
+               
+2) Compilation using Android Studio
+       
+       0) Prerequisite for running the Android application
+               Install Android Studio and use the Android SDK manager to update the Android API to 21
+       
+       a) Import following projects to the Studio using the "File->New->Import Project"
+               - service\easy-setup\sdk\android\EasySetupCore
+               - service\easy-setup\sampleapp\android\EasySetup
+       
+       b) EasySetupCore is dependent on the .aar files generated in 1.b 
+               1) To add an .aar file to the 'EasySetupCore' project,
+                       a.Right click on EasySetup->New->Module->Import .JAR or .AAR Package
+                       b.Select the .aar file(iotivity-armeabi-base-*.aar) from the location in steps 1.b
+                       c.Right click on EasySetup->Open Module Settings
+                       d.Select each sample app module under 'Modules'->Dependencies->Add->Module Dependency
+                       
+       c)      Build EasySetupCore project using "Android Studio->Build->Make Module "easySetupCore"
+               If the project is setup correctly, you should see a BUILD SUCCESSFUL in the Android Studio Gradle Build terminal
+                       You should see the .aar file generated inside of 
+                       'iotivity\service\easy-setup\sdk\mediator\android\easySetupCore\build\outputs\aar'
+       
+       d) EasySetup application is also dependent on the .so files generated in 1.d step
+               1) Drag and drop the following .so files in to the EasySetup\app\src\main\jniLibs\armeabi folder
+                       - libeasysetup-jni.so [Easy Setup file]
+                       
+       e) EasySetup is also dependent on the .aar files generated in 1.b and 2.c steps
+               1) To add an .aar file to the 'EasySetup' project,
+                       a.Right click on EasySetup->New->Module->Import .JAR or .AAR Package
+                       b.Select the .aar file from the location in steps 1.b and 2.b above
+                       c.Right click on EasySetup->Open Module Settings
+                       d.Select each sample app module under 'Modules'->Dependencies->Add->Module Dependency
+                       e.The .aar files (easySetupCore-*.aar & iotivity-armeabi-base-*.aar) selected in step 2.c.1.b above should be present. Select it.
+       
+                       
+       e) Run "Easy Setup" as an Android application
+       
+Folder structure
+iotivity/
+└── service
+       â””── easy-setup/
+               â”‚── SConscript
+               â”‚── sdk
+               â”‚     â””── inc
+               â”‚     â””── src
+               â”‚     â””── android
+               â”‚     â””── arduino
+               â”‚             â””──wifi
+               â”‚                     â””──inc            
+               â”‚                     â””──src            
+               â”‚── sampleapp
+               â”‚     â””──android
+               â”‚     â””──arduino                
+               â”‚     â””──linux
+               â””── README - You are reading this.
+
+
diff --git a/service/easy-setup/sampleapp/SConscript b/service/easy-setup/sampleapp/SConscript
new file mode 100644 (file)
index 0000000..13c1c3a
--- /dev/null
@@ -0,0 +1,46 @@
+#******************************************************************
+#
+# Copyright 2014 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+##
+# sampleapp build script
+##
+
+Import('env')
+
+# Add third party libraries
+lib_env = env.Clone()
+
+sample_env = lib_env.Clone()
+target_os = env.get('TARGET_OS')
+
+######################################################################
+# Build flags
+######################################################################
+
+######################################################################
+# Source files and Targets
+######################################################################
+if target_os == 'arduino' :
+       # Build linux sample app
+       SConscript('arduino/thinserver/SConscript')
+
+if target_os == 'linux' :
+       # Build linux sample app
+       SConscript('linux/richclient/SConscript')
diff --git a/service/easy-setup/sampleapp/android/.gitignore b/service/easy-setup/sampleapp/android/.gitignore
new file mode 100644 (file)
index 0000000..6451fc5
--- /dev/null
@@ -0,0 +1,50 @@
+#built application files\r
+*.apk\r
+*.ap_\r
+\r
+# files for the dex VM\r
+*.dex\r
+\r
+# Java class files\r
+*.class\r
+\r
+# generated files\r
+bin/\r
+gen/\r
+\r
+# Local configuration file (sdk path, etc)\r
+local.properties\r
+\r
+# Proguard folder generated by Eclipse \r
+proguard/ \r
+\r
+# Windows thumbnail db\r
+Thumbs.db\r
+\r
+# OSX files\r
+.DS_Store\r
+\r
+# Eclipse project files\r
+.classpath\r
+.project\r
+\r
+#Android Studio & Gradle\r
+.gradle\r
+/local.properties\r
+/.idea/workspace.xml\r
+/.idea/libraries\r
+.DS_Store\r
+/build/*\r
+/base/build/*\r
+/base/obj/*\r
+/base/libs/*\r
+/sample/*\r
+\r
+#Some older projects\r
+/*/out\r
+/*/*/build\r
+/*/*/production\r
+*.iws\r
+*.ipr\r
+*~\r
+*.swp
\ No newline at end of file
diff --git a/service/easy-setup/sampleapp/android/EasySetup/EasySetupGradle.iml b/service/easy-setup/sampleapp/android/EasySetup/EasySetupGradle.iml
new file mode 100644 (file)
index 0000000..4ac7e4f
--- /dev/null
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module external.linked.project.id="EasySetupGradle" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
+  <component name="FacetManager">
+    <facet type="java-gradle" name="Java-Gradle">
+      <configuration>
+        <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
+        <option name="BUILDABLE" value="false" />
+      </configuration>
+    </facet>
+  </component>
+  <component name="NewModuleRootManager" inherit-compiler-output="true">
+    <exclude-output />
+    <content url="file://$MODULE_DIR$">
+      <excludeFolder url="file://$MODULE_DIR$/.gradle" />
+    </content>
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+  </component>
+</module>
\ No newline at end of file
diff --git a/service/easy-setup/sampleapp/android/EasySetup/app/app.iml b/service/easy-setup/sampleapp/android/EasySetup/app/app.iml
new file mode 100644 (file)
index 0000000..b14367f
--- /dev/null
@@ -0,0 +1,96 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module external.linked.project.id=":app" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="EasySetup" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
+  <component name="FacetManager">
+    <facet type="android-gradle" name="Android-Gradle">
+      <configuration>
+        <option name="GRADLE_PROJECT_PATH" value=":app" />
+      </configuration>
+    </facet>
+    <facet type="android" name="Android">
+      <configuration>
+        <option name="SELECTED_BUILD_VARIANT" value="debug" />
+        <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
+        <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
+        <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
+        <option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
+        <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugAndroidTest" />
+        <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugAndroidTestSources" />
+        <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugAndroidTestSources" />
+        <option name="ALLOW_USER_CONFIGURATION" value="false" />
+        <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
+        <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
+        <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
+        <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
+      </configuration>
+    </facet>
+  </component>
+  <component name="NewModuleRootManager" inherit-compiler-output="false">
+    <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
+    <output-test url="file://$MODULE_DIR$/build/intermediates/classes/androidTest/debug" />
+    <exclude-output />
+    <content url="file://$MODULE_DIR$">
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/androidTest/debug" type="java-test-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/EasySetup/easySetupCore-debug/unspecified/jars" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/EasySetup/iotivity-armeabi-base-debug/unspecified/jars" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
+      <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
+      <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
+    </content>
+    <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
+    <orderEntry type="sourceFolder" forTests="false" />
+    <orderEntry type="module" module-name="easySetupCore-debug" exported="" />
+    <orderEntry type="module" module-name="iotivity-armeabi-base-debug" exported="" />
+    <orderEntry type="library" exported="" name="easySetupCore-debug-unspecified" level="project" />
+    <orderEntry type="library" exported="" name="iotivity-armeabi-base-debug-unspecified" level="project" />
+  </component>
+</module>
\ No newline at end of file
diff --git a/service/easy-setup/sampleapp/android/EasySetup/app/build.gradle b/service/easy-setup/sampleapp/android/EasySetup/app/build.gradle
new file mode 100644 (file)
index 0000000..c30034a
--- /dev/null
@@ -0,0 +1,23 @@
+apply plugin: 'com.android.application'\r
+android {\r
+    compileSdkVersion 21\r
+    buildToolsVersion '21.1.2'\r
+\r
+    defaultConfig {\r
+        applicationId "org.iotivity.service.easysetup"\r
+        minSdkVersion 21\r
+        targetSdkVersion 21\r
+    }\r
+\r
+    buildTypes {\r
+        release {\r
+            minifyEnabled false\r
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'\r
+        }\r
+    }\r
+}\r
+\r
+dependencies {\r
+    compile project(':iotivity-armeabi-base-debug')\r
+    compile project(':easySetupCore-debug')\r
+}
\ No newline at end of file
diff --git a/service/easy-setup/sampleapp/android/EasySetup/app/src/main/AndroidManifest.xml b/service/easy-setup/sampleapp/android/EasySetup/app/src/main/AndroidManifest.xml
new file mode 100644 (file)
index 0000000..d3e74dd
--- /dev/null
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="org.iotivity.service.easysetup"
+    android:versionCode="1"
+    android:versionName="1.0" >
+    
+    <uses-permission android:name="android.permission.INTERNET" />
+    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
+    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />    
+    <uses-feature android:name="android.hardware.camera" android:required="true" />
+       <uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
+       <uses-feature android:name="android.hardware.touchscreen" android:required="false"/>
+
+    <uses-permission android:name="android.permission.CAMERA"/>
+
+
+     <application
+        android:allowBackup="true"
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme" >
+        <activity
+            android:name=".MainActivity"
+            android:label="@string/app_name" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+            <intent-filter>
+                               <action android:name="android.intent.action.SEND"/>
+                               <category android:name="android.intent.category.DEFAULT"/>
+                               <data android:mimeType="text/plain"/>
+                       </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
diff --git a/service/easy-setup/sampleapp/android/EasySetup/app/src/main/java/org/iotivity/service/easysetup/MainActivity.java b/service/easy-setup/sampleapp/android/EasySetup/app/src/main/java/org/iotivity/service/easysetup/MainActivity.java
new file mode 100644 (file)
index 0000000..3b785e5
--- /dev/null
@@ -0,0 +1,303 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+package org.iotivity.service.easysetup;\r
+\r
+import java.util.Timer;\r
+import java.util.TimerTask;\r
+\r
+import org.iotivity.base.ModeType;\r
+import org.iotivity.base.OcPlatform;\r
+import org.iotivity.base.PlatformConfig;\r
+import org.iotivity.base.QualityOfService;\r
+import org.iotivity.base.ServiceType;\r
+import org.iotivity.service.easysetup.mediator.common.EnrolleeDevice;\r
+import org.iotivity.service.easysetup.mediator.IOnBoardingStatus;\r
+import org.iotivity.service.easysetup.mediator.IProvisioningListener;\r
+import org.iotivity.service.easysetup.mediator.OnBoardEnrollee;\r
+import org.iotivity.service.easysetup.mediator.ProvisionEnrollee;\r
+import org.iotivity.base.OcConnectivityType;\r
+import org.iotivity.service.easysetup.mediator.ip.IPEnrolleeDevice;\r
+import org.iotivity.service.easysetup.mediator.ip.IPProvisioningInfo;\r
+import org.iotivity.service.easysetup.mediator.ip.WiFiSoftAPOnBoardingConfig;\r
+\r
+import android.app.Activity;\r
+import android.content.Intent;\r
+import android.graphics.Bitmap;\r
+import android.net.wifi.WifiConfiguration;\r
+import android.os.Bundle;\r
+import android.util.Log;\r
+import android.view.Menu;\r
+import android.view.View;\r
+import android.view.View.OnClickListener;\r
+import android.widget.Button;\r
+import android.widget.ImageView;\r
+import android.widget.TextView;\r
+import android.widget.Toast;\r
+\r
+public class MainActivity extends Activity implements IProvisioningListener,\r
+        IOnBoardingStatus {\r
+    String            devicesConnected;\r
+    TextView          textView1;\r
+\r
+    private Timer     myTimer;\r
+    private Timer     myTimer2;\r
+    static int        scanCount             = 0;\r
+    static int        easySetupCount        = 0;\r
+    static final int  REQUEST_IMAGE_CAPTURE = 1;\r
+    ImageView         imageView;\r
+    EnrolleeDevice    connectedDevice;\r
+\r
+    OnBoardEnrollee   onBoardingHandlerInstance;\r
+    ProvisionEnrollee provisionEnrolleInstance;\r
+\r
+    @Override\r
+    protected void onCreate(Bundle savedInstanceState) {\r
+        super.onCreate(savedInstanceState);\r
+        setContentView(R.layout.activity_main);\r
+\r
+        textView1 = (TextView) findViewById(R.id.textView1);\r
+\r
+        // OnBoarding Process\r
+        onBoardingHandlerInstance = new OnBoardEnrollee(this, OcConnectivityType.IPV4);\r
+        onBoardingHandlerInstance.registerOnBoardingStatusHandler(this);\r
+\r
+        // Get intent, action and MIME type\r
+        Intent intent = getIntent();\r
+        String action = intent.getAction();\r
+        String type = intent.getType();\r
+\r
+        addListenerForStartAP();\r
+        addListenerForStopAP();\r
+        addListenerOnProvisioning();\r
+        initOICStack();\r
+\r
+        myTimer2 = new Timer();\r
+        myTimer2.schedule(new TimerTask() {\r
+            @Override\r
+            public void run() {\r
+                onBoardingHandlerInstance.startDeviceScan(300);\r
+            }\r
+\r
+        }, 0, 2000);\r
+    }\r
+\r
+    public void onDestroy() {\r
+        super.onDestroy();\r
+        if(provisionEnrolleInstance != null)\r
+        {\r
+            provisionEnrolleInstance.stopEnrolleeProvisioning(OcConnectivityType.IPV4);\r
+        }\r
+        onBoardingHandlerInstance.disableWiFiAP();\r
+        finish();\r
+    }\r
+\r
+    @Override\r
+    public boolean onCreateOptionsMenu(Menu menu) {\r
+        menu.add(0, 0, 0, "Get Clients");\r
+        menu.add(0, 1, 0, "Start AP");\r
+        menu.add(0, 2, 0, "Stop AP");\r
+        menu.add(0, 3, 0, "Provision");\r
+        // Inflate the menu; this adds items to the action bar if it is present.\r
+        getMenuInflater().inflate(R.menu.main, menu);\r
+        return true;\r
+    }\r
+\r
+    @Override\r
+    public void onFinishProvisioning(final int statuscode) {\r
+        // TODO Auto-generated method stub\r
+        try {\r
+            // code runs in a thread\r
+            runOnUiThread(new Runnable() {\r
+                @Override\r
+                public void run() {\r
+                    // TODO Auto-generated method stub\r
+                    Toast toast = null;\r
+                    IPEnrolleeDevice ipEnrolleeDevice = (IPEnrolleeDevice)connectedDevice;\r
+                    if (statuscode == 0) {\r
+                        toast = Toast.makeText(getApplicationContext(),\r
+                                ipEnrolleeDevice.getIpAddr()\r
+                                        + " - is Provisioned",\r
+                                Toast.LENGTH_LONG);\r
+                        Log.i("EasyConnect", "Provisioned statuscode-"\r
+                                + statuscode);\r
+                    } else {\r
+                        toast = Toast.makeText(getApplicationContext(),\r
+                                ipEnrolleeDevice.getIpAddr()\r
+                                        + " - is NOT Provisioned",\r
+                                Toast.LENGTH_LONG);\r
+                        Log.i("EasyConnect", "Not Provisioned statuscode-"\r
+                                + statuscode);\r
+                    }\r
+\r
+                    toast.show();\r
+                }\r
+            });\r
+        } catch (final Exception ex) {\r
+            Log.i("---", "Exception in thread");\r
+        }\r
+    }\r
+\r
+    private void scan() {\r
+        onBoardingHandlerInstance.registerOnBoardingStatusHandler(this);\r
+        onBoardingHandlerInstance.startDeviceScan(300);\r
+    }\r
+\r
+    public void addListenerForStartAP() {\r
+        Button button = (Button) findViewById(R.id.button1);\r
+\r
+        button.setOnClickListener(new OnClickListener() {\r
+            @Override\r
+            public void onClick(View arg0) {\r
+                WiFiSoftAPOnBoardingConfig transportConfig = new WiFiSoftAPOnBoardingConfig();\r
+\r
+                WifiConfiguration netConfig = new WifiConfiguration();\r
+                netConfig.SSID = "EasySetup123";\r
+                netConfig.allowedAuthAlgorithms\r
+                        .set(WifiConfiguration.AuthAlgorithm.OPEN);\r
+                netConfig.allowedKeyManagement\r
+                        .set(WifiConfiguration.KeyMgmt.WPA_PSK);\r
+                netConfig.preSharedKey = "EasySetup123";\r
+\r
+                transportConfig.setConnectivityType(OcConnectivityType.IPV4);\r
+                transportConfig.setNetConfig(netConfig);\r
+                onBoardingHandlerInstance.enableNetwork(transportConfig, true);\r
+            }\r
+        });\r
+    }\r
+\r
+    public void addListenerForStopAP() {\r
+        Button button = (Button) findViewById(R.id.stopapbutton);\r
+\r
+        button.setOnClickListener(new OnClickListener() {\r
+            @Override\r
+            public void onClick(View arg0) {\r
+                onBoardingHandlerInstance.disableWiFiAP();\r
+            }\r
+        });\r
+    }\r
+\r
+    public void addListenerOnProvisioning() {\r
+        Button button = (Button) findViewById(R.id.button2);\r
+\r
+        button.setOnClickListener(new OnClickListener() {\r
+            @Override\r
+            public void onClick(View arg0) {\r
+                IPEnrolleeDevice ipEnrolleeDevice = (IPEnrolleeDevice)connectedDevice;\r
+                IPProvisioningInfo ipProvisioningInfo = new IPProvisioningInfo();\r
+\r
+                ipProvisioningInfo.setConnectivityType(OcConnectivityType.IPV4);\r
+                ipProvisioningInfo.setIpAddress(ipEnrolleeDevice.getIpAddr());\r
+                ipProvisioningInfo.setNetSSID("EasySetup123");\r
+                ipProvisioningInfo.setNetPWD("EasySetup123");\r
+\r
+                provisionEnrolleInstance.provisionEnrollee(\r
+                        ipProvisioningInfo, OcConnectivityType.IPV4);\r
+                easySetupCount++;\r
+                Log.i("EasyConnect", "easy Setup Count-" + easySetupCount);\r
+                Log.i("EasyConnect",\r
+                        "IP Address-" + ipProvisioningInfo.getIpAddress());\r
+            }\r
+        });\r
+\r
+    }\r
+\r
+    @Override\r
+    protected void onActivityResult(int requestCode, int resultCode, Intent data) {\r
+        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {\r
+            Bundle extras = data.getExtras();\r
+            Bitmap imageBitmap = (Bitmap) extras.get("data");\r
+            imageView.setImageBitmap(imageBitmap);\r
+        }\r
+    }\r
+\r
+    /**\r
+     * configure OIC platform and call findResource\r
+     */\r
+    private void initOICStack() {\r
+        //create platform config\r
+        PlatformConfig cfg = new PlatformConfig(\r
+                this,\r
+                ServiceType.IN_PROC,\r
+                ModeType.CLIENT,\r
+                "0.0.0.0", // bind to all available interfaces\r
+                0,\r
+                QualityOfService.LOW);\r
+        OcPlatform.Configure(cfg);\r
+        Log.i("EasyConnect","OcPlatform Configure is invoked");\r
+    }\r
+\r
+    @Override\r
+    public void deviceOnBoardingStatus(EnrolleeDevice enrolleeDevice) {\r
+        // TODO Auto-generated method stub\r
+        // TODO Auto-generated method stub\r
+        if(enrolleeDevice.getConnectivityType() == OcConnectivityType.IPV4) {\r
+            IPEnrolleeDevice ipEnrolleeDevice = (IPEnrolleeDevice)enrolleeDevice;\r
+            if (ipEnrolleeDevice.getIpAddr() != null) {\r
+                String finalResult = "Easy Connect : ";\r
+                if (ipEnrolleeDevice.isReachable()) {\r
+                    finalResult = "Device OnBoarded" + "["\r
+                            + ipEnrolleeDevice.getIpAddr() + "]";\r
+\r
+                    /*\r
+                     * easySetupInstance.StartEasySetup(enrolleStatus.getIpAddr()) ;\r
+                     * easySetupCount++; Log.i("EasyConnect",\r
+                     * "easy Setup Count-"+easySetupCount); Log.i("EasyConnect",\r
+                     * "IP Address-"+enrolleStatus.getIpAddr());\r
+                     */\r
+                    connectedDevice = ipEnrolleeDevice;\r
+\r
+                    // Only after onboarding is successful, provisioning is performed\r
+                    provisionEnrolleInstance = new ProvisionEnrollee(this);\r
+                    provisionEnrolleInstance.registerProvisioningHandler(this);\r
+\r
+                } else {\r
+                    finalResult = "Device Removed" + "["\r
+                            + ipEnrolleeDevice.getIpAddr() + "]";\r
+                }\r
+\r
+                textView1.setText("");\r
+                textView1.append("Clients: \n");\r
+                textView1.append("####################\n");\r
+                textView1.append("IP Address   : " + ipEnrolleeDevice.getIpAddr()\r
+                        + "\n");\r
+                textView1.append("HW Address   : " + ipEnrolleeDevice.getHWAddr()\r
+                        + "\n");\r
+                textView1.append("Is OnBoarded : " + ipEnrolleeDevice.isReachable()\r
+                        + "\n");\r
+\r
+                Toast.makeText(getApplicationContext(), finalResult,\r
+                        Toast.LENGTH_LONG).show();\r
+\r
+                /*\r
+                 * myTimer2 = new Timer(); myTimer2.schedule(new TimerTask() {\r
+                 *\r
+                 * @Override public void run() {\r
+                 * easySetupInstance.StartEasySetup(enrolleStatus.getIpAddr());\r
+                 * easySetupCount++; Log.i("EasyConnect",\r
+                 * "easy Setup Count-"+easySetupCount); Log.i("EasyConnect",\r
+                 * "IP Address-"+enrolleStatus.getIpAddr()); }\r
+                 *\r
+                 * }, 0, 10000);\r
+                 */\r
+            }\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/drawable-hdpi/background.png b/service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/drawable-hdpi/background.png
new file mode 100644 (file)
index 0000000..561cce8
Binary files /dev/null and b/service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/drawable-hdpi/background.png differ
diff --git a/service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/drawable-hdpi/cancel.png b/service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/drawable-hdpi/cancel.png
new file mode 100644 (file)
index 0000000..da342e5
Binary files /dev/null and b/service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/drawable-hdpi/cancel.png differ
diff --git a/service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/drawable-hdpi/ic_launcher.png b/service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/drawable-hdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..288b665
Binary files /dev/null and b/service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/drawable-hdpi/ic_launcher.png differ
diff --git a/service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/drawable-hdpi/icon.png b/service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/drawable-hdpi/icon.png
new file mode 100644 (file)
index 0000000..24a8af2
Binary files /dev/null and b/service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/drawable-hdpi/icon.png differ
diff --git a/service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/layout/activity_main.xml b/service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/layout/activity_main.xml
new file mode 100644 (file)
index 0000000..2f7737e
--- /dev/null
@@ -0,0 +1,71 @@
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"\r
+    xmlns:tools="http://schemas.android.com/tools"\r
+    android:layout_width="match_parent"\r
+    android:layout_height="match_parent"\r
+    android:background="@drawable/background"\r
+    android:paddingBottom="@dimen/activity_vertical_margin"\r
+    android:paddingLeft="@dimen/activity_horizontal_margin"\r
+    android:paddingRight="@dimen/activity_horizontal_margin"\r
+    android:paddingTop="@dimen/activity_vertical_margin"\r
+    tools:context="org.iotivity.service.easysetup.mediator.MainActivity" >\r
+\r
+    <Button\r
+        android:id="@+id/button1"\r
+        android:layout_width="wrap_content"\r
+        android:layout_height="wrap_content"\r
+        android:layout_alignParentTop="true"\r
+        android:layout_centerHorizontal="true"\r
+        android:layout_margin="10dp"\r
+        android:layout_marginTop="20dp"\r
+        android:elegantTextHeight="true"\r
+        android:text="@string/start_soft_ap"\r
+        android:textAllCaps="false"\r
+        android:textSize="18sp" />\r
+\r
+    <Button\r
+        android:id="@+id/button2"\r
+        android:layout_width="wrap_content"\r
+        android:layout_height="wrap_content"\r
+        android:layout_alignParentBottom="true"\r
+        android:layout_centerHorizontal="true"\r
+        android:layout_marginBottom="72dp"\r
+        android:elegantTextHeight="true"\r
+        android:text="@string/provision_device"\r
+        android:textAllCaps="false"\r
+        android:textSize="18sp" />\r
+\r
+    <Button\r
+        android:id="@+id/stopapbutton"\r
+        android:layout_width="wrap_content"\r
+        android:layout_height="wrap_content"\r
+        android:layout_below="@+id/button1"\r
+        android:layout_centerHorizontal="true"\r
+        android:layout_margin="10dp"\r
+        android:elegantTextHeight="true"\r
+        android:text="@string/stop_soft_ap"\r
+        android:textAllCaps="false"\r
+        android:textSize="18sp" />\r
+\r
+    <TextView\r
+        android:id="@+id/textView1"\r
+        android:layout_width="wrap_content"\r
+        android:layout_height="wrap_content"\r
+        android:layout_alignLeft="@+id/TextView01"\r
+        android:layout_below="@+id/stopapbutton"\r
+        android:layout_marginTop="43dp"\r
+        android:text="@string/textview1"\r
+        android:textColor="#ffffff"\r
+        android:textSize="15sp" />\r
+\r
+    <TextView\r
+        android:id="@+id/TextView01"\r
+        android:layout_width="wrap_content"\r
+        android:layout_height="wrap_content"\r
+        android:layout_alignLeft="@+id/button2"\r
+        android:layout_below="@+id/stopapbutton"\r
+        android:layout_marginTop="16dp"\r
+        android:text="@string/textview2"\r
+        android:textColor="#ffffff"\r
+        android:textSize="20sp" />\r
+\r
+</RelativeLayout>
\ No newline at end of file
diff --git a/service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/menu/main.xml b/service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/menu/main.xml
new file mode 100644 (file)
index 0000000..921b3c4
--- /dev/null
@@ -0,0 +1,11 @@
+<menu xmlns:android="http://schemas.android.com/apk/res/android"\r
+    xmlns:app="http://schemas.android.com/apk/res-auto"\r
+    xmlns:tools="http://schemas.android.com/tools"\r
+    tools:context="org.iotivity.service.easysetup.MainActivity" >\r
+\r
+    <item\r
+        android:id="@+id/action_settings"\r
+        android:orderInCategory="100"\r
+        android:title="@string/action_settings"/>\r
+\r
+</menu>\r
diff --git a/service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/values/dimens.xml b/service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/values/dimens.xml
new file mode 100644 (file)
index 0000000..55c1e59
--- /dev/null
@@ -0,0 +1,7 @@
+<resources>
+
+    <!-- Default screen margins, per the Android Design guidelines. -->
+    <dimen name="activity_horizontal_margin">16dp</dimen>
+    <dimen name="activity_vertical_margin">16dp</dimen>
+
+</resources>
diff --git a/service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/values/strings.xml b/service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/values/strings.xml
new file mode 100644 (file)
index 0000000..94af49e
--- /dev/null
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <string name="app_name">Easy Setup</string>
+    <string name="action_settings">Settings</string>
+    <string name="textview2">Device Information</string>
+    <string name="textview1"> -- empty -- </string>
+    <string name="scan_qr_code">Scan QR Code</string> 
+       <string name="start_easy_setup">Start Easy Setup</string> 
+       <string name="start_soft_ap">Start Wi-Fi Soft AP</string>
+       <string name="stop_soft_ap">Stop Soft AP</string>  
+    <string name="provision_device">Provision Connected Device</string>
+</resources>
diff --git a/service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/values/styles.xml b/service/easy-setup/sampleapp/android/EasySetup/app/src/main/res/values/styles.xml
new file mode 100644 (file)
index 0000000..6ce89c7
--- /dev/null
@@ -0,0 +1,20 @@
+<resources>
+
+    <!--
+        Base application theme, dependent on API level. This theme is replaced
+        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
+    -->
+    <style name="AppBaseTheme" parent="android:Theme.Light">
+        <!--
+            Theme customizations available in newer API levels can go in
+            res/values-vXX/styles.xml, while customizations related to
+            backward-compatibility can go here.
+        -->
+    </style>
+
+    <!-- Application theme. -->
+    <style name="AppTheme" parent="AppBaseTheme">
+        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
+    </style>
+
+</resources>
diff --git a/service/easy-setup/sampleapp/android/EasySetup/build.gradle b/service/easy-setup/sampleapp/android/EasySetup/build.gradle
new file mode 100644 (file)
index 0000000..0a7f6ce
--- /dev/null
@@ -0,0 +1,15 @@
+// Top-level build file where you can add configuration options common to all sub-projects/modules.\r
+buildscript {\r
+    repositories {\r
+        jcenter()\r
+    }\r
+    dependencies {\r
+        classpath 'com.android.tools.build:gradle:1.2.3'\r
+    }\r
+}\r
+\r
+allprojects {\r
+    repositories {\r
+        jcenter()\r
+    }\r
+}\r
diff --git a/service/easy-setup/sampleapp/android/EasySetup/easySetupCore-debug/build.gradle b/service/easy-setup/sampleapp/android/EasySetup/easySetupCore-debug/build.gradle
new file mode 100644 (file)
index 0000000..4213d41
--- /dev/null
@@ -0,0 +1,2 @@
+configurations.create("default")
+artifacts.add("default", file('easySetupCore-debug.aar'))
\ No newline at end of file
diff --git a/service/easy-setup/sampleapp/android/EasySetup/easySetupCore-debug/easySetupCore-debug.iml b/service/easy-setup/sampleapp/android/EasySetup/easySetupCore-debug/easySetupCore-debug.iml
new file mode 100644 (file)
index 0000000..995ecfb
--- /dev/null
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module external.linked.project.id=":easySetupCore-debug" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="EasySetup" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
+  <component name="FacetManager">
+    <facet type="android-gradle" name="Android-Gradle">
+      <configuration>
+        <option name="GRADLE_PROJECT_PATH" value=":easySetupCore-debug" />
+      </configuration>
+    </facet>
+    <facet type="java-gradle" name="Java-Gradle">
+      <configuration>
+        <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
+        <option name="BUILDABLE" value="false" />
+      </configuration>
+    </facet>
+  </component>
+  <component name="NewModuleRootManager" inherit-compiler-output="true">
+    <exclude-output />
+    <content url="file://$MODULE_DIR$">
+      <excludeFolder url="file://$MODULE_DIR$/.gradle" />
+      <excludeFolder url="file://$MODULE_DIR$/build" />
+    </content>
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+  </component>
+</module>
\ No newline at end of file
diff --git a/service/easy-setup/sampleapp/android/EasySetup/iotivity-armeabi-base-debug/build.gradle b/service/easy-setup/sampleapp/android/EasySetup/iotivity-armeabi-base-debug/build.gradle
new file mode 100644 (file)
index 0000000..65c8cbe
--- /dev/null
@@ -0,0 +1,2 @@
+configurations.create("default")
+artifacts.add("default", file('iotivity-armeabi-base-debug.aar'))
\ No newline at end of file
diff --git a/service/easy-setup/sampleapp/android/EasySetup/iotivity-armeabi-base-debug/iotivity-armeabi-base-debug.iml b/service/easy-setup/sampleapp/android/EasySetup/iotivity-armeabi-base-debug/iotivity-armeabi-base-debug.iml
new file mode 100644 (file)
index 0000000..8f28f8f
--- /dev/null
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module external.linked.project.id=":iotivity-armeabi-base-debug" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="EasySetup" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
+  <component name="FacetManager">
+    <facet type="android-gradle" name="Android-Gradle">
+      <configuration>
+        <option name="GRADLE_PROJECT_PATH" value=":iotivity-armeabi-base-debug" />
+      </configuration>
+    </facet>
+    <facet type="java-gradle" name="Java-Gradle">
+      <configuration>
+        <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
+        <option name="BUILDABLE" value="false" />
+      </configuration>
+    </facet>
+  </component>
+  <component name="NewModuleRootManager" inherit-compiler-output="true">
+    <exclude-output />
+    <content url="file://$MODULE_DIR$">
+      <excludeFolder url="file://$MODULE_DIR$/.gradle" />
+      <excludeFolder url="file://$MODULE_DIR$/build" />
+    </content>
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+  </component>
+</module>
\ No newline at end of file
diff --git a/service/easy-setup/sampleapp/android/EasySetup/settings.gradle b/service/easy-setup/sampleapp/android/EasySetup/settings.gradle
new file mode 100644 (file)
index 0000000..40189da
--- /dev/null
@@ -0,0 +1 @@
+include ':app', ':iotivity-armeabi-base-debug', ':easySetupCore-debug'\r
diff --git a/service/easy-setup/sampleapp/arduino/thinserver/SConscript b/service/easy-setup/sampleapp/arduino/thinserver/SConscript
new file mode 100644 (file)
index 0000000..fca7b3d
--- /dev/null
@@ -0,0 +1,56 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+Import('env')
+
+thinserver_env = env.Clone()
+######################################################################
+# Build flags
+######################################################################
+thinserver_env.PrependUnique(CPPPATH = [
+                '../../../../../resource/oc_logger/include',
+               '../../../../../resource/csdk/logger/include',
+                '../../../../../resource/csdk/stack/include',
+               '../../../../../extlibs/cjson',
+               '../../../sdk/common',
+               '../../../sdk/enrollee/arduino/wifi',
+               '../../../sdk/enrollee/common/inc',
+               '../../../sdk/enrollee/common/src'
+               ])
+
+thinserver_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+thinserver_env.AppendUnique(CPPDEFINES = ['TB_LOG', 'ARDUINOWIFI'])
+
+thinserver_env.PrependUnique(LIBS = ['octbstack','ocsrm','connectivity_abstraction','coap', 'ESSDKLibrary'])
+
+thinserver = thinserver_env.Program('thinserver', 'thinserver.cpp')
+env.CreateBin('thinserver')
+
+i_thinserver = thinserver_env.Install(env.get('BUILD_DIR'), thinserver)
+
+Alias('thinserver', i_thinserver)
+env.AppendTarget('thinserver')
+
+if(thinserver_env['UPLOAD'] == True):
+       from sys import platform as _platform
+       if _platform == "linux" or _platform == "linux2":
+               thinserver_env.Upload(env.get('BUILD_DIR') + '/service/easy-setup/sampleapp/arduino/thinserver/thinserver.hex')
+       else:
+               print 'Please use appropriate install method for your developing machine. Linux is the only supported platform right now.'
diff --git a/service/easy-setup/sampleapp/arduino/thinserver/thinserver.cpp b/service/easy-setup/sampleapp/arduino/thinserver/thinserver.cpp
new file mode 100644 (file)
index 0000000..ee3617d
--- /dev/null
@@ -0,0 +1,119 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+// Do not remove the include below
+#include "Arduino.h"
+
+#include "logger.h"
+#include "ocstack.h"
+#include <string.h>
+
+#ifdef ARDUINOWIFI
+// Arduino WiFi Shield
+#include <SPI.h>
+#include <WiFi.h>
+#include <WiFiUdp.h>
+#else
+// Arduino Ethernet Shield
+#include <EthernetServer.h>
+#include <Ethernet.h>
+#include <Dns.h>
+#include <EthernetClient.h>
+#include <util.h>
+#include <EthernetUdp.h>
+#include <Dhcp.h>
+#endif
+
+#include "easysetup.h"
+
+const char *getResult(OCStackResult result);
+
+PROGMEM const char TAG[] = "ThinServer";
+
+char ssid[] = "EasySetup123";
+char passwd[] = "EasySetup123";
+
+void EventCallbackInApp(ES_RESULT eventFlag)
+{
+    Serial.println("callback!!! in app");
+}
+
+// On Arduino Atmel boards with Harvard memory architecture, the stack grows
+// downwards from the top and the heap grows upwards. This method will print
+// the distance(in terms of bytes) between those two.
+// See here for more details :
+// http://www.atmel.com/webdoc/AVRLibcReferenceManual/malloc_1malloc_intro.html
+void PrintArduinoMemoryStats()
+{
+#ifdef ARDUINO_AVR_MEGA2560
+    //This var is declared in avr-libc/stdlib/malloc.c
+    //It keeps the largest address not allocated for heap
+    extern char *__brkval;
+    //address of tmp gives us the current stack boundry
+    int tmp;
+    OC_LOG_V(INFO, TAG, "Stack: %u         Heap: %u", (unsigned int)&tmp, (unsigned int)__brkval);
+    OC_LOG_V(INFO, TAG, "Unallocated Memory between heap and stack: %u",
+            ((unsigned int)&tmp - (unsigned int)__brkval));
+#endif
+}
+//The setup function is called once at startup of the sketch
+void setup()
+{
+    // Add your initialization code here
+    // Note : This will initialize Serial port on Arduino at 115200 bauds
+    OC_LOG_INIT();
+    OC_LOG(DEBUG, TAG, PCF("OCServer is starting..."));
+
+    FindNetworkForOnboarding(ES_WIFI, ssid, passwd, EventCallbackInApp);
+
+    // Initialize the OC Stack in Server mode
+    if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
+    {
+        OC_LOG(ERROR, TAG, PCF("OCStack init error"));
+        return;
+    }
+
+    InitializeProvisioning(EventCallbackInApp);
+
+   /* if (OCStartPresence(0) != OC_STACK_OK)
+    {
+        OC_LOG(ERROR, TAG, PCF("Start Presence init error"));
+        return;
+    }
+       */
+}
+
+// The loop function is called in an endless loop
+void loop()
+{
+    // This artificial delay is kept here to avoid endless spinning
+    // of Arduino microcontroller. Modify it as per specific application needs.
+    delay(2000);
+
+    // This call displays the amount of free SRAM available on Arduino
+    PrintArduinoMemoryStats();
+
+    // Give CPU cycles to OCStack to perform send/recv and other OCStack stuff
+    if (OCProcess() != OC_STACK_OK)
+    {
+        OC_LOG(ERROR, TAG, PCF("OCStack process error"));
+        return;
+    }
+}
diff --git a/service/easy-setup/sampleapp/linux/richclient/SConscript b/service/easy-setup/sampleapp/linux/richclient/SConscript
new file mode 100644 (file)
index 0000000..09bddda
--- /dev/null
@@ -0,0 +1,51 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+Import('env')
+
+richclient_env = env.Clone()
+
+target_os = env.get('TARGET_OS')
+
+######################################################################
+# Build flags
+######################################################################
+richclient_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+richclient_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+richclient_env.PrependUnique(CPPPATH = [
+                       env.get('SRC_DIR') + '/resource/csdk/ocmalloc/include',         
+                       env.get('SRC_DIR') + '/resource/csdk/connectivity/common/inc',
+                       env.get('SRC_DIR') + '/resource/csdk/connectivity/api',
+                       env.get('SRC_DIR') + '/resource/csdk/stack/include',
+                       env.get('SRC_DIR') + '/resource/csdk/logger/include',
+                       env.get('SRC_DIR') + '/resource/csdk/security/include',
+                       env.get('SRC_DIR') + '/extlibs/cjson',
+                       env.get('SRC_DIR') + '/service/easy-setup/sdk/mediator/inc',
+                       env.get('SRC_DIR') + '/service/easy-setup/sdk/common'])
+
+richclient_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction', 'coap', 'ESSDKLibrary'])
+
+richclient = richclient_env.Program('richclient', 'easysetupsample.cpp')
+
+i_richclient = richclient_env.Install(env.get('BUILD_DIR'), richclient)
+
+Alias('richclient', i_richclient)
+env.AppendTarget('richclient')
diff --git a/service/easy-setup/sampleapp/linux/richclient/easysetupsample.cpp b/service/easy-setup/sampleapp/linux/richclient/easysetupsample.cpp
new file mode 100644 (file)
index 0000000..54735b9
--- /dev/null
@@ -0,0 +1,113 @@
+//******************************************************************
+//
+// 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 <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <signal.h>
+#include <unistd.h>
+#include <stdint.h>
+#include <sstream>
+
+#include "easysetupmgr.h"
+#include "logger.h"
+
+#define TAG "easysetupsample"
+
+int quitFlag = 0;
+
+/* SIGINT handler: set quitFlag to 1 for graceful termination */
+void handleSigInt(int signum) {
+    if (signum == SIGINT) {
+        quitFlag = 1;
+    }
+}
+
+/**
+ * This callback function is used to receive the notifications about the provisioning status
+ * In success or failure, ProvisioningInfo structure holds the current state of provisioning
+ * and also holds the Enrollee information for which provisioning is requested
+ * This function can be used to update the application about the current provisioning status of the Enrollee
+ */
+void ProvisioningStatusCallback(ProvisioningInfo *provInfo) {
+    OIC_LOG_V(INFO, TAG, "Enrollee connectivity: %d", provInfo->provDeviceInfo.connType);
+    if(provInfo->provStatus == DEVICE_PROVISIONED)
+    {
+        OIC_LOG_V(INFO, TAG, "Successfully provisioned the Enrollee with IP : %s ",
+            provInfo->provDeviceInfo.addr->addr);
+    }
+    else{
+        OIC_LOG_V(INFO, TAG, "Provisioing Failed for the Enrollee with IP : %s",
+            provInfo->provDeviceInfo.addr->addr);
+    }
+}
+
+static void PrintUsage()
+{
+    OIC_LOG(INFO, TAG, "Usage : occlient -d \"192.168.0.20\"");
+}
+
+
+int main (int argc, char**argv) {
+    int opt;
+    EnrolleeNWProvInfo_t netInfo;
+    PrintUsage();
+    InitEasySetupManager();
+
+    RegisterProvisioningStausCallback(ProvisioningStatusCallback);
+
+    while ((opt = getopt(argc, argv, "d:s:p:")) != -1)
+    {
+        switch(opt)
+        {
+            case 'd':
+                strncpy(netInfo.netAddressInfo.WIFI.ipAddress, optarg, IPV4_ADDR_SIZE);
+                break;
+            case 's':
+                strncpy(netInfo.netAddressInfo.WIFI.ssid, optarg, NET_WIFI_SSID_SIZE);
+                break;
+            case 'p':
+                strncpy(netInfo.netAddressInfo.WIFI.pwd, optarg, NET_WIFI_PWD_SIZE);
+                break;
+            default:
+                PrintUsage();
+                return -1;
+        }
+    }
+
+    netInfo.connType = CT_ADAPTER_IP;
+    OIC_LOG_V(INFO, TAG, "IP Address of the Provisioning device is =%s\n",
+                        netInfo.netAddressInfo.WIFI.ipAddress);
+    OIC_LOG_V(INFO, TAG, "SSID of the Enroller is =%s\n",netInfo.netAddressInfo.WIFI.ssid);
+    OIC_LOG_V(INFO, TAG, "Password of the Enroller is =%s\n",netInfo.netAddressInfo.WIFI.pwd);
+
+    ProvisionEnrollee(&netInfo);
+
+    signal(SIGINT, handleSigInt);
+    while (!quitFlag) {
+        sleep(1);
+    }
+
+    TerminateEasySetupManager();
+    OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
+
+    return 0;
+}
+
diff --git a/service/easy-setup/sdk/common/common.h b/service/easy-setup/sdk/common/common.h
new file mode 100644 (file)
index 0000000..281754b
--- /dev/null
@@ -0,0 +1,151 @@
+//******************************************************************
+//
+// Copyright 2014 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 ES_COMMON_H_
+#define ES_COMMON_H_
+
+#include "ocstack.h"
+#include "octypes.h"
+
+// Defines
+#define OIC_STRING_MAX_VALUE 100
+#define IPV4_ADDR_SIZE 16
+#define IP_PORT 6298
+#define NET_WIFI_SSID_SIZE 16
+#define NET_WIFI_PWD_SIZE 16
+
+/**
+ * @brief Mac address length for BT port
+ */
+#define NET_MACADDR_SIZE 18
+
+//The following variable determines the interface (wifi, ethernet etc.)
+//to be used for sending unicast messages. Default set to Ethernet.
+static OCConnectivityType OC_CONNTYPE = CT_ADAPTER_IP;
+
+static const char * UNICAST_PROVISIONING_QUERY = "coap://%s:%d/oic/res?rt=oic.prov";
+static const char * UNICAST_PROV_STATUS_QUERY = "coap://%s:%d%s";
+
+
+/**
+ * Attributes used to form a proper easysetup conforming JSON message.
+ */
+#define OC_RSRVD_ES_PS                     "ps"
+#define OC_RSRVD_ES_TNN                    "tnn"
+#define OC_RSRVD_ES_CD                     "cd"
+#define OC_RSRVD_ES_TR                     "tr"
+#define OC_RSRVD_ES_TNT                    "tnt"
+#define OC_RSRVD_ES_ANT                    "ant"
+#define OC_RSRVD_ES_URI_PROV               "/oic/prov"
+#define OC_RSRVD_ES_URI_NET                "/oic/net"
+
+
+
+typedef enum
+{
+    ES_ERROR = -1,
+    ES_OK = 0,
+    ES_NETWORKFOUND = 1,
+    ES_NETWORKCONNECTED,
+    ES_NETWORKNOTCONNECTED,
+    ES_RESOURCECREATED = 11,
+    ES_RECVREQOFPROVRES = 21,
+    ES_RECVREQOFNETRES,
+    ES_RECVUPDATEOFPROVRES,
+    ES_RECVTRIGGEROFPROVRES,
+} ES_RESULT;
+
+
+/**
+ * Provisioning Device Status
+ */
+typedef struct {
+    /// Address of remote server
+    OCDevAddr * addr;
+    /// Indicates adaptor type on which the response was received
+    OCConnectivityType connType;
+} ProvDeviceInfo;
+
+/**
+ * Provosioning Status
+ */
+typedef enum {
+    DEVICE_PROVISIONED = 0, DEVICE_NOT_PROVISIONED
+} ProvStatus;
+
+/**
+ * Response from queries to remote servers. Queries are made by calling the @ref OCDoResource API.
+ */
+typedef struct {
+    // Provisioning Status
+    ProvStatus provStatus;
+    // Provisioning Device Info
+    ProvDeviceInfo provDeviceInfo;
+} ProvisioningInfo;
+
+/**
+ * @brief  Network information of the Enroller
+ */
+typedef union
+{
+    /**
+     * @brief BT Mac Information
+     */
+    struct
+    {
+        char btMacAddress[NET_MACADDR_SIZE];   /**< BT mac address **/
+    } BT;
+
+    /**
+     * @brief LE MAC Information
+     */
+    struct
+    {
+        char leMacAddress[NET_MACADDR_SIZE];   /**< BLE mac address **/
+    } LE;
+
+    /**
+     * @brief IP Information
+     */
+    struct
+    {
+        char ipAddress[IPV4_ADDR_SIZE]; /**< IP Address of the Enroller**/
+        char ssid[NET_WIFI_SSID_SIZE]; /**< ssid of the Enroller**/
+        char pwd[NET_WIFI_PWD_SIZE]; /**< pwd of the Enroller**/
+    } WIFI;
+} EnrolleeInfo_t;
+
+
+/**
+ * @brief Network Information
+ */
+typedef struct
+{
+    EnrolleeInfo_t netAddressInfo;          /**< Enroller Network Info**/
+    OCConnectivityType connType;            /**< Connectivity Type**/
+    bool isSecured;                         /**< Secure connection**/
+} EnrolleeNWProvInfo_t;
+
+/**
+ * Client applications implement this callback to consume responses received from Servers.
+ */
+typedef void (*OCProvisioningStatusCB)(ProvisioningInfo *provInfo);
+
+#endif
diff --git a/service/easy-setup/sdk/enrollee/arduino/wifi/networkHandler.cpp b/service/easy-setup/sdk/enrollee/arduino/wifi/networkHandler.cpp
new file mode 100644 (file)
index 0000000..95ad75e
--- /dev/null
@@ -0,0 +1,181 @@
+//******************************************************************
+//
+// Copyright 2014 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 "networkHandler.h"
+
+PROGMEM const char TAG[] = "networkHandler";
+
+int findNetwork(const char *ssid);
+int ConnectToNetwork(const char *ssid, const char *pass);
+void printEncryptionType(int thisType);
+
+// Arduino WiFi Shield
+// Note : Arduino WiFi Shield currently does NOT support multicast and therefore
+// this server will NOT be listening on 224.0.1.187 multicast address.
+
+static const char ARDUINO_WIFI_SHIELD_UDP_FW_VER[] = "1.1.0";
+
+IPAddress myIP;
+
+ES_RESULT ConnectToWiFiNetwork(const char *ssid, const char *pass, NetworkEventCallback cb)
+{
+    char *fwVersion;
+    int status = WL_IDLE_STATUS;
+    int res;
+
+    // check for the presence of the shield:
+    if (WiFi.status() == WL_NO_SHIELD)
+    {
+        OC_LOG(ERROR, TAG, PCF("WiFi shield not present"));
+        return ES_ERROR;
+    }
+
+    // Verify that WiFi Shield is running the firmware with all UDP fixes
+    fwVersion = WiFi.firmwareVersion();
+    OC_LOG_V(INFO, TAG, "WiFi Shield Firmware version %s", fwVersion);
+    if (strncmp(fwVersion, ARDUINO_WIFI_SHIELD_UDP_FW_VER, sizeof(ARDUINO_WIFI_SHIELD_UDP_FW_VER))
+            != 0)
+    {
+        OC_LOG(DEBUG, TAG, PCF("!!!!! Upgrade WiFi Shield Firmware version !!!!!!"));
+        //return ES_ERROR;
+    }
+
+    while (findNetwork(ssid) == 0) // found
+    {
+        delay(1000);
+    }
+
+    if (cb != NULL)
+    {
+        cb(ES_NETWORKFOUND);
+    }
+
+    if (WiFi.status() == WL_CONNECTED)
+        WiFi.disconnect();
+
+    res = ConnectToNetwork(ssid, pass);
+
+    if (res == 0)
+    {
+        return ES_NETWORKCONNECTED;
+    }
+    else
+    {
+        return ES_NETWORKNOTCONNECTED;
+    }
+}
+
+int findNetwork(const char *ssid)
+{
+    int res = 0;
+    // scan for nearby networks:
+    Serial.println("** Scan Networks **");
+    int numSsid = WiFi.scanNetworks();
+    if (numSsid == -1)
+    {
+        Serial.println("Couldn't get a wifi connection");
+
+        return res;
+    }
+
+    // print the list of networks seen:
+    Serial.print("number of available networks:");
+    Serial.println(numSsid);
+
+    // print the network number and name for each network found:
+    for (int thisNet = 0; thisNet < numSsid; thisNet++)
+    {
+        Serial.print(thisNet);
+        Serial.print(") ");
+        Serial.print(WiFi.SSID(thisNet));
+        Serial.print("\tEncryption: ");
+        printEncryptionType(WiFi.encryptionType(thisNet));
+
+        if (strcmp(WiFi.SSID(thisNet), ssid) == 0)
+        {
+            res = 1;
+        }
+    }
+
+    return res;
+}
+
+int ConnectToNetwork(const char *ssid, const char *pass)
+{
+    int status = WL_IDLE_STATUS;
+
+    // attempt to connect to Wifi network:
+    while (status != WL_CONNECTED)
+    {
+        OC_LOG_V(INFO, TAG, "Attempting to connect to SSID: %s", ssid);
+
+        status = WiFi.begin((char *) ssid, (char *) pass);
+
+        // wait 10 seconds for connection:
+        delay(10000);
+    }
+    OC_LOG(DEBUG, TAG, PCF("Connected to wifi"));
+
+    myIP = WiFi.localIP();
+    OC_LOG_V(INFO, TAG, "IP Address:  %d.%d.%d.%d", myIP[0], myIP[1], myIP[2], myIP[3]);
+
+    char buf[50];
+    sprintf(buf, "IP Address:  %d.%d.%d.%d", myIP[0], myIP[1], myIP[2], myIP[3]);
+    Serial.println(buf);
+
+    return 0;
+}
+
+int getCurrentNetworkInfo(NetworkType targetType, NetworkInfo *info)
+{
+    if (targetType == ES_WIFI && WiFi.status() == WL_CONNECTED)
+    {
+        info->type = ES_WIFI;
+        info->ipaddr = WiFi.localIP();
+        strcpy(info->ssid, WiFi.SSID());
+
+        return 0;
+    }
+
+    return -1;
+}
+
+void printEncryptionType(int thisType)
+{
+    // read the encryption type and print out the name:
+    switch (thisType)
+    {
+        case ENC_TYPE_WEP:
+            Serial.println("WEP");
+            break;
+        case ENC_TYPE_TKIP:
+            Serial.println("WPA");
+            break;
+        case ENC_TYPE_CCMP:
+            Serial.println("WPA2");
+            break;
+        case ENC_TYPE_NONE:
+            Serial.println("None");
+            break;
+        case ENC_TYPE_AUTO:
+            Serial.println("Auto");
+            break;
+    }
+}
diff --git a/service/easy-setup/sdk/enrollee/arduino/wifi/networkHandler.h b/service/easy-setup/sdk/enrollee/arduino/wifi/networkHandler.h
new file mode 100644 (file)
index 0000000..7509940
--- /dev/null
@@ -0,0 +1,65 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+// Do not remove the include below
+#include "Arduino.h"
+
+#include "logger.h"
+#include "ocstack.h"
+#include <string.h>
+
+// Arduino WiFi Shield
+#include <SPI.h>
+#include <WiFi.h>
+#include <WiFiUdp.h>
+
+#include "common.h"
+
+#ifndef ES_NETWORK_HANDLER_H_
+#define ES_NETWORK_HANDLER_H_
+
+#define MAXSSIDLEN 33
+#define MAXNETCREDLEN 20
+#define MAXNUMTYPE 5
+#define MAXADDRLEN 15
+
+typedef void (*NetworkEventCallback)(ES_RESULT);
+
+enum NetworkType
+{
+    ES_WIFI = 1, ES_BT = 2, ES_BLE = 3, ES_ZIGBEE = 4, ES_ETH = 5
+};
+
+typedef struct NETWORKINFO
+{
+    NetworkType type;
+
+    // for WiFI
+    IPAddress ipaddr;
+    char ssid[MAXSSIDLEN];
+
+    // for BT, BLE
+    byte mac[6];
+} NetworkInfo;
+
+ES_RESULT ConnectToWiFiNetwork(const char *ssid, const char *pass, NetworkEventCallback);
+int getCurrentNetworkInfo(NetworkType targetType, NetworkInfo *info);
+
+#endif
diff --git a/service/easy-setup/sdk/enrollee/common/inc/easysetup.h b/service/easy-setup/sdk/enrollee/common/inc/easysetup.h
new file mode 100644 (file)
index 0000000..9066e50
--- /dev/null
@@ -0,0 +1,43 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+// Do not remove the include below
+#include "Arduino.h"
+
+#include "logger.h"
+#include "ocstack.h"
+#include <string.h>
+
+#include "common.h"
+#include "networkHandler.h"
+#include "resourceHandler.h"
+
+typedef void (*EventCallback)(ES_RESULT);
+
+OCStackResult Init();
+
+ES_RESULT FindNetworkForOnboarding(NetworkType networkType, EventCallback);
+ES_RESULT FindNetworkForOnboarding(NetworkType networkType, const char *name, const char *pass,
+        EventCallback);
+
+//OCStackResult FindNetworkForOnboarding(NetworkType networkType, char *name);
+//OCStackResult FindNetworkForOnboarding(NetworkType networkType, char *name, char *pass);
+
+ES_RESULT InitializeProvisioning(EventCallback);
diff --git a/service/easy-setup/sdk/enrollee/common/inc/resourceHandler.h b/service/easy-setup/sdk/enrollee/common/inc/resourceHandler.h
new file mode 100644 (file)
index 0000000..0f1567f
--- /dev/null
@@ -0,0 +1,62 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+// Do not remove the include below
+#include "Arduino.h"
+
+#include "logger.h"
+#include "ocstack.h"
+#include <string.h>
+
+#include "common.h"
+#include "networkHandler.h"
+#include "octypes.h"
+
+#ifndef ES_RESOURCE_HANDLER_H_
+#define ES_RESOURCE_HANDLER_H_
+
+typedef void (*ResourceEventCallback)(ES_RESULT);
+
+/* Structure to represent a Light resource */
+typedef struct PROVRESOURCE
+{
+    OCResourceHandle handle;
+    int ps; // provisiong status, 1 : need to provisioning, 2 : Connected to Internet
+    int tnt; // target network type, 1: WLAN, 2: BT, 3: BLE, 4: Zigbee, ...
+    char tnn[MAXSSIDLEN]; // target network name, i.e. SSID for WLAN, MAC address for BT
+    char cd[MAXNETCREDLEN]; // credential information
+} ProvResource;
+
+/* Structure to represent a Light resource */
+typedef struct NETRESOURCE
+{
+    OCResourceHandle handle;
+    int cnt; // current network type, 1: WLAN, 2: BT, 3: BLE, 4: Zigbee, ...
+    int ant[MAXNUMTYPE]; // available network type, 1: WLAN, 2: BT, 3: BLE, 4: Zigbee, ...
+    char ipaddr[MAXADDRLEN]; // ip address
+    char cnn[MAXSSIDLEN]; // current network name
+} NetResource;
+
+OCStackResult CreateProvisioningResource();
+OCStackResult CreateNetworkResource();
+void GetTargetNetworkInfoFromProvResource(char *, char *);
+void RegisterResourceEventCallBack(ResourceEventCallback);
+
+#endif
diff --git a/service/easy-setup/sdk/enrollee/common/src/easysetup.cpp b/service/easy-setup/sdk/enrollee/common/src/easysetup.cpp
new file mode 100644 (file)
index 0000000..c44fdf0
--- /dev/null
@@ -0,0 +1,138 @@
+//******************************************************************
+//
+// Copyright 2014 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 "easysetup.h"
+
+/// WiFi network info and credentials
+char defaultSsid[] = "EasyConnect";
+char defaultPass[] = "EasyConnect";
+
+int g_eventflag = 0;
+int g_cnt = 0;
+char *targetSsid;
+char *targetPass;
+
+EventCallback g_cbForProvisioning = NULL;
+EventCallback g_cbForOnboarding = NULL;
+
+void EventCallbackInOnboarding(ES_RESULT event);
+void EventCallbackInProvisioning(ES_RESULT event);
+void EventCallbackAfterProvisioning(ES_RESULT event);
+
+void EventCallbackInOnboarding(ES_RESULT event)
+{
+    if (event == ES_NETWORKFOUND || event == ES_NETWORKCONNECTED)
+    {
+        if (g_cbForOnboarding != NULL)
+        {
+            g_cbForOnboarding(event);
+        }
+    }
+}
+
+void EventCallbackInProvisioning(ES_RESULT event)
+{
+    ES_RESULT res = ES_OK;
+
+    if (event == ES_RECVTRIGGEROFPROVRES)
+    {
+        targetSsid = (char *) malloc(MAXSSIDLEN);
+        targetPass = (char *) malloc(MAXNETCREDLEN);
+
+        GetTargetNetworkInfoFromProvResource(targetSsid, targetPass);
+
+        res = ConnectToWiFiNetwork(targetSsid, targetPass, EventCallbackAfterProvisioning);
+
+        if (g_cbForProvisioning != NULL)
+        {
+            g_cbForProvisioning(res);
+        }
+    }
+}
+
+void EventCallbackAfterProvisioning(ES_RESULT event)
+{
+    if (event == ES_NETWORKFOUND || event == ES_NETWORKCONNECTED)
+    {
+        if (g_cbForProvisioning != NULL)
+        {
+            g_cbForProvisioning(event);
+        }
+    }
+}
+
+ES_RESULT FindNetworkForOnboarding(NetworkType networkType, EventCallback cb)
+{
+    if (networkType == ES_WIFI)
+    {
+        if (g_cbForOnboarding == NULL)
+        {
+            g_cbForOnboarding = cb;
+        }
+
+        return ConnectToWiFiNetwork(defaultSsid, defaultPass, EventCallbackInOnboarding);
+    }
+}
+
+ES_RESULT FindNetworkForOnboarding(NetworkType networkType, const char *ssid, const char *passwd,
+        EventCallback cb)
+{
+    if (!ssid || !passwd)
+    {
+        return ES_ERROR;
+    }
+
+    if (networkType == ES_WIFI)
+    {
+        if (g_cbForOnboarding == NULL)
+        {
+            g_cbForOnboarding = cb;
+        }
+
+        return ConnectToWiFiNetwork(ssid, passwd, EventCallbackInOnboarding);
+    }
+}
+
+ES_RESULT InitializeProvisioning(EventCallback cb)
+{
+    if (cb == NULL)
+    {
+        return ES_ERROR;
+    }
+    else
+    {
+        g_cbForProvisioning = cb;
+    }
+
+    if (CreateProvisioningResource() != OC_STACK_OK)
+    {
+        return ES_ERROR;
+    }
+
+    if (CreateNetworkResource() != OC_STACK_OK)
+    {
+        return ES_ERROR;
+    }
+
+    RegisterResourceEventCallBack(EventCallbackInProvisioning);
+
+    return ES_RESOURCECREATED;
+}
+
diff --git a/service/easy-setup/sdk/enrollee/common/src/resourceHandler.cpp b/service/easy-setup/sdk/enrollee/common/src/resourceHandler.cpp
new file mode 100644 (file)
index 0000000..8024fdd
--- /dev/null
@@ -0,0 +1,336 @@
+//******************************************************************
+//
+// Copyright 2014 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 "resourceHandler.h"
+#include "ocpayload.h"
+
+PROGMEM const char TAG[] = "resourceHandler";
+
+ProvResource g_prov;
+NetResource g_net;
+
+OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag, OCEntityHandlerRequest *, void *callback);
+const char *getResult(OCStackResult result);
+
+OCEntityHandlerResult ProcessGetRequest(OCEntityHandlerRequest *ehRequest,OCRepPayload** payload);
+OCEntityHandlerResult ProcessPutRequest(OCEntityHandlerRequest *ehRequest,OCRepPayload** payload);
+OCEntityHandlerResult ProcessPostRequest(OCEntityHandlerRequest *ehRequest,OCRepPayload** payload);
+OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest);
+int g_flag = 0;
+
+ResourceEventCallback g_cbForResEvent = NULL;
+
+void RegisterResourceEventCallBack(ResourceEventCallback cb)
+{
+       g_cbForResEvent = cb;
+}
+
+void GetTargetNetworkInfoFromProvResource(char *name, char *pass)
+{
+       if (name != NULL && pass != NULL)
+       {
+               sprintf(name, "%s", g_prov.tnn);
+               sprintf(pass, "%s", g_prov.cd);
+       }
+}
+
+OCStackResult CreateProvisioningResource()
+{
+       g_prov.ps = 1; // need to provisioning
+       g_prov.tnt = ES_WIFI;
+       sprintf(g_prov.tnn, "Unknown");
+       sprintf(g_prov.cd, "Unknown");
+
+       OCStackResult res = OCCreateResource(&g_prov.handle, "oic.prov", OC_RSRVD_INTERFACE_DEFAULT,
+                       OC_RSRVD_ES_URI_PROV, OCEntityHandlerCb,NULL, OC_DISCOVERABLE | OC_OBSERVABLE);
+
+       OC_LOG_V(INFO, TAG, "Created Prov resource with result: %s", getResult(res));
+
+       return res;
+}
+
+OCStackResult CreateNetworkResource()
+{
+       NetworkInfo netInfo;
+
+       if (getCurrentNetworkInfo(ES_WIFI, &netInfo) != 0)
+       {
+               return OC_STACK_ERROR;
+       }
+
+       if (netInfo.type != ES_WIFI)
+       {
+               return OC_STACK_ERROR;
+       }
+
+       g_net.cnt = (int) netInfo.type;
+       g_net.ant[0] = (int) ES_WIFI;
+       sprintf(g_net.ipaddr, "%d.%d.%d.%d", netInfo.ipaddr[0], netInfo.ipaddr[1], netInfo.ipaddr[2],
+                       netInfo.ipaddr[3]);
+       sprintf(g_net.cnn, "%s", netInfo.ssid);
+
+       OC_LOG_V(INFO, TAG, "SSID: %s", g_net.cnn);
+       OC_LOG_V(INFO, TAG, "IP Address: %s", g_net.ipaddr);
+
+       OCStackResult res = OCCreateResource(&g_net.handle, "oic.net", OC_RSRVD_INTERFACE_DEFAULT,
+                       OC_RSRVD_ES_URI_NET, OCEntityHandlerCb,NULL, OC_DISCOVERABLE | OC_OBSERVABLE);
+       OC_LOG_V(INFO, TAG, "Created Net resource with result: %s", getResult(res));
+
+       return res;
+}
+
+OCEntityHandlerResult ProcessGetRequest(OCEntityHandlerRequest *ehRequest, OCRepPayload **payload)
+{
+       OCEntityHandlerResult ehResult = OC_EH_ERROR;
+       OCRepPayload *getResp = constructResponse(ehRequest);
+       if(!getResp)
+       {
+               OC_LOG(ERROR, TAG, "constructResponse failed");
+               return OC_EH_ERROR;
+       }
+
+       *payload = getResp;
+       ehResult = OC_EH_OK;
+
+       return ehResult;
+}
+
+OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
+               OCRepPayload** payload)
+{
+
+       OCEntityHandlerResult ehResult=OC_EH_ERROR;
+       if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
+       {
+               OC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
+               return ehResult;
+       }
+
+       OCRepPayload* input = (OCRepPayload*)(ehRequest->payload);
+       if(!input)
+       {
+               OC_LOG_V(ERROR, TAG, "Failed to parse");
+               return ehResult;
+       }
+
+       const char* tnn;
+       if(OCRepPayloadGetPropString(input,OC_RSRVD_ES_TNN, &tnn))
+       {
+               sprintf(g_prov.tnn, "%s", tnn);
+       }
+
+       const char* cd;
+       if(OCRepPayloadGetPropString(input, OC_RSRVD_ES_CD, &cd))
+       {
+               sprintf(g_prov.cd, "%s", cd);
+       }
+
+       g_flag = 1;
+
+       OCRepPayload *getResp = constructResponse(ehRequest);
+       if(!getResp)
+       {
+               OC_LOG(ERROR, TAG, "constructResponse failed");
+               return OC_EH_ERROR;
+       }
+
+       *payload = getResp;
+       ehResult = OC_EH_OK;
+
+
+
+       return ehResult;
+}
+
+
+OCEntityHandlerResult ProcessPostRequest(OCEntityHandlerRequest *ehRequest, OCRepPayload** payload)
+{
+       OCEntityHandlerResult ehResult = OC_EH_ERROR;
+       if(!ehRequest)
+       {
+               OC_LOG(ERROR, TAG, PCF("Request is Null"));
+               return ehResult;
+       }
+       if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
+       {
+               OC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
+               return ehResult;
+       }
+
+       OCRepPayload* input = (OCRepPayload*)(ehRequest->payload);
+       if(!input)
+       {
+               OC_LOG_V(ERROR, TAG, "Failed to parse" );
+               return ehResult;
+       }
+       const char* tr;
+       if(OCRepPayloadGetPropString(input, OC_RSRVD_ES_TR, &tr))
+       {
+
+               // Triggering
+               ehResult = OC_EH_OK;
+       }
+
+       g_flag = 1;
+
+       return ehResult;
+}
+
+OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest)
+{
+
+       OCRepPayload* payload = OCRepPayloadCreate();
+       if(!payload)
+       {
+               OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
+               return NULL;
+       }
+
+       if (g_prov.handle != NULL && ehRequest->resource == g_prov.handle)
+       {
+
+               
+               OCRepPayloadSetUri(payload,OC_RSRVD_ES_URI_PROV);
+
+               OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_PS,g_prov.ps);
+               OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_TNT, g_prov.tnt);
+               OCRepPayloadSetPropString(payload,OC_RSRVD_ES_TNN, g_prov.tnn);
+               OCRepPayloadSetPropString(payload,OC_RSRVD_ES_CD, g_prov.cd);
+       }
+       else if (g_net.handle != NULL && ehRequest->requestHandle == g_net.handle)
+       {
+               
+               OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_NET);
+               OCRepPayloadSetPropInt(payload, "ant", g_net.ant[0]);
+       }
+       return payload;
+}
+
+// This is the entity handler for the registered resource.
+// This is invoked by OCStack whenever it recevies a request for this resource.
+
+OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
+               OCEntityHandlerRequest* entityHandlerRequest,void *callback)
+{
+       (void)callback;
+       OCEntityHandlerResult ehRet = OC_EH_OK;
+       OCEntityHandlerResponse response =
+       { 0 };
+       OCRepPayload* payload = NULL;
+       if (entityHandlerRequest && (flag & OC_REQUEST_FLAG))
+       {
+               if (OC_REST_GET == entityHandlerRequest->method)
+               {
+                       OC_LOG_V(INFO, TAG, "Received GET request");
+                       ehRet = ProcessGetRequest(entityHandlerRequest, &payload);
+               }
+               else if (OC_REST_PUT == entityHandlerRequest->method)
+               {
+                       OC_LOG_V(INFO, TAG, "Received PUT request");
+
+                       if (g_prov.handle != NULL && entityHandlerRequest->resource == g_prov.handle)
+                       {
+                               ehRet = ProcessPutRequest(entityHandlerRequest, &payload);
+                       }
+                       else
+                       {
+                               ehRet = OC_EH_ERROR;
+                       }
+               }
+               else if (OC_REST_POST == entityHandlerRequest->method)
+               {
+                       // TODO: As of now, POST request will be not received.
+                       OC_LOG(INFO, TAG, "Received OC_REST_POST from client");
+                       //ehRet = ProcessPostRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
+               }
+
+               if (ehRet == OC_EH_OK)
+               {
+                       // Format the response.  Note this requires some info about the request
+                       response.requestHandle = entityHandlerRequest->requestHandle;
+                       response.resourceHandle = entityHandlerRequest->resource;
+                       response.ehResult = ehRet;
+                       response.payload = (OCPayload*)(&payload);  //response uses OCPaylod while all get,put methodes use OCRepPayload 
+                       response.numSendVendorSpecificHeaderOptions = 0;
+                       memset(response.sendVendorSpecificHeaderOptions, 0,
+                                       sizeof response.sendVendorSpecificHeaderOptions);
+                       memset(response.resourceUri, 0, sizeof response.resourceUri);
+                       // Indicate that response is NOT in a persistent buffer
+                       response.persistentBufferFlag = 0;
+
+                       // Send the response
+                       if (OCDoResponse(&response) != OC_STACK_OK)
+                       {
+                               OC_LOG(ERROR, TAG, "Error sending response");
+                               ehRet = OC_EH_ERROR;
+                       }
+               }
+       }
+
+       if (g_flag == 1)
+       {
+               g_cbForResEvent(ES_RECVTRIGGEROFPROVRES);
+               g_flag = 0;
+       }
+
+       return ehRet;
+}
+
+const char *getResult(OCStackResult result)
+{
+       switch (result)
+       {
+       case OC_STACK_OK:
+               return "OC_STACK_OK";
+       case OC_STACK_INVALID_URI:
+               return "OC_STACK_INVALID_URI";
+       case OC_STACK_INVALID_QUERY:
+               return "OC_STACK_INVALID_QUERY";
+       case OC_STACK_INVALID_IP:
+               return "OC_STACK_INVALID_IP";
+       case OC_STACK_INVALID_PORT:
+               return "OC_STACK_INVALID_PORT";
+       case OC_STACK_INVALID_CALLBACK:
+               return "OC_STACK_INVALID_CALLBACK";
+       case OC_STACK_INVALID_METHOD:
+               return "OC_STACK_INVALID_METHOD";
+       case OC_STACK_NO_MEMORY:
+               return "OC_STACK_NO_MEMORY";
+       case OC_STACK_COMM_ERROR:
+               return "OC_STACK_COMM_ERROR";
+       case OC_STACK_INVALID_PARAM:
+               return "OC_STACK_INVALID_PARAM";
+       case OC_STACK_NOTIMPL:
+               return "OC_STACK_NOTIMPL";
+       case OC_STACK_NO_RESOURCE:
+               return "OC_STACK_NO_RESOURCE";
+       case OC_STACK_RESOURCE_ERROR:
+               return "OC_STACK_RESOURCE_ERROR";
+       case OC_STACK_SLOW_RESOURCE:
+               return "OC_STACK_SLOW_RESOURCE";
+       case OC_STACK_NO_OBSERVERS:
+               return "OC_STACK_NO_OBSERVERS";
+       case OC_STACK_ERROR:
+               return "OC_STACK_ERROR";
+       default:
+               return "UNKNOWN";
+       }
+}
+
diff --git a/service/easy-setup/sdk/mediator/android/.gitignore b/service/easy-setup/sdk/mediator/android/.gitignore
new file mode 100644 (file)
index 0000000..6451fc5
--- /dev/null
@@ -0,0 +1,50 @@
+#built application files\r
+*.apk\r
+*.ap_\r
+\r
+# files for the dex VM\r
+*.dex\r
+\r
+# Java class files\r
+*.class\r
+\r
+# generated files\r
+bin/\r
+gen/\r
+\r
+# Local configuration file (sdk path, etc)\r
+local.properties\r
+\r
+# Proguard folder generated by Eclipse \r
+proguard/ \r
+\r
+# Windows thumbnail db\r
+Thumbs.db\r
+\r
+# OSX files\r
+.DS_Store\r
+\r
+# Eclipse project files\r
+.classpath\r
+.project\r
+\r
+#Android Studio & Gradle\r
+.gradle\r
+/local.properties\r
+/.idea/workspace.xml\r
+/.idea/libraries\r
+.DS_Store\r
+/build/*\r
+/base/build/*\r
+/base/obj/*\r
+/base/libs/*\r
+/sample/*\r
+\r
+#Some older projects\r
+/*/out\r
+/*/*/build\r
+/*/*/production\r
+*.iws\r
+*.ipr\r
+*~\r
+*.swp
\ No newline at end of file
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/build.gradle b/service/easy-setup/sdk/mediator/android/EasySetupCore/build.gradle
new file mode 100644 (file)
index 0000000..c1f2134
--- /dev/null
@@ -0,0 +1,40 @@
+apply plugin: 'com.android.library'\r
+// Top-level build file where you can add configuration options common to all sub-projects/modules.\r
+buildscript {\r
+    repositories {\r
+        jcenter()\r
+    }\r
+    dependencies {\r
+        classpath 'com.android.tools.build:gradle:1.2.3'\r
+    }\r
+}\r
+\r
+allprojects {\r
+    repositories {\r
+        jcenter()\r
+    }\r
+}\r
+\r
+android {\r
+    compileSdkVersion 21\r
+    buildToolsVersion '21.1.2'\r
+\r
+    defaultConfig {\r
+        minSdkVersion 21\r
+        targetSdkVersion 21\r
+    }\r
+\r
+    buildTypes {\r
+        release {\r
+            minifyEnabled false\r
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'\r
+        }\r
+    }\r
+    sourceSets {\r
+        main { java.srcDirs = ['src/main/java', 'src/main/java/common', 'src/main/java/interface'] }\r
+    }\r
+}\r
+\r
+dependencies {\r
+    compile project(':iotivity-armeabi-base-debug')\r
+}
\ No newline at end of file
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/easySetupCore.iml b/service/easy-setup/sdk/mediator/android/EasySetupCore/easySetupCore.iml
new file mode 100644 (file)
index 0000000..915035d
--- /dev/null
@@ -0,0 +1,93 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module external.linked.project.id="EasySetupCore" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
+  <component name="FacetManager">
+    <facet type="android-gradle" name="Android-Gradle">
+      <configuration>
+        <option name="GRADLE_PROJECT_PATH" value=":" />
+      </configuration>
+    </facet>
+    <facet type="android" name="Android">
+      <configuration>
+        <option name="SELECTED_BUILD_VARIANT" value="debug" />
+        <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
+        <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
+        <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
+        <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugAndroidTest" />
+        <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugAndroidTestSources" />
+        <option name="ALLOW_USER_CONFIGURATION" value="false" />
+        <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
+        <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
+        <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
+        <option name="LIBRARY_PROJECT" value="true" />
+      </configuration>
+    </facet>
+  </component>
+  <component name="NewModuleRootManager" inherit-compiler-output="false">
+    <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
+    <output-test url="file://$MODULE_DIR$/build/intermediates/classes/androidTest/debug" />
+    <exclude-output />
+    <content url="file://$MODULE_DIR$">
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/androidTest/debug" type="java-test-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/java/common" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/java/interface" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/EasySetupCore/iotivity-armeabi-base-debug/unspecified/jars" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
+      <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
+      <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
+    </content>
+    <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
+    <orderEntry type="sourceFolder" forTests="false" />
+    <orderEntry type="module" module-name="iotivity-armeabi-base-debug" exported="" />
+    <orderEntry type="library" exported="" name="iotivity-armeabi-base-debug-unspecified" level="project" />
+  </component>
+</module>
\ No newline at end of file
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/settings.gradle b/service/easy-setup/sdk/mediator/android/EasySetupCore/settings.gradle
new file mode 100644 (file)
index 0000000..3f6e49d
--- /dev/null
@@ -0,0 +1 @@
+include ':iotivity-armeabi-base-debug'
\ No newline at end of file
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/AndroidManifest.xml b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/AndroidManifest.xml
new file mode 100644 (file)
index 0000000..a77611d
--- /dev/null
@@ -0,0 +1,17 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"\r
+    package="org.iotivity.service.easysetup.mediator"\r
+    android:versionCode="1"\r
+    android:versionName="1.0" >\r
+\r
+    <uses-sdk\r
+        android:minSdkVersion="8"\r
+        android:targetSdkVersion="21" />\r
+\r
+    <application\r
+        android:allowBackup="true"\r
+        android:icon="@drawable/ic_launcher"\r
+        android:label="@string/app_name"\r
+        android:theme="@style/AppTheme" >\r
+    </application>\r
+\r
+</manifest>\r
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EasySetupCallbackHandler.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EasySetupCallbackHandler.java
new file mode 100644 (file)
index 0000000..2137f60
--- /dev/null
@@ -0,0 +1,51 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+package org.iotivity.service.easysetup.mediator;\r
+\r
+import android.util.Log;\r
+\r
+public class EasySetupCallbackHandler {\r
+    private static final String             TAG = "ESCallbackHandler";\r
+    ProvisionEnrollee                       provisioningListener;\r
+\r
+    private static EasySetupCallbackHandler easySetupCallbackHandlerObj;\r
+\r
+    public static synchronized EasySetupCallbackHandler getInstance() {\r
+        if (null == easySetupCallbackHandlerObj) {\r
+            easySetupCallbackHandlerObj = new EasySetupCallbackHandler();\r
+        }\r
+        return easySetupCallbackHandlerObj;\r
+    }\r
+\r
+    public void ProvisioningStatusCallBack(int statuscode) {\r
+        // TODO Auto-generated method stub\r
+        Log.d(TAG, "onFinishProvisioning(). statuscode - " + statuscode);\r
+        if (this.provisioningListener != null) {\r
+            this.provisioningListener.ProvisioningStatusCallBack(statuscode);\r
+        } else {\r
+            Log.e(TAG, "provisioningListener is not registered");\r
+        }\r
+    }\r
+\r
+    public void registerProvisioningHandler(\r
+            ProvisionEnrollee provisioningListener) {\r
+        this.provisioningListener = provisioningListener;\r
+    }\r
+}\r
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EasySetupManager.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EasySetupManager.java
new file mode 100644 (file)
index 0000000..b65f785
--- /dev/null
@@ -0,0 +1,68 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+package org.iotivity.service.easysetup.mediator;\r
+\r
+import android.content.Context;\r
+\r
+public class EasySetupManager {\r
+    private native void InitEasySetup();\r
+    private native void TerminateEasySetup();\r
+    private native void ProvisionEnrollee(String ipAddress, String netSSID,\r
+            String netPWD, int connectivityType);\r
+    private native void StopEnrolleeProvisioning(int connectivityType);\r
+    private static EasySetupManager easySetupManagerInterfaceObj = null;\r
+    private Context                 appContext                   = null;\r
+\r
+    private EasySetupManager() {\r
+\r
+    }\r
+\r
+    /**\r
+     * Function for Getting instance of EasySetupManager object.\r
+     *\r
+     * @return EasySetupManager instance.\r
+     *\r
+     */\r
+    public static synchronized EasySetupManager getInstance() {\r
+        if (null == easySetupManagerInterfaceObj) {\r
+            easySetupManagerInterfaceObj = new EasySetupManager();\r
+        }\r
+        return easySetupManagerInterfaceObj;\r
+    }\r
+\r
+    public void initEasySetup() {\r
+        InitEasySetup();\r
+    }\r
+\r
+    public void terminateEasySetup() {\r
+        TerminateEasySetup();\r
+    }\r
+\r
+    public void provisionIPEnrollee(String ipAddress, String netSSID,\r
+            String netPWD, int connectivityType) {\r
+\r
+        ProvisionEnrollee(ipAddress, netSSID, netPWD, connectivityType);\r
+    }\r
+\r
+    public void stopEnrolleeProvisioning(int connectivityType) {\r
+        StopEnrolleeProvisioning(connectivityType);\r
+    }\r
+\r
+}\r
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeOnBoardingInfo.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeOnBoardingInfo.java
new file mode 100644 (file)
index 0000000..fa7e8b4
--- /dev/null
@@ -0,0 +1,72 @@
+/******************************************************************
+ *
+ * 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 org.iotivity.service.easysetup.mediator;
+
+import org.iotivity.service.easysetup.mediator.common.EnrolleeDevice;
+
+public class EnrolleeOnBoardingInfo {
+
+    private EnrolleeDevice enrolleeDevice;
+    private boolean isReachable;
+    private boolean isAdditionNotified;
+    private boolean isRemovalNotified;
+
+    public EnrolleeOnBoardingInfo(EnrolleeDevice enrolleeDevice,
+            boolean isReachable, boolean isRemovalNotified,
+            boolean isAdditionNotified) {
+        this.enrolleeDevice = enrolleeDevice;
+        this.isReachable = isReachable;
+        this.isRemovalNotified = isRemovalNotified;
+        this.isAdditionNotified = isAdditionNotified;
+    }
+
+    public void setEnrolleeDevice(EnrolleeDevice enrolleeDevice) {
+        this.enrolleeDevice = enrolleeDevice;
+    }
+
+    public EnrolleeDevice getEnrolleeDevice() {
+        return this.enrolleeDevice;
+    }
+
+    public boolean isReachable() {
+        return isReachable;
+    }
+
+    public void setReachable(boolean isReachable) {
+        this.isReachable = isReachable;
+    }
+
+    public boolean isRemovalNotified() {
+        return isRemovalNotified;
+    }
+
+    public void setRemovalNotified(boolean isRemovalNotified) {
+        this.isRemovalNotified = isRemovalNotified;
+    }
+
+    public boolean isAdditionNotified() {
+        return isAdditionNotified;
+    }
+
+    public void setAdditionNotified(boolean isAdditionNotified) {
+        this.isAdditionNotified = isAdditionNotified;
+    }
+
+}
\ No newline at end of file
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/IOnBoardingStatus.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/IOnBoardingStatus.java
new file mode 100644 (file)
index 0000000..a7bc24d
--- /dev/null
@@ -0,0 +1,36 @@
+/******************************************************************
+ *
+ * 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 org.iotivity.service.easysetup.mediator;
+
+import org.iotivity.service.easysetup.mediator.common.EnrolleeDevice;
+
+public interface IOnBoardingStatus {
+
+    /**
+     * Interface called when the scan method finishes. Network operations should
+     * not execute on UI thread
+     * 
+     * @param enrolleeDevice
+     *            of {@link EnrolleeDevice}
+     */
+
+    public void deviceOnBoardingStatus(EnrolleeDevice enrolleeDevice);
+
+}
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/IProvisioningListener.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/IProvisioningListener.java
new file mode 100644 (file)
index 0000000..a178401
--- /dev/null
@@ -0,0 +1,28 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+package org.iotivity.service.easysetup.mediator;\r
+\r
+public interface IProvisioningListener {\r
+    /**\r
+     * Interface called when the provisioning finishes\r
+     */\r
+\r
+    public void onFinishProvisioning(int statuscode);\r
+}\r
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/OnBoardEnrollee.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/OnBoardEnrollee.java
new file mode 100644 (file)
index 0000000..87f8a8f
--- /dev/null
@@ -0,0 +1,68 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+package org.iotivity.service.easysetup.mediator;\r
+\r
+import android.content.Context;\r
+\r
+import org.iotivity.base.OcConnectivityType;\r
+import org.iotivity.service.easysetup.mediator.common.OnBoardingConfig;\r
+import org.iotivity.service.easysetup.mediator.ip.WiFiSoftAPManager;\r
+import org.iotivity.service.easysetup.mediator.ip.WiFiSoftAPOnBoardingConfig;\r
+\r
+public class OnBoardEnrollee {\r
+    WiFiSoftAPManager wifiSoftAPManager;\r
+    IOnBoardingStatus deviceScanListener;\r
+    OcConnectivityType selectedConnectivityType;\r
+\r
+    /**\r
+     * Constructor for OnBoardEnrollee.\r
+     */\r
+    public OnBoardEnrollee(Context context, OcConnectivityType connectivityType) {\r
+        if(connectivityType == OcConnectivityType.IPV4) {\r
+            wifiSoftAPManager = new WiFiSoftAPManager(context);\r
+        }\r
+        this.selectedConnectivityType = connectivityType;\r
+    }\r
+\r
+    public void registerOnBoardingStatusHandler(\r
+            IOnBoardingStatus deviceScanListener) {\r
+        this.deviceScanListener = deviceScanListener;\r
+    }\r
+\r
+    public void startDeviceScan(final int reachableTimeout) {\r
+        if(selectedConnectivityType == OcConnectivityType.IPV4) {\r
+            wifiSoftAPManager.getClientList(this.deviceScanListener, reachableTimeout);\r
+        }\r
+    }\r
+\r
+    public void enableNetwork(OnBoardingConfig transportConfig, boolean enabled) {\r
+        if(selectedConnectivityType == OcConnectivityType.IPV4) {\r
+            wifiSoftAPManager.setWifiApEnabled(\r
+                    ((WiFiSoftAPOnBoardingConfig)transportConfig).getNetConfig(),\r
+                    true);\r
+        }\r
+    }\r
+\r
+    public void disableWiFiAP() {\r
+        if(selectedConnectivityType == OcConnectivityType.IPV4) {\r
+            wifiSoftAPManager.setWifiApEnabled(null, false);\r
+        }\r
+    }\r
+}\r
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ProvisionEnrollee.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ProvisionEnrollee.java
new file mode 100644 (file)
index 0000000..91c8d20
--- /dev/null
@@ -0,0 +1,67 @@
+package org.iotivity.service.easysetup.mediator;\r
+\r
+import android.content.Context;\r
+import android.util.Log;\r
+\r
+import org.iotivity.base.OcConnectivityType;\r
+import org.iotivity.service.easysetup.mediator.common.ProvisioningInfo;\r
+import org.iotivity.service.easysetup.mediator.ip.IPProvisioningInfo;\r
+\r
+public class ProvisionEnrollee {\r
+    private static final String   TAG                            = "ProvisionEnrollee";\r
+    private EasySetupManager      easySetupManagerNativeInstance = null;\r
+    private IProvisioningListener provisioningListener;\r
+\r
+    static {\r
+        // Load Easy Setup JNI interface\r
+        System.loadLibrary("gnustl_shared");\r
+        System.loadLibrary("octbstack");\r
+        System.loadLibrary("connectivity_abstraction");\r
+        System.loadLibrary("easysetup-jni");\r
+    }\r
+    /**\r
+     * Constructor for ProvisionEnrollee. Constructs a new ProvisionEnrollee.\r
+     */\r
+    public ProvisionEnrollee(Context context) {\r
+        easySetupManagerNativeInstance = EasySetupManager.getInstance();\r
+    }\r
+    \r
+    @Override\r
+    protected void finalize() throws Throwable {\r
+        super.finalize();\r
+        easySetupManagerNativeInstance.terminateEasySetup();\r
+    }\r
+\r
+    public void provisionEnrollee(ProvisioningInfo provisioningInfo,\r
+                                  OcConnectivityType connectivityType) {\r
+        if(connectivityType == OcConnectivityType.IPV4)\r
+        {\r
+            easySetupManagerNativeInstance.initEasySetup();\r
+            easySetupManagerNativeInstance.provisionIPEnrollee(\r
+                    ((IPProvisioningInfo)provisioningInfo).getIpAddress(),\r
+                    ((IPProvisioningInfo)provisioningInfo).getNetSSID(),\r
+                    ((IPProvisioningInfo)provisioningInfo).getNetPWD(),\r
+                    OcConnectivityType.IPV4.getValue());\r
+        }\r
+    }\r
+\r
+    public void stopEnrolleeProvisioning(OcConnectivityType connectivityType) {\r
+        easySetupManagerNativeInstance\r
+                .stopEnrolleeProvisioning(OcConnectivityType.IPV4.getValue());\r
+    }\r
+\r
+    public void ProvisioningStatusCallBack(int statuscode) {\r
+        // TODO Auto-generated method stub\r
+        Log.d(TAG,\r
+                "onFinishProvisioning() inside Android Java application. statuscode - "\r
+                        + statuscode);\r
+        this.provisioningListener.onFinishProvisioning(statuscode);\r
+    }\r
+\r
+    public void registerProvisioningHandler(\r
+            IProvisioningListener provisioningListener) {\r
+        this.provisioningListener = provisioningListener;\r
+        EasySetupCallbackHandler.getInstance()\r
+                .registerProvisioningHandler(this);\r
+    }\r
+}\r
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/common/EnrolleeDevice.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/common/EnrolleeDevice.java
new file mode 100644 (file)
index 0000000..d76c37f
--- /dev/null
@@ -0,0 +1,48 @@
+/******************************************************************
+ *
+ * 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 org.iotivity.service.easysetup.mediator.common;
+
+import org.iotivity.base.OcConnectivityType;
+
+/*
+* EnrolleeDevice is a super class for handling Enrollees on different transports.
+* All the transport specific Enrollee Devices inherit from this base class and provide the
+* transport specific implementation in the transport specific subclasses.
+*/
+public class EnrolleeDevice {
+    private OcConnectivityType connectivityType;
+    private boolean isReachable;
+
+    public boolean isReachable() {
+        return isReachable;
+    }
+
+    public void setReachable(boolean isReachable) {
+        this.isReachable = isReachable;
+    }
+
+    public OcConnectivityType getConnectivityType() {
+        return connectivityType;
+    }
+
+    public void setConnectivityType(OcConnectivityType connectivityType) {
+        this.connectivityType = connectivityType;
+    }
+}
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/common/EnrolleeDeviceFactory.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/common/EnrolleeDeviceFactory.java
new file mode 100644 (file)
index 0000000..3a4333f
--- /dev/null
@@ -0,0 +1,42 @@
+/******************************************************************
+ *
+ * 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 org.iotivity.service.easysetup.mediator.common;
+
+import org.iotivity.base.OcConnectivityType;
+import org.iotivity.service.easysetup.mediator.ip.IPEnrolleeDevice;
+
+/*
+* EnrolleeDeviceFactory is a factory class which instantiates a respective transport specific
+* EnrolleeDevice class.
+* This class will be used during the OnBoarding Phase to create a transport specific Enrollee Device
+* after the device is OnBoarded successfully
+* The transport specific instantiation of Enrollee Device will be used in all subsequent operations
+* after OnBoarding
+*/
+public class EnrolleeDeviceFactory {
+    public static EnrolleeDevice getDevice(OcConnectivityType connectivityType)
+    {
+        if(connectivityType == OcConnectivityType.IPV4)
+        {
+            return new IPEnrolleeDevice();
+        }
+        return null;
+    }
+}
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/common/OnBoardingConfig.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/common/OnBoardingConfig.java
new file mode 100644 (file)
index 0000000..7e65c42
--- /dev/null
@@ -0,0 +1,43 @@
+/******************************************************************
+ *
+ * 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 org.iotivity.service.easysetup.mediator.common;
+
+import org.iotivity.base.OcConnectivityType;
+
+/*
+* OnBoardingConfig is a super class for handling different types of transport configurations.
+* OnBoardingConfig will be used during the OnBoarding phase to provide the transport details for
+* OnBoarding Enrollees
+* Transport specific subclasses will be inheriting from OnBoardingConfig to represent transport
+* specific implementations of OnBoardingConfig.
+* The base class provides the connecitivity type information which is needed for dynamic casting of
+* subclasses at runtime.
+*/
+public class OnBoardingConfig {
+    private OcConnectivityType connectivityType;
+
+    public OcConnectivityType getConnectivityType() {
+        return connectivityType;
+    }
+
+    public void setConnectivityType(OcConnectivityType connectivityType) {
+        this.connectivityType = connectivityType;
+    }
+}
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/common/ProvisioningInfo.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/common/ProvisioningInfo.java
new file mode 100644 (file)
index 0000000..b22d47f
--- /dev/null
@@ -0,0 +1,42 @@
+/******************************************************************
+ *
+ * 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 org.iotivity.service.easysetup.mediator.common;
+
+import org.iotivity.base.OcConnectivityType;
+
+/*
+* ProvisioningInfo is a super class for handling different types of transport provisioning
+* informations.
+* Different Connectivities have different types of provisioning information. This base class holds
+* the common information that is related to all the subclasses.
+* Transport specific provisioning information will be available with the subclasses of
+* ProvisioningInfo
+*/
+public class ProvisioningInfo {
+    private OcConnectivityType connectivityType;
+
+    public OcConnectivityType getConnectivityType() {
+        return connectivityType;
+    }
+
+    public void setConnectivityType(OcConnectivityType connectivityType) {
+        this.connectivityType = connectivityType;
+    }
+}
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ip/IPEnrolleeDevice.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ip/IPEnrolleeDevice.java
new file mode 100644 (file)
index 0000000..4ecb10d
--- /dev/null
@@ -0,0 +1,47 @@
+/******************************************************************
+ *
+ * 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 org.iotivity.service.easysetup.mediator.ip;
+
+import org.iotivity.service.easysetup.mediator.common.EnrolleeDevice;
+
+/*
+* IPEnrolleeDevice is a subclass of EnrolleeDevice for creating EnrolleeDevice for WiFi transport.
+*/
+public class IPEnrolleeDevice extends EnrolleeDevice {
+    private String  IpAddr;
+    private String  HWAddr;
+
+    public String getIpAddr() {
+        return IpAddr;
+    }
+
+    public void setIpAddr(String ipAddr) {
+        IpAddr = ipAddr;
+    }
+
+    public String getHWAddr() {
+        return HWAddr;
+    }
+
+    public void setHWAddr(String hWAddr) {
+        HWAddr = hWAddr;
+    }
+}
\ No newline at end of file
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ip/IPProvisioningInfo.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ip/IPProvisioningInfo.java
new file mode 100644 (file)
index 0000000..140c179
--- /dev/null
@@ -0,0 +1,55 @@
+/******************************************************************
+ *
+ * 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 org.iotivity.service.easysetup.mediator.ip;
+
+import org.iotivity.service.easysetup.mediator.common.ProvisioningInfo;
+
+/*
+* IPProvisioningInfo is a sub class for handling IP transport provisioning information.
+*/
+public class IPProvisioningInfo extends ProvisioningInfo {
+    private String ipAddress;
+    private String netSSID;
+    private String netPWD;
+
+    public String getIpAddress() {
+        return ipAddress;
+    }
+
+    public void setIpAddress(String ipAddress) {
+        this.ipAddress = ipAddress;
+    }
+
+    public String getNetSSID() {
+        return netSSID;
+    }
+
+    public void setNetSSID(String netSSID) {
+        this.netSSID = netSSID;
+    }
+
+    public String getNetPWD() {
+        return netPWD;
+    }
+
+    public void setNetPWD(String netPWD) {
+        this.netPWD = netPWD;
+    }
+}
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ip/WiFiSoftAPManager.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ip/WiFiSoftAPManager.java
new file mode 100644 (file)
index 0000000..e7e20dd
--- /dev/null
@@ -0,0 +1,348 @@
+/******************************************************************
+ *
+ * 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 org.iotivity.service.easysetup.mediator.ip;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.net.InetAddress;
+import java.util.ArrayList;
+
+import android.content.Context;
+import android.net.wifi.WifiConfiguration;
+import android.net.wifi.WifiManager;
+import android.os.Handler;
+import android.util.Log;
+
+import org.iotivity.base.OcConnectivityType;
+import org.iotivity.service.easysetup.mediator.common.EnrolleeDeviceFactory;
+import org.iotivity.service.easysetup.mediator.EnrolleeOnBoardingInfo;
+import org.iotivity.service.easysetup.mediator.IOnBoardingStatus;
+
+/**
+ * WiFiSoftAPManager provides wrapper methods for accessing Android Soft Access Point functionality.
+ * This is a convenient class, providing Android "WiFiManager" kind of equivalent class for Soft AP.
+ * <p>
+ * Note: Android doesn't provide public APIs for Soft Access Point feature access.
+ * This class provides only reference implementation to use the Soft AP and it uses Java reflection
+ * for access Soft Access point features.
+ * </p>
+ */
+public class WiFiSoftAPManager {
+    private final WifiManager                mWifiManager;
+    private Context                          context;
+    static ArrayList<EnrolleeOnBoardingInfo> appNotification =
+                                                    new ArrayList<EnrolleeOnBoardingInfo>();
+    IOnBoardingStatus finishListener  = null;
+
+    public enum WIFI_AP_STATE {
+        WIFI_AP_STATE_DISABLING,
+        WIFI_AP_STATE_DISABLED,
+        WIFI_AP_STATE_ENABLING,
+        WIFI_AP_STATE_ENABLED,
+        WIFI_AP_STATE_FAILED
+    }
+
+    public WiFiSoftAPManager(Context context) {
+        this.context = context;
+        mWifiManager = (WifiManager) this.context
+                .getSystemService(Context.WIFI_SERVICE);
+    }
+
+    /*
+    * Utility API to check the validity of the MAC Address read from the ARP cache
+    */
+    private boolean CheckIfValidMacAddress(String macAddr)
+    {
+        if(macAddr.matches("..:..:..:..:..:.."))
+        {
+            return true;
+        }
+        else {
+            return false;
+        }
+    }
+
+    /*
+    * The API is used for checking the device entry in the list maintained for the device
+    * notifications.
+    * If device entry is not found in the list, app is notified.
+    * If the device entry is found in the device, as application is already notified it will
+    * continue
+    */
+    private synchronized boolean CheckForDeviceEntryAndNotify(String ipAddr,
+                                                 String macAddr, boolean isReachable)
+    {
+        final IPEnrolleeDevice result = new IPEnrolleeDevice();
+        boolean deviceAddedToList = false;
+
+        result.setConnectivityType(OcConnectivityType.IPV4);
+
+        if (appNotification.size() > 0) {
+            for (EnrolleeOnBoardingInfo ipDeviceOnBoardingNotification : appNotification) {
+                IPEnrolleeDevice ipEnrolleeDevice = (IPEnrolleeDevice)ipDeviceOnBoardingNotification
+                        .getEnrolleeDevice();
+                boolean macAddressComparison = ipEnrolleeDevice.getHWAddr().equalsIgnoreCase(
+                                macAddr) ? true : false;
+
+                if (macAddressComparison) {
+                    deviceAddedToList = true;
+
+                    if (ipDeviceOnBoardingNotification
+                            .isAdditionNotified()
+                            && isReachable) {
+                        continue;
+                    } else if (ipDeviceOnBoardingNotification
+                            .isRemovalNotified()
+                            && !isReachable) {
+                        continue;
+                    } else {
+                        result.setIpAddr(ipAddr);
+                        result.setHWAddr(macAddr);
+                        result.setReachable(isReachable);
+
+                        appNotification
+                                .remove(ipDeviceOnBoardingNotification);
+                        if (isReachable) {
+                            appNotification
+                                    .add(new EnrolleeOnBoardingInfo(ipEnrolleeDevice, isReachable,
+                                            false, true));
+                        } else {
+                            appNotification
+                                    .add(new EnrolleeOnBoardingInfo(ipEnrolleeDevice, isReachable,
+                                            true, false));
+                        }
+
+                        NotifyApplication(result);
+                        return true;
+                    }
+                }
+            }
+            if (!deviceAddedToList) {
+                IPEnrolleeDevice ipEnrolleeDevice = (IPEnrolleeDevice) EnrolleeDeviceFactory.getDevice(
+                        OcConnectivityType.IPV4);
+                ipEnrolleeDevice.setIpAddr(ipAddr);
+                ipEnrolleeDevice.setHWAddr(macAddr);
+                if (isReachable) {
+                    appNotification
+                            .add(new EnrolleeOnBoardingInfo(ipEnrolleeDevice, isReachable, false,
+                                    true));
+                } else {
+                    appNotification
+                            .add(new EnrolleeOnBoardingInfo(ipEnrolleeDevice, isReachable, true,
+                                    false));
+                }
+
+                result.setIpAddr(ipAddr);
+                result.setHWAddr(macAddr);
+                result.setReachable(isReachable);
+
+                NotifyApplication(result);
+                return true;
+            }
+        } else {
+            IPEnrolleeDevice ipEnrolleeDevice = (IPEnrolleeDevice)EnrolleeDeviceFactory.getDevice(
+                    OcConnectivityType.IPV4);
+            ipEnrolleeDevice.setIpAddr(ipAddr);
+            ipEnrolleeDevice.setHWAddr(macAddr);
+            if (isReachable) {
+                appNotification
+                        .add(new EnrolleeOnBoardingInfo(ipEnrolleeDevice, isReachable, false,
+                                true));
+            } else {
+                appNotification
+                        .add(new EnrolleeOnBoardingInfo(ipEnrolleeDevice, isReachable, true,
+                                false));
+            }
+
+            result.setIpAddr(ipAddr);
+            result.setHWAddr(macAddr);
+            result.setReachable(isReachable);
+
+            NotifyApplication(result);
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Start WiFi Soft AccessPoint mode with the specified configuration.
+     * If the Soft AP is already running, this API call will update the new configuration.
+     * <p>
+     * Note: Starting Wi-Fi Soft Access Point will disable the Wi-Fi normal operation.
+     * </p>
+     *
+     * @param wifiConfig
+     *            SSID, security and channel details as part of WifiConfiguration
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public boolean setWifiApEnabled(WifiConfiguration wifiConfig,
+            boolean enabled) {
+        try {
+            // Stopping Wi-Fi mode
+            if (enabled) {
+                mWifiManager.setWifiEnabled(false);
+            }
+
+            Method method = mWifiManager.getClass().getMethod(
+                    "setWifiApEnabled", WifiConfiguration.class, boolean.class);
+            return (Boolean) method.invoke(mWifiManager, wifiConfig, enabled);
+        } catch (Exception e) {
+            Log.e(this.getClass().toString(), "", e);
+            return false;
+        }
+    }
+
+    /**
+     * Fetch the current state of the Wi-Fi Soft AP
+     *
+     * @return {@link WIFI_AP_STATE}
+     */
+    public WIFI_AP_STATE getWifiApState() {
+        try {
+            Method method = mWifiManager.getClass().getMethod("getWifiApState");
+
+            int currentWiFiState = ((Integer) method.invoke(mWifiManager));
+
+            return WIFI_AP_STATE.class.getEnumConstants()[currentWiFiState];
+        } catch (Exception e) {
+            Log.e(this.getClass().toString(), "", e);
+            return WIFI_AP_STATE.WIFI_AP_STATE_FAILED;
+        }
+    }
+
+    /**
+     * Fetch the current Wi-Fi AP Configuration.
+     *
+     * @return AP details in {@link WifiConfiguration}
+     */
+    public WifiConfiguration getWifiApConfiguration() {
+        try {
+            Method method = mWifiManager.getClass().getMethod(
+                    "getWifiApConfiguration");
+            return (WifiConfiguration) method.invoke(mWifiManager);
+        } catch (Exception e) {
+            Log.e(this.getClass().toString(), "", e);
+            return null;
+        }
+    }
+
+    /**
+     * Set/Update the Wi-Fi AP Configuration.
+     *
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public boolean setWifiApConfiguration(WifiConfiguration wifiConfig) {
+        try {
+            Method method = mWifiManager.getClass().getMethod(
+                    "setWifiApConfiguration", WifiConfiguration.class);
+            return (Boolean) method.invoke(mWifiManager, wifiConfig);
+        } catch (Exception e) {
+            Log.e(this.getClass().toString(), "", e);
+            return false;
+        }
+    }
+
+    /**
+     * Gets a list of the Soft AP clients connected to the Wi-Fi Soft Access point
+     *
+     * @param finishListener
+     *            Interface called when the scan method finishes
+     * @param reachableTimeout
+     *            Reachable Timeout in miliseconds
+     */
+    public void getClientList(IOnBoardingStatus finishListener, final int reachableTimeout) {
+        this.finishListener = finishListener;
+        Runnable runnable = new Runnable() {
+            public void run() {
+
+                BufferedReader bufferedReader = null;
+
+                try {
+                    // Note : This is a reference implementation for getting the list of Enrollee's
+                    // connected to the Soft AP.
+                    // There is no Android API for getting list of connected devices to the Soft AP.
+                    // The connected device information is fetched from Arp cache for Soft AP and
+                    // it is maintained in the file "/proc/net/arp"
+                    bufferedReader = new BufferedReader(new FileReader("/proc/net/arp"));
+                    String line;
+                    while ((line = bufferedReader.readLine()) != null) {
+                        //ARP entries are splitted using Regex for getting the IP and MAC Address
+                        // info
+                        String[] arpEntry = line.split(" +");
+
+                        if ((arpEntry != null) && (arpEntry.length >= 4)) {
+                            String ipAddr = arpEntry[0];
+                            String macAddr = arpEntry[3];
+
+
+                            // Checking if the string is matching MAC Address is matching the
+                            // standard MAC address format.
+                            // If the entry is not matching with MAC address format,
+                            // it will continue
+                            if (CheckIfValidMacAddress(macAddr)) {
+                                boolean isReachable = InetAddress.getByName(
+                                        ipAddr).isReachable(
+                                        reachableTimeout);
+
+                                Log.i("exec statement", ipAddr);
+                                Log.i("Return Value", " " + isReachable);
+
+                                // Checking if the app notification entries are available in the
+                                // list for the current device
+                                // API returns true is there is a notification to the application.
+                                // API returns false if there is no entry or if device is
+                                // already notified
+                                if(CheckForDeviceEntryAndNotify(ipAddr, macAddr, isReachable))
+                                {
+                                    break;
+                                }
+                            }
+                        }
+                    }
+                } catch (Exception e) {
+                    Log.e(this.getClass().toString(), e.toString());
+                } finally {
+                    try {
+                        bufferedReader.close();
+                    } catch (IOException e) {
+                        Log.e(this.getClass().toString(), e.getMessage());
+                    }
+                }
+            }
+        };
+
+        Thread mythread = new Thread(runnable);
+        mythread.start();
+    }
+
+    void NotifyApplication(final IPEnrolleeDevice result) {
+        // Get a handler that can be used to post to the main thread
+        Handler mainHandler = new Handler(context.getMainLooper());
+        Runnable myRunnable = new Runnable() {
+            @Override
+            public void run() {
+                finishListener.deviceOnBoardingStatus(result);
+            }
+        };
+        mainHandler.post(myRunnable);
+    }
+}
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ip/WiFiSoftAPOnBoardingConfig.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ip/WiFiSoftAPOnBoardingConfig.java
new file mode 100644 (file)
index 0000000..bae89a0
--- /dev/null
@@ -0,0 +1,42 @@
+/******************************************************************
+ *
+ * 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 org.iotivity.service.easysetup.mediator.ip;
+
+import android.net.wifi.WifiConfiguration;
+import org.iotivity.service.easysetup.mediator.common.OnBoardingConfig;
+
+/*
+* WiFiSoftAPOnBoardingConfig is a sub class for handling WiFi SoftAP transport configurations.
+* WiFiSoftAPOnBoardingConfig will be used during the OnBoarding phase to provide the
+* WiFi Soft AP transport details for OnBoarding Enrollee's
+* The base class OnBoardingConfig provides the connecitivity type information which is needed
+* for dynamic casting of subclasses at runtime.
+*/
+public class WiFiSoftAPOnBoardingConfig extends OnBoardingConfig {
+    private WifiConfiguration netConfig;
+
+    public WifiConfiguration getNetConfig() {
+        return netConfig;
+    }
+
+    public void setNetConfig(WifiConfiguration netConfig) {
+        this.netConfig = netConfig;
+    }
+}
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/res/drawable-hdpi/ic_launcher.png b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/res/drawable-hdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..288b665
Binary files /dev/null and b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/res/drawable-hdpi/ic_launcher.png differ
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/res/values/strings.xml b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/res/values/strings.xml
new file mode 100644 (file)
index 0000000..6ce9178
--- /dev/null
@@ -0,0 +1,5 @@
+<resources>\r
+\r
+    <string name="app_name">EasySetupCore</string>\r
+\r
+</resources>\r
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/res/values/styles.xml b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/res/values/styles.xml
new file mode 100644 (file)
index 0000000..4ea9326
--- /dev/null
@@ -0,0 +1,20 @@
+<resources>\r
+\r
+    <!--\r
+        Base application theme, dependent on API level. This theme is replaced
+        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.\r
+    -->\r
+    <style name="AppBaseTheme" parent="android:Theme.Light">\r
+        <!--\r
+            Theme customizations available in newer API levels can go in
+            res/values-vXX/styles.xml, while customizations related to
+            backward-compatibility can go here.\r
+        -->\r
+    </style>\r
+\r
+    <!-- Application theme. -->\r
+    <style name="AppTheme" parent="AppBaseTheme">\r
+        <!-- All customizations that are NOT specific to a particular API-level can go here. -->\r
+    </style>\r
+\r
+</resources>\r
diff --git a/service/easy-setup/sdk/mediator/android/jni/Android.mk b/service/easy-setup/sdk/mediator/android/jni/Android.mk
new file mode 100644 (file)
index 0000000..d85ab3f
--- /dev/null
@@ -0,0 +1,84 @@
+LOCAL_PATH := $(call my-dir)
+
+ifeq ($(strip $(ANDROID_NDK)),)
+$(error ANDROID_NDK is not set!)
+endif
+
+$(warning "Current path" $(LOCAL_PATH))
+$(info TC_PREFIX=$(TOOLCHAIN_PREFIX))
+$(info CFLAGS=$(TARGET_CFLAGS))
+$(info CXXFLAGS=$(TARGET_CXXFLAGS) $(TARGET_NO_EXECUTE_CFLAGS))
+$(info CPPFLAGS=$(TARGET_CPPFLAGS))
+$(info CPPPATH=$(TARGET_C_INCLUDES) $(__ndk_modules.$(APP_STL).EXPORT_C_INCLUDES))
+$(info SYSROOT=$(SYSROOT_LINK))
+$(info LDFLAGS=$(TARGET_LDFLAGS) $(TARGET_NO_EXECUTE_LDFLAGS) $(TARGET_NO_UNDEFINED_LDFLAGS) $(TARGET_RELRO_LDFLAGS))
+$(info TC_VER=$(TOOLCHAIN_VERSION))
+$(info PLATFORM=$(APP_PLATFORM))
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../../../out/android/$(TARGET_ARCH_ABI)/debug
+LOCAL_MODULE := android-octbstack
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboctbstack.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../../../out/android/$(TARGET_ARCH_ABI)/debug
+LOCAL_MODULE := android-connectivity_abstraction
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libconnectivity_abstraction.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../../../out/android/$(TARGET_ARCH_ABI)/debug
+LOCAL_MODULE := android-easysetup
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libESSDK.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE    := easysetup-jni
+
+#Add Pre processor definitions
+DEFINE_FLAG =  -DWITH_POSIX -D__ANDROID__
+
+#Add Debug flags here
+DEBUG_FLAG      = -DTB_LOG
+
+BUILD_FLAG = $(DEFINE_FLAG) $(DEBUG_FLAG)
+
+LOCAL_CPPFLAGS = $(BUILD_FLAG)
+LOCAL_CPPFLAGS += -std=c++0x -frtti -fexceptions
+
+$(info CPPFLAGSUPDATED=$(LOCAL_CPPFLAGS))
+
+NDK_ROOT         := /home/madan/android-ndk-r10d
+
+LOCAL_C_INCLUDES := $(LOCAL_PATH) \
+                                       $(LOCAL_PATH)/jniutil/inc \
+                                       $(LOCAL_PATH)/../../../../../../service/easy-setup/sdk/mediator/inc \
+                                       $(LOCAL_PATH)/../../../../../../service/easy-setup/sdk/common \
+                                       $(LOCAL_PATH)/../../../../../../resource/csdk/logger/include \
+                                       $(LOCAL_PATH)/../../../../../../resource/csdk/connectivity/common/inc \
+                                       $(LOCAL_PATH)/../../../../../../resource/include \
+                                       $(LOCAL_PATH)/../../../../../../resource/oc_logger/include \
+                                       $(LOCAL_PATH)/../../../../../../resource/csdk/ocmalloc/include \
+                                       $(LOCAL_PATH)/../../../../../../resource/csdk/connectivity/api \
+                                       $(LOCAL_PATH)/../../../../../../resource/csdk/stack/include \
+                                       $(LOCAL_PATH)/../../../../../../resource/csdk/logger/include \
+                                       $(LOCAL_PATH)/../../../../../../resource/csdk/security/include \
+                                       $(LOCAL_PATH)/../../../../../../extlibs/cjson \
+                                       $(LOCAL_PATH)/../../../../../../extlibs/boost/boost_1_58_0 \
+                    $(LOCAL_PATH)/../../../../../../extlibs/timer \
+                                       $(LOCAL_PATH)/../../../../../../android/android_api/base/jni \
+                                       $(NDK_ROOT)/sources/cxx-stl/gnu-libstdc++/$(TOOLCHAIN_VERSION)/include \
+                    $(NDK_ROOT)/sources/cxx-stl/gnu-libstdc++/$(TOOLCHAIN_VERSION)/libs/$(TARGET_ARCH_ABI)/include \
+                                       
+LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/jni_easy_setup.cpp))
+LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/jniutil/src/*.cpp))
+
+LOCAL_LDLIBS := -llog 
+LOCAL_LDLIBS += -L$(NDK_ROOT)/sources/cxx-stl/gnu-libstdc++/$(TOOLCHAIN_VERSION)/libs/$(TARGET_ARCH_ABI)
+LOCAL_SHARED_LIBRARIES := android-easysetup
+LOCAL_SHARED_LIBRARIES += android-connectivity_abstraction
+LOCAL_SHARED_LIBRARIES += android-octbstack
+
+include $(BUILD_SHARED_LIBRARY)
\ No newline at end of file
diff --git a/service/easy-setup/sdk/mediator/android/jni/Application.mk b/service/easy-setup/sdk/mediator/android/jni/Application.mk
new file mode 100644 (file)
index 0000000..d5fc03c
--- /dev/null
@@ -0,0 +1,4 @@
+APP_STL               := gnustl_shared
+APP_PLATFORM = android-21
+NDK_TOOLCHAIN_VERSION := 4.8
+
diff --git a/service/easy-setup/sdk/mediator/android/jni/jni_easy_setup.cpp b/service/easy-setup/sdk/mediator/android/jni/jni_easy_setup.cpp
new file mode 100644 (file)
index 0000000..bab8c05
--- /dev/null
@@ -0,0 +1,171 @@
+//******************************************************************\r
+//\r
+// Copyright 2015 Samsung Electronics All Rights Reserved.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+//\r
+// Licensed under the Apache License, Version 2.0 (the "License");\r
+// you may not use this file except in compliance with the License.\r
+// You may obtain a copy of the License at\r
+//\r
+//      http://www.apache.org/licenses/LICENSE-2.0\r
+//\r
+// Unless required by applicable law or agreed to in writing, software\r
+// distributed under the License is distributed on an "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+// See the License for the specific language governing permissions and\r
+// limitations under the License.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+\r
+#include "jni_easy_setup.h"\r
+\r
+#include "jni_easy_setup_jvm.h"\r
+#include "easysetupmgr.h"\r
+\r
+void JNIProvisioningStatusCallback(ProvisioningInfo *provInfo) {\r
+    JNIEnv *env = EasySetupJVM::getEnv();\r
+    if (env == NULL) {\r
+        LOGE("JNIProvisioningStatusCallback : Getting JNIEnv failed");\r
+        return;\r
+    }\r
+\r
+    // Get EasySetupHandler class reference\r
+    jclass easysetupCallbacks = GetJClass(\r
+            EASY_SETUP_SERVICE_CALLBACK_NATIVE_API_CLASS_PATH);\r
+    if (NULL == easysetupCallbacks) {\r
+        LOGE(\r
+                "JNIProvisioningStatusCallback : GetJClass easysetupCallbacks failed");\r
+        EasySetupJVM::releaseEnv();\r
+        return;\r
+    }\r
+\r
+    // Get the easysetupCallback class instance\r
+    jobject jobjectCallback = GetJObjectInstance(\r
+            EASY_SETUP_SERVICE_CALLBACK_NATIVE_API_CLASS_PATH);\r
+    if (NULL == jobjectCallback) {\r
+        LOGE("getInstance( %s) failed!",\r
+                EASY_SETUP_SERVICE_CALLBACK_NATIVE_API_CLASS_PATH);\r
+        EasySetupJVM::releaseEnv();\r
+        return;\r
+    }\r
+\r
+    // Get onResourceCallback method reference\r
+    jmethodID method_id = env->GetMethodID(easysetupCallbacks,\r
+            "ProvisioningStatusCallBack",\r
+            METHOD_PROVISIONING_STATUS_INTEGER_CALLBACK);\r
+    if (NULL == method_id) {\r
+        LOGE(\r
+                "JNIProvisioningStatusCallback: onResourceCallback : GetMethodID failed");\r
+        EasySetupJVM::releaseEnv();\r
+        return;\r
+    }\r
+\r
+    if ((env)->ExceptionCheck()) {\r
+        LOGE("JNIProvisioningStatusCallback : ExceptionCheck failed");\r
+        EasySetupJVM::releaseEnv();\r
+        return;\r
+    }\r
+\r
+    if (NULL == method_id) {\r
+        LOGI("JNI method_id is NULL");\r
+    } else {\r
+        LOGI("JNI method_id is VALID");\r
+\r
+        jint result;\r
+        if (provInfo->provStatus == DEVICE_PROVISIONED) {\r
+            result = 0;\r
+        } else {\r
+            result = -1;\r
+        }\r
+\r
+        env->CallVoidMethod(jobjectCallback, method_id, (jint) result);\r
+    }\r
+\r
+    EasySetupJVM::releaseEnv();\r
+}\r
+\r
+JNIEXPORT void JNICALL JNIInitEasySetup(JNIEnv *env, jobject thisObj)\r
+{\r
+    LOGI("JNI JNIInitEasySetup: Enter");\r
+    InitEasySetupManager();\r
+    RegisterProvisioningStausCallback(JNIProvisioningStatusCallback);\r
+}\r
+\r
+JNIEXPORT void JNICALL JNITerminateEasySetup(JNIEnv *env, jobject thisObj)\r
+{\r
+    LOGI("JNI JNITerminateEasySetup: Enter");\r
+    TerminateEasySetupManager();\r
+}\r
+\r
+\r
+JNIEXPORT void JNICALL JNIProvisionEnrollee(JNIEnv *env, jobject thisObj,\r
+                                                    jstring jIPAddress,\r
+                                                    jstring jNetSSID,\r
+                                                    jstring jNetPWD,\r
+                                                    jint jConnectivityType)\r
+{\r
+    LOGI("JNI JNIProvisionEnrollee: Enter");\r
+\r
+    if (!jIPAddress)\r
+    {\r
+        LOGE("JNI JNIProvisionEnrollee : jIPAddress is NULL!");\r
+        return;\r
+    }\r
+\r
+    const char *ipAddress = env->GetStringUTFChars(jIPAddress, NULL);\r
+    if (NULL == ipAddress)\r
+    {\r
+        LOGE("JNI JNIProvisionEnrollee : Failed to convert jstring to char string!");\r
+    }\r
+\r
+    LOGI("JNI JNIProvisionEnrollee : ipAddress is : %s",ipAddress);\r
+\r
+    const char *netSSID = env->GetStringUTFChars(jNetSSID, NULL);\r
+    if (NULL == netSSID)\r
+    {\r
+        LOGE("JNI JNIProvisionEnrollee : Failed to convert jstring to char string!");\r
+    }\r
+\r
+    LOGI("JNI JNIProvisionEnrollee : netSSID is : %s",netSSID);\r
+\r
+    const char *netPWD = env->GetStringUTFChars(jNetPWD, NULL);\r
+    if (NULL == netPWD)\r
+    {\r
+        LOGE("JNI JNIProvisionEnrollee : Failed to convert jstring to char string!");\r
+    }\r
+\r
+    LOGI("JNI JNIProvisionEnrollee : netPWD is : %s",netPWD);\r
+\r
+    OCConnectivityType connecitivityType;\r
+    EnrolleeNWProvInfo_t netInfo = {0};\r
+\r
+    strncpy(netInfo.netAddressInfo.WIFI.ipAddress, ipAddress, IPV4_ADDR_SIZE);\r
+    strncpy(netInfo.netAddressInfo.WIFI.ssid, netSSID, NET_WIFI_SSID_SIZE);\r
+    strncpy(netInfo.netAddressInfo.WIFI.pwd, netPWD, NET_WIFI_PWD_SIZE);\r
+    netInfo.connType = OCConnectivityType::CT_ADAPTER_IP;\r
+    netInfo.isSecured = true;\r
+\r
+    ProvisionEnrollee(&netInfo);\r
+\r
+    return;\r
+}\r
+\r
+JNIEXPORT void JNICALL JNIStopEnrolleeProvisioning(JNIEnv *env, jobject thisObj,\r
+                                                    jint jConnectivityType)\r
+{\r
+    LOGI("JNI Stop Easy Setup: Entering");\r
+\r
+    OCConnectivityType connecitivityType;\r
+\r
+    if(jConnectivityType == 0)\r
+    {\r
+        connecitivityType = OCConnectivityType::CT_ADAPTER_IP;\r
+    }\r
+\r
+    StopEnrolleeProvisioning(connecitivityType);\r
+\r
+    return;\r
+}\r
+\r
+\r
diff --git a/service/easy-setup/sdk/mediator/android/jni/jni_easy_setup.h b/service/easy-setup/sdk/mediator/android/jni/jni_easy_setup.h
new file mode 100644 (file)
index 0000000..a69d657
--- /dev/null
@@ -0,0 +1,42 @@
+/* DO NOT EDIT THIS FILE - it is machine generated */\r
+#include <stdio.h>\r
+#include <string.h>\r
+\r
+#include <jni.h>\r
+#include <jni_string.h>\r
+\r
+#include "JniOcStack.h"\r
+\r
+#define METHOD_PROVISIONING_STATUS_VOID_CALLBACK    "("")V"\r
+#define METHOD_PROVISIONING_STATUS_INTEGER_CALLBACK    "("EASY_SETUP_JAVA_INTEGER_TYPE")V"\r
+\r
+/* Header for class org_iotivity_service_easyconnect_java_EasySetupHandler */\r
+\r
+#ifndef _Included_org_iotivity_service_easysetup_java_EasySetupHandler\r
+#define _Included_org_iotivity_service_easysetup_java_EasySetupHandler\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+JNIEXPORT void JNICALL JNIInitEasySetup(JNIEnv *env, jobject thisObj);\r
+JNIEXPORT void JNICALL JNITerminateEasySetup(JNIEnv *env, jobject thisObj);\r
+\r
+/*\r
+ * Class:     org_iotivity_service_easyconnect_java_EasySetupHandler\r
+ * Method:    JNIProvisionEnrollee\r
+ * Signature: ()V\r
+ */\r
+JNIEXPORT void JNICALL JNIProvisionEnrollee(JNIEnv *env, jobject ,\r
+                                                jstring ,\r
+                                                jstring ,\r
+                                                jstring ,\r
+                                                jint jConnectivityType);\r
+\r
+JNIEXPORT void JNICALL JNIStopEnrolleeProvisioning(JNIEnv *, jobject, jint);\r
+\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif\r
diff --git a/service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_easy_setup_jvm.h b/service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_easy_setup_jvm.h
new file mode 100644 (file)
index 0000000..0e9e383
--- /dev/null
@@ -0,0 +1,94 @@
+/******************************************************************
+ *
+ * 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_easy_setup_jvm.h
+ *
+ * @brief  This file contains the essential declarations and functions required
+ *            for JNI implementation
+ */
+
+#ifndef __JNI_EASY_SETUP_JVM_H_
+#define __JNI_EASY_SETUP_JVM_H_
+
+#include <jni.h>
+#include <thread>
+#include <mutex>
+
+#define EASY_SETUP_SERVICE_NATIVE_API_CLASS_PATH    "org/iotivity/service/easysetup/mediator/EasySetupManager"
+#define EASY_SETUP_SERVICE_NATIVE_API_CLASS_TYPE    "Lorg/iotivity/service/easysetup/mediator/EasySetupManager;"
+#define EASY_SETUP_SERVICE_CALLBACK_NATIVE_API_CLASS_PATH    "org/iotivity/service/easysetup/mediator/EasySetupCallbackHandler"
+#define EASY_SETUP_SERVICE_CALLBACK_NATIVE_API_CLASS_TYPE    "Lorg/iotivity/service/easysetup/mediator/EasySetupCallbackHandler;"
+
+#define EASY_SETUP_JAVA_STRING_TYPE "Ljava/lang/String;"
+#define EASY_SETUP_JAVA_INTEGER_TYPE "I"
+
+/**
+ * @class   EasySetupJVM
+ * @brief   This class provides functions related to JNI Environment.
+ *
+ */
+class EasySetupJVM {
+public:
+    /**
+     * @brief destructor
+     */
+    ~EasySetupJVM() {
+    }
+    ;
+
+    /**
+     * @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
+     */
+    EasySetupJVM();
+
+    /**
+     *  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_EASY_SETUP_JVM_H_
+
diff --git a/service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_getter.h b/service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_getter.h
new file mode 100644 (file)
index 0000000..fe92a82
--- /dev/null
@@ -0,0 +1,111 @@
+/******************************************************************
+ *
+ * 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_
diff --git a/service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_object.h b/service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_object.h
new file mode 100644 (file)
index 0000000..5f27a47
--- /dev/null
@@ -0,0 +1,96 @@
+/******************************************************************
+ *
+ * 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_
diff --git a/service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_setter.h b/service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_setter.h
new file mode 100644 (file)
index 0000000..c4593cc
--- /dev/null
@@ -0,0 +1,128 @@
+/******************************************************************
+ *
+ * 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_
diff --git a/service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_string.h b/service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_string.h
new file mode 100644 (file)
index 0000000..358e869
--- /dev/null
@@ -0,0 +1,80 @@
+/******************************************************************
+ *
+ * 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_
diff --git a/service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_easy_setup_jvm.cpp b/service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_easy_setup_jvm.cpp
new file mode 100644 (file)
index 0000000..acfe662
--- /dev/null
@@ -0,0 +1,318 @@
+/******************************************************************
+ *
+ * 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_easy_setup_jvm.h"
+#include <string>
+#include "jni_easy_setup.h"
+
+/**
+ * @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(
+        EASY_SETUP_SERVICE_NATIVE_API_CLASS_PATH), JClassMap(
+        EASY_SETUP_SERVICE_CALLBACK_NATIVE_API_CLASS_PATH) };
+
+static JObjectMap gJObjectMapArray[] = { JObjectMap(
+        EASY_SETUP_SERVICE_CALLBACK_NATIVE_API_CLASS_PATH) };
+
+static JNINativeMethod gEasySetupMethodTable[] = {
+    { "InitEasySetup", "()V", (void *) JNIInitEasySetup },
+    { "TerminateEasySetup", "()V", (void *) JNITerminateEasySetup },
+    { "ProvisionEnrollee", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V",
+                                (void *) JNIProvisionEnrollee },
+    { "StopEnrolleeProvisioning", "(I)V", (void *) JNIStopEnrolleeProvisioning }, };
+
+static int gEasySetupMethodTableSize = sizeof(gEasySetupMethodTable)
+        / sizeof(gEasySetupMethodTable[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 *EasySetupJVM::m_jvm = NULL;
+std::mutex EasySetupJVM::m_currentThreadMutex;
+JNIEnv *EasySetupJVM::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 EasySetupJVM::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 easySetupClassRef = GetJClass(
+            EASY_SETUP_SERVICE_NATIVE_API_CLASS_PATH);
+    if (NULL == easySetupClassRef) {
+        LOGE("JNI_OnLoad: GetJClass gEasySetupClass failed !");
+        return JNI_ERR;
+    }
+    env->RegisterNatives(easySetupClassRef, gEasySetupMethodTable,
+            gEasySetupMethodTableSize);
+
+    EasySetupJVM::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
+
diff --git a/service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_getter.cpp b/service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_getter.cpp
new file mode 100644 (file)
index 0000000..135f6a2
--- /dev/null
@@ -0,0 +1,148 @@
+/******************************************************************
+ *
+ * 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;
+}
diff --git a/service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_object.cpp b/service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_object.cpp
new file mode 100644 (file)
index 0000000..51c6bf6
--- /dev/null
@@ -0,0 +1,67 @@
+#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;
+       }
+}
+
diff --git a/service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_setter.cpp b/service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_setter.cpp
new file mode 100644 (file)
index 0000000..6c38004
--- /dev/null
@@ -0,0 +1,175 @@
+/******************************************************************
+ *
+ * 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;
+}
+
diff --git a/service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_string.cpp b/service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_string.cpp
new file mode 100644 (file)
index 0000000..93bcdf4
--- /dev/null
@@ -0,0 +1,62 @@
+/******************************************************************
+ *
+ * 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();
+}
+
diff --git a/service/easy-setup/sdk/mediator/inc/easysetupmgr.h b/service/easy-setup/sdk/mediator/inc/easysetupmgr.h
new file mode 100644 (file)
index 0000000..a3e18de
--- /dev/null
@@ -0,0 +1,57 @@
+//******************************************************************
+//
+// 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 __EASYSETUP_MGR_H_
+#define __EASYSETUP_MGR_H_
+
+#include <string.h>
+
+#include "logger.h"
+#include "ocstack.h"
+#include "octypes.h"
+#include "common.h"
+
+#include "provisioninghandler.h"
+
+
+//-----------------------------------------------------------------------------
+// Defines
+//-----------------------------------------------------------------------------
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+OCStackResult InitEasySetupManager();
+
+OCStackResult TerminateEasySetupManager();
+
+OCStackResult RegisterProvisioningStausCallback(
+        OCProvisioningStatusCB provisioningStatusCallback);
+
+void UnRegisterProvisioningStausCallback();
+
+OCStackResult ProvisionEnrollee(const EnrolleeNWProvInfo_t *netInfo);
+
+OCStackResult StopEnrolleeProvisioning(OCConnectivityType connectivityType);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/service/easy-setup/sdk/mediator/inc/provisioninghandler.h b/service/easy-setup/sdk/mediator/inc/provisioninghandler.h
new file mode 100644 (file)
index 0000000..f4380e8
--- /dev/null
@@ -0,0 +1,89 @@
+//******************************************************************
+//
+// 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 __PROVISIONING_HANDLER_H_
+#define __PROVISIONING_HANDLER_H_
+
+
+#include "octypes.h"
+
+#include "logger.h"
+#include "ocstack.h"
+#include "common.h"
+
+//-----------------------------------------------------------------------------
+// Defines
+//-----------------------------------------------------------------------------
+#define TAG "provisioninghandler"
+#define DEFAULT_CONTEXT_VALUE 0x99
+#ifndef MAX_LENGTH_IPv4_ADDR
+#define MAX_LENGTH_IPv4_ADDR 16
+#endif
+
+//-----------------------------------------------------------------------------
+// Typedefs
+//-----------------------------------------------------------------------------
+
+/**
+ * List of methods that can be inititated from the client
+ */
+OCStackResult InitProvisioningHandler();
+
+OCStackResult TerminateProvisioningHandler();
+
+void listeningFunc(void*);
+
+OCStackApplicationResult ProvisionEnrolleeResponse(void* ctx, OCDoHandle handle,
+        OCClientResponse * clientResponse);
+
+OCStackResult ProvisionEnrollee(OCQualityOfService qos, const char* query, const char* resUri);
+
+OCStackApplicationResult GetProvisioningStatusResponse(void* ctx,
+        OCDoHandle handle, OCClientResponse * clientResponse);
+
+OCStackResult InvokeOCDoResource(const char* query, OCMethod method,
+        OCQualityOfService qos, OCClientResponseHandler cb,OCRepPayload * request,
+        OCHeaderOption * options, uint8_t numOptions);
+
+OCStackResult GetProvisioningStatus(OCQualityOfService qos, const char* query);
+
+OCStackResult StartProvisioningProcess(const EnrolleeNWProvInfo_t *netInfo,
+        OCProvisioningStatusCB provisioningStatusCallback);
+
+
+void StopProvisioningProcess();
+
+OCStackApplicationResult SubscribeProvPresenceCallback(void* ctx, OCDoHandle handle,
+        OCClientResponse* clientResponse);
+
+OCStackResult SubscribeProvPresence(OCQualityOfService qos, const char* requestURI);
+
+OCStackApplicationResult FindProvisioningResourceResponse(void* ctx,
+        OCDoHandle handle, OCClientResponse * clientResponse);
+
+void FindProvisioningResource(void *data);
+
+//Invoke Provisioning Status Callback
+ProvisioningInfo* PrepareProvisioingStatusCB(OCClientResponse * clientResponse,
+            ProvStatus provStatus);
+
+#endif
+
diff --git a/service/easy-setup/sdk/mediator/src/camutex_pthreads.c b/service/easy-setup/sdk/mediator/src/camutex_pthreads.c
new file mode 100644 (file)
index 0000000..58549bc
--- /dev/null
@@ -0,0 +1,320 @@
+//******************************************************************
+//
+// Copyright 2015 Intel Mobile Communications GmbH 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
+ * This file provides APIs related to mutex and semaphores.
+ */
+
+// Defining _POSIX_C_SOURCE macro with 199309L (or greater) as value
+// causes header files to expose definitions
+// corresponding to the POSIX.1b, Real-time extensions
+// (IEEE Std 1003.1b-1993) specification
+//
+// For this specific file, see use of clock_gettime and PTHREAD_MUTEX_DEFAULT
+#ifndef _POSIX_C_SOURCE
+#define _POSIX_C_SOURCE 200809L
+#endif
+
+#include <string.h>
+#include <pthread.h>
+#include <errno.h>
+#include <unistd.h>
+#include <time.h>
+#include <sys/time.h>
+#include <assert.h>
+#include <oic_malloc.h>
+
+#include "camutex.h"
+#include "logger.h"
+
+/**
+ * TAG
+ * Logging tag for module name
+ */
+#define TAG PCF("UMUTEX")
+
+static const uint64_t USECS_PER_SEC = 1000000;
+static const uint64_t NANOSECS_PER_USECS = 1000;
+static const uint64_t NANOSECS_PER_SEC = 1000000000L;
+
+typedef struct _tagMutexInfo_t {
+       pthread_mutex_t mutex;
+} ca_mutex_internal;
+
+typedef struct _tagEventInfo_t {
+       pthread_cond_t cond;
+       pthread_condattr_t condattr;
+} ca_cond_internal;
+
+ca_mutex ca_mutex_new(void) {
+       ca_mutex retVal = NULL;
+       ca_mutex_internal *mutexInfo = (ca_mutex_internal*) OICMalloc(
+                       sizeof(ca_mutex_internal));
+       if (NULL != mutexInfo) {
+               // create the mutex with the attributes set
+               int ret = pthread_mutex_init(&(mutexInfo->mutex),
+                               PTHREAD_MUTEX_DEFAULT);
+               if (0 == ret) {
+                       retVal = (ca_mutex) mutexInfo;
+               } else {
+                       OIC_LOG_V(ERROR, TAG, "%s Failed to initialize mutex !", __func__);
+                       OICFree(mutexInfo);
+               }
+       }
+
+       return retVal;
+}
+
+bool ca_mutex_free(ca_mutex mutex) {
+       bool bRet = false;
+
+       ca_mutex_internal *mutexInfo = (ca_mutex_internal*) mutex;
+       if (mutexInfo) {
+               int ret = pthread_mutex_destroy(&mutexInfo->mutex);
+               if (0 == ret) {
+                       OICFree(mutexInfo);
+                       bRet = true;
+               } else {
+                       OIC_LOG_V(ERROR, TAG, "%s Failed to free mutex !", __func__);
+               }
+       } else {
+               OIC_LOG_V(ERROR, TAG, "%s Invalid mutex !", __func__);
+       }
+
+       return bRet;
+}
+
+void ca_mutex_lock(ca_mutex mutex) {
+       ca_mutex_internal *mutexInfo = (ca_mutex_internal*) mutex;
+       if (mutexInfo) {
+               int ret = pthread_mutex_lock(&mutexInfo->mutex);
+               assert(0 == ret);
+               (void) ret;
+       } else {
+               OIC_LOG_V(ERROR, TAG, "%s Invalid mutex !", __func__);
+               return;
+       }
+}
+
+bool ca_mutex_trylock(ca_mutex mutex) {
+       if (NULL == mutex) {
+               OIC_LOG_V(ERROR, TAG, "%s Invalid mutex !", __func__);
+               return false;
+       }
+
+       bool bRet = false;
+
+       ca_mutex_internal *mutexInfo = (ca_mutex_internal*) mutex;
+
+       int result = pthread_mutex_trylock(&mutexInfo->mutex);
+
+       switch (result) {
+       case 0:
+               // Success
+               bRet = true;
+               break;
+       case EINVAL:
+               OIC_LOG_V(ERROR, TAG, "%s: Invalid mutex !", __func__);
+               break;
+       case EBUSY:
+       default:
+               break;
+       }
+
+       return bRet;
+}
+
+void ca_mutex_unlock(ca_mutex mutex) {
+       ca_mutex_internal *mutexInfo = (ca_mutex_internal*) mutex;
+       if (mutexInfo) {
+               int ret = pthread_mutex_unlock(&mutexInfo->mutex);
+               assert(0 == ret);
+               (void) ret;
+       } else {
+               OIC_LOG_V(ERROR, TAG, "%s: Invalid mutex !", __func__);
+               return;
+       }
+}
+
+ca_cond ca_cond_new(void) {
+       ca_cond retVal = NULL;
+       ca_cond_internal *eventInfo = (ca_cond_internal*) OICMalloc(
+                       sizeof(ca_cond_internal));
+       if (NULL != eventInfo) {
+               int ret = pthread_condattr_init(&(eventInfo->condattr));
+               if (0 != ret) {
+                       OIC_LOG_V(ERROR, TAG,
+                                       "%s: Failed to initialize condition variable attribute %d!",
+                                       __func__, ret);
+                       return retVal;
+               }
+
+#if defined(__ANDROID__) || _POSIX_TIMERS > 0
+               ret = pthread_condattr_setclock(&(eventInfo->condattr), CLOCK_MONOTONIC);
+
+               if(0 != ret)
+               {
+                       OIC_LOG_V(ERROR, TAG, "%s: Failed to set condition variable clock %d!",
+                                       __func__, ret);
+                       return retVal;
+               }
+#endif
+               ret = pthread_cond_init(&(eventInfo->cond), &(eventInfo->condattr));
+               if (0 == ret) {
+                       retVal = (ca_cond) eventInfo;
+               } else {
+                       OIC_LOG_V(ERROR, TAG,
+                                       "%s: Failed to initialize condition variable %d!", __func__,
+                                       ret);
+                       OICFree(eventInfo);
+               }
+       }
+
+       return retVal;
+}
+
+void ca_cond_free(ca_cond cond) {
+       ca_cond_internal *eventInfo = (ca_cond_internal*) cond;
+       if (eventInfo != NULL) {
+               int ret = pthread_cond_destroy(&(eventInfo->cond));
+               int ret2 = pthread_condattr_destroy(&(eventInfo->condattr));
+               if (0 == ret && 0 == ret2) {
+                       OICFree(cond);
+               } else {
+                       OIC_LOG_V(ERROR, TAG,
+                                       "%s: Failed to destroy condition variable %d, %d", __func__,
+                                       ret, ret2);
+               }
+       } else {
+               OIC_LOG_V(ERROR, TAG, "%s: Invalid parameter", __func__);
+       }
+}
+
+void ca_cond_signal(ca_cond cond) {
+       ca_cond_internal *eventInfo = (ca_cond_internal*) cond;
+       if (eventInfo != NULL) {
+               int ret = pthread_cond_signal(&(eventInfo->cond));
+               if (0 != ret) {
+                       OIC_LOG_V(ERROR, TAG, "%s: Failed to signal condition variable",
+                                       __func__);
+               }
+       } else {
+               OIC_LOG_V(ERROR, TAG, "%s: Invalid parameter", __func__);
+       }
+}
+
+void ca_cond_broadcast(ca_cond cond) {
+       ca_cond_internal* eventInfo = (ca_cond_internal*) cond;
+       if (eventInfo != NULL) {
+               int ret = pthread_cond_broadcast(&(eventInfo->cond));
+               if (0 != ret) {
+                       OIC_LOG_V(ERROR, TAG, "%s: failed to signal condition variable",
+                                       __func__);
+               }
+       } else {
+               OIC_LOG_V(ERROR, TAG, "%s: Invalid parameter", __func__);
+       }
+}
+
+void ca_cond_wait(ca_cond cond, ca_mutex mutex) {
+       ca_cond_wait_for(cond, mutex, 0L);
+}
+
+struct timespec ca_get_current_time() {
+#if defined(__ANDROID__) || _POSIX_TIMERS > 0
+       struct timespec ts;
+       clock_gettime(CLOCK_MONOTONIC, &ts);
+       return ts;
+#else
+       struct timeval tv;
+       gettimeofday(&tv, NULL);
+       struct timespec ts;
+       TIMEVAL_TO_TIMESPEC(&tv, &ts);
+       return ts;
+#endif
+}
+
+void ca_add_microseconds_to_timespec(struct timespec* ts,
+               uint64_t microseconds) {
+       time_t secPart = microseconds / USECS_PER_SEC;
+       uint64_t nsecPart = (microseconds % USECS_PER_SEC) * NANOSECS_PER_USECS;
+       uint64_t totalNs = ts->tv_nsec + nsecPart;
+       time_t secOfNs = totalNs / NANOSECS_PER_SEC;
+
+       ts->tv_nsec = (totalNs) % NANOSECS_PER_SEC;
+       ts->tv_sec += secPart + secOfNs;
+}
+
+CAWaitResult_t ca_cond_wait_for(ca_cond cond, ca_mutex mutex,
+               uint64_t microseconds) {
+       CAWaitResult_t retVal = CA_WAIT_INVAL;
+
+       ca_cond_internal *eventInfo = (ca_cond_internal*) cond;
+       ca_mutex_internal *mutexInfo = (ca_mutex_internal*) mutex;
+
+       if (NULL == mutexInfo) {
+               OIC_LOG_V(ERROR, TAG, "%s: Invalid mutex", __func__);
+               return CA_WAIT_INVAL;
+       }
+
+       if (NULL == eventInfo) {
+               OIC_LOG_V(ERROR, TAG, "%s: Invalid condition", __func__);
+               return CA_WAIT_INVAL;
+       }
+
+       if (microseconds > 0) {
+               struct timespec abstime = ca_get_current_time();
+               ca_add_microseconds_to_timespec(&abstime, microseconds);
+
+               //Wait for the given time
+               int ret = pthread_cond_timedwait(&(eventInfo->cond),
+                               &(mutexInfo->mutex), &abstime);
+               switch (ret) {
+               case 0:
+                       // Success
+                       retVal = CA_WAIT_SUCCESS;
+                       break;
+               case ETIMEDOUT:
+                       retVal = CA_WAIT_TIMEDOUT;
+                       break;
+               case EINVAL:
+                       OIC_LOG_V(ERROR, TAG, "%s: condition, mutex, or abstime is Invalid",
+                                       __func__);
+                       retVal = CA_WAIT_INVAL;
+                       break;
+               default:
+                       OIC_LOG_V(ERROR, TAG, "%s: pthread_cond_timedwait returned %d",
+                                       __func__, retVal);
+                       retVal = CA_WAIT_INVAL;
+                       break;
+               }
+       } else {
+               // Wait forever
+               int ret = pthread_cond_wait(&eventInfo->cond, &mutexInfo->mutex);
+               retVal = ret == 0 ? CA_WAIT_SUCCESS : CA_WAIT_INVAL;
+       }
+
+       return retVal;
+}
+
diff --git a/service/easy-setup/sdk/mediator/src/easysetupmgr.cpp b/service/easy-setup/sdk/mediator/src/easysetupmgr.cpp
new file mode 100644 (file)
index 0000000..7f29ab9
--- /dev/null
@@ -0,0 +1,92 @@
+ //******************************************************************
+//
+// 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 <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <signal.h>
+#include <unistd.h>
+#include <stdint.h>
+#include <sstream>
+
+#include "easysetupmgr.h"
+
+//Use ipv4addr for both InitDiscovery and InitDeviceDiscovery
+char ipv4addr[IPV4_ADDR_SIZE] = { 0 };
+
+static OCProvisioningStatusCB cbData = NULL;
+
+OCStackResult InitEasySetupManager() {
+       
+       
+    OCStackResult result = OC_STACK_ERROR;
+
+    if (InitProvisioningHandler() == OC_STACK_OK) {
+        result = OC_STACK_OK;
+        OIC_LOG(DEBUG, TAG, "InitProvisioningHandler returned Success");
+    } else {
+        result = OC_STACK_ERROR;
+        OIC_LOG_V(ERROR, TAG, "InitProvisioningHandler returned error = %s",
+                result);
+    }
+
+    return result;
+}
+
+OCStackResult TerminateEasySetupManager() {
+    return TerminateProvisioningHandler();
+}
+
+OCStackResult RegisterProvisioningStausCallback(
+        OCProvisioningStatusCB provisioningStatusCallback) {
+    OCStackResult result = OC_STACK_OK;
+
+    if(provisioningStatusCallback != NULL)
+    {
+        cbData = provisioningStatusCallback;
+    }
+    else
+    {
+        result = OC_STACK_ERROR;
+        OIC_LOG(ERROR, TAG, "provisioningStatusCallback is NULL");
+    }
+
+    return result;
+}
+
+void UnRegisterProvisioningStausCallback() {
+    if (cbData) {
+        cbData = NULL;
+    }
+}
+
+OCStackResult ProvisionEnrollee(const EnrolleeNWProvInfo_t *netInfo)
+{
+       return StartProvisioningProcess(netInfo, cbData);
+}
+
+OCStackResult StopEnrolleeProvisioning(OCConnectivityType connectivityType) {
+    OCStackResult result = OC_STACK_OK;
+
+    //TODO: Have to handle the transport specific easy setup termination
+    StopProvisioningProcess();
+
+    return result;
+}
+
diff --git a/service/easy-setup/sdk/mediator/src/provisioninghandler.cpp b/service/easy-setup/sdk/mediator/src/provisioninghandler.cpp
new file mode 100644 (file)
index 0000000..f242269
--- /dev/null
@@ -0,0 +1,737 @@
+//******************************************************************\r
+//\r
+// Copyright 2015 Samsung Electronics All Rights Reserved.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+//\r
+// Licensed under the Apache License, Version 2.0 (the "License");\r
+// you may not use this file except in compliance with the License.\r
+// You may obtain a copy of the License at\r
+//\r
+//      http://www.apache.org/licenses/LICENSE-2.0\r
+//\r
+// Unless required by applicable law or agreed to in writing, software\r
+// distributed under the License is distributed on an "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+// See the License for the specific language governing permissions and\r
+// limitations under the License.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <string.h>\r
+#include <signal.h>\r
+#include <unistd.h>\r
+#include "ocpayload.h"\r
+#include "provisioninghandler.h"\r
+\r
+// External includes\r
+\r
+#include "camutex.h"\r
+#include "cathreadpool.h"\r
+#include "logger.h"\r
+#include "oic_malloc.h"\r
+\r
+\r
+/**\r
+ * @var g_provisioningMutex\r
+ * @brief Mutex to synchronize access to g_caDtlsContext.\r
+ */\r
+static ca_mutex g_provisioningMutex = NULL;\r
+static ca_cond g_provisioningCond = NULL;\r
+bool g_provisioningCondFlag = false;\r
+\r
+static EnrolleeNWProvInfo_t* netProvInfo;\r
+\r
+/**\r
+ * @var cbData\r
+ * @brief Callback for providing provisioning status callback to application\r
+ */\r
+static OCProvisioningStatusCB cbData = NULL;\r
+static ca_thread_pool_t g_threadPoolHandle = NULL;\r
+\r
+OCStackResult InitProvisioningHandler() {\r
+    OCStackResult ret = OC_STACK_ERROR;\r
+    /* Initialize OCStack*/\r
+    if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK) {\r
+        OIC_LOG(ERROR, TAG, "OCStack init error");\r
+        return ret;\r
+    }\r
+\r
+    g_provisioningMutex = ca_mutex_new();\r
+\r
+    OIC_LOG(DEBUG, TAG, "ca_thread_pool_init initializing");\r
+\r
+    if (CA_STATUS_OK != ca_thread_pool_init(2, &g_threadPoolHandle)) {\r
+        OIC_LOG(DEBUG, TAG, "thread_pool_init failed");\r
+        return OC_STACK_ERROR;\r
+    }\r
+\r
+    g_provisioningCond = ca_cond_new();\r
+    if (NULL == g_provisioningCond) {\r
+        OIC_LOG(DEBUG, TAG, "Failed to create condition");\r
+        ca_mutex_free(g_provisioningMutex);\r
+        ca_thread_pool_free(g_threadPoolHandle);\r
+        return OC_STACK_ERROR;\r
+    }\r
+\r
+    char *string = "listeningFunc invoked in a thread";\r
+    if (CA_STATUS_OK\r
+            != ca_thread_pool_add_task(g_threadPoolHandle, listeningFunc,\r
+                    (void *) string)) {\r
+        OIC_LOG(DEBUG, TAG, "thread_pool_add_task failed");\r
+        ca_thread_pool_free(g_threadPoolHandle);\r
+        ca_mutex_unlock(g_provisioningMutex);\r
+        ca_mutex_free(g_provisioningMutex);\r
+        ca_cond_free(g_provisioningCond);\r
+        return OC_STACK_ERROR;\r
+    }\r
+    return OC_STACK_OK;\r
+}\r
+\r
+OCStackResult TerminateProvisioningHandler() {\r
+    OCStackResult ret = OC_STACK_ERROR;\r
+    if (OCStop() != OC_STACK_OK) {\r
+        OIC_LOG(ERROR, TAG, "OCStack stop error");\r
+    }\r
+\r
+    ca_mutex_lock(g_provisioningMutex);\r
+    g_provisioningCondFlag = true;\r
+    //ca_cond_signal(g_provisioningCond);\r
+    ca_mutex_unlock(g_provisioningMutex);\r
+\r
+    ca_mutex_free(g_provisioningMutex);\r
+    g_provisioningMutex = NULL;\r
+\r
+    ca_thread_pool_free(g_threadPoolHandle);\r
+    g_threadPoolHandle = NULL;\r
+\r
+    ret = OC_STACK_OK;\r
+    return ret;\r
+}\r
+\r
+void listeningFunc(void *data) {\r
+    while (!g_provisioningCondFlag) {\r
+        OCStackResult result;\r
+\r
+        ca_mutex_lock(g_provisioningMutex);\r
+        result = OCProcess();\r
+        ca_mutex_unlock(g_provisioningMutex);\r
+\r
+        if (result != OC_STACK_OK) {\r
+            OIC_LOG(ERROR, TAG, "OCStack stop error");\r
+        }\r
+\r
+        // To minimize CPU utilization we may wish to do this with sleep\r
+        sleep(1);\r
+    }\r
+}\r
+\r
+OCStackApplicationResult ProvisionEnrolleeResponse(void* ctx, OCDoHandle handle,\r
+        OCClientResponse * clientResponse) {\r
+    ProvisioningInfo *provInfo;\r
+\r
+    if (clientResponse) {\r
+        OIC_LOG_V(INFO, TAG, "Put Response");\r
+    } else {\r
+        OIC_LOG_V(INFO, TAG,\r
+                "ProvisionEnrolleeResponse received Null clientResponse");\r
+        provInfo = PrepareProvisioingStatusCB(clientResponse,\r
+                DEVICE_NOT_PROVISIONED);\r
+        cbData(provInfo);\r
+        return OC_STACK_DELETE_TRANSACTION;\r
+    }\r
+\r
+    if (clientResponse->payload) {\r
+\r
+        if(clientResponse->payload->type != PAYLOAD_TYPE_REPRESENTATION)\r
+        {\r
+            OIC_LOG_V(DEBUG, TAG, "Incoming payload not a representation");\r
+            return OC_STACK_DELETE_TRANSACTION;\r
+        }\r
+\r
+        OCRepPayload* input = (OCRepPayload*)(clientResponse->payload);\r
+        if(!input)\r
+        {\r
+            OIC_LOG_V(DEBUG, TAG, "Failed To parse");\r
+            return OC_STACK_DELETE_TRANSACTION;\r
+        }\r
+\r
+        while(input){\r
+\r
+            int64_t ps;\r
+            if(OCRepPayloadGetPropInt(input,OC_RSRVD_ES_PS,&ps))    {\r
+                if(ps == 1)\r
+                {\r
+                    OIC_LOG_V(DEBUG, TAG, "PS is proper");\r
+                    continue;\r
+                }\r
+                else{\r
+                    OIC_LOG_V(DEBUG, TAG, "PS is NOT proper");\r
+                    provInfo = PrepareProvisioingStatusCB(clientResponse,\r
+                            DEVICE_NOT_PROVISIONED);\r
+                    cbData(provInfo);\r
+\r
+                }\r
+            }\r
+\r
+            const char* tnn;\r
+            if(OCRepPayloadGetPropString(input,OC_RSRVD_ES_TNN,&tnn)){\r
+                if(!strcmp(tnn, netProvInfo->netAddressInfo.WIFI.ssid))\r
+                {\r
+                    OIC_LOG_V(DEBUG, TAG, "SSID is proper");\r
+                    continue;\r
+                }\r
+                else{\r
+                    OIC_LOG_V(DEBUG, TAG, "SSID is NOT proper");\r
+                    provInfo = PrepareProvisioingStatusCB(clientResponse,\r
+                            DEVICE_NOT_PROVISIONED);\r
+                    cbData(provInfo);\r
+                }\r
+            }\r
+            const char* cd;\r
+            if(OCRepPayloadGetPropString(input, OC_RSRVD_ES_CD,&cd)){\r
+                if(!strcmp(cd,netProvInfo->netAddressInfo.WIFI.pwd))\r
+                {\r
+                    OIC_LOG_V(DEBUG, TAG, "Password is proper");\r
+                    continue;\r
+                }\r
+                else{\r
+                    OIC_LOG_V(DEBUG, TAG, "Password is NOT proper");\r
+                    provInfo = PrepareProvisioingStatusCB(clientResponse,\r
+                            DEVICE_NOT_PROVISIONED);\r
+                    cbData(provInfo);\r
+                }\r
+            }\r
+\r
+            OCRepPayloadValue* val = input->values;\r
+\r
+            switch(val->type)\r
+            {\r
+                case OCREP_PROP_NULL:\r
+                    OIC_LOG_V(DEBUG, TAG, "\t\t%s: NULL", val->name);\r
+                    break;\r
+                case OCREP_PROP_INT:\r
+                    OIC_LOG_V(DEBUG, TAG, "\t\t%s(int):%lld", val->name, val->i);\r
+                    break;\r
+                case OCREP_PROP_DOUBLE:\r
+                    OIC_LOG_V(DEBUG, TAG, "\t\t%s(double):%f", val->name, val->d);\r
+                    break;\r
+                case OCREP_PROP_BOOL:\r
+                    OIC_LOG_V(DEBUG, TAG, "\t\t%s(bool):%s", val->name, val->b ? "true" : "false");\r
+                    break;\r
+                case OCREP_PROP_STRING:\r
+                    OIC_LOG_V(DEBUG, TAG, "\t\t%s(string):%s", val->name, val->str);\r
+                    break;\r
+                case OCREP_PROP_OBJECT:\r
+                    // Note: Only prints the URI (if available), to print further, you'll\r
+                    // need to dig into the object better!\r
+                    OIC_LOG_V(DEBUG, TAG, "\t\t%s(OCRep):%s", val->name, val->obj->uri);\r
+                    break;\r
+                case OCREP_PROP_ARRAY:\r
+                    switch(val->arr.type)\r
+                    {\r
+                        case OCREP_PROP_INT:\r
+                            OIC_LOG_V(DEBUG, TAG, "\t\t%s(int array):%lld x %lld x %lld",\r
+                                    val->name,\r
+                                    val->arr.dimensions[0], val->arr.dimensions[1],\r
+                                    val->arr.dimensions[2]);\r
+                            break;\r
+                        case OCREP_PROP_DOUBLE:\r
+                            OIC_LOG_V(DEBUG, TAG, "\t\t%s(double array):%lld x %lld x %lld",\r
+                                    val->name,\r
+                                    val->arr.dimensions[0], val->arr.dimensions[1],\r
+                                    val->arr.dimensions[2]);\r
+                            break;\r
+                        case OCREP_PROP_BOOL:\r
+                            OIC_LOG_V(DEBUG, TAG, "\t\t%s(bool array):%lld x %lld x %lld",\r
+                                    val->name,\r
+                                    val->arr.dimensions[0], val->arr.dimensions[1],\r
+                                    val->arr.dimensions[2]);\r
+                            break;\r
+                        case OCREP_PROP_STRING:\r
+                            OIC_LOG_V(DEBUG, TAG, "\t\t%s(string array):%lld x %lld x %lld",\r
+                                    val->name,\r
+                                    val->arr.dimensions[0], val->arr.dimensions[1],\r
+                                    val->arr.dimensions[2]);\r
+                            break;\r
+                        case OCREP_PROP_OBJECT:\r
+                            OIC_LOG_V(DEBUG, TAG, "\t\t%s(OCRep array):%lld x %lld x %lld",\r
+                                    val->name,\r
+                                    val->arr.dimensions[0], val->arr.dimensions[1],\r
+                                    val->arr.dimensions[2]);\r
+                            break;\r
+                        default:\r
+                            //OIC_LOG_V(ERROR, TAG, "\t\t%s <-- Unknown/unsupported array type!",\r
+                            //  val->name);\r
+                            break;\r
+                    }\r
+                    break;\r
+                        default:\r
+                            /*OC_LOG_V(ERROR, TAG\r
+                                , "\t\t%s <-- Unknown type!", val->name);*/\r
+                            break;\r
+            }\r
+            input=input->next;\r
+        }\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+        provInfo = PrepareProvisioingStatusCB(clientResponse,\r
+                DEVICE_PROVISIONED);\r
+        cbData(provInfo);\r
+\r
+        return OC_STACK_KEEP_TRANSACTION;\r
+    } else {\r
+        OIC_LOG(INFO, TAG,\r
+                "ProvisionEnrolleeResponse received NULL clientResponse. \\r
+        Invoking Provisioing Status Callback");\r
+        provInfo = PrepareProvisioingStatusCB(clientResponse,\r
+                DEVICE_NOT_PROVISIONED);\r
+        cbData(provInfo);\r
+        return OC_STACK_DELETE_TRANSACTION;\r
+    }\r
+}\r
+\r
+\r
+\r
+OCStackResult ProvisionEnrollee(OCQualityOfService qos, const char* query, const char* resUri) {\r
+    OIC_LOG_V(INFO, TAG, "\n\nExecuting ProvisionEnrollee%s", __func__);\r
+\r
+\r
+    OCRepPayload* payload = OCRepPayloadCreate();\r
+\r
+    OCRepPayloadSetUri(payload,resUri);\r
+    OCRepPayloadSetPropString(payload,OC_RSRVD_ES_TNN,netProvInfo->netAddressInfo.WIFI.ssid);\r
+    OCRepPayloadSetPropString(payload,OC_RSRVD_ES_CD,netProvInfo->netAddressInfo.WIFI.pwd);\r
+\r
+    OIC_LOG_V(DEBUG, TAG, "OCPayload ready for ProvisionEnrollee");\r
+\r
+    OCStackResult ret = InvokeOCDoResource(query, OC_REST_PUT, OC_HIGH_QOS,\r
+            ProvisionEnrolleeResponse, payload, NULL, 0);\r
+\r
+    return ret;\r
+}\r
+\r
+\r
+OCStackApplicationResult GetProvisioningStatusResponse(void* ctx,\r
+        OCDoHandle handle, OCClientResponse * clientResponse) {\r
+    ProvisioningInfo *provInfo;\r
+\r
+    if (clientResponse == NULL) {\r
+        OIC_LOG(INFO, TAG,\r
+                "getReqCB received NULL clientResponse. \\r
+        Invoking Provisioing Status Callback");\r
+        provInfo = PrepareProvisioingStatusCB(clientResponse,\r
+                DEVICE_NOT_PROVISIONED);\r
+        cbData(provInfo);\r
+        return OC_STACK_DELETE_TRANSACTION;\r
+    }\r
+\r
+    if (clientResponse->rcvdVendorSpecificHeaderOptions\r
+            && clientResponse->numRcvdVendorSpecificHeaderOptions) {\r
+        OIC_LOG(INFO, TAG, "Received vendor specific options");\r
+        uint8_t i = 0;\r
+        OCHeaderOption * rcvdOptions =\r
+                clientResponse->rcvdVendorSpecificHeaderOptions;\r
+        for (i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions;\r
+                i++) {\r
+            if (((OCHeaderOption) rcvdOptions[i]).protocolID == OC_COAP_ID) {\r
+                OIC_LOG_V(INFO, TAG,\r
+                        "Received option with OC_COAP_ID and ID %u with",\r
+                        ((OCHeaderOption) rcvdOptions[i]).optionID);\r
+\r
+                OIC_LOG_BUFFER(INFO, TAG,\r
+                        ((OCHeaderOption) rcvdOptions[i]).optionData,\r
+                        MAX_HEADER_OPTION_DATA_LENGTH);\r
+            }\r
+        }\r
+    }\r
+\r
+    char query[OIC_STRING_MAX_VALUE] = { '\0' };\r
+\r
+\r
+    if (clientResponse->payload) {\r
+\r
+        if(clientResponse->payload && clientResponse->payload->type != PAYLOAD_TYPE_REPRESENTATION)\r
+\r
+        {\r
+            OIC_LOG_V(DEBUG, TAG, "Incoming payload not a representation");\r
+            return OC_STACK_DELETE_TRANSACTION;\r
+        }\r
+\r
+        OCRepPayload* input = (OCRepPayload*)(clientResponse->payload);\r
+        if(!input)\r
+        {\r
+            OIC_LOG_V(DEBUG, TAG, "Failed To parse");\r
+            return OC_STACK_DELETE_TRANSACTION;\r
+        }\r
+        OIC_LOG_V(DEBUG, TAG, "resUri = %s",input->uri);\r
+\r
+        char resURI[MAX_URI_LENGTH]={'\0'};\r
+\r
+        strncpy(resURI, input->uri, sizeof(resURI));\r
+\r
+        snprintf(query, sizeof(query), UNICAST_PROV_STATUS_QUERY,\r
+                clientResponse->addr->addr,\r
+                IP_PORT, resURI);\r
+\r
+        //OCPayloadLogRep(DEBUG,TAG,input);\r
+\r
+        if (ProvisionEnrollee(OC_HIGH_QOS, query, resURI) != OC_STACK_OK) {\r
+            OIC_LOG(INFO, TAG,\r
+                    "GetProvisioningStatusResponse received NULL clientResponse. \\r
+            Invoking Provisioing Status Callback");\r
+            provInfo = PrepareProvisioingStatusCB(clientResponse,\r
+                    DEVICE_NOT_PROVISIONED);\r
+            cbData(provInfo);\r
+\r
+            return OC_STACK_DELETE_TRANSACTION;\r
+        }\r
+    } else {\r
+        OIC_LOG(INFO, TAG,\r
+                "GetProvisioningStatusResponse received NULL clientResponse. \\r
+        Invoking Provisioing Status Callback");\r
+        provInfo = PrepareProvisioingStatusCB(clientResponse,\r
+                DEVICE_NOT_PROVISIONED);\r
+        cbData(provInfo);\r
+        return OC_STACK_DELETE_TRANSACTION;\r
+    }\r
+    return OC_STACK_DELETE_TRANSACTION;\r
+}\r
+\r
+OCStackResult InvokeOCDoResource(const char* query, OCMethod method,\r
+        OCQualityOfService qos, OCClientResponseHandler cb,OCRepPayload* request,\r
+        OCHeaderOption * options, uint8_t numOptions) {\r
+    OCStackResult ret;\r
+    OCCallbackData cbData;\r
+\r
+    cbData.cb = cb;\r
+    cbData.context = (void*) DEFAULT_CONTEXT_VALUE;\r
+    cbData.cd = NULL;\r
+\r
+    ret = OCDoResource(NULL, method, query, 0, &request->base, OC_CONNTYPE, qos,\r
+            &cbData, options, numOptions);\r
+\r
+    if (ret != OC_STACK_OK) {\r
+        OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d",\r
+                ret, method);\r
+    }\r
+\r
+    return ret;\r
+}\r
+\r
+OCStackResult GetProvisioningStatus(OCQualityOfService qos, const char* query) {\r
+    OCStackResult ret = OC_STACK_ERROR;\r
+    OCHeaderOption options[MAX_HEADER_OPTIONS];\r
+\r
+    OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);\r
+\r
+    uint8_t option0[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };\r
+    uint8_t option1[] = { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };\r
+    memset(options, 0, sizeof(OCHeaderOption) * MAX_HEADER_OPTIONS);\r
+    options[0].protocolID = OC_COAP_ID;\r
+    options[0].optionID = 2048;\r
+    memcpy(options[0].optionData, option0, sizeof(option0));\r
+    options[0].optionLength = 10;\r
+    options[1].protocolID = OC_COAP_ID;\r
+    options[1].optionID = 3000;\r
+    memcpy(options[1].optionData, option1, sizeof(option1));\r
+    options[1].optionLength = 10;\r
+\r
+    ret = InvokeOCDoResource(query, OC_REST_GET, OC_HIGH_QOS,\r
+            GetProvisioningStatusResponse, NULL, options, 2);\r
+    return ret;\r
+}\r
+\r
+OCStackResult StartProvisioningProcess(const EnrolleeNWProvInfo_t *netInfo,\r
+        OCProvisioningStatusCB provisioningStatusCallback) {\r
+    OCStackResult result = OC_STACK_ERROR;\r
+\r
+    if (netInfo->netAddressInfo.WIFI.ipAddress == NULL) {\r
+        OIC_LOG(ERROR, TAG, "Request URI is NULL");\r
+        return result;\r
+    }\r
+\r
+    if (provisioningStatusCallback == NULL) {\r
+        OIC_LOG(ERROR, TAG, "ProvisioningStatusCallback is NULL");\r
+        return result;\r
+    }\r
+\r
+    cbData = provisioningStatusCallback;\r
+\r
+    //Copy Network Provisioning  Information\r
+    netProvInfo = (EnrolleeNWProvInfo_t *)OICCalloc(1, sizeof(EnrolleeNWProvInfo_t));\r
+\r
+    if (NULL == netProvInfo)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Invalid input..");\r
+        return OC_STACK_ERROR;\r
+    }\r
+    memcpy(netProvInfo, netInfo, sizeof(EnrolleeNWProvInfo_t));\r
+\r
+    OIC_LOG_V(DEBUG, TAG, "Network Provisioning Info. SSID = %s",\r
+            netProvInfo->netAddressInfo.WIFI.ssid);\r
+\r
+    OIC_LOG_V(DEBUG, TAG, "Network Provisioning Info. PWD = %s",\r
+            netProvInfo->netAddressInfo.WIFI.pwd);\r
+\r
+\r
+    if (CA_STATUS_OK\r
+            != ca_thread_pool_add_task(g_threadPoolHandle, FindProvisioningResource,\r
+                    (void *) "")) {\r
+        OIC_LOG(DEBUG, TAG, "thread_pool_add_task of FindProvisioningResource failed");\r
+        ca_thread_pool_free(g_threadPoolHandle);\r
+        ca_mutex_unlock(g_provisioningMutex);\r
+        ca_mutex_free(g_provisioningMutex);\r
+        ca_cond_free(g_provisioningCond);\r
+        return OC_STACK_ERROR;\r
+    }\r
+    return OC_STACK_OK;\r
+}\r
+\r
+void StopProvisioningProcess() {\r
+    cbData = NULL;\r
+}\r
+\r
+\r
+// This is a function called back when a device is discovered\r
+OCStackApplicationResult FindProvisioningResourceResponse(void* ctx,\r
+        OCDoHandle handle, OCClientResponse * clientResponse) {\r
+    OIC_LOG(INFO, TAG, PCF("Entering FindProvisioningResourceResponse"));\r
+\r
+    OCStackApplicationResult response = OC_STACK_DELETE_TRANSACTION;\r
+\r
+    ProvisioningInfo *provInfo;\r
+\r
+    if (clientResponse->result != OC_STACK_OK) {\r
+        OIC_LOG(ERROR, TAG,\r
+                "OCStack stop error. Calling Provisioing Status Callback");\r
+\r
+        provInfo = PrepareProvisioingStatusCB(clientResponse,\r
+                DEVICE_NOT_PROVISIONED);\r
+\r
+        cbData(provInfo);\r
+        return response;\r
+    }\r
+\r
+    if (clientResponse) {\r
+\r
+\r
+        if(clientResponse->payload && clientResponse->payload->type != PAYLOAD_TYPE_REPRESENTATION)\r
+        {\r
+            OIC_LOG_V(DEBUG, TAG, "Incoming payload not a representation");\r
+            return OC_STACK_DELETE_TRANSACTION;\r
+        }\r
+\r
+        OCRepPayload* discoveryPayload= (OCRepPayload*)(clientResponse->payload);\r
+        if(!discoveryPayload)\r
+        {\r
+            OIC_LOG_V(DEBUG, TAG, "Failed To parse");\r
+            provInfo = PrepareProvisioingStatusCB(clientResponse,\r
+                    DEVICE_NOT_PROVISIONED);\r
+            cbData(provInfo);\r
+            return response;\r
+        }\r
+        OIC_LOG_V(DEBUG, TAG, "resUri = %s",discoveryPayload->uri);\r
+        char szQueryUri[64] = { 0 };\r
+\r
+        snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_PROV_STATUS_QUERY,\r
+                clientResponse->devAddr.addr, IP_PORT, discoveryPayload->uri);\r
+        OIC_LOG_V(DEBUG, TAG, "query before GetProvisioningStatus call = %s", szQueryUri);\r
+\r
+        if (GetProvisioningStatus(OC_HIGH_QOS, szQueryUri) != OC_STACK_OK) {\r
+            OIC_LOG(INFO, TAG,\r
+                    "GetProvisioningStatus returned error. \\r
+            Invoking Provisioing Status Callback");\r
+            provInfo = PrepareProvisioingStatusCB(clientResponse,\r
+                    DEVICE_NOT_PROVISIONED);\r
+\r
+            cbData(provInfo);\r
+            return OC_STACK_DELETE_TRANSACTION;\r
+        }\r
+    } else {\r
+        // clientResponse is invalid\r
+        OIC_LOG(ERROR, TAG,\r
+                "Invalid response for Provisioning Discovery request. \\r
+        Invoking Provisioing Status Callback");\r
+        provInfo = PrepareProvisioingStatusCB(clientResponse,\r
+                DEVICE_NOT_PROVISIONED);\r
+        cbData(provInfo);\r
+        return response;\r
+    }\r
+    return OC_STACK_KEEP_TRANSACTION;\r
+}\r
+\r
+\r
+void FindProvisioningResource(void *data)\r
+{\r
+    OCStackResult ret = OC_STACK_ERROR;\r
+\r
+    /* Start a discovery query*/\r
+    char szQueryUri[64] = { 0 };\r
+\r
+    snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_PROVISIONING_QUERY,\r
+            netProvInfo->netAddressInfo.WIFI.ipAddress, IP_PORT);\r
+\r
+    OIC_LOG_V(DEBUG, TAG, "szQueryUri = %s", szQueryUri);\r
+\r
+    OCCallbackData ocCBData;\r
+\r
+    ocCBData.cb = FindProvisioningResourceResponse;\r
+    ocCBData.context = (void*) DEFAULT_CONTEXT_VALUE;\r
+    ocCBData.cd = NULL;\r
+\r
+    ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,\r
+            OC_LOW_QOS, &ocCBData, NULL, 0);\r
+\r
+    if (ret != OC_STACK_OK) {\r
+        OIC_LOG(ERROR, TAG, "OCStack resource error");\r
+\r
+        OIC_LOG(ERROR, TAG,\r
+                "FindProvisioningResource failed. \\r
+        Invoking Provisioing Status Callback");\r
+\r
+        ProvisioningInfo *provInfo;\r
+        provInfo = (ProvisioningInfo *) OICCalloc(1, sizeof(ProvisioningInfo));\r
+\r
+        if(provInfo == NULL)\r
+        {\r
+            OIC_LOG_V(ERROR, TAG, "Failed to allocate memory");\r
+            return;\r
+        }\r
+\r
+        OCDevAddr *devAddr = (OCDevAddr *) OICCalloc(1, sizeof(OCDevAddr));\r
+\r
+        if(devAddr == NULL)\r
+        {\r
+            OIC_LOG_V(ERROR, TAG, "Failed to allocate memory");\r
+            return;\r
+        }\r
+\r
+        strncpy(devAddr->addr, netProvInfo->netAddressInfo.WIFI.ipAddress, sizeof(devAddr->addr));\r
+        devAddr->port= IP_PORT;\r
+        provInfo->provDeviceInfo.addr = devAddr;\r
+        provInfo->provStatus = DEVICE_NOT_PROVISIONED;\r
+\r
+\r
+        cbData(provInfo);\r
+    }\r
+}\r
+\r
+OCStackApplicationResult SubscribeProvPresenceCallback(void* ctx, OCDoHandle handle,\r
+        OCClientResponse* clientResponse) {\r
+    OIC_LOG(INFO, TAG, PCF("Entering SubscribeProvPresenceCallback"));\r
+\r
+    OCStackApplicationResult response = OC_STACK_DELETE_TRANSACTION;\r
+\r
+    if (clientResponse->result != OC_STACK_OK) {\r
+        OIC_LOG(ERROR, TAG, "OCStack stop error");\r
+        return response;\r
+    }\r
+\r
+    if (clientResponse) {\r
+        OIC_LOG(INFO, TAG, PCF("Client Response exists"));\r
+\r
+        if(clientResponse->payload && clientResponse->payload->type != PAYLOAD_TYPE_REPRESENTATION)\r
+        {\r
+            OIC_LOG_V(DEBUG, TAG, "Incoming payload not a representation");\r
+            return response;\r
+        }\r
+\r
+        OCRepPayload* discoveryPayload= (OCRepPayload*)(clientResponse->payload);\r
+        if(!discoveryPayload)\r
+        {\r
+            OIC_LOG_V(DEBUG, TAG, "invalid payload");\r
+            return response;\r
+        }\r
+\r
+        char sourceIPAddr[OIC_STRING_MAX_VALUE] = { '\0' };\r
+        snprintf(sourceIPAddr, sizeof(sourceIPAddr), "%s", clientResponse->addr->addr);\r
+\r
+        OIC_LOG_V(DEBUG, TAG, "Discovered %s @ %s",\r
+                discoveryPayload->uri, sourceIPAddr);\r
+\r
+        /* Start a discovery query*/\r
+        char szQueryUri[64] = { 0 };\r
+\r
+        snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_PROVISIONING_QUERY,\r
+                sourceIPAddr, IP_PORT);\r
+\r
+        /*if (FindProvisioningResource(qos, szQueryUri) != OC_STACK_OK) {\r
+            OIC_LOG(ERROR, TAG, "FindProvisioningResource failed");\r
+            return OC_STACK_KEEP_TRANSACTION;\r
+        }*/\r
+    } else {\r
+        // clientResponse is invalid\r
+        OIC_LOG(ERROR, TAG, PCF("Client Response is NULL!"));\r
+    }\r
+    return OC_STACK_KEEP_TRANSACTION;\r
+}\r
+\r
+\r
+OCStackResult SubscribeProvPresence(OCQualityOfService qos,\r
+        const char* requestURI) {\r
+    OCStackResult ret = OC_STACK_ERROR;\r
+\r
+    OCCallbackData cbData;\r
+\r
+    cbData.cb = &SubscribeProvPresenceCallback;\r
+    cbData.context = (void*) DEFAULT_CONTEXT_VALUE;\r
+    cbData.cd = NULL;\r
+\r
+    ret = OCDoResource(NULL, OC_REST_PRESENCE, requestURI, 0, 0, OC_CONNTYPE,\r
+            OC_LOW_QOS, &cbData, NULL, 0);\r
+\r
+    if (ret != OC_STACK_OK) {\r
+        OIC_LOG(ERROR, TAG, "OCStack resource error");\r
+    }\r
+\r
+    return ret;\r
+}\r
+\r
+OCStackResult FindNetworkResource() {\r
+    OCStackResult ret = OC_STACK_ERROR;\r
+    if (OCStop() != OC_STACK_OK) {\r
+        OIC_LOG(ERROR, TAG, "OCStack stop error");\r
+    }\r
+\r
+    return ret;\r
+}\r
+\r
+ProvisioningInfo* PrepareProvisioingStatusCB(OCClientResponse * clientResponse, ProvStatus provStatus) {\r
+\r
+    ProvisioningInfo *provInfo = (ProvisioningInfo *) OICCalloc(1, sizeof(ProvisioningInfo));\r
+\r
+    if(provInfo == NULL)\r
+    {\r
+        OIC_LOG_V(ERROR, TAG, "Failed to allocate memory");\r
+        return NULL;\r
+    }\r
+\r
+    OCDevAddr *devAddr = (OCDevAddr *) OICCalloc(1, sizeof(OCDevAddr));\r
+\r
+    if(devAddr == NULL)\r
+    {\r
+        OIC_LOG_V(ERROR, TAG, "Failed to allocate memory");\r
+        return NULL;\r
+    }\r
+\r
+    strncpy(devAddr->addr, clientResponse->addr->addr, sizeof(devAddr->addr));\r
+    devAddr->port= clientResponse->addr->port;\r
+\r
+    provInfo->provDeviceInfo.addr = devAddr;\r
+\r
+    provInfo->provStatus = provStatus;\r
+\r
+    return provInfo;\r
+}\r
+\r
+\r
+\r
+\r