-/******************************************************************
- *
- * 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
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')
# Build protocol plugin project
# protocol-plugin use 'inotify', this feature isn't support by MAC OSX
- if target_os not in ['darwin', 'ios']:
+ if target_os not in ['darwin', 'ios', 'android']:
SConscript('protocol-plugin/SConscript')
# Build notification manager project
- if target_os not in ['android']:
- SConscript('notification-manager/SConscript')
+ SConscript('notification-manager/SConscript')
+
+if target_os in ['arduino','android', 'linux']:
+ SConscript('easy-setup/SConscript')
# Build resource-encapsulation project
- SConscript('resource-encapsulation/SConscript')
-#else:
-# SConscript('notification-manager/SampleApp/arduino/SConscript')
+ if target_os not in ['tizen']:
+ SConscript('resource-encapsulation/SConscript')
--- /dev/null
+=== Prerequisites ===
+
+* 1. Scons
+
+Please refer to the following page to install scons:
+ http://www.scons.org/doc/production/HTML/scons-user.html#chap-build-install
+(Note: on Windows, install Python 2.x before installing scons)
+
+* 2. IDE/SDK Pre-requites
+To build for some OS (Android / Arduino / IOS ...), an IDE/SDK may be required,
+please go to the relative page to download and install the required IDE/SDK.
+
+Note: Connectivity module building has been changed. We have to build connectivity
+ from the iotivity root folder.
+
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+Android Build:
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+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
+
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+Arduino Build:
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+Steps to build and deploy Easysetup Mediator in Arduino platform
+1) Compilation using Scons for Arduino Due
+ a) Set up Arduino first before building. Refer to "connectivity\build\arduino\Arduino_Setup_README.txt" file for help.
+ b) Go to "iotivity/" folder.
+ c) Prerequisite exports for Arduino
+ export ARDUINO_HOME=<ARDUINO_HOME_DIR>
+ d) Start Arduino IDE. Select ""Tools->Port->Programming port"
+ e) scons TARGET_OS=arduino BOARD=arduino_due_x_dbg TARGET_ARCH=arm SHIELD=WIFI
+ - With debug or logging
+ scons TARGET_OS=arduino BOARD=arduino_due_x_dbg TARGET_ARCH=arm SHIELD=WIFI RELEASE=0
+ - With installation to Arduino
+ scons TARGET_OS=arduino BOARD=arduino_due_x_dbg TARGET_ARCH=arm SHIELD=WIFI RELEASE=0 UPLOAD=true
+ NOTE: BOARD=arduino_due_x_dbg|arduino_due_x. Default is arduino_due_x_dbg.
+
+ Possible values for <transport> are:
+ -> IP :
+ $ scons TARGET_OS=arduino BOARD=arduino_due_x_dbg TARGET_ARCH=arm SHIELD=WIFI RELEASE=0
+ -> BLE :
+ $ scons TARGET_OS=arduino BOARD=arduino_due_x_dbg TARGET_ARCH=arm SHIELD=WIFI RELEASE=0
+
+ Note :- Only single transport can be built at a time for Arduino
+ f) The above command will build sample. The "thinserver.hex" can be found at "out/arduino/arm/release/service/easy-setup/sampleapp/arduino/thinserver/"
+ g) After building sample, script will try to install on "/dev/ttyACM0" port in 'sudo' mode.
+ To skip installation, set command line argument 'UPLOAD=false' or without UPLOAD option
+ h) To set BLE Shield Name, include the option DEVICE_NAME during scons build.
+ -> $ scons TARGET_OS=arduino BOARD=arduino_due_x_dbg TARGET_ARCH=arm SHIELD=BLE RELEASE=0 DEVICE_NAME=OIC
+
+ Specified Device name length MUST be less than 10 characters. RBL Library has this limitation.
+ By Default DEVICE_NAME=OIC-DEVICE, if device name option is not specified
+
+ To change the port number, please modify "port" variable in __upload() function in: "/build/arduino/SConscript".
+
+
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+Folder structure:
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+
+iotivity/
+└── service
+ └── easy-setup/
+ │── SConscript
+ │── sdk
+ │ └── inc
+ │ └── src
+ │ └── android
+ │ └── arduino
+ │ └──wifi
+ │ └──inc
+ │ └──src
+ │── sampleapp
+ │ └──android
+ │ └──arduino
+ │ └──linux
+ └── Build_Instructions_Android_Arduino.txt - You are reading this.
\ No newline at end of file
--- /dev/null
+#******************************************************************
+#
+# 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')
+
+
--- /dev/null
+#******************************************************************
+#
+# 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')
--- /dev/null
+#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
--- /dev/null
+<?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
--- /dev/null
+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
+}
\ No newline at end of file
--- /dev/null
+<?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-feature android:name="android.permission.CONNECTIVITY_INTERNAL" android:required="true"/>
+
+
+
+ <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>
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p/>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p/>\r
+ * <p/>\r
+ * <p/>\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
+ * <p/>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p/>\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
+ * <p/>\r
+ * ****************************************************************\r
+ */\r
+\r
+package org.iotivity.service.easysetup;\r
+\r
+import java.io.IOException;\r
+\r
+import org.iotivity.service.easysetup.core.EasySetupService;\r
+import org.iotivity.service.easysetup.core.EasySetupStatus;\r
+import org.iotivity.service.easysetup.core.EnrolleeDevice;\r
+import org.iotivity.service.easysetup.core.EnrolleeState;\r
+import org.iotivity.service.easysetup.core.IpOnBoardingConnection;\r
+import org.iotivity.service.easysetup.impl.EnrolleeDeviceFactory;\r
+import org.iotivity.service.easysetup.impl.WiFiOnBoardingConfig;\r
+import org.iotivity.service.easysetup.impl.WiFiProvConfig;\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.os.Handler;\r
+import android.os.Message;\r
+import android.util.Log;\r
+import android.view.View;\r
+import android.view.View.OnClickListener;\r
+import android.widget.Button;\r
+import android.widget.EditText;\r
+import android.widget.ImageView;\r
+import android.widget.ProgressBar;\r
+import android.widget.TextView;\r
+import android.widget.Toast;\r
+\r
+public class MainActivity extends Activity {\r
+\r
+\r
+ /*Status to update the UI */\r
+ public static final int SUCCESS = 0;\r
+ public static final int FAILED = 1;\r
+ public static final int STATE_CHANGED = 2;\r
+\r
+ static final int REQUEST_IMAGE_CAPTURE = 1;\r
+ ImageView imageView;\r
+\r
+ EditText mSsidText;\r
+ EditText mPassText;\r
+\r
+ EditText mEnrolleeSsidText;\r
+ EditText mmEnrolleePasswordPassText;\r
+\r
+\r
+ TextView mDeviceIpTextView;\r
+ TextView mDeviceMacTextView;\r
+\r
+\r
+ TextView mResultTextView;\r
+ ProgressBar mProgressbar;\r
+ Button mStartButton;\r
+ Button mStopButton;\r
+ Handler mHandler = new ThreadHandler();\r
+\r
+ /**\r
+ * Objects to be instantiated by the programmer\r
+ */\r
+ WiFiProvConfig mWiFiProvConfig;\r
+ WiFiOnBoardingConfig mWiFiOnBoardingConfig;\r
+ EasySetupService mEasySetupService;\r
+ EnrolleeDeviceFactory mDeviceFactory;\r
+ EnrolleeDevice mDevice;\r
+\r
+ @Override\r
+ protected void onCreate(Bundle savedInstanceState) {\r
+ super.onCreate(savedInstanceState);\r
+ setContentView(R.layout.activity_main);\r
+\r
+ /* Initialize widgets to get user input for target network's SSID & password*/\r
+ mSsidText = (EditText) findViewById(R.id.ssid);\r
+ mPassText = (EditText) findViewById(R.id.password);\r
+ mEnrolleeSsidText = (EditText) findViewById(R.id.enrolleeSsid);\r
+ mmEnrolleePasswordPassText = (EditText) findViewById(R.id.enrolleePass);\r
+ mDeviceIpTextView = (TextView) findViewById(R.id.ipAddr);\r
+ mDeviceMacTextView = (TextView) findViewById(R.id.hardAddr);\r
+\r
+ mResultTextView = (TextView) findViewById(R.id.status);\r
+ mProgressbar = (ProgressBar) findViewById(R.id.progressBar);\r
+\r
+\r
+\r
+\r
+ /* Create Easy Setup Service instance*/\r
+ mEasySetupService = EasySetupService.getInstance(getApplicationContext(),\r
+ new EasySetupStatus() {\r
+\r
+ @Override\r
+ public void onFinished(final EnrolleeDevice enrolledevice) {\r
+ Log.i("MainActivity", "onFinished() is received " + enrolledevice\r
+ .isSetupSuccessful());\r
+ if (enrolledevice.isSetupSuccessful()) {\r
+ mHandler.sendEmptyMessage(SUCCESS);\r
+ } else {\r
+ mHandler.sendEmptyMessage(FAILED);\r
+ }\r
+ }\r
+\r
+ @Override\r
+ public void onProgress(EnrolleeState state) {\r
+ Log.i("MainActivity", "onProgress() is received ");\r
+ mHandler.sendEmptyMessage(STATE_CHANGED);\r
+ }\r
+\r
+ });\r
+\r
+ /* Create EnrolleeDevice Factory instance*/\r
+ mDeviceFactory = EnrolleeDeviceFactory.newInstance(getApplicationContext());\r
+\r
+ /* Create a device using Factory instance*/\r
+ mDevice = mDeviceFactory.newEnrolleeDevice(getOnBoardingWifiConfig(),\r
+ getEnrollerWifiConfig());\r
+\r
+ addListenerForStartAP();\r
+ addListenerForStopAP();\r
+ }\r
+\r
+ public WiFiProvConfig getEnrollerWifiConfig() {\r
+ /* Provide the credentials for the Mediator Soft AP to be connected by Enrollee*/\r
+ mWiFiProvConfig = new WiFiProvConfig("hub2.4G", "11112222");\r
+ mEnrolleeSsidText.setText("hub2.4G");\r
+ mmEnrolleePasswordPassText.setText("11112222");\r
+\r
+ return mWiFiProvConfig;\r
+ }\r
+\r
+ public WiFiOnBoardingConfig getOnBoardingWifiConfig() {\r
+ mWiFiOnBoardingConfig = new WiFiOnBoardingConfig();\r
+\r
+ /* Provide the target credentials to be provisioned to the Enrollee by Mediator*/\r
+ mWiFiOnBoardingConfig.setSSId("EasySetup123");\r
+ mWiFiOnBoardingConfig.setSharedKey("EasySetup123");\r
+ mWiFiOnBoardingConfig.setAuthAlgo(WifiConfiguration.AuthAlgorithm.OPEN);\r
+ mWiFiOnBoardingConfig.setKms(WifiConfiguration.KeyMgmt.WPA_PSK);\r
+\r
+ // Updating the UI with default credentials\r
+ mSsidText.setText("EasySetup123");\r
+ mPassText.setText("EasySetup123");\r
+\r
+ return mWiFiOnBoardingConfig;\r
+ }\r
+\r
+\r
+ public void onDestroy() {\r
+ super.onDestroy();\r
+ /*Reset the Easy setup process*/\r
+ if(mEasySetupService != null)\r
+ {\r
+ mEasySetupService.finish();\r
+ }\r
+ }\r
+\r
+ public void addListenerForStartAP() {\r
+ mStartButton = (Button) findViewById(R.id.startSetup);\r
+\r
+ mStartButton.setOnClickListener(new OnClickListener() {\r
+ @Override\r
+ public void onClick(View arg0) {\r
+ try {\r
+\r
+ mProgressbar.setVisibility(View.VISIBLE);\r
+ mProgressbar.setIndeterminate(true);\r
+ mStartButton.setEnabled(false);\r
+ mResultTextView.setText(R.string.running);\r
+\r
+ //Reset Device information\r
+ mDeviceIpTextView.setText(R.string.not_available);\r
+ mDeviceMacTextView.setText(R.string.not_available);\r
+\r
+\r
+ String ssid = mSsidText.getText().toString();\r
+ String password = mPassText.getText().toString();\r
+\r
+ String enrolleeSsid = mEnrolleeSsidText.getText().toString();\r
+ String enrolleePassword = mmEnrolleePasswordPassText.getText().toString();\r
+\r
+ mWiFiProvConfig = new WiFiProvConfig(enrolleeSsid, enrolleePassword);\r
+\r
+ mWiFiOnBoardingConfig.setSSId(ssid);\r
+ mWiFiOnBoardingConfig.setSharedKey(password);\r
+\r
+\r
+ mEasySetupService.startSetup(mDevice);\r
+\r
+ mStopButton.setEnabled(true);\r
+\r
+\r
+ } catch (IOException e) {\r
+ e.printStackTrace();\r
+ }\r
+\r
+ }\r
+ });\r
+ }\r
+\r
+ public void addListenerForStopAP() {\r
+ mStopButton = (Button) findViewById(R.id.stopSetup);\r
+\r
+ mStopButton.setOnClickListener(new OnClickListener() {\r
+ @Override\r
+ public void onClick(View arg0) {\r
+ mStartButton.setEnabled(true);\r
+ mStopButton.setEnabled(false);\r
+ mResultTextView.setText(R.string.stopped);\r
+ mProgressbar.setIndeterminate(false);\r
+ mProgressbar.setVisibility(View.INVISIBLE);\r
+ mEasySetupService.stopSetup(mDevice);\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
+ class ThreadHandler extends Handler {\r
+ @Override\r
+ public void handleMessage(Message msg) {\r
+\r
+ switch (msg.what) {\r
+ case SUCCESS: {\r
+\r
+ mProgressbar.setIndeterminate(false);\r
+ mStopButton.setEnabled(false);\r
+ mStartButton.setEnabled(true);\r
+ mProgressbar.setVisibility(View.INVISIBLE);\r
+ String resultMsg = "Device configured successfully";\r
+ mResultTextView.setText(R.string.success);\r
+\r
+ /* Update device information on the Ui */\r
+ IpOnBoardingConnection connection = (IpOnBoardingConnection) mDevice\r
+ .getConnection();\r
+ mDeviceIpTextView.setText(connection.getIp());\r
+ mDeviceMacTextView.setText(connection.getHardwareAddress());\r
+\r
+ Toast.makeText(getApplicationContext(), resultMsg, Toast.LENGTH_SHORT).show();\r
+ break;\r
+ }\r
+ case FAILED: {\r
+\r
+ mProgressbar.setIndeterminate(false);\r
+ mStopButton.setEnabled(false);\r
+ mStartButton.setEnabled(true);\r
+ mProgressbar.setVisibility(View.INVISIBLE);\r
+ String resultMsg = "Device configuration failed";\r
+ mResultTextView.setText(R.string.failed);\r
+ Toast.makeText(getApplicationContext(), resultMsg, Toast.LENGTH_SHORT).show();\r
+ break;\r
+ }\r
+\r
+ case STATE_CHANGED: {\r
+ String resultMsg = "Device state changed";\r
+ Toast.makeText(getApplicationContext(), resultMsg, Toast.LENGTH_SHORT).show();\r
+ break;\r
+ }\r
+\r
+ }\r
+\r
+\r
+ }\r
+ }\r
+\r
+}\r
--- /dev/null
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:background="@drawable/background"
+ android:orientation="vertical"
+ android:paddingBottom="@dimen/activity_vertical_margin"
+ android:paddingLeft="@dimen/activity_horizontal_margin"
+ android:paddingRight="@dimen/activity_horizontal_margin"
+ android:paddingTop="@dimen/activity_vertical_margin"
+ tools:context="org.iotivity.service.easysetup.mediator.MainActivity">
+
+
+ <ProgressBar
+ android:id="@+id/progressBar"
+ style="?android:attr/progressBarStyleHorizontal"
+ android:layout_width="350dp"
+ android:layout_height="wrap_content"
+ android:visibility="invisible" />
+
+
+ <LinearLayout
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center"
+ android:layout_marginTop="5dp"
+ android:orientation="horizontal">
+
+
+ <TextView
+ android:id="@+id/lablestatus"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginLeft="8dp"
+ android:layout_marginRight="20dp"
+ android:elegantTextHeight="true"
+ android:text="@string/test_status"
+ android:textSize="15sp" />
+
+ <TextView
+ android:id="@+id/status"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginLeft="10dp"
+ android:layout_marginRight="30dp"
+ android:text="@string/not_started"
+ android:textColor="@android:color/background_light"
+ android:textSize="20dp" />
+
+ </LinearLayout>
+
+ <LinearLayout
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerHorizontal="true"
+ android:layout_gravity="center"
+ android:layout_marginTop="10dp"
+ android:orientation="vertical">
+
+ <TextView
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="Enter Enroller's SSID" />
+
+
+ <EditText
+ android:id="@+id/enrolleeSsid"
+ android:layout_width="250dp"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal" />
+
+
+ <TextView
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="10dp"
+ android:text="Enter Enroller's Password" />
+
+
+ <EditText
+ android:id="@+id/enrolleePass"
+ android:layout_width="250dp"
+ android:layout_height="wrap_content"
+
+ android:layout_gravity="center_horizontal" />
+
+ </LinearLayout>
+
+
+ <LinearLayout
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerHorizontal="true"
+ android:layout_gravity="center"
+ android:layout_marginTop="10dp"
+ android:orientation="vertical">
+
+ <TextView
+ android:id="@+id/textView"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="Enter SoftAP SSID" />
+
+
+ <EditText
+ android:id="@+id/ssid"
+ android:layout_width="250dp"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal" />
+
+
+ <TextView
+ android:id="@+id/textView2"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="10dp"
+ android:text="Enter SoftAP PWD" />
+
+
+ <EditText
+ android:id="@+id/password"
+ android:layout_width="250dp"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal" />
+
+ </LinearLayout>
+
+
+ <TextView
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:layout_marginTop="5dp"
+ android:text="Device information"
+ android:textAppearance="?android:attr/textAppearanceMedium" />
+
+ <RelativeLayout
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerHorizontal="true"
+ android:layout_gravity="center"
+ android:layout_marginTop="10dp"
+ android:orientation="vertical">
+
+
+ <TextView
+ android:id="@+id/ipAddrLable"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:text="IP Address"
+ android:textAppearance="?android:attr/textAppearanceSmall" />
+
+ <TextView
+ android:id="@+id/ipAddr"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:layout_toRightOf="@id/ipAddrLable"
+ android:text="@string/not_available"
+
+ android:textAppearance="?android:attr/textAppearanceSmall" />
+
+
+ <TextView
+ android:id="@+id/hardAddrLable"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_below="@id/ipAddrLable"
+ android:layout_gravity="center_horizontal"
+ android:text="MAC Address"
+ android:textAppearance="?android:attr/textAppearanceSmall" />
+
+ <TextView
+ android:id="@+id/hardAddr"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_below="@id/ipAddr"
+ android:layout_gravity="center_horizontal"
+ android:layout_toRightOf="@id/hardAddrLable"
+ android:text="@string/not_available"
+ android:textAppearance="?android:attr/textAppearanceSmall" />
+
+
+ </RelativeLayout>
+
+
+ <LinearLayout
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerHorizontal="true"
+ android:layout_gravity="center"
+ android:layout_marginTop="20dp"
+ android:orientation="horizontal">
+
+ <Button
+ android:id="@+id/startSetup"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_alignParentTop="true"
+ android:layout_centerHorizontal="true"
+ android:layout_margin="10dp"
+ android:layout_marginTop="20dp"
+ android:elegantTextHeight="true"
+ android:text="@string/startSetup"
+ android:textAllCaps="false"
+ android:textSize="18sp" />
+
+ <Button
+ android:id="@+id/stopSetup"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_below="@+id/startSetup"
+ android:layout_centerHorizontal="true"
+ android:layout_margin="10dp"
+ android:elegantTextHeight="true"
+ android:enabled="false"
+ android:text="@string/stopSetup"
+ android:textAllCaps="false"
+ android:textSize="18sp" />
+
+ </LinearLayout>
+
+</LinearLayout>
\ No newline at end of file
--- /dev/null
+<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
--- /dev/null
+<resources>
+
+ <!-- Default screen margins, per the Android Design guidelines. -->
+ <dimen name="activity_horizontal_margin">16dp</dimen>
+ <dimen name="activity_vertical_margin">1dp</dimen>
+
+</resources>
--- /dev/null
+<?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>
+
+ <string name="startSetup">Start Setup</string>
+ <string name="stopSetup">Stop Setup</string>
+ <string name="SSID">SSID</string>
+ <string name="Password">Password</string>
+ <string name="success">Successful</string>
+ <string name="failed">Failed</string>
+ <string name="not_started">Not started</string>
+ <string name="test_status">Device configuration</string>
+ <string name="running">Running</string>
+ <string name="stopped">Stopped</string>
+ <string name="not_available">Not available</string>
+
+
+</resources>
--- /dev/null
+<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>
--- /dev/null
+// 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
--- /dev/null
+include ':app'\r
--- /dev/null
+#******************************************************************
+#
+# 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.'
--- /dev/null
+//******************************************************************
+//
+// 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 <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(ESResult 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..."));
+
+ if(InitEasySetup(ES_WIFI, ssid, passwd, EventCallbackInApp) == ES_ERROR)
+ {
+ OC_LOG(ERROR, TAG, "EasySetup Init Failed");
+ return;
+ }
+
+ if(InitProvisioning(EventCallbackInApp)== ES_ERROR)
+ {
+ OC_LOG(ERROR, TAG, "Init Provisioning Failed");
+ 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;
+ }
+}
--- /dev/null
+#******************************************************************
+#
+# 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')
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include <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;
+}
+
--- /dev/null
+//******************************************************************
+//
+// 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 55555
+#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_IP_USE_V4;
+
+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,
+} ESResult;
+
+
+/**
+ * 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
--- /dev/null
+//******************************************************************
+//
+// 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"
+
+#define TAG PCF("ES_NH")
+
+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;
+
+ESResult 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;
+ }
+
+ OC_LOG_V(INFO, TAG, PCF("Finding SSID: %s"), ssid);
+
+ 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, PCF("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, PCF("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;
+ }
+}
--- /dev/null
+//******************************************************************
+//
+// 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)(ESResult);
+
+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;
+
+ESResult ConnectToWiFiNetwork(const char *ssid, const char *pass, NetworkEventCallback);
+int getCurrentNetworkInfo(NetworkType targetType, NetworkInfo *info);
+
+#endif
--- /dev/null
+//******************************************************************
+//
+// 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)(ESResult);
+
+ESResult InitEasySetup(NetworkType networkType, const char *ssid, const char *passwd,
+ EventCallback cb);
+ESResult InitProvisioning(EventCallback cb);
+ESResult TerminateEasySetup();
+
--- /dev/null
+//******************************************************************
+//
+// 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)(ESResult);
+
+/* 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
--- /dev/null
+//******************************************************************
+//
+// 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"
+#include "ocstack.h"
+
+#define TAG PCF("ES")
+
+int g_eventflag = 0;
+int g_cnt = 0;
+char *targetSsid;
+char *targetPass;
+
+EventCallback g_cbForProvisioning = NULL;
+EventCallback g_cbForOnboarding = NULL;
+
+void EventCallbackInOnboarding(ESResult event);
+void EventCallbackInProvisioning(ESResult event);
+void EventCallbackAfterProvisioning(ESResult event);
+
+void EventCallbackInOnboarding(ESResult event)
+{
+ if (event == ES_NETWORKFOUND || event == ES_NETWORKCONNECTED)
+ {
+ if (g_cbForOnboarding != NULL)
+ {
+ g_cbForOnboarding(event);
+ }
+ }
+}
+
+void EventCallbackInProvisioning(ESResult event)
+{
+ ESResult res = ES_OK;
+
+ if (event == ES_RECVTRIGGEROFPROVRES)
+ {
+ targetSsid = (char *) malloc(MAXSSIDLEN);
+ targetPass = (char *) malloc(MAXNETCREDLEN);
+
+ if(TerminateEasySetup() != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, PCF("Terminating stack failed"));
+ return;
+ }
+
+ GetTargetNetworkInfoFromProvResource(targetSsid, targetPass);
+
+ res = ConnectToWiFiNetwork(targetSsid, targetPass, EventCallbackAfterProvisioning);
+
+ if (g_cbForProvisioning != NULL)
+ {
+ g_cbForProvisioning(res);
+ }
+ }
+}
+
+void EventCallbackAfterProvisioning(ESResult event)
+{
+ if (event == ES_NETWORKFOUND || event == ES_NETWORKCONNECTED)
+ {
+ if (g_cbForProvisioning != NULL)
+ {
+ g_cbForProvisioning(event);
+ }
+ }
+}
+
+ESResult 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;
+ }
+
+ if(ConnectToWiFiNetwork(ssid, passwd, EventCallbackInOnboarding) != ES_NETWORKCONNECTED)
+ {
+ OC_LOG(ERROR, TAG, PCF("ConnectToWiFiNetwork Failed"));
+ return ES_ERROR;
+ }
+ else{
+ OC_LOG(INFO, TAG, PCF("ConnectToWiFiNetwork Success"));
+ return ES_OK;
+ }
+ }
+}
+
+
+ESResult InitEasySetup(NetworkType networkType, const char *ssid, const char *passwd,
+ EventCallback cb)
+{
+ if(FindNetworkForOnboarding(networkType, ssid, passwd, cb) != ES_OK)
+ {
+ OC_LOG(ERROR, TAG, PCF("OnBoarding Failed"));
+ return ES_ERROR;
+ }
+
+ // 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 ES_ERROR;
+ }
+ else
+ {
+ OC_LOG(DEBUG, TAG, PCF("OCStack init success"));
+ return ES_OK;
+ }
+}
+
+ESResult TerminateEasySetup()
+{
+ if(OCStop() != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, PCF("OCStack stop failed"));
+ return ES_ERROR;
+ }
+ else
+ {
+ OC_LOG(ERROR, TAG, PCF("OCStack stop success"));
+ return ES_OK;
+ }
+}
+
+ESResult InitProvisioning(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;
+}
+
--- /dev/null
+//******************************************************************
+//
+// 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"
+
+#define TAG PCF("ES_RH")
+
+ProvResource g_prov;
+NetResource g_net;
+
+OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
+ OCEntityHandlerRequest *ehRequest,
+ 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, PCF("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, PCF("SSID: %s"), g_net.cnn);
+ OC_LOG_V(INFO, TAG, PCF("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;
+ 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 *getResp = constructResponse(ehRequest);
+ if(!getResp)
+ {
+ OC_LOG(ERROR, TAG, PCF("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, PCF("Failed to parse"));
+ return ehResult;
+ }
+
+ char* tnn;
+ if(OCRepPayloadGetPropString(input,OC_RSRVD_ES_TNN, &tnn))
+ {
+ sprintf(g_prov.tnn, "%s", tnn);
+ }
+
+ 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, PCF("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, PCF("Failed to parse") );
+ return ehResult;
+ }
+ 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 (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 (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, PCF("Received GET request"));
+ ehRet = ProcessGetRequest(entityHandlerRequest, &payload);
+ }
+ else if (OC_REST_PUT == entityHandlerRequest->method)
+ {
+ OC_LOG_V(INFO, TAG, PCF("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 uses OCPaylod while all get,put methodes use OCRepPayload
+ response.payload = (OCPayload*)(payload);
+ 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, PCF("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";
+ }
+}
+
--- /dev/null
+#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
--- /dev/null
+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
--- /dev/null
+<?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
--- /dev/null
+include ':iotivity-armeabi-base-debug'
\ No newline at end of file
--- /dev/null
+<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
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p/>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p/>\r
+ * <p/>\r
+ * <p/>\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
+ * <p/>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p/>\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
+ * <p/>\r
+ * ****************************************************************\r
+ */\r
+\r
+package org.iotivity.service.easysetup.core;\r
+\r
+import android.content.Context;\r
+import android.util.Log;\r
+\r
+import org.iotivity.service.easysetup.impl.EnrolleeDeviceFactory;\r
+import org.iotivity.service.easysetup.mediator.EasySetupManager;\r
+import org.iotivity.service.easysetup.mediator.ProvisionEnrollee;\r
+\r
+import java.io.IOException;\r
+import java.util.ArrayList;\r
+\r
+/**\r
+ * This is facade class, a single point of contact for Application.\r
+ * It contains set of APIs to do easy setup of the enrolling device.\r
+ * ON-BOARDING - This is a step to establish connectivity between the device & Mediator device.\r
+ * PROVISION - This is a step where the netowork's detail & credentials are given to the\r
+ * enrolling device.\r
+ */\r
+public class EasySetupService {\r
+\r
+ public static String TAG = EasySetupService.class.getName();\r
+\r
+ private static EasySetupService sInstance;\r
+\r
+ private final EasySetupStatus mCallback;\r
+\r
+ private ArrayList<EnrolleeDevice> mEnrolleeDeviceList;\r
+\r
+ private final ProvisioningCallback mProvisioningCallback;\r
+\r
+ private static Context mContext;\r
+\r
+ public EnrolleeDeviceFactory mDeviceFactory;\r
+\r
+ ProvisionEnrollee mProvisionEnrolleeInstance;\r
+\r
+ private EasySetupService(EasySetupStatus callback) {\r
+ mCallback = callback;\r
+ mProvisioningCallback = new ProvisioningCallbackImpl(mCallback);\r
+ mEnrolleeDeviceList = new ArrayList<EnrolleeDevice>();\r
+ mContext = null;\r
+ mDeviceFactory = null;\r
+ }\r
+\r
+ /**\r
+ * Gives a singleton instance of Easy setup service and initialize the service\r
+ *\r
+ * @param callback Application needs to provide this callback to receive the status of easy\r
+ * setup process.\r
+ */\r
+\r
+ public synchronized static EasySetupService getInstance(Context context, EasySetupStatus\r
+ callback) {\r
+ if (sInstance == null) {\r
+ sInstance = new EasySetupService(callback);\r
+ mContext = context;\r
+ }\r
+ return sInstance;\r
+ }\r
+\r
+ /**\r
+ * Reset the Easy setup Service\r
+ */\r
+\r
+ public void finish() {\r
+ //Native Api call to reset OIC stack\r
+ if(mProvisionEnrolleeInstance != null)\r
+ {\r
+ mProvisionEnrolleeInstance.stopEnrolleeProvisioning(0);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Starts Easy setup process for the enrolling device.\r
+ *\r
+ * @param enrolledevice Device to be enrolled in network\r
+ * @throws IOException Throws exception in case of any connection error.\r
+ */\r
+\r
+ public synchronized void startSetup(final EnrolleeDevice enrolledevice) throws IOException {\r
+\r
+ mEnrolleeDeviceList.add(enrolledevice);\r
+\r
+ // Starts the provisioning directly if the device is already on boarded on the network.\r
+ if (enrolledevice.onBoarded()) {\r
+ enrolledevice.startProvisioning(mProvisioningCallback);\r
+ return;\r
+ }\r
+\r
+ enrolledevice.startOnBoarding(new OnBoardingCallback() {\r
+\r
+ @Override\r
+ public void onFinished(OnBoardingConnection connection) {\r
+ if (connection.isConnected()) {\r
+ Log.i(TAG, "On boarding is successful ");\r
+ try {\r
+ Log.i(TAG, "waiting for 15 seconds to start provisioning");\r
+ Thread.sleep(15000);//Sleep for allowing thin device to start the services\r
+ } catch (InterruptedException e) {\r
+ e.printStackTrace();\r
+ }\r
+\r
+ // Start provisioning here\r
+ enrolledevice.setConnection(connection);\r
+ enrolledevice.startProvisioning(mProvisioningCallback);\r
+ } else {\r
+ enrolledevice.mState = EnrolleeState.DEVICE_PROVISIONING_FAILED_STATE;\r
+ mProvisioningCallback.onFinished(enrolledevice);\r
+ }\r
+\r
+ }\r
+\r
+ });\r
+\r
+ }\r
+\r
+ /**\r
+ * Stops on-going Easy setup process for enrolling device.\r
+ *\r
+ * @param enrolleedevice Device to be enrolled in network\r
+ */\r
+ public synchronized void stopSetup(EnrolleeDevice enrolleedevice) {\r
+ enrolleedevice.stopOnBoardingProcess();\r
+ mEnrolleeDeviceList.remove(enrolleedevice);\r
+\r
+ //Native Api call to stop on-going enrolling process for the enrolling device\r
+ EasySetupManager.getInstance().stopEnrolleeProvisioning(enrolleedevice.mOnBoardingConfig.getConnType().getValue());\r
+ }\r
+\r
+ public synchronized void getEnrolleeDevice(OnBoardingConfig connType) {\r
+ mDeviceFactory = EnrolleeDeviceFactory.newInstance(mContext);\r
+ }\r
+\r
+ class ProvisioningCallbackImpl extends ProvisioningCallback {\r
+\r
+ private final EasySetupStatus mCallback;\r
+\r
+ ProvisioningCallbackImpl(EasySetupStatus callback) {\r
+ mCallback = callback;\r
+ }\r
+\r
+ @Override\r
+ public void onFinished(EnrolleeDevice enrolledevice) {\r
+ //if(mEnrolleeDeviceList.contains(enrolledevice)) {\r
+ Log.i(TAG, "onFinished() is received " + enrolledevice.isSetupSuccessful());\r
+ mCallback.onFinished(enrolledevice);\r
+ // }\r
+ }\r
+\r
+ }\r
+\r
+\r
+}\r
--- /dev/null
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.core;
+
+/**
+ * This interface facilitates Application to get progress & result of Easy setup
+ * process Easy setup process.
+ */
+public interface EasySetupStatus {
+
+ /**
+ * This method is called back when easy setup process is finished. Easy
+ * setup process status can read from the APIs given in Enrollee class.This
+ * method is called on worker thread, UI operations to be executed on main /
+ * Ui Thread.
+ *
+ * @param enrolledevice Device to be enrolled in network through Easy setup process
+ */
+ public void onFinished(EnrolleeDevice enrolledevice);
+
+ /**
+ * This method is called back to give intermediate progress on the easy
+ * setup process This method is called on worker thread, UI operations to be
+ * executed on main / Ui Thread.
+ *
+ * @param state Gives state of the device changed during easy setup process
+ */
+ public void onProgress(EnrolleeState state);
+
+}
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p/>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p/>\r
+ * <p/>\r
+ * <p/>\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
+ * <p/>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p/>\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
+ * <p/>\r
+ * ****************************************************************\r
+ */\r
+\r
+package org.iotivity.service.easysetup.core;\r
+\r
+/**\r
+ * This is an abstract class represents the device being provisioned into the network. The\r
+ * device being enrolled or provisioned into the network is called Enrollee.\r
+ * Application has to extend this class and provide implementation of abstract methods according\r
+ * to the ON-BOARDING & PROVISION connectivity i.e. WiFi, BLE, BT etc. the device is having.\r
+ */\r
+\r
+public abstract class EnrolleeDevice {\r
+\r
+ protected EnrolleeState mState;\r
+ private EnrolleeSetupError mError;\r
+\r
+ protected OnBoardingConnection mConnection;\r
+ protected final ProvisioningConfig mProvConfig;\r
+ protected final OnBoardingConfig mOnBoardingConfig;\r
+\r
+ protected OnBoardingCallback mOnBoardingCallback;\r
+ protected ProvisioningCallback mProvisioningCallback;\r
+\r
+ /**\r
+ * @param onBoardingConfig Contains details about the connectivity to be established between\r
+ * the Enrollee device & Mediator device in order to perform\r
+ * on-boarding\r
+ * @param provConfig Contains details about the network to which Enrollee device is\r
+ * going to connect.\r
+ */\r
+ protected EnrolleeDevice(OnBoardingConfig onBoardingConfig, ProvisioningConfig provConfig) {\r
+ mProvConfig = provConfig;\r
+ mOnBoardingConfig = onBoardingConfig;\r
+ }\r
+\r
+ /**\r
+ * Application has to implement it according to the on boarding connectivity the device is\r
+ * having.\r
+ * This method will be called back during the easy setup process.\r
+ */\r
+ protected abstract void startOnBoardingProcess();\r
+\r
+ /**\r
+ * This method is called back during the easy setup process if Application cancels the setup.\r
+ * Easy setup service checks the state of device and calls this function accordingly.\r
+ * Application has to provide implementation for this method to cancel the on boarding step.\r
+ */\r
+ protected abstract void stopOnBoardingProcess();\r
+\r
+ /**\r
+ * Application has to implement it according to the type of the network device is going to\r
+ * connect or provisioned.\r
+ * This method will be called back once on-boarding of the device is successful.\r
+ *\r
+ * @param conn Contains detail about the network established between the Enrollee device &\r
+ * Mediator device. Its implementation vary according to the connectivity type.\r
+ */\r
+ protected abstract void startProvisioningProcess(OnBoardingConnection conn);\r
+\r
+ /**\r
+ * Once on boarding is successful concrete Enrollee class would call this method and set the\r
+ * Connection.\r
+ *\r
+ * @param conn Connectivity between Enrollee device & Mediator device.\r
+ */\r
+ public void setConnection(OnBoardingConnection conn) {\r
+ mConnection = conn;\r
+ }\r
+\r
+ public OnBoardingConnection getConnection() { return mConnection;}\r
+\r
+\r
+ /**\r
+ * This method is called back by Easy setup service if on boarding needs to be done.\r
+ *\r
+ * @param onBoardingCallback This is called back once the on boarding is completed.\r
+ */\r
+ void startOnBoarding(OnBoardingCallback onBoardingCallback) {\r
+ mOnBoardingCallback = onBoardingCallback;\r
+ startOnBoardingProcess();\r
+ }\r
+\r
+ /**\r
+ * This method is called back by Easy setup service once on boarding is successful\r
+ *\r
+ * @param provisioningCallback This is called back once the provisioning process is completed\r
+ */\r
+ void startProvisioning(ProvisioningCallback provisioningCallback) {\r
+ mProvisioningCallback = provisioningCallback;\r
+ startProvisioningProcess(mConnection);\r
+ }\r
+\r
+ /**\r
+ * This method is used to check easy setup status\r
+ *\r
+ * @return true if successful or false\r
+ */\r
+\r
+ public boolean isSetupSuccessful() {\r
+ return (mState == EnrolleeState.DEVICE_PROVISIONING_SUCCESS_STATE) ? true : false;\r
+ }\r
+\r
+ /**\r
+ * Returns error occured during easy setup process\r
+ *\r
+ * @return True EnrolleeSetupError object\r
+ */\r
+ public EnrolleeSetupError getError() {\r
+ return mError;\r
+ }\r
+\r
+ /**\r
+ * Gives the state of the device being enrolled during the easy setup process.\r
+ *\r
+ * @return Returns EnrolleeState object\r
+ */\r
+ public EnrolleeState getState() {\r
+ return mState;\r
+ }\r
+\r
+ /**\r
+ * This method is used to know if the device is on boarded or not\r
+ *\r
+ * @return True if on-boarded successfully or False\r
+ */\r
+\r
+ public boolean onBoarded() {\r
+ return (mState == EnrolleeState.DEVICE_PROVISIONING_STATE) ? true : false;\r
+ }\r
+\r
+\r
+\r
+}\r
--- /dev/null
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.core;
+
+/**
+ * This class defines constants for Errors comes during Easy setup process
+ */
+public enum EnrolleeSetupError {
+ /**
+ * Device setup successful
+ */
+ DEVICE_SETUP_SUCCESSFUL,
+ /**
+ * Device setup failed
+ */
+ DEVICE_SETUP_FAILED,
+}
--- /dev/null
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.core;
+
+/**
+ * It defines various states of the Enrollee device during easy setup process
+ */
+
+public enum EnrolleeState {
+
+ /**
+ * Default state of the device
+ */
+ DEVICE_INIT_STATE,
+
+ /**
+ * Device will move to this state after successful on-boarding of the device
+ */
+ DEVICE_ON_BOARDING_STATE,
+
+ /**
+ * Device will move to this state once the on boarding is done
+ */
+ DEVICE_PROVISIONING_STATE,
+
+ /**
+ * Easy setup process is successful.
+ */
+ DEVICE_PROVISIONING_SUCCESS_STATE,
+
+ /**
+ * Device is not able to provisioned.
+ * Easy setup process failed to enrolled the device in the network
+ */
+ DEVICE_PROVISIONING_FAILED_STATE,
+
+ /**
+ * This state is arbitrary one, any time device can come into this state
+ * Device will move to this state if the ownership transfer initiated by the Application
+ */
+ DEVICE_OWNERSHIP_TRANSFER_STATE,
+
+ /**
+ * This state is arbitrary one, any time device can come into this state
+ * Device will move to this state once the Application factory reset the device
+ */
+ DEVICE_FACTORY_RESET_STATE,
+
+}
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p/>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p/>\r
+ * <p/>\r
+ * <p/>\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
+ * <p/>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p/>\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
+ * <p/>\r
+ * ****************************************************************\r
+ */\r
+\r
+package org.iotivity.service.easysetup.core;\r
+\r
+public class IpOnBoardingConnection implements OnBoardingConnection {\r
+\r
+ private boolean mIsConnected;\r
+ private String mIp;\r
+ private String mHardwareAddress;\r
+ private String mDeviceName;\r
+\r
+ private boolean isReachable;\r
+\r
+ public void setHardwareAddress(String address) {\r
+ mHardwareAddress = address;\r
+ }\r
+\r
+ public String getHardwareAddress() {\r
+ return mHardwareAddress;\r
+ }\r
+\r
+ public void setDeviceName(String name) {\r
+ mDeviceName = name;\r
+ }\r
+\r
+ public String getDeviceName() {\r
+ return mDeviceName;\r
+ }\r
+\r
+ public void setConnectivity(boolean connected) {\r
+ mIsConnected = connected;\r
+ }\r
+\r
+ public void setIp(String ip) {\r
+ mIp = ip;\r
+ }\r
+\r
+ public String getIp() {\r
+ return mIp;\r
+ }\r
+\r
+ @Override\r
+ public String getDesc() {\r
+ return "Description";\r
+ }\r
+\r
+ @Override\r
+ public boolean isConnected() {\r
+ return mIsConnected;\r
+ }\r
+\r
+ @Override\r
+ public Object getConnection() {\r
+ return this;\r
+ }\r
+\r
+}\r
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p/>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p/>\r
+ * <p/>\r
+ * <p/>\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
+ * <p/>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p/>\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
+ * <p/>\r
+ * ****************************************************************\r
+ */\r
+\r
+package org.iotivity.service.easysetup.core;\r
+\r
+public abstract class OnBoardingCallback {\r
+ public abstract void onFinished(OnBoardingConnection connection);\r
+}\r
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p/>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p/>\r
+ * <p/>\r
+ * <p/>\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
+ * <p/>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p/>\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
+ * <p/>\r
+ * ****************************************************************\r
+ */\r
+\r
+package org.iotivity.service.easysetup.core;\r
+\r
+/**\r
+ * It contains configuration details about the connectivity type between the Enrollee device &\r
+ * Mediator device in order to perform on-boarding.\r
+ */\r
+\r
+public interface OnBoardingConfig {\r
+\r
+ /**\r
+ * It provides constants for connectivity types used for on-boarding Enrollee device\r
+ */\r
+ public static enum ConnType {\r
+ // Note : Enum Ids should matched with Native Ids\r
+ WiFi(0),\r
+ BLE(1);\r
+\r
+ private int mConnType;\r
+\r
+ ConnType(int connType) {\r
+ mConnType = connType;\r
+ }\r
+\r
+ public int getValue() {\r
+ return mConnType;\r
+ }\r
+\r
+ }\r
+\r
+ /**\r
+ * Gives configuration object specific to the on-boarding connectivity of the enrolling device.\r
+ *\r
+ * @return instance object of configuration according to connectivity type\r
+ */\r
+ public Object getConfig();\r
+\r
+ /**\r
+ * Gives connectivity type of on-boarding device\r
+ *\r
+ * @return on-boarding connectivity type\r
+ */\r
+ public ConnType getConnType();\r
+\r
+\r
+}\r
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p/>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p/>\r
+ * <p/>\r
+ * <p/>\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
+ * <p/>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p/>\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
+ * <p/>\r
+ * ****************************************************************\r
+ */\r
+package org.iotivity.service.easysetup.core;\r
+\r
+public interface OnBoardingConnection {\r
+\r
+\r
+ // Get the implementation of the Connection\r
+ public Object getConnection();\r
+\r
+ // Any general description on the connectivity.\r
+ public String getDesc();\r
+\r
+ public boolean isConnected();\r
+\r
+}\r
--- /dev/null
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.core;
+
+public abstract class ProvisioningCallback {
+ public abstract void onFinished(EnrolleeDevice enrolledevice);
+}
--- /dev/null
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.core;
+/**
+ * It contains configuration details about the the target network where Enrollee device is
+ * going to be enrolled.
+ */
+public interface ProvisioningConfig {
+
+ /**
+ * It provides constants for connectivity types of target network
+ */
+ public static enum ConnType {
+ WiFi,
+ BT
+ }
+
+ /**
+ * Gives the instance of the configuration object created according to the connectivity
+ * type of target network.
+ *
+ * @return instance object of configuration according to connectivity type of target network
+ */
+ Object getConfig();
+
+
+ /**
+ * Gives connectivity type of target network
+ *
+ * @return Connectivity type of target network
+ */
+ ConnType getConnType();
+
+}
--- /dev/null
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.impl;
+
+import org.iotivity.service.easysetup.core.EnrolleeDevice;
+import org.iotivity.service.easysetup.core.OnBoardingConfig;
+import org.iotivity.service.easysetup.core.ProvisioningConfig;
+
+import android.content.Context;
+
+/**
+ * This a factory class provides the native implementation of the various Enrollee devices.
+ * Application can make use of Enrollee factory if it does not want to create its own Enrollee devices.
+ */
+public class EnrolleeDeviceFactory {
+
+ Context mContext;
+
+ /**
+ * This method create & returns instance of EnrolleeDeviceFactory
+ *
+ * @param context This is Android Application context
+ */
+ public static EnrolleeDeviceFactory newInstance(Context context) {
+ return new EnrolleeDeviceFactory(context);
+ }
+
+ private EnrolleeDeviceFactory(Context context) {
+ mContext = context;
+ }
+
+ /**
+ * This method create & returns instance of Enrollee device of supported configuration
+ *
+ * @param onboardingConfig Contains details about the connectivity to be established between the Enrollee device & Mediator device in order to perform on-boarding
+ * @param provConfig Contains details about the network to which Enrollee device is going to connect.
+ * @return Instance of the Enrollee device created natively.
+ */
+
+ public EnrolleeDevice newEnrolleeDevice(OnBoardingConfig onboardingConfig, ProvisioningConfig provConfig) {
+
+ EnrolleeDevice enrolleeDevice;
+
+ if (onboardingConfig.getConnType() == OnBoardingConfig.ConnType.WiFi) {
+ enrolleeDevice = new EnrolleeDeviceWiFiOnboarding(mContext, onboardingConfig, provConfig);
+ } else {
+ throw new IllegalArgumentException("OnBoarding configuration is not supported");
+ }
+
+ return enrolleeDevice;
+ }
+
+}
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p>\r
+ * <p>\r
+ * <p>\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
+ * <p>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p>\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
+ * <p>\r
+ * ****************************************************************\r
+ */\r
+\r
+package org.iotivity.service.easysetup.impl;\r
+\r
+import java.util.Timer;\r
+import java.util.TimerTask;\r
+\r
+import org.iotivity.service.easysetup.core.OnBoardingConnection;\r
+import org.iotivity.service.easysetup.core.EnrolleeDevice;\r
+import org.iotivity.service.easysetup.core.EnrolleeState;\r
+import org.iotivity.service.easysetup.core.IpOnBoardingConnection;\r
+import org.iotivity.service.easysetup.core.OnBoardingConfig;\r
+import org.iotivity.service.easysetup.core.ProvisioningConfig;\r
+import org.iotivity.service.easysetup.mediator.EasySetupCallbackHandler;\r
+import org.iotivity.service.easysetup.mediator.EasySetupManager;\r
+import org.iotivity.service.easysetup.mediator.EnrolleeInfo;\r
+import org.iotivity.service.easysetup.mediator.IOnBoardingStatus;\r
+import org.iotivity.service.easysetup.mediator.IProvisioningListener;\r
+import org.iotivity.service.easysetup.mediator.ProvisionEnrollee;\r
+import org.iotivity.service.easysetup.mediator.ip.WiFiSoftAPManager;\r
+\r
+import android.content.Context;\r
+import android.net.wifi.WifiConfiguration;\r
+import android.util.Log;\r
+\r
+/**\r
+ * This is a ready to use class for Enrollee device having Soft AP as on-boarding connectivity.\r
+ */\r
+public class EnrolleeDeviceWiFiOnboarding extends EnrolleeDevice {\r
+\r
+ public static final String TAG = EnrolleeDeviceWiFiOnboarding.class.getName();\r
+\r
+ final Context mContext;\r
+ final WiFiSoftAPManager mWifiSoftAPManager;\r
+ EnrolleeInfo connectedDevice;\r
+ private EasySetupManager easySetupManagerNativeInstance;\r
+ ProvisionEnrollee provisionEnrolleInstance;\r
+ Timer myTimer;\r
+\r
+ IOnBoardingStatus deviceScanListener = new IOnBoardingStatus() {\r
+\r
+ @Override\r
+ public void deviceOnBoardingStatus(EnrolleeInfo enrolleStatus) {\r
+ Log.d("ESSoftAPOnBoarding", "Entered");\r
+ if (mState == EnrolleeState.DEVICE_ON_BOARDING_STATE) {\r
+ Log.d("ESSoftAPOnBoarding", "Device in OnBoarding State");\r
+ if (enrolleStatus != null && enrolleStatus.getIpAddr() != null) {\r
+ String finalResult = "Easy Connect : ";\r
+\r
+ if (enrolleStatus.isReachable()) {\r
+ finalResult = "Device OnBoarded" + "["\r
+ + enrolleStatus.getIpAddr() + "]";\r
+\r
+ connectedDevice = enrolleStatus;\r
+ IpOnBoardingConnection conn = new IpOnBoardingConnection();\r
+\r
+ conn.setConnectivity(true);\r
+ conn.setIp(connectedDevice.getIpAddr());\r
+ conn.setHardwareAddress(enrolleStatus.getHWAddr());\r
+ conn.setDeviceName(enrolleStatus.getDevice());\r
+\r
+ Log.d("ESSoftAPOnBoarding", "Entered");\r
+ mOnBoardingCallback.onFinished(conn);\r
+ return;\r
+\r
+ }\r
+ }\r
+\r
+ IpOnBoardingConnection conn = new IpOnBoardingConnection();\r
+ conn.setConnectivity(false);\r
+ mOnBoardingCallback.onFinished(conn);\r
+ }\r
+ else\r
+ {\r
+ Log.e("ESSoftAPOnBoarding", "Device NOT in OnBoarding State. Ignoring the event");\r
+ }\r
+ }\r
+ };\r
+\r
+\r
+ protected EnrolleeDeviceWiFiOnboarding(Context context, OnBoardingConfig onBoardingConfig,\r
+ ProvisioningConfig provConfig) {\r
+ super(onBoardingConfig, provConfig);\r
+ mContext = context;\r
+ mWifiSoftAPManager = new WiFiSoftAPManager(mContext);\r
+ }\r
+\r
+ @Override\r
+ protected void startOnBoardingProcess() {\r
+ Log.i(TAG, "Starting on boarding process");\r
+\r
+ //1. Create Soft AP\r
+ boolean status = mWifiSoftAPManager.setWifiApEnabled((WifiConfiguration)\r
+ mOnBoardingConfig.getConfig(), true);\r
+\r
+ mState = EnrolleeState.DEVICE_ON_BOARDING_STATE;\r
+\r
+ Log.i(TAG, "Soft AP is created with status " + status);\r
+\r
+ myTimer = new Timer();\r
+ myTimer.schedule(new TimerTask() {\r
+ @Override\r
+ public void run() {\r
+ // Below function to be called after 5 seconds\r
+ mWifiSoftAPManager.getClientList(deviceScanListener, 300);\r
+ }\r
+\r
+ }, 0, 5000);\r
+ }\r
+\r
+ protected void stopOnBoardingProcess() {\r
+ Log.i(TAG, "Stopping on boarding process");\r
+ myTimer.cancel();\r
+ boolean status = mWifiSoftAPManager.setWifiApEnabled(null, false);\r
+ Log.i(TAG, "Soft AP is disabled with status " + status);\r
+ }\r
+\r
+ @Override\r
+ protected void startProvisioningProcess(OnBoardingConnection conn) {\r
+ mState = EnrolleeState.DEVICE_PROVISIONING_STATE;\r
+\r
+ if (mProvConfig.getConnType() == ProvisioningConfig.ConnType.WiFi) {\r
+\r
+ provisionEnrolleInstance = new ProvisionEnrollee(mContext);\r
+ provisionEnrolleInstance.registerProvisioningHandler(new IProvisioningListener() {\r
+ @Override\r
+ public void onFinishProvisioning(int statuscode) {\r
+\r
+ Log.i(TAG, "Provisioning is finished with status code " + statuscode);\r
+ mState = (statuscode == 0) ? EnrolleeState.DEVICE_PROVISIONING_SUCCESS_STATE\r
+ : EnrolleeState.DEVICE_PROVISIONING_FAILED_STATE;\r
+ stopOnBoardingProcess();\r
+ mProvisioningCallback.onFinished(EnrolleeDeviceWiFiOnboarding.this);\r
+ }\r
+ });\r
+\r
+ IpOnBoardingConnection connection = (IpOnBoardingConnection) conn;\r
+ WiFiProvConfig wifiProvConfig = (WiFiProvConfig) mProvConfig;\r
+\r
+ easySetupManagerNativeInstance = EasySetupManager.getInstance();\r
+ easySetupManagerNativeInstance.initEasySetup();\r
+\r
+ // Native Api call to start provisioning of the enrolling device\r
+ easySetupManagerNativeInstance.provisionEnrollee(connection.getIp(), wifiProvConfig\r
+ .getSsId(), wifiProvConfig.getPassword(), mOnBoardingConfig.getConnType()\r
+ .getValue());\r
+ }\r
+ }\r
+}\r
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p/>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p/>\r
+ * <p/>\r
+ * <p/>\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
+ * <p/>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p/>\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
+ * <p/>\r
+ * ****************************************************************\r
+ */\r
+\r
+package org.iotivity.service.easysetup.impl;\r
+\r
+import org.iotivity.service.easysetup.core.IpOnBoardingConnection;\r
+import org.iotivity.service.easysetup.core.OnBoardingConfig;\r
+\r
+import android.net.wifi.WifiConfiguration;\r
+\r
+/**\r
+ * This class contains on boarding configuration information for Soft AP on boarding connectivity.\r
+ * It implements OnBoardingConfig interface & provide implementation for WiFi Soft AP connectivity.\r
+ */\r
+\r
+public class WiFiOnBoardingConfig implements OnBoardingConfig {\r
+\r
+ private final WifiConfiguration config = new WifiConfiguration();\r
+ private final ConnType mConnType = OnBoardingConfig.ConnType.WiFi;\r
+ private IpOnBoardingConnection mConnection;\r
+\r
+ @Override\r
+ public Object getConfig() {\r
+ return config;\r
+ }\r
+\r
+ public void setSSId(String ssid) {\r
+ config.SSID = ssid;\r
+ }\r
+\r
+ public void setSharedKey(String sharedKey) {\r
+ config.preSharedKey = sharedKey;\r
+ }\r
+\r
+ public void setAuthAlgo(int aurthAlgo) {\r
+ config.allowedAuthAlgorithms.set(aurthAlgo);\r
+ }\r
+\r
+ public void setKms(int kms) {\r
+ config.allowedKeyManagement.set(kms);\r
+ }\r
+\r
+ @Override\r
+ public ConnType getConnType() {\r
+ return mConnType;\r
+ }\r
+}\r
--- /dev/null
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.impl;
+
+import org.iotivity.service.easysetup.core.ProvisioningConfig;
+import org.iotivity.service.easysetup.mediator.EnrolleeInfo;
+
+import android.net.wifi.WifiConfiguration;
+
+/**
+ * This class contains on provisioning configuration information for for target network.
+ * It implements ProvisioningConfig interface and provide configuration object specific to WiFi target network
+ */
+public class WiFiProvConfig implements ProvisioningConfig {
+
+ private final ConnType mConnType = ProvisioningConfig.ConnType.WiFi;
+
+ private final String mSsId;
+ private final String mPassword;
+
+ public WiFiProvConfig(String ssid, String pass) {
+ mSsId = ssid;
+ mPassword = pass;
+ }
+
+ @Override
+ public Object getConfig() {
+ return this;
+ }
+
+ @Override
+ public ConnType getConnType() {
+ return mConnType;
+ }
+
+ public String getSsId() {
+ return mSsId;
+ }
+
+ public String getPassword() {
+ return mPassword;
+ }
+
+}
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p>\r
+ * <p>\r
+ * <p>\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
+ * <p>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p>\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
+ * <p>\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
+ Log.d(TAG,\r
+ "onFinishProvisioning() inside Android Java application. statuscode - "\r
+ + 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
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p>\r
+ * <p>\r
+ * <p>\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
+ * <p>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p>\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
+ * <p>\r
+ * ****************************************************************\r
+ */\r
+package org.iotivity.service.easysetup.mediator;\r
+\r
+import android.content.Context;\r
+\r
+import org.iotivity.ca.CaInterface;\r
+\r
+public class EasySetupManager {\r
+ private native void InitEasySetup();\r
+\r
+ private native void TerminateEasySetup();\r
+\r
+ // TODO : "OcConnectivityType connectivityType" has to be passed as the\r
+ // second parameter for PerformEasySetup\r
+ // instead of integer\r
+ private native void ProvisionEnrollee(String ipAddress, String netSSID,\r
+ String netPWD, int connectivityType);\r
+\r
+ private native void StopEnrolleeProvisioning(int connectivityType);\r
+\r
+ public static native void initialize(Context context);\r
+\r
+ private static EasySetupManager easySetupManagerInterfaceObj = null;\r
+ private Context appContext = null;\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
+ 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 setApplicationContext(Context context) {\r
+ appContext = context;\r
+ }\r
+\r
+ public void initEasySetup() {\r
+ CaInterface.initialize(appContext);\r
+ InitEasySetup();\r
+ }\r
+\r
+ public void terminateEasySetup() {\r
+ TerminateEasySetup();\r
+ }\r
+\r
+ public void provisionEnrollee(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
--- /dev/null
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+public class EnrolleeInfo {
+
+ private String IpAddr;
+ private String HWAddr;
+ private String Device;
+ private boolean isReachable;
+
+ public String getIpAddr() {
+ return IpAddr;
+ }
+
+ public void setIpAddr(String ipAddr) {
+ IpAddr = ipAddr;
+ }
+
+ public String getHWAddr() {
+ return HWAddr;
+ }
+
+ public void setHWAddr(String hWAddr) {
+ HWAddr = hWAddr;
+ }
+
+ public String getDevice() {
+ return Device;
+ }
+
+ public void setDevice(String device) {
+ Device = device;
+ }
+
+ public boolean isReachable() {
+ return isReachable;
+ }
+
+ public void setReachable(boolean isReachable) {
+ this.isReachable = isReachable;
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+package org.iotivity.service.easysetup.mediator;
+
+public class EnrolleeOnBoardingInfo {
+
+ private String IpAddr;
+ private String HWAddr;
+ private String Device;
+ private boolean isReachable;
+ private boolean isAdditionNotified;
+ private boolean isRemovalNotified;
+
+ public EnrolleeOnBoardingInfo(String ipAddr, String hWAddr, String device,
+ boolean isReachable, boolean isRemovalNotified,
+ boolean isAdditionNotified) {
+ this.IpAddr = ipAddr;
+ this.HWAddr = hWAddr;
+ this.Device = device;
+ this.isReachable = isReachable;
+ this.isRemovalNotified = isRemovalNotified;
+ this.isAdditionNotified = isAdditionNotified;
+ }
+
+ public String getIpAddr() {
+ return IpAddr;
+ }
+
+ public void setIpAddr(String ipAddr) {
+ IpAddr = ipAddr;
+ }
+
+ public String getHWAddr() {
+ return HWAddr;
+ }
+
+ public void setHWAddr(String hWAddr) {
+ HWAddr = hWAddr;
+ }
+
+ public String getDevice() {
+ return Device;
+ }
+
+ public void setDevice(String device) {
+ Device = device;
+ }
+
+ 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
--- /dev/null
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+package org.iotivity.service.easysetup.mediator;
+
+import java.util.ArrayList;
+
+import org.iotivity.service.easysetup.mediator.EnrolleeInfo;
+
+public interface IOnBoardingStatus {
+
+ /**
+ * Interface called when the scan method finishes. Network operations should
+ * not execute on UI thread
+ *
+ * @param clients of {@link EnrolleeInfo}
+ */
+
+ public void deviceOnBoardingStatus(EnrolleeInfo clients);
+
+}
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p>\r
+ * <p>\r
+ * <p>\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
+ * <p>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p>\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
+ * <p>\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
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p>\r
+ * <p>\r
+ * <p>\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
+ * <p>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p>\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
+ * <p>\r
+ * ****************************************************************\r
+ */\r
+package org.iotivity.service.easysetup.mediator;\r
+\r
+import android.content.Context;\r
+import android.net.wifi.WifiConfiguration;\r
+\r
+\r
+import org.iotivity.service.easysetup.mediator.ip.WiFiSoftAPManager;\r
+\r
+public class OnBoardEnrollee {\r
+ WiFiSoftAPManager wifiSoftAPManager;\r
+ IOnBoardingStatus deviceScanListener;\r
+\r
+ /**\r
+ * Constructor for OnBoardEnrollee. Constructs a new OnBoardEnrollee.\r
+ */\r
+ public OnBoardEnrollee(Context context) {\r
+ wifiSoftAPManager = new WiFiSoftAPManager(context);\r
+ }\r
+\r
+ public void registerOnBoardingStatusHandler(\r
+ IOnBoardingStatus deviceScanListener) {\r
+ this.deviceScanListener = deviceScanListener;\r
+ }\r
+\r
+ public void startDeviceScan() {\r
+ wifiSoftAPManager.getClientList(this.deviceScanListener, 300);\r
+ }\r
+\r
+ public void enableWiFiAP(WifiConfiguration netConfig, boolean enabled) {\r
+ wifiSoftAPManager.setWifiApEnabled(netConfig, true);\r
+ }\r
+\r
+ public void disableWiFiAP() {\r
+ wifiSoftAPManager.setWifiApEnabled(null, false);\r
+ }\r
+}\r
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p>\r
+ * <p>\r
+ * <p>\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
+ * <p>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p>\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
+ * <p>\r
+ * ****************************************************************\r
+ */\r
+\r
+package org.iotivity.service.easysetup.mediator;\r
+\r
+import android.content.Context;\r
+import android.util.Log;\r
+\r
+public class ProvisionEnrollee {\r
+ private static final String TAG = "ProvisionEnrollee";\r
+ private Context appContext = null;\r
+ private EasySetupManager easySetupManagerNativeInstance = null;\r
+ private IProvisioningListener provisioningListener;\r
+\r
+ /**\r
+ * Constructor for ProvisionEnrollee. Constructs a new ProvisionEnrollee.\r
+ */\r
+ public ProvisionEnrollee(Context context) {\r
+ appContext = context;\r
+ easySetupManagerNativeInstance = EasySetupManager.getInstance();\r
+ easySetupManagerNativeInstance.initEasySetup();\r
+ }\r
+\r
+ @Override\r
+ protected void finalize() throws Throwable {\r
+ super.finalize();\r
+ easySetupManagerNativeInstance.terminateEasySetup();\r
+ }\r
+\r
+ public void provisionEnrollee(String ipAddress, String netSSID,\r
+ String netPWD, int connectivityType) {\r
+ Log.i(TAG, "JNI start provisioning is called ");\r
+ easySetupManagerNativeInstance.provisionEnrollee(ipAddress, netSSID,\r
+ netPWD, connectivityType);\r
+ }\r
+\r
+ public void stopEnrolleeProvisioning(int connectivityType) {\r
+ Log.i(TAG, "JNI stop provisioning is called ");\r
+ easySetupManagerNativeInstance\r
+ .stopEnrolleeProvisioning(connectivityType);\r
+ }\r
+\r
+ public void ProvisioningStatusCallBack(int statuscode) {\r
+ Log.d(TAG,\r
+ "JNI 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
+ Log.i(TAG, "JNI Callback is registered for getting provisioning status");\r
+ }\r
+}\r
--- /dev/null
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+
+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.service.easysetup.mediator.EnrolleeInfo;
+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 static final String TAG = WiFiSoftAPManager.class.getName();
+ 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 EnrolleeInfo result = new EnrolleeInfo();
+ boolean deviceAddedToList = false;
+
+ if (appNotification.size() > 0) {
+ for (EnrolleeOnBoardingInfo ipDeviceOnBoardingNotification : appNotification) {
+ EnrolleeOnBoardingInfo ipEnrolleeDevice = (EnrolleeOnBoardingInfo) ipDeviceOnBoardingNotification;
+ 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(ipAddr, macAddr, "", isReachable,
+ false, true));
+ } else {
+ appNotification
+ .add(new EnrolleeOnBoardingInfo(ipAddr, macAddr, "", isReachable,
+ true, false));
+ }
+
+ NotifyApplication(result);
+ return true;
+ }
+ }
+ }
+ if (!deviceAddedToList) {
+ if (isReachable) {
+ appNotification
+ .add(new EnrolleeOnBoardingInfo(ipAddr, macAddr, "", isReachable, false,
+ true));
+ } else {
+ appNotification
+ .add(new EnrolleeOnBoardingInfo(ipAddr, macAddr, "", isReachable, true,
+ false));
+ }
+
+ result.setIpAddr(ipAddr);
+ result.setHWAddr(macAddr);
+ result.setReachable(isReachable);
+
+ NotifyApplication(result);
+ return true;
+ }
+ } else {
+ if (isReachable) {
+ appNotification
+ .add(new EnrolleeOnBoardingInfo(ipAddr, macAddr, "", isReachable, false,
+ true));
+ } else {
+ appNotification
+ .add(new EnrolleeOnBoardingInfo(ipAddr, macAddr, "", 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 {
+ appNotification.clear();
+ // 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() {
+ Log.i(TAG, "Scanning enrolling device in the network" );
+
+ 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 EnrolleeInfo 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);
+*/
+ Log.i(TAG, "Scanning is finished with result, IP : " + result.getIpAddr() + "Notifying to Application");
+ finishListener.deviceOnBoardingStatus(result);
+
+ }
+}
--- /dev/null
+<resources>\r
+\r
+ <string name="app_name">EasySetupCore</string>\r
+\r
+</resources>\r
--- /dev/null
+<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
--- /dev/null
+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/c_common \
+ $(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
--- /dev/null
+APP_STL := gnustl_shared
+APP_PLATFORM = android-21
+NDK_TOOLCHAIN_VERSION := 4.8
+
--- /dev/null
+//******************************************************************\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)jConnectivityType;\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
--- /dev/null
+/* 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
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file jni_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_
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file jni_getter.h
+ *
+ * @brief This file contains the JGetter class declarations and its functions required
+ * for getting and setting basic data types in C++ and Java
+ */
+
+#ifndef __JNI_GETTER_H_
+#define __JNI_GETTER_H_
+
+#include <string>
+#include <jni.h>
+
+/**
+ * @class JGetter
+ * @brief This class provide utility for get/set basic data types in C++ and Java
+ *
+ */
+class JGetter {
+public:
+ /**
+ * This function is called to get String field from the C++ object
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject from which string field is expected
+ * @param fieldName
+ * Name of the field to be extracted from JObject
+ * @param value
+ * reference to string value mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool getJStringField(JNIEnv *env, jobject &object,
+ const char *fieldName, std::string &value);
+
+ /**
+ * This function is called to get Boolean field from the C++ object
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject from which boolean field is expected
+ * @param fieldName
+ * Name of the field to be extracted from JObject
+ * @param value
+ * reference to boolean value mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool getJBoolField(JNIEnv *env, jobject &object,
+ const char *fieldName, bool &value);
+
+ /**
+ * This function is called to get Integer field from the C++ object
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject from which integer field is expected
+ * @param fieldName
+ * Name of the field to be extracted from JObject
+ * @param value
+ * reference to integer value mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool getJIntField(JNIEnv *env, jobject &object,
+ const char *fieldName, int &value);
+
+ /**
+ * This function is called to get Object reference from the C++ object
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject from which Object reference is expected
+ * @param fieldName
+ * Name of the field to be extracted from JObject
+ * @param fieldType
+ * Type of the field to be extracted from JObject
+ * @param value
+ * reference to Object reference mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool getJObjectField(JNIEnv *env, jobject &object,
+ const char *fieldName, const char *fieldType, jobject &value);
+};
+#endif //__JNI_GETTER_H_
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file jni_object.h
+ *
+ * @brief This file contains the JObject class declarations and its functions required
+ * for getting and setting basic data types in C++ and Java
+ */
+
+#ifndef __JNI_OBJECT_H_
+#define __JNI_OBJECT_H_
+
+#include <jni.h>
+#include "JniOcResource.h"
+
+/**
+ * @class JObject
+ * @brief This class provides a set of functions for JNI object.
+ *
+ */
+class JObject {
+public:
+ /**
+ * @brief constructor
+ */
+ JObject(JNIEnv *env);
+
+ /**
+ * @brief constructor
+ */
+ JObject(JNIEnv *env, jobject obj);
+
+ /**
+ * @brief constructor
+ */
+ JObject(JNIEnv *env, const char *classPath);
+
+ /**
+ * @brief destructor
+ *
+ */
+ virtual ~JObject();
+
+ /**
+ * Function to get the jobject.
+ *
+ * @return jobject, returns a new JNI object or NULL otherwise.
+ *
+ */
+ virtual jobject getObject() const;
+
+ /**
+ * Function to detach the jobject.
+ *
+ * @return void
+ *
+ */
+ void detachObject();
+
+protected:
+ /**
+ * JNI Environment Pointer
+ */
+ JNIEnv *m_pEnv;
+ /**
+ * Java Object
+ */
+ jobject m_pObject;
+ /**
+ * Java Class
+ */
+ jclass m_pClazz;
+ /**
+ * Boolean variable to check if an object is new
+ */
+ bool m_fIsNewObject;
+};
+#endif //__JNI_OBJECT_H_
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file jni_setter.h
+ *
+ * @brief This file contains the JSetter class declarations and and its functions required
+ * to set data types in C++ object from Java object
+ */
+
+#ifndef __JNI_SETTER_H_
+#define __JNI_SETTER_H_
+
+#include <jni.h>
+
+/**
+ * @class JSetter
+ * @brief This class provide utility to set data types in C++ object from Java object
+ *
+ */
+class JSetter {
+public:
+
+ /**
+ * This function is called to set Integer field in to C++ object.
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject to which integer field will be set.
+ * @param fieldName
+ * Name of the field to be set in JObject
+ * @param value
+ * integer value mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool setJIntField(JNIEnv *env, jobject &object,
+ const char *fieldName, int value);
+
+ /**
+ * This function is called to set Long field in to C++ object.
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject to which Long field will be set.
+ * @param fieldName
+ * Name of the field to be set in JObject
+ * @param value
+ * Long value mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool setJLongField(JNIEnv *env, jobject &object,
+ const char *fieldName, jlong value);
+
+ /**
+ * This function is called to Set Boolean field to C++ object
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject to which boolean field has to be set
+ * @param fieldName
+ * Name of the field to be set in JObject
+ * @param value
+ * boolean value mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool setJBoolField(JNIEnv *env, jobject &object,
+ const char *fieldName, bool value);
+ /**
+ * This function is called to Set String field from the C++ object
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject in which string value has to be set
+ * @param fieldName
+ * Name of the field to be set in JObject
+ * @param value
+ * string value mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool setJStringField(JNIEnv *env, jobject &object,
+ const char *fieldName, const char *value);
+
+ /**
+ * This function is called to set Object reference in C++ object.
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject to which Object reference is to be set.
+ * @param fieldName
+ * Name of the field to be set in JObject
+ * @param fieldType
+ * Type of the field to be set in JObject
+ * @param value
+ * value of Object mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool setJObjectField(JNIEnv *env, jobject &object,
+ const char *fieldName, const char *fieldType, const jobject value);
+};
+
+#endif //__JNI_SETTER_H_
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file jni_string.h
+ *
+ * @brief This file contains the declaration of JString class and its members related to JString.
+ *
+ */
+
+#ifndef __JNI_STRING_H_
+#define __JNI_STRING_H_
+
+#include <string>
+
+#include "jni_object.h"
+
+/**
+ * @class JString
+ * @brief This class inherits JObject class and provides a set of functions for JNI String.
+ *
+ */
+class JString: public JObject {
+public:
+ /**
+ * @brief constructor
+ */
+ JString(JNIEnv *env, jstring value);
+ /**
+ * @brief constructor
+ */
+ JString(JNIEnv *env, const char *value);
+ /**
+ * @brief constructor
+ */
+ JString(JNIEnv *env, const std::string &value);
+ /**
+ * @brief destructor
+ */
+ ~JString();
+
+ /**
+ * Function to get the string value and set it.
+ *
+ * @param value - String value to set to a private member variable.
+ *
+ * @return bool - true on success
+ *
+ */
+ bool getValue(std::string &value);
+
+ /**
+ * Function to get the private string value.
+ *
+ * @return C String value.
+ *
+ */
+ const char *c_str();
+
+private:
+ std::string m_cstr;
+};
+#endif //__JNI_STRING_H_
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#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
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#include "jni_getter.h"
+
+#include <string>
+
+#include "JniOcResource.h"
+
+#define LOG_TAG "TM_JGetter"
+
+bool JGetter::getJStringField(JNIEnv *env, jobject &object,
+ const char *fieldName, std::string &value) {
+ if (NULL == env || NULL == object || NULL == fieldName) {
+ LOGE("getJStringField invalid parameters");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass(object);
+ if (NULL == clazz) {
+ LOGE("GetObjectClass failed [%s]", fieldName);
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID(clazz, fieldName, "Ljava/lang/String;");
+ if (0 == fieldID) {
+ LOGE("GetFieldID failed [%s]", fieldName);
+ env->DeleteLocalRef(clazz);
+ return false;
+ }
+
+ jstring jValue = (jstring) env->GetObjectField(object, fieldID);
+ if (NULL == jValue) {
+ LOGE("GetObjectField failed [%s]", fieldName);
+ env->DeleteLocalRef(clazz);
+ return false;
+ }
+
+ const char *cstr = env->GetStringUTFChars(jValue, 0);
+ if (cstr == NULL) {
+ LOGE("GetStringUTFChars failed");
+ } else {
+ value = cstr;
+ env->ReleaseStringUTFChars(jValue, cstr);
+ }
+
+ env->DeleteLocalRef(clazz);
+ env->DeleteLocalRef(jValue);
+
+ return true;
+}
+
+bool JGetter::getJBoolField(JNIEnv *env, jobject &object, const char *fieldName,
+ bool &value) {
+ if (NULL == env || NULL == object || NULL == fieldName) {
+ LOGE("getJBoolField invalid parameters");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass(object);
+ if (NULL == clazz) {
+ LOGE("GetObjectClass failed");
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID(clazz, fieldName, "Z");
+ if (0 == fieldID) {
+ LOGE("GetFieldID failed [%s]", fieldName);
+ env->DeleteLocalRef(clazz);
+ return false;
+ }
+
+ value = env->GetBooleanField(object, fieldID);
+
+ env->DeleteLocalRef(clazz);
+
+ return true;
+}
+
+bool JGetter::getJIntField(JNIEnv *env, jobject &object, const char *fieldName,
+ int &value) {
+ if (NULL == env || NULL == object || NULL == fieldName) {
+ LOGE("getJIntField invalid parameters");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass(object);
+ if (NULL == clazz) {
+ LOGE("GetObjectClass failed");
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID(clazz, fieldName, "I");
+ if (0 == fieldID) {
+ LOGE("GetFieldID failed [%s]", fieldName);
+ env->DeleteLocalRef(clazz);
+ return false;
+ }
+
+ value = env->GetIntField(object, fieldID);
+
+ env->DeleteLocalRef(clazz);
+
+ return true;
+}
+
+bool JGetter::getJObjectField(JNIEnv *env, jobject &object,
+ const char *fieldName, const char *fieldType, jobject &value) {
+ if (NULL == env || NULL == object || NULL == fieldName) {
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass(object);
+ if (NULL == clazz) {
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID(clazz, fieldName, fieldType);
+ if (0 == fieldID) {
+ LOGE("GetFieldID failed [%s][%s]", fieldName, fieldType);
+ return false;
+ }
+
+ value = env->GetObjectField(object, fieldID);
+ if (NULL == value) {
+ return false;
+ }
+
+ env->DeleteLocalRef(clazz);
+
+ return true;
+}
--- /dev/null
+#include "jni_object.h"
+
+//#define NULL 0
+#define LOG_TAG "TM_JObject"
+
+JObject::JObject(JNIEnv *env) :
+ m_pEnv(env), m_pObject(NULL), m_pClazz(NULL), m_fIsNewObject(true) {
+}
+
+JObject::JObject(JNIEnv *env, jobject obj) :
+ m_pEnv(NULL), m_pObject(NULL), m_pClazz(NULL), m_fIsNewObject(false) {
+ if (NULL == env || NULL == obj) {
+ return;
+ }
+
+ m_pEnv = env;
+ m_pObject = obj;
+ m_pClazz = m_pEnv->GetObjectClass(obj);
+}
+
+JObject::JObject(JNIEnv *env, const char *classPath) :
+ m_pEnv(NULL), m_pObject(NULL), m_pClazz(NULL), m_fIsNewObject(true) {
+ if (NULL == env || NULL == classPath) {
+ LOGI("JObject Invalid parameters");
+ return;
+ }
+
+ m_pEnv = env;
+ //m_pClazz = GetJClass( classPath );
+
+ if (NULL == m_pClazz) {
+ LOGE("GetJClass failed [%s]", classPath);
+ return;
+ }
+
+ jmethodID mid = env->GetMethodID(m_pClazz, "<init>", "()V");
+ if (NULL == mid) {
+ LOGE("GetMethodID failed [%s]", classPath);
+ return;
+ }
+
+ m_pObject = env->NewObject(m_pClazz, mid);
+}
+
+JObject::~JObject() {
+ if (m_pEnv) {
+ if (m_pObject && m_fIsNewObject) {
+ m_pEnv->DeleteLocalRef(m_pObject);
+ }
+
+ if (m_pClazz && !m_fIsNewObject) {
+ m_pEnv->DeleteLocalRef(m_pClazz);
+ }
+ }
+}
+
+jobject JObject::getObject() const {
+ return m_pObject;
+}
+
+void JObject::detachObject() {
+ if (m_fIsNewObject) {
+ m_fIsNewObject = false;
+ m_pClazz = NULL;
+ }
+}
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#include "jni_setter.h"
+
+#include <string>
+
+#include "JniOcResource.h"
+
+#define LOG_TAG "TM_JSetter"
+
+bool JSetter::setJStringField(JNIEnv *env, jobject &object,
+ const char *fieldName, const char *value) {
+ if (NULL == env || NULL == fieldName) {
+ LOGE("setJStringField invalid parameters");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass(object);
+ if (NULL == clazz) {
+ LOGE("GetObjectClass failed");
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID(clazz, fieldName, "Ljava/lang/String;");
+ if (0 == fieldID) {
+ LOGE("GetFieldID failed [%s]", fieldName);
+ env->DeleteLocalRef(clazz);
+ return false;
+ }
+
+ jstring jvalue;
+ if (value != NULL && strlen(value) > 0) {
+ jclass strClass = env->FindClass("java/lang/String");
+ jmethodID ctorID = env->GetMethodID(strClass, "<init>",
+ "([BLjava/lang/String;)V");
+ jbyteArray bytes = env->NewByteArray(strlen(value));
+ env->SetByteArrayRegion(bytes, 0, strlen(value), (jbyte *) value);
+ jstring encoding = env->NewStringUTF("utf-8");
+ jvalue = (jstring) env->NewObject(strClass, ctorID, bytes, encoding);
+ env->DeleteLocalRef(strClass);
+ env->DeleteLocalRef(bytes);
+ env->DeleteLocalRef(encoding);
+ } else {
+ jvalue = env->NewStringUTF("");
+ }
+
+ env->SetObjectField(object, fieldID, jvalue);
+
+ env->DeleteLocalRef(jvalue);
+ env->DeleteLocalRef(clazz);
+
+ return true;
+}
+
+bool JSetter::setJIntField(JNIEnv *env, jobject &object, const char *fieldName,
+ int value) {
+ if (NULL == env || NULL == fieldName) {
+ LOGE("setJIntField invalid paramter");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass(object);
+ if (NULL == clazz) {
+ LOGE("GetObjectClass failed");
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID(clazz, fieldName, "I");
+ if (0 == fieldID) {
+ LOGE("GetFieldID failed [%s]", fieldName);
+ env->DeleteLocalRef(clazz);
+ return false;
+ }
+ env->SetIntField(object, fieldID, value);
+
+ env->DeleteLocalRef(clazz);
+
+ return true;
+}
+
+bool JSetter::setJLongField(JNIEnv *env, jobject &object, const char *fieldName,
+ jlong value) {
+ if (NULL == env || NULL == fieldName) {
+ LOGE("setJLongField invalid parameters");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass(object);
+ if (NULL == clazz) {
+ LOGE("GetObjectClass failed");
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID(clazz, fieldName, "J");
+ if (0 == fieldID) {
+ LOGE("GetFieldID failed [%s]", fieldName);
+ env->DeleteLocalRef(clazz);
+ return false;
+ }
+ env->SetLongField(object, fieldID, value);
+
+ env->DeleteLocalRef(clazz);
+
+ return true;
+}
+
+bool JSetter::setJBoolField(JNIEnv *env, jobject &object, const char *fieldName,
+ bool value) {
+ if (NULL == env || NULL == fieldName) {
+ LOGE("setJBoolField invalid parameters");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass(object);
+ if (NULL == clazz) {
+ LOGE("GetObjectClass failed");
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID(clazz, fieldName, "Z");
+ if (0 == fieldID) {
+ LOGE("GetFieldID failed [%s]", fieldName);
+ env->DeleteLocalRef(clazz);
+ return false;
+ }
+ env->SetBooleanField(object, fieldID, value);
+
+ env->DeleteLocalRef(clazz);
+
+ return true;
+}
+
+bool JSetter::setJObjectField(JNIEnv *env, jobject &object,
+ const char *fieldName, const char *fieldType, const jobject value) {
+ if (NULL == env || NULL == fieldName) {
+ LOGE("setJBoolField invalid parameters");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass(object);
+ if (NULL == clazz) {
+ LOGE("GetObjectClass failed");
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID(clazz, fieldName, fieldType);
+ if (0 == fieldID) {
+ LOGE("GetFieldID failed [%s] [%s]", fieldName, fieldType);
+ env->DeleteLocalRef(clazz);
+ return false;
+ }
+ env->SetObjectField(object, fieldID, value);
+
+ env->DeleteLocalRef(clazz);
+
+ return true;
+}
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#include "jni_string.h"
+
+#define LOG_TAG "TM_JString"
+
+JString::JString(JNIEnv *env, jstring value) :
+ JObject(env, value) {
+ const char *buff = env->GetStringUTFChars(value, 0);
+
+ m_cstr = buff;
+
+ env->ReleaseStringUTFChars(value, buff);
+}
+
+JString::JString(JNIEnv *env, const char *value) :
+ JObject(env) {
+ m_cstr = value;
+
+ if (env) {
+ m_pObject = env->NewStringUTF(value);
+ }
+}
+
+JString::JString(JNIEnv *env, const std::string &value) :
+ JObject(env) {
+ m_cstr = value;
+
+ if (env) {
+ m_pObject = env->NewStringUTF(value.c_str());
+ }
+}
+
+JString::~JString() {
+}
+
+bool JString::getValue(std::string &value) {
+ value = m_cstr;
+ return true;
+}
+
+const char *JString::c_str() {
+ return m_cstr.c_str();
+}
+
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#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
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+
+#ifndef __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,OCDevAddr *destination);
+
+OCStackApplicationResult GetProvisioningStatusResponse(void* ctx, OCDoHandle handle,
+ OCClientResponse * clientResponse);
+
+OCStackResult InvokeOCDoResource(const char* query, OCMethod method, const OCDevAddr *dest,
+ OCQualityOfService qos, OCClientResponseHandler cb, OCRepPayload* payload,
+ OCHeaderOption * options, uint8_t numOptions);
+
+OCStackResult GetProvisioningStatus(OCQualityOfService qos, const char* query,
+ const OCDevAddr*destination);
+
+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);
+
+
+void LogProvisioningResponse(OCRepPayloadValue* val);
+
+bool ConfigEnrolleeObject(const EnrolleeNWProvInfo_t *netInfo);
+
+bool ClearMemory();
+
+void SuccessCallback(OCClientResponse * clientResponse);
+
+void ErrorCallback(ProvStatus status);
+
+bool ValidateEnrolleResponse(OCClientResponse * clientResponse);
+
+bool ValidateFinddResourceResponse(OCClientResponse * clientResponse);
+
+ProvisioningInfo* GetCallbackObjectOnSuccess(OCClientResponse * clientResponse,
+ ProvStatus provStatus);
+
+ProvisioningInfo* GetCallbackObjectOnError(ProvStatus status);
+
+ProvisioningInfo* CreateCallBackObject();
+
+bool ResetProgress();
+
+bool SetProgress(OCProvisioningStatusCB provisioningStatusCallback);
+
+bool InProgress();
+
+bool ValidateEasySetupParams(const EnrolleeNWProvInfo_t *netInfo,
+ OCProvisioningStatusCB provisioningStatusCallback);
+
+
+#endif
+
--- /dev/null
+//******************************************************************
+//
+// 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;
+}
+
--- /dev/null
+ //******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#include <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;
+}
+
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <signal.h>
+#include <unistd.h>
+#include "ocpayload.h"
+#include "provisioninghandler.h"
+#include "common.h"
+// External includes
+
+#include "camutex.h"
+#include "cathreadpool.h"
+#include "logger.h"
+#include "oic_malloc.h"
+
+/**
+ * @var g_provisioningMutex
+ * @brief Mutex to synchronize access to g_caDtlsContext.
+ */
+static ca_mutex g_provisioningMutex = NULL;
+static ca_cond g_provisioningCond = NULL;
+bool g_provisioningCondFlag = false;
+
+static EnrolleeNWProvInfo_t* netProvInfo;
+
+/**
+ * @var cbData
+ * @brief Callback for providing provisioning status callback to application
+ */
+static OCProvisioningStatusCB cbData = NULL;
+static ca_thread_pool_t g_threadPoolHandle = NULL;
+
+void ErrorCallback(ProvStatus status)
+{
+ ProvisioningInfo *provInfo = GetCallbackObjectOnError(status);
+ cbData(provInfo);
+ ResetProgress();
+}
+
+OCStackResult InitProvisioningHandler()
+{
+ OCStackResult ret = OC_STACK_ERROR;
+ /* Initialize OCStack*/
+ if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
+ {
+ OIC_LOG(ERROR, TAG, "OCStack init error");
+ return ret;
+ }
+
+ g_provisioningMutex = ca_mutex_new();
+
+ OIC_LOG(DEBUG, TAG, "ca_thread_pool_init initializing");
+
+ if (CA_STATUS_OK != ca_thread_pool_init(2, &g_threadPoolHandle))
+ {
+ OIC_LOG(DEBUG, TAG, "thread_pool_init failed");
+ return OC_STACK_ERROR;
+ }
+
+ g_provisioningCond = ca_cond_new();
+ if (NULL == g_provisioningCond)
+ {
+ OIC_LOG(DEBUG, TAG, "Failed to create condition");
+ ca_mutex_free(g_provisioningMutex);
+ ca_thread_pool_free(g_threadPoolHandle);
+ return OC_STACK_ERROR;
+ }
+
+ char *string = "listeningFunc invoked in a thread";
+ if (CA_STATUS_OK != ca_thread_pool_add_task(g_threadPoolHandle, listeningFunc, (void *) string))
+ {
+ OIC_LOG(DEBUG, TAG, "thread_pool_add_task failed");
+ ca_thread_pool_free(g_threadPoolHandle);
+ ca_mutex_unlock(g_provisioningMutex);
+ ca_mutex_free(g_provisioningMutex);
+ ca_cond_free(g_provisioningCond);
+ return OC_STACK_ERROR;
+ }
+
+ ResetProgress();
+
+ return OC_STACK_OK;
+}
+
+OCStackResult TerminateProvisioningHandler()
+{
+ OCStackResult ret = OC_STACK_ERROR;
+ if (OCStop() != OC_STACK_OK)
+ {
+ OIC_LOG(ERROR, TAG, "OCStack stop error");
+ }
+
+ ca_mutex_lock(g_provisioningMutex);
+ g_provisioningCondFlag = true;
+ //ca_cond_signal(g_provisioningCond);
+ ca_mutex_unlock(g_provisioningMutex);
+
+ ca_mutex_free(g_provisioningMutex);
+ g_provisioningMutex = NULL;
+
+ ca_thread_pool_free(g_threadPoolHandle);
+ g_threadPoolHandle = NULL;
+
+ ret = OC_STACK_OK;
+ return ret;
+}
+
+void listeningFunc(void *data)
+{
+ while (!g_provisioningCondFlag)
+ {
+ OCStackResult result;
+
+ ca_mutex_lock(g_provisioningMutex);
+ result = OCProcess();
+ ca_mutex_unlock(g_provisioningMutex);
+
+ if (result != OC_STACK_OK)
+ {
+ OIC_LOG(ERROR, TAG, "OCStack stop error");
+ }
+
+ // To minimize CPU utilization we may wish to do this with sleep
+ sleep(1);
+ }
+}
+
+OCStackApplicationResult ProvisionEnrolleeResponse(void* ctx, OCDoHandle handle,
+ OCClientResponse * clientResponse)
+{
+
+ ProvisioningInfo *provInfo;
+
+ if (!ValidateEnrolleResponse(clientResponse))
+ {
+ ErrorCallback( DEVICE_NOT_PROVISIONED);
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+
+ char* tnn;
+ char* cd;
+
+ OCRepPayload* input = (OCRepPayload*) (clientResponse->payload);
+
+ while (input)
+ {
+
+ int64_t ps;
+ if (OCRepPayloadGetPropInt(input, OC_RSRVD_ES_PS, &ps))
+ {
+
+ if (ps == 1)
+ {
+ OIC_LOG_V(DEBUG, TAG, "PS is proper");
+ input = input->next;
+ continue;
+ }
+ else
+ {
+ OIC_LOG_V(DEBUG, TAG, "PS is NOT proper");
+ goto Error;
+
+ }
+ }
+
+ if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_TNN, &tnn))
+ {
+ if (!strcmp(tnn, netProvInfo->netAddressInfo.WIFI.ssid))
+ {
+ OIC_LOG_V(DEBUG, TAG, "SSID is proper");
+ input = input->next;
+ continue;
+ }
+ else
+ {
+ OIC_LOG_V(DEBUG, TAG, "SSID is NOT proper");
+ goto Error;
+ }
+ }
+
+ if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_CD, &cd))
+ {
+ if (!strcmp(cd, netProvInfo->netAddressInfo.WIFI.pwd))
+ {
+ OIC_LOG_V(DEBUG, TAG, "Password is proper");
+ input = input->next;
+ continue;
+ }
+ else
+ {
+ OIC_LOG_V(DEBUG, TAG, "Password is NOT proper");
+ goto Error;
+ }
+ }
+
+ LogProvisioningResponse(input->values);
+
+ input = input->next;
+
+ }
+
+ SuccessCallback(clientResponse);
+
+ return OC_STACK_KEEP_TRANSACTION;
+
+ Error:
+ {
+
+ ErrorCallback( DEVICE_NOT_PROVISIONED);
+
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+
+}
+
+OCStackResult ProvisionEnrollee(OCQualityOfService qos, const char* query, const char* resUri,
+ OCDevAddr *destination)
+{
+ OIC_LOG_V(INFO, TAG, "\n\nExecuting ProvisionEnrollee%s", __func__);
+
+ OCRepPayload* payload = OCRepPayloadCreate();
+
+ OCRepPayloadSetUri(payload, resUri);
+ OCRepPayloadSetPropString(payload, OC_RSRVD_ES_TNN, netProvInfo->netAddressInfo.WIFI.ssid);
+ OCRepPayloadSetPropString(payload, OC_RSRVD_ES_CD, netProvInfo->netAddressInfo.WIFI.pwd);
+
+ OIC_LOG_V(DEBUG, TAG, "OCPayload ready for ProvisionEnrollee");
+
+ OCStackResult ret = InvokeOCDoResource(query, OC_REST_PUT, destination, OC_HIGH_QOS,
+ ProvisionEnrolleeResponse, payload, NULL, 0);
+
+ return ret;
+}
+
+OCStackApplicationResult GetProvisioningStatusResponse(void* ctx, OCDoHandle handle,
+ OCClientResponse * clientResponse)
+{
+
+ ProvisioningInfo *provInfo;
+
+ if (!ValidateEnrolleResponse(clientResponse))
+ {
+ ErrorCallback( DEVICE_NOT_PROVISIONED);
+ ClearMemory();
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+
+ OCRepPayload* input = (OCRepPayload*) (clientResponse->payload);
+
+ char query[OIC_STRING_MAX_VALUE] =
+ { '\0' };
+ char resURI[MAX_URI_LENGTH] =
+ { '\0' };
+
+ OIC_LOG_V(DEBUG, TAG, "resUri = %s", input->uri);
+
+ strncpy(resURI, input->uri, sizeof(resURI));
+
+ snprintf(query, sizeof(query), UNICAST_PROV_STATUS_QUERY, clientResponse->addr->addr, IP_PORT,
+ resURI);
+
+ //OCPayloadLogRep(DEBUG,TAG,input);
+
+ if (ProvisionEnrollee(OC_HIGH_QOS, query, OC_RSRVD_ES_URI_PROV, clientResponse->addr)
+ != OC_STACK_OK)
+ {
+ OIC_LOG(INFO, TAG,
+ "GetProvisioningStatusResponse received NULL clientResponse.Invoking Provisioing Status Callback");
+
+ ErrorCallback( DEVICE_NOT_PROVISIONED);
+ ClearMemory();
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+
+ return OC_STACK_KEEP_TRANSACTION;
+
+}
+
+OCStackResult InvokeOCDoResource(const char* query, OCMethod method, const OCDevAddr *dest,
+ OCQualityOfService qos, OCClientResponseHandler cb, OCRepPayload* payload,
+ OCHeaderOption * options, uint8_t numOptions)
+{
+ OCStackResult ret;
+ OCCallbackData cbData;
+
+ cbData.cb = cb;
+ cbData.context = (void*) DEFAULT_CONTEXT_VALUE;
+ cbData.cd = NULL;
+
+ ret = OCDoResource(NULL, method, query, dest, (OCPayload*) payload, OC_CONNTYPE, qos, &cbData,
+ options, numOptions);
+
+ if (ret != OC_STACK_OK)
+ {
+ OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
+ }
+
+ return ret;
+}
+
+OCStackResult GetProvisioningStatus(OCQualityOfService qos, const char* query,
+ const OCDevAddr *destination)
+{
+ OCStackResult ret = OC_STACK_ERROR;
+ OCHeaderOption options[MAX_HEADER_OPTIONS];
+
+ OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
+
+ uint8_t option0[] =
+ { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
+ uint8_t option1[] =
+ { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
+ memset(options, 0, sizeof(OCHeaderOption) * MAX_HEADER_OPTIONS);
+ options[0].protocolID = OC_COAP_ID;
+ options[0].optionID = 2048;
+ memcpy(options[0].optionData, option0, sizeof(option0));
+ options[0].optionLength = 10;
+ options[1].protocolID = OC_COAP_ID;
+ options[1].optionID = 3000;
+ memcpy(options[1].optionData, option1, sizeof(option1));
+ options[1].optionLength = 10;
+
+ ret = InvokeOCDoResource(query, OC_REST_GET, destination, OC_HIGH_QOS,
+ GetProvisioningStatusResponse, NULL, options, 2);
+ return ret;
+}
+
+OCStackResult StartProvisioningProcess(const EnrolleeNWProvInfo_t *netInfo,
+ OCProvisioningStatusCB provisioningStatusCallback)
+{
+
+ OCStackResult result = OC_STACK_ERROR;
+
+ if (!ValidateEasySetupParams(netInfo, provisioningStatusCallback))
+ {
+ goto Error;
+ }
+
+ //Only basis test is done for below API
+ if (!SetProgress(provisioningStatusCallback))
+ {
+ // Device provisioning session is running already.
+ OIC_LOG(INFO, TAG, PCF("Device provisioning session is running already"));
+ goto Error;
+ }
+
+ if (!ConfigEnrolleeObject(netInfo))
+ {
+ goto Error;
+ }
+
+ if (CA_STATUS_OK != ca_thread_pool_add_task(g_threadPoolHandle, FindProvisioningResource,
+ (void *) ""))
+ {
+ goto Error;
+ }
+
+ return OC_STACK_OK;
+
+ Error:
+ {
+ ErrorCallback( DEVICE_NOT_PROVISIONED);
+ ClearMemory();
+ return OC_STACK_ERROR;
+ }
+
+}
+
+void StopProvisioningProcess()
+{
+ //Only basis test is done for below API
+ ResetProgress();
+}
+
+// This is a function called back when a device is discovered
+OCStackApplicationResult FindProvisioningResourceResponse(void* ctx, OCDoHandle handle,
+ OCClientResponse * clientResponse)
+{
+
+ OIC_LOG(INFO, TAG, PCF("Entering FindProvisioningResourceResponse"));
+
+ if (!ValidateFinddResourceResponse(clientResponse))
+ {
+ ErrorCallback( DEVICE_NOT_PROVISIONED);
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+
+ OCStackApplicationResult response = OC_STACK_DELETE_TRANSACTION;
+
+ ProvisioningInfo *provInfo;
+ char szQueryUri[64] =
+ { 0 };
+
+ OCDiscoveryPayload* discoveryPayload = (OCDiscoveryPayload*) (clientResponse->payload);
+
+ // Need to conform if below check is required or not. As Null check of clientResponse->payload is already performed above
+ if (!discoveryPayload)
+ {
+ OIC_LOG_V(DEBUG, TAG, "Failed To parse");
+ ErrorCallback( DEVICE_NOT_PROVISIONED);
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+
+ OIC_LOG_V(DEBUG, TAG, "resUri = %s", discoveryPayload->resources->uri);
+
+ snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_PROV_STATUS_QUERY,
+ clientResponse->devAddr.addr, IP_PORT, discoveryPayload->resources->uri);
+
+ OIC_LOG_V(DEBUG, TAG, "query before GetProvisioningStatus call = %s", szQueryUri);
+
+ if (GetProvisioningStatus(OC_HIGH_QOS, szQueryUri, &clientResponse->devAddr) != OC_STACK_OK)
+ {
+ ErrorCallback( DEVICE_NOT_PROVISIONED);
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+
+ return OC_STACK_KEEP_TRANSACTION;
+
+}
+
+void FindProvisioningResource(void *data)
+{
+ OCStackResult ret = OC_STACK_ERROR;
+
+ /* Start a discovery query*/
+ char szQueryUri[64] =
+ { 0 };
+
+ snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_PROVISIONING_QUERY,
+ netProvInfo->netAddressInfo.WIFI.ipAddress, IP_PORT);
+
+ OIC_LOG_V(DEBUG, TAG, "szQueryUri = %s", szQueryUri);
+
+ OCCallbackData ocCBData;
+
+ ocCBData.cb = FindProvisioningResourceResponse;
+ ocCBData.context = (void*) DEFAULT_CONTEXT_VALUE;
+ ocCBData.cd = NULL;
+
+ ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, NULL, NULL, OC_CONNTYPE, OC_LOW_QOS,
+ &ocCBData, NULL, 0);
+
+ if (ret != OC_STACK_OK)
+ {
+ ErrorCallback( DEVICE_NOT_PROVISIONED);
+ ClearMemory();
+ }
+}
+
+OCStackApplicationResult SubscribeProvPresenceCallback(void* ctx, OCDoHandle handle,
+ OCClientResponse* clientResponse)
+{
+ OIC_LOG(INFO, TAG, PCF("Entering SubscribeProvPresenceCallback"));
+
+ OCStackApplicationResult response = OC_STACK_DELETE_TRANSACTION;
+
+ if (clientResponse->result != OC_STACK_OK)
+ {
+ OIC_LOG(ERROR, TAG, "OCStack stop error");
+ return response;
+ }
+
+ if (clientResponse)
+ {
+ OIC_LOG(INFO, TAG, PCF("Client Response exists"));
+
+ if (clientResponse->payload && clientResponse->payload->type != PAYLOAD_TYPE_REPRESENTATION)
+ {
+ OIC_LOG_V(DEBUG, TAG, "Incoming payload not a representation");
+ return response;
+ }
+
+ OCRepPayload* discoveryPayload = (OCRepPayload*) (clientResponse->payload);
+ if (!discoveryPayload)
+ {
+ OIC_LOG_V(DEBUG, TAG, "invalid payload");
+ return response;
+ }
+
+ char sourceIPAddr[OIC_STRING_MAX_VALUE] =
+ { '\0' };
+ snprintf(sourceIPAddr, sizeof(sourceIPAddr), "%s", clientResponse->addr->addr);
+
+ OIC_LOG_V(DEBUG, TAG, "Discovered %s @ %s", discoveryPayload->uri, sourceIPAddr);
+
+ /* Start a discovery query*/
+ char szQueryUri[64] =
+ { 0 };
+
+ snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_PROVISIONING_QUERY, sourceIPAddr, IP_PORT);
+
+ /*if (FindProvisioningResource(qos, szQueryUri) != OC_STACK_OK) {
+ OIC_LOG(ERROR, TAG, "FindProvisioningResource failed");
+ return OC_STACK_KEEP_TRANSACTION;
+ }*/
+ }
+ else
+ {
+ // clientResponse is invalid
+ OIC_LOG(ERROR, TAG, PCF("Client Response is NULL!"));
+ }
+ return OC_STACK_KEEP_TRANSACTION;
+}
+
+OCStackResult SubscribeProvPresence(OCQualityOfService qos, const char* requestURI)
+{
+ OCStackResult ret = OC_STACK_ERROR;
+
+ OCCallbackData cbData;
+
+ cbData.cb = &SubscribeProvPresenceCallback;
+ cbData.context = (void*) DEFAULT_CONTEXT_VALUE;
+ cbData.cd = NULL;
+
+ ret = OCDoResource(NULL, OC_REST_PRESENCE, requestURI, 0, 0, OC_CONNTYPE, OC_LOW_QOS, &cbData,
+ NULL, 0);
+
+ if (ret != OC_STACK_OK)
+ {
+ OIC_LOG(ERROR, TAG, "OCStack resource error");
+ }
+
+ return ret;
+}
+
+OCStackResult FindNetworkResource()
+{
+ OCStackResult ret = OC_STACK_ERROR;
+ if (OCStop() != OC_STACK_OK)
+ {
+ OIC_LOG(ERROR, TAG, "OCStack stop error");
+ }
+
+ return ret;
+}
+
+ProvisioningInfo* PrepareProvisioingStatusCB(OCClientResponse * clientResponse,
+ ProvStatus provStatus)
+{
+
+ ProvisioningInfo *provInfo = (ProvisioningInfo *) OICCalloc(1, sizeof(ProvisioningInfo));
+
+ if (provInfo == NULL)
+ {
+ OIC_LOG_V(ERROR, TAG, "Failed to allocate memory");
+ return NULL;
+ }
+
+ OCDevAddr *devAddr = (OCDevAddr *) OICCalloc(1, sizeof(OCDevAddr));
+
+ if (devAddr == NULL)
+ {
+ OIC_LOG_V(ERROR, TAG, "Failed to allocate memory");
+ return NULL;
+ }
+
+ strncpy(devAddr->addr, clientResponse->addr->addr, sizeof(devAddr->addr));
+ devAddr->port = clientResponse->addr->port;
+
+ provInfo->provDeviceInfo.addr = devAddr;
+
+ provInfo->provStatus = provStatus;
+
+ return provInfo;
+}
+
+bool ValidateEasySetupParams(const EnrolleeNWProvInfo_t *netInfo,
+ OCProvisioningStatusCB provisioningStatusCallback)
+{
+
+ if (netInfo == NULL || netInfo->netAddressInfo.WIFI.ipAddress == NULL)
+ {
+ OIC_LOG(ERROR, TAG, "Request URI is NULL");
+ return false;
+ }
+
+ if (provisioningStatusCallback == NULL)
+ {
+ OIC_LOG(ERROR, TAG, "ProvisioningStatusCallback is NULL");
+ return false;
+ }
+
+ return true;
+
+}
+
+bool InProgress()
+{
+
+ // It means already Easy Setup provisioning session is going on.
+ if (NULL != cbData)
+ {
+ OIC_LOG(ERROR, TAG, "Easy setup session is already in progress");
+ return true;
+ }
+
+ return false;
+}
+
+bool SetProgress(OCProvisioningStatusCB provisioningStatusCallback)
+{
+ ca_mutex_lock(g_provisioningMutex);
+
+ if (InProgress())
+ return false;
+
+ cbData = provisioningStatusCallback;
+
+ ca_mutex_unlock(g_provisioningMutex);
+
+ return true;
+}
+
+bool ResetProgress()
+{
+ ca_mutex_lock(g_provisioningMutex);
+
+ cbData = NULL;
+
+ ca_mutex_unlock(g_provisioningMutex);
+}
+
+ProvisioningInfo* CreateCallBackObject()
+{
+
+ ProvisioningInfo *provInfo = (ProvisioningInfo *) OICCalloc(1, sizeof(ProvisioningInfo));
+
+ if (provInfo == NULL)
+ {
+ OIC_LOG_V(ERROR, TAG, "Failed to allocate memory");
+ return NULL;
+ }
+
+ OCDevAddr *devAddr = (OCDevAddr *) OICCalloc(1, sizeof(OCDevAddr));
+
+ if (devAddr == NULL)
+ {
+ OIC_LOG_V(ERROR, TAG, "Failed to allocate memory");
+ return NULL;
+ }
+
+ provInfo->provDeviceInfo.addr = devAddr;
+
+ return provInfo;
+
+}
+
+ProvisioningInfo* GetCallbackObjectOnError(ProvStatus status)
+{
+
+ ProvisioningInfo *provInfo = CreateCallBackObject();
+ strncpy(provInfo->provDeviceInfo.addr->addr, netProvInfo->netAddressInfo.WIFI.ipAddress,
+ sizeof(provInfo->provDeviceInfo.addr->addr));
+ provInfo->provDeviceInfo.addr->port = IP_PORT;
+ provInfo->provStatus = status;
+ return provInfo;
+}
+
+ProvisioningInfo* GetCallbackObjectOnSuccess(OCClientResponse * clientResponse,
+ ProvStatus provStatus)
+{
+ ProvisioningInfo *provInfo = CreateCallBackObject();
+ strncpy(provInfo->provDeviceInfo.addr->addr, clientResponse->addr->addr,
+ sizeof(provInfo->provDeviceInfo.addr->addr));
+ provInfo->provDeviceInfo.addr->port = clientResponse->addr->port;
+ provInfo->provStatus = provStatus;
+ return provInfo;
+}
+
+bool ValidateFinddResourceResponse(OCClientResponse * clientResponse)
+{
+
+ if (!(clientResponse) || !(clientResponse->payload))
+ {
+
+ OIC_LOG_V(INFO, TAG, "ProvisionEnrolleeResponse received Null clientResponse");
+
+ return false;
+
+ }
+return true;
+}
+
+bool ValidateEnrolleResponse(OCClientResponse * clientResponse)
+{
+
+ if (!(clientResponse) || !(clientResponse->payload))
+ {
+
+ OIC_LOG_V(INFO, TAG, "ProvisionEnrolleeResponse received Null clientResponse");
+
+ return false;
+
+ }
+
+ if (clientResponse->payload->type != PAYLOAD_TYPE_REPRESENTATION)
+ {
+
+ OIC_LOG_V(DEBUG, TAG, "Incoming payload not a representation");
+ return false;
+
+ }
+
+ // If flow reachese here means no error condition hit.
+ return true;
+
+}
+
+
+void SuccessCallback(OCClientResponse * clientResponse)
+{
+ ProvisioningInfo *provInfo = GetCallbackObjectOnSuccess(clientResponse, DEVICE_PROVISIONED);
+ cbData(provInfo);
+ ResetProgress();
+}
+
+bool ClearMemory()
+{
+
+ OIC_LOG(DEBUG, TAG, "thread_pool_add_task of FindProvisioningResource failed");
+ ca_thread_pool_free(g_threadPoolHandle);
+ ca_mutex_unlock(g_provisioningMutex);
+ ca_mutex_free(g_provisioningMutex);
+ ca_cond_free(g_provisioningCond);
+
+ return true;
+
+}
+
+bool ConfigEnrolleeObject(const EnrolleeNWProvInfo_t *netInfo)
+{
+
+ //Copy Network Provisioning Information
+ netProvInfo = (EnrolleeNWProvInfo_t *) OICCalloc(1, sizeof(EnrolleeNWProvInfo_t));
+
+ if (netProvInfo == NULL)
+ {
+ OIC_LOG(ERROR, TAG, "Invalid input..");
+ return false;
+ }
+
+ memcpy(netProvInfo, netInfo, sizeof(EnrolleeNWProvInfo_t));
+
+ OIC_LOG_V(DEBUG, TAG, "Network Provisioning Info. SSID = %s",
+ netProvInfo->netAddressInfo.WIFI.ssid);
+
+ OIC_LOG_V(DEBUG, TAG, "Network Provisioning Info. PWD = %s",
+ netProvInfo->netAddressInfo.WIFI.pwd);
+
+ return true;
+
+}
+
+void LogProvisioningResponse(OCRepPayloadValue* val)
+{
+
+ switch (val->type)
+ {
+ case OCREP_PROP_NULL:
+ OIC_LOG_V(DEBUG, TAG, "\t\t%s: NULL", val->name);
+ break;
+ case OCREP_PROP_INT:
+ OIC_LOG_V(DEBUG, TAG, "\t\t%s(int):%lld", val->name, val->i);
+ break;
+ case OCREP_PROP_DOUBLE:
+ OIC_LOG_V(DEBUG, TAG, "\t\t%s(double):%f", val->name, val->d);
+ break;
+ case OCREP_PROP_BOOL:
+ OIC_LOG_V(DEBUG, TAG, "\t\t%s(bool):%s", val->name, val->b ? "true" : "false");
+ break;
+ case OCREP_PROP_STRING:
+ OIC_LOG_V(DEBUG, TAG, "\t\t%s(string):%s", val->name, val->str);
+ break;
+ case OCREP_PROP_OBJECT:
+ // Note: Only prints the URI (if available), to print further, you'll
+ // need to dig into the object better!
+ OIC_LOG_V(DEBUG, TAG, "\t\t%s(OCRep):%s", val->name, val->obj->uri);
+ break;
+ case OCREP_PROP_ARRAY:
+ switch (val->arr.type)
+ {
+ case OCREP_PROP_INT:
+ OIC_LOG_V(DEBUG, TAG, "\t\t%s(int array):%lld x %lld x %lld", val->name,
+ val->arr.dimensions[0], val->arr.dimensions[1], val->arr.dimensions[2]);
+ break;
+ case OCREP_PROP_DOUBLE:
+ OIC_LOG_V(DEBUG, TAG, "\t\t%s(double array):%lld x %lld x %lld", val->name,
+ val->arr.dimensions[0], val->arr.dimensions[1], val->arr.dimensions[2]);
+ break;
+ case OCREP_PROP_BOOL:
+ OIC_LOG_V(DEBUG, TAG, "\t\t%s(bool array):%lld x %lld x %lld", val->name,
+ val->arr.dimensions[0], val->arr.dimensions[1], val->arr.dimensions[2]);
+ break;
+ case OCREP_PROP_STRING:
+ OIC_LOG_V(DEBUG, TAG, "\t\t%s(string array):%lld x %lld x %lld", val->name,
+ val->arr.dimensions[0], val->arr.dimensions[1], val->arr.dimensions[2]);
+ break;
+ case OCREP_PROP_OBJECT:
+ OIC_LOG_V(DEBUG, TAG, "\t\t%s(OCRep array):%lld x %lld x %lld", val->name,
+ val->arr.dimensions[0], val->arr.dimensions[1], val->arr.dimensions[2]);
+ break;
+ default:
+ //OIC_LOG_V(ERROR, TAG, "\t\t%s <-- Unknown/unsupported array type!",
+ // val->name);
+ break;
+ }
+ break;
+ default:
+ /*OC_LOG_V(ERROR, TAG
+ , "\t\t%s <-- Unknown type!", val->name);*/
+ break;
+ }
+}
+