# android examples require android api to be built before being invoked
Depends(cmdBuildExamples, cmdBuildApi)
+env.AppendUnique(baseAAR = cmdBuildApi)
help_vars.Add(PathVariable('ANDROID_NDK', 'Android NDK path', None, PathVariable.PathAccept))
help_vars.Add(PathVariable('ANDROID_HOME', 'Android SDK path', None, PathVariable.PathAccept))
help_vars.Add(PathVariable('ANDROID_GRADLE', 'Gradle binary file', None, PathVariable.PathIsFile))
-#ES_TARGET_ENROLLEE is for specifying what is our target enrollee (Arduino or rest of platforms which support Multicast)
-help_vars.Add(EnumVariable('ES_TARGET_ENROLLEE', 'Target Enrollee', 'arduino', allowed_values=('arduino', 'tizen', 'linux')))
-#ES_ROLE is for specifying the role (Enrollee or Mediator) for which scons is being executed
-help_vars.Add(EnumVariable('ES_ROLE', 'Target build mode', 'mediator', allowed_values=('mediator', 'enrollee')))
-#ES_SOFT_MODE is for specifying MODE (Mode 1 : Enrollee with Soft AP or Mode 2 : Mediator with Soft AP)
-help_vars.Add(EnumVariable('ES_SOFTAP_MODE', 'Target build mode', 'ENROLLEE_SOFTAP', allowed_values=('ENROLLEE_SOFTAP', 'MEDIATOR_SOFTAP')))
AddOption('--prefix',
dest='prefix',
../../csdk/stack/include/internal/oicgroup.h \
../../csdk/stack/include/internal/oickeepalive.h \
guides \
+ ../../../service/easy-setup/inc \
../../../service/easy-setup/enrollee/inc \
- ../../../service/easy-setup/enrollee/src/softap.h \
../../../service/resource-directory/include \
export ANDROID_NDK=<ANDROID_NDK>
a) In the IoTivity root source folder execute
- scons TARGET_OS=android TARGET_ARCH=armeabi TARGET_TRANSPORT=IP ES_ROLE=mediator ES_TARGET_ENROLLEE={Platform} RELEASE=0
- Note : {Platform} can be -> arduino , linux, tizen
+ 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
Possible values for <transport> are: [Only ip is currently supported]
-> IP :
- $ scons service TARGET_OS=arduino BOARD=arduino_due_x_dbg TARGET_ARCH=arm SHIELD=WIFI ES_ROLE=enrollee RELEASE=0
+ $ scons service TARGET_OS=arduino BOARD=arduino_due_x_dbg TARGET_ARCH=arm SHIELD=WIFI RELEASE=0
-> BLE :
$ scons service TARGET_OS=arduino BOARD=arduino_due_x_dbg TARGET_ARCH=arm SHIELD=BLE RELEASE=0 [Currently not supporting]
Import('env')
es_target = env.get ('TARGET_OS')
-es_role = env.get('ES_ROLE')
-es_target_enrollee = env.get('ES_TARGET_ENROLLEE')
-print "************************************************************************************"
-print "Easysetup device role --> %s " % es_role
-print "Target Platform --> %s " % es_target
-print "Target Enrollee platform --> %s " % es_target_enrollee
-print "************************************************************************************"
+if es_target in ['linux']:
+ SConscript('mediator/SConscript')
+ SConscript('enrollee/SConscript')
-#Go to build sample apps
-if ('mediator' in es_role) :
- print "Building Easysetup mediator SDKs [CSDK & RichSDK]"
+if es_target in ['android']:
+ SConscript('mediator/SConscript')
- if es_target in ['linux','android']:
- SConscript('mediator/SConscript')
- else :
- print "****************************Mediator supports Linux and Android platform****************************"
-
-if ('enrollee' in es_role) :
- print "Building Easysetup enrollee SDK"
-
- if es_target in ['linux', 'arduino', 'tizen']:
- SConscript('enrollee/SConscript')
- else :
- print "****************************Enrollee supports linux, tizen and arduino platform****************************"
\ No newline at end of file
+if es_target in ['tizen']:
+ SConscript('enrollee/SConscript')
if enrollee_env.get('LOGGING'):
enrollee_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
-# Enrollees are implemented for IP transport only.
-if 'IP' in enrollee_env.get('TARGET_TRANSPORT'):
- print "Enrollees are implemented for IP transport only"
- enrollee_env.AppendUnique(CPPDEFINES = ['ESWIFI'])
-
-if enrollee_env.get('ES_SOFTAP_MODE') == 'ENROLLEE_SOFTAP':
- enrollee_env.AppendUnique(CPPDEFINES = ['ENROLLEE_SOFTAP'])
-
######################################################################
# Build flags
######################################################################
enrollee_env.get('SRC_DIR') + '/resource/include',
enrollee_env.get('SRC_DIR') + '/resource/csdk/logger/include',
enrollee_env.get('SRC_DIR') + '/resource/oc_logger/include',
- enrollee_env.get('SRC_DIR') + '/resource/csdk/stack/include',
- enrollee_env.get('SRC_DIR') + '/resource/csdk/logger/include',
+ enrollee_env.get('SRC_DIR') + '/resource/csdk/stack/include',
+ enrollee_env.get('SRC_DIR') + '/resource/csdk/logger/include',
enrollee_env.get('SRC_DIR') + '/resource/csdk/security/include',
enrollee_env.get('SRC_DIR') + '/extlibs/cjson',
enrollee_env.get('SRC_DIR') + '/extlibs/sqlite3',
enrollee_env.get('SRC_DIR') + '/service/easy-setup/inc',
- enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/linux/wifi',
enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/inc',
- enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/src',
- enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/arduino'])
+ enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/src'])
if enrollee_env.get('SECURED') == '1':
enrollee_env.AppendUnique(CPPPATH = [
if target_os not in ['windows']:
enrollee_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
+if not env.get('RELEASE'):
+ enrollee_env.PrependUnique(LIBS = ['gcov'])
+ enrollee_env.AppendUnique(CCFLAGS = ['--coverage'])
+
######################################################################
# Linux Enrollee
######################################################################
if target_os in ['linux']:
- enrollee_env.PrependUnique(CPPPATH = [
- enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/linux/wifi'])
-
enrollee_env.AppendUnique(LIBS = ['pthread', 'dl'])
enrollee_env.AppendUnique(LIBPATH = [enrollee_env.get('BUILD_DIR')])
enrollee_env.AppendUnique(RPATH = [enrollee_env.get('BUILD_DIR')])
# Tizen Enrollee
######################################################################
if target_os == 'tizen':
- enrollee_env.AppendUnique(LIBPATH = [enrollee_env.get('BUILD_DIR')])
- enrollee_env.AppendUnique(RPATH = [enrollee_env.get('BUILD_DIR')])
- enrollee_env.AppendUnique(CXXFLAGS = ['-pthread'])
- enrollee_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction'])
- enrollee_env.AppendUnique(CPPPATH = [
- enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/tizen/wifi'])
+ enrollee_env.AppendUnique(LIBPATH = [enrollee_env.get('BUILD_DIR')])
+ enrollee_env.AppendUnique(RPATH = [enrollee_env.get('BUILD_DIR')])
+ enrollee_env.AppendUnique(CXXFLAGS = ['-pthread'])
+ enrollee_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction'])
+ enrollee_env.AppendUnique(CPPPATH = [enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/tizen/wifi'])
######################################################################
# Arduino Enrollee
enrollee_env.AppendUnique(LIBPATH = [enrollee_env.get('BUILD_DIR')])
enrollee_env.AppendUnique(RPATH = [enrollee_env.get('BUILD_DIR')])
enrollee_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction'])
- enrollee_env.AppendUnique(CPPPATH = [
- enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/arduino/wifi'])
######################################################################
# Source files and Targets
######################################################################
es_enrollee_src = None
-if target_os in ['linux']:
- es_enrollee_common_src = [enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/src/easysetup.c',
- enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/src/onboarding.c',
- enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/src/resourcehandler.c',
- enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/src/softap.c',
- enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/linux/wifi/softapnative.c',
- enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/linux/wifi/networkhandler.c']
-
- enrollee_env.AppendUnique(es_enrollee_src = es_enrollee_common_src)
-
- enrollee_sdk_shared = enrollee_env.SharedLibrary('ESEnrolleeSDK', enrollee_env.get('es_enrollee_src'))
+if target_os in ['linux', 'tizen']:
+ es_enrollee_common_src = ['./src/easysetup.c','./src/resourcehandler.c']
+ enrollee_sdk_shared = enrollee_env.SharedLibrary('ESEnrolleeSDK', es_enrollee_common_src)
enrollee_env.InstallTarget(enrollee_sdk_shared, 'libESEnrollee')
-
-if target_os == 'tizen':
- enrollee_sdk_shared = enrollee_env.SharedLibrary('ESEnrolleeSDK', [
- enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/src/easysetup.c',
- enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/src/onboarding.c',
- enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/src/softap.c',
- enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/src/resourcehandler.c',
- enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/tizen/wifi/networkhandler.c',
- enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/tizen/wifi/softapnative.c'])
- enrollee_env.InstallTarget(enrollee_sdk_shared, 'libESEnrolleeSDK')
- enrollee_env.UserInstallTargetLib(enrollee_sdk_shared, 'libESEnrolleeSDK')
+ enrollee_env.UserInstallTargetLib(enrollee_sdk_shared, 'libESEnrollee')
if target_os == 'arduino':
- es_sdk_static = enrollee_env.StaticLibrary('ESEnrolleeSDK', [
- enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/arduino/easysetup.cpp',
- enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/arduino/onboarding.cpp',
- enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/arduino/softap.cpp',
- enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/arduino/resourcehandler.cpp',
- enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/arduino/wifi/networkhandler.cpp'])
- enrollee_env.InstallTarget(es_sdk_static, 'libESEnrolleeSDK')
+ es_enrollee_common_src = ['./src/easysetup.c','./src/resourcehandler.c']
+ enrollee_sdk_static = enrollee_env.StaticLibrary('ESEnrolleeSDK', es_enrollee_common_src)
+ enrollee_env.InstallTarget(enrollee_sdk_static, 'libESEnrolleeSDK')
+ enrollee_env.UserInstallTargetLib(enrollee_sdk_static, 'libESEnrollee')
#Go to build sample apps
-if target_os == 'arduino':
- SConscript('../sampleapp/enrollee/arduino/SConscript')
+#if target_os == 'arduino':
+# SConscript('../sampleapp/enrollee/arduino/SConscript')
if target_os in ['linux']:
SConscript('../sampleapp/enrollee/linux/SConscript')
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-/**
- * @file
- *
- * This file contains the implementation for EasySetup Enrollee device
- */
-
-#include "easysetup.h"
-#include "softap.h"
-#include "onboarding.h"
-#include "logger.h"
-#include "resourcehandler.h"
-
-/**
- * @var ES_ENROLLEE_TAG
- * @brief Logging tag for module name.
- */
-#define ES_ENROLLEE_TAG "ES"
-
-//-----------------------------------------------------------------------------
-// Private variables
-//-----------------------------------------------------------------------------
-
-/**
- * @var gTargetSsid
- * @brief Target SSID of the Soft Access point to which the device has to connect
- */
-static char gTargetSsid[MAXSSIDLEN];
-
-/**
- * @var gTargetPass
- * @brief Password of the target access point to which the device has to connect
- */
-static char gTargetPass[MAXNETCREDLEN];
-
-/**
- * @var gEnrolleeStatusCb
- * @brief Fucntion pointer holding the callback for intimation of EasySetup Enrollee status callback
- */
-static ESEnrolleeEventCallback gEnrolleeStatusCb = NULL;
-
-/**
- * @var gIsSecured
- * @brief Variable to check if secure mode is enabled or not.
- */
-static bool gIsSecured = false;
-
-//-----------------------------------------------------------------------------
-// Private internal function prototypes
-//-----------------------------------------------------------------------------
-void ESOnboardingCallback(ESResult esResult);
-void ESProvisioningCallback(ESResult esResult);
-void ESOnboardingCallbackTargetNet(ESResult esResult);
-static bool ESEnrolleeValidateParam(OCConnectivityType networkType, const char *ssid,
- const char *passwd, ESEnrolleeEventCallback cb);
-
-
-void ESOnboardingCallback(ESResult esResult)
-{
- OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "ESOnboardingCallback with result = %d", esResult);
- if(esResult == ES_OK)
- {
- gEnrolleeStatusCb(esResult, ES_ON_BOARDED_STATE);
- }
- else
- {
- OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG,
- "Onboarding is failed callback result is = %d", esResult);
- gEnrolleeStatusCb(esResult, ES_INIT_STATE);
- }
-}
-
-void ESProvisioningCallback(ESResult esResult)
-{
- OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "ESProvisioningCallback with result = %d", esResult);
-
- if (esResult == ES_RECVTRIGGEROFPROVRES)
- {
- GetTargetNetworkInfoFromProvResource(gTargetSsid, gTargetPass);
- gEnrolleeStatusCb(ES_OK, ES_PROVISIONED_STATE);
- OIC_LOG(DEBUG, ES_ENROLLEE_TAG, "Connecting with target network");
-
- // Connecting/onboarding to target network
- ConnectToWiFiNetwork(gTargetSsid, gTargetPass, ESOnboardingCallbackTargetNet);
- }
- else
- {
- OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "Provisioning is failed callback result is = %d", esResult);
- // Resetting Enrollee to ONBOARDED_STATE as Enrollee is alreday onboarded in previous step
- gEnrolleeStatusCb(ES_OK, ES_ON_BOARDED_STATE);
- }
-}
-
-void ESOnboardingCallbackTargetNet(ESResult esResult)
-{
- OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "ESOnboardingCallback on target network with result = %d",
- esResult);
- if(esResult == ES_OK)
- {
- gEnrolleeStatusCb(esResult, ES_ON_BOARDED_TARGET_NETWORK_STATE);
- }
- else
- {
- OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG,
- "Onboarding is failed on target network and callback result is = %d", esResult);
- // Resetting Enrollee state to the ES_PROVISIONED_STATE
- // as device is already being provisioned with target network creds.
- gEnrolleeStatusCb(esResult, ES_PROVISIONED_STATE);
- }
-}
-
-ESResult ESInitEnrollee(OCConnectivityType networkType, const char *ssid, const char *passwd,
- bool isSecured,
- ESEnrolleeEventCallback cb)
-{
- OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitEnrollee IN");
- if(!ESEnrolleeValidateParam(networkType,ssid,passwd,cb))
- {
- OIC_LOG(ERROR, ES_ENROLLEE_TAG,
- "ESInitEnrollee::Stopping Easy setup due to invalid parameters");
- return ES_ERROR;
- }
-
- //Init callback
- gEnrolleeStatusCb = cb;
-
- gIsSecured = isSecured;
-
- // TODO : This onboarding state has to be set by lower layer, as they better
- // knows when actually on-boarding started.
- cb(ES_ERROR,ES_ON_BOARDING_STATE);
-
- OIC_LOG(INFO, ES_ENROLLEE_TAG, "received callback");
- OIC_LOG(INFO, ES_ENROLLEE_TAG, "onboarding now..");
-
- if(!ESOnboard(ssid, passwd, ESOnboardingCallback))
- {
- OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESInitEnrollee::On-boarding failed");
- cb(ES_ERROR, ES_INIT_STATE);
- return ES_ERROR;
- }
-
- OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitEnrollee OUT");
- return ES_OK;
-}
-
-ESResult ESTerminateEnrollee()
-{
- UnRegisterResourceEventCallBack();
-
- //Delete Prov resource
- if (DeleteProvisioningResource() != OC_STACK_OK)
- {
- OIC_LOG(ERROR, ES_ENROLLEE_TAG, "Deleting prov resource error!!");
- return ES_ERROR;
- }
-
- OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESTerminateEnrollee success");
- return ES_OK;
-}
-
-ESResult ESInitProvisioning()
-{
- OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitProvisioning <<IN>>");
-
- if (CreateProvisioningResource(gIsSecured) != OC_STACK_OK)
- {
- OIC_LOG(ERROR, ES_ENROLLEE_TAG, "CreateProvisioningResource error");
- return ES_ERROR;
- }
-
- RegisterResourceEventCallBack(ESProvisioningCallback);
-
- OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitProvisioning <<OUT>>");
- return ES_RESOURCECREATED;
-}
-
-static bool ESEnrolleeValidateParam(OCConnectivityType /*networkType*/, const char *ssid,
- const char *passwd, ESEnrolleeEventCallback cb)
-{
- if (!ssid || !passwd || !cb)
- {
- OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESEnrolleeValidateParam - Invalid parameters");
- return false;
- }
- 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-/**
- * @file
- *
- * This file has methods for on-boarding the Enrollee device.
- * This will contain template methods that will have core business logic & negotiation algorithm
- * on various on-boarding methods.
- */
-
-#include "easysetup.h"
-#include "softap.h"
-#include "onboarding.h"
-
-#include "logger.h"
-#include "resourcehandler.h"
-
-/**
- * @var ES_ENROLLEE_TAG
- * @brief Logging tag for module name.
- */
-#define ES_ENROLLEE_TAG "ES_SOFTAP"
-
-/**
- * It will return true on-boarding type is soft AP
- */
-bool ESSoftapOnboarding()
-{
- // TODO: To be changed based on user config. Current version, hardcoded to SoftAp onboarding
- return true;
-}
-
-/**
- * It will return true on-boarding type is BLE
- */
-bool ESBleOnboarding()
-{
- //BLE onboarding is not supported with current version.
- return false;
-}
-
-/**
- * It will do onboarding based on the user's configuration.
- */
-bool ESOnboard(const char * ssid, const char* passwd, ESEnrolleeNetworkEventCallback cb)
-{
- OIC_LOG(DEBUG, ES_ENROLLEE_TAG, "ESOnboard IN");
-
- if (ESSoftapOnboarding())
- {
- OIC_LOG(DEBUG, ES_ENROLLEE_TAG, "Connecting to Mediator SoftAp");
- ConnectToWiFiNetwork(ssid, passwd, cb);
- return true;
- }
- else if (ESBleOnboarding())
- {
- OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESOnboard::Ble onboarding is not supported");
- // TODO:
- return false;
- }
- else
- {
- // TODO:
- OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESOnboard::Invalid onboarding option");
- return false;
- }
-}
-
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "resourcehandler.h"
-
-#include <stdio.h>
-
-#include "ocpayload.h"
-#include "oic_string.h"
-
-/**
- * @var ES_RH_TAG
- * @brief Logging tag for module name.
- */
-#define ES_RH_TAG "ES_RH"
-//-----------------------------------------------------------------------------
-// Private variables
-//-----------------------------------------------------------------------------
-
-/**
- * @var gProvResource
- * @brief Structure for holding the Provisioning status and target information required to
- * connect to the target network
- */
-static ProvResource gProvResource;
-
-/**
- * @var gNetResource
- * @brief Structure forr holding the Provisioning status of network information
- */
-static NetResource gNetResource;
-
-//-----------------------------------------------------------------------------
-// Private internal function prototypes
-//-----------------------------------------------------------------------------
-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);
-
-ESEnrolleeResourceEventCallback gNetworkInfoProvEventCb = NULL;
-
-void RegisterResourceEventCallBack(ESEnrolleeResourceEventCallback cb)
-{
- gNetworkInfoProvEventCb = cb;
-}
-
-void UnRegisterResourceEventCallBack()
-{
- if (gNetworkInfoProvEventCb)
- {
- gNetworkInfoProvEventCb = NULL;
- }
-}
-
-void GetTargetNetworkInfoFromProvResource(char *name, char *pass)
-{
- if (name != NULL && pass != NULL)
- {
- OICStrcpy(name, MAXSSIDLEN, gProvResource.tnn);
- OICStrcpy(pass, MAXNETCREDLEN, gProvResource.cd);
- }
-}
-
-OCStackResult CreateProvisioningResource(bool isSecured)
-{
- gProvResource.ps = ES_PS_NEED_PROVISIONING;
- gProvResource.tr = ES_PS_TRIGGER_INIT_VALUE;
-
- gProvResource.tnt = CT_ADAPTER_IP;
- OICStrcpy(gProvResource.tnn, sizeof(gProvResource.tnn), "Unknown");
- OICStrcpy(gProvResource.cd, sizeof(gProvResource.cd), "Unknown");
-
- OCStackResult res = OC_STACK_ERROR;
- if (isSecured)
- {
- res = OCCreateResource(&gProvResource.handle, OC_RSRVD_ES_PROV_RES_TYPE,
- OC_RSRVD_INTERFACE_DEFAULT,
- OC_RSRVD_ES_URI_PROV, OCEntityHandlerCb,
- NULL, OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE);
- }
- else
- {
- res = OCCreateResource(&gProvResource.handle, OC_RSRVD_ES_PROV_RES_TYPE,
- OC_RSRVD_INTERFACE_DEFAULT,
- OC_RSRVD_ES_URI_PROV, OCEntityHandlerCb,
- NULL, OC_DISCOVERABLE | OC_OBSERVABLE);
- }
-
- OIC_LOG_V(INFO, ES_RH_TAG, "Created Prov resource with result: %s", getResult(res));
- return res;
-}
-
-OCStackResult DeleteProvisioningResource()
-{
- OCStackResult res = OCDeleteResource(gProvResource.handle);
- if (res != OC_STACK_OK)
- {
- OIC_LOG_V(INFO, ES_RH_TAG, "Deleting Prov resource error with result: %s", getResult(res));
- }
-
- return res;
-}
-
-OCEntityHandlerResult ProcessGetRequest(OCEntityHandlerRequest *ehRequest, OCRepPayload **payload)
-{
- OCEntityHandlerResult ehResult = OC_EH_ERROR;
- if (!ehRequest)
- {
- OIC_LOG(ERROR, ES_RH_TAG, "Request is Null");
- return ehResult;
- }
- if (ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
- {
- OIC_LOG(ERROR, ES_RH_TAG, "Incoming payload not a representation");
- return ehResult;
- }
-
- OCRepPayload *getResp = constructResponse(ehRequest);
- if (!getResp)
- {
- OIC_LOG(ERROR, ES_RH_TAG, "constructResponse failed");
- return OC_EH_ERROR;
- }
-
- *payload = getResp;
- ehResult = OC_EH_OK;
-
- return ehResult;
-}
-
-OCEntityHandlerResult ProcessPostRequest(OCEntityHandlerRequest *ehRequest, OCRepPayload** payload)
-{
- OIC_LOG(INFO, ES_RH_TAG, "ProcessPostRequest enter");
- OCEntityHandlerResult ehResult = OC_EH_ERROR;
- if (ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
- {
- OIC_LOG(ERROR, ES_RH_TAG, "Incoming payload not a representation");
- return ehResult;
- }
-
- OCRepPayload* input = (OCRepPayload*) (ehRequest->payload);
- if (!input)
- {
- OIC_LOG(ERROR, ES_RH_TAG, "Failed to parse");
- return ehResult;
- }
-
- char* tnn;
- if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_TNN, &tnn))
- {
- OICStrcpy(gProvResource.tnn, sizeof(gProvResource.tnn), tnn);
- OIC_LOG_V(INFO, ES_RH_TAG, "gProvResource.tnn %s", gProvResource.tnn);
-
- gProvResource.ps = ES_PS_PROVISIONING_COMPLETED;
- }
-
- char* cd;
- if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_CD, &cd))
- {
- OICStrcpy(gProvResource.cd, sizeof(gProvResource.cd), cd);
- OIC_LOG_V(INFO, ES_RH_TAG, "gProvResource.cd %s", gProvResource.cd);
- }
-
- OIC_LOG_V(INFO, ES_RH_TAG, "gProvResource.ps %lld", gProvResource.ps);
-
- int64_t tr;
- if (OCRepPayloadGetPropInt(input, OC_RSRVD_ES_TR, &tr))
- {
- // Triggering
- gProvResource.tr = tr;
- }
-
- //ES_PS_PROVISIONING_COMPLETED state indicates that already provisioning is completed.
- // A new request for provisioning means overriding existing network provisioning information.
- if (gProvResource.ps == ES_PS_PROVISIONING_COMPLETED && tr == ES_PS_TRIGGER_CONNECTION)
- {
- OIC_LOG(DEBUG, ES_RH_TAG, "Provisioning already completed."
- "Tiggering the network connection");
-
- if (gNetworkInfoProvEventCb)
- {
- gNetworkInfoProvEventCb(ES_RECVTRIGGEROFPROVRES);
- ehResult = OC_EH_OK;
- }
- else
- {
- gProvResource.tr = ES_PS_TRIGGER_INIT_VALUE;
- OIC_LOG(ERROR, ES_RH_TAG, "gNetworkInfoProvEventCb is NULL."
- "Network handler not registered. Failed to connect to the network");
- ehResult = OC_EH_ERROR;
- }
-
- return ehResult;
- }
- else if (gProvResource.ps == ES_PS_PROVISIONING_COMPLETED)
- {
- OIC_LOG(DEBUG, ES_RH_TAG, "Provisioning already completed. "
- "This a request to override the existing the network provisioning information");
- }
- else
- {
- OIC_LOG(DEBUG, ES_RH_TAG, "Provisioning the network information to the Enrollee.");
- }
-
- OCRepPayload *getResp = constructResponse(ehRequest);
- if (!getResp)
- {
- OIC_LOG(ERROR, ES_RH_TAG, "constructResponse failed");
- return OC_EH_ERROR;
- }
-
- *payload = getResp;
- ehResult = OC_EH_OK;
-
- return ehResult;
-}
-
-OCEntityHandlerResult ProcessPutRequest(OCEntityHandlerRequest * /*ehRequest*/,
- OCRepPayload** /*payload*/)
-{
- OCEntityHandlerResult ehResult = OC_EH_ERROR;
-
- return ehResult;
-}
-
-OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest)
-{
- OCRepPayload* payload = OCRepPayloadCreate();
- if (!payload)
- {
- OIC_LOG(ERROR, ES_RH_TAG, "Failed to allocate Payload");
- return NULL;
- }
-
- if (ehRequest->resource == gProvResource.handle)
- {
- OIC_LOG(INFO, ES_RH_TAG, "constructResponse prov res");
- OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_PROV);
- OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_PS, gProvResource.ps);
- OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_TNT, gProvResource.tnt);
- }
- else if (ehRequest->requestHandle == gNetResource.handle)
- {
-
- OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_NET);
- OCRepPayloadSetPropInt(payload, "ant", gNetResource.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, 0, OC_EH_ERROR, 0, 0,
- { },
- { 0 }, false };
- OCRepPayload* payload = NULL;
-
- if (entityHandlerRequest && (flag & OC_REQUEST_FLAG))
- {
- if (OC_REST_GET == entityHandlerRequest->method)
- {
- OIC_LOG(INFO, ES_RH_TAG, "Received GET request");
- ehRet = ProcessGetRequest(entityHandlerRequest, &payload);
- }
- else if (OC_REST_PUT == entityHandlerRequest->method)
- {
- OIC_LOG(INFO, ES_RH_TAG, "Received PUT request");
-
- //PUT request will be handled in the internal implementation
- if (gProvResource.handle != NULL
- && entityHandlerRequest->resource == gProvResource.handle)
- {
- ehRet = ProcessPutRequest(entityHandlerRequest, &payload);
- }
- else
- {
- OIC_LOG(ERROR, ES_RH_TAG, "Cannot process put");
- ehRet = OC_EH_ERROR;
- }
- }
- else if (OC_REST_POST == entityHandlerRequest->method)
- {
- OIC_LOG(INFO, ES_RH_TAG, "Received OC_REST_POST from client");
- if (gProvResource.handle != NULL
- && entityHandlerRequest->resource == gProvResource.handle)
- {
- ehRet = ProcessPostRequest(entityHandlerRequest, &payload);
- }
- else
- {
- OIC_LOG(ERROR, ES_RH_TAG, "Cannot process put");
- ehRet = OC_EH_ERROR;
- }
- }
-
- 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)
- {
- OIC_LOG(ERROR, ES_RH_TAG, "Error sending response");
- ehRet = OC_EH_ERROR;
- }
- }
- }
-
- 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
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-/**
- * These are adapter APIs will make caller modules agnostic to platform.
- */
-
-#include "softapnative.h"
-#include "easysetup.h"
-#include "softap.h"
-#include "networkhandler.h"
-
-void ESCreateSoftapCallback(int result, const char *ip, const char* mac_addr,
- const char* device_name );
-
-ESEnrolleeNetworkEventCallback gCallback;
-
-/**
- * It will return Device which is creating Soft AP.
- * i.e.Enrollee or Mediator.
- * This decesion is based on, what is the value set for ES_SOFTAP_MODE in build command as well as
- * in iotivity.spec file.
- */
-DeviceRole ESSoftapHost()
-{
-#ifdef ENROLLEE_SOFTAP
- //SoftAp at enrollee
- return ENROLLEE;
-#else
- //SoftAp at mediator
- return MEDIATOR;
-#endif
-}
-
-/**
- * It will return true if the Soft AP is created at Enrollee device
- */
-bool ESSoftapAtEnrollee()
-{
- return ( ESSoftapHost() == ENROLLEE) ? true : false;
-}
-
-/**
- * It will return true if the Soft AP is created at Mediator device
- */
-bool ESSoftapAtMediator()
-{
- return (ESSoftapHost() == MEDIATOR) ? true : false;
-}
-
-/**
- * This API will map result returned from the native to the caller.
- * Callback API's signature needs to be modified under build switch according
- * to the underline platform.
- */
-void ESCreateSoftapCallback(int result, const char *ip, const char* mac_addr,
- const char* device_name)
-{
- if(SOFTAP_SUCCESS == result) //on Success
- {
- gCallback(ES_OK);
- }
- else //on Failure
- {
- gCallback(ES_ERROR);
- }
-}
-
-/**
- * This API will create the softap at enrollee
- */
-void ESCreateSoftap(const char * ssid, const char* passwd, ESEnrolleeNetworkEventCallback cb)
-{
- gCallback = cb;
-
- // TODO: To be implemented
- // Create Soft AP through native APIs -- start
- // native API call by and pass ESCreateSoftapCallback() as callback
- ESCreateSoftapNative(ssid, passwd,ESCreateSoftapCallback);
- // Create Soft AP through native APIs -- end
-}
-
+++ /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 "networkhandler.h"
-
-// Arduino WiFi Shield includes
-#include <SPI.h>
-#include <WiFi.h>
-#include <WiFiUdp.h>
-
-#include <string.h>
-
-#include "logger.h"
-
-/**
- * @var ES_NH_TAG
- * @brief Logging tag for module name.
- */
-#define ES_NH_TAG "ES_NH"
-
-//-----------------------------------------------------------------------------
-// Defines
-//-----------------------------------------------------------------------------
-/**
- * ES_MAX_NETWORK_RETRY sets the default number of retry count for network connection.
- */
-#define ES_MAX_NETWORK_RETRY (5)
-
-//-----------------------------------------------------------------------------
-// Private variables
-//-----------------------------------------------------------------------------
-static IPAddress enrolleeIP;
-
-/**
- * @var g_retryCounter
- * @brief Retry counter for cancelling network retry. Currently network retry is
- * limited to 5 attempts
- */
-static uint16_t g_retryCounter = 0;
-
-
-
-//-----------------------------------------------------------------------------
-// Private internal function prototypes
-//-----------------------------------------------------------------------------
-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";
-
-ESResult ConnectToWiFiNetwork(const char *ssid, const char *pass,
- ESEnrolleeNetworkEventCallback cb)
-{
- char *fwVersion;
- int status = WL_IDLE_STATUS;
- int res;
-
- // check for the presence of the shield:
- if (WiFi.status() == WL_NO_SHIELD)
- {
- OIC_LOG(ERROR, ES_NH_TAG, "WiFi shield not present");
- return ES_ERROR;
- }
-
- // Verify that WiFi Shield is running the firmware with all UDP fixes
- fwVersion = WiFi.firmwareVersion();
- OIC_LOG_V(INFO, ES_NH_TAG, "WiFi Shield Firmware version %s", fwVersion);
- if (strncmp(fwVersion, ARDUINO_WIFI_SHIELD_UDP_FW_VER, sizeof(ARDUINO_WIFI_SHIELD_UDP_FW_VER))
- != 0)
- {
- OIC_LOG(DEBUG, ES_NH_TAG, "!!!!! Upgrade WiFi Shield Firmware version !!!!!!");
- return ES_ERROR;
- }
-
- //Retry counter is reset everytime the ConnectToWiFiNetwork is invoked
- g_retryCounter = 0;
-
- OIC_LOG_V(INFO, ES_NH_TAG, "Finding SSID: %s", ssid);
-
- while ((findNetwork(ssid) == 0) && g_retryCounter < ES_MAX_NETWORK_RETRY) // found
- {
- delay(1000);
- g_retryCounter++;
- }
-
- if(g_retryCounter == ES_MAX_NETWORK_RETRY){
- OIC_LOG_V(ERROR, ES_NH_TAG, "Connection to network failed after %d attempts",
- g_retryCounter);
- return ES_ERROR;
- }
-
- if (cb != NULL)
- {
- cb(ES_OK);
- }
-
- if (WiFi.status() == WL_CONNECTED)
- WiFi.disconnect();
-
- //Retry counter is reset everytime the ConnectToWiFiNetwork is invoked
- g_retryCounter = 0;
-
- 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 && g_retryCounter < ES_MAX_NETWORK_RETRY)
- {
- OIC_LOG_V(INFO, ES_NH_TAG, "Attempting to connect to SSID: %s", ssid);
-
- status = WiFi.begin((char *) ssid, (char *) pass);
-
- // wait 10 seconds for connection:
- delay(10000);
-
- g_retryCounter++;
- }
-
- if(g_retryCounter == ES_MAX_NETWORK_RETRY){
- OIC_LOG_V(ERROR, ES_NH_TAG, "Connection to network failed after %d attempts",
- g_retryCounter);
- return ES_ERROR;
- }
-
- OIC_LOG(DEBUG, ES_NH_TAG, "Connected to wifi");
-
- enrolleeIP = WiFi.localIP();
- OIC_LOG_V(INFO, ES_NH_TAG, "IP Address: %d.%d.%d.%d", enrolleeIP[0], enrolleeIP[1],
- enrolleeIP[2], enrolleeIP[3]);
-
- char buf[50];
- sprintf(buf, "IP Address: %d.%d.%d.%d", enrolleeIP[0], enrolleeIP[1],
- enrolleeIP[2], enrolleeIP[3]);
- Serial.println(buf);
-
- return 0;
-}
-
-ESResult getCurrentNetworkInfo(OCConnectivityType targetType, NetworkInfo *info)
-{
- if (targetType == CT_ADAPTER_IP && WiFi.status() == WL_CONNECTED)
- {
- info->type = CT_ADAPTER_IP;
- info->ipaddr = WiFi.localIP();
- if((sizeof(info->ssid) >= MAXSSIDLEN) && (strlen(WiFi.SSID()) <= MAXSSIDLEN))
- {
- strcpy(info->ssid, WiFi.SSID());
- return ES_OK;
- }
- else
- {
- return ES_ERROR;
- }
- }
-
- return ES_ERROR;
-}
-
-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 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
- *
- * This file contains IP network handling functionality for Enrollee device
- */
-
-#ifndef ES_NETWORK_HANDLER_H_
-#define ES_NETWORK_HANDLER_H_
-
-// Do not remove the include below
-#include "Arduino.h"
-
-// Arduino WiFi Shield includes
-#include <SPI.h>
-#include <WiFi.h>
-#include <WiFiUdp.h>
-
-#include <string.h>
-#include "logger.h"
-#include "escommon.h"
-
-#define MAXSSIDLEN 33
-#define MAXNETCREDLEN 20
-#define MAXNUMTYPE 5
-#define MAXADDRLEN 15
-
-/*
- * Callback function for updating the Network status to the subscribers
- *
- * @param esResult ESResult provides the current state of the network connection status
- */
-typedef void (*ESEnrolleeNetworkEventCallback)(ESResult esResult);
-
-typedef struct
-{
- OCConnectivityType type;
- // for WiFI
- IPAddress ipaddr;
- char ssid[MAXSSIDLEN];
- // for BT, BLE
- byte mac[6];
-} NetworkInfo;
-
-ESResult ConnectToWiFiNetwork(const char *ssid, const char *pass,
- ESEnrolleeNetworkEventCallback);
-ESResult getCurrentNetworkInfo(OCConnectivityType targetType, NetworkInfo *info);
-
-#endif
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 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_ENROLLEE_COMMON_H_
+#define ES_ENROLLEE_COMMON_H_
+
+#include "ocstack.h"
+#include "octypes.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @brief Data structure delivered from mediator, which provides WiFi information
+ */
+typedef struct
+{
+ char ssid[MAX_SSIDLEN]; /**< Ssid of the Enroller**/
+ char pwd[MAX_CREDLEN]; /**< Pwd of the Enroller**/
+ WIFI_AUTHTYPE authtype; /**< Auth type of the Enroller**/
+ WIFI_ENCTYPE enctype; /**< Encryption type of the Enroller**/
+ void *userdata; /**< Vender-specific data**/
+} ESWiFiProvData;
+
+/**
+ * @brief Data structure delivered from mediator, which provides device configuration information
+ */
+typedef struct
+{
+ char language[OIC_STRING_MAX_VALUE]; /**< IETF language tag using ISO 639X **/
+ char country[OIC_STRING_MAX_VALUE]; /**< ISO Country Code (ISO 3166-1 Alpha-2) **/
+ void *userdata; /**< Vender-specific data**/
+} ESDevConfProvData;
+
+/**
+ * @brief Data structure delivered from mediator, which provides Cloud server information
+ */
+typedef struct
+{
+ char authCode[OIC_STRING_MAX_VALUE]; /**< Auth code issued by OAuth2.0-compatible account server **/
+ char authProvider[OIC_STRING_MAX_VALUE]; /**< Auth provider ID **/
+ char ciServer[OIC_STRING_MAX_VALUE]; /**< Cloud interface server URL which an Enrollee is going to registered **/
+ void *userdata; /**< Vender-specific data**/
+} ESCloudProvData;
+
+/**
+ * @brief Data structure stored for Device property which includes a WiFi and device configuration.
+ */
+typedef struct
+{
+ /**
+ * @brief Data structure indicating WiFi configuration of Enrollee
+ */
+ struct
+ {
+ WIFI_MODE mode[NUM_WIFIMODE];
+ WIFI_FREQ freq;
+ } WiFi;
+
+ /**
+ * @brief Data structure indicating device configuration of Enrollee
+ */
+ struct
+ {
+ char deviceName[MAX_DEVICELEN];
+ } DevConf;
+} ESDeviceProperty;
+
+/**
+ * A set of functions pointers for callback functions which are called after provisioning data is
+ * received from Mediator.
+ */
+typedef struct
+{
+ void (*WiFiProvCb) (ESWiFiProvData *);
+ void (*DevConfProvCb) (ESDevConfProvData *);
+ void (*CloudDataProvCb) (ESCloudProvData *);
+} ESProvisioningCallbacks;
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //ES_ENROLLEE_COMMON_H_
+
#define EASYSETUP_ENROLLEE_H__
#include "escommon.h"
+#include "ESEnrolleeCommon.h"
/**
* @file
extern "C" {
#endif // __cplusplus
-/*
- * Callback function for updating the Enrollee OnBoarding and Provisioning status result
- * to the application
- *
- * @param esResult ESResult provides the current state of the Enrollee Device
+/**
+ * A function pointer for registering a user-defined function to set user-specific properties to a
+ * response going back to a client.
+ * @param payload Represents a response. You can set a specific value with specific property key
+ * to the payload. If a client receives the response and know the property key, then it can
+ * extract the value.
+ * @param resourceType Used to distinguish which resource the received property belongs to.
+ */
+typedef void (*ESWriteUserdataCb)(OCRepPayload* payload, char* resourceType);
+
+/**
+ * A function pointer for registering a user-defined function to parse user-specific properties from
+ * received POST request.
+ * @param payload Represents a received POST request. If you know user-specific property key,
+ * then you can extract a corresponding value if it exists.
+ * @param resourceType Used to distinguish which resource the received property belongs to
+ * @param userdata User-specific data you want to deliver to desired users, i.e. application.
+ * The user should know a data structure of passed userdata.
*/
-typedef void (*ESEnrolleeEventCallback)(ESResult esResult, ESEnrolleeState enrolleeState);
+typedef void (*ESReadUserdataCb)(OCRepPayload* payload, char* resourceType, void** userdata);
/**
* This function Initializes the EasySetup. This API must be called prior to invoking any other API
*
- * @param networkType NetworkType on which OnBoarding has to be performed.
- * @param ssid SSID of the target SoftAP network to which the Enrollee is connecting.
- * @param passwd Password of the target SoftAP network to which the Enrollee is
- * connecting
* @param isSecured True if the Enrollee is operating in secured mode.
- * @param eventCallback ESEnrolleeEventCallback for for updating the Enrollee OnBoarding status
- * result to the application
+ * @param resourceMask Provisining Resource Type which application wants to make.
+ * ES_WIFI_RESOURCE = 0x01,
+ * ES_CLOUD_RESOURCE = 0x02,
+ * ES_DEVCONF_RESOURCE = 0x04
+ * @param callbacks ESProvisioningCallbacks for updating Provisioning Resources' data to the application
* @return ::ES_OK on success, some other value upon failure.
*/
-ESResult ESInitEnrollee(OCConnectivityType networkType, const char *ssid, const char *passwd,
- bool isSecured, ESEnrolleeEventCallback eventCallback);
+ESResult ESInitEnrollee(bool isSecured, ESResourceMask resourceMask, ESProvisioningCallbacks callbacks);
+
/**
- * This function performs initialization of Provisioning and Network resources needed for EasySetup
- * process.
+ * This function Sets Device Information.
+ *
+ * @param deviceProperty Contains device information composed of WiFi Structure & DevConf Structure
* @return ::ES_OK on success, some other value upon failure.
+ *
+ * @see ESDeviceProperty
*/
-ESResult ESInitProvisioning();
+ESResult ESSetDeviceProperty(ESDeviceProperty *deviceProperty);
+
+
+/**
+ * This function Sets Enrollee's State.
+ *
+ * @param esState Contains current enrollee's state.
+ * @return ::ES_OK on success, some other value upon failure.
+ *
+ * @see ESEnrolleeState
+ */
+ESResult ESSetState(ESEnrolleeState esState);
+
+
+/**
+ * This function Sets Enrollee's Error Code.
+ *
+ * @param esErrCode Contains enrollee's error code.
+ * @return ::ES_OK on success, some other value upon failure.
+ *
+ * @see ESErrorCode
+ */
+ESResult ESSetErrorCode(ESErrorCode esErrCode);
/**
* This function performs termination of Provisioning and Network resources.
*/
ESResult ESTerminateEnrollee();
+/**
+ * This function is to set two function pointer to handle user-specific properties in in-comming
+ * POST request and to out-going response for GET or POST request.
+ * If you register certain functions with this API, you have to handle OCRepPayload structure to
+ * set and get properties you want.
+ *
+ * @param readCb a callback for parsing properties from POST request
+ * @param writeCb a callback for putting properties to a response to be sent
+ *
+ * @return ::ES_OK on success, some other value upon failure.
+ *
+ * @see ESReadUserdataCb
+ * @see ESWriteUserdataCb
+ */
+ESResult ESSetCallbackForUserdata(ESReadUserdataCb readCb, ESWriteUserdataCb writeCb);
+
#ifdef __cplusplus
}
#endif // __cplusplus
+++ /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 "networkhandler.h"
-
-#include <unistd.h>
-
-#include "logger.h"
-#include "easysetup.h"
-#include "oic_string.h"
-
-#define LOG_TAG "LINUX ES"
-
-const char *gSsid = "DLNA_LISMORE1";
-const char *gPass = "dlna@010203";
-char *gIpAddress;
-ESEnrolleeNetworkEventCallback gNetworkEventCb;
-
-/*
- * All the functions defined in this file are stub functions to be implemented by the end user of
- * Easysetup Enrollee applications.
- */
-static void ESActivateWifi()
-{
-
-}
-
-static void start()
-{
- OIC_LOG(INFO, LOG_TAG, "START");
- ESActivateWifi();
-}
-
-void ConnectToWiFiNetwork(const char *ssid, const char *pass,
- ESEnrolleeNetworkEventCallback cb)
-{
- OIC_LOG_V(INFO, LOG_TAG, "ConnectToWiFiNetwork %s %s",ssid,pass);
- gPass = pass;
- gSsid = ssid;
- gNetworkEventCb = cb;
- start();
-}
-
-ESResult getCurrentNetworkInfo(OCConnectivityType targetType, NetworkInfo *info)
-{
- if (targetType == CT_ADAPTER_IP)
- {
- info->type = CT_ADAPTER_IP;
- info->ipaddr = gIpAddress;
- if (strlen(gSsid) <= MAXSSIDLEN)
- {
- OICStrcpy(info->ssid, sizeof(info->ssid), gSsid);
- return ES_OK;
- }
- else
- {
- return ES_ERROR;
- }
- }
-
- return ES_ERROR;
-}
-
+++ /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
- *
- * This file contains IP network handling functionality for Enrollee device
- */
-
-#ifndef ES_NETWORK_HANDLER_H_
-#define ES_NETWORK_HANDLER_H_
-
-
-#include <string.h>
-#include "easysetup.h"
-#include "logger.h"
-#include "escommon.h"
-
-#define MAXSSIDLEN 33
-#define MAXNETCREDLEN 20
-#define MAXNUMTYPE 5
-#define MAXADDRLEN 15
-
-/*
- * Callback function for updating the Network status to the subscribers
- *
- * @param esResult ESResult provides the current state of the network connection status
- */
-typedef void (*ESEnrolleeNetworkEventCallback)(ESResult esResult);
-
-typedef struct
-{
- OCConnectivityType type;
- // for WiFI
- //IPAddress ipaddr;
- char *ipaddr;
- char ssid[MAXSSIDLEN];
- // for BT, BLE
- //byte mac[6];
-} NetworkInfo;
-
-void ConnectToWiFiNetwork(const char *ssid, const char *pass,
- ESEnrolleeNetworkEventCallback);
-ESResult getCurrentNetworkInfo(OCConnectivityType targetType, NetworkInfo *info);
-
-#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 "softapnative.h"
-
-/**
- * This API will create the Soft AP at Enrollee device.
- */
-void ESCreateSoftapNative(const char * ssid, const char* passwd, SoftAPCallbackNative cb)
-{
- const char *ip, *macaddr, *devicename;
-
- // Soft is created successfully. This callback may be send from other cascaded callbacks
- cb(SOFTAP_SUCCESS, ip, macaddr, devicename);
-
- // TODO: Use below code to indicate failed on-boarding / softap creation
- // Soft creation is failed. This callback may be send from other cascaded callbacks
- //cb(SOFTAP_FAILED, nullptr,nullptr,nullptr);
-}
-
*/
#include "easysetup.h"
-#include "softap.h"
-#include "onboarding.h"
#include "logger.h"
#include "resourcehandler.h"
-#include "easysetupcallbacks.h"
+#include "oic_string.h"
/**
* @var ES_ENROLLEE_TAG
// Private variables
//-----------------------------------------------------------------------------
-/**
- * @var gTargetSsid
- * @brief Target SSID of the Soft Access point to which the device has to connect
- */
-static char gTargetSsid[MAXSSIDLEN];
+static bool gIsSecured = false;
-/**
- * @var gTargetPass
- * @brief Password of the target access point to which the device has to connect
- */
-static char gTargetPass[MAXNETCREDLEN];
+static ESProvisioningCallbacks gESProvisioningCb;
+static ESDeviceProperty gESDeviceProperty;
-/**
- * @var gEnrolleeStatusCb
- * @brief Fucntion pointer holding the callback for intimation of EasySetup Enrollee status callback
- */
-static ESEnrolleeEventCallback gEnrolleeStatusCb = NULL;
+void ESWiFiRsrcCallback(ESResult esResult, ESWiFiProvData *eventData)
+{
+ OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "ESWiFiRsrcCallback IN");
-/**
- * @var gIsSecured
- * @brief Variable to check if secure mode is enabled or not.
- */
-static bool gIsSecured = false;
+ if(esResult != ES_OK)
+ {
+ OIC_LOG_V(ERROR, ES_ENROLLEE_TAG, "ESWiFiRsrcCallback Error Occured");
+ return;
+ }
-void ESOnboardingCallback(ESResult esResult)
-{
- OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "ESOnboardingCallback with result = %d", esResult);
- if(esResult == ES_OK)
- {
- gEnrolleeStatusCb(esResult, ES_ON_BOARDED_STATE);
- }
- else
- {
- OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG,
- "Onboarding is failed callback result is = %d", esResult);
- gEnrolleeStatusCb(esResult, ES_INIT_STATE);
- }
+ // deliver data to ESProvisioningCallbacks
+ if(gESProvisioningCb.WiFiProvCb != NULL)
+ {
+ gESProvisioningCb.WiFiProvCb(eventData);
+ }
+ else
+ {
+ OIC_LOG_V(ERROR, ES_ENROLLEE_TAG, "WiFiProvCb is NULL");
+ return;
+ }
}
-void ESProvisioningCallback(ESResult esResult)
+void ESCloudRsrcCallback(ESResult esResult, ESCloudProvData *eventData)
{
- OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "ESProvisioningCallback with result = %d", esResult);
+ OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "ESCloudRsrcCallback IN");
- if (esResult == ES_RECVTRIGGEROFPROVRES)
+ if(esResult != ES_OK)
{
- GetTargetNetworkInfoFromProvResource(gTargetSsid, gTargetPass);
- gEnrolleeStatusCb(ES_OK, ES_PROVISIONED_STATE);
- OIC_LOG(DEBUG, ES_ENROLLEE_TAG, "Connecting with target network");
+ OIC_LOG_V(ERROR, ES_ENROLLEE_TAG, "ESCloudRsrcCallback Error Occured");
+ return;
+ }
- // Connecting/onboarding to target network
- ConnectToWiFiNetwork(gTargetSsid, gTargetPass, ESOnboardingCallbackTargetNet);
+ if(gESProvisioningCb.CloudDataProvCb != NULL)
+ {
+ gESProvisioningCb.CloudDataProvCb(eventData);
}
else
{
- OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "Provisioning is failed callback result is = %d", esResult);
- // Resetting Enrollee to ONBOARDED_STATE as Enrollee is alreday onboarded in previous step
- gEnrolleeStatusCb(ES_OK, ES_ON_BOARDED_STATE);
+ OIC_LOG_V(ERROR, ES_ENROLLEE_TAG, "CloudDataProvCb is NULL");
+ return;
}
}
-void ESOnboardingCallbackTargetNet(ESResult esResult)
+void ESDevconfRsrcallback(ESResult esResult, ESDevConfProvData *eventData)
{
- OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "ESOnboardingCallback on target network with result = %d",
- esResult);
- if(esResult == ES_OK)
+ OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "ESDevconfRsrcallback IN");
+
+ if(esResult != ES_OK)
{
- gEnrolleeStatusCb(esResult, ES_ON_BOARDED_TARGET_NETWORK_STATE);
+ OIC_LOG_V(ERROR, ES_ENROLLEE_TAG, "ESDevconfRsrcallback Error Occured");
+ return;
+ }
+
+ if(gESProvisioningCb.DevConfProvCb != NULL)
+ {
+ gESProvisioningCb.DevConfProvCb(eventData);
}
else
{
- OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG,
- "Onboarding is failed on target network and callback result is = %d", esResult);
- // Resetting Enrollee state to the ES_PROVISIONED_STATE
- // as device is already being provisioned with target network creds.
- gEnrolleeStatusCb(esResult, ES_PROVISIONED_STATE);
+ OIC_LOG_V(ERROR, ES_ENROLLEE_TAG, "DevConfProvCb is NULL");
+ return;
}
}
-ESResult ESInitEnrollee(OCConnectivityType networkType, const char *ssid, const char *passwd,
- bool isSecured,
- ESEnrolleeEventCallback cb)
+ESResult ESInitEnrollee(bool isSecured, ESResourceMask resourceMask, ESProvisioningCallbacks callbacks)
{
OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitEnrollee IN");
- if(!ESEnrolleeValidateParam(networkType,ssid,passwd,cb))
+
+ gIsSecured = isSecured;
+
+ if((resourceMask & ES_WIFI_RESOURCE) == ES_WIFI_RESOURCE)
{
- OIC_LOG(ERROR, ES_ENROLLEE_TAG,
- "ESInitEnrollee::Stopping Easy setup due to invalid parameters");
- return ES_ERROR;
+ if(callbacks.WiFiProvCb != NULL)
+ {
+ gESProvisioningCb.WiFiProvCb = callbacks.WiFiProvCb;
+ RegisterWifiRsrcEventCallBack(ESWiFiRsrcCallback);
+ }
+ else
+ {
+ OIC_LOG(ERROR, ES_ENROLLEE_TAG, "WiFiProvCb NULL");
+ return ES_ERROR;
+ }
+ }
+ if((resourceMask & ES_DEVCONF_RESOURCE) == ES_DEVCONF_RESOURCE)
+ {
+ if(callbacks.DevConfProvCb != NULL)
+ {
+ gESProvisioningCb.DevConfProvCb = callbacks.DevConfProvCb;
+ RegisterDevConfRsrcEventCallBack(ESDevconfRsrcallback);
+ }
+ else
+ {
+ OIC_LOG(ERROR, ES_ENROLLEE_TAG, "DevConfProvCb NULL");
+ return ES_ERROR;
+ }
+ }
+ if((resourceMask & ES_CLOUD_RESOURCE) == ES_CLOUD_RESOURCE)
+ {
+ if(callbacks.CloudDataProvCb != NULL)
+ {
+ gESProvisioningCb.CloudDataProvCb = callbacks.CloudDataProvCb;
+ RegisterCloudRsrcEventCallBack(ESCloudRsrcCallback);
+ }
+ else
+ {
+ OIC_LOG(ERROR, ES_ENROLLEE_TAG, "CloudDataProvCb NULL");
+ return ES_ERROR;
+ }
}
- //Init callback
- gEnrolleeStatusCb = cb;
+ if(CreateEasySetupResources(gIsSecured, resourceMask) != OC_STACK_OK)
+ {
+ UnRegisterResourceEventCallBack();
- gIsSecured = isSecured;
+ if (DeleteEasySetupResources() != OC_STACK_OK)
+ {
+ OIC_LOG(ERROR, ES_ENROLLEE_TAG, "Deleting prov resource error!!");
+ }
+
+ return ES_ERROR;
+ }
- // TODO : This onboarding state has to be set by lower layer, as they better
- // knows when actually on-boarding started.
- cb(ES_ERROR,ES_ON_BOARDING_STATE);
- OIC_LOG(INFO, ES_ENROLLEE_TAG, "received callback");
- OIC_LOG(INFO, ES_ENROLLEE_TAG, "onboarding now..");
+ OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitEnrollee OUT");
+ return ES_OK;
+}
- if(!ESOnboard(ssid, passwd, ESOnboardingCallback))
+ESResult ESSetDeviceProperty(ESDeviceProperty *deviceProperty)
+{
+ OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESSetDeviceProperty IN");
+
+ if(SetDeviceProperty(deviceProperty) != OC_STACK_OK)
{
- OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESInitEnrollee::On-boarding failed");
- cb(ES_ERROR, ES_INIT_STATE);
+ OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESSetDeviceProperty Error");
return ES_ERROR;
}
- OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitEnrollee OUT");
+ int modeIdx = 0;
+ while((deviceProperty->WiFi).mode[modeIdx] != WiFi_EOF)
+ {
+ (gESDeviceProperty.WiFi).mode[modeIdx] = (deviceProperty->WiFi).mode[modeIdx];
+ OIC_LOG_V(INFO, ES_ENROLLEE_TAG, "WiFi Mode : %d", (gESDeviceProperty.WiFi).mode[modeIdx]);
+ modeIdx ++;
+ }
+ (gESDeviceProperty.WiFi).freq = (deviceProperty->WiFi).freq;
+ OIC_LOG_V(INFO, ES_ENROLLEE_TAG, "WiFi Freq : %d", (gESDeviceProperty.WiFi).freq);
+
+ OICStrcpy((gESDeviceProperty.DevConf).deviceName, MAX_DEVICELEN, (deviceProperty->DevConf).deviceName);
+ OIC_LOG_V(INFO, ES_ENROLLEE_TAG, "Device Name : %s", (gESDeviceProperty.DevConf).deviceName);
+
+ OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESSetDeviceProperty OUT");
return ES_OK;
}
-ESResult ESTerminateEnrollee()
+ESResult ESSetState(ESEnrolleeState esState)
{
- UnRegisterResourceEventCallBack();
+ OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESSetState IN");
- //Delete Prov resource
- if (DeleteProvisioningResource() != OC_STACK_OK)
+ if(esState < ES_STATE_INIT || esState > ES_STATE_REGISTRRED_FAIL_TO_CLOUD)
{
- OIC_LOG(ERROR, ES_ENROLLEE_TAG, "Deleting prov resource error!!");
+ OIC_LOG_V(ERROR, ES_ENROLLEE_TAG, "Invalid ESEnrolleeState : %d", esState);
return ES_ERROR;
}
- OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESTerminateEnrollee success");
+ if(SetEnrolleeState(esState) != OC_STACK_OK)
+ {
+ OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESSetState ES_ERROR");
+ return ES_ERROR;
+ }
+
+ OIC_LOG_V(INFO, ES_ENROLLEE_TAG, "Set ESState succesfully : %d", esState);
+ OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESSetState OUT");
return ES_OK;
}
-ESResult ESInitProvisioning()
+ESResult ESSetErrorCode(ESErrorCode esErrCode)
{
- OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitProvisioning <<IN>>");
+ OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESSetErrorCode IN");
- if (CreateProvisioningResource(gIsSecured) != OC_STACK_OK)
+ if(esErrCode < ES_ERRCODE_NO_ERROR || esErrCode > ES_ERRCODE_UNKNOWN)
{
- OIC_LOG(ERROR, ES_ENROLLEE_TAG, "CreateProvisioningResource error");
- return ES_ERROR;
+ OIC_LOG_V(ERROR, ES_ENROLLEE_TAG, "Invalid ESSetErrorCode : %d", esErrCode);
+ return ES_ERROR;
}
- RegisterResourceEventCallBack(ESProvisioningCallback);
+ if(SetEnrolleeErrCode(esErrCode) != OC_STACK_OK)
+ {
+ OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESSetErrorCode ES_ERROR");
+ return ES_ERROR;
+ }
- OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitProvisioning <<OUT>>");
- return ES_RESOURCECREATED;
+ OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "Set ESErrorCode succesfully : %d", esErrCode);
+ OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESSetErrorCode OUT");
+ return ES_OK;
}
-static bool ESEnrolleeValidateParam(OCConnectivityType networkType, const char *ssid,
- const char *passwd, ESEnrolleeEventCallback cb)
+ESResult ESTerminateEnrollee()
{
- if (!ssid || !passwd || !cb)
+ OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESTerminateEnrollee IN");
+
+ UnRegisterResourceEventCallBack();
+
+ //Delete Prov resource
+ if (DeleteEasySetupResources() != OC_STACK_OK)
{
- OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESEnrolleeValidateParam - Invalid parameters");
- return false;
+ OIC_LOG(ERROR, ES_ENROLLEE_TAG, "Deleting prov resource error!!");
+ return ES_ERROR;
}
- return true;
+
+ OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESTerminateEnrollee success");
+ return ES_OK;
}
+ESResult ESSetCallbackForUserdata(ESReadUserdataCb readCb, ESWriteUserdataCb writeCb)
+{
+ if(!readCb && !writeCb)
+ {
+ OIC_LOG(INFO, ES_ENROLLEE_TAG, "Both of callbacks for user data are null");
+ return ES_ERROR;
+ }
+
+ SetCallbackForUserData(readCb, writeCb);
+ return ES_OK;
+}
\ No newline at end of file
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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
- *
- * This file contains private internal callback function
- * prototypes for Easy setup [Enrollee]
- */
-
-#ifndef EASYSETUP_ENROLLEE_CALLBACKS_H__
-#define EASYSETUP_ENROLLEE_CALLBACKS_H__
-
-#include "escommon.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif // __cplusplus
-
-//-----------------------------------------------------------------------------
-// Private internal callback function prototypes for Easy setup [Enrollee]
-//-----------------------------------------------------------------------------
-
- /*
- * Callback for on boarding
- */
-void ESOnboardingCallback(ESResult esResult);
-
- /*
- * Callback for provisioning
- */
-void ESProvisioningCallback(ESResult SSSS);
-
- /*
- * Callback for on boarding target Network
- */
-void ESOnboardingCallbackTargetNet(ESResult esResult);
-
- /*
- * Function for validating the parameter for ESInitEnrollee API
- */
-static bool ESEnrolleeValidateParam(OCConnectivityType networkType, const char *ssid,
- const char *passwd, ESEnrolleeEventCallback cb);
-
-#ifdef __cplusplus
-}
-#endif // __cplusplus
-
-
-#endif /* EASYSETUP_ENROLLEE_CALLBACKS_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
- *
- * This file has methods for on-boarding the Enrollee device.
- * This will contain template methods that will have core business logic & negotiation algorithm
- * on various on-boarding methods.
- */
-
-#include "easysetup.h"
-#include "softap.h"
-#include "onboarding.h"
-
-#include "logger.h"
-#include "resourcehandler.h"
-
-/**
- * @var ES_ENROLLEE_TAG
- * @brief Logging tag for module name.
- */
-#define ES_ENROLLEE_TAG "ES_SOFTAP"
-
-/**
- * It will return true on-boarding type is soft AP
- */
-bool ESSoftapOnboarding()
-{
- // TODO: To be changed based on user config. Current version, hardcoded to SoftAp onboarding
- return true;
-}
-
-/**
- * It will return true on-boarding type is BLE
- */
-bool ESBleOnboarding()
-{
- //BLE onboarding is not supported with current version.
- return false;
-}
-
-/**
- * It will do onboarding based on the user's configuration.
- */
-bool ESOnboard(const char * ssid, const char* passwd, ESEnrolleeNetworkEventCallback cb)
-{
- OIC_LOG(DEBUG, ES_ENROLLEE_TAG, "ESOnboard IN");
-
- if (ESSoftapOnboarding())
- {
- if (ESSoftapAtEnrollee())
- {
- OIC_LOG(DEBUG, ES_ENROLLEE_TAG, "Create SoftAp at enrollee");
- ESCreateSoftap(ssid, passwd, cb);
- }
- else
- {
- OIC_LOG(DEBUG, ES_ENROLLEE_TAG, "Connecting to Mediator SoftAp");
- ConnectToWiFiNetwork(ssid, passwd, cb);
- }
- return true;
- }
- else if (ESBleOnboarding())
- {
- OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESOnboard::Ble onboarding is not supported");
- // TODO:
- return false;
- }
- else
- {
- // TODO:
- OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESOnboard::Invalid onboarding option");
- return false;
- }
-}
-
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-
-#ifndef EASYSETUP_ENROLLEE_ONBOARDING_H__
-#define EASYSETUP_ENROLLEE_ONBOARDING_H__
-
-#ifdef __cplusplus
-extern "C" {
-#endif // __cplusplus:$
-
-#include "networkhandler.h"
-
-/**
- * @file
- *
- * This file contains APIs to on-board ( connect ) Enrollee device into Ad-hoc network
- * @Note : Some of the APIs of this file need to be modified by the OEM according to the
- * device configuration
- */
-
-/**
- * This function on-board Enrollee device onto ad-hoc network.
- * @param ssid SSID of the target SoftAP network to which the Enrollee
- * is connecting.
- * @param passwd Password of the target SoftAP network to which the
- * Enrollee is connecting.
- * @param ESEnrolleeNetworkEventCallback Callback function for result update
- * @return ::True, if on-boarding is successful.
- */
-
-bool ESOnboard(const char * ssid, const char* passwd, ESEnrolleeNetworkEventCallback cb);
-
-/**
- * This function verify if the on-boarding is through SoftAP.
- * @return ::True, if Soft AP on-boarding enabled.
- * @Note : This API to be modified by the OEM according to the device configuration
- */
-bool ESSoftapOnboarding();
-
-/**
- * This function verify if the on-boarding is through Ble beacons.
- * @return ::True, if Ble beacons enabled.
- * @Note : This API to be modified by the OEM according to the device configuration
- */
-bool ESBleOnboarding();
-
-#ifdef __cplusplus
-}
-#endif // __cplusplus
-
-
-#endif /* EASYSETUP_ENROLLEE_ONBOARDING_H__ */
#include "resourcehandler.h"
-#include <stdio.h>
-
#include "ocpayload.h"
#include "oic_string.h"
+#include "oic_malloc.h"
/**
* @var ES_RH_TAG
* connect to the target network
*/
static ProvResource gProvResource;
-
-/**
- * @var gNetResource
- * @brief Structure forr holding the Provisioning status of network information
- */
-static NetResource gNetResource;
+static WiFiResource gWiFiResource;
+static CloudResource gCloudResource;
+static DevConfResource gDevConfResource;
//-----------------------------------------------------------------------------
// Private internal function prototypes
//-----------------------------------------------------------------------------
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);
+void updateProvResource(OCEntityHandlerRequest* ehRequest, OCRepPayload* input);
+void updateWiFiResource(OCRepPayload* input);
+void updateCloudResource(OCRepPayload* input);
+void updateDevConfResource(OCRepPayload* input);
+const char *getResult(OCStackResult result);
+
+ESWiFiCB gWifiRsrcEvtCb = NULL;
+ESCloudCB gCloudRsrcEvtCb = NULL;
+ESDevConfCB gDevConfRsrcEvtCb = NULL;
-ESEnrolleeResourceEventCallback gNetworkInfoProvEventCb = NULL;
+ESReadUserdataCb gReadUserdataCb = NULL;
+ESWriteUserdataCb gWriteUserdataCb = NULL;
-void RegisterResourceEventCallBack(ESEnrolleeResourceEventCallback cb)
+ESResult SetCallbackForUserData(ESReadUserdataCb readCb, ESWriteUserdataCb writeCb)
{
- gNetworkInfoProvEventCb = cb;
+ if(!readCb && !writeCb)
+ {
+ OIC_LOG(INFO, ES_RH_TAG, "Both of callbacks for user data are null");
+ return ES_ERROR;
+ }
+ gReadUserdataCb = readCb;
+ gWriteUserdataCb = writeCb;
+ return ES_OK;
+}
+
+void RegisterWifiRsrcEventCallBack(ESWiFiCB cb)
+{
+ gWifiRsrcEvtCb = cb;
+}
+
+void RegisterCloudRsrcEventCallBack(ESCloudCB cb)
+{
+ gCloudRsrcEvtCb = cb;
+}
+
+void RegisterDevConfRsrcEventCallBack(ESDevConfCB cb)
+{
+ gDevConfRsrcEvtCb = cb;
}
void UnRegisterResourceEventCallBack()
{
- if (gNetworkInfoProvEventCb)
+ if (gWifiRsrcEvtCb)
+ {
+ gWifiRsrcEvtCb = NULL;
+ }
+ if (gCloudRsrcEvtCb)
+ {
+ gCloudRsrcEvtCb = NULL;
+ }
+ if (gDevConfRsrcEvtCb)
{
- gNetworkInfoProvEventCb = NULL;
+ gDevConfRsrcEvtCb = NULL;
}
}
{
if (name != NULL && pass != NULL)
{
- OICStrcpy(name, MAXSSIDLEN, gProvResource.tnn);
- OICStrcpy(pass, MAXNETCREDLEN, gProvResource.cd);
+ OICStrcpy(name, MAX_SSIDLEN, gWiFiResource.ssid);
+ OICStrcpy(pass, MAX_CREDLEN, gWiFiResource.cred);
}
}
-OCStackResult CreateProvisioningResource(bool isSecured)
+OCStackResult initProvResource(bool isSecured)
{
- gProvResource.ps = ES_PS_NEED_PROVISIONING;
- gProvResource.tr = ES_PS_TRIGGER_INIT_VALUE;
-
- gProvResource.tnt = CT_ADAPTER_IP;
- OICStrcpy(gProvResource.tnn, sizeof(gProvResource.tnn), "Unknown");
- OICStrcpy(gProvResource.cd, sizeof(gProvResource.cd), "Unknown");
+ gProvResource.status = ES_STATE_INIT;
+ gProvResource.lastErrCode = ES_ERRCODE_NO_ERROR;
+ OICStrcpy(gProvResource.ocfWebLinks, MAX_WEBLINKLEN, "");
OCStackResult res = OC_STACK_ERROR;
if (isSecured)
{
- res = OCCreateResource(&gProvResource.handle, OC_RSRVD_ES_PROV_RES_TYPE,
+ res = OCCreateResource(&gProvResource.handle, OC_RSRVD_ES_RES_TYPE_PROV,
OC_RSRVD_INTERFACE_DEFAULT,
OC_RSRVD_ES_URI_PROV, OCEntityHandlerCb,
NULL, OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE);
- }
- else
+ }else
{
- res = OCCreateResource(&gProvResource.handle, OC_RSRVD_ES_PROV_RES_TYPE,
+ res = OCCreateResource(&gProvResource.handle, OC_RSRVD_ES_RES_TYPE_PROV,
OC_RSRVD_INTERFACE_DEFAULT,
OC_RSRVD_ES_URI_PROV, OCEntityHandlerCb,
NULL, OC_DISCOVERABLE | OC_OBSERVABLE);
}
+ if(res)
+ {
+ OIC_LOG_V(INFO, ES_RH_TAG, "Created Prov resource with result: %s", getResult(res));
+ return res;
+ }
+
+ res = OCBindResourceInterfaceToResource(gProvResource.handle, OC_RSRVD_INTERFACE_LL);
+ if(res)
+ {
+ OIC_LOG_V(INFO, ES_RH_TAG, "Binding Resource interface with result: %s", getResult(res));
+ return res;
+ }
+ res = OCBindResourceInterfaceToResource(gProvResource.handle, OC_RSRVD_INTERFACE_BATCH);
+ if(res)
+ {
+ OIC_LOG_V(INFO, ES_RH_TAG, "Binding Resource interface with result: %s", getResult(res));
+ return res;
+ }
OIC_LOG_V(INFO, ES_RH_TAG, "Created Prov resource with result: %s", getResult(res));
return res;
}
+OCStackResult initWiFiResource(bool isSecured)
+{
+ OCStackResult res = OC_STACK_ERROR;
+
+ gWiFiResource.supportedFreq = WIFI_BOTH;
+ gWiFiResource.supportedMode[0] = WIFI_11A;
+ gWiFiResource.supportedMode[1] = WIFI_11B;
+ gWiFiResource.supportedMode[2] = WIFI_11G;
+ gWiFiResource.supportedMode[3] = WIFI_11N;
+ gWiFiResource.numMode = 4;
+ gWiFiResource.authType = NONE_AUTH;
+ gWiFiResource.encType = NONE_ENC;
+ OICStrcpy(gWiFiResource.ssid, sizeof(gWiFiResource.ssid), "");
+ OICStrcpy(gWiFiResource.cred, sizeof(gWiFiResource.cred), "");
+
+ if (isSecured)
+ {
+ res = OCCreateResource(&gWiFiResource.handle, OC_RSRVD_ES_RES_TYPE_WIFI,
+ OC_RSRVD_INTERFACE_DEFAULT,
+ OC_RSRVD_ES_URI_WIFI, OCEntityHandlerCb,
+ NULL, OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE);
+ }else
+ {
+ res = OCCreateResource(&gWiFiResource.handle, OC_RSRVD_ES_RES_TYPE_WIFI,
+ OC_RSRVD_INTERFACE_DEFAULT,
+ OC_RSRVD_ES_URI_WIFI, OCEntityHandlerCb,
+ NULL, OC_DISCOVERABLE | OC_OBSERVABLE);
+ }
+
+ OIC_LOG_V(INFO, ES_RH_TAG, "Created WiFi resource with result: %s", getResult(res));
+ return res;
+
+}
+
+OCStackResult initCloudServerResource(bool isSecured)
+{
+ OCStackResult res = OC_STACK_ERROR;
+
+ OICStrcpy(gCloudResource.authCode, sizeof(gCloudResource.authCode), "");
+ OICStrcpy(gCloudResource.authProvider, sizeof(gCloudResource.authProvider), "");
+ OICStrcpy(gCloudResource.ciServer, sizeof(gCloudResource.ciServer), "");
+
+ if (isSecured)
+ {
+ res = OCCreateResource(&gCloudResource.handle, OC_RSRVD_ES_RES_TYPE_CLOUDSERVER,
+ OC_RSRVD_INTERFACE_DEFAULT,
+ OC_RSRVD_ES_URI_CLOUDSERVER, OCEntityHandlerCb,
+ NULL, OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE);
+ }else
+ {
+ res = OCCreateResource(&gCloudResource.handle, OC_RSRVD_ES_RES_TYPE_CLOUDSERVER,
+ OC_RSRVD_INTERFACE_DEFAULT,
+ OC_RSRVD_ES_URI_CLOUDSERVER, OCEntityHandlerCb,
+ NULL, OC_DISCOVERABLE | OC_OBSERVABLE);
+ }
+
+ OIC_LOG_V(INFO, ES_RH_TAG, "Created CloudServer resource with result: %s", getResult(res));
+ return res;
+
+}
+
+OCStackResult initDevConfResource(bool isSecured)
+{
+ OCStackResult res = OC_STACK_ERROR;
+
+ OICStrcpy(gDevConfResource.devName, sizeof(gDevConfResource.devName), "");
+ OICStrcpy(gDevConfResource.country, sizeof(gDevConfResource.country), "");
+ OICStrcpy(gDevConfResource.language, sizeof(gDevConfResource.language), "");
+
+ if (isSecured)
+ {
+ res = OCCreateResource(&gDevConfResource.handle, OC_RSRVD_ES_RES_TYPE_DEVCONF,
+ OC_RSRVD_INTERFACE_DEFAULT,
+ OC_RSRVD_ES_URI_DEVCONF, OCEntityHandlerCb,
+ NULL, OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE);
+ }else
+ {
+ res = OCCreateResource(&gDevConfResource.handle, OC_RSRVD_ES_RES_TYPE_DEVCONF,
+ OC_RSRVD_INTERFACE_DEFAULT,
+ OC_RSRVD_ES_URI_DEVCONF, OCEntityHandlerCb,
+ NULL, OC_DISCOVERABLE | OC_OBSERVABLE);
+ }
+
+ OIC_LOG_V(INFO, ES_RH_TAG, "Created DevConf resource with result: %s", getResult(res));
+ return res;
+
+}
+
+void updateProvResource(OCEntityHandlerRequest* ehRequest, OCRepPayload* input)
+{
+ OIC_LOG_V(INFO, ES_RH_TAG, "gProvResource.status %d", gProvResource.status);
+
+ if(ehRequest->query)
+ {
+ if(strstr(ehRequest->query, OC_RSRVD_INTERFACE_BATCH))
+ {
+ // When Provisioning resource has a POST with BatchInterface
+ updateCloudResource(input);
+ updateWiFiResource(input);
+ updateDevConfResource(input);
+ }
+ }
+}
+
+void updateWiFiResource(OCRepPayload* input)
+{
+ ESWiFiProvData* wiFiData = (ESWiFiProvData*)OICMalloc(sizeof(ESWiFiProvData));
+
+ if(wiFiData == NULL)
+ {
+ OIC_LOG(DEBUG, ES_RH_TAG, "OICMalloc is failed");
+ return ;
+ }
+
+ memset(wiFiData->ssid, 0, MAX_SSIDLEN);
+ memset(wiFiData->pwd, 0, MAX_CREDLEN);
+ wiFiData->authtype = NONE_AUTH;
+ wiFiData->enctype = NONE_AUTH;
+ wiFiData->userdata = NULL;
+
+ char* ssid = NULL;
+ if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_SSID, &ssid))
+ {
+ OICStrcpy(gWiFiResource.ssid, sizeof(gWiFiResource.ssid), ssid);
+ OICStrcpy(wiFiData->ssid, sizeof(wiFiData->ssid), ssid);
+ OIC_LOG_V(INFO, ES_RH_TAG, "gWiFiResource.ssid : %s", gWiFiResource.ssid);
+ }
+
+ char* cred = NULL;
+ if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_CRED, &cred))
+ {
+ OICStrcpy(gWiFiResource.cred, sizeof(gWiFiResource.cred), cred);
+ OICStrcpy(wiFiData->pwd, sizeof(wiFiData->pwd), cred);
+ OIC_LOG_V(INFO, ES_RH_TAG, "gWiFiResource.cred %s", gWiFiResource.cred);
+ }
+
+ int64_t authType = -1;
+ if (OCRepPayloadGetPropInt(input, OC_RSRVD_ES_AUTHTYPE, &authType))
+ {
+ gWiFiResource.authType = authType;
+ wiFiData->authtype = gWiFiResource.authType;
+ OIC_LOG_V(INFO, ES_RH_TAG, "gWiFiResource.authType %u", gWiFiResource.authType);
+ }
+
+ int64_t encType = -1;
+ if (OCRepPayloadGetPropInt(input, OC_RSRVD_ES_ENCTYPE, &encType))
+ {
+ gWiFiResource.encType = encType;
+ wiFiData->enctype = gWiFiResource.encType;
+ OIC_LOG_V(INFO, ES_RH_TAG, "gWiFiResource.encType %u", gWiFiResource.encType);
+ }
+
+ if(gReadUserdataCb)
+ {
+ gReadUserdataCb(input, OC_RSRVD_ES_RES_TYPE_WIFI, &wiFiData->userdata);
+ }
+
+ if(ssid || cred || authType!= -1 || encType != -1)
+ {
+ OIC_LOG(INFO, ES_RH_TAG, "Send WiFiRsrc Callback To ES");
+
+ // TODO : Need to check appropriateness of gWiFiData
+ if(gWifiRsrcEvtCb != NULL)
+ {
+ gWifiRsrcEvtCb(ES_OK, wiFiData);
+ }
+ else
+ {
+ OIC_LOG(ERROR, ES_RH_TAG, "gWifiRsrcEvtCb is NULL");
+ }
+ }
+
+ OICFree(wiFiData);
+}
+
+void updateCloudResource(OCRepPayload* input)
+{
+ ESCloudProvData* cloudData = (ESCloudProvData*)OICMalloc(sizeof(ESCloudProvData));
+
+ if(cloudData == NULL)
+ {
+ OIC_LOG(DEBUG, ES_RH_TAG, "OICMalloc is failed");
+ return;
+ }
+
+ memset(cloudData->authCode, 0, OIC_STRING_MAX_VALUE);
+ memset(cloudData->authProvider, 0, OIC_STRING_MAX_VALUE);
+ memset(cloudData->ciServer, 0, OIC_STRING_MAX_VALUE);
+ cloudData->userdata = NULL;
+
+ char *authCode = NULL;
+ if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_AUTHCODE, &authCode))
+ {
+ OICStrcpy(gCloudResource.authCode, sizeof(gCloudResource.authCode), authCode);
+ OICStrcpy(cloudData->authCode, sizeof(cloudData->authCode), authCode);
+ OIC_LOG_V(INFO, ES_RH_TAG, "gCloudResource.authCode %s", gCloudResource.authCode);
+ }
+
+ char *authProvider = NULL;
+ if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_AUTHPROVIDER, &authProvider))
+ {
+ OICStrcpy(gCloudResource.authProvider, sizeof(gCloudResource.authProvider), authProvider);
+ OICStrcpy(cloudData->authProvider, sizeof(cloudData->authProvider), authProvider);
+ OIC_LOG_V(INFO, ES_RH_TAG, "gCloudResource.authServerUrl %s", gCloudResource.authProvider);
+ }
+
+ char *ciServer = NULL;
+ if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_CISERVER, &ciServer))
+ {
+ OICStrcpy(gCloudResource.ciServer, sizeof(gCloudResource.ciServer), ciServer);
+ OICStrcpy(cloudData->ciServer, sizeof(cloudData->ciServer), ciServer);
+ OIC_LOG_V(INFO, ES_RH_TAG, "gCloudResource.ciServer %s", gCloudResource.ciServer);
+ }
+
+ if(gReadUserdataCb)
+ {
+ gReadUserdataCb(input, OC_RSRVD_ES_RES_TYPE_CLOUDSERVER, &cloudData->userdata);
+ }
+
+ if(authCode || authProvider || ciServer)
+ {
+ OIC_LOG(INFO, ES_RH_TAG, "Send CloudRsrc Callback To ES");
+
+ // TODO : Need to check appropriateness of gCloudData
+ if(gCloudRsrcEvtCb != NULL)
+ {
+ gCloudRsrcEvtCb(ES_OK, cloudData);
+ }
+ else
+ {
+ OIC_LOG(ERROR, ES_RH_TAG, "gCloudRsrcEvtCb is NULL");
+ }
+ }
+
+ OICFree(cloudData);
+}
+
+void updateDevConfResource(OCRepPayload* input)
+{
+ ESDevConfProvData* devConfData = (ESDevConfProvData*)OICMalloc(sizeof(ESDevConfProvData));
+
+ if(devConfData == NULL)
+ {
+ OIC_LOG(DEBUG, ES_RH_TAG, "OICMalloc is failed");
+ return;
+ }
+ memset(devConfData->language, 0, OIC_STRING_MAX_VALUE);
+ memset(devConfData->country, 0, OIC_STRING_MAX_VALUE);
+ devConfData->userdata = NULL;
+
+ char *country = NULL;
+ if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_COUNTRY, &country))
+ {
+ OICStrcpy(gDevConfResource.country, sizeof(gDevConfResource.country), country);
+ OICStrcpy(devConfData->country, sizeof(devConfData->country), country);
+ OIC_LOG_V(INFO, ES_RH_TAG, "gDevConfResource.country %s", gDevConfResource.country);
+ }
+
+ char *language = NULL;
+ if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_LANGUAGE, &language))
+ {
+ OICStrcpy(gDevConfResource.language, sizeof(gDevConfResource.language), language);
+ OICStrcpy(devConfData->language, sizeof(devConfData->language), language);
+ OIC_LOG_V(INFO, ES_RH_TAG, "gDevConfResource.language %s", gDevConfResource.language);
+ }
+
+ if(gReadUserdataCb)
+ {
+ gReadUserdataCb(input, OC_RSRVD_ES_RES_TYPE_DEVCONF, &devConfData->userdata);
+ }
+
+ if(country || language)
+ {
+ OIC_LOG(INFO, ES_RH_TAG, "Send DevConfRsrc Callback To ES");
+
+ // TODO : Need to check appropriateness of gDevConfData
+ if(gDevConfRsrcEvtCb != NULL)
+ {
+ gDevConfRsrcEvtCb(ES_OK, devConfData);
+ }
+ else
+ {
+ OIC_LOG(ERROR, ES_RH_TAG, "gDevConfRsrcEvtCb is NULL");
+ }
+ }
+
+ OICFree(devConfData);
+}
+
+OCRepPayload* constructResponseOfWiFi()
+{
+ OCRepPayload* payload = OCRepPayloadCreate();
+ if (!payload)
+ {
+ OIC_LOG(ERROR, ES_RH_TAG, "Failed to allocate Payload");
+ return NULL;
+ }
+
+ OIC_LOG(INFO, ES_RH_TAG, "constructResponse wifi res");
+ OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_WIFI);
+
+ size_t dimensions[MAX_REP_ARRAY_DEPTH] = {gWiFiResource.numMode, 0, 0};
+ int64_t *modes_64 = (int64_t *)OICMalloc(gWiFiResource.numMode * sizeof(int64_t));
+ for(int i = 0 ; i < gWiFiResource.numMode ; ++i)
+ {
+ modes_64[i] = gWiFiResource.supportedMode[i];
+ }
+ OCRepPayloadSetIntArray(payload, OC_RSRVD_ES_SUPPORTEDWIFIMODE, (int64_t *)modes_64, dimensions);
+
+ OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_SUPPORTEDWIFIFREQ, gWiFiResource.supportedFreq);
+ OCRepPayloadSetPropString(payload, OC_RSRVD_ES_SSID, gWiFiResource.ssid);
+ OCRepPayloadSetPropString(payload, OC_RSRVD_ES_CRED, gWiFiResource.cred);
+ OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_AUTHTYPE, (int) gWiFiResource.authType);
+ OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_ENCTYPE, (int) gWiFiResource.encType);
+
+ if(gWriteUserdataCb)
+ {
+ gWriteUserdataCb(payload, OC_RSRVD_ES_RES_TYPE_WIFI);
+ }
+
+ return payload;
+}
+
+OCRepPayload* constructResponseOfCloud()
+{
+ OCRepPayload* payload = OCRepPayloadCreate();
+ if (!payload)
+ {
+ OIC_LOG(ERROR, ES_RH_TAG, "Failed to allocate Payload");
+ return NULL;
+ }
+
+ OIC_LOG(INFO, ES_RH_TAG, "constructResponse prov res");
+ OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_CLOUDSERVER);
+ OCRepPayloadSetPropString(payload, OC_RSRVD_ES_AUTHCODE, gCloudResource.authCode);
+ OCRepPayloadSetPropString(payload, OC_RSRVD_ES_AUTHPROVIDER, gCloudResource.authProvider);
+ OCRepPayloadSetPropString(payload, OC_RSRVD_ES_CISERVER, gCloudResource.ciServer);
+
+ if(gWriteUserdataCb)
+ {
+ gWriteUserdataCb(payload, OC_RSRVD_ES_RES_TYPE_CLOUDSERVER);
+ }
+
+ return payload;
+}
+
+OCRepPayload* constructResponseOfDevConf()
+{
+ OCRepPayload* payload = OCRepPayloadCreate();
+ if (!payload)
+ {
+ OIC_LOG(ERROR, ES_RH_TAG, "Failed to allocate Payload");
+ return NULL;
+ }
+
+ OIC_LOG(INFO, ES_RH_TAG, "constructResponse prov res");
+ OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_DEVCONF);
+ OCRepPayloadSetPropString(payload, OC_RSRVD_ES_DEVNAME, gDevConfResource.devName);
+ OCRepPayloadSetPropString(payload, OC_RSRVD_ES_LANGUAGE, gDevConfResource.language);
+ OCRepPayloadSetPropString(payload, OC_RSRVD_ES_COUNTRY, gDevConfResource.country);
+
+ if(gWriteUserdataCb)
+ {
+ gWriteUserdataCb(payload, OC_RSRVD_ES_RES_TYPE_DEVCONF);
+ }
+
+ return payload;
+}
+
+OCRepPayload* constructResponseOfProv(OCEntityHandlerRequest *ehRequest)
+{
+ OCRepPayload* payload = OCRepPayloadCreate();
+ if (!payload)
+ {
+ OIC_LOG(ERROR, ES_RH_TAG, "Failed to allocate Payload");
+ return NULL;
+ }
+
+ OIC_LOG(INFO, ES_RH_TAG, "constructResponse prov res");
+ OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_PROV);
+ OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_PROVSTATUS, gProvResource.status);
+ OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_LAST_ERRORCODE, gProvResource.lastErrCode);
+ OCRepPayloadSetPropString(payload, OC_RSRVD_ES_LINKS, gProvResource.ocfWebLinks);
+
+ if(gWriteUserdataCb)
+ {
+ gWriteUserdataCb(payload, OC_RSRVD_ES_RES_TYPE_PROV);
+ }
+
+ if(ehRequest->query)
+ {
+ if(strstr(ehRequest->query, OC_RSRVD_INTERFACE_BATCH))
+ {// When Provisioning resource has a GET with BatchInterface
+ OCRepPayload* head = payload;
+ OCRepPayload* nextPayload = NULL;
+
+ nextPayload = constructResponseOfWiFi();
+ if(nextPayload != NULL)
+ {
+ payload->next = nextPayload;
+ payload = payload->next;
+ }
+
+ nextPayload = constructResponseOfCloud();
+ if(nextPayload != NULL)
+ {
+ payload->next = nextPayload;
+ payload = payload->next;
+ }
+
+ nextPayload = constructResponseOfDevConf();
+ if(nextPayload != NULL)
+ {
+ payload->next = nextPayload;
+ payload = payload->next;
+ }
+
+ payload = head;
+ }
+ }
+
+ return payload;
+}
+
+
+OCStackResult CreateEasySetupResources(bool isSecured, ESResourceMask resourceMask)
+{
+ OCStackResult res = OC_STACK_ERROR;
+ bool maskFlag = false;
+
+ res = initProvResource(isSecured);
+ if(res != OC_STACK_OK)
+ {
+ // TODO: destroy logic will be added
+ OIC_LOG_V(ERROR, ES_RH_TAG, "initProvResource result: %s", getResult(res));
+
+ return res;
+ }
+
+ if((resourceMask & ES_WIFI_RESOURCE) == ES_WIFI_RESOURCE)
+ {
+ maskFlag = true;
+ res = initWiFiResource(isSecured);
+ if(res != OC_STACK_OK)
+ {
+ OIC_LOG_V(ERROR, ES_RH_TAG, "initWiFiResource result: %s", getResult(res));
+ return res;
+ }
+
+ res = OCBindResource(gProvResource.handle, gWiFiResource.handle);
+ if(res != OC_STACK_OK)
+ {
+ OIC_LOG_V(ERROR, ES_RH_TAG, "Bind WiFiResource result: %s", getResult(res));
+ return res;
+ }
+
+ }
+
+ if((resourceMask & ES_CLOUD_RESOURCE) == ES_CLOUD_RESOURCE)
+ {
+ maskFlag = true;
+ res = initCloudServerResource(isSecured);
+ if(res != OC_STACK_OK)
+ {
+ OIC_LOG_V(ERROR, ES_RH_TAG, "initCloudResource result: %s", getResult(res));
+ return res;
+ }
+
+ res = OCBindResource(gProvResource.handle, gCloudResource.handle);
+ if(res != OC_STACK_OK)
+ {
+ OIC_LOG_V(ERROR, ES_RH_TAG, "Bind CloudResource result: %s", getResult(res));
+ return res;
+ }
+ }
+
+ if((resourceMask & ES_DEVCONF_RESOURCE) == ES_DEVCONF_RESOURCE)
+ {
+ maskFlag = true;
+ res = initDevConfResource(isSecured);
+ if(res != OC_STACK_OK)
+ {
+ OIC_LOG_V(ERROR, ES_RH_TAG, "initDevConf result: %s", getResult(res));
+ return res;
+ }
+
+ res = OCBindResource(gProvResource.handle, gDevConfResource.handle);
+ if(res != OC_STACK_OK)
+ {
+ OIC_LOG_V(ERROR, ES_RH_TAG, "Bind DevConfResource result: %s", getResult(res));
+ return res;
+ }
+ }
+
+
+ if(maskFlag == false)
+ {
+ OIC_LOG_V(ERROR, ES_RH_TAG, "Invalid ResourceMask");
+ return OC_STACK_ERROR;
+
+ }
+
+ OIC_LOG_V(INFO, ES_RH_TAG, "Created all resources with result: %s", getResult(res));
+
+ return res;
+}
+
OCStackResult DeleteProvisioningResource()
{
OCStackResult res = OCDeleteResource(gProvResource.handle);
return res;
}
+OCStackResult DeleteEasySetupResources()
+{
+ OCStackResult res = OC_STACK_ERROR;
+ if (gWiFiResource.handle != NULL)
+ {
+ res = OCUnBindResource(gProvResource.handle, gWiFiResource.handle);
+ if(res != OC_STACK_OK)
+ {
+ OIC_LOG_V(ERROR, ES_RH_TAG, "Unbind WiFi resource error with result: %s", getResult(res));
+ }
+ }
+ if (gCloudResource.handle != NULL)
+ {
+ res = OCUnBindResource(gProvResource.handle, gCloudResource.handle);
+ if(res != OC_STACK_OK)
+ {
+ OIC_LOG_V(ERROR, ES_RH_TAG, "Unbind CloudServer resource error with result: %s", getResult(res));
+ }
+ }
+ if (gDevConfResource.handle != NULL)
+ {
+ res = OCUnBindResource(gProvResource.handle, gDevConfResource.handle);
+ if(res != OC_STACK_OK)
+ {
+ OIC_LOG_V(ERROR, ES_RH_TAG, "Unbind DevConf resource error with result: %s", getResult(res));
+ }
+ }
+
+ if (gWiFiResource.handle != NULL)
+ {
+ res = OCDeleteResource(gWiFiResource.handle);
+ if (res != OC_STACK_OK)
+ {
+ OIC_LOG_V(ERROR, ES_RH_TAG, "Deleting WiFi resource error with result: %s", getResult(res));
+ }
+ }
+
+ if(gCloudResource.handle != NULL)
+ {
+ res = OCDeleteResource(gCloudResource.handle);
+ if (res != OC_STACK_OK)
+ {
+ OIC_LOG_V(ERROR, ES_RH_TAG, "Deleting CloudServer resource error with result: %s", getResult(res));
+ }
+ }
+
+ if(gDevConfResource.handle != NULL)
+ {
+ res = OCDeleteResource(gDevConfResource.handle);
+ if (res != OC_STACK_OK)
+ {
+ OIC_LOG_V(ERROR, ES_RH_TAG, "Deleting DevConf resource error with result: %s", getResult(res));
+ }
+ }
+
+ if(gProvResource.handle != NULL)
+ {
+ res = OCDeleteResource(gProvResource.handle);
+ if (res != OC_STACK_OK)
+ {
+ OIC_LOG_V(ERROR, ES_RH_TAG, "Deleting Prov resource error with result: %s", getResult(res));
+ }
+ }
+
+ return res;
+}
+
OCEntityHandlerResult ProcessGetRequest(OCEntityHandlerRequest *ehRequest, OCRepPayload **payload)
{
OCEntityHandlerResult ehResult = OC_EH_ERROR;
return ehResult;
}
- OCRepPayload *getResp = constructResponse(ehRequest);
+ OCRepPayload *getResp = NULL;
+
+ if(ehRequest->resource == gProvResource.handle)
+ {
+ getResp = constructResponseOfProv(ehRequest);
+ }
+ else if(ehRequest->resource == gWiFiResource.handle)
+ {
+ getResp = constructResponseOfWiFi();
+ }
+ else if(ehRequest->resource == gCloudResource.handle)
+ {
+ getResp = constructResponseOfCloud();
+ }
+ else if(ehRequest->resource == gDevConfResource.handle)
+ {
+ getResp = constructResponseOfDevConf();
+ }
+
if (!getResp)
{
OIC_LOG(ERROR, ES_RH_TAG, "constructResponse failed");
return ehResult;
}
- char* tnn;
- if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_TNN, &tnn))
+ if(ehRequest->resource == gProvResource.handle)
{
- OICStrcpy(gProvResource.tnn, sizeof(gProvResource.tnn), tnn);
- OIC_LOG_V(INFO, ES_RH_TAG, "gProvResource.tnn %s", gProvResource.tnn);
-
- gProvResource.ps = ES_PS_PROVISIONING_COMPLETED;
+ updateProvResource(ehRequest, input);
}
-
- char* cd;
- if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_CD, &cd))
+ else if(ehRequest->resource == gWiFiResource.handle)
{
- OICStrcpy(gProvResource.cd, sizeof(gProvResource.cd), cd);
- OIC_LOG_V(INFO, ES_RH_TAG, "gProvResource.cd %s", gProvResource.cd);
+ updateWiFiResource(input);
}
-
- OIC_LOG_V(INFO, ES_RH_TAG, "gProvResource.ps %lld", gProvResource.ps);
-
- int64_t tr;
- if (OCRepPayloadGetPropInt(input, OC_RSRVD_ES_TR, &tr))
+ else if(ehRequest->resource == gCloudResource.handle)
{
- // Triggering
- gProvResource.tr = tr;
+ updateCloudResource(input);
}
-
- //ES_PS_PROVISIONING_COMPLETED state indicates that already provisioning is completed.
- // A new request for provisioning means overriding existing network provisioning information.
- if (gProvResource.ps == ES_PS_PROVISIONING_COMPLETED && tr == ES_PS_TRIGGER_CONNECTION)
+ else if(ehRequest->resource == gDevConfResource.handle)
{
- OIC_LOG(DEBUG, ES_RH_TAG, "Provisioning already completed."
- "Tiggering the network connection");
-
- if (gNetworkInfoProvEventCb)
- {
- gNetworkInfoProvEventCb(ES_RECVTRIGGEROFPROVRES);
- ehResult = OC_EH_OK;
- }
- else
- {
- gProvResource.tr = ES_PS_TRIGGER_INIT_VALUE;
- OIC_LOG(ERROR, ES_RH_TAG, "gNetworkInfoProvEventCb is NULL."
- "Network handler not registered. Failed to connect to the network");
- ehResult = OC_EH_ERROR;
- }
+ updateDevConfResource(input);
+ }
- return ehResult;
+ OCRepPayload *getResp = NULL;
+ if(ehRequest->resource == gProvResource.handle)
+ {
+ getResp = constructResponseOfProv(ehRequest);
}
- else if (gProvResource.ps == ES_PS_PROVISIONING_COMPLETED)
+ else if(ehRequest->resource == gWiFiResource.handle)
{
- OIC_LOG(DEBUG, ES_RH_TAG, "Provisioning already completed. "
- "This a request to override the existing the network provisioning information");
+ getResp = constructResponseOfWiFi();
}
- else
+ else if(ehRequest->resource == gCloudResource.handle)
{
- OIC_LOG(DEBUG, ES_RH_TAG, "Provisioning the network information to the Enrollee.");
+ getResp = constructResponseOfCloud();
+ }
+ else if(ehRequest->resource == gDevConfResource.handle)
+ {
+ getResp = constructResponseOfDevConf();
}
- OCRepPayload *getResp = constructResponse(ehRequest);
if (!getResp)
{
OIC_LOG(ERROR, ES_RH_TAG, "constructResponse failed");
OCEntityHandlerResult ProcessPutRequest(OCEntityHandlerRequest * ehRequest,
OCRepPayload** payload)
{
+ (void) ehRequest;
+ (void) payload;
OCEntityHandlerResult ehResult = OC_EH_ERROR;
return ehResult;
}
-
-OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest)
-{
- OCRepPayload* payload = OCRepPayloadCreate();
- if (!payload)
- {
- OIC_LOG(ERROR, ES_RH_TAG, "Failed to allocate Payload");
- return NULL;
- }
-
- if (ehRequest->resource == gProvResource.handle)
- {
- OIC_LOG(INFO, ES_RH_TAG, "constructResponse prov res");
- OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_PROV);
- OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_PS, gProvResource.ps);
- OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_TNT, gProvResource.tnt);
- }
- else if (ehRequest->requestHandle == gNetResource.handle)
- {
-
- OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_NET);
- OCRepPayloadSetPropInt(payload, "ant", gNetResource.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.
OIC_LOG(INFO, ES_RH_TAG, "Received PUT request");
//PUT request will be handled in the internal implementation
- if (gProvResource.handle != NULL
- && entityHandlerRequest->resource == gProvResource.handle)
+ if (gProvResource.handle != NULL)
{
ehRet = ProcessPutRequest(entityHandlerRequest, &payload);
}
else if (OC_REST_POST == entityHandlerRequest->method)
{
OIC_LOG(INFO, ES_RH_TAG, "Received OC_REST_POST from client");
- if (gProvResource.handle != NULL
- && entityHandlerRequest->resource == gProvResource.handle)
+ if (gProvResource.handle != NULL)
{
ehRet = ProcessPostRequest(entityHandlerRequest, &payload);
}
return ehRet;
}
+OCStackResult SetDeviceProperty(ESDeviceProperty *deviceProperty)
+{
+ OIC_LOG(INFO, ES_RH_TAG, "SetDeviceProperty IN");
+
+ gWiFiResource.supportedFreq = (deviceProperty->WiFi).freq;
+ OIC_LOG_V(INFO, ES_RH_TAG, "WiFi Freq : %d", gWiFiResource.supportedFreq);
+
+ int modeIdx = 0;
+ while((deviceProperty->WiFi).mode[modeIdx] != WiFi_EOF)
+ {
+ gWiFiResource.supportedMode[modeIdx] = (deviceProperty->WiFi).mode[modeIdx];
+ OIC_LOG_V(INFO, ES_RH_TAG, "WiFi Mode : %d", gWiFiResource.supportedMode[modeIdx]);
+ modeIdx ++;
+ }
+ gWiFiResource.numMode = modeIdx;
+
+ OICStrcpy(gDevConfResource.devName, MAX_DEVICELEN, (deviceProperty->DevConf).deviceName);
+ OIC_LOG_V(INFO, ES_RH_TAG, "Device Name : %s", gDevConfResource.devName);
+
+ OIC_LOG(INFO, ES_RH_TAG, "SetDeviceProperty OUT");
+ return OC_STACK_OK;
+}
+
+OCStackResult SetEnrolleeState(ESEnrolleeState esState)
+{
+ OIC_LOG(INFO, ES_RH_TAG, "SetEnrolleeState IN");
+
+ gProvResource.status = esState;
+ OIC_LOG_V(INFO, ES_RH_TAG, "Enrollee Status : %d", gProvResource.status);
+
+ OIC_LOG(INFO, ES_RH_TAG, "SetEnrolleeState OUT");
+ return OC_STACK_OK;
+}
+
+OCStackResult SetEnrolleeErrCode(ESErrorCode esErrCode)
+{
+ OIC_LOG(INFO, ES_RH_TAG, "SetEnrolleeErrCode IN");
+
+ gProvResource.lastErrCode = esErrCode;
+ OIC_LOG_V(INFO, ES_RH_TAG, "Enrollee ErrorCode : %d", gProvResource.lastErrCode);
+
+ OIC_LOG(INFO, ES_RH_TAG, "SetEnrolleeErrCode OUT");
+ return OC_STACK_OK;
+}
+
const char *getResult(OCStackResult result)
{
switch (result)
return "UNKNOWN";
}
}
-
#include "logger.h"
#include "ocstack.h"
#include "escommon.h"
-#include "networkhandler.h"
+#include "ESEnrolleeCommon.h"
#include "octypes.h"
#ifndef ES_RESOURCE_HANDLER_H_
extern "C" {
#endif
-typedef void (*ESEnrolleeResourceEventCallback)(ESResult);
+typedef void (*ESWiFiCB) (ESResult, ESWiFiProvData *);
+typedef void (*ESCloudCB) (ESResult, ESCloudProvData *);
+typedef void (*ESDevConfCB) (ESResult, ESDevConfProvData *);
+
+typedef void (*ESWriteUserdataCb)(OCRepPayload* payload, char* resourceType);
+typedef void (*ESReadUserdataCb)(OCRepPayload* payload, char* resourceType, void** userdata);
/* Structure to represent a Light resource */
typedef struct PROVRESOURCE
{
OCResourceHandle handle;
- int64_t ps; // provisiong status, 1 : need to provisioning, 2 : Connected to Enroller.
- int64_t tr; // Trigger network connection, 0 : Init value, 1 : Connected to the target network.
- int64_t 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.
+ ProvStatus status; // provisiong status
+ ESErrorCode lastErrCode;
+ char ocfWebLinks[MAX_WEBLINKLEN];
} ProvResource;
-/* Structure to represent a Light resource */
-typedef struct NETRESOURCE
+typedef struct
+{
+ OCResourceHandle handle;
+ WIFI_MODE supportedMode[NUM_WIFIMODE];
+ uint8_t numMode; // the number of device's supported wifi modes
+ WIFI_FREQ supportedFreq;
+ char ssid[MAX_SSIDLEN]; // SSID
+ char cred[MAX_CREDLEN]; // credential information.
+ WIFI_AUTHTYPE authType;
+ WIFI_ENCTYPE encType;
+} WiFiResource;
+
+typedef struct
{
OCResourceHandle handle;
- int64_t cnt; // current network type, 1: WLAN, 2: BT, 3: BLE, 4: Zigbee.
- int64_t 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;
+ char authCode[OIC_STRING_MAX_VALUE];
+ char authProvider[OIC_STRING_MAX_VALUE];
+ char ciServer[OIC_STRING_MAX_VALUE];
+} CloudResource;
+
+typedef struct
+{
+ OCResourceHandle handle;
+ char devName[MAX_DEVICELEN];
+ char language[OIC_STRING_MAX_VALUE];
+ char country[OIC_STRING_MAX_VALUE];
+} DevConfResource;
+
+OCStackResult CreateEasySetupResources(bool isSecured, ESResourceMask resourceMask);
+OCStackResult DeleteEasySetupResources();
-OCStackResult CreateProvisioningResource(bool isSecured);
-OCStackResult DeleteProvisioningResource();
+OCStackResult SetDeviceProperty(ESDeviceProperty *deviceProperty);
+OCStackResult SetEnrolleeState(ESEnrolleeState esState);
+OCStackResult SetEnrolleeErrCode(ESErrorCode esErrCode);
void GetTargetNetworkInfoFromProvResource(char *, char *);
-void RegisterResourceEventCallBack(ESEnrolleeResourceEventCallback);
+void RegisterWifiRsrcEventCallBack(ESWiFiCB);
+void RegisterCloudRsrcEventCallBack(ESCloudCB);
+void RegisterDevConfRsrcEventCallBack(ESDevConfCB);
void UnRegisterResourceEventCallBack(void);
+ESResult SetCallbackForUserData(ESReadUserdataCb readCb, ESWriteUserdataCb writeCb);
#ifdef __cplusplus
}
#endif
-#endif //ES_RESOURCE_HANDLER_H_
\ No newline at end of file
+#endif //ES_RESOURCE_HANDLER_H_
+++ /dev/null
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-/**
- * These are adapter APIs will make caller modules agnostic to platform.
- */
-
-#include "softapnative.h"
-#include "easysetup.h"
-#include "softap.h"
-#include "networkhandler.h"
-
-void ESCreateSoftapCallback(int result, const char *ip, const char* mac_addr,
- const char* device_name );
-
-ESEnrolleeNetworkEventCallback gCallback;
-
-/**
- * It will return Device which is creating Soft AP.
- * i.e.Enrollee or Mediator.
- * This decision is based on, what is the value set for ES_SOFTAP_MODE in build command as well as
- * in iotivity.spec file.
- */
-DeviceRole ESSoftapHost()
-{
-#ifdef ENROLLEE_SOFTAP
- //SoftAp at enrollee
- return ENROLLEE;
-#else
- //SoftAp at mediator
- return MEDIATOR;
-#endif
-}
-
-/**
- * It will return true if the Soft AP is created at Enrollee device
- */
-bool ESSoftapAtEnrollee()
-{
- return ( ESSoftapHost() == ENROLLEE) ? true : false;
-}
-
-/**
- * It will return true if the Soft AP is created at Mediator device
- */
-bool ESSoftapAtMediator()
-{
- return (ESSoftapHost() == MEDIATOR) ? true : false;
-}
-
-/**
- * This API will map result returned from the native to the caller.
- * Callback API's signature needs to be modified under build switch according
- * to the underline platform.
- */
-void ESCreateSoftapCallback(int result, const char *ip, const char* mac_addr,
- const char* device_name)
-{
- if(SOFTAP_SUCCESS == result) //on Success
- {
- gCallback(ES_OK);
- }
- else //on Failure
- {
- gCallback(ES_ERROR);
- }
-}
-
-/**
- * This API will create the softap at enrollee
- */
-void ESCreateSoftap(const char * ssid, const char* passwd, ESEnrolleeNetworkEventCallback cb)
-{
- gCallback = cb;
-
- // TODO: To be implemented
- // Create Soft AP through native APIs -- start
- // native API call by and pass ESCreateSoftapCallback() as callback
- ESCreateSoftapNative(ssid, passwd,ESCreateSoftapCallback);
- // Create Soft AP through native APIs -- end
-}
-
+++ /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_ENROLLEE_SOFTAP_H__
-#define EASYSETUP_ENROLLEE_SOFTAP_H__
-
-#include "escommon.h"
-#include "networkhandler.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * @file
- *
- * This file contains platform agnostic API for creation of Soft AP
- * @Note : Some of the APIs of this file need to be modified by the OEM according to the device
- * configuration
- */
-
-/**
- * This function verify if the Soft AP is created at Enrollee device.
- * @return ::True, if Soft AP is created at Enrollee device.
- * @Note : This API needs to be modified by the OEM according to the device configuration
- */
-
-bool ESSoftapAtEnrollee();
-
-/**
- * This function verify if the Soft AP is created at Mediator device.
- * @return ::True, if Soft AP is created at Mediator device.
- * @Note : This API needs to be modified by the OEM according to the device configuration
- */
-
-bool ESSoftapAtMediator();
-
-
-/**
- * This function finds which Device (Enrollee or Mediator) is creating Soft AP.
- * @return ::DeviceRole (ENROLLEE or MEDIATOR)
- * @Note : This API needs to be modified by the OEM according to the device configuration
- */
-
-DeviceRole ESSoftapHost();
-
-/**
- * This function Initializes the EasySetup. This API must be called prior to invoking any other API
- *
- * @param ssid SSID of the target SoftAP network to which the Enrollee is
- * connecting.
- * @param passwd Password of the target SoftAP network to which the Enrollee is
- * connecting
- * @param ESEnrolleeNetworkEventCallback Callback function for result update
- * @return ::void.
- */
-void ESCreateSoftap(const char * ssid, const char* passwd, ESEnrolleeNetworkEventCallback cb);
-
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* EASYSETUP_ENROLLEE_SOFTAP_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 "networkhandler.h"
-
-#include <wifi.h>
-#include <unistd.h>
-
-#include "logger.h"
-#include "easysetup.h"
-#include "oic_string.h"
-
-#define LOG_TAG "TIZEN ES"
-
-const char *gSsid = "DLNA_LISMORE1";
-const char *gPass = "dlna@010203";
-char *gIpAddress = NULL;
-wifi_ap_h connectedWifi;
-ESEnrolleeNetworkEventCallback gNetworkEventCb;
-static void ESActivateWifi();
-
-static const char*
-print_state(wifi_connection_state_e state)
-{
- switch (state)
- {
- case WIFI_CONNECTION_STATE_DISCONNECTED:
- return "Disconnected";
- case WIFI_CONNECTION_STATE_ASSOCIATION:
- return "Association";
- case WIFI_CONNECTION_STATE_CONNECTED:
- return "Connected";
- case WIFI_CONNECTION_STATE_CONFIGURATION:
- return "Configuration";
- }
-}
-
-void __wifi_connected_cb(wifi_error_e error_code, void *user_data)
-{
- OIC_LOG(INFO,LOG_TAG,"#### __connected ");
-
- if (gIpAddress)
- free(gIpAddress);
-
- wifi_ap_get_ip_address(connectedWifi, WIFI_ADDRESS_FAMILY_IPV4, &gIpAddress);
- OIC_LOG_V(INFO,LOG_TAG,"#### __connected, Ipaddress=%s", gIpAddress);
- gNetworkEventCb(ES_OK);
-
-}
-
-bool __wifi_found_ap_cb(wifi_ap_h ap, void *user_data)
-{
- OIC_LOG(INFO,LOG_TAG,"#### __wifi_found_ap_cb received ");
-
- int error_code = 0;
- char *ap_name = NULL;
- wifi_connection_state_e state;
-
- error_code = wifi_ap_get_essid(ap, &ap_name);
- if (error_code != WIFI_ERROR_NONE)
- {
- OIC_LOG(ERROR,LOG_TAG,"#### Fail to get AP name.");
-
- return false;
- }
- error_code = wifi_ap_get_connection_state(ap, &state);
- if (error_code != WIFI_ERROR_NONE)
- {
- OIC_LOG(ERROR,LOG_TAG,"#### Fail to get state.");
- free(ap_name);
-
- return false;
- }
- OIC_LOG_V(INFO,LOG_TAG,"#### AP name : %s, state : %s", ap_name, print_state(state));
-
- if (strcmp(ap_name, gSsid) == 0)
- {
- OIC_LOG(INFO,LOG_TAG,"#### network found");
- wifi_ap_set_passphrase(ap, gPass);
- connectedWifi = ap;
- error_code = wifi_connect(ap, __wifi_connected_cb, NULL);
- OIC_LOG_V(INFO,LOG_TAG,"Code=%d", error_code);
- }
- OIC_LOG(INFO,LOG_TAG,"#### __wifi_found_ap_cb received ");
- free(ap_name);
- return true;
-}
-void __scan_request_cb(wifi_error_e error_code, void *user_data)
-{
- OIC_LOG(INFO, LOG_TAG, "__scan_request_cb");
- int error_code1;
- error_code1 = wifi_foreach_found_aps(__wifi_found_ap_cb, NULL);
- if (error_code1 != WIFI_ERROR_NONE)
- OIC_LOG(INFO,LOG_TAG,"#### Fail to scan");
-
- OIC_LOG(INFO, LOG_TAG,"#### __scan_request_cb exit ");
-}
-
-static void __wifi_activated_cb(wifi_error_e result, void *user_data)
-{
- OIC_LOG(INFO, LOG_TAG, "__wifi_activated_cb");
- if (result == WIFI_ERROR_NONE)
- {
- OIC_LOG(INFO,LOG_TAG,"#### Success to activate Wi-Fi device!");
- }
- wifi_scan(__scan_request_cb, NULL);
-
-}
-static void ESActivateWifi()
-{
- int error_code;
- error_code = wifi_initialize();
- OIC_LOG_V(INFO,LOG_TAG,"#### WIFI INITIALIZED WITH STATUS :%d", error_code);
-
- error_code = wifi_activate(__wifi_activated_cb, NULL);
- OIC_LOG_V(INFO,LOG_TAG,"#### WIFI ACTIVATED WITH STATUS :%d", error_code);
-
- bool wifi_activated = false;
- wifi_is_activated(&wifi_activated);
- if (wifi_activated)
- {
- OIC_LOG(INFO,LOG_TAG,"#### Success to get Wi-Fi device state.");
- int scan_result = wifi_scan(__scan_request_cb, NULL);
- OIC_LOG_V(INFO,LOG_TAG,"#### Wifi scan result:%d", scan_result);
- }
- else
- {
- OIC_LOG(ERROR,LOG_TAG, "#### Fail to get Wi-Fi device state.");
- }
-}
-
-static void start()
-{
- OIC_LOG(INFO, LOG_TAG, "START");
- ESActivateWifi();
-}
-
-void ConnectToWiFiNetwork(const char *ssid, const char *pass,
- ESEnrolleeNetworkEventCallback cb)
-{
- OIC_LOG_V(INFO, LOG_TAG, "ConnectToWiFiNetwork %s %s",ssid,pass);
- gPass = pass;
- gSsid = ssid;
- gNetworkEventCb = cb;
- start();
-}
-
-ESResult getCurrentNetworkInfo(OCConnectivityType targetType, NetworkInfo *info)
-{
- if (targetType == CT_ADAPTER_IP)
- {
- info->type = CT_ADAPTER_IP;
- info->ipaddr = gIpAddress;
- if (strlen(gSsid) <= MAXSSIDLEN)
- {
- OICStrcpy(info->ssid, sizeof(info->ssid), gSsid);
- return ES_OK;
- }
- else
- {
- return ES_ERROR;
- }
- }
-
- return ES_ERROR;
-}
-
+++ /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
- *
- * This file contains IP network handling functionality for Enrollee device
- */
-
-#ifndef ES_NETWORK_HANDLER_H_
-#define ES_NETWORK_HANDLER_H_
-
-
-#include <string.h>
-#include "easysetup.h"
-#include "logger.h"
-#include "escommon.h"
-
-#define MAXSSIDLEN 33
-#define MAXNETCREDLEN 20
-#define MAXNUMTYPE 5
-#define MAXADDRLEN 15
-
-/*
- * Callback function for updating the Network status to the subscribers
- *
- * @param esResult ESResult provides the current state of the network connection status
- */
-typedef void (*ESEnrolleeNetworkEventCallback)(ESResult esResult);
-
-typedef struct
-{
- OCConnectivityType type;
- // for WiFI
- //IPAddress ipaddr;
- char *ipaddr;
- char ssid[MAXSSIDLEN];
- // for BT, BLE
- //byte mac[6];
-} NetworkInfo;
-
-void ConnectToWiFiNetwork(const char *ssid, const char *pass,
- ESEnrolleeNetworkEventCallback);
-ESResult getCurrentNetworkInfo(OCConnectivityType targetType, NetworkInfo *info);
-
-#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 "softapnative.h"
-
-/**
- * This API will create the Soft AP at Enrollee device.
- */
-void ESCreateSoftapNative(const char * ssid, const char* passwd, SoftAPCallbackNative cb)
-{
- // TODO: Assign proper values after hardware integration is supported to create SoftAp
- //We are not using this now. Assiging NULL to remove SVACE error
- const char *ip = (char *)0;
- const char *macaddr = (char *)0;
- const char *devicename = (char *)0;
-
- // Soft is created successfully. This callback may be send from other cascaded callbacks
- cb(SOFTAP_SUCCESS, ip, macaddr, devicename);
-
- // TODO: Use below code to indicate failed on-boarding / softap creation
- // Soft creation is failed. This callback may be send from other cascaded callbacks
- //cb(SOFTAP_FAILED, nullptr,nullptr,nullptr);
-}
-
+++ /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_ENROLLEE_SOFTAP_H__
-#define EASYSETUP_ENROLLEE_SOFTAP_H__
-
-#ifdef __cplusplus
-extern "C" {
-#endif // __cplusplus
-
-
-#define SOFTAP_SUCCESS 1
-#define SOFTAP_FAILED 0
-
-/**
- * @file
- *
- * This file contains the API declaration for creating & configuration for SoftAP
- */
-
-//This callback signagure may get changed as per the native implementation.
-typedef void (*SoftAPCallbackNative)(int result, const char *ip, const char* mac_addr,
- const char*device_name);
-/**
- * This API creats the Soft AP using the platform specific native system calls.
- * @Note This API to be implemented by the OEM if Enrollee device SoC supports SoftAP
- *
- * @param networkType NetworkType on which OnBoarding has to be performed.
- * @param ssid SSID of the target SoftAP network to which the Enrollee is
- * connecting.
- * @param passwd Password of the target SoftAP network to which the Enrollee is
- * connecting
- * @param SoftAPCallbackNative EventCallback for for updating the Enrollee OnBoarding status
- * result to the application
- */
-
-void ESCreateSoftapNative(const char * ssid, const char* passwd, SoftAPCallbackNative cb);
-
-#ifdef __cplusplus
-}
-#endif // __cplusplus
-
-
-#endif /* EASYSETUP_ENROLLEE_SOFTAP_H__ */
-
-
-
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 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 <gtest/gtest.h>
+#include <HippoMocks/hippomocks.h>
+#include <atomic>
+#include <functional>
+#include <condition_variable>
+#include <mutex>
+#include <chrono>
+
+#include "ESMediatorSimulator.h"
+#include "easysetup.h"
+
+using namespace OC;
+
+namespace
+{
+ std::atomic_bool g_isStartedStack(false);
+
+ std::chrono::milliseconds g_waitForResponse(1000);
+
+ std::condition_variable responseCon;
+ std::mutex mutexForCondition;
+
+ ESMediatorSimulator g_mediatorSimul;
+}
+
+class TestWithMock: public testing::Test
+{
+public:
+ MockRepository mocks;
+
+protected:
+ virtual ~TestWithMock() noexcept(noexcept(std::declval<Test>().~Test()))
+ {
+ }
+
+ virtual void TearDown()
+ {
+ try
+ {
+ mocks.VerifyAll();
+ }
+ catch (...)
+ {
+ mocks.reset();
+ throw;
+ }
+ }
+};
+
+class EasysetupEnrolleeTest : public TestWithMock
+{
+public:
+ EasysetupEnrolleeTest() = default;
+ ~EasysetupEnrolleeTest() = default;
+
+ static void discoveredResource(std::shared_ptr<OC::OCResource>)
+ {
+ std::cout << __func__ << std::endl;
+ }
+
+ static void onGetStatus(std::shared_ptr< GetEnrolleeStatus >)
+ {
+ std::cout << __func__ << std::endl;
+ }
+
+ static void onGetConfiguration(std::shared_ptr< GetConfigurationStatus >)
+ {
+ std::cout << __func__ << std::endl;
+ }
+
+ static void deviceProvisioningStatusCallback(std::shared_ptr< DevicePropProvisioningStatus >)
+ {
+ std::cout << __func__ << std::endl;
+ }
+
+ static void cloudProvisioningStatusCallback(std::shared_ptr< CloudPropProvisioningStatus >)
+ {
+ std::cout << __func__ << std::endl;
+ }
+
+ static void WiFiProvCbInApp(ESWiFiProvData *)
+ {
+ std::cout << __func__ << std::endl;
+ }
+
+ static void DevConfProvCbInApp(ESDevConfProvData *)
+ {
+ std::cout << __func__ << std::endl;
+ }
+
+ static void CloudDataCbInApp(ESCloudProvData *)
+ {
+ std::cout << __func__ << std::endl;
+ }
+
+ ESResult startEnrollee()
+ {
+ ESResourceMask resourcemMask = (ESResourceMask)(ES_WIFI_RESOURCE |
+ ES_CLOUD_RESOURCE |
+ ES_DEVCONF_RESOURCE);
+ ESProvisioningCallbacks callbacks;
+ callbacks.WiFiProvCb = &EasysetupEnrolleeTest::WiFiProvCbInApp;
+ callbacks.DevConfProvCb = &EasysetupEnrolleeTest::DevConfProvCbInApp;
+ callbacks.CloudDataProvCb = &EasysetupEnrolleeTest::CloudDataCbInApp;
+
+ return ESInitEnrollee(false, resourcemMask, callbacks);
+ }
+
+ ESResult setDeviceProperty()
+ {
+ ESDeviceProperty deviceProperty = {
+ {{WIFI_11G, WiFi_EOF}, WIFI_5G}, {"Test Device"}
+ };
+
+ return ESSetDeviceProperty(&deviceProperty);
+ }
+
+protected:
+
+ void SetUp()
+ {
+ TestWithMock::SetUp();
+
+ if (g_isStartedStack == false)
+ {
+ if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
+ {
+ printf("OCStack init error!!\n");
+ return;
+ }
+
+ g_isStartedStack = true;
+ }
+ }
+
+ void TearDown()
+ {
+ TestWithMock::TearDown();
+ }
+
+};
+
+TEST_F(EasysetupEnrolleeTest, ESInitEnrolleeSuccess)
+{
+ ESResult ret = startEnrollee();
+ EXPECT_EQ(ret, ES_OK);
+ ESTerminateEnrollee();
+}
+
+TEST_F(EasysetupEnrolleeTest, ESInitEnrolleeFailedByWiFiCbIsNull)
+{
+ ESResourceMask resourcemMask = (ESResourceMask)(ES_WIFI_RESOURCE |
+ ES_CLOUD_RESOURCE |
+ ES_DEVCONF_RESOURCE);
+ ESProvisioningCallbacks callbacks;
+ callbacks.WiFiProvCb = NULL;
+ callbacks.DevConfProvCb = &EasysetupEnrolleeTest::DevConfProvCbInApp;
+ callbacks.CloudDataProvCb = &EasysetupEnrolleeTest::CloudDataCbInApp;
+
+ ESResult ret = ESInitEnrollee(false, resourcemMask, callbacks);
+ EXPECT_EQ(ret, ES_ERROR);
+ ESTerminateEnrollee();
+}
+
+TEST_F(EasysetupEnrolleeTest, ESInitEnrolleeFailedByDevConfCbIsNull)
+{
+ ESResourceMask resourcemMask = (ESResourceMask)(ES_WIFI_RESOURCE |
+ ES_CLOUD_RESOURCE |
+ ES_DEVCONF_RESOURCE);
+ ESProvisioningCallbacks callbacks;
+ callbacks.WiFiProvCb = &EasysetupEnrolleeTest::WiFiProvCbInApp;
+ callbacks.DevConfProvCb = NULL;
+ callbacks.CloudDataProvCb = &EasysetupEnrolleeTest::CloudDataCbInApp;
+
+ ESResult ret = ESInitEnrollee(false, resourcemMask, callbacks);
+ EXPECT_EQ(ret, ES_ERROR);
+ ESTerminateEnrollee();
+}
+
+TEST_F(EasysetupEnrolleeTest, ESInitEnrolleeFailedByCloudCbIsNull)
+{
+ ESResourceMask resourcemMask = (ESResourceMask)(ES_WIFI_RESOURCE |
+ ES_CLOUD_RESOURCE |
+ ES_DEVCONF_RESOURCE);
+ ESProvisioningCallbacks callbacks;
+ callbacks.WiFiProvCb = &EasysetupEnrolleeTest::WiFiProvCbInApp;
+ callbacks.DevConfProvCb = &EasysetupEnrolleeTest::DevConfProvCbInApp;
+ callbacks.CloudDataProvCb = NULL;
+
+ ESResult ret = ESInitEnrollee(false, resourcemMask, callbacks);
+ EXPECT_EQ(ret, ES_ERROR);
+ ESTerminateEnrollee();
+}
+
+TEST_F(EasysetupEnrolleeTest, FindProvisioningResourceAtEnrolleeWithSuccess)
+{
+ mocks.ExpectCallFunc(discoveredResource).Do(
+ [](std::shared_ptr<OC::OCResource> resource)
+ {
+ try
+ {
+ std::cout<<"DISCOVERED Resource:"<<std::endl;
+ // Get the resource host address
+ std::string uri = resource->uri();
+ std::cout << "\tURI of the resource: " << uri << std::endl;
+ } catch (OCException &e)
+ {
+ std::cout << e.reason() << std::endl;
+ }
+
+ });
+
+ ESResult ret = startEnrollee();
+
+ g_mediatorSimul.discoverRemoteEnrollee(discoveredResource);
+
+ std::unique_lock< std::mutex > lock{ mutexForCondition };
+ responseCon.wait_for(lock, g_waitForResponse);
+
+ EXPECT_EQ(ret, ES_OK);
+
+ ESTerminateEnrollee();
+}
+
+TEST_F(EasysetupEnrolleeTest, SetDevicePropertyWithSuccess)
+{
+ ESResult ret = startEnrollee();
+ ret = setDeviceProperty();
+ EXPECT_EQ(ret, ES_OK);
+ ESTerminateEnrollee();
+}
+
+TEST_F(EasysetupEnrolleeTest, SetProvStatusWithSuccess)
+{
+ ESResult ret = startEnrollee();
+ ret = ESSetState(ES_STATE_CONNECTED_TO_ENROLLER);
+ EXPECT_EQ(ret, ES_OK);
+ ESTerminateEnrollee();
+}
+
+TEST_F(EasysetupEnrolleeTest, SetErrorCodeWithSuccess)
+{
+ ESResult ret = startEnrollee();
+ ret = ESSetErrorCode(ES_ERRCODE_PW_WRONG);
+ EXPECT_EQ(ret, ES_OK);
+ ESTerminateEnrollee();
+}
+
+TEST_F(EasysetupEnrolleeTest, DevicePropertyIsWellConstructedInResponsePayload)
+{
+ bool isWellConstructed = false;
+ mocks.ExpectCallFunc(onGetConfiguration).Do(
+ [& isWellConstructed](std::shared_ptr< GetConfigurationStatus > status)
+ {
+ if(status->getESResult() == ES_OK)
+ {
+ EnrolleeConf conf = status->getEnrolleeConf();
+ if(conf.getWiFiModes().at(0) == WIFI_11G &&
+ conf.getWiFiFreq() == WIFI_5G &&
+ !strcmp(conf.getDeviceName().c_str(), "Test Device"))
+ {
+ isWellConstructed = true;
+ }
+ }
+ });
+ ESResult ret = startEnrollee();
+ ret = setDeviceProperty();
+
+ g_mediatorSimul.getConfiguration(onGetConfiguration);
+
+ std::unique_lock< std::mutex > lock{ mutexForCondition };
+ responseCon.wait_for(lock, g_waitForResponse);
+
+ EXPECT_EQ(ret, ES_OK);
+
+ ESTerminateEnrollee();
+}
+
+TEST_F(EasysetupEnrolleeTest, ProvisioningPropertiesIsWellConstructedInResponsePayload)
+{
+ bool isWellConstructed = false;
+ mocks.ExpectCallFunc(onGetStatus).Do(
+ [& isWellConstructed](std::shared_ptr< GetEnrolleeStatus > status)
+ {
+ if(status->getESResult() == ES_OK)
+ {
+ EnrolleeStatus enrolleeStatus = status->getEnrolleeStatus();
+
+
+ if(enrolleeStatus.getProvStatus() == ES_STATE_CONNECTED_TO_ENROLLER &&
+ enrolleeStatus.getLastErrCode() == ES_ERRCODE_NO_INTERNETCONNECTION)
+ {
+ isWellConstructed = true;
+ }
+ }
+ });
+ ESResult ret = startEnrollee();
+ ret = setDeviceProperty();
+ ret = ESSetState(ES_STATE_CONNECTED_TO_ENROLLER);
+ ret = ESSetErrorCode(ES_ERRCODE_NO_INTERNETCONNECTION);
+
+ g_mediatorSimul.getStatus(onGetStatus);
+
+ std::unique_lock< std::mutex > lock{ mutexForCondition };
+ responseCon.wait_for(lock, g_waitForResponse);
+
+ EXPECT_EQ(ret, ES_OK);
+
+ ESTerminateEnrollee();
+}
+
+TEST_F(EasysetupEnrolleeTest, WiFiAndDevConfProperiesProvisionedWithSuccess)
+{
+ int cntForReceivedCallbackWithSuccess = 0;
+
+ mocks.OnCallFunc(deviceProvisioningStatusCallback).Do(
+ [& cntForReceivedCallbackWithSuccess](std::shared_ptr< DevicePropProvisioningStatus > status)
+ {
+ if(status->getESResult() == ES_OK)
+ cntForReceivedCallbackWithSuccess++;
+ });
+
+ mocks.OnCallFunc(WiFiProvCbInApp).Do(
+ [& cntForReceivedCallbackWithSuccess](ESWiFiProvData *data)
+ {
+ if(!strcmp(data->ssid, "Iotivity_SSID") &&
+ !strcmp(data->pwd, "Iotivity_PWD") &&
+ data->authtype == WPA2_PSK &&
+ data->enctype == TKIP_AES)
+ {
+ cntForReceivedCallbackWithSuccess++;
+ }
+ });
+ mocks.OnCallFunc(DevConfProvCbInApp).Do(
+ [& cntForReceivedCallbackWithSuccess](ESDevConfProvData *data)
+ {
+ if(!strcmp(data->language, "korean") &&
+ !strcmp(data->country, "Korea"))
+ {
+ cntForReceivedCallbackWithSuccess++;
+ }
+ });
+
+ startEnrollee();
+
+ g_mediatorSimul.provisionDeviceProperties(deviceProvisioningStatusCallback);
+
+ std::unique_lock< std::mutex > lock{ mutexForCondition };
+ responseCon.wait_for(lock, g_waitForResponse);
+
+ EXPECT_EQ(cntForReceivedCallbackWithSuccess, 3);
+
+ ESTerminateEnrollee();
+}
+
+TEST_F(EasysetupEnrolleeTest, CloudServerProperiesProvisionedWithSuccess)
+{
+ int cntForReceivedCallbackWithSuccess = 0;
+
+ mocks.OnCallFunc(cloudProvisioningStatusCallback).Do(
+ [& cntForReceivedCallbackWithSuccess](std::shared_ptr< CloudPropProvisioningStatus > status)
+ {
+ // Will called twice
+ if(status->getESResult() == ES_OK)
+ {
+ cntForReceivedCallbackWithSuccess++;
+ }
+ });
+
+ mocks.OnCallFunc(CloudDataCbInApp).Do(
+ [& cntForReceivedCallbackWithSuccess](ESCloudProvData *data)
+ {
+ if(!strcmp(data->authCode, "authCode") &&
+ !strcmp(data->authProvider, "authProvider") &&
+ !strcmp(data->ciServer, "ciServer"))
+ {
+ cntForReceivedCallbackWithSuccess++;
+ }
+ });
+
+ startEnrollee();
+
+ g_mediatorSimul.provisionCloudProperties(cloudProvisioningStatusCallback);
+
+ std::unique_lock< std::mutex > lock{ mutexForCondition };
+ responseCon.wait_for(lock, g_waitForResponse);
+
+ EXPECT_EQ(cntForReceivedCallbackWithSuccess, 3);
+
+ ESTerminateEnrollee();
+}
+
+
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 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_MEDIATOR_SIMULATOR_H_
+#define _ES_MEDIATOR_SIMULATOR_H_
+
+#include <iostream>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "oic_malloc.h"
+
+#include "EasySetup.h"
+#include "ESRichCommon.h"
+
+#define PROV_RESOURCE_TYPE "ocf.wk.prov"
+
+using namespace OIC::Service;
+
+class ESMediatorSimulator
+{
+private:
+ std::function<void(std::shared_ptr<OC::OCResource> resource)> m_discoveryCb;
+ std::function<void(std::shared_ptr< GetConfigurationStatus > status)> m_getConfigurationCb;
+ std::function<void(std::shared_ptr< GetEnrolleeStatus >)> m_getStatusCb;
+ std::function<void(std::shared_ptr< DevicePropProvisioningStatus >)> m_DevicePropProvisioningCb;
+ std::function<void(std::shared_ptr< CloudPropProvisioningStatus >)> m_CloudPropProvisioningCb;
+
+ std::shared_ptr<RemoteEnrollee> m_remoteEnrollee;
+
+public:
+ ESMediatorSimulator()
+ : m_remoteEnrollee(), m_discoveryCb(), m_getConfigurationCb(), m_getStatusCb(),
+ m_DevicePropProvisioningCb(), m_CloudPropProvisioningCb()
+ {
+ };
+ ~ESMediatorSimulator() = default;
+
+ ESMediatorSimulator(const ESMediatorSimulator &) = delete;
+ ESMediatorSimulator & operator = (const ESMediatorSimulator &) = delete;
+
+ ESMediatorSimulator(ESMediatorSimulator &&) = delete;
+ ESMediatorSimulator & operator = (ESMediatorSimulator &&) = delete;
+
+ void discoverRemoteEnrollee(std::function<void(std::shared_ptr<OC::OCResource> resource)> cb)
+ {
+ m_discoveryCb = cb;
+ std::string uri = std::string("/oic/res?rt=") + PROV_RESOURCE_TYPE;
+ OC::OCPlatform::findResource("", uri,
+ OCConnectivityType::CT_DEFAULT,
+ std::bind(&ESMediatorSimulator::discoverRemoteEnrolleeCb,
+ this, std::placeholders::_1));
+
+ }
+
+ void getConfiguration(std::function<void(std::shared_ptr< GetConfigurationStatus >)> cb)
+ {
+ m_getConfigurationCb = cb;
+ m_remoteEnrollee = NULL;
+ std::string uri = std::string("/oic/res?rt=") + PROV_RESOURCE_TYPE;
+ OC::OCPlatform::findResource("", uri,
+ OCConnectivityType::CT_DEFAULT,
+ std::bind(&ESMediatorSimulator::discoverRemoteEnrolleeCbToGetConfiguration,
+ this, std::placeholders::_1));
+ }
+
+ void getStatus(std::function<void(std::shared_ptr< GetEnrolleeStatus >)> cb)
+ {
+ m_getStatusCb = cb;
+ m_remoteEnrollee = NULL;
+ std::string uri = std::string("/oic/res?rt=") + PROV_RESOURCE_TYPE;
+ OC::OCPlatform::findResource("", uri,
+ OCConnectivityType::CT_DEFAULT,
+ std::bind(&ESMediatorSimulator::discoverRemoteEnrolleeCbToGetStatus,
+ this, std::placeholders::_1));
+ }
+
+ void provisionDeviceProperties(std::function<void(std::shared_ptr< DevicePropProvisioningStatus >)> cb)
+ {
+ m_DevicePropProvisioningCb = cb;
+ m_remoteEnrollee = NULL;
+ std::string uri = std::string("/oic/res?rt=") + PROV_RESOURCE_TYPE;
+ OC::OCPlatform::findResource("", uri,
+ OCConnectivityType::CT_DEFAULT,
+ std::bind(&ESMediatorSimulator::discoverRemoteEnrolleeCbToProvisionDeviceProperties,
+ this, std::placeholders::_1));
+ }
+
+ void provisionCloudProperties(std::function<void(std::shared_ptr< CloudPropProvisioningStatus >)> cb)
+ {
+ m_CloudPropProvisioningCb = cb;
+ m_remoteEnrollee = NULL;
+ std::string uri = std::string("/oic/res?rt=") + PROV_RESOURCE_TYPE;
+ OC::OCPlatform::findResource("", uri,
+ OCConnectivityType::CT_DEFAULT,
+ std::bind(&ESMediatorSimulator::discoverRemoteEnrolleeCbToProvisionCloudProperties,
+ this, std::placeholders::_1));
+ }
+
+private:
+
+ void discoverRemoteEnrolleeCb(std::shared_ptr<OC::OCResource> resource)
+ {
+ if(!resource->getResourceTypes().at(0).compare(PROV_RESOURCE_TYPE) && m_discoveryCb)
+ {
+ m_discoveryCb(resource);
+ m_discoveryCb = NULL;
+ }
+ }
+
+ void getConfigurationCallback(std::shared_ptr< GetConfigurationStatus > getConfigurationStatus)
+ {
+ if(m_getConfigurationCb != NULL)
+ {
+ m_getConfigurationCb(getConfigurationStatus);
+ m_getConfigurationCb = NULL;
+ }
+ }
+
+ void discoverRemoteEnrolleeCbToGetConfiguration(std::shared_ptr<OC::OCResource> resource)
+ {
+ if(!resource->getResourceTypes().at(0).compare(PROV_RESOURCE_TYPE) && m_getConfigurationCb
+ && !m_remoteEnrollee)
+ {
+ m_remoteEnrollee = EasySetup::getInstance()->createRemoteEnrollee(resource);
+
+ if(m_remoteEnrollee != NULL)
+ {
+ m_remoteEnrollee->getConfiguration(std::bind(
+ &ESMediatorSimulator::getConfigurationCallback, this, std::placeholders::_1));
+ }
+ }
+ }
+
+ void getStatusCallback(std::shared_ptr< GetEnrolleeStatus > getEnrolleeStatus)
+ {
+ if(m_getStatusCb != NULL)
+ {
+ m_getStatusCb(getEnrolleeStatus);
+ m_getStatusCb = NULL;
+ }
+ }
+
+ void discoverRemoteEnrolleeCbToGetStatus(std::shared_ptr<OC::OCResource> resource)
+ {
+ if(!resource->getResourceTypes().at(0).compare(PROV_RESOURCE_TYPE) && m_getStatusCb
+ && !m_remoteEnrollee)
+ {
+ m_remoteEnrollee = EasySetup::getInstance()->createRemoteEnrollee(resource);
+
+ if(m_remoteEnrollee != NULL)
+ {
+ m_remoteEnrollee->getStatus(std::bind(
+ &ESMediatorSimulator::getStatusCallback, this, std::placeholders::_1));
+ }
+ }
+ }
+
+ void deviceProvisioningStatusCallback(std::shared_ptr< DevicePropProvisioningStatus >
+ devicePropProvisioningStatus)
+ {
+ if(m_DevicePropProvisioningCb != NULL)
+ {
+ m_DevicePropProvisioningCb(devicePropProvisioningStatus);
+ m_DevicePropProvisioningCb = NULL;
+ }
+ }
+
+ void discoverRemoteEnrolleeCbToProvisionDeviceProperties(std::shared_ptr<OC::OCResource> resource)
+ {
+ if(!resource->getResourceTypes().at(0).compare(PROV_RESOURCE_TYPE) &&
+ m_DevicePropProvisioningCb && !m_remoteEnrollee)
+ {
+ m_remoteEnrollee = EasySetup::getInstance()->createRemoteEnrollee(resource);
+
+ if(m_remoteEnrollee != NULL)
+ {
+ DeviceProp devProp;
+ devProp.setWiFiProp("Iotivity_SSID", "Iotivity_PWD", WPA2_PSK, TKIP_AES);
+ devProp.setDevConfProp("korean", "Korea");
+
+ m_remoteEnrollee->provisionDeviceProperties(devProp,
+ std::bind(&ESMediatorSimulator::deviceProvisioningStatusCallback,
+ this, std::placeholders::_1));
+ }
+ }
+ }
+
+ void cloudProvisioningStatusCallback(std::shared_ptr< CloudPropProvisioningStatus >
+ cloudPropProvisioningStatus)
+ {
+ if(m_CloudPropProvisioningCb != NULL)
+ {
+ m_CloudPropProvisioningCb(cloudPropProvisioningStatus);
+ if(cloudPropProvisioningStatus->getESCloudState() == ES_CLOUD_PROVISIONING_SUCCESS)
+ {
+ m_CloudPropProvisioningCb = NULL;
+ }
+ }
+ }
+
+ void discoverRemoteEnrolleeCbToProvisionCloudProperties(std::shared_ptr<OC::OCResource> resource)
+ {
+ if(!resource->getResourceTypes().at(0).compare(PROV_RESOURCE_TYPE) &&
+ m_CloudPropProvisioningCb && !m_remoteEnrollee)
+ {
+ m_remoteEnrollee = EasySetup::getInstance()->createRemoteEnrollee(resource);
+
+ if(m_remoteEnrollee != NULL)
+ {
+ CloudProp cloudProp;
+ cloudProp.setCloudProp("authCode", "authProvider", "ciServer");
+
+ m_remoteEnrollee->provisionCloudProperties(cloudProp,
+ std::bind(&ESMediatorSimulator::cloudProvisioningStatusCallback,
+ this, std::placeholders::_1));
+ }
+ }
+ }
+};
+
+
+#endif //_NS_CONSUMER_SIMULATOR_H_
+
-#######################################################################
+#******************************************************************
+#
# Copyright 2016 Samsung Electronics All Rights Reserved.
#
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-import os
-import os.path
+##
+# Notification Unit Test build script
+##
+
+Import('env')
+
+if env.get('RELEASE'):
+ env.AppendUnique(CCFLAGS = ['-Os'])
+ env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+else:
+ env.AppendUnique(CCFLAGS = ['-g'])
+
+if env.get('LOGGING'):
+ env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+
+######################################################################
+#unit test setting
+######################################################################
+src_dir = lib_env.get('SRC_DIR')
+gtest_dir = src_dir + '/extlibs/gtest/gtest-1.7.0'
-# SConscript file for Local PKI google tests
-gtest_env = SConscript('#extlibs/gtest/SConscript')
-enrollee_test_env = gtest_env.Clone()
-src_dir = enrollee_test_env.get('SRC_DIR')
-target_os = enrollee_test_env.get('TARGET_OS')
+easysetup_test_env = lib_env.Clone()
+target_os = env.get('TARGET_OS')
######################################################################
# Build flags
######################################################################
+GTest = File(gtest_dir + '/lib/.libs/libgtest.a')
+GTest_Main = File(gtest_dir + '/lib/.libs/libgtest_main.a')
+
+easysetup_test_env.AppendUnique(LIBPATH = [lib_env.get('BUILD_DIR')])
+easysetup_test_env.AppendUnique(LIBS = [
+ 'connectivity_abstraction', 'oc', 'octbstack', 'oc_logger', 'coap',
+ GTest_Main, GTest])
+
+if target_os not in ['windows', 'winrt']:
+ easysetup_test_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
+
+easysetup_test_env.AppendUnique(CXXFLAGS = ['-pthread'])
+easysetup_test_env.AppendUnique(LIBS = ['pthread'])
+
+easysetup_test_env.PrependUnique(CPPPATH = [ src_dir + '/extlibs/hippomocks-master', gtest_dir + '/include'])
-enrollee_test_env.PrependUnique(CPPPATH = [
- enrollee_test_env.get('SRC_DIR') + '/resource/c_common/ocrandom/include',
- enrollee_test_env.get('SRC_DIR') + '/resource/csdk/stack/include/internal',
- enrollee_test_env.get('SRC_DIR') + '/resource/csdk/connectivity/api',
- enrollee_test_env.get('SRC_DIR') + '/resource/c_common/oic_malloc/include',
- enrollee_test_env.get('SRC_DIR') + '/resource/include',
- enrollee_test_env.get('SRC_DIR') + '/resource/csdk/logger/include',
- enrollee_test_env.get('SRC_DIR') + '/resource/oc_logger/include',
- enrollee_test_env.get('SRC_DIR') + '/resource/csdk/stack/include',
- enrollee_test_env.get('SRC_DIR') + '/resource/csdk/stack/include/internal',
- enrollee_test_env.get('SRC_DIR') + '/resource/csdk/logger/include',
- enrollee_test_env.get('SRC_DIR') + '/resource/csdk/security/include',
- enrollee_test_env.get('SRC_DIR') + '/extlibs/cjson',
- enrollee_test_env.get('SRC_DIR') + '/extlibs/sqlite3',
- enrollee_test_env.get('SRC_DIR') + '/service/easy-setup/inc',
- enrollee_test_env.get('SRC_DIR') + '/service/easy-setup/enrollee/linux/wifi',
- enrollee_test_env.get('SRC_DIR') + '/service/easy-setup/enrollee/inc',
- enrollee_test_env.get('SRC_DIR') + '/service/easy-setup/enrollee/src'])
-
-enrollee_test_env.AppendUnique(LIBPATH = [enrollee_test_env.get('BUILD_DIR')])
-enrollee_test_env.PrependUnique(LIBS = [ 'octbstack',
- 'ocsrm',
- 'connectivity_abstraction',
- 'coap'])
-if target_os not in ['windows']:
- enrollee_test_env.AppendUnique(LIBS = ['m'])
-
-if target_os != 'darwin':
- enrollee_test_env.PrependUnique(LIBS = ['oc_logger'])
-
-if enrollee_test_env.get('SECURED') == '1':
- enrollee_test_env.AppendUnique(LIBS = ['tinydtls'])
-
-if enrollee_test_env.get('LOGGING'):
- enrollee_test_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
-
-if enrollee_test_env.get('ES_SOFTAP_MODE') == 'ENROLLEE_SOFTAP':
- print "ES_SOFTAP_MODE == ENROLLEE_SOFTAP"
- enrollee_test_env.AppendUnique(CPPDEFINES = ['ENROLLEE_SOFTAP'])
-
-enrollee_test_env.PrependUnique(LIBS = ['ESEnrolleeSDK'])
+easysetup_test_env.AppendUnique(CPPPATH = ['../../../../resource/include',
+ '../inc',
+ '../../inc',
+ '../../mediator/richsdk/inc'])
######################################################################
-# Source files and Targets
+# Build Test
######################################################################
-enrolleetests = enrollee_test_env.Program('enrolleetests', ['enrolleetests.cpp'])
-Alias("test", [enrolleetests])
+easysetup_enrollee_test_env = easysetup_test_env.Clone()
+easysetup_enrollee_test_env.AppendUnique(LIBS = ['ESEnrolleeSDK', 'ESMediatorRich'])
-enrolleetests.AppendTarget('test')
-if enrollee_test_env.get('TEST') == '1':
- if target_os in ['linux']:
- from tools.scons.RunTest import *
- run_test(enrollee_test_env,
- '',
- 'service/easy-setup/enrollee/unittests/enrolleetests')
+easysetup_enrollee_test_src = env.Glob('./ESEnrolleeTest.cpp')
+easysetup_enrollee_test = easysetup_enrollee_test_env.Program('easysetup_enrollee_test', easysetup_enrollee_test_src)
+Alias("easysetup_enrollee_test", easysetup_enrollee_test)
+env.AppendTarget('easysetup_enrollee_test')
+if env.get('TEST') == '1':
+ if target_os == 'linux':
+ from tools.scons.RunTest import *
+ run_test(easysetup_enrollee_test_env, '', 'service/easy-setup/enrollee/unittests/easysetup_enrollee_test')
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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
- *
- * This file contains the implementation for EasySetup Enrollee testcases
- */
-
-#include "gtest/gtest.h"
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <stdlib.h>
-
-//-----------------------------------------------------------------------------
-// Includes
-//-----------------------------------------------------------------------------
-#include <stdio.h>
-#include <string.h>
-
-#include <iostream>
-#include <stdint.h>
-
-#include "ocstack.h"
-#include "logger.h"
-#include "oic_malloc.h"
-#include "escommon.h"
-#include "easysetup.h"
-#include "onboarding.h"
-#include "resourcehandler.h"
-#include "softap.h"
-#include "easysetupcallbacks.h"
-
-#include "gtesthelper.h"
-
-using namespace std;
-
-namespace itst = iotivity::test;
-
-#define DEFAULT_CONTEXT_VALUE 0x99
-
-//-----------------------------------------------------------------------------
-// Private variables
-//-----------------------------------------------------------------------------
-static const char TAG[] = "TestHarness";
-
-char ssid[] = "EasySetup123";
-char passwd[] = "EasySetup123";
-
-//-----------------------------------------------------------------------------
-// Callback functions
-//-----------------------------------------------------------------------------
-extern "C" void EventCallbackInApplication(ESResult esResult,
- ESEnrolleeState enrolleeState)
-{
- OIC_LOG(INFO, TAG, "Entering EventCallbackInApplication");
-
- if(esResult != ES_OK)
- {
- cout<<"Easy stup is failed at Enrollee state = "<<enrolleeState<<endl;
- }
- else
- {
- if(enrolleeState == ES_ON_BOARDED_STATE)
- {
- cout<<"Device is successfully OnBoared on Adhoc network"<<endl;
- }
- else if (enrolleeState == ES_PROVISIONED_STATE)
- {
- cout<<"Device is provisioned with target network's credentials"<<endl;
- }
- else if (enrolleeState == ES_ON_BOARDED_TARGET_NETWORK_STATE)
- {
- cout<<"Device is onboarded/connected with target network"<<endl;
- }
- else
- {
- cout<<"Wrong state !! Easy setup is failed at Enrollee state = "<<enrolleeState<<endl;
- }
- }
-}
-
-//-----------------------------------------------------------------------------
-// Local functions
-//-----------------------------------------------------------------------------
-
-void InitESEnrollee()
-{
- OIC_LOG(INFO, TAG, "Entering InitESEnrollee");
-
- EXPECT_EQ(ES_OK, ESInitEnrollee(CT_ADAPTER_IP,
- "EasySetup123",
- "EasySetup123",
- 0,
- EventCallbackInApplication));
- OIC_LOG(INFO, TAG, "Leaving InitESEnrollee");
-}
-
-//-----------------------------------------------------------------------------
-// Tests
-//-----------------------------------------------------------------------------
-
-TEST(ESEnrolleeInit, ESEnrolleeInitNullSSID)
-{
- EXPECT_EQ(ES_ERROR, ESInitEnrollee(CT_ADAPTER_IP, 0, passwd, 0, EventCallbackInApplication));
-}
-
-TEST(ESEnrolleeInit, ESEnrolleeInitNullPassword)
-{
- EXPECT_EQ(ES_ERROR, ESInitEnrollee(CT_ADAPTER_IP, ssid, 0, 0, EventCallbackInApplication));
-}
-
-TEST(ESEnrolleeInit, ESEnrolleeInitNullCb)
-{
- EXPECT_EQ(ES_ERROR, ESInitEnrollee(CT_ADAPTER_IP, ssid, passwd, 0, 0));
-}
-
-TEST(ESEnrolleeInit, ESEnrolleeESInitEnrolleeSuccess)
-{
- EXPECT_EQ(ES_OK, ESInitEnrollee(CT_ADAPTER_IP,
- ssid,
- passwd,
- 0,
- EventCallbackInApplication));
-}
-
-TEST(ESEnrolleeInit, ESEnrolleeBleOnboarding)
-{
- EXPECT_EQ(0, ESBleOnboarding());
-}
-
-TEST(ESEnrolleeInit, ESEnrolleeSoftapOnboarding)
-{
- EXPECT_EQ(true, ESSoftapOnboarding());
-}
-
-TEST(ESOCInit, ESOCInitNullIPAddr)
-{
- EXPECT_EQ(OC_STACK_OK, OCInit(0, 5683, OC_SERVER));
- EXPECT_EQ(OC_STACK_OK, OCStop());
-}
-
-TEST(ESOCInit, ESOCInitNullPort)
-{
- EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 0, OC_SERVER));
- EXPECT_EQ(OC_STACK_OK, OCStop());
-}
-
-TEST(ESOCInit, ESOCInitNullAddrAndPort)
-{
- EXPECT_EQ(OC_STACK_OK, OCInit(0, 0, OC_SERVER));
- EXPECT_EQ(OC_STACK_OK, OCStop());
-}
-
-TEST(ESOCInit, ESOCInitInvalidMode)
-{
- EXPECT_EQ(OC_STACK_ERROR, OCInit(0, 0, (OCMode)10));
- EXPECT_EQ(OC_STACK_ERROR, OCStop());
-}
-
-TEST(ESProvisioning, ESInitProvisioningResource)
-{
- EXPECT_EQ(ES_RESOURCECREATED, ESInitProvisioning());
-}
-
-TEST(ESProvisioning, ESInitProvisioningWithOCStackClientMode)
-{
- EXPECT_EQ(OC_STACK_OK, OCInit(NULL, 0, OC_CLIENT));
- EXPECT_EQ(ES_ERROR, ESInitProvisioning());
- EXPECT_EQ(OC_STACK_OK, OCStop());
-}
-
-TEST(ESProvisioningResource, ESCreateProvisioningResourceSecurityDisabled)
-{
- EXPECT_EQ(OC_STACK_OK, OCInit(0, 0, OC_SERVER));
- EXPECT_EQ(OC_STACK_OK, CreateProvisioningResource(0));
- EXPECT_EQ(OC_STACK_OK, OCStop());
-}
-
-TEST(ESProvisioningResource, ESCreateProvisioningResourceSecurityEnabled)
-{
- EXPECT_EQ(OC_STACK_OK, OCInit(0, 0, OC_SERVER));
- EXPECT_EQ(OC_STACK_OK, CreateProvisioningResource(1));
- EXPECT_EQ(OC_STACK_OK, OCStop());
-}
-
-TEST(ESProvisioningResource, ESDeleteProvisioningResource)
-{
- EXPECT_EQ(OC_STACK_OK, OCInit(0, 0, OC_SERVER));
- EXPECT_EQ(OC_STACK_OK, CreateProvisioningResource(0));
- EXPECT_EQ(OC_STACK_OK, DeleteProvisioningResource());
- EXPECT_EQ(OC_STACK_OK, OCStop());
-}
-
-TEST(ESProvisioningResource, ESDeleteProvisioningResourceWithoutCreating)
-{
- EXPECT_EQ(OC_STACK_OK, OCInit(0, 0, OC_SERVER));
- EXPECT_EQ(OC_STACK_NO_RESOURCE, DeleteProvisioningResource());
- EXPECT_EQ(OC_STACK_OK, OCStop());
-}
-
-TEST(ESOnboarding, ESOnboardingSoftAp)
-{
- EXPECT_EQ(1, ESOnboard(ssid, passwd, ESOnboardingCallback));
-}
-
-TEST(ESOnboarding, ESOnboardingSoftApEnrollee)
-{
-#ifdef ENROLLEE_SOFTAP
- EXPECT_EQ(1, ESSoftapAtEnrollee());
- EXPECT_EQ(0, ESSoftapAtMediator());
-#endif
-}
-
-TEST(ESOnboarding, ESOnboardingSoftApMediator)
-{
-#ifndef ENROLLEE_SOFTAP
- EXPECT_EQ(0, ESSoftapAtEnrollee());
- EXPECT_EQ(1, ESSoftapAtMediator());
-#endif
-}
-
-TEST(ESOnboarding, ESOnboardingSoftApHost)
-{
-#ifdef ENROLLEE_SOFTAP
- EXPECT_EQ(ENROLLEE, ESSoftapHost());
-#else
- EXPECT_EQ(MEDIATOR, ESSoftapHost());
-#endif
-}
-
-TEST(ESStop, ESTerminateEasysetupWithoutESInit)
-{
- EXPECT_EQ(ES_ERROR, ESTerminateEnrollee());
-}
-
-TEST(ESStop, ESTerminateEasysetupWithoutOCStack)
-{
- EXPECT_EQ(ES_OK, ESInitEnrollee(CT_ADAPTER_IP,
- ssid,
- passwd,
- 0,
- EventCallbackInApplication));
- EXPECT_EQ(ES_ERROR, ESTerminateEnrollee());
-}
-
-TEST(ESStop, ESTerminateEasysetupWithOutCreateProvisioningResource)
-{
- EXPECT_EQ(ES_OK, ESInitEnrollee(CT_ADAPTER_IP,
- ssid,
- passwd,
- 0,
- EventCallbackInApplication));
- EXPECT_EQ(OC_STACK_OK, OCInit(0, 0, OC_SERVER));
- EXPECT_EQ(ES_ERROR, ESTerminateEnrollee());
- EXPECT_EQ(OC_STACK_OK, OCStop());
-}
-
-TEST(ESStop, ESTerminateEasysetupWithoutProviosioningResource)
-{
- EXPECT_EQ(ES_OK, ESInitEnrollee(CT_ADAPTER_IP,
- ssid,
- passwd,
- 0,
- EventCallbackInApplication));
- EXPECT_EQ(OC_STACK_OK, OCInit(NULL, 0, OC_SERVER));
- EXPECT_EQ(ES_ERROR, ESTerminateEnrollee());
- EXPECT_EQ(OC_STACK_OK, OCStop());
-}
-
-TEST(ESStop, ESTerminateEasysetupSuccess)
-{
- EXPECT_EQ(ES_OK, ESInitEnrollee(CT_ADAPTER_IP,
- ssid,
- passwd,
- 0,
- EventCallbackInApplication));
- EXPECT_EQ(OC_STACK_OK, OCInit(NULL, 0, OC_SERVER));
- EXPECT_EQ(ES_RESOURCECREATED, ESInitProvisioning());
- EXPECT_EQ(ES_OK, ESTerminateEnrollee());
- EXPECT_EQ(OC_STACK_OK, OCStop());
-}
-
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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 IOTY_GTEST_HELPER_H
-#define IOTY_GTEST_HELPER_H
-
-#include <atomic>
-#include <chrono>
-#include <condition_variable>
-#include <future>
-#include <mutex>
-#include <thread>
-
-namespace iotivity
-{
- namespace test
- {
- /**
- * Simple implementation of a deadman's timer that can be used to
- * terminate a test that hangs.
- *
- * Since there is no standard way to terminate an individual thread,
- * the entire process will be killed once time has been exceeded.
- *
- * @note provisions for watchdog thread cleanup are not currently added.
- * Testing has not yet shown any need for such complexity.
- */
- class DeadmanTimer
- {
- public:
-
- /**
- * Creates an instance of a timer set to kill the running process
- * after the specified timeout.
- *
- * If the destructor is invoked before time is up (aka this instance
- * goes out of scope) the timeout will not cause the program to be
- * terminated.
- *
- * @param time to wait before assuming the process is hung and must be
- * killed.
- * Examples of values that can be passed include
- * std::chrono::milliseconds(250), std::chrono::seconds(5),
- * std::chrono::minutes(3).
- */
- DeadmanTimer(std::chrono::milliseconds timeout) :
- m_ctx(new DeadmanCtx(timeout)),
- m_thread()
- {
- m_thread = std::thread([this](){run(m_ctx);});
- {
- std::unique_lock<std::mutex> lock(m_ctx->m_mutex);
- while (!m_ctx->m_isArmed)
- {
- m_ctx->m_cond.wait(lock);
- }
- }
- // Now that the thread is live, we can stop tracking it.
- m_thread.detach();
- }
-
- /**
- * Destructor that also will cancel the termination of the
- * running process.
- */
- ~DeadmanTimer()
- {
- std::unique_lock<std::mutex> lock(m_ctx->m_mutex);
- m_ctx->m_isArmed = false;
- }
-
- private:
-
- /**
- * Shared data that main and child thread might both need to
- * access.
- *
- * Avoids referencing data in class instances that have been
- * deleted.
- */
- class DeadmanCtx
- {
- public:
-
- DeadmanCtx(std::chrono::milliseconds timeout) :
- m_mutex(),
- m_cond(),
- m_isArmed(false),
- m_timeout(timeout)
- {
- }
-
- std::mutex m_mutex;
- std::condition_variable m_cond;
- bool m_isArmed;
- std::chrono::milliseconds m_timeout;
- };
-
- // Explicitly block assignment and copy ctor
- DeadmanTimer &operator=(const DeadmanTimer &rhs);
- DeadmanTimer(const iotivity::test::DeadmanTimer &rhs);
-
- std::shared_ptr<DeadmanCtx> m_ctx;
- std::thread m_thread;
-
-
- static void run(std::shared_ptr<DeadmanCtx> ctx)
- {
- // Let the calling thread know it can stop waiting:
- {
- std::unique_lock<std::mutex> lock(ctx->m_mutex);
- ctx->m_isArmed = true;
- ctx->m_cond.notify_all();
- }
-
- std::this_thread::sleep_for(ctx->m_timeout);
-
- std::unique_lock<std::mutex> lock(ctx->m_mutex);
- if (ctx->m_isArmed)
- {
- try {
- throw std::runtime_error("deadman timer expired");
- }
- catch (std::exception&)
- {
- std::terminate();
- }
- }
- }
- };
- } // namespace test
-} // namespace iotivity
-
-#endif // IOTY_GTEST_HELPER_H
#include "ocstack.h"
#include "octypes.h"
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
// Defines
#define OIC_STRING_MAX_VALUE 100
#define IPV4_ADDR_SIZE 16
#define IP_PORT 55555
-#define NET_WIFI_SSID_SIZE 100
-#define NET_WIFI_PWD_SIZE 100
/**
* @brief Mac address length for BT port
/**
* 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_PROVSTATUS "ps"
+#define OC_RSRVD_ES_LAST_ERRORCODE "lec"
+#define OC_RSRVD_ES_LINKS "links"
+#define OC_RSRVD_ES_SUPPORTEDWIFIMODE "swmt"
+#define OC_RSRVD_ES_SUPPORTEDWIFIFREQ "swf"
+#define OC_RSRVD_ES_SSID "tnn"
+#define OC_RSRVD_ES_CRED "cd"
+#define OC_RSRVD_ES_AUTHTYPE "wat"
+#define OC_RSRVD_ES_ENCTYPE "wet"
+#define OC_RSRVD_ES_AUTHCODE "ac"
+#define OC_RSRVD_ES_AUTHPROVIDER "apn"
+#define OC_RSRVD_ES_CISERVER "cis"
+#define OC_RSRVD_ES_SERVERID "sid"
+#define OC_RSRVD_ES_DEVNAME "dn"
+#define OC_RSRVD_ES_LANGUAGE "lang"
+#define OC_RSRVD_ES_COUNTRY "ctry"
/**
* Easysetup defined resoruce types and uris.
*/
-#define OC_RSRVD_ES_PROV_RES_TYPE "oic.r.prov"
-#define OC_RSRVD_ES_URI_PROV "/oic/prov"
-#define OC_RSRVD_ES_URI_NET "/oic/net"
+#define OC_RSRVD_ES_RES_TYPE_PROV "ocf.wk.prov"
+#define OC_RSRVD_ES_URI_PROV "/ProvisioningResURI"
+#define OC_RSRVD_ES_RES_TYPE_WIFI "ocf.wk.wifi"
+#define OC_RSRVD_ES_URI_WIFI "/WiFiProvisioningResURI"
+#define OC_RSRVD_ES_RES_TYPE_CLOUDSERVER "ocf.wk.cloudserver"
+#define OC_RSRVD_ES_URI_CLOUDSERVER "/CloudServerProvisioningResURI"
+#define OC_RSRVD_ES_RES_TYPE_DEVCONF "ocf.wk.devconf"
+#define OC_RSRVD_ES_URI_DEVCONF "/DevConfProvisioningResURI"
+
+#define NUM_WIFIMODE 10
+#define MAX_SSIDLEN 33
+#define MAX_CREDLEN 20
+
+#define MAX_DEVICELEN 100
+#define MAX_WEBLINKLEN 100
/**
- * @brief Defines for Provisioning status accepted values
+ * @brief Supported WIFI frequency like 2.4G and 5G
*/
-#define ES_PS_NEED_PROVISIONING 1
-#define ES_PS_PROVISIONING_COMPLETED 2
-#define ES_PS_TRIGGER_INIT_VALUE 0
-#define ES_PS_TRIGGER_CONNECTION 1
+typedef enum
+{
+ WIFI_24G = 0, /**< 2.4G **/
+ WIFI_5G, /**< 5G **/
+ WIFI_BOTH, /**< 2.4G and 5G **/
+ WIFI_FREQ_NONE /**< EOF **/
+} WIFI_FREQ;
+
+/**
+ * @brief Supported WIFI mode like 802.11g and 802.11n
+ */
+typedef enum
+{
+ WIFI_11A = 0, /**< 802.11a **/
+ WIFI_11B, /**< 802.11b **/
+ WIFI_11G, /**< 802.11g **/
+ WIFI_11N, /**< 802.11n **/
+ WIFI_11AC, /**< 802.11ac **/
+ WiFi_EOF = 999
+} WIFI_MODE;
/**
-* Device Roles defined for each device type used in easy setup
-*/
+ * @brief WIFI Authentication tlype of the Enroller
+ */
typedef enum
{
- ENROLLEE,
- MEDIATOR,
- ENROLLER,
-} DeviceRole;
+ NONE_AUTH = 0, /**< NO authentication **/
+ WEP, /**< WEP **/
+ WPA_PSK, /**< WPA-PSK **/
+ WPA2_PSK /**< WPA2-PSK **/
+} WIFI_AUTHTYPE;
/**
-* On-boarding connection to create Adhoc network.
-*/
+ * @brief WIFI encryption type of the Enroller
+ */
typedef enum
{
- SOFTAP,
- BLE,
-} OBConnection;
+ NONE_ENC = 0, /**< NO encryption **/
+ WEP_64, /**< WEP-64 **/
+ WEP_128, /**< WEP-128**/
+ TKIP, /**< TKIP **/
+ AES, /**< AES **/
+ TKIP_AES /**< TKIP-AES **/
+} WIFI_ENCTYPE;
typedef enum
{
ES_RECVREQOFNETRES,
ES_RECVUPDATEOFPROVRES,
ES_RECVTRIGGEROFPROVRES,
+ ES_UNAUTHORIZED = 31,
+ ES_UNSUPPORTED_OPERATION = 41
} ESResult;
+/**
+ * @brief Indicate which resource is created in Enrollee
+ */
typedef enum
{
- /**
- * Default state of the device
- */
- ES_INIT_STATE,
-
- /**
- * Device will move to this state once the on boarding begins
- */
- ES_ON_BOARDING_STATE,
+ ES_WIFI_RESOURCE = 0x01,
+ ES_CLOUD_RESOURCE = 0x02,
+ ES_DEVCONF_RESOURCE = 0x04
+} ESResourceMask;
+/**
+ * @brief Indicate enrollee and provisioning status. Provisioning status is shown in "provisioning
+ * status" property in provisioning resource.
+ */
+typedef enum
+{
/**
- * Device will move to this state after successful on-boarding of the device
+ * Default state of the device
*/
- ES_ON_BOARDED_STATE,
+ ES_STATE_INIT = 0,
/**
- * Device will move to this state once the on boarding is done
- */
- ES_PROVISIONING_STATE,
+ * Status indicating being cnnecting to target network
+ */
+ ES_STATE_CONNECTING_TO_ENROLLER,
/**
- * Easy setup process is successful.
- */
- ES_PROVISIONED_STATE,
+ * Status indicating successful conection to target network
+ */
+ ES_STATE_CONNECTED_TO_ENROLLER,
/**
- * 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
- */
- ES_OWNERSHIP_TRANSFERRING_STATE,
+ * Status indicating failure connection to target network
+ */
+ ES_STATE_CONNECTED_FAIL_TO_ENROLLER,
/**
- * This state is arbitrary one, any time device can come into this state
- * Device will move to this state if the ownership transfer is completed
- */
- ES_OWNERSHIP_TRANSFERRED_STATE,
+ * Status indicating successful registration to cloud
+ */
+ ES_STATE_REGISTERED_TO_CLOUD,
/**
- * 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
- */
- ES_FACTORY_RESET_STATE,
-
- /**
- * Enrollee moves to this state after connecting to target network
- */
- ES_ON_BOARDED_TARGET_NETWORK_STATE,
-}ESEnrolleeState;
-
-/**
- * Provisioning Device Status
- */
-typedef struct
-{
- // Address of remote server
- OCDevAddr * addr;
- // Indicates adaptor type on which the response was received
- OCConnectivityType connType;
-} EasySetupDeviceInfo;
+ * Status indicating failure registeration to cloud
+ */
+ ES_STATE_REGISTRRED_FAIL_TO_CLOUD
+} ESEnrolleeState, ProvStatus;
/**
- * Provosioning Status
+ * @brief Indicate last error code to describe a reason of error during easy setup.
*/
typedef enum
{
- DEVICE_PROVISIONED = 0,
- DEVICE_NOT_PROVISIONED,
- DEVICE_OWNED,
- DEVICE_NOT_OWNED
-} EasySetupState, ProvStatus;
-
-/**
- * Response from queries to remote servers.
- */
-typedef struct
-{
- // EasySetup Status
- EasySetupState provStatus;
- // EasySetup Device Info
- EasySetupDeviceInfo provDeviceInfo;
-} EasySetupInfo, ProvisioningInfo;
-
-/**
- * @brief Network information of the Enroller
- */
-typedef union
-{
/**
- * @brief BT Mac Information
+ * Init Error Code
*/
- struct
- {
- char btMacAddress[NET_MACADDR_SIZE]; /**< BT mac address **/
- } BT;
+ ES_ERRCODE_NO_ERROR = 0,
/**
- * @brief LE MAC Information
- */
- struct
- {
- char leMacAddress[NET_MACADDR_SIZE]; /**< BLE mac address **/
- } LE;
+ * Error Code that given WiFi's SSID is not found
+ */
+ ES_ERRCODE_SSID_NOT_FOUND,
/**
- * @brief IP Information
- */
- struct
- {
- char ssid[NET_WIFI_SSID_SIZE]; /**< ssid of the Enroller**/
- char pwd[NET_WIFI_PWD_SIZE]; /**< pwd of the Enroller**/
- } WIFI;
-} ProvData;
-
-/**
- * @brief Network Information
- */
-typedef struct
-{
- ProvData provData; /**< Enroller Network Info**/
- OCConnectivityType connType; /**< Connectivity Type**/
-} ProvConfig;
-
-/**
- * Client applications implement this callback to consume responses received from Servers.
- */
-typedef void (*OCProvisioningStatusCB)(EasySetupInfo *easySetupInfo);
+ * Error Code that given WiFi's Password is wrong
+ */
+ ES_ERRCODE_PW_WRONG,
-/**
- * @brief This structure represent configuration information to create wifi onboarding SoftAP or connection.
-*/
+ /**
+ * Error Code that IP address is not allocated
+ */
+ ES_ERRCODE_IP_NOT_ALLOCATED,
+ /**
+ * Error Code that there is no Internet connection
+ */
+ ES_ERRCODE_NO_INTERNETCONNECTION,
-// Note : Below structure is not currently used but added for future purpose.
-typedef struct {
- char ssid[NET_WIFI_SSID_SIZE]; /**< ssid of the onboarding Adhoc Wifi network**/
- char pwd[NET_WIFI_PWD_SIZE]; /**< pwd of the onboarding Adhoc wifi network**/
- bool isSecured; /**< Secure connection**/
-}WiFiOnboardingConfig;
+ /**
+ * Error Code that Timeout occured
+ */
+ ES_ERRCODE_TIMEOUT,
-/**
- * @brief This structure represent onboarding connection instance.
-*/
-typedef struct {
- /*Actual use of ipAddress is for unicast discovery, but also used to identify the Enrollee device as of now,
- device identification should be based on DeviceID in next release.*/
- char ipAddress[IPV4_ADDR_SIZE]; /**< IP Address of the Enrollee **/
- bool isSecured; /**< Secure connection**/
-}WiFiOnboadingConnection;
+ /**
+ * Error Code that Unknown error occured
+ */
+ ES_ERRCODE_UNKNOWN
+} ESErrorCode;
+
+#ifdef __cplusplus
+}
+#endif
#endif //ES_COMMON_H_
target_os = env.get('TARGET_OS')
-# Build easy-setup Mediator C SDK
-SConscript('csdk/SConscript')
-
# Build easy-setup Mediator Rich [C++] SDK
SConscript('richsdk/SConscript')
+++ /dev/null
-#******************************************************************
-#
-# Copyright 2016 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 Mediator CSDK build script
-######################################################################
-
-import os
-
-Import('env')
-
-env.AppendUnique(CPPDEFINES = ['EASY_SETUP_CA_INIT'])
-
-if env.get('RELEASE'):
- env.AppendUnique(CCFLAGS = ['-Os'])
- env.AppendUnique(CPPDEFINES = ['NDEBUG'])
-else:
- env.AppendUnique(CCFLAGS = ['-g'])
-
-if env.get('LOGGING'):
- env.AppendUnique(CPPDEFINES = ['TB_LOG'])
-
-# Easysetup provides reference implemenation of Arduino Enrollee.
-# Mediator applications developed on different platforms will be default defining the
-# flag 'REMOTE_ARDUINO_ENROLEE'. If the target Enrollee is not Arduino, the below commented
-# modifications must be enabled instead (and the existing define must be commented).
-#
-##### The following lines must be uncommented, if target Enrollee is not Arduino
-target_enrollee = env.get('ES_TARGET_ENROLLEE')
-if target_enrollee == 'arduino':
- print "REMOTE_ARDUINO_ENROLEE flag is defined."
- print "The Mediator application will be working only with Arduino Enrollee."
- env.AppendUnique(CPPDEFINES = ['REMOTE_ARDUINO_ENROLEE'])
-
-lib_env = env.Clone()
-easy_setup_env = env.Clone()
-
-target_os = env.get('TARGET_OS')
-
-if target_os in ['android']:
- # Add third party libraries
- SConscript('#service/third_party_libs.scons', 'lib_env')
-
-######################################################################
-# Build flags
-######################################################################
-
-easy_setup_env.AppendUnique(CPPPATH = ['inc', 'src','../../inc'])
-easy_setup_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
-if target_os in ['linux']:
- easy_setup_env.AppendUnique(LIBS = ['pthread', 'dl'])
-
-
-######################################################################
-# Linux Mediator
-######################################################################
-if target_os in ['linux']:
- easy_setup_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
- easy_setup_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
- easy_setup_env.AppendUnique(CXXFLAGS = ['-pthread'])
- easy_setup_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction'])
-
-######################################################################
-# Android Mediator
-######################################################################
-if target_os == 'android':
- 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'])
- easy_setup_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'gnustl_shared'])
- if not env.get('RELEASE'):
- easy_setup_env.AppendUnique(LIBS = ['log'])
-
-
-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/security/include',
- env.get('SRC_DIR') + '/extlibs/cjson',
- env.get('SRC_DIR') + '/service/easy-setup/inc',
- 'inc'])
-
-######################################################################
-# Source files and Targets
-######################################################################
-
-if target_os == 'android':
- es_m_csdk_static = easy_setup_env.StaticLibrary('libESMediatorCSDK',
- ['src/provisioningapi.cpp',
- 'src/wifiprovisioning.cpp',
- 'src/provisioning.cpp'])
- easy_setup_env.InstallTarget(es_m_csdk_static, 'libESMediatorCSDK')
-
-if target_os in ['linux']:
- es_m_csdk_shared = easy_setup_env.SharedLibrary('ESMediatorCSDK',
- ['src/provisioningapi.cpp',
- 'src/wifiprovisioning.cpp',
- 'src/provisioning.cpp'])
- easy_setup_env.InstallTarget(es_m_csdk_shared, 'libESMediatorCSDK')
-
- #Go to build sample apps
- SConscript('../../sampleapp/mediator/linux/csdk_sample/SConscript')
-
-######################################################################
-#Build UnitTestcases for Mediator[CSDK]
-################################################ ######################
-if target_os in ['linux']:
- SConscript('unittests/SConscript')
-
-
-
-
-
-
-
-
-
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#ifndef __ES_PROVISIONING_HANDLER_H_
-#define __ES_PROVISIONING_HANDLER_H_
-
-#include "octypes.h"
-
-#include "logger.h"
-#include "ocstack.h"
-#include "escommon.h"
-
-//-----------------------------------------------------------------------------
-// Defines
-//-----------------------------------------------------------------------------
-#define EASY_SETUP_DEFAULT_CONTEXT_VALUE 0x99
-
-/**
- * List of methods that can be inititated from the client
- */
-OCStackResult InitProvisioningHandler();
-
-OCStackResult TerminateProvisioningHandler();
-
-OCStackResult GetProvisioningStatus(OCQualityOfService qos, const char *query,
- const OCDevAddr *destination);
-
-OCStackResult StartProvisioningProcess(const ProvConfig *netInfo,
- WiFiOnboadingConnection *onboardConn, OCProvisioningStatusCB provisioningStatusCallback,
- char *findResQuery);
-
-void StopProvisioningProcess();
-
-/**
- * Internal worker functions.
- */
-OCStackResult TriggerNetworkConnection(OCQualityOfService qos, const char *query,
- const char *resUri, OCDevAddr *destination, int /*pauseBeforeStart*/);
-
-OCStackApplicationResult TriggerNetworkConnectionResponse(void *ctx, OCDoHandle handle,
- OCClientResponse *clientResponse);
-
-OCStackApplicationResult ProvisionEnrolleeResponse(void *ctx, OCDoHandle handle,
- OCClientResponse *clientResponse);
-
-OCStackResult ProvisionEnrollee(OCQualityOfService qos, const char *query, const char *resUri,
- OCDevAddr *destination, int pauseBeforeStart);
-
-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);
-
-OCStackApplicationResult FindProvisioningResourceResponse(void *ctx, OCDoHandle handle,
- OCClientResponse *clientResponse);
-
-void *FindProvisioningResource(void *data);
-
-ProvisioningInfo *PrepareProvisioingStatusCB(OCClientResponse *clientResponse,
- ProvStatus provStatus);
-
-/**
- * Internal Util functions.
- */
-void LogProvisioningResponse(OCRepPayloadValue * val);
-
-bool ConfigEnrolleeObject(const ProvConfig *netInfo, WiFiOnboadingConnection *onboardConn);
-
-bool ClearMemory();
-
-void SuccessCallback(OCClientResponse * clientResponse);
-
-void ErrorCallback(ProvStatus status);
-
-bool ValidateEnrolleeResponse(OCClientResponse * clientResponse);
-
-bool ValidateFindResourceResponse(OCClientResponse * clientResponse);
-
-bool ValidateEnrolleeBasicResponse(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 ProvConfig *netInfo, WiFiOnboadingConnection *onboardConn,
- OCProvisioningStatusCB provisioningStatusCallback);
-
-bool IsSetupStopped();
-
-#endif //__ES_PROVISIONING_HANDLER_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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#ifndef __EASYSETUP_MGR_H_
-#define __EASYSETUP_MGR_H_
-
-#include <string.h>
-
-#include "logger.h"
-#include "ocstack.h"
-#include "octypes.h"
-#include "escommon.h"
-
-#include "provisioning.h"
-
-//-----------------------------------------------------------------------------
-// Defines
-//-----------------------------------------------------------------------------
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif
- OCStackResult InitProvProcess();
-
- OCStackResult ResetProvProcess();
-
- OCStackResult RegisterCallback(OCProvisioningStatusCB provisioningStatusCallback);
-
- void UnRegisterCallback();
-
- OCStackResult StartProvisioning(const ProvConfig *netInfo,
- WiFiOnboadingConnection *onboardConn);
-
- OCStackResult StopProvisioning(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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "provisioning.h"
-
-//Standard includes
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <signal.h>
-#include <unistd.h>
-#include <pthread.h>
-
-//EasySetup include files
-#include "ocpayload.h"
-#include "escommon.h"
-
-// External includes
-#include "logger.h"
-#include "oic_malloc.h"
-#include "oic_string.h"
-
-#define ES_PROV_TAG "EASY_SETUP_PROVISIONING"
-
-bool gProvisioningCondFlag = false;
-
-static ProvConfig *gProvConfig;
-static WiFiOnboadingConnection *gOnboardConn;
-static char gSzFindResourceQueryUri[MAX_QUERY_LENGTH] =
-{ 0 };
-
-/**
- * @var cbData
- * @brief Callback for providing provisioning status callback to application
- */
-static OCProvisioningStatusCB cbData = NULL;
-
-/**
- * Utility function for error callback.
- */
-void ErrorCallback(ProvStatus status)
-{
- ProvisioningInfo *provInfo = GetCallbackObjectOnError(status);
- if(cbData != NULL)
- {
- cbData(provInfo);
- }
-}
-
-/**
- * Functions implementing the exposed APIs.
- */
-OCStackResult InitProvisioningHandler()
-{
- OCStackResult ret = OC_STACK_ERROR;
- /* Initialize OCStack*/
- if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
- {
- OIC_LOG(ERROR, ES_PROV_TAG, "OCStack init error");
- return ret;
- }
-
- return OC_STACK_OK;
-}
-
-OCStackResult StartProvisioningProcess(const ProvConfig *netInfo,
- WiFiOnboadingConnection *onboardConn, OCProvisioningStatusCB provisioningStatusCallback,
- char *findResQuery)
-{
-
- if (findResQuery != NULL)
- {
- OICStrcpy(gSzFindResourceQueryUri, sizeof(gSzFindResourceQueryUri) - 1, findResQuery);
- }
- else
- {
- OIC_LOG(ERROR, ES_PROV_TAG, PCF("Find resource query is NULL"));
- goto Error;
- }
-
- pthread_t thread_handle;
-
- if (!ValidateEasySetupParams(netInfo, onboardConn, provisioningStatusCallback))
- {
- goto Error;
- }
-
- if (!SetProgress(provisioningStatusCallback))
- {
- // Device provisioning session is running already.
- OIC_LOG(INFO, ES_PROV_TAG, PCF("Device provisioning session is running already"));
- goto Error;
- }
-
- if (!ConfigEnrolleeObject(netInfo, onboardConn))
- {
- goto Error;
- }
-
- if (pthread_create(&thread_handle, NULL, FindProvisioningResource, NULL))
- {
- goto Error;
-
- }
-
- pthread_join(thread_handle, NULL);
-
- return OC_STACK_OK;
-
- Error:
- {
- ErrorCallback(DEVICE_NOT_PROVISIONED);
- ClearMemory();
- return OC_STACK_ERROR;
- }
-
-}
-
-void StopProvisioningProcess()
-{
- ResetProgress();
-}
-
-OCStackResult TerminateProvisioningHandler()
-{
- OCStackResult ret = OC_STACK_ERROR;
- if (OCStop() != OC_STACK_OK)
- {
- OIC_LOG(ERROR, ES_PROV_TAG, "OCStack stop error");
- }
-
- gProvisioningCondFlag = true;
- ResetProgress();
-
- ret = OC_STACK_OK;
- return ret;
-}
-
-OCStackApplicationResult TriggerNetworkConnectionResponse(void* /*ctx*/, OCDoHandle /*handle*/,
- OCClientResponse *clientResponse)
-{
- OIC_LOG_V(DEBUG, ES_PROV_TAG, "INSIDE TriggerNetworkConnectionResponse");
-
- // If user stopped the process then return from this function;
- if (IsSetupStopped())
- {
- ErrorCallback(DEVICE_NOT_PROVISIONED);
- ClearMemory();
- return OC_STACK_DELETE_TRANSACTION;
- }
-
- if (!ValidateEnrolleeBasicResponse(clientResponse))
- {
- ErrorCallback(DEVICE_NOT_PROVISIONED);
- return OC_STACK_DELETE_TRANSACTION;
- }
-
- SuccessCallback(clientResponse);
- return OC_STACK_KEEP_TRANSACTION;
-}
-
-OCStackResult TriggerNetworkConnection(OCQualityOfService qos, const char *query,
- const char *resUri, OCDevAddr *destination, int /*pauseBeforeStart*/)
-{
- OIC_LOG_V(INFO, ES_PROV_TAG, "Inside TriggerNetworkConnection");
-
- OCRepPayload *payload = OCRepPayloadCreate();
-
- OCRepPayloadSetUri(payload, resUri);
- OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_TR, ES_PS_TRIGGER_CONNECTION);
-
- OIC_LOG_V(DEBUG, ES_PROV_TAG, "Triggering network connection from Mediator");
-
- OCStackResult ret = InvokeOCDoResource(query, OC_REST_POST, destination, qos,
- TriggerNetworkConnectionResponse, payload, NULL, 0);
-
- return ret;
-}
-
-
-
-bool ClearMemory()
-{
-
- OIC_LOG(DEBUG, ES_PROV_TAG, "thread_pool_add_task of FindProvisioningResource failed");
- OICFree(gProvConfig);
- OICFree(gOnboardConn);
-
- return true;
-
-}
-
-bool ConfigEnrolleeObject(const ProvConfig *netInfo, WiFiOnboadingConnection *connection)
-{
-
- //Copy Network Provisioning Information
- gProvConfig = (ProvConfig *) OICCalloc(1, sizeof(ProvConfig));
- gOnboardConn = (WiFiOnboadingConnection *) OICCalloc(1, sizeof(WiFiOnboadingConnection));
-
- if (gProvConfig == NULL)
- {
- OIC_LOG(ERROR, ES_PROV_TAG, "Invalid input..");
- return false;
- }
-
- if (gOnboardConn == NULL)
- {
- OIC_LOG(ERROR, ES_PROV_TAG, "Invalid input..");
- return false;
- }
-
- memcpy(gProvConfig, netInfo, sizeof(ProvConfig));
- memcpy(gOnboardConn, connection, sizeof(WiFiOnboadingConnection));
-
- OIC_LOG_V(DEBUG, ES_PROV_TAG, "Network Provisioning Info. SSID = %s",
- gProvConfig->provData.WIFI.ssid);
-
- OIC_LOG_V(DEBUG, ES_PROV_TAG, "Network Provisioning Info. PWD = %s",
- gProvConfig->provData.WIFI.pwd);
-
- return true;
-
-}
-
-void LogProvisioningResponse(OCRepPayloadValue * val)
-{
-
- switch (val->type)
- {
- case OCREP_PROP_NULL:
- OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s: NULL", val->name);
- break;
- case OCREP_PROP_INT:
- OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(int):%lld", val->name, val->i);
- break;
- case OCREP_PROP_DOUBLE:
- OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(double):%f", val->name, val->d);
- break;
- case OCREP_PROP_BOOL:
- OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(bool):%s", val->name, val->b ? "true" : "false");
- break;
- case OCREP_PROP_STRING:
- OIC_LOG_V(DEBUG, ES_PROV_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, ES_PROV_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, ES_PROV_TAG, "\t\t%s(int array):%zu x %zu x %zu",
- val->name,
- val->arr.dimensions[0], val->arr.dimensions[1],
- val->arr.dimensions[2]);
- break;
- case OCREP_PROP_DOUBLE:
- OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(double array):%zu x %zu x %zu",
- val->name,
- val->arr.dimensions[0], val->arr.dimensions[1],
- val->arr.dimensions[2]);
- break;
- case OCREP_PROP_BOOL:
- OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(bool array):%zu x %zu x %zu",
- val->name,
- val->arr.dimensions[0], val->arr.dimensions[1],
- val->arr.dimensions[2]);
- break;
- case OCREP_PROP_STRING:
- OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(string array):%zu x %zu x %zu",
- val->name,
- val->arr.dimensions[0], val->arr.dimensions[1],
- val->arr.dimensions[2]);
- break;
- case OCREP_PROP_OBJECT:
- OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(OCRep array):%zu x %zu x %zu",
- val->name,
- val->arr.dimensions[0], val->arr.dimensions[1],
- val->arr.dimensions[2]);
- break;
- default:
- break;
- }
- break;
- default:
- break;
- }
-}
-
-OCStackResult FindNetworkResource()
-{
- OCStackResult ret = OC_STACK_ERROR;
- if (OCStop() != OC_STACK_OK)
- {
- OIC_LOG(ERROR, ES_PROV_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, ES_PROV_TAG, "Failed to allocate memory");
- return NULL;
- }
-
- OCDevAddr *devAddr = (OCDevAddr *) OICCalloc(1, sizeof(OCDevAddr));
-
- if (devAddr == NULL)
- {
- OIC_LOG_V(ERROR, ES_PROV_TAG, "Failed to allocate memory");
- OICFree(provInfo);
- return NULL;
- }
-
- OICStrcpy(devAddr->addr, sizeof(devAddr->addr), clientResponse->addr->addr);
-
- devAddr->port = clientResponse->addr->port;
-
- provInfo->provDeviceInfo.addr = devAddr;
-
- provInfo->provStatus = provStatus;
-
- return provInfo;
-}
-
-bool InProgress()
-{
-
- // It means already Easy Setup provisioning session is going on.
- if (NULL != cbData)
- {
- OIC_LOG(ERROR, ES_PROV_TAG, "Easy setup session is already in progress");
- return true;
- }
-
- return false;
-}
-
-bool SetProgress(OCProvisioningStatusCB provisioningStatusCallback)
-{
-
- if (InProgress())
- return false;
-
- cbData = provisioningStatusCallback;
-
- return true;
-}
-
-bool ResetProgress()
-{
-
- cbData = NULL;
- return true;
-}
-
-ProvisioningInfo *CreateCallBackObject()
-{
-
- ProvisioningInfo *provInfo = (ProvisioningInfo *) OICCalloc(1, sizeof(ProvisioningInfo));
-
- if (provInfo == NULL)
- {
- OIC_LOG_V(ERROR, ES_PROV_TAG, "Failed to allocate memory");
- return NULL;
- }
-
- OCDevAddr *devAddr = (OCDevAddr *) OICCalloc(1, sizeof(OCDevAddr));
-
- if (devAddr == NULL)
- {
- OIC_LOG_V(ERROR, ES_PROV_TAG, "Failed to allocate memory");
- OICFree(provInfo);
- return NULL;
- }
-
- provInfo->provDeviceInfo.addr = devAddr;
-
- return provInfo;
-
-}
-
-ProvisioningInfo *GetCallbackObjectOnError(ProvStatus status)
-{
-
- ProvisioningInfo *provInfo = CreateCallBackObject();
- OICStrcpy(provInfo->provDeviceInfo.addr->addr, sizeof(provInfo->provDeviceInfo.addr->addr),
- gOnboardConn->ipAddress);
-
- provInfo->provDeviceInfo.addr->port = IP_PORT;
- provInfo->provStatus = status;
- return provInfo;
-}
-
-ProvisioningInfo *GetCallbackObjectOnSuccess(OCClientResponse *clientResponse,
- ProvStatus provStatus)
-{
- ProvisioningInfo *provInfo = CreateCallBackObject();
- OICStrcpy(provInfo->provDeviceInfo.addr->addr, sizeof(provInfo->provDeviceInfo.addr->addr),
- clientResponse->addr->addr);
-
- provInfo->provDeviceInfo.addr->port = clientResponse->addr->port;
- provInfo->provStatus = provStatus;
- return provInfo;
-}
-
-bool ValidateFindResourceResponse(OCClientResponse * clientResponse)
-{
- if (!(clientResponse) || !(clientResponse->payload))
- {
- OIC_LOG_V(INFO, ES_PROV_TAG, "Received Null clientResponse");
- return false;
- }
-
- if (clientResponse->payload->type != PAYLOAD_TYPE_DISCOVERY)
- {
- OIC_LOG_V(DEBUG, ES_PROV_TAG, "Payload is not discovery type");
- return false;
- }
-
- return true;
-}
-
-bool ValidateEnrolleeResponse(OCClientResponse * clientResponse)
-{
- if (!(clientResponse) || !(clientResponse->payload))
- {
- OIC_LOG_V(INFO, ES_PROV_TAG, "Received Null clientResponse");
- return false;
- }
-
- if (clientResponse->payload->type != PAYLOAD_TYPE_REPRESENTATION)
- {
- OIC_LOG_V(DEBUG, ES_PROV_TAG, "Incoming payload is not a representation");
- return false;
- }
-
- // If flow reachese here means no error condition hit.
- return true;
-}
-
-bool ValidateEnrolleeBasicResponse(OCClientResponse * clientResponse)
-{
- if (!clientResponse)
- {
- OIC_LOG_V(INFO, ES_PROV_TAG, "Received Null clientResponse");
- return false;
- }
-
- if(clientResponse->result != OC_STACK_OK)
- {
- OIC_LOG_V(INFO, ES_PROV_TAG, "Received error response");
- return false;
- }
-
- // If flow reaches, then there no error condition hit.
- return true;
-}
-
-
-void SuccessCallback(OCClientResponse * clientResponse)
-{
- ProvisioningInfo *provInfo = GetCallbackObjectOnSuccess(clientResponse, DEVICE_PROVISIONED);
- if(cbData != NULL)
- {
- cbData(provInfo);
- }
-}
-
-void* FindProvisioningResource(void* /*data*/)
-{
-
- // If user stopped the process before thread get scheduled then check and return from this function;
- if (IsSetupStopped())
- {
- ErrorCallback(DEVICE_NOT_PROVISIONED);
- ClearMemory();
- return NULL;
- }
-
- OCStackResult ret = OC_STACK_ERROR;
-
- OIC_LOG_V(DEBUG, ES_PROV_TAG, "szFindResourceQueryUri = %s", gSzFindResourceQueryUri);
-
- OCCallbackData ocCBData;
-
- ocCBData.cb = FindProvisioningResourceResponse;
- ocCBData.context = (void *) EASY_SETUP_DEFAULT_CONTEXT_VALUE;
- ocCBData.cd = NULL;
-
- ret = OCDoResource(NULL, OC_REST_DISCOVER, gSzFindResourceQueryUri, NULL, NULL,
- gProvConfig->connType, OC_LOW_QOS, &ocCBData, NULL, 0);
-
- if (ret != OC_STACK_OK)
- {
- ErrorCallback(DEVICE_NOT_PROVISIONED);
- ClearMemory();
- }
-
- return NULL;
-}
-
-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 *) EASY_SETUP_DEFAULT_CONTEXT_VALUE;
- cbData.cd = NULL;
-
- ret = OCDoResource(NULL, method, query, dest, (OCPayload *) payload, gProvConfig->connType, qos,
- &cbData, options, numOptions);
-
- if (ret != OC_STACK_OK)
- {
- OIC_LOG_V(ERROR, ES_PROV_TAG, "OCDoResource returns error %d with method %d", ret, method);
- }
-
- return ret;
-}
-
-OCStackResult ProvisionEnrollee(OCQualityOfService qos, const char *query, const char *resUri,
- OCDevAddr *destination, int pauseBeforeStart)
-{
-
- // This sleep is required in case of BLE provisioning due to packet drop issue.
- OIC_LOG_V(INFO, ES_PROV_TAG, "Sleeping for %d seconds", pauseBeforeStart);
- sleep(pauseBeforeStart);
- OIC_LOG_V(INFO, ES_PROV_TAG, "\n\nExecuting ProvisionEnrollee%s", __func__);
-
- OCRepPayload *payload = OCRepPayloadCreate();
-
- OCRepPayloadSetUri(payload, resUri);
- OCRepPayloadSetPropString(payload, OC_RSRVD_ES_TNN, gProvConfig->provData.WIFI.ssid);
- OCRepPayloadSetPropString(payload, OC_RSRVD_ES_CD, gProvConfig->provData.WIFI.pwd);
-
- OIC_LOG_V(DEBUG, ES_PROV_TAG, "OCPayload ready for ProvisionEnrollee");
-
- OCStackResult ret = InvokeOCDoResource(query, OC_REST_POST, destination, qos,
- ProvisionEnrolleeResponse, payload, NULL, 0);
-
- return ret;
-}
-
-bool IsSetupStopped()
-{
- return (cbData == NULL) ? true : false;
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <signal.h>
-#include <unistd.h>
-#include <stdint.h>
-#include <sstream>
-
-#include "provisioningapi.h"
-#include "oic_string.h"
-
-#define ES_PROV_ADAP_TAG "ES_PROVISIONING_ADAPTER"
-
-//Use ipv4addr for both InitDiscovery and InitDeviceDiscovery
-char ipv4addr[IPV4_ADDR_SIZE] =
-{ 0 };
-
-#ifdef REMOTE_ARDUINO_ENROLEE
-//Arduino Enrollee needs mediator application provide IP and port55555 which is specific
-// to Arduino WiFi enrollee
-static const char * UNICAST_PROVISIONING_QUERY = "coap://%s:%d/oic/res?rt=oic.r.prov";
-#else
-static const char * UNICAST_PROVISIONING_QUERY = "/oic/res?rt=oic.r.prov";
-#endif
-
-volatile static OCProvisioningStatusCB cbData = NULL;
-
-OCStackResult InitProvProcess()
-{
-
- OCStackResult result = OC_STACK_ERROR;
-
- if (InitProvisioningHandler() == OC_STACK_OK)
- {
- result = OC_STACK_OK;
- OIC_LOG(DEBUG, ES_PROV_ADAP_TAG, "InitProvisioningHandler returned Success");
- }
- else
- {
- result = OC_STACK_ERROR;
- OIC_LOG_V(ERROR, ES_PROV_ADAP_TAG, "InitProvisioningHandler returned error = %d",
- result);
- }
-
- return result;
-}
-
-OCStackResult ResetProvProcess()
-{
- return TerminateProvisioningHandler();
-}
-
-OCStackResult RegisterCallback(OCProvisioningStatusCB provisioningStatusCallback)
-{
- OCStackResult result = OC_STACK_OK;
-
- if (provisioningStatusCallback != NULL)
- {
- cbData = provisioningStatusCallback;
- }
- else
- {
- result = OC_STACK_ERROR;
- OIC_LOG(ERROR, ES_PROV_ADAP_TAG, "provisioningStatusCallback is NULL");
- }
-
- return result;
-}
-
-void UnRegisterCallback()
-{
- if (cbData)
- {
- cbData = NULL;
- }
-}
-
-OCStackResult StartProvisioning(const ProvConfig *provConfig, WiFiOnboadingConnection *onboardConn)
-{
-
- char findQuery[MAX_QUERY_LENGTH] =
- { 0 };
-
- if (provConfig == NULL || onboardConn == NULL)
- {
- return OC_STACK_ERROR;
- }
-
-#ifdef REMOTE_ARDUINO_ENROLEE
- //Arduino Enrollee needs mediator application provide IP and port55555 which is specific
- // to Arduino WiFi enrollee
- snprintf(findQuery, sizeof(findQuery) - 1, UNICAST_PROVISIONING_QUERY,
- onboardConn->ipAddress, IP_PORT);
-#else
- OICStrcpy(findQuery, sizeof(findQuery) - 1, UNICAST_PROVISIONING_QUERY);
-#endif
-
- return StartProvisioningProcess(provConfig, onboardConn, cbData, findQuery);
-}
-
-OCStackResult StopProvisioning(OCConnectivityType /*connectivityType*/)
-{
- OCStackResult result = OC_STACK_OK;
-
- 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-// NOTE : Keeping Wifi provisioning in this file to have adaptability while doing OOPs refactoring
-
-#include "provisioning.h"
-
-//Standard includes
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <signal.h>
-#include <unistd.h>
-#include <pthread.h>
-
-//EasySetup include files
-#include "ocpayload.h"
-#include "escommon.h"
-
-// External includes
-#include "logger.h"
-#include "oic_string.h"
-
-#define ES_WIFI_PROV_TAG "ES_WIFI_PROVISIONING"
-
-static const char * UNICAST_PROV_STATUS_QUERY = "coap://%s:%d%s";
-
-OCStackApplicationResult ProvisionEnrolleeResponse(void* /*ctx*/, OCDoHandle /*handle*/,
- OCClientResponse *clientResponse)
-{
- OIC_LOG_V(DEBUG, ES_WIFI_PROV_TAG, "Inside ProvisionEnrolleeResponse");
-
- // If user stopped the process then return from this function;
- if (IsSetupStopped())
- {
- ErrorCallback(DEVICE_NOT_PROVISIONED);
- ClearMemory();
- return OC_STACK_DELETE_TRANSACTION;
- }
-
- if (!ValidateEnrolleeResponse(clientResponse))
- {
- ErrorCallback(DEVICE_NOT_PROVISIONED);
- return OC_STACK_DELETE_TRANSACTION;
- }
-
- char query[OIC_STRING_MAX_VALUE] =
- { '\0' };
- char resUri[MAX_URI_LENGTH] =
- { '\0' };
-
- OIC_LOG_V(DEBUG, ES_WIFI_PROV_TAG, "Resource URI = %s", clientResponse->resourceUri);
-
- OICStrcpy(resUri, sizeof(resUri), clientResponse->resourceUri);
-
-#ifdef REMOTE_ARDUINO_ENROLEE
- //Arduino Enrollee needs mediator application provide IP and port55555 which is specific
- // to Arduino WiFi enrollee
- // REMOTE_ARDUINO_ENROLEE has to be defined if Mediator is being tested with Arduino
- snprintf(query, sizeof(query), UNICAST_PROV_STATUS_QUERY, clientResponse->addr->addr, IP_PORT,
- resUri);
-#else
- snprintf(query, sizeof(query), UNICAST_PROV_STATUS_QUERY, clientResponse->addr->addr,
- clientResponse->addr->port, resUri);
-#endif
-
- if (TriggerNetworkConnection(OC_HIGH_QOS, query, OC_RSRVD_ES_URI_PROV, clientResponse->addr, 0)
- != OC_STACK_OK)
- {
- OIC_LOG(INFO, ES_WIFI_PROV_TAG, "GetProvisioningStatusResponse received NULL clientResponse");
-
- ErrorCallback(DEVICE_NOT_PROVISIONED);
- ClearMemory();
- }
-
- return OC_STACK_DELETE_TRANSACTION;
-}
-
-OCStackApplicationResult GetProvisioningStatusResponse(void* /*ctx*/, OCDoHandle /*handle*/,
- OCClientResponse *clientResponse)
-{
- // If user stopped the process then return from this function;
- if (IsSetupStopped())
- {
- ErrorCallback(DEVICE_NOT_PROVISIONED);
- ClearMemory();
- return OC_STACK_DELETE_TRANSACTION;
- }
-
- if (!ValidateEnrolleeResponse(clientResponse))
- {
- ErrorCallback(DEVICE_NOT_PROVISIONED);
- ClearMemory();
- return OC_STACK_DELETE_TRANSACTION;
- }
-
- OCRepPayload *input = (OCRepPayload *) (clientResponse->payload);
-
- char resUri[MAX_URI_LENGTH] = { '\0' };
-
- OIC_LOG_V(DEBUG, ES_WIFI_PROV_TAG, "resUri = %s", clientResponse->resourceUri);
-
- OICStrcpy(resUri, sizeof(resUri), clientResponse->resourceUri);
-
- while (input)
- {
- int64_t ps;
- if (OCRepPayloadGetPropInt(input, OC_RSRVD_ES_PS, &ps))
- {
-
- if (ps == ES_PS_NEED_PROVISIONING)
- {
- input = input->next;
- continue;
- }
- else
- {
- ErrorCallback(DEVICE_NOT_PROVISIONED);
- ClearMemory();
- return OC_STACK_DELETE_TRANSACTION;
- }
- }
-
- LogProvisioningResponse(input->values);
- input = input->next;
- }
-
- char query[OIC_STRING_MAX_VALUE] =
- { '\0' };
-
-#ifdef REMOTE_ARDUINO_ENROLEE
- //Arduino Enrollee needs mediator application provide IP and port55555 which is specific
- // to Arduino WiFi enrollee
- // REMOTE_ARDUINO_ENROLEE has to be defined if Mediator is being tested with Arduino
- snprintf(query, sizeof(query), UNICAST_PROV_STATUS_QUERY, clientResponse->addr->addr, IP_PORT,
- resUri);
-#else
- snprintf(query, sizeof(query), UNICAST_PROV_STATUS_QUERY, clientResponse->addr->addr,
- clientResponse->addr->port, resUri);
-#endif
-
- if (ProvisionEnrollee(OC_HIGH_QOS, query, OC_RSRVD_ES_URI_PROV, clientResponse->addr, 0)
- != OC_STACK_OK)
- {
- OIC_LOG(INFO, ES_WIFI_PROV_TAG, "GetProvisioningStatusResponse received NULL clientResponse");
-
- ErrorCallback(DEVICE_NOT_PROVISIONED);
- ClearMemory();
- return OC_STACK_DELETE_TRANSACTION;
- }
-
- return OC_STACK_KEEP_TRANSACTION;
-
-}
-
-OCStackResult GetProvisioningStatus(OCQualityOfService qos, const char *query,
- const OCDevAddr *destination)
-{
- OCStackResult ret = OC_STACK_ERROR;
- OCHeaderOption options[MAX_HEADER_OPTIONS];
-
- OIC_LOG(DEBUG, ES_WIFI_PROV_TAG, "Inside GetProvisioningStatus");
-
- 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, qos, GetProvisioningStatusResponse,
- NULL, options, 2);
- return ret;
-}
-
-// This is a function called back when a device is discovered
-OCStackApplicationResult FindProvisioningResourceResponse(void* /*ctx*/, OCDoHandle /*handle*/,
- OCClientResponse *clientResponse)
-{
-
- OIC_LOG_V(INFO, ES_WIFI_PROV_TAG, "Entering FindProvisioningResourceResponse %s",
- clientResponse->devAddr.addr);
-
- // If user stopped the process then return from this function;
- if (IsSetupStopped())
- {
- ErrorCallback(DEVICE_NOT_PROVISIONED);
- ClearMemory();
- return OC_STACK_DELETE_TRANSACTION;
- }
-
- if (!ValidateFindResourceResponse(clientResponse))
- {
- ErrorCallback(DEVICE_NOT_PROVISIONED);
- return OC_STACK_DELETE_TRANSACTION;
- }
-
- char szQueryUri[MAX_QUERY_LENGTH] =
- { 0 };
-
- OCDiscoveryPayload *discoveryPayload = (OCDiscoveryPayload *) (clientResponse->payload);
-
- OIC_LOG_V(DEBUG, ES_WIFI_PROV_TAG, "resUri = %s", discoveryPayload->resources->uri);
-
-#ifdef REMOTE_ARDUINO_ENROLEE
- //Arduino Enrollee needs mediator application provide IP and port55555 which is specific
- // to Arduino WiFi enrollee
- // REMOTE_ARDUINO_ENROLEE has to be defined if Mediator is being tested with Arduino
- snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_PROV_STATUS_QUERY,
- clientResponse->addr->addr,
- IP_PORT,
- discoveryPayload->resources->uri);
-#else
- snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_PROV_STATUS_QUERY,
- clientResponse->devAddr.addr, clientResponse->devAddr.port,
- discoveryPayload->resources->uri);
-#endif
-
- OIC_LOG_V(DEBUG, ES_WIFI_PROV_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;
-
-}
-
-bool ValidateEasySetupParams(const ProvConfig */*netInfo*/, WiFiOnboadingConnection *onboardConn,
- OCProvisioningStatusCB provisioningStatusCallback)
-{
-
- if (onboardConn == NULL || strlen(onboardConn->ipAddress) == 0)
- {
- OIC_LOG(ERROR, ES_WIFI_PROV_TAG, "Request URI is NULL");
- return false;
- }
-
- if (provisioningStatusCallback == NULL)
- {
- OIC_LOG(ERROR, ES_WIFI_PROV_TAG, "ProvisioningStatusCallback is NULL");
- return false;
- }
-
- return true;
-
-}
-
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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 "UnitTestHelper.h"
-
-#include "ocstack.h"
-#include "OCPlatform.h"
-#include "OCApi.h"
-#include "oic_string.h"
-#include "logger.h"
-
-#include "provisioningapi.h"
-#include "provisioning.h"
-#include "escommon.h"
-
-#include <iostream>
-#include <string.h>
-#include <functional>
-#include <pthread.h>
-#include <condition_variable>
-
-class MediatorCSDKTest: public TestWithMock
-{
-
- protected:
- void SetUp()
- {
- TestWithMock::SetUp();
- }
-
- void TearDown()
- {
- TestWithMock::TearDown();
- }
-
-};
-
-//callbacks
-void OCProvisioningStatusCallback(EasySetupInfo *easySetupInfo)
-{
- (void) easySetupInfo;
-}
-
-/* Test cases for prov_adapter*/
-
-//InitProvProcess
-TEST_F(MediatorCSDKTest, testInitProvProcess)
-{
- OCStackResult result = InitProvProcess();
- ASSERT_EQ(OC_STACK_OK, result);
-}
-
-//ResetProvProcess
-TEST_F(MediatorCSDKTest, testResetProvProcess)
-{
- OCStackResult result = ResetProvProcess();
- ASSERT_EQ(OC_STACK_OK, result);
-}
-
-//RegisterCallback [positive]
-TEST_F(MediatorCSDKTest, testRegisterCallback)
-{
- OCStackResult result = RegisterCallback(&OCProvisioningStatusCallback);
- ASSERT_EQ(OC_STACK_OK, result);
-}
-
-//RegisterCallback [Negative]
-TEST_F(MediatorCSDKTest, testRegisterCallbackNegative)
-{
- OCStackResult result = RegisterCallback(NULL);
- ASSERT_EQ(OC_STACK_ERROR, result);
-}
-
-//StartProvisioning [positive]
-TEST_F(MediatorCSDKTest, testStartProvisioning)
-{
- ProvConfig provConfig;
- WiFiOnboadingConnection onboardConn;
-
- strncpy(onboardConn.ipAddress, "1.1.1.1", IPV4_ADDR_SIZE - 1);
-
- strncpy(provConfig.provData.WIFI.ssid, "testAP", NET_WIFI_SSID_SIZE - 1);
- strncpy(provConfig.provData.WIFI.pwd, "test@123", NET_WIFI_PWD_SIZE - 1);
- provConfig.connType = CT_ADAPTER_IP;
-
- //API Call
- OCStackResult result = StartProvisioning(&provConfig, &onboardConn);
-
- ASSERT_EQ(OC_STACK_OK, result);
-}
-
-//StartProvisioning [Negative]
-TEST_F(MediatorCSDKTest, testStartProvisioningNegative)
-{
- OCStackResult result = StartProvisioning(NULL, NULL);
- ASSERT_EQ(OC_STACK_ERROR, result);
-}
-
-//StopProvisioning
-TEST_F(MediatorCSDKTest, testStopProvisioning)
-{
- // This API always return success
- OCStackResult result = StopProvisioning(CT_ADAPTER_IP);
- ASSERT_EQ(OC_STACK_OK, result);
-}
-
-
+++ /dev/null
-#******************************************************************
-#
-# Copyright 2016 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.
-#
-#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-##
-# Mediator[CSDK] Unit Test build script
-##
-import os
-
-# SConscript file for Local PKI google tests
-gtest_env = SConscript('#extlibs/gtest/SConscript')
-lib_env = gtest_env.Clone()
-
-if lib_env.get('RELEASE'):
- lib_env.AppendUnique(CCFLAGS = ['-Os'])
- lib_env.AppendUnique(CPPDEFINES = ['NDEBUG'])
-else:
- lib_env.AppendUnique(CCFLAGS = ['-g'])
-
-if lib_env.get('LOGGING'):
- lib_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
-
-# Add third party libraries
-SConscript('#service/third_party_libs.scons', 'lib_env')
-
-target_os = lib_env.get('TARGET_OS')
-if target_os in ['linux']:
- # Verify that 'hippomocks' mocking code is installed. If not,
- # get it and install it
- SConscript('#extlibs/hippomocks.scons')
-
-mediator_csdk_test_env = lib_env.Clone()
-
-######################################################################
-#unit test setting
-######################################################################
-src_dir = lib_env.get('SRC_DIR')
-
-######################################################################
-# Build flags
-######################################################################
-
-mediator_csdk_test_env.AppendUnique(
- CPPPATH = [
- src_dir + '/extlibs/hippomocks-master',
- '../inc',
- '../../../inc',
- ])
-
-mediator_csdk_test_env.PrependUnique(LIBS = [
- 'ESMediatorCSDK',
- 'oc',
- 'octbstack',
- 'oc_logger',
- 'oc_logger_core',
- 'connectivity_abstraction'])
-
-######################################################################
-# Build Test
-######################################################################
-mediator_csdk_test_src = mediator_csdk_test_env.Glob('./*.cpp')
-
-mediator_csdk_test = mediator_csdk_test_env.Program('mediator_csdk_test', mediator_csdk_test_src)
-Alias("mediator_csdk_test", mediator_csdk_test)
-mediator_csdk_test_env.AppendTarget('mediator_csdk_test')
-
-if mediator_csdk_test_env.get('TEST') == '1':
- target_os = mediator_csdk_test_env.get('TARGET_OS')
- if target_os in ['linux']:
- from tools.scons.RunTest import *
- run_test(mediator_csdk_test_env, '', 'service/easy-setup/mediator/csdk/unittests/mediator_csdk_test')
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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 COMMON_UTILS_UNITTESTHELPER_H
-#define COMMON_UTILS_UNITTESTHELPER_H
-
-#include <gtest/gtest.h>
-#include <HippoMocks/hippomocks.h>
-
-class TestWithMock: public testing::Test
-{
- public:
- MockRepository mocks;
-
- protected:
- virtual ~TestWithMock() noexcept(noexcept(std::declval<Test>().~Test())) {}
-
- virtual void TearDown()
- {
- try
- {
- mocks.VerifyAll();
- }
- catch (...)
- {
- mocks.reset();
- throw;
- }
- }
-};
-#endif // COMMON_UTILS_UNITTESTHELPER_H
env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/internal',
env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/oxm'])
+if not env.get('RELEASE'):
+ easy_setup_env.PrependUnique(LIBS = ['gcov'])
+ easy_setup_env.AppendUnique(CCFLAGS = ['--coverage'])
+
######################################################################
# Source files and Targets
######################################################################
-
print"easysetup_path %s" % easysetup_path
es_src = None
env.AppendUnique(es_src = [os.path.join(easysetup_path, 'src/EnrolleeSecurity.cpp')])
es_common_src = ['src/RemoteEnrollee.cpp',
- 'src/RemoteEnrolleeResource.cpp',
+ 'src/EnrolleeResource.cpp',
+ 'src/CloudResource.cpp',
'src/EasySetup.cpp',
'src/ESException.cpp']
es_sdk_shared = easy_setup_env.SharedLibrary('ESMediatorRich', env.get('es_src'))
easy_setup_env.InstallTarget(es_sdk_shared, 'libESMediatorRich')
+ easy_setup_env.AppendUnique(LINKFLAGS = ['-Wl,-soname,libESMediatorRich.so'])
print "Files path is %s" % env.get('es_src')
######################################################################
+# Generate RichSDK Mediator AAR
+################################################ ######################
+if target_os in ['android']:
+ SConscript('android/SConscript')
+
+######################################################################
# Build RichSDK Mediator Sample App
################################################ ######################
if target_os in ['linux']:
SConscript('../../sampleapp/mediator/linux/richsdk_sample/SConscript')
+if target_os in ['android']:
+ SConscript('../../sampleapp/mediator/android/SConscript')
+
+
######################################################################
#Build UnitTestcases for Mediator[RichSDK]
################################################ ######################
-if target_os in ['linux']:
+if target_os == 'linux':
SConscript('unittests/SConscript')
--- /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" />
+ <afterSyncTasks>
+ <task>generateDebugSources</task>
+ </afterSyncTasks>
+ <option name="ALLOW_USER_CONFIGURATION" value="false" />
+ <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
+ <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
+ <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
+ <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
+ <option name="LIBRARY_PROJECT" value="true" />
+ </configuration>
+ </facet>
+ </component>
+ <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="false">
+ <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
+ <output-test url="file://$MODULE_DIR$/build/intermediates/classes/test/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/testDebug/res" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/testDebug/resources" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/testDebug/assets" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/testDebug/aidl" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/testDebug/java" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/testDebug/jni" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/testDebug/rs" isTestSource="true" />
+ <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" />
+ <sourceFolder url="file://$MODULE_DIR$/src/test/res" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/test/assets" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/test/aidl" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/test/jni" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/test/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/dependency-cache" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/EasySetupCore/iotivity-base-armeabi-debug/unspecified/jars" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/mockable-android-21.jar" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/resources" />
+ <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="library" exported="" scope="TEST" name="mockable-android-21" level="project" />
+ <orderEntry type="module" module-name="iotivity-base-armeabi-debug" exported="" />
+ <orderEntry type="library" exported="" name="iotivity-base-armeabi-debug-unspecified" level="project" />
+ </component>
+</module>
\ No newline at end of file
apply plugin: 'com.android.library'
// Top-level build file where you can add configuration options common to all sub-projects/modules.
-buildscript {
- repositories {
- jcenter()
- }
- dependencies {
- classpath 'com.android.tools.build:gradle:1.2.3'
- }
-}
-
-allprojects {
- repositories {
- jcenter()
- }
-}
android {
compileSdkVersion 21
- buildToolsVersion '21.1.2'
+ buildToolsVersion '20.0.0'
+ archivesBaseName = "iotivity"
+ libraryVariants.all { variant ->
+ variant.outputs.each { output ->
+ def outputFile = output.outputFile
+ if (outputFile != null && outputFile.name.endsWith('.aar')) {
+ def fileName = "${outputFile.name}"
+ output.outputFile = new File(outputFile.parent, fileName)
+ }
+ }
+ }
+
defaultConfig {
minSdkVersion 21
targetSdkVersion 21
+ versionCode 1
+ versionName "1.0"
+ }
+
+ repositories {
+ flatDir {
+ dirs '../../../../../../android/android_api/base/build/outputs/aar'
+ }
}
buildTypes {
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
+
+ lintOptions {
+ abortOnError false
+ }
sourceSets {
- main { java.srcDirs = ['src/main/java', 'src/main/java/common', 'src/main/java/interface'] }
+ main {
+ manifest.srcFile 'src/main/AndroidManifest.xml'
+ jni.srcDirs = [] //disable automatic ndk-build call
+ jniLibs.srcDir new File(buildDir, 'native-libs')
+ }
+ //androidTest.setRoot('src/androidTest')
+ }
+}
+
+dependencies {
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
+ androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.0'
+ androidTestCompile 'com.google.dexmaker:dexmaker:1.0'
+ androidTestCompile 'org.mockito:mockito-core:1.10.19'
+}
+
+////////////////
+////NDK Support
+////////////////
+//If using this, Android studio will fail run the following to set the environment variable for android studio:
+//launchctl setenv ANDROID_NDK_HOME
+//otherwise remove the dependsOn part and run ./gradlew buildNative from the command line
+task copyNativeLibs(type: Copy, dependsOn: 'buildNative') {
+ dependsOn 'buildNative'
+ from(new File('src/main/libs/armeabi')) { include '**/*.so' exclude '**/libgnustl_shared.so', '**/liboc.so', '**/libocstack-jni.so'}
+ into new File(buildDir, 'native-libs/armeabi')
+}
+
+tasks.withType(JavaCompile) { compileTask -> compileTask.dependsOn copyNativeLibs }
+
+clean.dependsOn 'cleanCopyNativeLibs'
+
+tasks.withType(com.android.build.gradle.tasks.PackageApplication) {
+ pkgTask ->
+ pkgTask.jniFolders = new HashSet<File>()
+ pkgTask.jniFolders.add(new File(buildDir, 'native-libs'))
+}
+
+task buildNative(type: Exec) {
+ if (System.env.ANDROID_NDK_HOME != null) {
+ //for windows use 'ndk-build.cmd'
+ //def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build.cmd')
+ def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build')
+ commandLine ndkBuild, "APP_ABI=$TARGET_ARCH", "APP_OPTIM=$RELEASE", '-C', file('src/main').absolutePath
+ } else {
+ println '##################'
+ println 'Skipping NDK build'
+ println 'Reason: ANDROID_NDK_HOME not set.'
+ println '##################'
}
}
\ No newline at end of file
--- /dev/null
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in C:/android/sdk/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the proguardFiles
+# directive in build.gradle.
+#
+# For more details, see
+# http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+# public *;
+#}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module type="JAVA_MODULE" version="4">
- <component name="NewModuleRootManager" inherit-compiler-output="true">
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <sourceFolder url="file://$MODULE_DIR$/java" isTestSource="false" />
- </content>
- <orderEntry type="inheritedJdk" />
- <orderEntry type="sourceFolder" forTests="false" />
- <orderEntry type="library" name="classes" level="project" />
- <orderEntry type="module" module-name="main" />
- </component>
-</module>
\ 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 android.test.AndroidTestCase;
-
-
-public class EasySetupServiceConfigTest extends AndroidTestCase {
-
-
- public void testConstruction() {
-
- EasySetupService service = EasySetupService.getInstance(getContext(), new EasySetupStatus() {
- @Override
- public void onFinished(EnrolleeDevice enrolledevice) {
-
- }
-
- @Override
- public void onProgress(EnrolleeDevice enrolleeDevice) {
-
- }
- });
-
- assertTrue(service != null);
-
-
- }
-
- public void testFinish() {
- EasySetupService service = EasySetupService.getInstance(getContext(), new EasySetupStatus() {
- @Override
- public void onFinished(EnrolleeDevice enrolledevice) {
-
- }
-
- @Override
- public void onProgress(EnrolleeDevice enrolleeDevice) {
-
- }
- });
- service.finish();
-
- // No runtime exception is thrown means test is successful
- assertTrue(true);
-
- }
-
- public void testEnrolleeDeviceFacotryConstruction() {
- EnrolleeDeviceFactory factory = EnrolleeDeviceFactory.newInstance(getContext());
- assertTrue(factory != 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-package org.iotivity.service.easysetup.mediator;
-
-import android.net.wifi.WifiConfiguration;
-import android.test.AndroidTestCase;
-import android.util.Log;
-
-import java.io.IOException;
-
-public class EasySetupServiceTest extends AndroidTestCase {
-
-
- public void testStartSetupWithWiFiOnboarding() {
-
- EasySetupService mService;
- EnrolleeDevice mDevice;
- EnrolleeDeviceFactory mFactory;
-
- final Object lock = new Object();
-
-
- /* Create Easy Setup service */
- mService = EasySetupService.getInstance(getContext(), new EasySetupStatus() {
- @Override
- public void onFinished(EnrolleeDevice enrolledevice) {
-
- //countDownLatch.countDown();
- Utility.toNotify(lock);
-
- if (enrolledevice.isSetupSuccessful()) {
-
- if (enrolledevice.mOnBoardingConfig.getConnType() == WiFiOnBoardingConfig.ConnType.WiFi) {
- IpOnBoardingConnection conn = (IpOnBoardingConnection) enrolledevice.getConnection();
- String ip = conn.getIp();
- if (ip == null || ip.isEmpty()) {
- assertTrue(false);
- return;
- }
- String mac = conn.getHardwareAddress();
- if (mac == null || mac.isEmpty()) {
- assertTrue(false);
- return;
- }
- // Device configured successfully
- assertTrue(true);
- }
-
- } else {
- assertTrue(false);
- }
- }
-
- @Override
- public void onProgress(EnrolleeDevice enrolleeDevice) {
- // Handled in EasySetupStatusTest
- }
- });
-
-
- /* Create On boarding configuration */
- WiFiOnBoardingConfig mWiFiOnBoardingConfig = new WiFiOnBoardingConfig();
- mWiFiOnBoardingConfig.setSSId("EasySetup123");
- mWiFiOnBoardingConfig.setSharedKey("EasySetup123");
- mWiFiOnBoardingConfig.setAuthAlgo(WifiConfiguration.AuthAlgorithm.OPEN);
- mWiFiOnBoardingConfig.setKms(WifiConfiguration.KeyMgmt.WPA_PSK);
-
- /* Create provisioning configuration */
- WiFiProvConfig mWiFiProvConfig = new WiFiProvConfig("hub2.4G", "11112222");
-
- /* Create enrolling device factory instance */
- mFactory = EnrolleeDeviceFactory.newInstance(getContext());
-
- /* Check if the factory created successfully */
- assertTrue(mFactory != null);
-
- /* Create enrolling device */
- mDevice = mFactory.newEnrolleeDevice(mWiFiProvConfig, mWiFiOnBoardingConfig);
-
- /* Check if the the device is created successfully*/
- assertTrue(mDevice != null);
-
- /* Check if the the correct device is created as per the given configuration*/
- assertTrue((mDevice instanceof EnrolleeDeviceWiFiOnboarding));
-
-
- try {
- mService.startSetup(mDevice);
- // If no exception is thrown means setup started successfully.
- assertTrue(true);
-
- } catch (IOException e) {
- assertTrue(false);
- }
- catch (ESException e) {
- assertTrue(false);
- }
-
- try {
-
- Utility.toWait(lock);
-
- Log.i("EasySetupTest", "Lock is released");
-
- if (!mDevice.isSetupSuccessful()) {
- assertTrue(false);
- return;
- }
-
- IpOnBoardingConnection conn = (IpOnBoardingConnection) mDevice.getConnection();
- if (conn == null) {
- assertTrue(false);
- return;
- }
-
- String ip = conn.getIp();
- if (ip == null || ip.isEmpty()) {
- assertTrue(false);
- return;
- }
-
- String mac = conn.getHardwareAddress();
- if (mac == null || mac.isEmpty()) {
- assertTrue(false);
- return;
- }
-
- Log.i("EasySetupTest", "Ip" + conn.getIp());
- Log.i("EasySetupTest", "MAC" + conn.getHardwareAddress());
-
- // Device configured successfully
- assertTrue(true);
-
- } catch (Exception e) {
- e.printStackTrace();
- assertTrue(false);
- }
-
- }
-
-}
\ No newline at end of file
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-package org.iotivity.service.easysetup.mediator;
-
-import android.net.wifi.WifiConfiguration;
-import android.test.AndroidTestCase;
-import android.util.Log;
-
-import java.io.IOException;
-
-public class EasySetupStatusTest extends AndroidTestCase {
-
-
- public void testStartSetupWithWiFiOnboarding() {
-
- EasySetupService mService;
- EnrolleeDevice mDevice;
- EnrolleeDeviceFactory mFactory;
-
- final Object lock = new Object();
-
-
- /* Create Easy Setup service */
- mService = EasySetupService.getInstance(getContext(), new EasySetupStatus() {
- EnrolleeState old_state = null;
-
- @Override
- public void onFinished(EnrolleeDevice enrolledevice) {
-
- //countDownLatch.countDown();
- Utility.toNotify(lock);
-
- if (enrolledevice.isSetupSuccessful()) {
-
- if (enrolledevice.mOnBoardingConfig.getConnType() == WiFiOnBoardingConfig.ConnType.WiFi) {
- IpOnBoardingConnection conn = (IpOnBoardingConnection) enrolledevice.getConnection();
- String ip = conn.getIp();
- if (ip == null || ip.isEmpty()) {
- assertTrue(false);
- return;
- }
- String mac = conn.getHardwareAddress();
- if (mac == null || mac.isEmpty()) {
- assertTrue(false);
- return;
- }
- // Device configured successfully
- assertTrue(true);
- }
-
- } else {
- assertTrue(false);
- }
- }
-
- @Override
- public void onProgress(EnrolleeDevice enrolleeDevice) {
- EnrolleeState state = enrolleeDevice.mState;
- // TODO
- switch (state) {
- case DEVICE_INIT_STATE:
- Log.d("enrollee state", "DEVICE_INIT_STATE");
- assertTrue(false);
- break;
- case DEVICE_ON_BOARDING_STATE:
- if (old_state == null)
- assertTrue(true);
- else assertTrue(false);
- old_state = EnrolleeState.DEVICE_ON_BOARDING_STATE;
- Log.d("enrollee state", "DEVICE_ON_BOARDING_STATE");
- break;
-
- case DEVICE_ON_BOARDED_STATE:
- if (old_state == EnrolleeState.DEVICE_ON_BOARDING_STATE)
- assertTrue(true);
- else assertTrue(false);
- old_state = EnrolleeState.DEVICE_ON_BOARDED_STATE;
- Log.d("enrollee state", "DEVICE_ON_BOARDED_STATE");
- break;
-
- case DEVICE_PROVISIONING_STATE:
- if (old_state == EnrolleeState.DEVICE_ON_BOARDED_STATE)
- assertTrue(true);
- else assertTrue(false);
- old_state = EnrolleeState.DEVICE_PROVISIONING_STATE;
- Log.d("enrollee state", "DEVICE_PROVISIONING_STATE");
- break;
-
- case DEVICE_PROVISIONED_STATE:
- if (old_state == EnrolleeState.DEVICE_PROVISIONING_STATE)
- assertTrue(true);
- else assertTrue(false);
- Log.d("enrollee state", "DEVICE_PROVISIONING_SUCCESS_STATE");
- break;
-
- default:
- Log.d("enrollee state", "unknown state");
- assertTrue(false);
- break;
- }
-
- }
- });
-
-
- /* Create On boarding configuration */
- WiFiOnBoardingConfig mWiFiOnBoardingConfig = new WiFiOnBoardingConfig();
- mWiFiOnBoardingConfig.setSSId("EasySetup123");
- mWiFiOnBoardingConfig.setSharedKey("EasySetup123");
- mWiFiOnBoardingConfig.setAuthAlgo(WifiConfiguration.AuthAlgorithm.OPEN);
- mWiFiOnBoardingConfig.setKms(WifiConfiguration.KeyMgmt.WPA_PSK);
-
- /* Create provisioning configuration */
- WiFiProvConfig mWiFiProvConfig = new WiFiProvConfig("hub2.4G", "11112222");
-
- /* Create enrolling device factory instance */
- mFactory = EnrolleeDeviceFactory.newInstance(getContext());
-
- /* Create enrolling device */
- mDevice = mFactory.newEnrolleeDevice(mWiFiProvConfig, mWiFiOnBoardingConfig);
-
- try {
- mService.startSetup(mDevice);
- } catch (ESException e) {
- }
- catch (IOException e) {
- }
-
- try {
-
- Utility.toWait(lock);
-
- Log.i("EasySetupTest", "Lock is released");
-
- IpOnBoardingConnection conn = (IpOnBoardingConnection) mDevice.getConnection();
-
- Log.i("EasySetupTest", "Ip" + conn.getIp());
- Log.i("EasySetupTest", "MAC" + conn.getHardwareAddress());
-
- // Device configured successfully
-
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- }
-
-}
\ 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 android.net.wifi.WifiConfiguration;
-import android.test.AndroidTestCase;
-
-public class EnrolleeDeviceFactoryTest extends AndroidTestCase {
-
- EnrolleeDeviceFactory mFactory;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- mFactory = EnrolleeDeviceFactory.newInstance(getContext());
- assertTrue(mFactory != null);
-
- }
-
- @Override
- protected void tearDown() throws Exception {
- super.tearDown();
- mFactory = null;
- }
-
-
- public void testNewEnrolleeDevice_with_WiFiOnboarding() {
-
- /* Create On boarding configuration */
- WiFiOnBoardingConfig mWiFiOnBoardingConfig = new WiFiOnBoardingConfig();
- mWiFiOnBoardingConfig.setSSId("EasySetup123");
- mWiFiOnBoardingConfig.setSharedKey("EasySetup123");
- mWiFiOnBoardingConfig.setAuthAlgo(WifiConfiguration.AuthAlgorithm.OPEN);
- mWiFiOnBoardingConfig.setKms(WifiConfiguration.KeyMgmt.WPA_PSK);
-
- /* Create provisioning configuration */
- WiFiProvConfig mWiFiProvConfig = new WiFiProvConfig("hub2.4G", "11112222");
-
- /* Create enrolling device */
- EnrolleeDevice device = mFactory.newEnrolleeDevice(mWiFiProvConfig, mWiFiOnBoardingConfig);
-
- /* Check if the the device is created */
- assertTrue(device != null);
-
- /* Check if the the correct device is created as per the given configuration*/
- assertTrue((device instanceof EnrolleeDeviceWiFiOnboarding));
-
- }
-
-}
+++ /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 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.core;
-
-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.core.ip;
-
-import java.io.BufferedReader;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStreamReader;
-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.util.Log;
-
-import org.iotivity.service.easysetup.core.EnrolleeInfo;
-import org.iotivity.service.easysetup.core.EnrolleeOnBoardingInfo;
-import org.iotivity.service.easysetup.core.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 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 {
- //This case will happen during the transition from connected to
- // disconneted. This case need not be notified to application.
- // Notifying this state will cause failure of OnBoarding
- }
- NotifyApplication(result);
- return true;
- }
- }
- }
- if (!deviceAddedToList) {
- if (isReachable) {
- appNotification
- .add(new EnrolleeOnBoardingInfo(ipAddr, macAddr, "", isReachable, false,
- true));
-
- result.setIpAddr(ipAddr);
- result.setHWAddr(macAddr);
- result.setReachable(isReachable);
-
- NotifyApplication(result);
- } else {
- //This case will happen for the first time device is listed, but reachability
- // is false. This case need not be notified to application. Notifying this
- // state will cause failure of OnBoarding
- }
- return true;
- }
- } else {
- if (isReachable) {
- appNotification
- .add(new EnrolleeOnBoardingInfo(ipAddr, macAddr, "", isReachable, false,
- true));
- result.setIpAddr(ipAddr);
- result.setHWAddr(macAddr);
- result.setReachable(isReachable);
-
- NotifyApplication(result);
- } else {
- //This case will happen for the first time device is listed, but
- // reachability is false. This case need not be notified to
- // application. Notifying this state will cause failure of OnBoarding
- }
-
- 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;
- }
- }
-
- /**
- * 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 synchronized void getClientList(IOnBoardingStatus finishListener, final int
- reachableTimeout) {
- this.finishListener = finishListener;
- //Clearing the scan list for providing u
- appNotification.clear();
- 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"
- // This holds an ASCII readable dump of the kernel ARP table used
- // for address resolutions. It will show both dynamically learned
- // and preprogrammed ARP entries. The format is:
- // IP address HW type Flags HW address Mask Device
- // 192.168.0.50 0x1 0x2 00:50:BF:25:68:F3 * eth0
- // 192.168.0.250 0x1 0xc 00:00:00:00:00:00 * eth0
- bufferedReader = new BufferedReader(new InputStreamReader(
- new FileInputStream("/proc/net/arp"), "UTF-8"));
- 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
+/**
+ * ***************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+import android.util.Log;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcRepresentation;
+
+/**
+ * This class contains cloud server properties to be delivered to Enrollee
+ */
+public class CloudProp {
+ private static final String TAG = CloudProp.class.getName();
+ protected OcRepresentation mRep;
+ protected String mCloudID;
+
+ /**
+ * Constructor
+ */
+ public CloudProp() {
+ mRep = new OcRepresentation();
+ mCloudID = "";
+ }
+
+ public void setCloudProp(String authCode, String authProvider, String ciServer)
+ {
+ try {
+ mRep.setValue(ESConstants.OC_RSRVD_ES_AUTHCODE, authCode);
+ mRep.setValue(ESConstants.OC_RSRVD_ES_AUTHPROVIDER, authProvider);
+ mRep.setValue(ESConstants.OC_RSRVD_ES_CISERVER, ciServer);
+ } catch (OcException e) {
+ Log.e(TAG, "setCloudProp is failed.");
+ }
+ }
+
+ public void setCloudID(String cloudID)
+ {
+ mCloudID = cloudID;
+ }
+
+ /**
+ * This method returns the authCode used for the first registration to IoTivity cloud
+ * @return AuthCode for sign-up to IoTivity cloud
+ */
+ public String getAuthCode()
+ {
+ try {
+ if (mRep.hasAttribute(ESConstants.OC_RSRVD_ES_AUTHCODE))
+ return mRep.getValue(ESConstants.OC_RSRVD_ES_AUTHCODE);
+ } catch (OcException e) {
+ Log.e(TAG, "getAuthCode is failed.");
+ }
+ return new String("");
+ }
+
+ /**
+ * This method returns the auth provider which issued the given AuthCode
+ * @return Auth provider which issued the given AuthCode
+ */
+ public String getAuthProvider()
+ {
+ try {
+ if (mRep.hasAttribute(ESConstants.OC_RSRVD_ES_AUTHPROVIDER))
+ return mRep.getValue(ESConstants.OC_RSRVD_ES_AUTHPROVIDER);
+ } catch (OcException e) {
+ Log.e(TAG, "getAuthProvider is failed.");
+ }
+ return new String("");
+ }
+
+ /**
+ * This method returns the Cloud Interface server's URL to be registered
+ * @return CI server's URL to be registered
+ */
+ public String getCiServer()
+ {
+ try {
+ if (mRep.hasAttribute(ESConstants.OC_RSRVD_ES_CISERVER))
+ return mRep.getValue(ESConstants.OC_RSRVD_ES_CISERVER);
+ } catch (OcException e) {
+ Log.e(TAG, "getCiServer is failed.");
+ }
+ return new String("");
+ }
+
+ /**
+ * This method returns the Cloud Interface server's UUID
+ * @return CI server's UUID
+ */
+ public String getCloudID()
+ {
+ return mCloudID;
+ }
+
+ public OcRepresentation toOCRepresentation()
+ {
+ return mRep;
+ }
+}
/**
* ***************************************************************
- * <p/>
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- * <p/>
- * <p/>
- * <p/>
+ *
+ * Copyright 2016 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
- * <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 abstract class OnBoardingCallback {
- public abstract void onFinished(OnBoardingConnection connection);
+import org.iotivity.service.easysetup.mediator.CloudPropProvisioningStatus;
+
+/**
+ * This interface class is used as a callback function called after receiving
+ * a response of cloud property provisioning result
+ *
+ * @see CloudPropProvisioningStatus
+ */
+public abstract class CloudPropProvisioningCallback {
+
+ /**
+ * Called after receiving a response of cloud property provisioning result
+ *
+ * @param status
+ * a result of cloud property provisioning
+ * a state of cloud property provisioning
+ */
+ public abstract void onProgress(CloudPropProvisioningStatus status);
}
+
--- /dev/null
+/**
+ * ***************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+import org.iotivity.service.easysetup.mediator.enums.ESCloudProvState;
+import org.iotivity.service.easysetup.mediator.enums.ESResult;
+
+/**
+ * This interface facilitates Application to get progress & result of Cloud provisioning
+ * process in easy setup
+ */
+public class CloudPropProvisioningStatus
+{
+ private ESResult m_result;
+ private ESCloudProvState m_esCloudState;
+
+ /**
+ * Constructor
+ *
+ * @param result a result of cloud property provisioning
+ * @param state a state of cloud property provisioning.
+ * ES_CLOUD_PROVISIONING_ERROR(-1), ES_CLOUD_PROVISIONING_SUCCESS(0),
+ * ES_CLOUD_ENROLLEE_FOUND(1), ES_CLOUD_ENROLLEE_NOT_FOUND(2)
+ *
+ * @see ESCloudProvState
+ */
+ public CloudPropProvisioningStatus(int result, int state)
+ {
+ m_result = ESResult.fromInt(result);
+ m_esCloudState = ESCloudProvState.fromInt(state);
+ }
+
+ /**
+ * Get a result of cloud property provisioning
+ *
+ * @result ESResult a result of cloud property provisioning
+ */
+ public ESResult getESResult()
+ {
+ return m_result;
+ }
+
+ /**
+ * Get a state of cloud property provisioning
+ *
+ * @result ESCloudProvState a state of cloud property provisioning
+ *
+ * @see ESCloudProvState
+ */
+ public ESCloudProvState getESCloudState()
+ {
+ return m_esCloudState;
+ }
+};
--- /dev/null
+/**
+ * ***************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+import android.util.Log;
+
+import org.iotivity.service.easysetup.mediator.enums.WIFI_AUTHTYPE;
+import org.iotivity.service.easysetup.mediator.enums.WIFI_ENCTYPE;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcRepresentation;
+
+/**
+ * This class contains device properties to be delivered to Enrollee
+ */
+public class DeviceProp {
+ private static final String TAG = DeviceProp.class.getName();
+ protected OcRepresentation mRep;
+
+ /**
+ * Constructor
+ */
+ public DeviceProp() {
+ mRep = new OcRepresentation();
+ }
+
+ public void setWiFiProp(String ssid, String pwd, WIFI_AUTHTYPE authtype, WIFI_ENCTYPE enctype)
+ {
+ try
+ {
+ mRep.setValue(ESConstants.OC_RSRVD_ES_SSID, ssid);
+ mRep.setValue(ESConstants.OC_RSRVD_ES_CRED, pwd);
+ mRep.setValue(ESConstants.OC_RSRVD_ES_AUTHTYPE, authtype.getValue());
+ mRep.setValue(ESConstants.OC_RSRVD_ES_ENCTYPE, enctype.getValue());
+ } catch (OcException e) {
+ Log.e(TAG, "setWiFiProp is failed.");
+ }
+ }
+
+ public void setDevConfProp(String language, String country)
+ {
+ try {
+ mRep.setValue(ESConstants.OC_RSRVD_ES_LANGUAGE, language);
+ mRep.setValue(ESConstants.OC_RSRVD_ES_COUNTRY, country);
+ } catch (OcException e) {
+ Log.e(TAG, "setDevConfProp is failed.");
+ }
+ }
+
+ /**
+ * Get WiFi AP's SSID
+ *
+ * @return String WiFi AP's SSID
+ */
+ public String getSsid()
+ {
+ try {
+ if(mRep.hasAttribute(ESConstants.OC_RSRVD_ES_SSID))
+ return mRep.getValue(ESConstants.OC_RSRVD_ES_SSID);
+ } catch (OcException e) {
+ Log.e(TAG, "getSsid is failed.");
+ }
+ return new String("");
+ }
+
+ /**
+ * Get WiFi AP's password
+ *
+ * @return String WiFi AP's password
+ */
+ public String getPassword()
+ {
+ try {
+ if(mRep.hasAttribute(ESConstants.OC_RSRVD_ES_CRED))
+ return mRep.getValue(ESConstants.OC_RSRVD_ES_CRED);
+ } catch (OcException e) {
+ Log.e(TAG, "getPassword is failed.");
+ }
+ return new String("");
+ }
+
+ /**
+ * Get WiFi AP's authenticate type
+ * NONE_AUTH(0), WEP(1), WPA_PSK(2), WPA2_PSK(3)
+ *
+ * @return WIFI_AUTHTYPE WiFi AP's authenticate type
+ */
+ public WIFI_AUTHTYPE getAuthType()
+ {
+ try {
+ if (mRep.hasAttribute(ESConstants.OC_RSRVD_ES_AUTHTYPE))
+ return WIFI_AUTHTYPE.fromInt((int)mRep.getValue(ESConstants.OC_RSRVD_ES_AUTHTYPE));
+ } catch (OcException e) {
+ Log.e(TAG, "getAuthType is failed.");
+ }
+ return WIFI_AUTHTYPE.NONE_AUTH;
+ }
+
+ /**
+ * Get WiFi AP's encryption type
+ * NONE_ENC(0), WEP_64(1), WEP_128(2), TKIP(3), AES(4), TKIP_AES(5)
+ *
+ * @return WIFI_ENCTYPE WiFi AP's encryption type
+ */
+ public WIFI_ENCTYPE getEncType()
+ {
+ try {
+ if (mRep.hasAttribute(ESConstants.OC_RSRVD_ES_ENCTYPE))
+ return WIFI_ENCTYPE.fromInt((int)mRep.getValue(ESConstants.OC_RSRVD_ES_ENCTYPE));
+ } catch (OcException e) {
+ Log.e(TAG, "getEncType is failed.");
+ }
+ return WIFI_ENCTYPE.NONE_ENC;
+ }
+
+ /**
+ * Get IETF language tag using ISO 639X
+ *
+ * @return String IETF language tag using ISO 639X
+ */
+ public String getLanguage()
+ {
+ try {
+ if(mRep.hasAttribute(ESConstants.OC_RSRVD_ES_LANGUAGE))
+ return mRep.getValue(ESConstants.OC_RSRVD_ES_LANGUAGE);
+ } catch (OcException e) {
+ Log.e(TAG, "getLanguage is failed.");
+ }
+ return new String("");
+ }
+
+ /**
+ * Get ISO Country Code (ISO 3166-1 Alpha-2)
+ *
+ * @return String ISO Country Code (ISO 3166-1 Alpha-2)
+ */
+ public String getCountry()
+ {
+ try {
+ if (mRep.hasAttribute(ESConstants.OC_RSRVD_ES_COUNTRY))
+ return mRep.getValue(ESConstants.OC_RSRVD_ES_COUNTRY);
+ } catch (OcException e) {
+ Log.e(TAG, "getCountry is failed.");
+ }
+ return new String("");
+ }
+
+ public OcRepresentation toOCRepresentation()
+ {
+ return mRep;
+ }
+}
/**
* ***************************************************************
- * <p/>
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- * <p/>
- * <p/>
- * <p/>
+ *
+ * Copyright 2016 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
- * <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 org.iotivity.service.easysetup.mediator.DevicePropProvisioningStatus;
+
/**
- * This interface contains the connection details of the enrollee device
+ * This interface class is used as a callback function called after receiving
+ * a response of device property provisioning result
+ *
+ * @see DevicePropProvisioningStatus
*/
-public interface OnBoardingConnection {
-
- /**
- * This method returns the implementation of the Connection
- *
- * @return implementation
- */
- public Object getConnection();
+public abstract class DevicePropProvisioningCallback {
/**
- * This method returns description on the connectivity.
+ * Called after receiving a response of device property provisioning result
*
- * @return description
- */
- public String getDesc();
-
- /**
- * This method is used to know if the device is connected or not
+ * @param status a result of device property provisioning
*
- * @return True if connected or False
+ * @see DevicePropProvisioningStatus
*/
- public boolean isConnected();
-
+ public abstract void onProgress(DevicePropProvisioningStatus status);
}
--- /dev/null
+/**
+ * ***************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+import org.iotivity.service.easysetup.mediator.enums.ESResult;
+
+/**
+ * This class indicates a result if a provisionDeviceProperties API succeed or fails
+ */
+public class DevicePropProvisioningStatus
+{
+ private ESResult m_result;
+
+ /**
+ * Constructor
+ *
+ * @param result a result if a provisionDeviceProperties API succeed or fails
+ */
+ public DevicePropProvisioningStatus(int result)
+ {
+ m_result = ESResult.fromInt(result);
+ }
+
+ /**
+ * Get a result if a provisionDeviceProperties API succeed or fails
+ *
+ * @return ESResult a result if a provisionDeviceProperties API succeed or fails
+ */
+ public ESResult getESResult()
+ {
+ return m_result;
+ }
+};
--- /dev/null
+package org.iotivity.service.easysetup.mediator;
+
+/**
+ * Created by jhha85 on 7/27/16.
+ */
+public class ESConstants {
+
+ public static final String OC_RSRVD_ES_PROVSTATUS = "ps";
+ public static final String OC_RSRVD_ES_LAST_ERRORCODE = "lec";
+ public static final String OC_RSRVD_ES_LINKS = "links";
+ public static final String OC_RSRVD_ES_SUPPORTEDWIFIMODE = "swmt";
+ public static final String OC_RSRVD_ES_SUPPORTEDWIFIFREQ = "swf";
+ public static final String OC_RSRVD_ES_SSID = "tnn";
+ public static final String OC_RSRVD_ES_CRED = "cd";
+ public static final String OC_RSRVD_ES_AUTHTYPE = "wat";
+ public static final String OC_RSRVD_ES_ENCTYPE = "wet";
+ public static final String OC_RSRVD_ES_AUTHCODE = "ac";
+ public static final String OC_RSRVD_ES_AUTHPROVIDER = "apn";
+ public static final String OC_RSRVD_ES_CISERVER = "cis";
+ public static final String OC_RSRVD_ES_SERVERID = "sid";
+ public static final String OC_RSRVD_ES_DEVNAME = "dn";
+ public static final String OC_RSRVD_ES_LANGUAGE = "lang";
+ public static final String OC_RSRVD_ES_COUNTRY = "ctry";
+
+/**
+* Easysetup defined resoruce types and uris
+*/
+ public static final String OC_RSRVD_ES_RES_TYPE_PROV = "ocf.wk.prov";
+ public static final String OC_RSRVD_ES_URI_PROV = "/ProvisioningResURI";
+ public static final String OC_RSRVD_ES_RES_TYPE_WIFI = "ocf.wk.wifi";
+ public static final String OC_RSRVD_ES_URI_WIFI = "/WiFiProvisioningResURI";
+ public static final String OC_RSRVD_ES_RES_TYPE_CLOUDSERVER = "ocf.wk.cloudserver";
+ public static final String OC_RSRVD_ES_URI_CLOUDSERVER = "/CloudServerProvisioningResURI";
+ public static final String OC_RSRVD_ES_RES_TYPE_DEVCONF = "ocf.wk.devconf";
+ public static final String OC_RSRVD_ES_URI_DEVCONF = "/DevConfProvisioningResURI";
+
+}
--- /dev/null
+/**
+ * ***************************************************************
+ *
+ * Copyright 2017 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+import android.content.Context;
+import android.util.Log;
+
+import org.iotivity.base.OcConnectivityType;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.OcPlatform;
+
+import java.util.ArrayList;
+import java.util.EnumSet;
+import java.util.List;
+
+/**
+ * This provides an API to instanciate a new RemoteEnrollee object correspondent to Enrollee
+ * Device to be setup.
+ */
+public class EasySetup {
+
+ private static final String TAG = EasySetup.class.getName();
+ public static final String PROV_RESOURCE_TYPE = "ocf.wk.prov";
+ private static EasySetup sInstance;
+
+ private static Context mContext;
+
+ private ArrayList<RemoteEnrollee> mRemoteEnrolleeList;
+
+ protected RemoteEnrollee mRemoteEnrollee;
+
+ // function to call the native nativeCreateRemoteEnrollee
+ private native RemoteEnrollee nativeCreateRemoteEnrollee(OcResource enrolleeResource);
+ static {
+ // Load Easy Setup JNI interface
+ try
+ {
+ System.loadLibrary("ocprovision");
+ } catch (UnsatisfiedLinkError e) {
+ Log.i(TAG, "ocprovision library does not exist. (Unsecure mode)");
+ }
+
+ System.loadLibrary("ocstack-jni");
+ System.loadLibrary("ESMediatorRich");
+ System.loadLibrary("easysetup-jni");
+ }
+
+ private EasySetup() {
+ mRemoteEnrolleeList = new ArrayList<RemoteEnrollee>();
+ mContext = null;
+ }
+
+ /**
+ * Gives a singleton instance of Easy setup and initialize the easy setup
+ */
+ public synchronized static EasySetup getInstance(Context context) {
+ if (sInstance == null) {
+ sInstance = new EasySetup();
+ mContext = context;
+ }
+ return sInstance;
+ }
+
+ /**
+ * This API is used for creating a remote Enrollee instance
+ *
+ * @param enrolleeResource an OCResource object corresponding to enrollee resource
+ * discovered in a network. The OcResource object can be obtained by calling
+ * OcPlatform.findResource() API. What resource you have to discover with
+ * the OcPlatform.findResource() API is a "provisioning" resource with a certain
+ * resource type, i.e. ocf.wk.prov
+ *
+ * @return Pointer to RemoteEnrollee instance
+ */
+ public synchronized RemoteEnrollee createRemoteEnrollee(OcResource enrolleeResource)
+ {
+ // native call
+ if(!enrolleeResource.getResourceTypes().contains(PROV_RESOURCE_TYPE)
+ || !enrolleeResource.getResourceInterfaces().contains(OcPlatform.BATCH_INTERFACE))
+ {
+ Log.e(TAG, "Validation check for OcResource is failed.");
+ return null;
+ }
+ mRemoteEnrollee = nativeCreateRemoteEnrollee(enrolleeResource);
+ mRemoteEnrolleeList.add(mRemoteEnrollee);
+ return mRemoteEnrollee;
+ }
+}
+++ /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 android.content.Context;
-import android.util.Log;
-
-import java.io.IOException;
-import java.util.ArrayList;
-
-/**
- * This is facade class, a single point of contact for Application.
- * It contains set of APIs to do easy setup of the enrolling device.
- * ON-BOARDING - This is a step to establish connectivity between the device & Mediator device.
- * PROVISION - This is a step where the netowork's detail & credentials are given to the
- * enrolling device.
- */
-public class EasySetupService {
-
- private static final String TAG = EasySetupService.class.getName();
-
- private static EasySetupService sInstance;
-
- private final EasySetupStatus mCallback;
-
- private ArrayList<EnrolleeDevice> mEnrolleeDeviceList;
-
- private final ProvisioningCallback mProvisioningCallback;
-
- private static Context mContext;
-
- protected RemoteEnrollee mRemoteEnrollee;
-
- //function to call the native createEnrolleeDevice
- private native RemoteEnrollee nativeCreateEnrolleeDevice(String ip, String ssid,
- String password, int type, boolean isSecured );
-
- static {
- // Load Easy Setup JNI interface
- System.loadLibrary("ESMediatorRich");
- System.loadLibrary("easysetup-jni");
- }
-
- private EasySetupService(EasySetupStatus callback) {
- mCallback = callback;
- mProvisioningCallback = new ProvisioningCallbackImpl(mCallback);
- mEnrolleeDeviceList = new ArrayList<EnrolleeDevice>();
- mContext = null;
- }
-
- /**
- * Gives a singleton instance of Easy setup service and initialize the service
- *
- * @param callback Application needs to provide this callback to receive the status of easy
- * setup process.
- */
-
- public synchronized static EasySetupService getInstance(Context context, EasySetupStatus
- callback) {
- if (sInstance == null) {
- sInstance = new EasySetupService(callback);
- mContext = context;
- }
- return sInstance;
- }
-
- /**
- * Reset the Easy setup Service
- */
-
- public void finish() {
- //Call the stop Provisioning
- for (EnrolleeDevice enrolleeDevice : mEnrolleeDeviceList) {
- enrolleeDevice.stopProvisioningProcess();
- }
- }
-
- /**
- * Starts Easy setup process for the enrolling device.
- *
- * @param enrolledevice Device to be enrolled in network
- * @throws IOException Throws exception in case of any connection error.
- */
-
- public synchronized void startSetup(final EnrolleeDevice enrolledevice) throws IOException,ESException {
-
- if (null == enrolledevice) {
- throw new ESException("enrolledevice is NULL");
- }
-
- mEnrolleeDeviceList.add(enrolledevice);
-
- // Starts the provisioning directly if the device is already on boarded on the network.
- if (enrolledevice.onBoarded()) {
- if(null == enrolledevice.mRemoteEnrollee){
- //create Native RemoteEnrollee
- WiFiProvConfig config = (WiFiProvConfig)enrolledevice.mProvConfig;
- String ip = "";
- String ssid = config.getSsId();
- String password = config.getPassword();
- int connectivityType = config.getConnType().getValue();
- boolean isSecured = config.isSecured();
-
- //native call
- mRemoteEnrollee = nativeCreateEnrolleeDevice(ip, ssid, password,
- connectivityType, isSecured);
- enrolledevice.mRemoteEnrollee = mRemoteEnrollee;
- }
- enrolledevice.startProvisioning(mProvisioningCallback);
- return;
- }
- enrolledevice.mState = EnrolleeState.DEVICE_ON_BOARDING_STATE;
- mCallback.onProgress(enrolledevice);
- enrolledevice.startOnBoarding(new OnBoardingCallback() {
-
- @Override
- public void onFinished(OnBoardingConnection connection) {
- if (connection.isConnected()) {
- Log.i(TAG, "On boarding is successful ");
- // Start provisioning here
- enrolledevice.mState = EnrolleeState.DEVICE_ON_BOARDED_STATE;
- mCallback.onProgress(enrolledevice);
- enrolledevice.setConnection(connection);
-
- //create a native RemoteEnrollee with network info
- IpOnBoardingConnection conn = (IpOnBoardingConnection) connection;
- WiFiProvConfig config = (WiFiProvConfig)enrolledevice.mProvConfig;
- String ip = conn.getIp();
- String ssid = config.getSsId();
- String password = config.getPassword();
- int connectivityType = config.getConnType().getValue();
- boolean isSecured = config.isSecured();
-
- //native call
- mRemoteEnrollee = nativeCreateEnrolleeDevice(ip, ssid, password,
- connectivityType, isSecured);
-
- enrolledevice.mRemoteEnrollee = mRemoteEnrollee;
-
- /* Delay is set according to Soft AP host and Mediator platform;
- * For Android with Soft AP it is 2000 ms
- */
- delayProvisioning(connection);
- enrolledevice.startProvisioning(mProvisioningCallback);
- } else {
- enrolledevice.mState = EnrolleeState.DEVICE_INIT_STATE;
- mProvisioningCallback.onFinished(enrolledevice);
- }
- }
- });
- }
-
- /**
- * Stops on-going Easy setup process for enrolling device.
- *
- * @param enrolleedevice Device to be enrolled in network
- */
- public synchronized void stopSetup(EnrolleeDevice enrolleedevice) throws ESException {
-
- if (null == enrolleedevice) {
- throw new ESException("enrolledevice is NULL");
- }
-
- if (mEnrolleeDeviceList.contains(enrolleedevice)) {
- if (enrolleedevice.mState == EnrolleeState.DEVICE_ON_BOARDING_STATE) {
- Log.i(TAG, "stopOnBoardingProcess for enrolleedevice");
- enrolleedevice.stopOnBoardingProcess();
- }else if (enrolleedevice.mState == EnrolleeState.DEVICE_PROVISIONING_STATE) {
- Log.i(TAG, "stopEnrolleeProvisioning for enrolleedevice");
- enrolleedevice.stopProvisioningProcess();
- }
- enrolleedevice.mState = EnrolleeState.DEVICE_INIT_STATE;
- mCallback.onProgress(enrolleedevice);
- mEnrolleeDeviceList.remove(enrolleedevice);
- }
- }
-
- class ProvisioningCallbackImpl extends ProvisioningCallback {
-
- private final EasySetupStatus mCallback;
-
- ProvisioningCallbackImpl(EasySetupStatus callback) {
- mCallback = callback;
- }
-
- @Override
- public void onFinished(EnrolleeDevice enrolledevice) {
- synchronized (EasySetupService.this) {
- if (mEnrolleeDeviceList.contains(enrolledevice)) {
- Log.i(TAG, "onFinished() is received " + enrolledevice.isSetupSuccessful());
- mCallback.onFinished(enrolledevice);
- mEnrolleeDeviceList.remove(enrolledevice);
- }
- }
- }
-
- @Override
- public void onProgress(EnrolleeDevice enrolledevice) {
- mCallback.onProgress(enrolledevice);
- }
- }
-
- private void delayProvisioning(OnBoardingConnection conn) {
- if (((IpOnBoardingConnection)conn).getThrottlingDelay()>0) {
- try {
- Log.i(TAG, "waiting for 20 seconds to start provisioning");
- Thread.sleep(20000);//Sleep for allowing thin device to start the services
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
-}
\ 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;
-
-/**
- * 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 enrolleeDevice Gives state of the device changed during easy setup process
- */
- public void onProgress(EnrolleeDevice enrolleeDevice);
-
-}
--- /dev/null
+/**
+ * ***************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+import android.util.Log;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.service.easysetup.mediator.ESConstants;
+import org.iotivity.service.easysetup.mediator.enums.WIFI_FREQ;
+import org.iotivity.service.easysetup.mediator.enums.WIFI_MODE;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * This class stores Enrollee's configuration including WiFi and Device configuration
+ * including supported WiFi frequency and device name
+ */
+public class EnrolleeConf
+{
+ private static final String TAG = EnrolleeConf.class.getName();
+ private OcRepresentation mProvRep = null, mWiFiRep = null, mDevConfRep = null, mCloudRep = null;
+ /**
+ * Constructor
+ *
+ * @param rep received properties in a form of OcRepresentation
+ *
+ */
+ public EnrolleeConf(OcRepresentation rep)
+ {
+ mProvRep = rep;
+
+ List<OcRepresentation> children = rep.getChildren();
+
+ for (OcRepresentation child : children) {
+ List<String> rts = child.getResourceTypes();
+
+ if(child.getUri().indexOf(ESConstants.OC_RSRVD_ES_URI_WIFI) != -1)
+ {
+ mWiFiRep = child;
+ }
+ else if(child.getUri().indexOf(ESConstants.OC_RSRVD_ES_URI_DEVCONF) != -1)
+ {
+ mDevConfRep = child;
+ }
+ else if(child.getUri().indexOf(ESConstants.OC_RSRVD_ES_URI_CLOUDSERVER) != -1)
+ {
+ mCloudRep = child;
+ }
+ }
+ }
+
+ /**
+ * Get Device Name property in DevConf resource
+ *
+ * @return deviceName
+ */
+ public String getDeviceName()
+ {
+ try
+ {
+ if(mDevConfRep != null && mDevConfRep.hasAttribute(ESConstants.OC_RSRVD_ES_DEVNAME)) {
+ return (String) mDevConfRep.getValue(ESConstants.OC_RSRVD_ES_DEVNAME);
+ }
+ } catch (OcException e) {
+ Log.e(TAG, "getWiFiModes is failed.");
+ }
+ return new String("");
+ }
+
+ /**
+ * Get Supported WiFi Modes property in WiFi resource
+ *
+ * @return a list of WiFi modes
+ */
+ public ArrayList<WIFI_MODE> getWiFiModes()
+ {
+ ArrayList<WIFI_MODE> modes = new ArrayList<WIFI_MODE>();
+ try {
+ if (mWiFiRep != null && mWiFiRep.hasAttribute(ESConstants.OC_RSRVD_ES_SUPPORTEDWIFIMODE)) {
+ int modes_int[] = mWiFiRep.getValue(ESConstants.OC_RSRVD_ES_SUPPORTEDWIFIMODE);
+ for (int i = 0 ; i < modes_int.length ; ++i) {
+ modes.add(WIFI_MODE.fromInt(modes_int[i]));
+ }
+ }
+ } catch (OcException e) {
+ Log.e(TAG, "getWiFiModes is failed.");
+ }
+ return modes;
+ }
+
+ /**
+ * Get Supported WiFi frequency property in WiFi resource
+ *
+ * @return WiFi frequency
+ */
+ public WIFI_FREQ getWiFiFreq()
+ {
+ try{
+ if(mWiFiRep != null && mWiFiRep.hasAttribute(ESConstants.OC_RSRVD_ES_SUPPORTEDWIFIFREQ))
+ return WIFI_FREQ.fromInt(
+ (int)mWiFiRep.getValue(ESConstants.OC_RSRVD_ES_SUPPORTEDWIFIFREQ));
+ } catch (OcException e) {
+ Log.e(TAG, "getWiFiFreq is failed.");
+ }
+ return WIFI_FREQ.WIFI_FREQ_NONE;
+ }
+
+ /**
+ * To check if Enrollee can access to cloud. To decide its preference, we check if a cloudserver
+ * resource is registered on Enrollee.
+ *
+ * @return boolean
+ */
+ public boolean isCloudAccessible()
+ {
+ if(mCloudRep != null && mCloudRep.getUri().indexOf(ESConstants.OC_RSRVD_ES_URI_CLOUDSERVER) != -1)
+ return true;
+
+ return false;
+ }
+}
+
+
+++ /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;
-
-/**
- * This is an abstract class represents the device being provisioned into the network. The
- * device being enrolled or provisioned into the network is called Enrollee.
- * Application has to extend this class and provide implementation of abstract methods according
- * to the ON-BOARDING & PROVISION connectivity i.e. WiFi etc.
- */
-
-public abstract class EnrolleeDevice {
-
- protected EnrolleeState mState;
- private EnrolleeSetupError mError;
-
- OnBoardingConnection mConnection;
- final ProvisioningConfig mProvConfig;
- final OnBoardingConfig mOnBoardingConfig;
-
- protected OnBoardingCallback mOnBoardingCallback;
- protected ProvisioningCallback mProvisioningCallback;
- protected RemoteEnrollee mRemoteEnrollee;
-
- /**
- * @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.
- */
- protected EnrolleeDevice(OnBoardingConfig onBoardingConfig, ProvisioningConfig provConfig) {
- mProvConfig = provConfig;
- mOnBoardingConfig = onBoardingConfig;
- }
-
- /**
- * Application has to implement it according to the on boarding connectivity the device is
- * having.
- * This method will be called back during the easy setup process.
- */
- protected abstract void startOnBoardingProcess();
-
- /**
- * This method is called back during the easy setup process if Application cancels the setup.
- * Easy setup service checks the state of device and calls this function accordingly.
- * Application has to provide implementation for this method to cancel the on boarding step.
- */
- protected abstract void stopOnBoardingProcess();
-
- /**
- * Application has to implement it according to the type of the network device is going to
- * connect or provisioned.
- * This method will be called back once on-boarding of the device is successful.
- *
- * @param conn Contains detail about the network established between the Enrollee device &
- * Mediator device. Its implementation vary according to the connectivity type.
- */
- protected abstract void startProvisioningProcess(OnBoardingConnection conn);
-
- /**
- * Application has to implement it according to the type of the network device is going to
- * connect or provisioned.
- * This method will stop the provisioning process if it is in progress
- *
- */
- protected abstract void stopProvisioningProcess();
-
- /**
- * Once on boarding is successful concrete Enrollee class would call this method and set the
- * Connection.
- *
- * @param conn Connectivity between Enrollee device & Mediator device.
- */
- protected void setConnection(OnBoardingConnection conn) {
- mConnection = conn;
- }
-
- /**
- * This method returns the OnBoardingConnection object depending on the connection type
- *
- * @return onBoardingConnection object
- */
- public OnBoardingConnection getConnection() {
- return mConnection;
- }
-
-
- /**
- * This method is called back by Easy setup service if on boarding needs to be done.
- *
- * @param onBoardingCallback This is called back once the on boarding is completed.
- */
- void startOnBoarding(OnBoardingCallback onBoardingCallback) {
- mOnBoardingCallback = onBoardingCallback;
- startOnBoardingProcess();
- }
-
- /**
- * This method is called back by Easy setup service once on boarding is successful
- *
- * @param provisioningCallback This is called back once the provisioning process is completed
- */
- void startProvisioning(ProvisioningCallback provisioningCallback) {
- mProvisioningCallback = provisioningCallback;
- startProvisioningProcess(mConnection);
- }
-
- /**
- * This method is used to check easy setup status
- *
- * @return true if successful or false
- */
-
- public boolean isSetupSuccessful() {
- return (mState == EnrolleeState.DEVICE_PROVISIONED_STATE) ? true : false;
- }
-
- /**
- * sets error occured during easy setup process
- */
- protected void setError(EnrolleeSetupError error) {
- mError = error;
- }
-
- /**
- * Returns error occured during easy setup process
- *
- * @return True EnrolleeSetupError object
- */
- public EnrolleeSetupError getError() {
- return mError;
- }
-
- /**
- * Gives the state of the device being enrolled during the easy setup process.
- *
- * @return Returns EnrolleeState object
- */
- public EnrolleeState getState() {
- return mState;
- }
-
- /**
- * This method is used to know if the device is on boarded or not
- *
- * @return True if on-boarded successfully or False
- */
-
- protected boolean onBoarded() {
- return (mState == EnrolleeState.DEVICE_ON_BOARDED_STATE) ? true : false;
- }
-}
+++ /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 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(ProvisioningConfig provConfig, OnBoardingConfig onboardingConfig) throws IllegalArgumentException {
-
- if (null == provConfig || null == onboardingConfig) {
- throw new IllegalArgumentException("provConfig/onboardingConfig is NULL");
- }
- else if (onboardingConfig.getConnType() != OnBoardingConfig.ConnType.WiFi) {
- throw new IllegalArgumentException("OnBoarding configuration is not supported");
- }
- return new EnrolleeDeviceWiFiOnboarding(mContext, onboardingConfig, provConfig);
- }
-
- /**
- * This method create & returns instance of Enrollee device of supported configuration
- * [When SoftAP is going to be created on Enrollee side]
- *
- * @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(ProvisioningConfig provConfig) throws IllegalArgumentException {
-
- if (null == provConfig) {
- throw new IllegalArgumentException("provConfig is NULL");
- }
- return new EnrolleeDeviceWiFiOnboarding(mContext, new IpOnBoardingConnection(true), provConfig);
- }
-}
+++ /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.Timer;
-import java.util.TimerTask;
-
-import org.iotivity.service.easysetup.core.EnrolleeInfo;
-import org.iotivity.service.easysetup.core.IOnBoardingStatus;
-import org.iotivity.service.easysetup.core.ip.WiFiSoftAPManager;
-
-import android.content.Context;
-import android.net.wifi.WifiConfiguration;
-import android.util.Log;
-
-/**
- * This is a ready to use class for Enrollee device having Soft AP as on-boarding connectivity.
- */
-public class EnrolleeDeviceWiFiOnboarding extends EnrolleeDevice {
-
- public static final String TAG = EnrolleeDeviceWiFiOnboarding.class.getName();
-
- final Context mContext;
- final WiFiSoftAPManager mWifiSoftAPManager;
- EnrolleeInfo connectedDevice;
- Timer myTimer = null;
-
- IOnBoardingStatus deviceScanListener = new IOnBoardingStatus() {
-
- @Override
- public void deviceOnBoardingStatus(EnrolleeInfo enrolleStatus) {
- myTimer.cancel();
- Log.d("ESSoftAPOnBoarding", "Entered");
- if (mState == EnrolleeState.DEVICE_ON_BOARDING_STATE) {
- Log.d("ESSoftAPOnBoarding", "Device in OnBoarding State");
- if (enrolleStatus != null && enrolleStatus.getIpAddr() != null) {
- String finalResult = "Easy Connect : ";
-
- if (enrolleStatus.isReachable()) {
- finalResult = "Device OnBoarded" + "["
- + enrolleStatus.getIpAddr() + "]";
-
- connectedDevice = enrolleStatus;
- IpOnBoardingConnection conn = new IpOnBoardingConnection();
-
- conn.setConnectivity(true);
- conn.setIp(connectedDevice.getIpAddr());
- conn.setHardwareAddress(enrolleStatus.getHWAddr());
- conn.setDeviceName(enrolleStatus.getDevice());
-
- Log.d("ESSoftAPOnBoarding", "Entered" + finalResult);
- mOnBoardingCallback.onFinished(conn);
- return;
-
- }
- }
-
- IpOnBoardingConnection conn = new IpOnBoardingConnection();
- conn.setConnectivity(false);
- mOnBoardingCallback.onFinished(conn);
- } else {
- Log.e("ESSoftAPOnBoarding", "Device NOT in OnBoarding State. Ignoring the event");
- }
- }
- };
-
-
- protected EnrolleeDeviceWiFiOnboarding(Context context, OnBoardingConfig onBoardingConfig,
- ProvisioningConfig provConfig) {
- super(onBoardingConfig, provConfig);
- mContext = context;
- mState = EnrolleeState.DEVICE_INIT_STATE;
- mWifiSoftAPManager = new WiFiSoftAPManager(mContext);
- }
-
- protected EnrolleeDeviceWiFiOnboarding(Context context, IpOnBoardingConnection conn,
- ProvisioningConfig provConfig) {
- super(new WiFiOnBoardingConfig(), provConfig);
- mContext = context;
- mState = EnrolleeState.DEVICE_ON_BOARDED_STATE;
- mConnection = conn;
- mWifiSoftAPManager = new WiFiSoftAPManager(mContext);
- }
-
- @Override
- protected void startOnBoardingProcess() {
- Log.i(TAG, "Starting on boarding process");
-
- //1. Create Soft AP
- boolean status = mWifiSoftAPManager.setWifiApEnabled((WifiConfiguration)
- mOnBoardingConfig.getConfig(), true);
-
- mState = EnrolleeState.DEVICE_ON_BOARDING_STATE;
-
- Log.i(TAG, "Soft AP is created with status " + status);
-
- myTimer = new Timer();
- myTimer.schedule(new TimerTask() {
- @Override
- public void run() {
- // Below function to be called after 5 seconds
- mWifiSoftAPManager.getClientList(deviceScanListener, 300);
- }
-
- }, 0, 5000);
- }
-
- protected void stopOnBoardingProcess() {
- Log.i(TAG, "Stopping on boarding process");
- if(myTimer != null)
- {
- myTimer.cancel();
- }
- boolean status = mWifiSoftAPManager.setWifiApEnabled(null, false);
- Log.i(TAG, "Soft AP is disabled with status " + status);
- }
-
- @Override
- protected void startProvisioningProcess(OnBoardingConnection conn) {
-
- mState = EnrolleeState.DEVICE_PROVISIONING_STATE;
- mProvisioningCallback.onProgress(this);
- final EnrolleeDevice device = this;
- if (mProvConfig.getConnType() == ProvisioningConfig.ConnType.WiFi) {
- try {
- mRemoteEnrollee.registerProvisioningHandler(new IProvisionStatusNativeHandler() {
- @Override
- public void onStatusRecieved(int state) {
- device.mState = convertIntToProvisioningState(state);
- Log.i(TAG,"Device state changed :"+device.mState);
- mProvisioningCallback.onProgress(device);
- if(0==state) {
- mProvisioningCallback.onFinished(EnrolleeDeviceWiFiOnboarding.this);
- }
- }
- });
- //native call
- mRemoteEnrollee.startProvision();
- }catch(ESException e) {
- Log.i(TAG,"startProvisioningProcess Register Listener to native exception");
- }
- }
- }
-
- protected void stopProvisioningProcess(){
- if(mState == EnrolleeState.DEVICE_PROVISIONING_STATE)
- { //native call
- try {
- mRemoteEnrollee.stopProvision();
- } catch (ESException e) {
- Log.i(TAG,"stopProvisioningProcess exception");
- }
- }else{
- Log.i(TAG,"stopProvisioningProcess : Provisioning is not in progress");
- }
- }
-
- private EnrolleeState convertIntToProvisioningState(int state){
-
- switch(state)
- {
- case 0 :
- return EnrolleeState.DEVICE_PROVISIONED_STATE;
- case 1:
- return EnrolleeState.DEVICE_NOT_PROVISIONED;
- case 2:
- return EnrolleeState.DEVICE_PROVISIONED_STATE;
- case 3:
- return EnrolleeState.DEVICE_NOT_PROVISIONED;
- }
- return EnrolleeState.DEVICE_INIT_STATE;
- }
-}
+++ /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;
-
-/**
- * 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_BOARDED_STATE,
-
- /**
- * Device will move to this state once the on boarding begins
- */
- 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_PROVISIONED_STATE,
-
- /**
- * Easy setup process failed.
- */
- DEVICE_NOT_PROVISIONED,
-
- /**
- * 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_TRANSFERRING_STATE,
-
- /**
- * This state is arbitrary one, any time device can come into this state
- * Device will move to this state if the ownership transfer is completed
- */
- DEVICE_OWNERSHIP_TRANSFERRED_STATE,
-
- /**
- * This state is arbitrary one, any time device can come into this state
- * Device will move to this state if the ownership transfer is not completed
- */
- DEVICE_NOT_OWNED,
-
- /**
- * 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
+/**
+ * ***************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+import android.util.Log;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.service.easysetup.mediator.ESConstants;
+import org.iotivity.service.easysetup.mediator.enums.ESErrorCode;
+import org.iotivity.service.easysetup.mediator.enums.ProvStatus;
+
+/**
+ * This class stores Enrollee's status including provisioning status and last error code.
+ */
+public class EnrolleeStatus
+{
+ private static final String TAG = EnrolleeStatus.class.getName();
+ private OcRepresentation mRep = null;
+ /**
+ * Constructor
+ *
+ * @param rep received properties in a form of OcRepresentation
+ *
+ */
+ public EnrolleeStatus(OcRepresentation rep)
+ {
+ mRep = rep;
+ }
+
+ /**
+ * Get a provisioning status property of Enrollee.
+ *
+ * @return a provisioning status property of Enrollee
+ */
+ public ProvStatus getProvStatus()
+ {
+ try
+ {
+ if(mRep != null && mRep.hasAttribute(ESConstants.OC_RSRVD_ES_PROVSTATUS)) {
+ int provStatus = mRep.getValue(ESConstants.OC_RSRVD_ES_PROVSTATUS);
+ return ProvStatus.fromInt(provStatus);
+ }
+ } catch (OcException e) {
+ Log.e(TAG, "getProvStatus is failed.");
+ }
+ return ProvStatus.fromInt(0);
+ }
+
+ /**
+ * Get a last error code property of Enrollee.
+ *
+ * @return a last error code property of Enrollee.
+ */
+ public ESErrorCode getLastErrCode()
+ {
+ try
+ {
+ if(mRep != null && mRep.hasAttribute(ESConstants.OC_RSRVD_ES_LAST_ERRORCODE)) {
+ int errCode = mRep.getValue(ESConstants.OC_RSRVD_ES_LAST_ERRORCODE);
+ return ESErrorCode.fromInt(errCode);
+ }
+ } catch (OcException e) {
+ Log.e(TAG, "getLastErrCode is failed.");
+ }
+ return ESErrorCode.fromInt(0);
+ }
+}
+
+
/**
* ***************************************************************
- * <p>
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- * <p>
- * <p>
- * <p>
+ *
+ * Copyright 2016 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
- * <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;
/**
- * This class defines constants for Errors comes during Easy setup process
+ * This interface class is used as a callback function called after receiving
+ * Enrollee's configuration.
+ *
+ * @see GetConfigurationStatus
*/
-public enum EnrolleeSetupError {
- /**
- * Device setup successful
- */
- DEVICE_SETUP_SUCCESSFUL,
+public abstract class GetConfigurationCallback {
+
/**
- * Device setup failed
+ * Called after receiving Enrollee's configuration
+ *
+ * @param status
+ * result if the request succeeds or fails
+ * Enrollee's configuration like supported WiFi freq and device name
*/
- DEVICE_SETUP_FAILED,
+ public abstract void onProgress(GetConfigurationStatus status);
}
--- /dev/null
+/**
+ * ***************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+import org.iotivity.service.easysetup.mediator.enums.ESResult;
+
+/**
+ * This class indicates a result if a getConfiguartion API succeed or fails and
+ * Enrollee's configuration delivered by a response.
+ */
+public class GetConfigurationStatus
+{
+ private ESResult mResult;
+ private EnrolleeConf mEnrolleeConf;
+
+ /**
+ * Constructor
+ *
+ * @param result a result if a getConfiguartion API succeed or fail
+ * @param conf Enrollee's configuration
+ *
+ */
+ public GetConfigurationStatus(int result, EnrolleeConf conf)
+ {
+ mResult = ESResult.fromInt(result);
+ mEnrolleeConf = conf;
+ }
+
+ /**
+ * Get a result of a getConfiguartion API call
+ *
+ * @return ESResult
+ *
+ */
+ public ESResult getESResult()
+ {
+ return mResult;
+ }
+
+ /**
+ * Get Enrollee's configuration
+ *
+ * @return EnrolleeConf includes a WiFi and Device configuration of Enrollee
+ *
+ * @see EnrolleeConf
+ */
+ public EnrolleeConf getEnrolleeConf()
+ {
+ return mEnrolleeConf;
+ }
+};
--- /dev/null
+/**
+ * ***************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+import org.iotivity.service.easysetup.mediator.enums.ESResult;
+
+/**
+ * This class indicates a result if a getConfiguartion API succeed or fails and
+ * Enrollee's configuration delivered by a response.
+ */
+public class GetEnrolleeStatus
+{
+ private ESResult mResult;
+ private EnrolleeStatus mEnrolleeStatus;
+
+ /**
+ * Constructor
+ *
+ * @param result a result if a getStatus API succeed or fail
+ * @param status Enrollee's status
+ *
+ */
+ public GetEnrolleeStatus(int result, EnrolleeStatus status)
+ {
+ mResult = ESResult.fromInt(result);
+ mEnrolleeStatus = status;
+ }
+
+ /**
+ * Get a result of a getStatus API call
+ *
+ * @return ESResult
+ *
+ */
+ public ESResult getESResult()
+ {
+ return mResult;
+ }
+
+ /**
+ * Get Enrollee's status
+ *
+ * @return EnrolleeStatus includes a provisioning status and last error code.
+ *
+ * @see EnrolleeStatus
+ */
+ public EnrolleeStatus getEnrolleeStatus()
+ {
+ return mEnrolleeStatus;
+ }
+};
/**
* ***************************************************************
- * <p/>
+ *
* Copyright 2016 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 interface IProvisionStatusNativeHandler {
-
- public void onStatusRecieved(int state);
+/**
+ * This interface class is used as a callback function called after receiving
+ * Enrollee's status.
+ *
+ * @see GetEnrolleeStatus
+ */
+public abstract class GetStatusCallback {
+ /**
+ * Called after receiving Enrollee's status
+ *
+ * @param status
+ * result if the request succeeds or fails
+ * Enrollee's status like a provisioning status and last error code
+ */
+ public abstract void onProgress(GetEnrolleeStatus status);
}
+++ /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 IpOnBoardingConnection implements OnBoardingConnection {
-
- private boolean mIsConnected;
- private String mIp;
- private String mHardwareAddress;
- private String mDeviceName;
-
- /**
- * @mThrottlingDelay
- * After creating the Soft AP at Mediator & on-boarding the-
- * -Enrollee device on it provisioning needs to be delayed by at least 2000 ms for Android Mediator
- */
- private int mThrottlingDelay = 2000 ;
-
- int getThrottlingDelay() {
- return mThrottlingDelay;
- }
-
- IpOnBoardingConnection(boolean enrolleeOnboarded) {
- mThrottlingDelay = 0;
- mIp = "0.0.0.01";
- mIsConnected = enrolleeOnboarded; // Always true for this constructor
- }
-
- IpOnBoardingConnection(){}
-
- public void setHardwareAddress(String address) {
- mHardwareAddress = address;
- }
-
- public String getHardwareAddress() {
- return mHardwareAddress;
- }
-
- public void setDeviceName(String name) {
- mDeviceName = name;
- }
-
- public String getDeviceName() {
- return mDeviceName;
- }
-
- public void setConnectivity(boolean connected) {
- mIsConnected = connected;
- }
-
- public void setIp(String ip) {
- mIp = ip;
- }
-
- public String getIp() {
- return mIp;
- }
-
- @Override
- public String getDesc() {
- return "Description";
- }
-
- @Override
- public boolean isConnected() {
- return mIsConnected;
- }
-
- @Override
- public Object getConnection() {
- return this;
- }
-
-}
+++ /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 android.util.Log;
-
-import org.iotivity.base.OcConnectivityType;
-
-/**
- * It contains configuration details about the connectivity type between the Enrollee device &
- * Mediator device in order to perform on-boarding.
- */
-
-public interface OnBoardingConfig {
- /**
- * It provides constants for connectivity types used for on-boarding Enrollee device
- */
- public static enum ConnType {
- // Note : Enum Ids should matched with Native Ids
- WiFi(OcConnectivityType.CT_ADAPTER_IP.getValue()),
- BLE(OcConnectivityType.CT_ADAPTER_GATT_BTLE.getValue());
-
- private int mConnType;
-
- ConnType(int connType) {
- mConnType = connType;
- }
-
- public int getValue() {
- return mConnType;
- }
-
- }
-
- /**
- * Gives configuration object specific to the on-boarding connectivity of the enrolling device.
- *
- * @return instance object of configuration according to connectivity type
- */
- public Object getConfig();
-
- /**
- * Gives connectivity type of on-boarding device
- *
- * @return on-boarding connectivity type
- */
- public ConnType getConnType();
-
- public boolean isSecured();
-
- public void setSecured(boolean isSecured);
-
-}
+++ /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 abstract class ProvisioningCallback {
- public abstract void onFinished(EnrolleeDevice enrolledevice);
- public abstract void onProgress(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.mediator;
-
-import android.util.Log;
-
-import org.iotivity.base.OcConnectivityType;
-/**
- * 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 {
- // Note : Enum Ids should matched with Native Ids
- WiFi(OcConnectivityType.CT_ADAPTER_IP.getValue()),
- BLE(OcConnectivityType.CT_ADAPTER_GATT_BTLE.getValue());
-
- private int mConnType;
-
- ConnType(int connType) {
- mConnType = connType;
- }
-
- public int getValue() {
- return mConnType;
- }
- }
-
- /**
- * 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();
-
- public boolean isSecured();
-
- public void setSecured(boolean isSecured);
-
-}
/**
* ***************************************************************
- * <p/>
+ *
* Copyright 2016 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/>
+ *
* ****************************************************************
*/
import android.util.Log;
+import org.iotivity.base.OcRepresentation;
+
+/**
+ * This class represents Remote Enrollee device instance. What operations the class provides:
+ * 1) Ownership transfer for enabling secured communication between Mediator and Enrollee
+ * devices.
+ * 2) Provision WiFi AP information used for which Enrollee is going to connect to the AP
+ * 3) Provision Device confiruation setting, i.e. language, country, and etc
+ * 4) Provision Cloud information used for which Enrollee is going to register to the cloud
+ */
public class RemoteEnrollee{
public static final String TAG = RemoteEnrollee.class.getName();
private long m_nativeHandle;
- private native void nativeStartProvision();
- private native void nativeStopProvision();
- private native void nativeRegisterProvisioningHandler(IProvisionStatusNativeHandler listener);
+ private native void nativeGetStatus(GetStatusCallback callback);
+ private native void nativeGetConfiguration(GetConfigurationCallback callback);
+ private native void nativeProvisionSecurity(SecurityProvisioningCallback callback);
+ private native void nativeProvisionDeviceProperties(OcRepresentation deviceProp,
+ DevicePropProvisioningCallback callback);
+ private native void nativeProvisionCloudProperties(OcRepresentation cloudProp, String cloudID,
+ CloudPropProvisioningCallback callback);
/* constructor will be invoked from the native layer */
private RemoteEnrollee(long nativeHandle){
this.m_nativeHandle = nativeHandle;
}
- /* Register native Listener for the Provisioning state */
- public void registerProvisioningHandler( IProvisionStatusNativeHandler provisioningListener) throws ESException{
- // this.provisioningListener = provisioningListener;
- nativeRegisterProvisioningHandler(provisioningListener);
- Log.i(TAG, "JNI Callback is registered for getting provisioning status");
+ /**
+ * Get an Enrollee's status which includes a provisioning status and last error code
+ *
+ * @param callback will give the requested status
+ *
+ * @throws ESException If some errors happen in this function
+ *
+ * @see GetStatusCallback
+ */
+ public void getStatus(GetStatusCallback callback) throws ESException
+ {
+ if(callback != null)
+ {
+ nativeGetStatus(callback);
+ return;
+ }
+ Log.d(TAG, "GetStatusCallback is null ");
}
- /* native StartProvision */
- public void startProvision() throws ESException{
- nativeStartProvision();
-}
+ /**
+ * Get an Enrollee's configuration which includes WiFi supported frequency and device name
+ *
+ * @param callback will give the requested configuration
+ *
+ * @throws ESException If some errors happen in this function
+ *
+ * @see GetConfigurationCallback
+ */
+ public void getConfiguration(GetConfigurationCallback callback)
+ throws ESException
+ {
+ if(callback != null)
+ {
+ nativeGetConfiguration(callback);
+ return;
+ }
+ Log.d(TAG, "GetConfigurationCallback is null ");
+ }
- /* native stopProvision */
- public void stopProvision() throws ESException{
- nativeStopProvision();
-}
+ /**
+ * Do security provisioning such as ownership tranfer to Enrollee.
+ *
+ * @param callback will give the result if the security provisioning succeeds or fails for some reasons
+ *
+ * @throws ESException If some errors happen in this function
+ *
+ * @see SecurityProvisioningCallback
+ */
+ public void provisionSecurity(SecurityProvisioningCallback callback)
+ throws ESException
+ {
+ if(callback != null)
+ {
+ nativeProvisionSecurity(callback);
+ return;
+ }
+ Log.d(TAG, "SecurityProvisioningCallback is null ");
+ }
+ /**
+ * Provision WiFi AP information and device configuration to Enrollee
+ * 1. WiFi AP information includes a SSID, password, auth type, and encryption type.
+ * 2. Device configuration includes a language (IETF language tags) and country (ISO 3166-1 Alpha-2)
+ *
+ * @param deviceProp a data structure storing the above information to be delivered
+ * @param callback will give the result if the provisioning succeeds or fails
+ *
+ * @throws ESException If some errors happen in this function
+ *
+ * @see DeviceProp
+ * @see DevicePropProvisioningCallback
+ */
+ public void provisionDeviceProperties(DeviceProp deviceProp,
+ DevicePropProvisioningCallback callback) throws ESException{
+ if(callback != null)
+ {
+ nativeProvisionDeviceProperties(deviceProp.toOCRepresentation(),
+ callback);
+ return;
+ }
+ Log.d(TAG, "DevicePropProvisioningCallback is null ");
+ }
+
+ /**
+ * Provision Cloud information to Enrollee, which includes Auth code, auth provider,
+ * Cloud interface server URL, and etc.
+ * In this function, Discovery for the Enrollee will happen again in a given network.
+ * Because, this function is expected to call *AFTER* the Enrollee disconnects its Soft AP
+ * and successfully connects to the certain WiFi AP. In that case, Mediator should discover
+ * the Enrollee with a certain Device ID in the network.
+ *
+ * @param cloudProp a data structure storing the above information to be delivered
+ * @param callback will give the result if the provisioning succeeds or fails
+ *
+ * @throws ESException If some errors happen in this function
+ *
+ * @see CloudProp
+ * @see CloudPropProvisioningCallback
+ */
+ public void provisionCloudProperties(CloudProp cloudProp,
+ CloudPropProvisioningCallback callback) throws ESException{
+ if(callback != null)
+ {
+ nativeProvisionCloudProperties(cloudProp.toOCRepresentation(),
+ cloudProp.getCloudID(),
+ callback);
+ return;
+ }
+ Log.d(TAG, "CloudPropProvisioningCallback is null ");
+ }
}
--- /dev/null
+/**
+ * ***************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+import org.iotivity.service.easysetup.mediator.SecurityProvisioningStatus;
+
+/**
+ * This interface class is used as a callback function called after receiving
+ * Security provisioning result
+ *
+ * @see SecurityProvisioningStatus
+ */
+public abstract class SecurityProvisioningCallback {
+
+ /**
+ * Called after receiving Security provisioning result
+ *
+ * @param status
+ * a result of security provisioning
+ * a device ID of a target Enrollee even if security provisioning
+ * is failed for some reasons
+ *
+ * @see SecurityProvisioningStatus
+ */
+ public abstract void onProgress(SecurityProvisioningStatus status);
+}
--- /dev/null
+/**
+ * ***************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+import android.util.Log;
+
+import org.iotivity.service.easysetup.mediator.enums.ESResult;
+
+/**
+ * This class indicates a result if a provisionSecurity API succeed or fails and
+ * a target Enrollee's device ID
+ */
+public class SecurityProvisioningStatus
+{
+ private ESResult mResult;
+ private String mDevUUID;
+
+ /**
+ * Constructor
+ *
+ * @param result a result of security provisioning
+ * @param uuid a device ID of a target Enrollee
+ */
+ public SecurityProvisioningStatus(int result, String uuid)
+ {
+ mResult = ESResult.fromInt(result);
+ mDevUUID = uuid;
+ }
+
+ /**
+ * Get a Result of security provisioning
+ *
+ * @return ESResult a result of security provisioning
+ */
+ public ESResult getESResult()
+ {
+ return mResult;
+ }
+
+ /**
+ * Get a device ID of a target Enrollee
+ *
+ * @return String a device ID of a target Enrollee
+ */
+ public String getDevUUID()
+ {
+ return mDevUUID;
+ }
+};
+++ /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 org.iotivity.service.easysetup.mediator.OnBoardingConfig;
-
-import android.net.wifi.WifiConfiguration;
-
-/**
- * This class contains on boarding configuration information for Soft AP on boarding connectivity.
- * It implements OnBoardingConfig interface & provide implementation for WiFi Soft AP connectivity.
- */
-
-public class WiFiOnBoardingConfig implements OnBoardingConfig {
-
- private boolean isSecured;
- private final WifiConfiguration config = new WifiConfiguration();
- private final ConnType mConnType = OnBoardingConfig.ConnType.WiFi;
-
- @Override
- public Object getConfig() {
- return config;
- }
-
- public void setSSId(String ssid) {
- config.SSID = ssid;
- }
-
- public void setSharedKey(String sharedKey) {
- config.preSharedKey = sharedKey;
- }
-
- public void setAuthAlgo(int aurthAlgo) {
- config.allowedAuthAlgorithms.set(aurthAlgo);
- }
-
- public void setKms(int kms) {
- config.allowedKeyManagement.set(kms);
- }
-
- @Override
- public ConnType getConnType() {
- return mConnType;
- }
-
- @Override
- public boolean isSecured(){
- return isSecured;
- }
-
- @Override
- public void setSecured(boolean flag) {
- isSecured = flag;
- }
-}
+++ /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 org.iotivity.service.easysetup.mediator.ProvisioningConfig;
-
-/**
- * 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 boolean isSecured;
-
- 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;
- }
-
- /**
- * This method returns the SSID of the Target WIFI network
- * @return SSID of Target Network
- */
- public String getSsId() {
- return mSsId;
- }
-
- /**
- * This method returns the password of the Target WIFI network
- * @return password of Target Network
- */
- public String getPassword() {
- return mPassword;
- }
-
- @Override
- public boolean isSecured(){
- return isSecured;
- }
-
- @Override
- public void setSecured(boolean flag) {
- isSecured = flag;
- }
-}
--- /dev/null
+/**
+ * ***************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator.enums;
+
+/**
+ * It defines various states of the cloud provisioning during easy setup process
+ */
+public enum ESCloudProvState {
+
+ /**
+ * Some error occurs during cloud data provisioning
+ */
+ ES_CLOUD_PROVISIONING_ERROR(-1),
+
+ /**
+ * Cloud data provisioning is successfully done
+ */
+ ES_CLOUD_PROVISIONING_SUCCESS(0),
+
+ /**
+ * Target enrollee which needs a cloud provisioning is found in a network
+ */
+ ES_CLOUD_ENROLLEE_FOUND(1),
+
+ /**
+ * Target enrollee which needs a cloud provisioning is NOT found in a network
+ */
+ ES_CLOUD_ENROLLEE_NOT_FOUND(2);
+
+ private int value;
+
+ private ESCloudProvState(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ public static ESCloudProvState fromInt(int i) {
+ for (ESCloudProvState b : ESCloudProvState.values()) {
+ if (b.getValue() == i) { return b; }
+ }
+ return null;
+ }
+};
+
--- /dev/null
+/**
+ * ***************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator.enums;
+
+/**
+ * @brief Indicate last error code to describe a reason of error during easy setup.
+ */
+public enum ESErrorCode {
+
+ /**
+ * Init Error Code
+ */
+ ES_ERRCODE_NO_ERROR(0),
+
+ /**
+ * Error Code that given WiFi's SSID is not found
+ */
+ ES_ERRCODE_SSID_NOT_FOUND(1),
+
+ /**
+ * Error Code that given WiFi's Password is wrong
+ */
+ ES_ERRCODE_PW_WRONG(2),
+
+ /**
+ * Error Code that IP address is not allocated
+ */
+ ES_ERRCODE_IP_NOT_ALLOCATED(3),
+
+ /**
+ * Error Code that there is no Internet connection
+ */
+ ES_ERRCODE_NO_INTERNETCONNECTION(4),
+
+ /**
+ * Error Code that Timeout occured
+ */
+ ES_ERRCODE_TIMEOUT(5),
+
+ /**
+ * Error Code that Unknown error occured
+ */
+ ES_ERRCODE_UNKNOWN(6);
+
+ private int value;
+
+ private ESErrorCode(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ public static ESErrorCode fromInt(int i) {
+ for (ESErrorCode b : ESErrorCode.values()) {
+ if (b.getValue() == i) { return b; }
+ }
+ return null;
+ }
+};
+
--- /dev/null
+/**
+ * ***************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator.enums;
+
+/**
+ * It defines an result during easy setup process, which is same as one in Easy Setup C++ SDK
+ */
+public enum ESResult {
+ ES_ERROR(-1),
+ ES_OK(0),
+ ES_NETWORKFOUND(1),
+ ES_NETWORKCONNECTED(2),
+ ES_NETWORKNOTCONNECTED(3),
+ ES_RESOURCECREATED(11),
+ ES_RECVREQOFPROVRES(21),
+ ES_RECVREQOFNETRES(22),
+ ES_RECVUPDATEOFPROVRES(23),
+ ES_RECVTRIGGEROFPROVRES(24),
+ ES_UNAUTHORIZED(25);
+
+ private int value;
+
+ private ESResult(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ public static ESResult fromInt(int i) {
+ for (ESResult b : ESResult.values()) {
+ if (b.getValue() == i) { return b; }
+ }
+ return null;
+ }
+};
\ No newline at end of file
--- /dev/null
+/**
+ * ***************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator.enums;
+
+/**
+ * It defines various states of the cloud provisioning during easy setup process
+ */
+public enum ProvStatus {
+
+ /**
+ * Default state of the device
+ */
+ ES_STATE_INIT(0),
+
+ /**
+ * Status indicating being connecting to target network
+ */
+ ES_STATE_CONNECTING_TO_ENROLLER(1),
+
+ /**
+ * Status indicating successful connection to target network
+ */
+ ES_STATE_CONNECTED_TO_ENROLLER(2),
+
+ /**
+ * Status indicating failure connection to target network
+ */
+ ES_STATE_CONNECTED_FAIL_TO_ENROLLER(3),
+
+ /**
+ * Status indicating successful registration to cloud
+ */
+ ES_STATE_REGISTERED_TO_CLOUD(4),
+
+ /**
+ * Status indicating failure registration to cloud
+ */
+ ES_STATE_REGISTRRED_FAIL_TO_CLOUD(5);
+
+ private int value;
+
+ private ProvStatus(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ public static ProvStatus fromInt(int i) {
+ for (ProvStatus b : ProvStatus.values()) {
+ if (b.getValue() == i) { return b; }
+ }
+ return null;
+ }
+};
+
/**
* ***************************************************************
- * <p>
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- * <p>
- * <p>
- * <p>
+ *
+ * Copyright 2016 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
- * <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 interface IOnBoardingStatus {
+package org.iotivity.service.easysetup.mediator.enums;
- /**
- * Interface called when the scan method finishes. Network operations should
- * not execute on UI thread
- *
- * @param clients of {@link EnrolleeInfo}
- */
+/**
+ * This enum class indicates a WiFi authentication type
+ */
+public enum WIFI_AUTHTYPE
+{
+ NONE_AUTH(0),
+ WEP(1),
+ WPA_PSK(2),
+ WPA2_PSK(3);
+
+ private int value;
+
+ private WIFI_AUTHTYPE(int value)
+ {
+ this.value = value;
+ }
- public void deviceOnBoardingStatus(EnrolleeInfo clients);
+ public int getValue()
+ {
+ return value;
+ }
+ public static WIFI_AUTHTYPE fromInt(int i)
+ {
+ for (WIFI_AUTHTYPE b : WIFI_AUTHTYPE.values())
+ {
+ if (b.getValue() == i)
+ return b;
+ }
+ return null;
+ }
}
--- /dev/null
+/**
+ * ***************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator.enums;
+
+/**
+ * This enum class indicates a WiFi encryption type
+ */
+public enum WIFI_ENCTYPE
+{
+ NONE_ENC(0),
+ WEP_64(1),
+ WEP_128(2),
+ TKIP(3),
+ AES(4),
+ TKIP_AES(5);
+
+ private int value;
+
+ private WIFI_ENCTYPE(int value)
+ {
+ this.value = value;
+ }
+
+ public int getValue()
+ {
+ return value;
+ }
+
+ public static WIFI_ENCTYPE fromInt(int i)
+ {
+ for (WIFI_ENCTYPE b : WIFI_ENCTYPE.values())
+ {
+ if (b.getValue() == i)
+ return b;
+ }
+ return null;
+ }
+}
--- /dev/null
+/**
+ * ***************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator.enums;
+
+/**
+ * This enum class indicates a WiFi frequency like 2.4G and 5G
+ */
+public enum WIFI_FREQ
+{
+ WIFI_24G(0),
+ WIFI_5G(1),
+ WIFI_BOTH(2),
+ WIFI_FREQ_NONE(999);
+
+ private int value;
+
+ private WIFI_FREQ(int value)
+ {
+ this.value = value;
+ }
+
+ /**
+ * Get WiFi frequency as an integer value
+ *
+ * @return int WiFi freq. as an integer value
+ */
+ public int getValue()
+ {
+ return value;
+ }
+
+ /**
+ * Get WiFi frequency as an integer value
+ *
+ * @return WIFI_FREQ enum value corresponding to its integer value
+ */
+ public static WIFI_FREQ fromInt(int i)
+ {
+ for (WIFI_FREQ b : WIFI_FREQ.values())
+ {
+ if (b.getValue() == i)
+ return b;
+ }
+ return null;
+ }
+}
--- /dev/null
+/**
+ * ***************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator.enums;
+
+/**
+ * This enum class indicates a WiFi mode like 11A and 11N.
+ */
+public enum WIFI_MODE
+{
+ /**
+ * 801.11A
+ */
+ WIFI_11A(0),
+
+ /**
+ * 801.11B
+ */
+ WIFI_11B(1),
+
+ /**
+ * 801.11G
+ */
+ WIFI_11G(2),
+
+ /**
+ * 801.11N
+ */
+ WIFI_11N(3),
+
+ /**
+ * 801.11AC
+ */
+ WIFI_11AC(4);
+
+ private int value;
+
+ private WIFI_MODE(int value)
+ {
+ this.value = value;
+ }
+
+ /**
+ * Get WiFi mode as an integer value
+ *
+ * @return int WiFi mode as an integer value
+ */
+ public int getValue()
+ {
+ return value;
+ }
+
+ /**
+ * Convert integer to WIFI_MODE enum value
+ *
+ * @param i An integer value converting
+ * @return WIFI_MODE enum value corresponding to its integer value
+ */
+ public static WIFI_MODE fromInt(int i)
+ {
+ for (WIFI_MODE b : WIFI_MODE.values())
+ {
+ if (b.getValue() == i)
+ return b;
+ }
+ return null;
+ }
+}
--- /dev/null
+#//******************************************************************
+#//
+#// Copyright 2016 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.
+#//
+#//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+LOCAL_PATH := $(call my-dir)
+SECURED := $(SECURE)
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../../../../../../out/android/$(TARGET_ARCH_ABI)/$(APP_OPTIM)
+LOCAL_MODULE := android-oc
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboc.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../../../../../../out/android/$(TARGET_ARCH_ABI)/$(APP_OPTIM)
+LOCAL_MODULE := android-easysetup
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libESMediatorRich.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+ifeq ($(SECURED), 1)
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../../../../../../out/android/$(TARGET_ARCH_ABI)/$(APP_OPTIM)
+LOCAL_MODULE := android-ocprovision
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libocprovision.so
+include $(PREBUILT_SHARED_LIBRARY)
+endif
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../../../../../../android/android_api/base/libs/armeabi
+LOCAL_MODULE := android-ocstack
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libocstack-jni.so
+include $(PREBUILT_SHARED_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))
+
+LOCAL_C_INCLUDES := $(LOCAL_PATH) \
+ $(LOCAL_PATH)/../../../../../inc \
+ $(LOCAL_PATH)/../../../../../../../inc \
+ $(LOCAL_PATH)/../../../../../../../../../resource/csdk/logger/include \
+ $(LOCAL_PATH)/../../../../../../../../../resource/csdk/connectivity/common/inc \
+ $(LOCAL_PATH)/../../../../../../../../../resource/c_common/oic_string/include \
+ $(LOCAL_PATH)/../../../../../../../../../resource/include \
+ $(LOCAL_PATH)/../../../../../../../../../resource/c_common \
+ $(LOCAL_PATH)/../../../../../../../../../resource/oc_logger/include \
+ $(LOCAL_PATH)/../../../../../../../../../resource/c_common/oic_malloc/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 \
+
+LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/*.cpp))
+LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/*.h))
+
+LOCAL_LDLIBS := -llog
+#LOCAL_SHARED_LIBRARIES += android-connectivity_abstraction
+LOCAL_SHARED_LIBRARIES += android-ocstack
+ifeq ($(SECURED), 1)
+LOCAL_SHARED_LIBRARIES += android-ocprovision
+endif
+LOCAL_SHARED_LIBRARIES += android-oc
+LOCAL_SHARED_LIBRARIES += android-easysetup
+
+include $(BUILD_SHARED_LIBRARY)
--- /dev/null
+#//******************************************************************
+#//
+#// Copyright 2016 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.
+#//
+#//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+APP_STL := gnustl_shared
+APP_PLATFORM = android-21
+NDK_TOOLCHAIN_VERSION := 4.8
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2016 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 "JniCloudPropProvisioningStatusListener.h"
+#include "JniRemoteEnrollee.h"
+
+using namespace OIC::Service;
+
+JniCloudPropProvisioningStatusListener::JniCloudPropProvisioningStatusListener(JNIEnv *env, jobject jListener,
+ JniRemoteEnrollee *owner)
+ : m_ownerResource(owner)
+{
+ m_jwListener = env->NewWeakGlobalRef(jListener);
+}
+
+JniCloudPropProvisioningStatusListener::~JniCloudPropProvisioningStatusListener()
+{
+ ES_LOGI("~JniCloudPropProvisioningStatusListener()");
+ if (m_jwListener)
+ {
+ jint ret;
+ JNIEnv *env = GetESJNIEnv(ret);
+ if (NULL == env) return;
+ env->DeleteWeakGlobalRef(m_jwListener);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ }
+}
+
+void JniCloudPropProvisioningStatusListener::onCloudPropProvisioningStatus(std::shared_ptr<CloudPropProvisioningStatus>
+ cloudPropProvisioningStatus)
+{
+
+ ES_LOGI("JniCloudPropProvisioningStatusListener::onCloudPropProvisioningStatus enter");
+
+ jint ret;
+ JNIEnv *env = GetESJNIEnv(ret);
+ if (NULL == env) return;
+ jobject jListener = env->NewLocalRef(m_jwListener);
+ if (!jListener)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ jclass clsL = env->GetObjectClass(jListener);
+ if (!clsL)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ jmethodID midL = env->GetMethodID(clsL, "onProgress",
+ "(Lorg/iotivity/service/easysetup/mediator/"
+ "CloudPropProvisioningStatus;"
+ ")V");
+ if (!midL)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ ESResult esResult = cloudPropProvisioningStatus->getESResult();
+ ESCloudProvState cloudProvisionState = cloudPropProvisioningStatus->getESCloudState();
+
+ //create the java object
+ jobject jCloudPropProvisioningStatus = NULL;
+ jCloudPropProvisioningStatus = env->NewObject(g_cls_CloudPropProvisioningStatus,
+ g_mid_CloudPropProvisioningStatus_ctor,
+ (jint)esResult,
+ (jint)cloudProvisionState);
+
+ ES_LOGI("JniCloudPropProvisioningStatus::onCloudPropProvisioningStatus - %d, %d", esResult, cloudProvisionState);
+ if (!jCloudPropProvisioningStatus)
+ {
+ ES_LOGE("JniCloudPropProvisioningStatus::onCloudPropProvisioningStatus Unable to create the java object");
+ return ;
+ }
+
+ env->CallVoidMethod(jListener, midL, jCloudPropProvisioningStatus);
+
+ bool needRemoveListener = false;
+
+ if(cloudProvisionState == ES_CLOUD_PROVISIONING_ERROR ||
+ cloudProvisionState == ES_CLOUD_PROVISIONING_SUCCESS )
+ {
+ needRemoveListener = true;
+ }
+
+ if (env->ExceptionCheck())
+ {
+ ES_LOGE("Java exception is thrown");
+ if(needRemoveListener)
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+}
+
+void JniCloudPropProvisioningStatusListener::checkExAndRemoveListener(JNIEnv *env)
+{
+ if (env->ExceptionCheck())
+ {
+ jthrowable ex = env->ExceptionOccurred();
+ env->ExceptionClear();
+ m_ownerResource->removeStatusListener<JniCloudPropProvisioningStatusListener>(env, m_jwListener);
+ env->Throw((jthrowable)ex);
+ }
+ else
+ {
+ m_ownerResource->removeStatusListener<JniCloudPropProvisioningStatusListener>(env, m_jwListener);
+ }
+}
* Copyright 2016 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
* @brief This file contains JNI Provisioing status Listener class
*/
-#ifndef __JNI_ES_PROVISIONING_STATUS_LISTENER_H_
-#define __JNI_ES_PROVISIONING_STATUS_LISTENER_H_
+#ifndef __JNI_ES_CLOUD_PROP_PROVISIONING_STATUS_LISTENER_H_
+#define __JNI_ES_CLOUD_PROP_PROVISIONING_STATUS_LISTENER_H_
#include <jni.h>
using namespace OIC::Service;
/**
- * @class JniProvisioningStatusListener
- * @brief This class provides functions for handling the provisioning status callback between the Java and native layer
+ * @class JniCloudPropProvisioningStatusListener
+ * @brief This class provides functions for handling the cloud provisioning status callback between the Java and native layer
*
*/
-class JniProvisioningStatusListener
+class JniCloudPropProvisioningStatusListener
{
public:
/**
* @brief constructor
*/
- JniProvisioningStatusListener(JNIEnv *env, jobject jListener, JniRemoteEnrollee *resource);
+ JniCloudPropProvisioningStatusListener(JNIEnv *env, jobject jListener, JniRemoteEnrollee *resource);
/**
* @brief destructor
*/
- ~JniProvisioningStatusListener();
+ ~JniCloudPropProvisioningStatusListener();
/**
* @brief callback function that will be passed to Native layer
*/
- void provisionStatusCallback (std::shared_ptr<EasySetupStatus> easySetupStatus);
+ void onCloudPropProvisioningStatus (std::shared_ptr<CloudPropProvisioningStatus> cloudPropProvisioningStatus);
private:
jweak m_jwListener;
void checkExAndRemoveListener(JNIEnv *env);
};
-#endif //__JNI_ES_PROVISIONING_STATUS_LISTENER_H_
+#endif //__JNI_ES_CLOUD_PROP_PROVISIONING_STATUS_LISTENER_H_
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2016 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 "JniDevicePropProvisioningStatusListener.h"
+#include "JniRemoteEnrollee.h"
+
+using namespace OIC::Service;
+
+JniDevicePropProvisioningStatusListener::JniDevicePropProvisioningStatusListener(JNIEnv *env, jobject jListener,
+ JniRemoteEnrollee *owner)
+ : m_ownerResource(owner)
+{
+ m_jwListener = env->NewWeakGlobalRef(jListener);
+}
+
+JniDevicePropProvisioningStatusListener::~JniDevicePropProvisioningStatusListener()
+{
+ ES_LOGI("~JniDevicePropProvisioningStatusListener()");
+ if (m_jwListener)
+ {
+ jint ret;
+ JNIEnv *env = GetESJNIEnv(ret);
+ if (NULL == env) return;
+ env->DeleteWeakGlobalRef(m_jwListener);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ }
+}
+
+void JniDevicePropProvisioningStatusListener::onDevicePropProvisioningStatusCallback (std::shared_ptr<DevicePropProvisioningStatus>
+ devicePropProvStatusCb)
+{
+
+ ES_LOGI("JniDevicePropProvisioningStatusListener::onDevicePropProvisioningStatusCallback enter");
+
+ jint ret;
+ JNIEnv *env = GetESJNIEnv(ret);
+ if (NULL == env) return;
+ jobject jListener = env->NewLocalRef(m_jwListener);
+ if (!jListener)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ jclass clsL = env->GetObjectClass(jListener);
+ if (!clsL)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+ //TODO:
+ jmethodID midL = env->GetMethodID(clsL, "onProgress",
+ "(Lorg/iotivity/service/easysetup/mediator/"
+ "DevicePropProvisioningStatus;"
+ ")V");
+
+ if (!midL)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ int nativeESResult = convertNativeDeviceProvResultToInt(devicePropProvStatusCb->getESResult());
+
+ jobject jDevicePropProvisioningStatus = NULL;
+ jDevicePropProvisioningStatus = env->NewObject(g_cls_DevicePropProvisioningStatus,
+ g_mid_DevicePropProvisioningStatus_ctor,
+ (jint)nativeESResult);
+
+ ES_LOGI("JniDevicePropProvisioningStatus::onDevicePropProvisioningStatus - %d", nativeESResult);
+ if (!jDevicePropProvisioningStatus)
+ {
+ ES_LOGE("JniDevicePropProvisioningStatus::onDevicePropProvisioningStatus Unable to create the java object");
+ return ;
+ }
+
+ env->CallVoidMethod(jListener, midL, jDevicePropProvisioningStatus);
+
+ if (env->ExceptionCheck())
+ {
+ ES_LOGE("Java exception is thrown");
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+}
+
+void JniDevicePropProvisioningStatusListener::checkExAndRemoveListener(JNIEnv *env)
+{
+ if (env->ExceptionCheck())
+ {
+ jthrowable ex = env->ExceptionOccurred();
+ env->ExceptionClear();
+ m_ownerResource->removeStatusListener<JniDevicePropProvisioningStatusListener>(env, m_jwListener);
+ env->Throw((jthrowable)ex);
+ }
+ else
+ {
+ m_ownerResource->removeStatusListener<JniDevicePropProvisioningStatusListener>(env, m_jwListener);
+ }
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2016 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 __JNI_ES_DEVICE_PROP_PROVISIONING_STATUS_LISTENER_H_
+#define __JNI_ES_DEVICE_PROP_PROVISIONING_STATUS_LISTENER_H_
+
+#include <jni.h>
+
+#include "RemoteEnrollee.h"
+#include "ESRichCommon.h"
+
+#include "JniJvm.h"
+
+class JniRemoteEnrollee;
+
+using namespace OIC::Service;
+
+class JniDevicePropProvisioningStatusListener
+{
+ public:
+ /**
+ * @brief constructor
+ */
+ JniDevicePropProvisioningStatusListener(JNIEnv *env, jobject jListener, JniRemoteEnrollee *resource);
+
+ /**
+ * @brief destructor
+ */
+ ~JniDevicePropProvisioningStatusListener();
+
+ /**
+ * @brief callback function that will be passed to Native layer
+ */
+ void onDevicePropProvisioningStatusCallback (std::shared_ptr<DevicePropProvisioningStatus> devicePropProvisioningStatus);
+
+ private:
+ jweak m_jwListener;
+ JniRemoteEnrollee *m_ownerResource;
+ void checkExAndRemoveListener(JNIEnv *env);
+};
+
+#endif //__JNI_ES_DEVICE_PROP_PROVISIONING_STATUS_LISTENER_H_
* limitations under the License.
*
******************************************************************/
+#include <memory>
+#include <vector>
+#include "OCPlatform.h"
+#include "OCResource.h"
+#include "octypes.h"
+#include "ESRichCommon.h"
+
+#include "JniOcResource.h"
#include "JniEasySetup.h"
+using namespace OC;
using namespace OIC::Service;
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_easysetup_mediator_EasySetupService_nativeCreateEnrolleeDevice
-(JNIEnv *env, jobject interfaceClass, jstring ip, jstring ssid, jstring password,
- jint connectivityType, jboolean isSecured)
+Java_org_iotivity_service_easysetup_mediator_EasySetup_nativeCreateRemoteEnrollee
+(JNIEnv *env, jobject thiz, jobject jResource)
{
-
- LOGI("JniEasySetup::nativeCreateEnrolleeDevice enter");
+ ES_LOGI("JniEasySetup::nativeCreateRemoteEnrollee enter");
std::shared_ptr<RemoteEnrollee> nativeRemoteEnrollee;
jobject jRemoteEnrollee;
- ProvConfig netInfo;
- WiFiOnboadingConnection onboardConn;
-
- const char *cIp = (env)->GetStringUTFChars(ip, NULL);
- const char *cSssid = (env)->GetStringUTFChars(ssid, NULL);
- const char *cPassword = (env)->GetStringUTFChars(password, NULL);
-
- std::string sIp(cIp);
- std::string sSssid(cSssid);
- std::string sPassword(cPassword);
- netInfo.connType = getOCConnectivityTypeFromInt(connectivityType);
+ JniOcResource* jniOcResource = JniOcResource::getJniOcResourcePtr(env, jResource);
- onboardConn.isSecured = bool(isSecured);
-
- OICStrcpy(onboardConn.ipAddress, IPV4_ADDR_SIZE - 1, sIp.c_str());
- OICStrcpy(netInfo.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, sSssid.c_str());
- OICStrcpy(netInfo.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, sPassword.c_str());
+ if (!jniOcResource)
+ {
+ ES_LOGE("JniEasySetup::nativeCreateRemoteEnrollee getJniOcResourcePtr returns nullptr.");
+ return nullptr;
+ }
try
{
- nativeRemoteEnrollee = EasySetup::getInstance()->createEnrolleeDevice(netInfo,onboardConn);
+ nativeRemoteEnrollee = EasySetup::getInstance()->createRemoteEnrollee(jniOcResource->getOCResource());
//create the java object
jRemoteEnrollee = env->NewObject(g_cls_RemoteEnrollee, g_mid_RemoteEnrollee_ctor);
if (!jRemoteEnrollee)
{
- LOGE("JniEasySetup::nativeCreateEnrolleeDevice Unable to create the java object");
+ ES_LOGE("JniEasySetup::nativeCreateRemoteEnrollee Unable to create the java object");
return NULL;
}
-
JniRemoteEnrollee *jniRemoteEnrollee = new JniRemoteEnrollee(nativeRemoteEnrollee);
ESSetHandle<JniRemoteEnrollee>(env, jRemoteEnrollee, jniRemoteEnrollee);
}
catch (ESBadRequestException exception)
{
- LOGE("JniEasySetup::nativeCreateEnrolleeDevice Unable to create the Native EnrolleeDevice");
+ ES_LOGE("JniEasySetup::nativeCreateRemoteEnrollee Unable to create the Native EnrolleeDevice");
//throw the exception to java layer
throwESException( env, exception.what());
}
- LOGI("JniEasySetup::nativeCreateEnrolleeDevice exit");
+ ES_LOGI("JniEasySetup::nativeCreateRemoteEnrollee exit");
return jRemoteEnrollee;
}
/**
* API for creating and returning the RemoteEnrollee object to Java Layer
*
- * @param ip - ip address of Enrollee
- * @param ssid - ssid of the Enroller
- * @param password - password of the enroller
- * @param connectivityType - Connectivity Type
- * @param needSecuredEasysetup - need secured easy setup or not
- *
* @return jobject - RemoteEnrolleee
*/
JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_easysetup_mediator_EasySetupService_nativeCreateEnrolleeDevice
-(JNIEnv *env, jobject interfaceClass, jstring ip, jstring ssid, jstring password,
- jint connectivityType, jboolean needSecuredEasysetup);
+Java_org_iotivity_service_easysetup_mediator_EasySetup_nativeCreateRemoteEnrollee
+(JNIEnv *env, jobject thiz, jobject jResource);
+
#ifdef __cplusplus
}
refPair.second++;
it->second = refPair;
m_listenerMap.insert(*it);
- LOGD("OnEventListener: ref. count is incremented");
+ ES_LOGD("OnEventListener: ref. count is incremented");
break;
}
}
}
else
{
- LOGD("OnEventListener: Failed to create global listener ref.");
+ ES_LOGD("OnEventListener: Failed to create global listener ref.");
delete onEventListener;
}
- LOGD("OnEventListener: new listener");
+ ES_LOGD("OnEventListener: new listener");
}
m_mapMutex.unlock();
return onEventListener;
refPair.second--;
it->second = refPair;
m_listenerMap.insert(*it);
- LOGI("OnEventListener: ref. count is decremented");
+ ES_LOGI("OnEventListener: ref. count is decremented");
}
else
{
delete listener;
m_listenerMap.erase(it);
- LOGI("OnEventListener is removed");
+ ES_LOGI("OnEventListener is removed");
}
break;
}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2016 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 "JniEsUtils.h"
+
+void throwESException(JNIEnv *env, std::string reason)
+{
+ jobject ex = env->NewObject(g_cls_ESException, g_mid_ESException_ctor,
+ env->NewStringUTF(reason.c_str()));
+ if (!ex)
+ {
+ ES_LOGI("throwException : jobject is NULL");
+ }
+ env->Throw((jthrowable)ex);
+}
+
+OCConnectivityType getOCConnectivityTypeFromInt(int connectivityType)
+{
+ switch (connectivityType)
+ {
+ case CT_DEFAULT:
+ return CT_DEFAULT;
+ case CT_ADAPTER_IP:
+ return CT_ADAPTER_IP;
+
+ //May be need to add more types, if easy setup service support more transport.
+ }
+ return CT_DEFAULT;
+}
+
+WIFI_AUTHTYPE getWifiAuthTypeFromInt(int authType)
+{
+ switch (authType)
+ {
+ case 0:
+ return WIFI_AUTHTYPE::NONE_AUTH;
+ case 1:
+ return WIFI_AUTHTYPE::WEP;
+ case 2:
+ return WIFI_AUTHTYPE::WPA_PSK;
+ case 3:
+ return WIFI_AUTHTYPE::WPA2_PSK;
+ }
+ return NONE_AUTH;
+}
+
+WIFI_ENCTYPE getWifiEncTypeFromInt(int encType)
+{
+ switch (encType)
+ {
+ case 0:
+ return WIFI_ENCTYPE::NONE_ENC;
+ case 1:
+ return WIFI_ENCTYPE::WEP_64;
+ case 2:
+ return WIFI_ENCTYPE::WEP_128;
+ case 3:
+ return WIFI_ENCTYPE::TKIP;
+ case 4:
+ return WIFI_ENCTYPE::AES;
+ case 5:
+ return WIFI_ENCTYPE::TKIP_AES;
+ }
+ return NONE_ENC;
+}
+
+int convertNativeWifiFreqToInt(WIFI_FREQ wifiFreq)
+{
+ switch (wifiFreq)
+ {
+ case WIFI_FREQ::WIFI_24G:
+ return 0;
+ case WIFI_FREQ::WIFI_5G:
+ return 1;
+ case WIFI_FREQ::WIFI_BOTH:
+ return 2;
+ }
+}
+
+int convertNativeWifiModeToInt(WIFI_MODE wifiMode)
+{
+ switch (wifiMode)
+ {
+ case WIFI_MODE::WIFI_11A:
+ return 0;
+ case WIFI_MODE::WIFI_11B:
+ return 1;
+ case WIFI_MODE::WIFI_11G:
+ return 2;
+ case WIFI_MODE::WIFI_11N:
+ return 3;
+ case WIFI_MODE::WIFI_11AC:
+ return 4;
+ }
+}
+
+int convertNativeDeviceProvResultToInt(ESResult nativeResult)
+{
+ switch (nativeResult)
+ {
+ case ESResult::ES_ERROR:
+ return -1;
+ case ESResult::ES_OK:
+ return 0;
+ case ESResult::ES_NETWORKFOUND:
+ return 1;
+ case ESResult::ES_NETWORKCONNECTED:
+ return 2;
+ case ESResult::ES_NETWORKNOTCONNECTED:
+ return 3;
+ case ESResult::ES_RESOURCECREATED:
+ return 11;
+ case ESResult::ES_RECVREQOFPROVRES:
+ return 21;
+ case ESResult::ES_RECVREQOFNETRES:
+ return 22;
+ case ESResult::ES_RECVUPDATEOFPROVRES:
+ return 23;
+ case ESResult::ES_RECVTRIGGEROFPROVRES:
+ return 24;
+ case ESResult::ES_UNAUTHORIZED:
+ return 31;
+ }
+}
\ No newline at end of file
*/
OCConnectivityType getOCConnectivityTypeFromInt(int connectivityType);
-/**
-* @brief Convert EasySetupState Enum Value to int
-*/
-int convertNativeProvisionStateToInt(EasySetupState nativeState);
-
+WIFI_AUTHTYPE getWifiAuthTypeFromInt(int authType);
+WIFI_ENCTYPE getWifiEncTypeFromInt(int encType);
+int convertNativeWifiFreqToInt(WIFI_FREQ wifiFreq);
+int convertNativeWifiModeToInt(WIFI_MODE wifiMode);
+int convertNativeDeviceProvResultToInt(ESResult nativeResult);
#endif //__JNI_ES_UTILS_H_
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2016 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 "JniGetConfigurationStatusListener.h"
+#include "JniRemoteEnrollee.h"
+
+using namespace OC;
+using namespace OIC::Service;
+
+JniGetConfigurationStatusListener::JniGetConfigurationStatusListener(JNIEnv *env, jobject jListener,
+ JniRemoteEnrollee *owner)
+ : m_ownerResource(owner)
+{
+ m_jwListener = env->NewWeakGlobalRef(jListener);
+}
+
+JniGetConfigurationStatusListener::~JniGetConfigurationStatusListener()
+{
+ ES_LOGI("~JniGetConfigurationStatusListener()");
+ if (m_jwListener)
+ {
+ jint ret;
+ JNIEnv *env = GetESJNIEnv(ret);
+ if (NULL == env) return;
+ env->DeleteWeakGlobalRef(m_jwListener);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ }
+}
+
+void JniGetConfigurationStatusListener::getConfigurationStatusCallback (
+ std::shared_ptr<GetConfigurationStatus> getConfigurationStatusCb)
+{
+ ES_LOGI("JniGetConfigurationStatusListener::provisioiningStatusCallback enter");
+
+ jint ret;
+ JNIEnv *env = GetESJNIEnv(ret);
+ if (NULL == env) return;
+ jobject jListener = env->NewLocalRef(m_jwListener);
+ if (!jListener)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ jclass clsL = env->GetObjectClass(jListener);
+ if (!clsL)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ jmethodID midL = env->GetMethodID(clsL, "onProgress",
+ "(Lorg/iotivity/service/easysetup/mediator/"
+ "GetConfigurationStatus;"
+ ")V");
+
+ if (!midL)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ EnrolleeConf enrolleeConf = getConfigurationStatusCb->getEnrolleeConf();
+ OCRepresentation m_ProvRep = enrolleeConf.getProvResRep();
+
+ OCRepresentation* rep = new OCRepresentation(m_ProvRep);
+ jlong handle = reinterpret_cast<jlong>(rep);
+ jobject jRepresentation = env->NewObject(g_cls_OcRepresentation, g_mid_OcRepresentation_N_ctor_bool,
+ handle, true);
+ if (!jRepresentation)
+ {
+ delete rep;
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ return;
+ }
+
+ jobject jEnrolleeConf = NULL;
+ jEnrolleeConf = env->NewObject(g_cls_EnrolleeConf, g_mid_EnrolleeConf_ctor, (jobject)jRepresentation);
+ if (!jEnrolleeConf) {
+ ES_LOGE("JniGetConfigurationStatusListener::getConfigurationStatusCallback Unable to create the jEnrolleeConf");
+ return ;
+ }
+
+ ESResult esResult = getConfigurationStatusCb->getESResult();
+ jobject jgetConfigurationStatus = NULL;
+ jgetConfigurationStatus = env->NewObject(g_cls_getConfigurationStatus,
+ g_mid_getConfigurationStatus_ctor,
+ (jint)esResult,
+ (jobject)jEnrolleeConf);
+
+ if (!jgetConfigurationStatus)
+ {
+ ES_LOGE("JniGetConfigurationStatusListener::getConfigurationStatusCallback Unable to create the java object");
+ return ;
+ }
+
+ env->CallVoidMethod(jListener, midL, jgetConfigurationStatus);
+
+ if (env->ExceptionCheck())
+ {
+ ES_LOGE("Java exception is thrown");
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+}
+
+void JniGetConfigurationStatusListener::checkExAndRemoveListener(JNIEnv *env)
+{
+ if (env->ExceptionCheck())
+ {
+ jthrowable ex = env->ExceptionOccurred();
+ env->ExceptionClear();
+ m_ownerResource->removeStatusListener<JniGetConfigurationStatusListener>(env, m_jwListener);
+
+ env->Throw((jthrowable)ex);
+ }
+ else
+ {
+ m_ownerResource->removeStatusListener<JniGetConfigurationStatusListener>(env, m_jwListener);
+ }
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2016 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 __JNI_ES_GET_CONFIGURATION_STATUS_LISTENER_H_
+#define __JNI_ES_GET_CONFIGURATION_STATUS_LISTENER_H_
+
+#include <jni.h>
+
+#include "OCPlatform.h"
+#include "RemoteEnrollee.h"
+#include "ESRichCommon.h"
+
+#include "JniJvm.h"
+
+class JniRemoteEnrollee;
+
+using namespace OIC::Service;
+
+class JniGetConfigurationStatusListener
+{
+ public:
+ /**
+ * @brief constructor
+ */
+ JniGetConfigurationStatusListener(JNIEnv *env, jobject jListener, JniRemoteEnrollee *resource);
+
+ /**
+ * @brief destructor
+ */
+ ~JniGetConfigurationStatusListener();
+
+ /**
+ * @brief callback function that will be passed to Native layer
+ */
+ void getConfigurationStatusCallback (std::shared_ptr<GetConfigurationStatus> getConfigurationStatus);
+
+ private:
+ jweak m_jwListener;
+ JniRemoteEnrollee *m_ownerResource;
+ void checkExAndRemoveListener(JNIEnv *env);
+};
+
+#endif //__JNI_ES_GET_CONFIGURATION_STATUS_LISTENER_H_
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2016 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 "JniGetEnrolleeStatusListener.h"
+#include "JniRemoteEnrollee.h"
+
+using namespace OC;
+using namespace OIC::Service;
+
+JniGetEnrolleeStatusListener::JniGetEnrolleeStatusListener(JNIEnv *env, jobject jListener,
+ JniRemoteEnrollee *owner)
+ : m_ownerResource(owner)
+{
+ m_jwListener = env->NewWeakGlobalRef(jListener);
+}
+
+JniGetEnrolleeStatusListener::~JniGetEnrolleeStatusListener()
+{
+ ES_LOGI("~JniGetEnrolleeStatusListener()");
+ if (m_jwListener)
+ {
+ jint ret;
+ JNIEnv *env = GetESJNIEnv(ret);
+ if (NULL == env) return;
+ env->DeleteWeakGlobalRef(m_jwListener);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ }
+}
+
+void JniGetEnrolleeStatusListener::getEnrolleeStatusCallback (
+ std::shared_ptr<GetEnrolleeStatus> getEnrolleeStatusCb)
+{
+ ES_LOGI("JniGetEnrolleeStatusListener::getEnrolleeStatusCallback enter");
+
+ jint ret;
+ JNIEnv *env = GetESJNIEnv(ret);
+ if (NULL == env) return;
+ jobject jListener = env->NewLocalRef(m_jwListener);
+ if (!jListener)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ jclass clsL = env->GetObjectClass(jListener);
+ if (!clsL)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ jmethodID midL = env->GetMethodID(clsL, "onProgress",
+ "(Lorg/iotivity/service/easysetup/mediator/"
+ "GetEnrolleeStatus;"
+ ")V");
+
+ if (!midL)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ EnrolleeStatus enrolleeStatus = getEnrolleeStatusCb->getEnrolleeStatus();
+ OCRepresentation m_Rep = enrolleeStatus.getRepresentation();
+ OCRepresentation* rep = new OCRepresentation(m_Rep);
+ jlong handle = reinterpret_cast<jlong>(rep);
+ jobject jRepresentation = env->NewObject(g_cls_OcRepresentation,
+ g_mid_OcRepresentation_N_ctor_bool,
+ handle, true);
+ if (!jRepresentation)
+ {
+ delete rep;
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ return;
+ }
+
+ jobject jEnrolleeStatus = NULL;
+ jEnrolleeStatus = env->NewObject(g_cls_EnrolleeStatus,
+ g_mid_EnrolleeStatus_ctor,
+ (jobject)jRepresentation);
+ if (!jEnrolleeStatus) {
+ ES_LOGE("JniGetEnrolleeStatusListener::getEnrolleeStatusCallback Unable to create the jEnrolleeStatus");
+ return ;
+ }
+
+ ESResult esResult = getEnrolleeStatusCb->getESResult();
+ jobject jgetEnrolleeStatus = NULL;
+ jgetEnrolleeStatus = env->NewObject(g_cls_getEnrolleeStatus,
+ g_mid_getEnrolleeStatus_ctor,
+ (jint)esResult,
+ (jobject)jEnrolleeStatus);
+
+ if (!jgetEnrolleeStatus)
+ {
+ ES_LOGE("JniGetEnrolleeStatusListener::getEnrolleeStatusCallback Unable to create the java object");
+ return ;
+ }
+
+ env->CallVoidMethod(jListener, midL, jgetEnrolleeStatus);
+
+ if (env->ExceptionCheck())
+ {
+ ES_LOGE("Java exception is thrown");
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+}
+
+void JniGetEnrolleeStatusListener::checkExAndRemoveListener(JNIEnv *env)
+{
+ if (env->ExceptionCheck())
+ {
+ jthrowable ex = env->ExceptionOccurred();
+ env->ExceptionClear();
+ m_ownerResource->removeStatusListener<JniGetEnrolleeStatusListener>
+ (env, m_jwListener);
+
+ env->Throw((jthrowable)ex);
+ }
+ else
+ {
+ m_ownerResource->removeStatusListener<JniGetEnrolleeStatusListener>
+ (env, m_jwListener);
+ }
+}
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2016 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 __JNI_ES_GET_ENROLLEE_STATUS_LISTENER_H_
+#define __JNI_ES_GET_ENROLLEE_STATUS_LISTENER_H_
+
+#include <jni.h>
+
+#include "OCPlatform.h"
+#include "RemoteEnrollee.h"
+#include "ESRichCommon.h"
+
+#include "JniJvm.h"
+
+class JniRemoteEnrollee;
+
+using namespace OIC::Service;
+
+class JniGetEnrolleeStatusListener
+{
+ public:
+ /**
+ * @brief constructor
+ */
+ JniGetEnrolleeStatusListener(JNIEnv *env, jobject jListener, JniRemoteEnrollee *resource);
+
+ /**
+ * @brief destructor
+ */
+ ~JniGetEnrolleeStatusListener();
+
+ /**
+ * @brief callback function that will be passed to Native layer
+ */
+ void getEnrolleeStatusCallback (std::shared_ptr<GetEnrolleeStatus> getEnrolleeStatus);
+
+ private:
+ jweak m_jwListener;
+ JniRemoteEnrollee *m_ownerResource;
+ void checkExAndRemoveListener(JNIEnv *env);
+};
+
+#endif //__JNI_ES_GET_CONFIGURATION_STATUS_LISTENER_H_
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2016 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 "JniJvm.h"
+
+JavaVM *g_jvm = NULL;
+
+jclass g_cls_RemoteEnrollee = NULL;
+jclass g_cls_ESException = NULL;
+jclass g_cls_EnrolleeStatus = NULL;
+jclass g_cls_EnrolleeConf = NULL;
+jclass g_cls_getEnrolleeStatus = NULL;
+jclass g_cls_getConfigurationStatus = NULL;
+jclass g_cls_SecurityProvisioningStatus = NULL;
+jclass g_cls_DevicePropProvisioningStatus = NULL;
+jclass g_cls_CloudPropProvisioningStatus = NULL;
+jclass g_cls_Integer = NULL;
+jclass g_cls_OcRepresentation = NULL;
+
+jmethodID g_mid_RemoteEnrollee_ctor = NULL;
+jmethodID g_mid_ESException_ctor = NULL;
+jmethodID g_mid_EnrolleeStatus_ctor = NULL;
+jmethodID g_mid_EnrolleeConf_ctor = NULL;
+jmethodID g_mid_getEnrolleeStatus_ctor = NULL;
+jmethodID g_mid_getConfigurationStatus_ctor = NULL;
+jmethodID g_mid_SecurityProvisioningStatus_ctor = NULL;
+jmethodID g_mid_DevicePropProvisioningStatus_ctor = NULL;
+jmethodID g_mid_CloudPropProvisioningStatus_ctor = NULL;
+jmethodID g_mid_Integer_ctor = NULL;
+jmethodID g_mid_OcRepresentation_N_ctor_bool = NULL;
+
+// JNI OnLoad
+JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
+{
+ ES_LOGI("JNI_OnLoad");
+ JNIEnv *env;
+ g_jvm = vm;
+
+ if (g_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION) != JNI_OK)
+ {
+ ES_LOGE("Failed to get the environment using GetEnv()");
+ return JNI_ERR;
+ }
+
+ jclass clazz = nullptr;
+
+ // Remote Enrollee
+ clazz = env->FindClass("org/iotivity/service/easysetup/mediator/RemoteEnrollee");
+ if (!clazz) return JNI_ERR;
+ g_cls_RemoteEnrollee = (jclass)env->NewGlobalRef(clazz);
+ env->DeleteLocalRef(clazz);
+
+ g_mid_RemoteEnrollee_ctor = env->GetMethodID(g_cls_RemoteEnrollee, "<init>",
+ "(J)V");
+ if (!g_mid_RemoteEnrollee_ctor) return JNI_ERR;
+
+ // ESException
+ clazz = env->FindClass("org/iotivity/service/easysetup/mediator/ESException");
+ if (!clazz) return JNI_ERR;
+ g_cls_ESException = (jclass)env->NewGlobalRef(clazz);
+ env->DeleteLocalRef(clazz);
+
+ g_mid_ESException_ctor = env->GetMethodID(g_cls_ESException, "<init>", "(Ljava/lang/String;)V");
+ if (!g_mid_ESException_ctor) return JNI_ERR;
+
+ // EnrolleeStatus
+ clazz = env->FindClass("org/iotivity/service/easysetup/mediator/EnrolleeStatus");
+ if (!clazz) return JNI_ERR;
+
+ g_cls_EnrolleeStatus = (jclass)env->NewGlobalRef(clazz);
+ env->DeleteLocalRef(clazz);
+
+ g_mid_EnrolleeStatus_ctor = env->GetMethodID(g_cls_EnrolleeStatus, "<init>",
+ "(Lorg/iotivity/base/OcRepresentation;)V");
+ if (!g_mid_EnrolleeStatus_ctor) return JNI_ERR;
+
+ // EnrolleeConf
+ clazz = env->FindClass("org/iotivity/service/easysetup/mediator/EnrolleeConf");
+ if (!clazz) return JNI_ERR;
+
+ g_cls_EnrolleeConf = (jclass)env->NewGlobalRef(clazz);
+ env->DeleteLocalRef(clazz);
+
+ g_mid_EnrolleeConf_ctor = env->GetMethodID(g_cls_EnrolleeConf, "<init>",
+ "(Lorg/iotivity/base/OcRepresentation;)V");
+ if (!g_mid_EnrolleeConf_ctor) return JNI_ERR;
+
+ // getEnrolleeStatus
+ clazz = env->FindClass("org/iotivity/service/easysetup/mediator/GetEnrolleeStatus");
+ if (!clazz) return JNI_ERR;
+
+ g_cls_getEnrolleeStatus = (jclass)env->NewGlobalRef(clazz);
+ env->DeleteLocalRef(clazz);
+
+ g_mid_getEnrolleeStatus_ctor = env->GetMethodID(g_cls_getEnrolleeStatus, "<init>",
+ "(ILorg/iotivity/service/easysetup/mediator/EnrolleeStatus;)V");
+ if (!g_mid_getEnrolleeStatus_ctor) return JNI_ERR;
+
+ // getConfigurationStatus
+ clazz = env->FindClass("org/iotivity/service/easysetup/mediator/GetConfigurationStatus");
+ if (!clazz) return JNI_ERR;
+
+ g_cls_getConfigurationStatus = (jclass)env->NewGlobalRef(clazz);
+ env->DeleteLocalRef(clazz);
+
+ g_mid_getConfigurationStatus_ctor = env->GetMethodID(g_cls_getConfigurationStatus, "<init>",
+ "(ILorg/iotivity/service/easysetup/mediator/EnrolleeConf;)V");
+ if (!g_mid_getConfigurationStatus_ctor) return JNI_ERR;
+
+ // SecurityProvisioningStatus
+ clazz = env->FindClass("org/iotivity/service/easysetup/mediator/SecurityProvisioningStatus");
+ if (!clazz) return JNI_ERR;
+
+ g_cls_SecurityProvisioningStatus = (jclass)env->NewGlobalRef(clazz);
+ env->DeleteLocalRef(clazz);
+
+ g_mid_SecurityProvisioningStatus_ctor = env->GetMethodID(g_cls_SecurityProvisioningStatus, "<init>",
+ "(ILjava/lang/String;)V");
+ if (!g_mid_SecurityProvisioningStatus_ctor) return JNI_ERR;
+
+ // DevicePropProvisioningStatus
+ clazz = env->FindClass("org/iotivity/service/easysetup/mediator/DevicePropProvisioningStatus");
+ if (!clazz) return JNI_ERR;
+
+ g_cls_DevicePropProvisioningStatus = (jclass)env->NewGlobalRef(clazz);
+ env->DeleteLocalRef(clazz);
+
+ g_mid_DevicePropProvisioningStatus_ctor = env->GetMethodID(g_cls_DevicePropProvisioningStatus, "<init>",
+ "(I)V");
+ if (!g_mid_DevicePropProvisioningStatus_ctor) return JNI_ERR;
+
+ // CloudPropProvisioningStatus
+ clazz = env->FindClass("org/iotivity/service/easysetup/mediator/CloudPropProvisioningStatus");
+ if (!clazz) return JNI_ERR;
+ g_cls_CloudPropProvisioningStatus = (jclass)env->NewGlobalRef(clazz);
+ env->DeleteLocalRef(clazz);
+
+ g_mid_CloudPropProvisioningStatus_ctor = env->GetMethodID(g_cls_CloudPropProvisioningStatus, "<init>",
+ "(II)V");
+ if (!g_mid_CloudPropProvisioningStatus_ctor) return JNI_ERR;
+
+ // Integer
+ clazz = env->FindClass("java/lang/Integer");
+ if (!clazz) return JNI_ERR;
+ g_cls_Integer = (jclass)env->NewGlobalRef(clazz);
+ env->DeleteLocalRef(clazz);
+
+ g_mid_Integer_ctor = env->GetMethodID(g_cls_Integer, "<init>",
+ "(I)V");
+ if (!g_mid_Integer_ctor) return JNI_ERR;
+
+ //OcRepresentation
+ clazz = env->FindClass("org/iotivity/base/OcRepresentation");
+ if (!clazz) return JNI_ERR;
+ g_cls_OcRepresentation = (jclass)env->NewGlobalRef(clazz);
+ env->DeleteLocalRef(clazz);
+
+ g_mid_OcRepresentation_N_ctor_bool = env->GetMethodID(g_cls_OcRepresentation, "<init>", "(JZ)V");
+ if (!g_mid_OcRepresentation_N_ctor_bool) return JNI_ERR;
+
+ return JNI_CURRENT_VERSION;
+}
+
+//JNI OnUnload
+JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
+{
+ ES_LOGI("JNI_OnUnload");
+ JNIEnv *env;
+
+ if (g_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION) != JNI_OK)
+ {
+ ES_LOGE("Failed to get the environment using GetEnv()");
+ return;
+ }
+ env->DeleteGlobalRef(g_cls_RemoteEnrollee);
+ env->DeleteGlobalRef(g_cls_ESException);
+}
#define __JNI_ES_JVM_H
#include <jni.h>
-#include<string>
+#include <string>
#include <android/log.h>
#define ESTAG "ES-JNI"
#define JNI_CURRENT_VERSION JNI_VERSION_1_6
-#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, ESTAG, __VA_ARGS__)
-#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, ESTAG, __VA_ARGS__)
-#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, ESTAG, __VA_ARGS__)
+#define ES_LOGI(...) __android_log_print(ANDROID_LOG_INFO, ESTAG, __VA_ARGS__)
+#define ES_LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, ESTAG, __VA_ARGS__)
+#define ES_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, ESTAG, __VA_ARGS__)
extern JavaVM *g_jvm;
extern jclass g_cls_RemoteEnrollee;
extern jclass g_cls_ESException;
-
-extern jmethodID g_mid_RemoteEnrollee_ctor ;
+extern jclass g_cls_EnrolleeStatus;
+extern jclass g_cls_EnrolleeConf;
+extern jclass g_cls_getEnrolleeStatus;
+extern jclass g_cls_getConfigurationStatus;
+extern jclass g_cls_SecurityProvisioningStatus;
+extern jclass g_cls_DevicePropProvisioningStatus;
+extern jclass g_cls_CloudPropProvisioningStatus;
+extern jclass g_cls_Integer;
+extern jclass g_cls_OcRepresentation;
+
+extern jmethodID g_mid_RemoteEnrollee_ctor;
extern jmethodID g_mid_ESException_ctor;
+extern jmethodID g_mid_EnrolleeStatus_ctor;
+extern jmethodID g_mid_EnrolleeConf_ctor;
+extern jmethodID g_mid_getEnrolleeStatus_ctor;
+extern jmethodID g_mid_getConfigurationStatus_ctor;
+extern jmethodID g_mid_SecurityProvisioningStatus_ctor;
+extern jmethodID g_mid_DevicePropProvisioningStatus_ctor;
+extern jmethodID g_mid_CloudPropProvisioningStatus_ctor;
+extern jmethodID g_mid_Integer_ctor;
+extern jmethodID g_mid_OcRepresentation_N_ctor_bool;
typedef void(*RemoveListenerCallback)(JNIEnv *env, jobject jListener);
case JNI_EDETACHED:
if (g_jvm->AttachCurrentThread(&env, NULL) < 0)
{
- LOGE("Failed to get the environment");
+ ES_LOGE("Failed to get the environment");
return nullptr;
}
else
}
case JNI_EVERSION:
- LOGE("JNI version not supported");
+ ES_LOGE("JNI version not supported");
default:
- LOGE("Failed to get the environment");
+ ES_LOGE("Failed to get the environment");
return nullptr;
}
}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2016 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 "JniRemoteEnrollee.h"
+
+#include "JniOcRepresentation.h"
+
+using namespace OIC::Service;
+
+JniRemoteEnrollee::JniRemoteEnrollee(std::shared_ptr<RemoteEnrollee> remoteEnrollee)
+ : m_sharedResource(remoteEnrollee) {}
+
+JniRemoteEnrollee::~JniRemoteEnrollee()
+{
+ ES_LOGD("JniRemoteEnrollee::~JniRemoteEnrollee()");
+ m_sharedResource = NULL;
+
+ jint envRet;
+ JNIEnv *env = GetESJNIEnv(envRet);
+ if (NULL == env) return;
+
+ if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+}
+
+JniRemoteEnrollee *JniRemoteEnrollee::getJniRemoteEnrollee(JNIEnv *env, jobject thiz)
+{
+ JniRemoteEnrollee *remoteEnrollee = ESGetHandle<JniRemoteEnrollee>(env, thiz);
+ if (env->ExceptionCheck())
+ {
+ ES_LOGE("getJniRemoteEnrollee :: Failed to get native handle from RemoteEnrollee object");
+ }
+ if (!remoteEnrollee)
+ {
+ ES_LOGE("getJniRemoteEnrollee :: no resource");
+ }
+ return remoteEnrollee;
+}
+
+void JniRemoteEnrollee::getStatus(JNIEnv *env, jobject jListener)
+{
+ JniGetEnrolleeStatusListener *onGetEnrolleeStatusReceived =
+ addStatusListener<JniGetEnrolleeStatusListener>(env, jListener);
+
+ GetStatusCb getEnrolleeStatusCallback = [onGetEnrolleeStatusReceived]
+ (std::shared_ptr<OIC::Service::GetEnrolleeStatus > getEnrolleeStatus)
+ {
+ onGetEnrolleeStatusReceived->getEnrolleeStatusCallback(getEnrolleeStatus);
+ };
+
+ try
+ {
+ m_sharedResource->getStatus(getEnrolleeStatusCallback);
+ }
+ catch (ESBadRequestException exception)
+ {
+ ES_LOGE("JNI getStatus :: Exception occured");
+ //throw the exception to java
+ throwESException( env, exception.what());
+ }
+}
+
+void JniRemoteEnrollee::getConfiguration(JNIEnv *env, jobject jListener)
+{
+ JniGetConfigurationStatusListener *onGetConfigurationStatusReceived =
+ addStatusListener<JniGetConfigurationStatusListener>(env, jListener);
+
+ GetConfigurationStatusCb getConfigurationStatusCallback = [onGetConfigurationStatusReceived]
+ (std::shared_ptr<OIC::Service::GetConfigurationStatus > getConfigurationStatus)
+ {
+ onGetConfigurationStatusReceived->getConfigurationStatusCallback(getConfigurationStatus);
+ };
+
+ try
+ {
+ m_sharedResource->getConfiguration(getConfigurationStatusCallback);
+ }
+ catch (ESBadRequestException exception)
+ {
+ ES_LOGE("JNI getConfiguration :: Exception occured");
+ //throw the exception to java
+ throwESException( env, exception.what());
+ }
+}
+
+void JniRemoteEnrollee::provisionSecurity(JNIEnv *env, jobject jListener)
+{
+ JniSecurityStatusListener *onSecurityProvStatusReceived =
+ addStatusListener<JniSecurityStatusListener>(env, jListener);
+
+ SecurityProvStatusCb secProvStatusCallback = [onSecurityProvStatusReceived]
+ (std::shared_ptr<OIC::Service::SecProvisioningStatus > SecProvisioningStatus)
+ {
+ onSecurityProvStatusReceived->secProvisionStatusCallback(SecProvisioningStatus);
+ };
+
+ try
+ {
+ m_sharedResource->provisionSecurity(secProvStatusCallback);
+ }
+ catch (ESBadRequestException exception)
+ {
+ ES_LOGE("JNI provisionSecurity :: Exception occured");
+ //throw the exception to java
+ throwESException( env, exception.what());
+ }
+}
+
+void JniRemoteEnrollee::provisionDeviceProperties(JNIEnv *env,
+ jobject jRepresentation,
+ jobject jListener)
+{
+ OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
+ if (!representation)
+ {
+ return;
+ }
+
+ DeviceProp deviceProp(*representation);
+ JniDevicePropProvisioningStatusListener *onDevicePropProvStatusReceived =
+ addStatusListener<JniDevicePropProvisioningStatusListener>(env, jListener);
+
+ DevicePropProvStatusCb devicePropProvStatusCallback = [onDevicePropProvStatusReceived]
+ (std::shared_ptr<OIC::Service::DevicePropProvisioningStatus > devicePropProvisioningStatus)
+ {
+ onDevicePropProvStatusReceived->onDevicePropProvisioningStatusCallback(devicePropProvisioningStatus);
+ };
+
+ try
+ {
+ m_sharedResource->provisionDeviceProperties(deviceProp, devicePropProvStatusCallback);
+ }
+ catch (ESBadRequestException exception)
+ {
+ ES_LOGE("JNI provisionDeviceProperties :: Exception occured");
+ //throw the exception to java
+ throwESException( env, exception.what());
+ }
+}
+
+void JniRemoteEnrollee::provisionCloudProperties(JNIEnv *env,
+ jobject jRepresentation,
+ jstring jCloudID,
+ jobject jListener)
+{
+ OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
+ if (!representation)
+ {
+ return;
+ }
+
+ CloudProp cloudProp(*representation);
+ cloudProp.setCloudID(env->GetStringUTFChars(jCloudID, NULL));
+
+ JniCloudPropProvisioningStatusListener *onCloudPropProvisioningStatusReceived =
+ addStatusListener<JniCloudPropProvisioningStatusListener>(env, jListener);
+
+ CloudPropProvStatusCb cloudPropProvStatusCallback = [onCloudPropProvisioningStatusReceived]
+ (std::shared_ptr< OIC::Service::CloudPropProvisioningStatus > cloudPropProvisioningStatus)
+
+ {
+ onCloudPropProvisioningStatusReceived->onCloudPropProvisioningStatus(cloudPropProvisioningStatus);
+ };
+
+ try
+ {
+ m_sharedResource->provisionCloudProperties(cloudProp, cloudPropProvStatusCallback);
+ }
+ catch (ESBadRequestException exception)
+ {
+ ES_LOGE("JNI startProvisioning :: Exception occured");
+ //throw the exception to java
+ throwESException(env, exception.what());
+ }
+}
+
+//JNI
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeGetStatus
+(JNIEnv *env, jobject jClass, jobject jListener)
+{
+ ES_LOGD("nativeGetStatus Enter");
+
+ JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
+ remoteEnrollee->getStatus(env, jListener);
+
+ ES_LOGD("nativeGetStatus Exit");
+}
+
+//JNI
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeGetConfiguration
+(JNIEnv *env, jobject jClass, jobject jListener)
+{
+ ES_LOGD("nativegetConfiguration Enter");
+
+ JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
+ remoteEnrollee->getConfiguration(env, jListener);
+
+ ES_LOGD("nativegetConfiguration Exit");
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeProvisionSecurity
+(JNIEnv *env, jobject jClass, jobject jListener)
+{
+ ES_LOGD("nativeStartSecurityProvision Enter");
+
+ JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
+ remoteEnrollee->provisionSecurity(env, jListener);
+
+ ES_LOGD("nativeStartSecurityProvision Exit");
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeProvisionDeviceProperties
+(JNIEnv *env, jobject jClass, jobject jRepresentation, jobject jListener)
+{
+ ES_LOGD("nativeProvisionDeviceProperties Enter");
+
+ JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
+ remoteEnrollee->provisionDeviceProperties(env, jRepresentation, jListener);
+
+ ES_LOGD("nativeProvisionDeviceProperties Exit");
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeProvisionCloudProperties
+(JNIEnv *env, jobject jClass, jobject jRepresentation, jstring jCloudID, jobject jListener)
+{
+ ES_LOGD("nativeprovisionCloudProperties Enter");
+
+ JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
+ remoteEnrollee->provisionCloudProperties(env, jRepresentation, jCloudID, jListener);
+
+ ES_LOGD("nativeprovisionCloudProperties Exit");
+}
#ifndef __JNI_ES_REMOTEENROLLEE_H
#define __JNI_ES_REMOTEENROLLEE_H
-#include "RemoteEnrollee.h"
#include "ESRichCommon.h"
#include "ESException.h"
+#include "RemoteEnrollee.h"
#include "JniJvm.h"
#include "JniEsUtils.h"
-#include "JniProvisioningStatusListener.h"
+#include "JniGetEnrolleeStatusListener.h"
+#include "JniGetConfigurationStatusListener.h"
+#include "JniSecurityStatusListener.h"
+#include "JniDevicePropProvisioningStatusListener.h"
+#include "JniCloudPropProvisioningStatusListener.h"
#include "JniEsListenerManager.h"
using namespace OIC::Service;
~JniRemoteEnrollee();
// ***** JNI APIs internally call the APIs of this class ***** //
+ void getStatus(JNIEnv *env, jobject jListener);
+ void getConfiguration(JNIEnv *env, jobject jListener);
+ void provisionSecurity(JNIEnv *env, jobject jListener);
+ void provisionDeviceProperties(JNIEnv *env, jobject jRepresentation, jobject jListener);
+ void provisionCloudProperties(JNIEnv *env, jobject jRepresentation, jstring jCloudID, jobject jListener);
- void startProvisioning(JNIEnv *env);
- void stopProvisioning(JNIEnv *env);
- void registerProvisioningHandler(JNIEnv *env, jobject jListener);
+ static JniRemoteEnrollee *getJniRemoteEnrollee(JNIEnv *env, jobject thiz);
- JniProvisioningStatusListener *addProvisioningStatusListener(JNIEnv *env, jobject jListener);
- void removeProvisioningStatusListener(JNIEnv *env, jobject jListener);
+ template <class T>
+ T *addStatusListener(JNIEnv *env, jobject jListener)
+ {
+ return JniEsListenerManager<T>().addListener(env, jListener, this);
+ };
- static JniRemoteEnrollee *getJniRemoteEnrollee(JNIEnv *env, jobject thiz);
+ template <class T>
+ void removeStatusListener(JNIEnv *env, jobject jListener)
+ {
+ JniEsListenerManager<T>().removeListener(env, jListener);
+ };
private:
- JniEsListenerManager<JniProvisioningStatusListener> m_provisioingStatus;
std::shared_ptr<RemoteEnrollee> m_sharedResource;
};
-
#ifdef __cplusplus
extern "C" {
#endif
/**
- * API for starting the provisioning process.
+ * API for starting the Request Enrollee status process.
*/
JNIEXPORT void JNICALL
-Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeStartProvision
-(JNIEnv *env, jobject jClass);
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeGetStatus
+(JNIEnv *env, jobject jClass, jobject jListener);
/**
- * API for stopping the provisioning process.
+ * API for starting the Request EnrolleeConf process.
*/
JNIEXPORT void JNICALL
-Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeStopProvision
-(JNIEnv *env, jobject jClass);
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeGetConfiguration
+(JNIEnv *env, jobject jClass, jobject jListener);
/**
- * API for setting the lisener for recieiving provisioning status.
- *
- * @param provisiongListener - Provisioning listener [callback from native layer will be passing to this listener]
+ * API for starting the Sequrity provisioning process.
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeProvisionSecurity
+(JNIEnv *env, jobject jClass, jobject jListener);
+
+/**
+ * API for starting the Data provisioning process.
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeProvisionDeviceProperties
+(JNIEnv *env, jobject jClass, jobject jRepresentation, jobject jListener);
+
+/**
+ * API for starting the cloud provisioning process.
*/
JNIEXPORT void JNICALL
-Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeRegisterProvisioningHandler
-(JNIEnv *env, jobject jClass, jobject provisiongListener);
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeProvisionCloudProperties
+(JNIEnv *env, jobject jClass, jobject jRepresentation, jstring jCloudID, jobject jListener);
#ifdef __cplusplus
}
*
******************************************************************/
-#include "JniProvisioningStatusListener.h"
+#include "JniSecurityStatusListener.h"
#include "JniRemoteEnrollee.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
using namespace OIC::Service;
-JniProvisioningStatusListener::JniProvisioningStatusListener(JNIEnv *env, jobject jListener,
+JniSecurityStatusListener::JniSecurityStatusListener(JNIEnv *env, jobject jListener,
JniRemoteEnrollee *owner)
: m_ownerResource(owner)
{
m_jwListener = env->NewWeakGlobalRef(jListener);
}
-JniProvisioningStatusListener::~JniProvisioningStatusListener()
+JniSecurityStatusListener::~JniSecurityStatusListener()
{
- LOGI("~JniProvisioningStatusListener()");
+ ES_LOGI("~JniSecurityStatusListener()");
if (m_jwListener)
{
jint ret;
if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
}
}
-
-void JniProvisioningStatusListener::provisionStatusCallback (std::shared_ptr<EasySetupStatus>
- easySetupStatus)
+void JniSecurityStatusListener::secProvisionStatusCallback(
+ std::shared_ptr<SecProvisioningStatus> secProvisioningStatus)
{
- LOGI("JniProvisioningStatusListener::provisioiningStatusCallback enter");
+ ES_LOGI("JniSecurityStatusListener::secProvisionStatusCallback enter");
jint ret;
JNIEnv *env = GetESJNIEnv(ret);
return;
}
- jmethodID midL = env->GetMethodID(clsL, "onStatusRecieved",
- "(I)V");
+ jmethodID midL = env->GetMethodID(clsL, "onProgress",
+ "(Lorg/iotivity/service/easysetup/mediator/"
+ "SecurityProvisioningStatus;"
+ ")V");
+
if (!midL)
{
checkExAndRemoveListener(env);
return;
}
- EasySetupState nativeProvisioningState = easySetupStatus->getEasySetupState();
- int provisionState = convertNativeProvisionStateToInt(nativeProvisioningState);
- env->CallVoidMethod(jListener, midL, provisionState);
+ ESResult esResult = secProvisioningStatus->getESResult();
+
+ //create the java object
+ jobject jSecurityProvisioningStatus = NULL;
+ jSecurityProvisioningStatus = env->NewObject(g_cls_SecurityProvisioningStatus,
+ g_mid_SecurityProvisioningStatus_ctor,
+ (jint)esResult,
+ env->NewStringUTF(secProvisioningStatus->getDeviceUUID().c_str()));
+
+ ES_LOGE("JniSecurityStatusListener::onSecurityProvisioningStatus UUID : %s",
+ secProvisioningStatus->getDeviceUUID().c_str());
+
+ if (!jSecurityProvisioningStatus)
+ {
+ ES_LOGE("JniSecurityStatusListener::onSecurityProvisioningStatus Unable to create the java object");
+ return ;
+ }
+
+ env->CallVoidMethod(jListener, midL, jSecurityProvisioningStatus);
+
if (env->ExceptionCheck())
{
- LOGE("Java exception is thrown");
+ ES_LOGE("Java exception is thrown");
checkExAndRemoveListener(env);
if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
return;
if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
}
-void JniProvisioningStatusListener::checkExAndRemoveListener(JNIEnv *env)
+void JniSecurityStatusListener::checkExAndRemoveListener(JNIEnv *env)
{
if (env->ExceptionCheck())
{
jthrowable ex = env->ExceptionOccurred();
env->ExceptionClear();
- m_ownerResource->removeProvisioningStatusListener(env, m_jwListener);
+ m_ownerResource->removeStatusListener<JniSecurityStatusListener>(env, m_jwListener);
env->Throw((jthrowable)ex);
}
else
{
- m_ownerResource->removeProvisioningStatusListener(env, m_jwListener);
+ m_ownerResource->removeStatusListener<JniSecurityStatusListener>(env, m_jwListener);
}
}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2016 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 __JNI_ES_SECURITY_PROVISIONING_STATUS_LISTENER_H_
+#define __JNI_ES_SECURITY_PROVISIONING_STATUS_LISTENER_H_
+
+#include <jni.h>
+
+#include "RemoteEnrollee.h"
+#include "ESRichCommon.h"
+
+#include "JniJvm.h"
+
+class JniRemoteEnrollee;
+
+using namespace OIC::Service;
+
+class JniSecurityStatusListener
+{
+ public:
+ /**
+ * @brief constructor
+ */
+ JniSecurityStatusListener(JNIEnv *env, jobject jListener, JniRemoteEnrollee *resource);
+
+ /**
+ * @brief destructor
+ */
+ ~JniSecurityStatusListener();
+
+ /**
+ * @brief callback function that will be passed to Native layer
+ */
+ void secProvisionStatusCallback (std::shared_ptr<SecProvisioningStatus> secProvisioningStatus);
+
+ private:
+ jweak m_jwListener;
+ JniRemoteEnrollee *m_ownerResource;
+ void checkExAndRemoveListener(JNIEnv *env);
+};
+
+#endif //__JNI_ES_SECURITY_PROVISIONING_STATUS_LISTENER_H_
--- /dev/null
+#//******************************************************************
+#//
+#// Copyright 2016 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.
+#//
+#//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+import os
+import platform
+Import('env')
+
+android_home = env.get('ANDROID_HOME')
+
+ANDROID_TARGET_ARCH = env.get('TARGET_ARCH')
+if env.get('RELEASE'):
+ ANDROID_RELEASE="release"
+else:
+ ANDROID_RELEASE="debug"
+
+os.environ['ANDROID_HOME'] = env.get('ANDROID_HOME')
+os.environ['ANDROID_NDK_HOME'] = env.get('ANDROID_NDK')
+
+if not os.path.exists(android_home + '/platforms/android-21') or not os.path.exists(android_home + '/build-tools/20.0.0'):
+ print '''
+***************************************** Info ********************************
+* Either 'Android API 21' is not installed or 'Android SDK Build Tools *
+* 20.0.0' is not installed. The Android SDK Manager will now open. Please *
+* be sure to deselect all options, then select the following 2 packages: *
+* 1. Under "Tools" select "Android SDK Build-tools" Revision 20. *
+* 2. Under "Android 5.0.1 (API 21)" select "SDK Platform" *
+* 3. Continue by selecting "Install 2 Packages" *
+* *
+* NOTE: If you have an http proxy, please press ctrl+c now and edit/create *
+* the following file in your $HOME directory as follows: *
+* *
+* Edit/Create file: "$HOME/.android/androidtool.cfg" *
+* *
+* http.proxyPort=<YOUR_PORT_NUMBER> *
+* sdkman.monitor.density=108 *
+* http.proxyHost=<YOUR_HTTP_PROXY_ADDRESS> *
+* sdkman.show.update.only=true *
+* sdkman.ask.adb.restart=false *
+* sdkman.force.http=true *
+* sdkman.show.updateonly=true *
+* *
+*******************************************************************************
+
+...Opening Android SDK Manager now. Once you are finished, the build will continue.
+'''
+ os.system(android_home + '/tools/android')
+
+#SConscript("../../../../../../android/android_api/SConscript")
+
+def ensure_libs(target, source, env):
+ return target, [source, env.get('BUILD_DIR') + 'liboc.so', env.get('BUILD_DIR') + 'liboc_logger.so']
+
+jdk_env = Environment(ENV=os.environ)
+jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') +
+ ' build -bservice/easy-setup/mediator/richsdk/android/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s --stacktrace' %(ANDROID_TARGET_ARCH, ANDROID_RELEASE),
+ emitter = ensure_libs)
+jdk_env['BUILD_DIR'] = env.get('BUILD_DIR')
+cmdBuildEasysetup=jdk_env.Gradle(target="EasySetupCore/objs",
+ source="EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EasySetup.java")
+
+Depends(cmdBuildEasysetup, env.get('baseAAR'))
+
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<module 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" />
+ </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>
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2016 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.
+ *
+ ******************************************************************/
+// Top-level build file where you can add configuration options common to all sub-projects/modules.
+
+buildscript {
+ repositories {
+ jcenter()
+ }
+ dependencies {
+ classpath 'com.android.tools.build:gradle:1.3.0'
+
+ // NOTE: Do not place your application dependencies here; they belong
+ // in the individual module build.gradle files
+ }
+}
+
+allprojects {
+ repositories {
+ jcenter {
+ url "http://jcenter.bintray.com/"
+ }
+ flatDir {
+ dirs "../../../../../../android/android_api/base/build/outputs/aar/"
+ }
+ }
+}
--- /dev/null
+#
+# //******************************************************************
+# //
+# // Copyright 2015 Intel Corporation.
+# //
+# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+# //
+# // Licensed under the Apache License, Version 2.0 (the "License");
+# // you may not use this file except in compliance with the License.
+# // You may obtain a copy of the License at
+# //
+# // http://www.apache.org/licenses/LICENSE-2.0
+# //
+# // Unless required by applicable law or agreed to in writing, software
+# // distributed under the License is distributed on an "AS IS" BASIS,
+# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# // See the License for the specific language governing permissions and
+# // limitations under the License.
+# //
+# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+
+# Project-wide Gradle settings.
+
+# IDE (e.g. Android Studio) users:
+# Gradle settings configured through the IDE *will override*
+# any settings specified in this file.
+
+# For more details on how to configure your build environment visit
+# http://www.gradle.org/docs/current/userguide/build_environment.html
+
+# Specifies the JVM arguments used for the daemon process.
+# The setting is particularly useful for tweaking memory settings.
+# Default value: -Xmx10248m -XX:MaxPermSize=256m
+# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
+
+# When configured, Gradle will run in incubating parallel mode.
+# This option should only be used with decoupled projects. More details, visit
+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
+# org.gradle.parallel=true
--- /dev/null
+#!/usr/bin/env bash
+
+##############################################################################
+##
+## Gradle start up script for UN*X
+##
+##############################################################################
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn ( ) {
+ echo "$*"
+}
+
+die ( ) {
+ echo
+ echo "$*"
+ echo
+ exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+case "`uname`" in
+ CYGWIN* )
+ cygwin=true
+ ;;
+ Darwin* )
+ darwin=true
+ ;;
+ MINGW* )
+ msys=true
+ ;;
+esac
+
+# For Cygwin, ensure paths are in UNIX format before anything is touched.
+if $cygwin ; then
+ [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
+fi
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >&-
+APP_HOME="`pwd -P`"
+cd "$SAVED" >&-
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD="java"
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
+ MAX_FD_LIMIT=`ulimit -H -n`
+ if [ $? -eq 0 ] ; then
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+ MAX_FD="$MAX_FD_LIMIT"
+ fi
+ ulimit -n $MAX_FD
+ if [ $? -ne 0 ] ; then
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
+ fi
+ else
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+ fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+
+ # We build the pattern for arguments to be converted via cygpath
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+ SEP=""
+ for dir in $ROOTDIRSRAW ; do
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
+ SEP="|"
+ done
+ OURCYGPATTERN="(^($ROOTDIRS))"
+ # Add a user-defined pattern to the cygpath arguments
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+ fi
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ i=0
+ for arg in "$@" ; do
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
+
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+ else
+ eval `echo args$i`="\"$arg\""
+ fi
+ i=$((i+1))
+ done
+ case $i in
+ (0) set -- ;;
+ (1) set -- "$args0" ;;
+ (2) set -- "$args0" "$args1" ;;
+ (3) set -- "$args0" "$args1" "$args2" ;;
+ (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+ (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+ (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+ (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+ (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+ (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+ esac
+fi
+
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
+function splitJvmOpts() {
+ JVM_OPTS=("$@")
+}
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
+
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
--- /dev/null
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto init
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto init
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:init
+@rem Get command-line arguments, handling Windowz variants
+
+if not "%OS%" == "Windows_NT" goto win9xME_args
+if "%@eval[2+2]" == "4" goto 4NT_args
+
+:win9xME_args
+@rem Slurp the command line arguments.
+set CMD_LINE_ARGS=
+set _SKIP=2
+
+:win9xME_args_slurp
+if "x%~1" == "x" goto execute
+
+set CMD_LINE_ARGS=%*
+goto execute
+
+:4NT_args
+@rem Get arguments from the 4NT Shell from JP Software
+set CMD_LINE_ARGS=%$
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
+++ /dev/null
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../../../out/android/$(TARGET_ARCH_ABI)/debug
-LOCAL_MODULE := android-oc
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboc.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)/libESMediatorRich.so
-include $(PREBUILT_SHARED_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))
-
-LOCAL_C_INCLUDES := $(LOCAL_PATH) \
- $(LOCAL_PATH)/../../inc \
- $(LOCAL_PATH)/../../src \
- $(LOCAL_PATH)/../../../../inc \
- $(LOCAL_PATH)/../../../../../../resource/csdk/logger/include \
- $(LOCAL_PATH)/../../../../../../resource/csdk/connectivity/common/inc \
- $(LOCAL_PATH)/../../../../../../resource/c_common/oic_string/include \
- $(LOCAL_PATH)/../../../../../../resource/include \
- $(LOCAL_PATH)/../../../../../../resource/c_common \
- $(LOCAL_PATH)/../../../../../../resource/oc_logger/include \
- $(LOCAL_PATH)/../../../../../../resource/c_common/oic_malloc/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 \
-
-LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/*.cpp))
-LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/*.h))
-
-LOCAL_LDLIBS := -llog
-#LOCAL_SHARED_LIBRARIES += android-connectivity_abstraction
-LOCAL_SHARED_LIBRARIES += android-oc
-LOCAL_SHARED_LIBRARIES += android-easysetup
-
-include $(BUILD_SHARED_LIBRARY)
+++ /dev/null
-APP_STL := gnustl_shared
-APP_PLATFORM = android-21
-NDK_TOOLCHAIN_VERSION := 4.8
-
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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 "JniEsUtils.h"
-
-void throwESException(JNIEnv *env, std::string reason)
-{
- jobject ex = env->NewObject(g_cls_ESException, g_mid_ESException_ctor,
- env->NewStringUTF(reason.c_str()));
- if (!ex)
- {
- LOGI("throwException : jobject is NULL");
- }
- env->Throw((jthrowable)ex);
-}
-
-OCConnectivityType getOCConnectivityTypeFromInt(int connectivityType)
-{
- switch (connectivityType)
- {
- case CT_DEFAULT:
- return CT_DEFAULT;
- case CT_ADAPTER_IP:
- return CT_ADAPTER_IP;
-
- //May be need to add more types, if easy setup service support more transport.
- }
- return CT_DEFAULT;
-}
-
-int convertNativeProvisionStateToInt(EasySetupState nativeState)
-{
- switch (nativeState)
- {
- case EasySetupState::DEVICE_PROVISIONED:
- return 0;
- case EasySetupState::DEVICE_NOT_PROVISIONED:
- return 1;
- case EasySetupState::DEVICE_OWNED:
- return 2;
- case EasySetupState::DEVICE_NOT_OWNED:
- return 3;
- }
- return -1;
-}
\ No newline at end of file
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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 "JniJvm.h"
-
-JavaVM *g_jvm = NULL;
-
-jclass g_cls_RemoteEnrollee = NULL;
-jclass g_cls_ESException = NULL;
-
-jmethodID g_mid_RemoteEnrollee_ctor = NULL;
-jmethodID g_mid_ESException_ctor = NULL;
-
-// JNI OnLoad
-JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
-{
- LOGI("JNI_OnLoad");
- JNIEnv *env;
- g_jvm = vm;
-
- if (g_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION) != JNI_OK)
- {
- LOGE("Failed to get the environment using GetEnv()");
- return JNI_ERR;
- }
-
- jclass clazz = nullptr;
-
- //Remote Enrollee
- clazz = env->FindClass("org/iotivity/service/easysetup/mediator/RemoteEnrollee");
- if (!clazz) return JNI_ERR;
- g_cls_RemoteEnrollee = (jclass)env->NewGlobalRef(clazz);
- env->DeleteLocalRef(clazz);
-
- g_mid_RemoteEnrollee_ctor = env->GetMethodID(g_cls_RemoteEnrollee, "<init>",
- "(J)V");
- if (!g_mid_RemoteEnrollee_ctor) return JNI_ERR;
-
- //ESException
- clazz = env->FindClass("org/iotivity/service/easysetup/mediator/ESException");
- if (!clazz) return JNI_ERR;
- g_cls_ESException = (jclass)env->NewGlobalRef(clazz);
- env->DeleteLocalRef(clazz);
-
- g_mid_ESException_ctor = env->GetMethodID(g_cls_ESException, "<init>", "(Ljava/lang/String;)V");
- if (!g_mid_ESException_ctor) return JNI_ERR;
-
- return JNI_CURRENT_VERSION;
-}
-
-//JNI OnUnload
-JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
-{
- LOGI("JNI_OnUnload");
- JNIEnv *env;
-
- if (g_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION) != JNI_OK)
- {
- LOGE("Failed to get the environment using GetEnv()");
- return;
- }
- env->DeleteGlobalRef(g_cls_RemoteEnrollee);
- env->DeleteGlobalRef(g_cls_ESException);
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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 "JniRemoteEnrollee.h"
-
-using namespace OIC::Service;
-
-JniRemoteEnrollee::JniRemoteEnrollee(std::shared_ptr<RemoteEnrollee> remoteEnrollee)
- : m_sharedResource(remoteEnrollee) {}
-
-JniRemoteEnrollee::~JniRemoteEnrollee()
-{
- LOGD("JniRemoteEnrollee::~JniRemoteEnrollee()");
- m_sharedResource = NULL;
-
- jint envRet;
- JNIEnv *env = GetESJNIEnv(envRet);
- if (NULL == env) return;
-
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
-
-}
-
-JniRemoteEnrollee *JniRemoteEnrollee::getJniRemoteEnrollee(JNIEnv *env, jobject thiz)
-{
- JniRemoteEnrollee *remoteEnrollee = ESGetHandle<JniRemoteEnrollee>(env, thiz);
- if (env->ExceptionCheck())
- {
- LOGE("getJniRemoteEnrollee :: Failed to get native handle from RemoteEnrollee object");
- }
- if (!remoteEnrollee)
- {
- LOGE("getJniRemoteEnrollee :: no resource");
- }
- return remoteEnrollee;
-}
-
-void JniRemoteEnrollee::startProvisioning(JNIEnv *env)
-{
- try
- {
- m_sharedResource->startProvisioning();
- }
- catch (ESBadRequestException exception)
- {
- LOGE("JNI startProvisioning :: Exception occured");
- //throw the exception to java
- throwESException( env, exception.what());
- }
-}
-void JniRemoteEnrollee::stopProvisioning(JNIEnv *env)
-{
- try
- {
- m_sharedResource->stopProvisioning();
- }
- catch (ESBadRequestException exception)
- {
- LOGE("JNI stopProvisioning :: Exception occured");
- //throw the exception to java
- throwESException( env, exception.what());
- }
-}
-
-void JniRemoteEnrollee::registerProvisioningHandler(JNIEnv *env, jobject jListener)
-{
- JniProvisioningStatusListener *onProvisioningStatusReceived = addProvisioningStatusListener(env,
- jListener);
-
- RemoteEnrollee::EasySetupStatusCB provisionStatusCallback = [onProvisioningStatusReceived]
- (std::shared_ptr< OIC::Service::EasySetupStatus > easySetupStatus)
-
- {
- onProvisioningStatusReceived->provisionStatusCallback(easySetupStatus);
- };
-
- try
- {
- m_sharedResource->registerEasySetupStatusHandler(provisionStatusCallback);
- }
- catch (ESException exception)
- {
- LOGE("JNI stopProvisioning :: Exception occured");
- //throw the exception to java
- throwESException( env, exception.what());
- }
-
-}
-
-JniProvisioningStatusListener *JniRemoteEnrollee::addProvisioningStatusListener(JNIEnv *env,
- jobject jListener)
-{
- return this->m_provisioingStatus.addListener(env, jListener, this);
-}
-
-void JniRemoteEnrollee::removeProvisioningStatusListener(JNIEnv *env, jobject jListener)
-{
- this->m_provisioingStatus.removeListener(env, jListener);
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeStartProvision
-(JNIEnv *env, jobject jClass)
-{
- LOGD("nativeStartProvision Enter");
-
- JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
- remoteEnrollee->startProvisioning(env);
-
- LOGD("nativeStartProvision Exit");
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeStopProvision
-(JNIEnv *env, jobject jClass)
-{
-
- LOGD("nativeStopProvision Enter");
-
- JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
- remoteEnrollee->stopProvisioning(env);
-
- LOGD("nativeStopProvision Exit");
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeRegisterProvisioningHandler
-(JNIEnv *env, jobject jClass, jobject provisiongListener)
-{
- LOGD("nativeRegisterProvisioningHandler Enter");
-
- if (!provisiongListener)
- {
- LOGE("nativeRegisterProvisioningHandler : listener is NULL");
- return;
- }
- JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
- remoteEnrollee->registerProvisioningHandler(env, provisiongListener);
-
- LOGD("nativeRegisterProvisioningHandler Exit");
-}
-
//******************************************************************
//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
+// Copyright 2016 Samsung Electronics All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.service.easysetup.mediator;
-
-
-public class Utility {
-
- public static void toNotify(Object toLock) {
- synchronized (toLock) {
- toLock.notify();
- }
- }
-
- public static void toWait(Object toLock) {
- synchronized (toLock) {
- try {
- toLock.wait(45000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
-}
+include ':EasySetupCore'
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 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 CLOUD_RESOURCE_H_
+#define CLOUD_RESOURCE_H_
+
+#include <mutex>
+#include <memory>
+
+#include "ESRichCommon.h"
+
+#include "OCApi.h"
+
+using namespace OC;
+
+namespace OIC
+{
+ namespace Service
+ {
+ class OCResource;
+ /**
+ * This class contains the resource discovery methods.
+ *
+ * @see CloudResource
+ */
+ class CloudResource
+ {
+ public:
+ CloudResource(std::shared_ptr< OC::OCResource > resource);
+ ~CloudResource() = default;
+
+ void registerCloudPropProvisioningStatusCallback (CloudPropProvStatusCb callback);
+ void provisionEnrollee(const CloudProp& CloudProp);
+
+ private:
+ void onCloudProvResponse(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+ const int eCode);
+
+ private:
+ std::shared_ptr< OC::OCResource > m_ocResource;
+ CloudPropProvStatusCb m_cloudPropProvStatusCb;
+ };
+ }
+}
+#endif
#include <string>
#ifndef WITH_ARDUINO
#include <memory>
+#include <vector>
#endif
+#include "OCPlatform.h"
#include "ocstack.h"
#include "octypes.h"
-using namespace std;
+#include "escommon.h"
-// Defines
-#define OIC_STRING_MAX_VALUE 100
-#define IPV4_ADDR_SIZE 16
-#define IP_PORT 55555
-#define NET_WIFI_SSID_SIZE 100
-#define NET_WIFI_PWD_SIZE 100
-
-/**
- * @brief Mac address length for BT port
- */
-#define NET_MACADDR_SIZE 18
-
-/**
- * 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"
-
-/**
- * Easysetup defined resoruce types and uris.
- */
-#define OC_RSRVD_ES_PROV_RES_TYPE "oic.r.prov"
-#define OC_RSRVD_ES_URI_PROV "/oic/prov"
-#define OC_RSRVD_ES_URI_NET "/oic/net"
-
-/**
- * @brief Defines for Provisioning status accepted values
- */
-#define ES_PS_NEED_PROVISIONING 1
-#define ES_PS_PROVISIONING_COMPLETED 2
-#define ES_PS_TRIGGER_INIT_VALUE 0
-#define ES_PS_TRIGGER_CONNECTION 1
+using namespace OC;
+using namespace std;
#ifndef WITH_ARDUINO
namespace OIC
{
namespace Service
{
-
/**
- * Device Roles defined for each device type used in easy setup
- */
- typedef enum
+ * @brief Properties of provisioning resource. It includes a provisioning status and last
+ * error code.
+ */
+ class EnrolleeStatus
{
- ENROLLEE,
- MEDIATOR,
- ENROLLER,
- } DeviceRole;
+ public:
- /**
- * On-boarding connection to create Adhoc network.
- */
- typedef enum
- {
- SOFTAP,
- BLE,
- } OBConnection;
+ /**
+ * Constructor
+ */
+ EnrolleeStatus(const OCRepresentation& rep)
+ {
+ m_rep = rep;
+ }
- 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;
+ EnrolleeStatus(const EnrolleeStatus& enrolleeStatus) :
+ m_rep(enrolleeStatus.getRepresentation())
+ {
+ }
- typedef enum
+ EnrolleeStatus(const EnrolleeStatus&& enrolleeStatus) :
+ m_rep(std::move(enrolleeStatus.getRepresentation()))
+ {
+ }
+
+ /**
+ * Get a provisioning status property of Enrollee.
+ *
+ * @return a provisioning status property of Enrollee
+ */
+ ProvStatus getProvStatus()
+ {
+ if(m_rep.hasAttribute(OC_RSRVD_ES_PROVSTATUS))
+ {
+ return static_cast<ProvStatus>(
+ m_rep.getValue<int>(OC_RSRVD_ES_PROVSTATUS));
+ }
+ return ES_STATE_INIT;
+ }
+
+ /**
+ * Get a last error code property of Enrollee.
+ *
+ * @return a last error code property of Enrollee.
+ */
+ ESErrorCode getLastErrCode()
+ {
+ if(m_rep.hasAttribute(OC_RSRVD_ES_LAST_ERRORCODE))
+ {
+ return static_cast<ESErrorCode>(
+ m_rep.getValue<int>(OC_RSRVD_ES_LAST_ERRORCODE));
+ }
+ return ES_ERRCODE_NO_ERROR;
+ }
+
+ /**
+ * Get OCRepresentation object
+ *
+ * @return OCRepresentation object
+ */
+ const OCRepresentation& getRepresentation() const
+ {
+ return m_rep;
+ }
+ protected:
+ OCRepresentation m_rep;
+ };
+
+ /**
+ * @brief Data class stored for Cloud server property provisioning
+ */
+ class CloudProp
{
+ public:
+
/**
- * Default state of the device
+ * Constructor
*/
- ES_INIT_STATE,
+ CloudProp()
+ {
+ };
/**
- * Device will move to this state once the on boarding begins
+ * Constructor with OCRepresentation object. This is used for JNI communication.
*/
- ES_ON_BOARDING_STATE,
+ CloudProp(const OCRepresentation &rep)
+ {
+ m_rep = rep;
+ m_cloudID = "";
+ }
/**
- * Device will move to this state after successful on-boarding of the device
+ * Set CloudServer resource properties to be delivered to Enrollee
+ *
+ * @param authCode Auth code issued by OAuth2.0-compatible account server
+ * @param authProvider Auth provider ID
+ * @param ciServer Cloud interface server URL which an Enrollee is going to registered
*/
- ES_ON_BOARDED_STATE,
+ void setCloudProp(string authCode, string authProvider, string ciServer)
+ {
+ m_rep.setValue(OC_RSRVD_ES_AUTHCODE, authCode);
+ m_rep.setValue(OC_RSRVD_ES_AUTHPROVIDER, authProvider);
+ m_rep.setValue(OC_RSRVD_ES_CISERVER, ciServer);
+ }
/**
- * Device will move to this state once the on boarding is done
+ * Set CloudServer's UUID
+ *
+ * @param cloudID Cloud Interface server's UUID
*/
- ES_PROVISIONING_STATE,
+ void setCloudID(string cloudID)
+ {
+ m_cloudID = cloudID;
+ }
/**
- * Easy setup process is successful.
+ * Get an auth code to be delivered.
+ *
+ * @return an auth code to be delivered.
*/
- ES_PROVISIONED_STATE,
+ std::string getAuthCode() const
+ {
+ if(m_rep.hasAttribute(OC_RSRVD_ES_AUTHCODE))
+ {
+ return m_rep.getValue<std::string>(OC_RSRVD_ES_AUTHCODE);
+ }
+ return std::string("");
+ }
/**
- * 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
+ * Get an auth provider which issued an auth code
+ *
+ * @return an auth provider which issued an auth code
*/
- ES_OWNERSHIP_TRANSFERRING_STATE,
+ std::string getAuthProvider() const
+ {
+ if(m_rep.hasAttribute(OC_RSRVD_ES_AUTHPROVIDER))
+ {
+ return m_rep.getValue<std::string>(OC_RSRVD_ES_AUTHPROVIDER);
+ }
+ return std::string("");
+ }
/**
- * This state is arbitrary one, any time device can come into this state
- * Device will move to this state if the ownership transfer is completed
+ * Get a CI server to be delivered
+ *
+ * @return a CI server to be delivered
*/
- ES_OWNERSHIP_TRANSFERRED_STATE,
+ std::string getCiServer() const
+ {
+ if(m_rep.hasAttribute(OC_RSRVD_ES_CISERVER))
+ {
+ return m_rep.getValue<std::string>(OC_RSRVD_ES_CISERVER);
+ }
+ return std::string("");
+ }
/**
- * 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
+ * Get a CI server's Uuid to be delivered
+ *
+ * @return a CI server's Uuid to be delivered
*/
- ES_FACTORY_RESET_STATE,
+ std::string getCloudID() const
+ {
+ return m_cloudID;
+ }
/**
- * Enrollee moves to this state after connecting to target network
+ * Get OCRepresentation object
+ *
+ * @return OCRepresentation object
*/
- ES_ON_BOARDED_TARGET_NETWORK_STATE,
- }EnrolleeState;
+ const OCRepresentation &toOCRepresentation() const
+ {
+ return m_rep;
+ }
+ protected:
+ OCRepresentation m_rep;
+ std::string m_cloudID;
+ };
/**
- * Provisioning Device Status
+ * @brief Data class stored for Device property provisioning which includes a WiFi
+ * and device configuration provisioning
*/
- typedef struct
+ class DeviceProp
{
- // Address of remote server
- OCDevAddr * addr;
- // Indicates adaptor type on which the response was received
- OCConnectivityType connType;
- } EasySetupDeviceInfo;
+ public:
- /**
- * Provosioning Status
- */
- typedef enum
- {
- DEVICE_PROVISIONED = 0,
- DEVICE_NOT_PROVISIONED,
- DEVICE_OWNED,
- DEVICE_NOT_OWNED
- } EasySetupState, ProvStatus;
+ /**
+ * Constructor
+ */
+ DeviceProp() {}
- /**
- * Response from queries to remote servers.
- */
- typedef struct
- {
- // EasySetup Status
- EasySetupState provStatus;
- // EasySetup Device Info
- EasySetupDeviceInfo provDeviceInfo;
- } EasySetupInfo, ProvisioningInfo;
+ /**
+ * Constructor with OCRepresentation object. This is used for JNI communication.
+ */
+ DeviceProp(const OCRepresentation &rep)
+ {
+ m_rep = rep;
+ }
- /**
- * @brief Network information of the Enroller
- */
- typedef union
- {
/**
- * @brief BT Mac Information
+ * Set WiFi resource properties to be delivered to Enrollee
+ *
+ * @param ssid Ssid of the Enroller
+ * @param pwd Pwd of the Enrolle
+ * @param authtype Auth type of the Enroller
+ * @param enctype Encryption type of the Enroller
+ *
+ * @see WIFI_AUTHTYPE
+ * @see WIFI_ENCTYPE
*/
- struct
+ void setWiFiProp(string ssid, string pwd, WIFI_AUTHTYPE authtype, WIFI_ENCTYPE enctype)
{
- char btMacAddress[NET_MACADDR_SIZE]; /**< BT mac address **/
- } BT;
+ m_rep.setValue(OC_RSRVD_ES_SSID, ssid);
+ m_rep.setValue(OC_RSRVD_ES_CRED, pwd);
+ m_rep.setValue(OC_RSRVD_ES_AUTHTYPE, authtype);
+ m_rep.setValue(OC_RSRVD_ES_ENCTYPE, enctype);
+ }
/**
- * @brief LE MAC Information
+ * Set DevConf resource properties to be delivered to Enrollee
+ *
+ * @param language IETF language tag using ISO 639X
+ * @param country ISO Country Code (ISO 3166-1 Alpha-2)
*/
- struct
+ void setDevConfProp(string language, string country)
{
- char leMacAddress[NET_MACADDR_SIZE]; /**< BLE mac address **/
- } LE;
+ m_rep.setValue(OC_RSRVD_ES_LANGUAGE, language);
+ m_rep.setValue(OC_RSRVD_ES_COUNTRY, country);
+ }
/**
- * @brief IP Information
+ * Get a SSID of Enroller
+ *
+ * @return a SSID of enroller
*/
- struct
+ std::string getSsid() const
{
- char ssid[NET_WIFI_SSID_SIZE]; /**< ssid of the Enroller**/
- char pwd[NET_WIFI_PWD_SIZE]; /**< pwd of the Enroller**/
- } WIFI;
- } ProvData;
+ if(m_rep.hasAttribute(OC_RSRVD_ES_SSID))
+ {
+ return m_rep.getValue<std::string>(OC_RSRVD_ES_SSID);
+ }
+ return std::string("");
+ }
- /**
- * @brief Network Information
- */
- typedef struct
- {
- ProvData provData; /**< Enroller Network Info**/
- OCConnectivityType connType; /**< Connectivity Type**/
- } ProvConfig;
+ /**
+ * Get a password of Enroller
+ *
+ * @return a password of enroller
+ */
+ std::string getPassword() const
+ {
+ if(m_rep.hasAttribute(OC_RSRVD_ES_CRED))
+ {
+ return m_rep.getValue<std::string>(OC_RSRVD_ES_CRED);
+ }
+ return std::string("");
+ }
- /**
- * Client applications implement this callback to consume responses received from Servers.
- */
- typedef void (*OCProvisioningStatusCB)(EasySetupInfo *easySetupInfo);
+ /**
+ * Get an auth type of Enroller
+ *
+ * @return an auth type of enroller
+ *
+ * @see WIFI_AUTHTYPE
+ */
+ WIFI_AUTHTYPE getAuthType() const
+ {
+ if(m_rep.hasAttribute(OC_RSRVD_ES_AUTHTYPE))
+ {
+ return static_cast<WIFI_AUTHTYPE>(m_rep.getValue<int>(OC_RSRVD_ES_AUTHTYPE));
+ }
+ return NONE_AUTH;
+ }
- /**
- * @brief This structure represent configuration information to create wifi onboarding SoftAP or connection.
- */
+ /**
+ * Get an encryption type of Enroller
+ *
+ * @return an encryption type of enroller
+ *
+ * @see WIFI_ENCTYPE
+ */
+ WIFI_ENCTYPE getEncType() const
+ {
+ if(m_rep.hasAttribute(OC_RSRVD_ES_ENCTYPE))
+ {
+ return static_cast<WIFI_ENCTYPE>(m_rep.getValue<int>(OC_RSRVD_ES_ENCTYPE));
+ }
+ return NONE_ENC;
+ }
- // Note : Below structure is not currently used but added for future purpose.
- typedef struct
- {
- char ssid[NET_WIFI_SSID_SIZE]; /**< ssid of the onboarding Adhoc Wifi network**/
- char pwd[NET_WIFI_PWD_SIZE]; /**< pwd of the onboarding Adhoc wifi network**/
- bool isSecured; /**< Secure connection**/
- }WiFiOnboardingConfig;
+ /**
+ * Get a language to be set. A language is expressed in IETF language tag
+ * using ISO 639X.
+ *
+ * @return a language to be set
+ */
+ std::string getLanguage() const
+ {
+ if(m_rep.hasAttribute(OC_RSRVD_ES_LANGUAGE))
+ {
+ return m_rep.getValue<std::string>(OC_RSRVD_ES_LANGUAGE);
+ }
+ return std::string("");
+ }
- /**
- * @brief This structure represent onboarding connection instance.
- */
- typedef struct
- {
- /*Actual use of ipAddress is for unicast discovery, but also used to identify the Enrollee device as of now,
- device identification should be based on DeviceID in next release.*/
- char ipAddress[IPV4_ADDR_SIZE]; /**< IP Address of the Enrollee **/
- bool isSecured; /**< Secure connection**/
- }WiFiOnboadingConnection;
+ /**
+ * Get a country to be set. A country is expressed in ISO Country Code
+ * (ISO 3166-1 Alpha-2)
+ *
+ * @return a country to be set
+ */
+ std::string getCountry() const
+ {
+ if(m_rep.hasAttribute(OC_RSRVD_ES_COUNTRY))
+ {
+ return m_rep.getValue<std::string>(OC_RSRVD_ES_COUNTRY);
+ }
+ return std::string("");
+ }
- typedef enum
- {
- ES_PROVISIONING_ERROR = -1,
- ES_NEED_PROVISIONING,
- ES_PROVISIONED_ALREADY,
- ES_PROVISIONING_SUCCESS
- } ESState;
+ /**
+ * Get OCRepresentation object
+ *
+ * @return OCRepresentation object
+ */
+ const OCRepresentation &toOCRepresentation() const
+ {
+ return m_rep;
+ }
- typedef enum
- {
- ES_UNKNOWN = 0,
- ES_ONBOARDED,
- ES_OWNED,
- ES_PROVISIONED
- } CurrentESState;
+ protected:
+ OCRepresentation m_rep;
+ };
+ /**
+ * @brief Provisioning state in cloud server property provisioning.
+ */
typedef enum
{
- ES_SEC_UNKNOWN = 0,
- ES_SEC_OWNED,
- ES_SEC_ACL_PROVISIONED,
- ES_SEC_CREDS_PROVISIONED
- } EnrolleeSecState;
+ ES_CLOUD_PROVISIONING_ERROR = -1, /**< An error in cloud provisioning happens **/
+ ES_CLOUD_PROVISIONING_SUCCESS, /**< Cloud provisioning is successfully done **/
+ ES_CLOUD_ENROLLEE_FOUND, /**< An enrollee is found in a given network **/
+ ES_CLOUD_ENROLLEE_NOT_FOUND /**< NO enrollee is found in a given network **/
+ }ESCloudProvState;
/**
* Security Provisioning Status
*/
- class SecProvisioningResult
+ class SecProvisioningStatus
{
public:
- std::shared_ptr< SecProvisioningResult > shared_ptr;
- SecProvisioningResult(std::string deviceUUID, ESResult result) :
+ SecProvisioningStatus(string deviceUUID, ESResult result) :
m_devUUID(deviceUUID), m_result(result)
{
-
}
- std::string getDeviceUUID()
+ const string getDeviceUUID()
{
return m_devUUID;
}
- ESResult getResult()
+ ESResult getESResult()
{
return m_result;
}
private:
- std::string m_devUUID;
+ string m_devUUID;
ESResult m_result;
};
/**
- * Callback function definition for providing Enrollee security status .
+ * @breif This provide a set of getter APIs from received response for getConfiguration().
+ * Received information includes a device name, WiFi supported mode, and frequency.
+ * Additionally, you can know if Enrollee can be access to cloud server with this
+ * object.
*/
- typedef std::function< void(std::shared_ptr<SecProvisioningResult>) > EnrolleeSecStatusCb;
+ class EnrolleeConf
+ {
+ public:
+ /**
+ * Constructor
+ * The expected OCRepresentation is one for collection resource and has several child
+ * OCRepresentation object corresponding to WiFi, DevConf, and CloudServer resource's
+ * representation.
+ */
+ EnrolleeConf(const OCRepresentation& rep)
+ {
+ m_ProvRep = rep;
+
+ std::vector<OCRepresentation> children = rep.getChildren();
+
+ for(auto child = children.begin(); child != children.end(); ++child)
+ {
+ if(child->getUri().find(OC_RSRVD_ES_URI_WIFI) != std::string::npos)
+ {
+ m_WiFiRep = *child;
+ }
+ else if(child->getUri().find(OC_RSRVD_ES_URI_DEVCONF) != std::string::npos)
+ {
+ m_DevConfRep = *child;
+ }
+ else if(child->getUri().find(OC_RSRVD_ES_URI_CLOUDSERVER) != std::string::npos)
+ {
+ m_CloudRep = *child;
+ }
+ }
+ }
+
+ /**
+ * Get a device name of Enrollee. It is Device's human-friendly name like device model
+ * name.
+ *
+ * @return a device name of Enrollee
+ */
+ std::string getDeviceName() const
+ {
+ if(m_DevConfRep.hasAttribute(OC_RSRVD_ES_DEVNAME))
+ return m_DevConfRep.getValue<std::string>(OC_RSRVD_ES_DEVNAME);
+ return std::string("");
+ }
+
+ /**
+ * Get a set of WiFi supported modes of Enrollee
+ *
+ * @return a set of WiFi supported modes of Enrollee
+ *
+ * @see WIFI_MODE
+ */
+ vector<WIFI_MODE> getWiFiModes() const
+ {
+ vector<WIFI_MODE> modes;
+ modes.clear();
+
+ if(m_WiFiRep.hasAttribute(OC_RSRVD_ES_SUPPORTEDWIFIMODE))
+ {
+ for(auto it : m_WiFiRep.getValue
+ <std::vector<int>>(OC_RSRVD_ES_SUPPORTEDWIFIMODE))
+ {
+ modes.push_back(static_cast<WIFI_MODE>(it));
+ }
+ }
+ return modes;
+ }
+
+ /**
+ * Get a WiFi supported frequency of Enrollee
+ *
+ * @return a WiFi supported frequency of Enrollee
+ *
+ * @see WIFI_FREQ
+ */
+ WIFI_FREQ getWiFiFreq() const
+ {
+ if(m_WiFiRep.hasAttribute(OC_RSRVD_ES_SUPPORTEDWIFIFREQ))
+ return static_cast<WIFI_FREQ>(
+ m_WiFiRep.getValue<int>(OC_RSRVD_ES_SUPPORTEDWIFIFREQ));
+ return WIFI_FREQ_NONE;
+ }
+
+ /**
+ * Get an accessibility to cloud server of an Enrollee
+ *
+ * @return an accessibility to cloud server of an Enrollee
+ */
+ bool isCloudAccessible() const
+ {
+ if(m_CloudRep.getUri().find(OC_RSRVD_ES_URI_CLOUDSERVER) != std::string::npos)
+ {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Get OCRepresentation object
+ *
+ * @return OCRepresentation object
+ */
+ const OCRepresentation& getProvResRep()
+ {
+ return m_ProvRep;
+ }
+
+ protected:
+ OCRepresentation m_ProvRep, m_WiFiRep, m_DevConfRep, m_CloudRep;
+ };
/**
- * Callback definition to be invoked when the security stack expects a pin from application.
+ * Status object for getStatus API. This object is given to application
+ * when a response for GET request to provisioning resource at Enrollee is arrived.
+ * It returns a result of the API and requested data delivered in the response which includes
+ * a provisioning status and last error code stored in Enrollee.
+ *
+ * @see EnrolleeStatus
*/
- typedef std::function< void(std::string&) > SecurityPinCb;
+ class GetEnrolleeStatus
+ {
+ public:
+ GetEnrolleeStatus(ESResult result, const EnrolleeStatus& status) :
+ m_result(result), m_enrolleeStatus(status)
+ {
+ }
+
+ ESResult getESResult()
+ {
+ return m_result;
+ }
+
+ const EnrolleeStatus& getEnrolleeStatus()
+ {
+ return m_enrolleeStatus;
+ }
+
+ private:
+ ESResult m_result;
+ EnrolleeStatus m_enrolleeStatus;
+ };
/**
- * Callback definition to be invoked when the stack expects a db path.
+ * Status object for getConfiguration API. This object is given to application
+ * when a response for GET request to provisioning resource at Enrollee is arrived.
+ * It returns a result of the API and requested data delivered in the response which includes
+ * WiFi configuration and device configuration stored in Enrollee.
+ *
+ * @see EnrolleeConf
*/
- typedef std::function< void(std::string&) > SecProvisioningDbPathCb;
-
- class ProvisioningStatus
+ class GetConfigurationStatus
{
public:
- std::shared_ptr< ProvisioningStatus > shared_ptr;
- ProvisioningStatus(ESResult result, ESState esState) :
- m_result(result), m_esState(esState)
+ GetConfigurationStatus(ESResult result, const EnrolleeConf& conf) :
+ m_result(result), m_enrolleeConf(conf)
{
-
}
ESResult getESResult()
return m_result;
}
- ESState getESState()
+ const EnrolleeConf& getEnrolleeConf()
{
- return m_esState;
+ return m_enrolleeConf;
}
+
private:
ESResult m_result;
- ESState m_esState;
+ EnrolleeConf m_enrolleeConf;
};
- class EasySetupStatus
+ /**
+ * Status object for provisionDeviceProperties API. This object is given to application
+ * when a response for GET request to provisioning resource at Enrollee is arrived.
+ * It returns a result of the request.
+ */
+ class DevicePropProvisioningStatus
{
public:
- std::shared_ptr< EasySetupStatus > shared_ptr;
- EasySetupStatus(const EasySetupState& easySetupState,
- const ProvConfig& provConfig) :
- m_easySetupState(easySetupState), m_ProvConfig(provConfig)
+ DevicePropProvisioningStatus(ESResult result) :
+ m_result(result)
{
+ }
+ ESResult getESResult()
+ {
+ return m_result;
+ }
+
+
+ private:
+ ESResult m_result;
+ };
+
+ /**
+ * Status object for provisionCloudProperties API. This object is given to application
+ * when a response for GET request to provisioning resource at Enrollee is arrived.
+ * It returns a result of the request and status of this provisioning. The status provides
+ * an information if the enrollee is found in a given network and the provisioning is
+ * successfully done.
+ */
+ class CloudPropProvisioningStatus
+ {
+ public:
+ CloudPropProvisioningStatus(ESResult result, ESCloudProvState state) :
+ m_result(result), m_esCloudState(state)
+ {
}
- ProvConfig getProvConfig()
+ ESResult getESResult()
{
- return m_ProvConfig;
+ return m_result;
}
- EasySetupState getEasySetupState()
+ ESCloudProvState getESCloudState()
{
- return m_easySetupState;
+ return m_esCloudState;
}
+
private:
- EasySetupState m_easySetupState;
- ProvConfig m_ProvConfig;
+ ESResult m_result;
+ ESCloudProvState m_esCloudState;
};
+
+ /**
+ * Callback function definition for providing Enrollee status
+ */
+ typedef function< void(shared_ptr< GetEnrolleeStatus >) > GetStatusCb;
+
+ /**
+ * Callback function definition for providing Enrollee configuration status
+ */
+ typedef function< void(shared_ptr< GetConfigurationStatus >) > GetConfigurationStatusCb;
+
+ /**
+ * Callback function definition for providing Enrollee device property provisioning status
+ */
+ typedef function< void(shared_ptr< DevicePropProvisioningStatus >) > DevicePropProvStatusCb;
+
+ /**
+ * Callback function definition for providing Enrollee cloud property provisioning status
+ */
+ typedef function< void(shared_ptr< CloudPropProvisioningStatus >) > CloudPropProvStatusCb;
+
+ /**
+ * Callback function definition for providing Enrollee security provisioning status
+ */
+ typedef function< void(shared_ptr<SecProvisioningStatus>) > SecurityProvStatusCb;
+
+ /**
+ * Callback definition to be invoked when the security stack expects a pin from application
+ */
+ typedef function< void(string&) > SecurityPinCb;
+
+ /**
+ * Callback definition to be invoked when the stack expects a db path
+ */
+ typedef function< void(string&) > SecProvisioningDbPathCb;
+
}
}
#endif //WITH_ARDUINO
#include "ESRichCommon.h"
#include "RemoteEnrollee.h"
+using namespace OC;
namespace OIC
{
namespace Service
class RemoteEnrollee;
/**
- * This provides methods for Mediator devices to perform EasySetup of Enrollee devices.
- * EasySetup involves
- * 1) Ownership transfer for enabling secured communication between Mediator and Enrollee
- * devices.
- * 2) Provisioning of Enrollee devices using the credentails of target Enroller devices.
+ * This provides an API to instanciate a new RemoteEnrollee object correspondent to Enrollee
+ * Device to be setup.
*/
class EasySetup
{
static EasySetup* getInstance();
/**
- * This API is used for creating a remote Enrollee device instance.
- * @param ProvConfig Provisioning information for configuring the Enrollee.
- * @param WiFiOnboadingConnection Onboarding connection information for configuring the Enrollee.
+ * This API is used for creating a remote Enrollee instance.
+ *
+ * @param enrolleeResource an OCResource object corresponding to enrollee resource
+ * discovered in a network. The OCResource object can be obtained by calling
+ * OCPlatform.findResource() API. What resource you have to discover with
+ * the OCPlatform.findResource() API is a "provisioning" resource with a certain
+ * resource type, i.e. ocf.wk.prov
*
* @throws ESBadRequestException If createEnrolleeDevice is invoked with the same
* provisioning information.
*
* @return Pointer to RemoteEnrollee instance.
*/
- std::shared_ptr<RemoteEnrollee> createEnrolleeDevice (
- const ProvConfig& enrolleeNWProvInfo,
- const WiFiOnboadingConnection& wifiOnboardingconn);
+ std::shared_ptr<RemoteEnrollee> createRemoteEnrollee(
+ std::shared_ptr< OC::OCResource > enrolleeResource);
+
private:
EasySetup();
~EasySetup();
- RemoteEnrollee::shared_ptr findDeviceInProvisioningList(
- const ProvConfig& enrolleeNWProvInfo,
- const WiFiOnboadingConnection& wifiOnboardingconn);
- bool addDeviceToProvisioningList(const RemoteEnrollee::shared_ptr remoteEnrollee);
- bool deleteDeviceFromProvisioningList (const ProvConfig& enrolleeNWProvInfo);
-
- std::vector< RemoteEnrollee::shared_ptr > m_activeEnrolleeList;
+ private:
+ std::shared_ptr< OC::OCResource > m_ocResource;
static EasySetup *s_instance;
};
}
--- /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 ENROLLEE_RESOURCE_H_
+#define ENROLLEE_RESOURCE_H_
+
+#include <mutex>
+#include <memory>
+
+#include "ESRichCommon.h"
+
+#include "OCApi.h"
+
+using namespace OC;
+
+namespace OIC
+{
+ namespace Service
+ {
+ class OCResource;
+ class EnrolleeSecurity;
+
+ /**
+ * This class contains the resource discovery methods.
+ *
+ * @see EnrolleeResource
+ */
+ class EnrolleeResource
+ {
+ friend class EnrolleeSecurity;
+
+ public:
+ EnrolleeResource(std::shared_ptr< OC::OCResource > resource);
+
+ ~EnrolleeResource() = default;
+
+ void registerGetStatusCallback (GetStatusCb callback);
+ void registerGetConfigurationStatusCallback (GetConfigurationStatusCb callback);
+ void registerDevicePropProvStatusCallback (DevicePropProvStatusCb callback);
+
+ void getConfiguration();
+ void getStatus();
+
+ void provisionEnrollee(const DeviceProp& deviceProp);
+
+ private:
+ std::shared_ptr< OC::OCResource > m_ocResource;
+
+ GetStatusCb m_getStatusCb;
+ GetConfigurationStatusCb m_getConfigurationStatusCb;
+ DevicePropProvStatusCb m_devicePropProvStatusCb;
+
+ private:
+ void onGetStatusResponse(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+ const int eCode);
+ void onGetConfigurationResponse(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+ const int eCode);
+ void checkProvInformationCb(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+ const int eCode);
+ };
+ }
+}
+#endif
#define ENROLLEE_SECURITY_H_
#include <functional>
+#include <condition_variable>
#include "ESRichCommon.h"
#include "OCProvisioningManager.h"
{
#define ENROLEE_SECURITY_TAG "ENROLEE_SECURITY"
- class RemoteEnrolleeResource;
+ class EnrolleeResource;
class OCSecureResource;
+ typedef std::vector<OCProvisionResult_t> PMResultList_t;
+
/**
* This class contains the methods needed for security layer interaction.
*
class EnrolleeSecurity
{
public:
- EnrolleeSecurity(std::shared_ptr< RemoteEnrolleeResource > remoteEnrolleeResource,
+ EnrolleeSecurity(std::shared_ptr< OC::OCResource > resource,
std::string secDbPath);
- ESResult registerCallbackHandler(EnrolleeSecStatusCb enrolleeSecStatusCb,
+ void registerCallbackHandler(SecurityProvStatusCb securityProvStatusCb,
SecurityPinCb securityPinCb, SecProvisioningDbPathCb secProvisioningDbPathCb);
- EasySetupState performOwnershipTransfer();
+ void performOwnershipTransfer();
+ ESResult performACLProvisioningForCloudServer(std::string cloudUuid);
+ std::string getUUID() const;
private:
- std::shared_ptr< RemoteEnrolleeResource > m_remoteEnrolleeResource;
- EnrolleeSecStatusCb m_enrolleeSecStatusCb;
+ std::shared_ptr< OC::OCResource > m_ocResource;
+ SecurityProvStatusCb m_securityProvStatusCb;
SecurityPinCb m_securityPinCb;
SecProvisioningDbPathCb m_secProvisioningDbPathCb;
std::shared_ptr< OC::OCSecureResource > m_unownedDevice;
- EnrolleeSecState m_enrolleeSecState;std::shared_ptr< OC::OCSecureResource > m_securedResource;
+ std::mutex m_mtx;
+ std::condition_variable m_cond;
+ bool aclResult;
+ std::shared_ptr< OC::OCSecureResource > m_securedResource;
std::shared_ptr< OC::OCSecureResource > getEnrollee(OC::DeviceList_t &list);
void ownershipTransferCb(OC::PMResultList_t *result, int hasError);
void convertUUIDToString(OicUuid_t uuid, std::string& uuidString);
+ void convertStringToUUID(OicUuid_t& uuid, std::string uuidString);
+ OicSecAcl_t* createAcl(OicUuid_t cloudUuid);
+
+ void ACLProvisioningCb(PMResultList_t *result, int hasError);
};
}
}
#ifndef REMOTE_ENROLLEE_H_
#define REMOTE_ENROLLEE_H_
+#include <memory>
+#include <iostream>
+#include <condition_variable>
+
#include "ESRichCommon.h"
+#include "OCApi.h"
+
+using namespace OC;
namespace OIC
{
namespace Service
{
- class RemoteEnrolleeResource;
+ class OCResource;
+ class EnrolleeResource;
+ class CloudResource;
class EnrolleeSecurity;
/**
- * This class represents Remote Enrollee device instance.
- * It will provide APIs for Mediator to perform operations to enable the Enrollee device
- * to connect to the Enroller.
+ * This class represents Remote Enrollee device instance. What operation the class provides:
+ * 1) Ownership transfer for enabling secured communication between Mediator and Enrollee
+ * devices.
+ * 2) Provision WiFi AP information used for which Enrollee is going to connect to the AP
+ * 3) Provision Device confiruation setting, i.e. language, country, and etc
+ * 4) Provision Cloud information used for which Enrollee is going to register to the cloud
*/
class RemoteEnrollee
{
public:
- /**
- * RemoteEnrollee constructor
- *
- * @param enrolleeNWProvInfo Provisioning information for the Enrollee
- *
- * @throw ESBadRequestException is thrown if the parameters are invalid
- */
- RemoteEnrollee(const ProvConfig& enrolleeNWProvInfo, const WiFiOnboadingConnection& connection) ;
-
~RemoteEnrollee() = default;
- typedef std::shared_ptr< RemoteEnrollee > shared_ptr;
-
- /**
- * Callback definition to be invoked when EasySetup status is changed.
- * The same callback will be invoked when there is an error in the
- * EasySetup process.
- *
- * @see registerResourceHandler
- * @see ResourceState
- */
- typedef std::function< void(std::shared_ptr< EasySetupStatus >) >
- EasySetupStatusCB;
-
#ifdef __WITH_DTLS__
/**
* Register Security status and other information callback handlers.
#endif //__WITH_DTLS__
/**
- * Register EasySetup status handler.
+ * Get an Enrollee's status which includes provisioning status and last error code
*
- * @param callback Callback to get EasySetup status.
- * @param secProvisioningDbCB Callback to be invoked when the stack expects a
- * path for the provisioning db.
+ * @param callback will give the requested status
*
- * @throws InvalidParameterException If callback is an empty function or null.
- * @throws ESBadRequestException If registration is already completed.
+ * @throws ESBadRequestException If RemoteEnrollee device not created prior to this call.
*
- * @see EasySetupStatus
+ * @see GetStatusCb
*/
- void registerEasySetupStatusHandler(EasySetupStatusCB callback);
+ void getStatus(GetStatusCb callback);
/**
- * Start provisioning of target Enrollers information to the Enrollee.
+ * Get an Enrollee's configuration which includes WiFi supported frequency and device name
+ *
+ * @param callback will give the requested configuration
*
* @throws ESBadRequestException If RemoteEnrollee device not created prior to this call.
*
- * @see RemoteEnrollee
+ * @see GetConfigurationStatusCb
*/
- void startProvisioning();
+ void getConfiguration(GetConfigurationStatusCb callback);
- /**
- * Stop provisioning process that is currently in progress.
+ /**
+ * Do security provisioning such as ownership tranfer to Enrollee.
*
- * @throws BadRequestException If provisioning is not in progress.
- */
- void stopProvisioning();
-
- /**
- * Check if the Enrollee device provisioned.
+ * @param callback will give the result if the security provisioning succeeds or fails for some reasons
+ *
+ * @throws ESBadRequestException If RemoteEnrollee device not created prior to this call.
+ *
+ * @see SecurityProvStatusCb
*/
- bool isEnrolleeProvisioned();
+ void provisionSecurity(SecurityProvStatusCb callback);
/**
- * Get the Provisioning information provided for the current Enrollee.
+ * Provision WiFi AP information and device configuration to Enrollee
+ * 1. WiFi AP information includes a SSID, password, auth type, and encryption type.
+ * 2. Device configuration includes a language (IETF language tags) and country (ISO 3166-1 Alpha-2)
+ *
+ * @param devProp a data structure storing the above information to be delivered
+ * @param callback will give the result if the provisioning succeeds or fails
*
- * @return ProvConfig Provisioning information provided for the current Enrollee.
+ * @throws ESBadRequestException If RemoteEnrollee device not created prior to this call.
+ *
+ * @see DeviceProp
+ * @see DevicePropProvStatusCb
*/
- ProvConfig getProvConfig ();
+ void provisionDeviceProperties(const DeviceProp& devProp,
+ DevicePropProvStatusCb callback);
/**
- * Get the Onboarding connection information between Mediator and Enrollee.
+ * Provision Cloud information to Enrollee, which includes Auth code, auth provider,
+ * Cloud interface server URL, and etc.
+ * In this function, Discovery for the Enrollee will happen again in a given network.
+ * Because, this function is expected to call *AFTER* the Enrollee disconnects its Soft AP
+ * and successfully connects to the certain WiFi AP. In that case, Mediator should discover
+ * the Enrollee with a certain Device ID in the network.
+ *
+ * @param cloudProp a data structure storing the above information to be delivered
+ * @param callback will give the result if the provisioning succeeds or fails
+ *
+ * @throws ESBadRequestException If RemoteEnrollee device not created prior to this call.
*
- * @return WiFiOnboadingConnection information between Mediator and Enrollee.
+ * @see CloudProp
+ * @see CloudPropProvStatusCb
*/
+ void provisionCloudProperties(const CloudProp& cloudProp,
+ CloudPropProvStatusCb callback);
- WiFiOnboadingConnection getOnboardConn();
+ private:
+ RemoteEnrollee(std::shared_ptr< OC::OCResource > resource);
+
+ ESResult discoverResource();
+ void onDeviceDiscovered(std::shared_ptr<OC::OCResource> resource);
+ void initCloudResource();
+
+ void getStatusHandler (std::shared_ptr< GetEnrolleeStatus > status);
+ void getConfigurationStatusHandler (std::shared_ptr< GetConfigurationStatus > status);
+ void devicePropProvisioningStatusHandler (std::shared_ptr< DevicePropProvisioningStatus > status);
+ void cloudPropProvisioningStatusHandler (std::shared_ptr< CloudPropProvisioningStatus > status);
+ void securityStatusHandler(std::shared_ptr< SecProvisioningStatus > status);
private:
- std::shared_ptr< RemoteEnrolleeResource > m_remoteResource;
- EasySetupStatusCB m_easySetupStatusCb;
- EnrolleeSecStatusCb m_enrolleeSecStatusCb;
+ std::shared_ptr< OC::OCResource > m_ocResource;
+ std::shared_ptr< EnrolleeResource > m_enrolleeResource;
+ std::shared_ptr< EnrolleeSecurity > m_enrolleeSecurity;
+ std::shared_ptr< CloudResource > m_cloudResource;
+
+ std::string m_deviceId;
+ bool m_discoveryResponse;
+
+ std::mutex m_discoverymtx;
+ std::condition_variable m_cond;
+
+ SecurityProvStatusCb m_securityProvStatusCb;
+ GetStatusCb m_getStatusCb;
+ GetConfigurationStatusCb m_getConfigurationStatusCb;
SecurityPinCb m_securityPinCb;
SecProvisioningDbPathCb m_secProvisioningDbPathCb;
- ProvConfig m_ProvConfig;
- WiFiOnboadingConnection m_wifiOnboardingconn;
-
- std::shared_ptr< EnrolleeSecurity > m_enrolleeSecurity;
- CurrentESState m_currentESState;
- bool m_isSecured;
+ DevicePropProvStatusCb m_devicePropProvStatusCb;
+ CloudPropProvStatusCb m_cloudPropProvStatusCb;
- void provisioningStatusHandler (std::shared_ptr< ProvisioningStatus > provStatus);
- void easySetupSecurityStatusCallback(
- std::shared_ptr< SecProvisioningResult > secProvisioningResult);
+ friend class EasySetup;
};
}
}
+++ /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 REMOTE_ENROLLEE_RESOURCE_H_
-#define REMOTE_ENROLLEE_RESOURCE_H_
-
-#include <mutex>
-#include <memory>
-
-#include "ESRichCommon.h"
-
-#include "OCApi.h"
-
-using namespace OC;
-
-namespace OIC
-{
- namespace Service
- {
- class OCResource;
- class EnrolleeSecurity;
-
- /**
- * This class contains the resource discovery methods.
- *
- * @see RemoteEnrolleeResource
- */
- class RemoteEnrolleeResource
- {
- friend class EnrolleeSecurity;
-
- public:
- typedef std::shared_ptr< RemoteEnrolleeResource > Ptr;
-
- typedef std::function< void(std::shared_ptr< ProvisioningStatus >) > ProvStatusCb;
-
- /**
- * RemoteEnrolleeResource constructor
- *
- * @param enrolleeNWProvInfo Provisioning information for the Enrollee
- *
- * @throw ESBadRequestException is thrown if the parameters are invalid
- */
- RemoteEnrolleeResource(const ProvConfig &enrolleeNWProvInfo,
- const WiFiOnboadingConnection &onboardingconn);
-
- ~RemoteEnrolleeResource() = default;
-
- /**
- * Register provisioning status handler.
- *
- * @param callback Callback to get Provisioning status.
- *
- * @throws InvalidParameterException If callback is an empty function or null.
- * @throws ESBadRequestException If registration is already completed.
- *
- * @see ProvisioningStatus
- */
- void registerProvStatusCallback (ProvStatusCb provStatusCb);
-
- /**
- * Construct Remote OIC resource using the enrollee host and connectivity information
- * provided in the constructor of RemoteEnrolleeResource.
- *
- * @throws InvalidParameterException If the provided information is invalid.
- * @throws ESBadRequestException If resource is already constructed.
- *
- * @see ProvisioningStatus
- */
- ESResult constructResourceObject();
-
- /**
- * Function for provisioning of Remote Enrollee resource using the information provided.
- *
- * @throws InvalidParameterException If cb is empty.
- */
- void provisionEnrollee();
-
- /**
- * Function for unprovisioning of Remote Enrollee and bring to unprovisioned state
- *
- * @throws ESBadRequestException If device is not provisioned already.
- */
- void unprovisionEnrollee();
-
-
-
- private:
- std::shared_ptr< OC::OCResource > m_ocResource;
- std::mutex m_mutex;
- ProvStatusCb m_provStatusCb;
- ProvConfig m_ProvConfig;
- WiFiOnboadingConnection m_wifiOnboardingconn;
- bool m_discoveryResponse;
-
- void getProvStatusResponse(const HeaderOptions& headerOptions, const OCRepresentation& rep,
- const int eCode);
-
- void checkProvInformationCb(const HeaderOptions& headerOptions, const OCRepresentation& rep,
- const int eCode);
-
- ESResult ESDiscoveryTimeout(unsigned short waittime);
-
- void onDeviceDiscovered(std::shared_ptr<OC::OCResource> resource);
-
- void triggerNetworkConnection();
-
- void triggerNetworkConnectionCb(
- const HeaderOptions& headerOptions, const OCRepresentation& rep,
- const int eCode);
- };
- }
-}
-#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 <functional>
+
+#include "CloudResource.h"
+
+#include "OCPlatform.h"
+#include "ESException.h"
+#include "OCResource.h"
+#include "logger.h"
+
+namespace OIC
+{
+ namespace Service
+ {
+ #define ES_CLOUD_RES_TAG "ES_CLOUD_RESOURCE"
+
+ static const char ES_BASE_RES_URI[] = "/oic/res";
+
+ CloudResource::CloudResource(std::shared_ptr< OC::OCResource > resource)
+ {
+ m_ocResource = resource;
+ }
+
+ void CloudResource::provisionEnrollee(const CloudProp& cloudProp)
+ {
+ OIC_LOG_V (DEBUG, ES_CLOUD_RES_TAG, "Enter provisionEnrollee.");
+
+ OCRepresentation provisioningRepresentation = cloudProp.toOCRepresentation();
+
+ m_ocResource->post(OC_RSRVD_ES_RES_TYPE_PROV, BATCH_INTERFACE,
+ provisioningRepresentation, QueryParamsMap(),
+ std::function<
+ void(const HeaderOptions& headerOptions,
+ const OCRepresentation& rep, const int eCode) >(
+ std::bind(&CloudResource::onCloudProvResponse, this,
+ std::placeholders::_1, std::placeholders::_2,
+ std::placeholders::_3)));
+ }
+
+ void CloudResource::onCloudProvResponse(const HeaderOptions& /*headerOptions*/,
+ const OCRepresentation& rep, const int eCode)
+ {
+ OIC_LOG_V (DEBUG, ES_CLOUD_RES_TAG, "onCloudProvResponse : %s, eCode = %d",
+ rep.getUri().c_str(), eCode);
+
+ if (eCode > OCStackResult::OC_STACK_RESOURCE_CHANGED)
+ {
+ ESResult result = ESResult::ES_ERROR;
+
+ OIC_LOG(DEBUG, ES_CLOUD_RES_TAG,"onCloudProvResponse : onCloudProvResponse is failed ");
+
+ if (eCode == OCStackResult::OC_STACK_UNAUTHORIZED_REQ)
+ {
+ OIC_LOG(DEBUG, ES_CLOUD_RES_TAG, "Mediator is unauthorized from Enrollee.");
+ result = ESResult::ES_UNAUTHORIZED;
+ }
+
+ std::shared_ptr< CloudPropProvisioningStatus > provStatus = std::make_shared<
+ CloudPropProvisioningStatus >(result, ESCloudProvState::ES_CLOUD_PROVISIONING_ERROR);
+ m_cloudPropProvStatusCb(provStatus);
+ }
+ else
+ {
+ OIC_LOG(DEBUG, ES_CLOUD_RES_TAG,"onCloudProvResponse : onCloudProvResponse is success ");
+ std::shared_ptr< CloudPropProvisioningStatus > provStatus = std::make_shared<
+ CloudPropProvisioningStatus >(ESResult::ES_OK, ESCloudProvState::ES_CLOUD_PROVISIONING_SUCCESS);
+ m_cloudPropProvStatusCb(provStatus);
+ }
+ }
+
+ void CloudResource::registerCloudPropProvisioningStatusCallback(CloudPropProvStatusCb callback)
+ {
+ OIC_LOG_V (DEBUG, ES_CLOUD_RES_TAG, "Enter registerCloudPropProvisioningStatusCallback.");
+ m_cloudPropProvStatusCb = callback;
+ }
+ }
+}
#include "EasySetup.h"
+#include "OCPlatform.h"
#include "logger.h"
#include "ESException.h"
#include "RemoteEnrollee.h"
+using namespace OC;
+
namespace OIC
{
namespace Service
return s_instance;
}
- RemoteEnrollee::shared_ptr EasySetup::findDeviceInProvisioningList (
- const ProvConfig& provConfig, const WiFiOnboadingConnection& onboardingconn)
- {
- OIC_LOG(DEBUG,EASYSETUP_TAG,"Entered findDeviceInProvisioningList ()");
-
- std::vector< std::shared_ptr< RemoteEnrollee > >::iterator it;
-
- std::shared_ptr< RemoteEnrollee > remoteEnrollee = nullptr;
- for(auto it : m_activeEnrolleeList)
- {
- OIC_LOG_V(DEBUG,EASYSETUP_TAG,"entered the iterator");
-
- ProvConfig activeEnrolleConfig = it->getProvConfig();
- WiFiOnboadingConnection activeEnrolleConn = it->getOnboardConn();
- if ((0 == memcmp(&activeEnrolleConfig.provData,
- &provConfig.provData, sizeof(ProvConfig))) &&
- (0 == memcmp(&activeEnrolleConn.ipAddress,
- &onboardingconn.ipAddress, sizeof(onboardingconn.ipAddress))))
- {
- remoteEnrollee = it;
- return remoteEnrollee;
- }
- }
-
- OIC_LOG_V(DEBUG,EASYSETUP_TAG,"Return nullptr for findDeviceInProvisioningList call");
- return remoteEnrollee;
- }
-
- bool EasySetup::addDeviceToProvisioningList(const RemoteEnrollee::shared_ptr remoteEnrollee)
+ std::shared_ptr<RemoteEnrollee> EasySetup::createRemoteEnrollee (std::shared_ptr< OC::OCResource > resource)
{
- ProvConfig remoteEnrolleConfig = remoteEnrollee->getProvConfig();
- WiFiOnboadingConnection remoteEnrolleConn = remoteEnrollee->getOnboardConn();
-
- for (auto it : m_activeEnrolleeList)
+ if(resource)
{
- ProvConfig activeEnrolleConfig = it->getProvConfig();
- WiFiOnboadingConnection activeEnrolleConn = it->getOnboardConn();
- if ( (0 == memcmp(&activeEnrolleConfig.provData,
- &remoteEnrolleConfig.provData,
- sizeof(ProvConfig))) &&
- (0 == memcmp(&activeEnrolleConn.ipAddress,
- &remoteEnrolleConn.ipAddress,
- sizeof(remoteEnrolleConn.ipAddress)))
- )
+ if(resource->getResourceTypes().at(0) != OC_RSRVD_ES_RES_TYPE_PROV)
{
- return false;
+ OIC_LOG_V (DEBUG, EASYSETUP_TAG, "createRemoteEnrollee : invalid reousrce");
+ return nullptr;
}
+ return std::shared_ptr< RemoteEnrollee > (new RemoteEnrollee(resource));
}
-
- OIC_LOG_V(DEBUG,EASYSETUP_TAG,"Adding new device RemoteEnrollee list");
- m_activeEnrolleeList.push_back(remoteEnrollee);
- return true;
- }
-
- std::shared_ptr<RemoteEnrollee> EasySetup::createEnrolleeDevice (
- const ProvConfig& provConfig, const WiFiOnboadingConnection& wifiOnboardingconn)
- {
- if (findDeviceInProvisioningList(provConfig,wifiOnboardingconn) != nullptr)
- {
- throw ESBadRequestException { "Device already created exception" };
- }
-
- RemoteEnrollee::shared_ptr remoteEnrollee;
-
- remoteEnrollee = std::make_shared< RemoteEnrollee > (provConfig, wifiOnboardingconn);
-
-
- if (!addDeviceToProvisioningList (remoteEnrollee))
- {
- return nullptr;
- }
-
- return remoteEnrollee;
+ return nullptr;
}
-
-
}
}
--- /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 <functional>
+
+#include "EnrolleeResource.h"
+
+#include "OCPlatform.h"
+#include "ESException.h"
+#include "OCResource.h"
+#include "logger.h"
+
+namespace OIC
+{
+ namespace Service
+ {
+ #define ES_REMOTE_ENROLLEE_RES_TAG "ES_ENROLLEE_RESOURCE"
+
+ EnrolleeResource::EnrolleeResource(std::shared_ptr< OC::OCResource > resource)
+ {
+ m_ocResource = resource;
+ }
+
+ void EnrolleeResource::checkProvInformationCb(const HeaderOptions& /*headerOptions*/,
+ const OCRepresentation& rep, const int eCode)
+ {
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "checkProvInformationCb : %s, eCode = %d",
+ rep.getUri().c_str(),
+ eCode);
+
+ if (eCode > OCStackResult::OC_STACK_RESOURCE_CHANGED)
+ {
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
+ "checkProvInformationCb : Provisioning is failed ");
+ std::shared_ptr< DevicePropProvisioningStatus > provStatus = std::make_shared<
+ DevicePropProvisioningStatus >(ESResult::ES_ERROR);
+ m_devicePropProvStatusCb(provStatus);
+ return;
+ }
+
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
+ "checkProvInformationCb : Provisioning is success. ");
+
+ std::shared_ptr< DevicePropProvisioningStatus > provStatus = std::make_shared<
+ DevicePropProvisioningStatus >(ESResult::ES_OK);
+ m_devicePropProvStatusCb(provStatus);
+ }
+
+ void EnrolleeResource::onGetStatusResponse(const HeaderOptions& /*headerOptions*/,
+ const OCRepresentation& rep, const int eCode)
+ {
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "onGetStatusResponse : %s, eCode = %d",
+ rep.getUri().c_str(), eCode);
+
+ if (eCode > OCStackResult::OC_STACK_RESOURCE_CHANGED)
+ {
+ ESResult result = ESResult::ES_ERROR;
+
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
+ "onGetStatusResponse : onGetStatusResponse is failed ");
+
+ if (eCode == OCStackResult::OC_STACK_UNAUTHORIZED_REQ)
+ {
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
+ "Mediator is unauthorized from Enrollee.");
+ result = ESResult::ES_UNAUTHORIZED;
+ }
+
+ EnrolleeStatus enrolleeStatus(rep);
+ std::shared_ptr< GetEnrolleeStatus > getEnrolleeStatus = std::make_shared<
+ GetEnrolleeStatus >(result, enrolleeStatus);
+
+ m_getStatusCb(getEnrolleeStatus);
+ }
+ else
+ {
+ EnrolleeStatus enrolleeStatus(rep);
+ std::shared_ptr< GetEnrolleeStatus > getEnrolleeStatus = std::make_shared<
+ GetEnrolleeStatus >(ESResult::ES_OK, enrolleeStatus);
+
+ m_getStatusCb(getEnrolleeStatus);
+ }
+ }
+
+ void EnrolleeResource::onGetConfigurationResponse(const HeaderOptions& /*headerOptions*/,
+ const OCRepresentation& rep, const int eCode)
+ {
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "onGetConfigurationResponse : %s, eCode = %d",
+ rep.getUri().c_str(), eCode);
+
+ if (eCode > OCStackResult::OC_STACK_RESOURCE_CHANGED)
+ {
+ ESResult result = ESResult::ES_ERROR;
+
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
+ "onGetConfigurationResponse : onGetConfigurationResponse is failed ");
+
+ if (eCode == OCStackResult::OC_STACK_UNAUTHORIZED_REQ)
+ {
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
+ "Mediator is unauthorized from Enrollee.");
+ result = ESResult::ES_UNAUTHORIZED;
+ }
+
+ EnrolleeConf enrolleeConf(rep);
+ std::shared_ptr< GetConfigurationStatus > getConfigurationStatus = std::make_shared<
+ GetConfigurationStatus >(result, enrolleeConf);
+ m_getConfigurationStatusCb(getConfigurationStatus);
+ }
+ else
+ {
+ EnrolleeConf enrolleeConf(rep);
+
+ std::shared_ptr< GetConfigurationStatus > getConfigurationStatus = std::make_shared<
+ GetConfigurationStatus >(ESResult::ES_OK, enrolleeConf);
+ m_getConfigurationStatusCb(getConfigurationStatus);
+ }
+ }
+
+ void EnrolleeResource::registerGetStatusCallback(GetStatusCb callback)
+ {
+ m_getStatusCb = callback;
+ }
+
+ void EnrolleeResource::registerGetConfigurationStatusCallback(GetConfigurationStatusCb callback)
+ {
+ m_getConfigurationStatusCb = callback;
+ }
+
+ void EnrolleeResource::registerDevicePropProvStatusCallback(DevicePropProvStatusCb callback)
+ {
+ m_devicePropProvStatusCb = callback;
+ }
+
+ void EnrolleeResource::getStatus()
+ {
+ if (m_ocResource == nullptr)
+ {
+ throw ESBadRequestException("Resource is not initialized");
+ }
+
+ OC::QueryParamsMap query;
+ OC::OCRepresentation rep;
+
+ std::function< OCStackResult(void) > getStatus = [&]
+ {
+ return m_ocResource->get(m_ocResource->getResourceTypes().at(0),
+ DEFAULT_INTERFACE, query, std::function<void(const HeaderOptions& headerOptions,
+ const OCRepresentation& rep, const int eCode) >(
+ std::bind(&EnrolleeResource::onGetStatusResponse, this,
+ std::placeholders::_1, std::placeholders::_2,
+ std::placeholders::_3)));
+ };
+
+ OCStackResult result = getStatus();
+
+ if (result != OCStackResult::OC_STACK_OK)
+ {
+ EnrolleeStatus enrolleeStatus(rep);// = {ES_STATE_INIT, ES_ERRCODE_NO_ERROR};
+ std::shared_ptr< GetEnrolleeStatus > getEnrolleeStatus = std::make_shared<
+ GetEnrolleeStatus >(ESResult::ES_ERROR, enrolleeStatus);
+
+ m_getStatusCb(getEnrolleeStatus);
+
+ return;
+ }
+ }
+
+ void EnrolleeResource::getConfiguration()
+ {
+ if (m_ocResource == nullptr)
+ {
+ throw ESBadRequestException("Resource is not initialized");
+ }
+
+ OC::QueryParamsMap query;
+ OC::OCRepresentation rep;
+
+ std::function< OCStackResult(void) > getConfigurationStatus = [&]
+ {
+ return m_ocResource->get(m_ocResource->getResourceTypes().at(0),
+ BATCH_INTERFACE, query, std::function<void(const HeaderOptions& headerOptions,
+ const OCRepresentation& rep, const int eCode) >(
+ std::bind(&EnrolleeResource::onGetConfigurationResponse, this,
+ std::placeholders::_1, std::placeholders::_2,
+ std::placeholders::_3)));
+ };
+
+ OCStackResult result = getConfigurationStatus();
+
+ if (result != OCStackResult::OC_STACK_OK)
+ {
+ EnrolleeConf enrolleeConf(rep);
+ std::shared_ptr< GetConfigurationStatus > getConfigurationStatus = std::make_shared<
+ GetConfigurationStatus >(ESResult::ES_ERROR, enrolleeConf);
+ m_getConfigurationStatusCb(getConfigurationStatus);
+ return;
+ }
+ }
+
+ void EnrolleeResource::provisionEnrollee(const DeviceProp& deviceProp)
+ {
+ if (m_ocResource == nullptr)
+ {
+ throw ESBadRequestException("Resource is not initialized");
+ }
+
+ OC::QueryParamsMap query;
+ OC::OCRepresentation provisioningRepresentation = deviceProp.toOCRepresentation();
+
+ m_ocResource->post(OC_RSRVD_ES_RES_TYPE_PROV, BATCH_INTERFACE,
+ provisioningRepresentation, QueryParamsMap(),
+ std::function<
+ void(const HeaderOptions& headerOptions,
+ const OCRepresentation& rep, const int eCode) >(
+ std::bind(&EnrolleeResource::checkProvInformationCb, this,
+ std::placeholders::_1, std::placeholders::_2,
+ std::placeholders::_3)));
+ }
+ }
+}
#include "EnrolleeSecurity.h"
#include "oxmjustworks.h"
#include "oxmrandompin.h"
-#include "RemoteEnrolleeResource.h"
+#include "EnrolleeResource.h"
#include "logger.h"
#include "ESException.h"
#include "oic_malloc.h"
#include "oic_string.h"
+#include "utlist.h"
namespace OIC
{
//TODO : Currently discovery timeout for owned and unowned devices is fixed as 5
// The value should be accepted from the application as a parameter during ocplatform
// config call
-#define ES_SEC_DISCOVERY_TIMEOUT 5
+ #define ES_SEC_DISCOVERY_TIMEOUT 5
EnrolleeSecurity::EnrolleeSecurity(
- std::shared_ptr< RemoteEnrolleeResource > remoteEnrolleeResource,
+ std::shared_ptr< OC::OCResource > resource,
std::string secDbPath)
{
- m_enrolleeSecState = EnrolleeSecState::ES_SEC_UNKNOWN;
- m_remoteEnrolleeResource = remoteEnrolleeResource;
+ (void) secDbPath;
+ m_ocResource = resource;
}
- ESResult EnrolleeSecurity::registerCallbackHandler(EnrolleeSecStatusCb enrolleeSecStatusCb,
+ void EnrolleeSecurity::registerCallbackHandler(SecurityProvStatusCb securityProvStatusCb,
SecurityPinCb securityPinCb, SecProvisioningDbPathCb secProvisioningDbPathCb)
-
{
- m_enrolleeSecStatusCb = enrolleeSecStatusCb;
+ m_securityProvStatusCb = securityProvStatusCb;
m_securityPinCb = securityPinCb;
m_secProvisioningDbPathCb = secProvisioningDbPathCb;
-
- return ES_ERROR;
}
std::shared_ptr< OC::OCSecureResource > EnrolleeSecurity::getEnrollee(DeviceList_t &list)
{
for (unsigned int i = 0; i < list.size(); i++)
{
- OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "Device %d ID %s ", i + 1,
- list[i]->getDeviceID().c_str());
- OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "From IP :%s", list[i]->getDevAddr().c_str());
-
- //Always return the first element of the unOwned devices. This is considering that Mediator is
- // always connected with only one Enrollee for which ownership transfer is being performed.
- // Incase of multiple Enrollee devices connected to the Mediator via any OnBoarding method (SoftAp
- // for example), the Enrollee devices will be provisioned in the first come first serve basis in the order
- // returned by the security layer.
- return list[i];
+ if(m_ocResource->sid() == list[i]->getDeviceID().c_str())
+ {
+ OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "Device %d ID %s ", i + 1,
+ list[i]->getDeviceID().c_str());
+ OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "From IP :%s", list[i]->getDevAddr().c_str());
+ return list[i];
+ }
}
OIC_LOG(ERROR, ENROLEE_SECURITY_TAG,"Error!!! DeviceList_t is NULL");
return NULL;
uuidString = deviceId.str();
}
+ void EnrolleeSecurity::convertStringToUUID(OicUuid_t& uuid, std::string uuidString)
+ {
+ size_t outBufSize = B64DECODE_OUT_SAFESIZE((uuidString.length() + 1));
+ uint8_t* outKey = (uint8_t*)OICCalloc(1, outBufSize);
+ uint32_t outKeySize = 0;
+ if(NULL == outKey)
+ {
+ OIC_LOG (ERROR, ENROLEE_SECURITY_TAG, "Failed to memoray allocation.");
+ throw ESBadRequestException ("Failed to memoray allocation.");
+ }
+
+ if(B64_OK == b64Decode((char*)uuidString.c_str(),
+ uuidString.length(),
+ outKey,
+ outBufSize,
+ &outKeySize))
+ {
+ memcpy(uuid.id, outKey, outKeySize);
+ }
+ else
+ {
+ OIC_LOG (ERROR, ENROLEE_SECURITY_TAG, "Failed to base64 decoding.");
+ throw ESBadRequestException ("Failed to base64 decoding.");
+ }
+
+ OICFree(outKey);
+ }
+
void EnrolleeSecurity::ownershipTransferCb(OC::PMResultList_t *result, int hasError)
{
if (hasError)
{
OIC_LOG(ERROR, ENROLEE_SECURITY_TAG,"Error!!! in OwnershipTransfer");
- std::shared_ptr< SecProvisioningResult > securityProvisioningStatus = nullptr;
std::string uuid;
convertUUIDToString(result->at(0).deviceId, uuid);
- securityProvisioningStatus = std::make_shared< SecProvisioningResult >(uuid,
- ES_ERROR);
-
- m_enrolleeSecStatusCb(securityProvisioningStatus);
+ std::shared_ptr< SecProvisioningStatus > securityProvisioningStatus =
+ std::make_shared< SecProvisioningStatus >(uuid, ES_ERROR);
+ m_securityProvStatusCb(securityProvisioningStatus);
return;
}
else
convertUUIDToString(result->at(0).deviceId, uuid);
OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "UUID : %s",uuid.c_str());
- std::shared_ptr< SecProvisioningResult > securityProvisioningStatus = nullptr;
- securityProvisioningStatus = std::make_shared< SecProvisioningResult >(uuid,
- ES_OK);
-
- m_enrolleeSecStatusCb(securityProvisioningStatus);
+ std::shared_ptr< SecProvisioningStatus > securityProvisioningStatus =
+ std::make_shared< SecProvisioningStatus >(uuid, ES_OK);
+ m_securityProvStatusCb(securityProvisioningStatus);
return;
}
}
}
- EasySetupState EnrolleeSecurity::performOwnershipTransfer()
+ void EnrolleeSecurity::performOwnershipTransfer()
{
- EasySetupState ownershipStatus = DEVICE_NOT_OWNED;
-
OC::DeviceList_t pUnownedDevList, pOwnedDevList;
pOwnedDevList.clear();
pUnownedDevList.clear();
- OCStackResult result;
+ OCStackResult result = OC_STACK_ERROR;
- //Developer note : Always test the mediator and enrollee applications on different devices. Running
- // Mediator and Enrollee in same device will result in returning the same device as already owned.
- /*result = OCSecure::discoverOwnedDevices(ES_SEC_DISCOVERY_TIMEOUT,
+ result = OCSecure::discoverOwnedDevices(ES_SEC_DISCOVERY_TIMEOUT,
pOwnedDevList);
if (result != OC_STACK_OK)
{
OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "Owned Discovery failed.");
- ownershipStatus = DEVICE_NOT_OWNED;
//Throw exception
throw ESPlatformException(result);
- return ownershipStatus;
}
else if (pOwnedDevList.size())
{
OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "Found owned devices. Count =%d",
pOwnedDevList.size());
std::shared_ptr< OC::OCSecureResource > ownedDevice = getEnrollee(pOwnedDevList);
+
if (ownedDevice)
{
- ownershipStatus = DEVICE_OWNED;
- return ownershipStatus;
+ std::shared_ptr< SecProvisioningStatus > securityProvisioningStatus =
+ std::make_shared< SecProvisioningStatus >(ownedDevice->getDeviceID(), ES_OK);
+ m_securityProvStatusCb(securityProvisioningStatus);
+ return;
}
}
- else
- {
- OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "No owned devices found.");
- ownershipStatus = DEVICE_NOT_OWNED;
- }*/
result = OCSecure::discoverUnownedDevices(ES_SEC_DISCOVERY_TIMEOUT, pUnownedDevList);
if (result != OC_STACK_OK)
{
OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "UnOwned Discovery failed.");
- ownershipStatus = DEVICE_NOT_OWNED;
//Throw exception
throw ESPlatformException(result);
}
&EnrolleeSecurity::ownershipTransferCb, this, std::placeholders::_1,
std::placeholders::_2);
- if (m_unownedDevice->doOwnershipTransfer(ownershipTransferCb) != OC_STACK_OK)
+ result = m_unownedDevice->doOwnershipTransfer(ownershipTransferCb);
+ if (result != OC_STACK_OK)
{
OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "OwnershipTransferCallback is failed");
- ownershipStatus = DEVICE_NOT_OWNED;
- return ownershipStatus;
+ throw ESPlatformException(result);
}
- ownershipStatus = DEVICE_NOT_OWNED;
+ }
+ else
+ {
+ OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "No matched unowned devices found.");
+ throw ESException("No matched unowned devices found.");
}
}
else
{
- OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "No unSecure devices found.");
- ownershipStatus = DEVICE_NOT_OWNED;
+ OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "No unowned devices found.");
+ throw ESException("No unowned devices found.");
+ }
+ }
+
+ ESResult EnrolleeSecurity::performACLProvisioningForCloudServer(std::string cloudUuid)
+ {
+ ESResult res = ESResult::ES_ERROR;
+
+ OicUuid_t uuid;
+ convertStringToUUID(uuid, cloudUuid);
+
+ // Need to discover Owned device in a given network, again
+ OC::DeviceList_t pOwnedDevList;
+ std::shared_ptr< OC::OCSecureResource > ownedDevice = NULL;
+
+ pOwnedDevList.clear();
+
+ OCStackResult result;
- return ownershipStatus;
+ result = OCSecure::discoverOwnedDevices(ES_SEC_DISCOVERY_TIMEOUT,
+ pOwnedDevList);
+ if (result != OC_STACK_OK)
+ {
+ OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "Owned Discovery failed.");
+ //Throw exception
+ throw ESPlatformException(result);
}
+ else if (pOwnedDevList.size())
+ {
+ OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "Found owned devices. Count =%d",
+ pOwnedDevList.size());
+ ownedDevice = getEnrollee(pOwnedDevList);
- return ownershipStatus;
+ if (!ownedDevice)
+ {
+ OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "Not found owned devices.");
+ return res;
+ }
+ }
+ else
+ {
+ OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "Not found owned devices.");
+ return res;
+ }
+
+ // Create Acl for Cloud Server to be provisioned to Enrollee
+ OicSecAcl_t* acl = createAcl(uuid);
+ if(!acl)
+ {
+ OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "createAcl error return");
+ return res;
+ }
+
+ OC::ResultCallBack aclProvisioningCb = std::bind(
+ &EnrolleeSecurity::ACLProvisioningCb, this, std::placeholders::_1,
+ std::placeholders::_2);
+ // ACL provisioning to Enrollee
+ OCStackResult rst = ownedDevice->provisionACL(acl, aclProvisioningCb);
+ if(OC_STACK_OK != rst)
+ {
+ OIC_LOG_V(ERROR, ENROLEE_SECURITY_TAG, "OCProvisionACL API error: %d", rst);
+ return res;
+ }
+
+ std::unique_lock<std::mutex> lck(m_mtx);
+ m_cond.wait_for(lck, std::chrono::seconds(ES_SEC_DISCOVERY_TIMEOUT));
+
+ if(aclResult)
+ {
+ res = ESResult::ES_OK;
+ }
+
+ return res;
+ }
+
+ std::string EnrolleeSecurity::getUUID() const
+ {
+ return m_ocResource->sid();
+ };
+
+ OicSecAcl_t* EnrolleeSecurity::createAcl(OicUuid_t cloudUuid)
+ {
+ // allocate memory for |acl| struct
+ OicSecAcl_t* acl = (OicSecAcl_t*) OICCalloc(1, sizeof(OicSecAcl_t));
+ if(!acl)
+ {
+ OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "createAcl: OICCalloc error return");
+ return NULL; // not need to 'goto' |ERROR| before allocating |acl|
+ }
+ OicSecAce_t* ace = (OicSecAce_t*) OICCalloc(1, sizeof(OicSecAce_t));
+ if(!ace)
+ {
+ OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "createAcl: OICCalloc error return");
+ return NULL; // not need to 'goto' |ERROR| before allocating |acl|
+ }
+ LL_APPEND(acl->aces, ace);
+
+ memcpy(&ace->subjectuuid, &cloudUuid, UUID_LENGTH);
+
+ OicSecRsrc_t* rsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+ if(!rsrc)
+ {
+ OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "createAcl: OICCalloc error return");
+ OCDeleteACLList(acl);
+ return NULL;
+ }
+
+ char href[] = "*";
+ size_t len = strlen(href)+1; // '1' for null termination
+ rsrc->href = (char*) OICCalloc(len, sizeof(char));
+ if(!rsrc->href)
+ {
+ OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "createAcl: OICCalloc error return");
+ OCDeleteACLList(acl);
+ return NULL;
+ }
+ OICStrcpy(rsrc->href, len, href);
+
+ size_t arrLen = 1;
+ rsrc->typeLen = arrLen;
+ rsrc->types = (char**)OICCalloc(arrLen, sizeof(char*));
+ rsrc->interfaces = (char**)OICCalloc(arrLen, sizeof(char*));
+ rsrc->types[0] = OICStrdup("rt"); // ignore
+ rsrc->interfaces[0] = OICStrdup("if"); // ignore
+
+ LL_APPEND(ace->resources, rsrc);
+
+ ace->permission = 31; // R/W/U/D
+
+ return acl;
+ }
+
+ void EnrolleeSecurity::ACLProvisioningCb(PMResultList_t *result, int hasError)
+ {
+ if (hasError)
+ {
+ OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "Error in provisioning operation!");
+ aclResult = false;
+ }
+ else
+ {
+ OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "Received provisioning results: ");
+
+ std::string devUuid;
+ for (unsigned int i = 0; i < result->size(); i++)
+ {
+ convertUUIDToString(result->at(i).deviceId, devUuid);
+ OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "Result is = %d for device %s",
+ result->at(i).res, devUuid.c_str());
+ }
+ delete result;
+ aclResult = true;
+ }
+ m_cond.notify_all();
}
}
}
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "RemoteEnrollee.h"
-#include "RemoteEnrolleeResource.h"
+#include "EnrolleeResource.h"
+#include "CloudResource.h"
+#include "OCPlatform.h"
#include "ESException.h"
#include "logger.h"
+#include "OCResource.h"
#ifdef __WITH_DTLS__
#include "EnrolleeSecurity.h"
+#include "base64.h"
+#include "oic_malloc.h"
#endif //__WITH_DTLS
namespace OIC
{
- #define ES_REMOTE_ENROLLEE_TAG "ES_REMOTE_ENROLLEE"
-
namespace Service
{
- RemoteEnrollee::RemoteEnrollee(const ProvConfig& provConfig, const WiFiOnboadingConnection& connection) :
- m_ProvConfig(provConfig), m_wifiOnboardingconn(connection)
- {
- m_currentESState = CurrentESState::ES_UNKNOWN;
- m_isSecured = connection.isSecured; //enrolleeNWProvInfo.needSecuredEasysetup;
+ static const char ES_BASE_RES_URI[] = "/oic/res";
+ #define ES_REMOTE_ENROLLEE_TAG "ES_REMOTE_ENROLLEE"
+ #define DISCOVERY_TIMEOUT 5
- OIC_LOG ( DEBUG, ES_REMOTE_ENROLLEE_TAG, "Inside RemoteEnrollee constr");
+ RemoteEnrollee::RemoteEnrollee(std::shared_ptr< OC::OCResource > resource)
+ {
+ m_ocResource = resource;
+ m_enrolleeResource = std::make_shared<EnrolleeResource>(m_ocResource);
+ m_securityProvStatusCb = nullptr;
+ m_getConfigurationStatusCb = nullptr;
+ m_securityPinCb = nullptr;
+ m_secProvisioningDbPathCb = nullptr;
+ m_devicePropProvStatusCb = nullptr;
+ m_cloudPropProvStatusCb = nullptr;
+
+ m_deviceId = resource->sid();
}
#ifdef __WITH_DTLS__
}
#endif //__WITH_DTLS__
- void RemoteEnrollee::registerEasySetupStatusHandler(EasySetupStatusCB callback)
+ void RemoteEnrollee::securityStatusHandler(
+ std::shared_ptr< SecProvisioningStatus > status)
{
- OIC_LOG ( DEBUG, ES_REMOTE_ENROLLEE_TAG, "Entered registerStatusHandler");
- if(!callback)
- {
- throw ESInvalidParameterException("Callback is empty");
- }
+ OIC_LOG_V(DEBUG, ES_REMOTE_ENROLLEE_TAG, "easySetupStatusCallback status is, UUID = %s,"
+ "Status = %d", status->getDeviceUUID().c_str(),
+ status->getESResult());
- if (m_easySetupStatusCb)
+ if(status->getESResult() == ES_OK)
{
- throw ESBadRequestException("Callback handler already registered");
+ OIC_LOG(DEBUG, ES_REMOTE_ENROLLEE_TAG, "Ownership and ACL are successful. "
+ "Continue with Network information provisioning");
+
+ OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Before ProvisionEnrollee");
+
+ m_securityProvStatusCb(status);
}
else
{
- m_easySetupStatusCb = callback;
+ OIC_LOG(DEBUG, ES_REMOTE_ENROLLEE_TAG, "Ownership and ACL are fail");
- m_remoteResource = std::make_shared< RemoteEnrolleeResource >(m_ProvConfig, m_wifiOnboardingconn);
+ m_securityProvStatusCb(status);
}
}
- void RemoteEnrollee::easySetupSecurityStatusCallback(
- std::shared_ptr< SecProvisioningResult > secProvisioningResult)
+ void RemoteEnrollee::getStatusHandler(std::shared_ptr< GetEnrolleeStatus > status)
{
- OIC_LOG_V(DEBUG, ES_REMOTE_ENROLLEE_TAG, "easySetupStatusCallback status is, UUID = %s, "
- "Status = %d", secProvisioningResult->getDeviceUUID().c_str(),
- secProvisioningResult->getResult());
+ OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Entering getStatusHandler");
- if(secProvisioningResult->getResult() == ES_OK)
- {
- OIC_LOG(DEBUG, ES_REMOTE_ENROLLEE_TAG, "Ownership and ACL are successful. "
- "Continue with Network information provisioning");
+ OIC_LOG_V(DEBUG,ES_REMOTE_ENROLLEE_TAG,"getStatusHandler = %d", status->getESResult());
- m_currentESState = CurrentESState::ES_OWNED;
+ m_getStatusCb(status);
+ }
- OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Before ProvisionEnrollee");
+ void RemoteEnrollee::getConfigurationStatusHandler (
+ std::shared_ptr< GetConfigurationStatus > status)
+ {
+ OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Entering getConfigurationStatusHandler");
- RemoteEnrolleeResource::ProvStatusCb provStatusCb = std::bind(
- &RemoteEnrollee::provisioningStatusHandler, this, std::placeholders::_1);
+ OIC_LOG_V(DEBUG,ES_REMOTE_ENROLLEE_TAG,"GetConfigurationStatus = %d",
+ status->getESResult());
- m_remoteResource->registerProvStatusCallback(provStatusCb);
- m_remoteResource->provisionEnrollee();
- }
- else
+ m_getConfigurationStatusCb(status);
+ }
+
+ void RemoteEnrollee::devicePropProvisioningStatusHandler(
+ std::shared_ptr< DevicePropProvisioningStatus > status)
+ {
+ OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Entering DevicePropProvisioningStatusHandler");
+
+ OIC_LOG_V(DEBUG,ES_REMOTE_ENROLLEE_TAG,"ProvStatus = %d", status->getESResult());
+
+ m_devicePropProvStatusCb(status);
+
+ return;
+ }
+
+ void RemoteEnrollee::cloudPropProvisioningStatusHandler (
+ std::shared_ptr< CloudPropProvisioningStatus > status)
+ {
+ OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Entering cloudPropProvisioningStatusHandler");
+
+ OIC_LOG_V(DEBUG,ES_REMOTE_ENROLLEE_TAG,"CloudProvStatus = %d",
+ status->getESCloudState());
+
+ m_cloudPropProvStatusCb(status);
+ return;
+ }
+
+ void RemoteEnrollee::onDeviceDiscovered(std::shared_ptr<OC::OCResource> resource)
+ {
+ OIC_LOG (DEBUG, ES_REMOTE_ENROLLEE_TAG, "onDeviceDiscovered");
+
+ std::string resourceURI;
+ std::string hostAddress;
+ std::string hostDeviceID;
+
+ try
{
- OIC_LOG(DEBUG, ES_REMOTE_ENROLLEE_TAG, "Ownership and ACL are successful");
- std::shared_ptr< EasySetupStatus > easySetupStatus = nullptr;
- easySetupStatus = std::make_shared< EasySetupStatus >(DEVICE_NOT_PROVISIONED,
- m_ProvConfig);
- if (m_easySetupStatusCb)
+ if(resource)
{
- if (easySetupStatus)
+ if(!(resource->connectivityType() & CT_ADAPTER_TCP))
{
- m_easySetupStatusCb(easySetupStatus);
- }
- else
- {
- m_easySetupStatusCb(nullptr);
+ // Get the resource URI
+ resourceURI = resource->uri();
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_TAG,
+ "URI of the resource: %s", resourceURI.c_str());
+
+ // Get the resource host address
+ hostAddress = resource->host();
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_TAG,
+ "Host address of the resource: %s", hostAddress.c_str());
+
+ hostDeviceID = resource->sid();
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_TAG,
+ "Host DeviceID of the resource: %s", hostDeviceID.c_str());
+
+ if(!m_deviceId.empty() && m_deviceId == hostDeviceID)
+ {
+ OIC_LOG (DEBUG, ES_REMOTE_ENROLLEE_TAG, "Find matched CloudResource");
+ m_ocResource = resource;
+ m_discoveryResponse = true;
+ m_cond.notify_all();
+ }
}
}
}
+ catch(std::exception& e)
+ {
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_TAG,
+ "Exception in foundResource: %s", e.what());
+ }
}
- void RemoteEnrollee::provisioningStatusHandler(
- std::shared_ptr< ProvisioningStatus > provStatus)
+ ESResult RemoteEnrollee::discoverResource()
{
- OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Entering ProvisioningStatusHandler");
+ OIC_LOG(DEBUG, ES_REMOTE_ENROLLEE_TAG, "Enter discoverResource");
+
+ std::string query("");
+ query.append(ES_BASE_RES_URI);
+ query.append("?rt=");
+ query.append(OC_RSRVD_ES_RES_TYPE_PROV);
+
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_TAG, "query = %s", query.c_str());
- OIC_LOG_V(DEBUG,ES_REMOTE_ENROLLEE_TAG,"ProvStatus = %d", provStatus->getESResult());
+ m_discoveryResponse = false;
- std::shared_ptr< EasySetupStatus > easySetupStatus = nullptr;
+ std::function< void (std::shared_ptr<OC::OCResource>) > onDeviceDiscoveredCb =
+ std::bind(&RemoteEnrollee::onDeviceDiscovered, this,
+ std::placeholders::_1);
+ OCStackResult result = OC::OCPlatform::findResource("", query, CT_DEFAULT,
+ onDeviceDiscoveredCb);
- if (m_isSecured)
+ if (result != OCStackResult::OC_STACK_OK)
{
- if (m_currentESState >= CurrentESState::ES_OWNED)
- {
- goto CALLBACK_CHECK;
- }
- else
- {
- goto FAILURE;
- }
+ OIC_LOG(ERROR,ES_REMOTE_ENROLLEE_TAG,
+ "Failed discoverResource");
+ return ES_ERROR;
}
- else
+
+ std::unique_lock<std::mutex> lck(m_discoverymtx);
+ m_cond.wait_for(lck, std::chrono::seconds(DISCOVERY_TIMEOUT));
+
+ if (!m_discoveryResponse)
{
- goto CALLBACK_CHECK;
+ OIC_LOG(ERROR,ES_REMOTE_ENROLLEE_TAG,
+ "Failed discoverResource because timeout");
+ return ES_ERROR;
}
+ return ES_OK;
+ }
- CALLBACK_CHECK:
+ void RemoteEnrollee::provisionSecurity(SecurityProvStatusCb callback)
+ {
+#ifdef __WITH_DTLS__
+ m_securityProvStatusCb = callback;
+
+ SecurityProvStatusCb securityProvStatusCb = std::bind(
+ &RemoteEnrollee::securityStatusHandler,
+ this,
+ std::placeholders::_1);
+ //TODO : DBPath is passed empty as of now. Need to take dbpath from application.
+ m_enrolleeSecurity = std::make_shared <EnrolleeSecurity> (m_ocResource, "");
- if (provStatus->getESResult() == ES_OK)
+ m_enrolleeSecurity->registerCallbackHandler(securityProvStatusCb, m_securityPinCb,
+ m_secProvisioningDbPathCb);
+
+ try
{
- if (provStatus->getESState() >= ESState::ES_PROVISIONED_ALREADY)
- {
- easySetupStatus = std::make_shared< EasySetupStatus >(DEVICE_PROVISIONED,
- m_ProvConfig);
- }
- else
- {
- easySetupStatus = std::make_shared< EasySetupStatus >(DEVICE_NOT_PROVISIONED,
- m_ProvConfig);
- }
+ m_enrolleeSecurity->performOwnershipTransfer();
}
- else
+ catch (const std::exception& e)
{
- easySetupStatus = std::make_shared< EasySetupStatus >(DEVICE_NOT_PROVISIONED,
- m_ProvConfig);
+ OIC_LOG_V(ERROR, ES_REMOTE_ENROLLEE_TAG,
+ "Exception for performOwnershipTransfer : %s", e.what());
+
+ OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Fail performOwnershipTransfer");
+ std::shared_ptr< SecProvisioningStatus > securityProvisioningStatus =
+ std::make_shared< SecProvisioningStatus >
+ (m_enrolleeSecurity->getUUID(), ES_ERROR);
+ m_securityProvStatusCb(securityProvisioningStatus);
+ return ;
}
+#else
+ OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Mediator is unsecured.");
- if (m_easySetupStatusCb)
+ std::shared_ptr< SecProvisioningStatus > securityProvisioningStatus =
+ std::make_shared< SecProvisioningStatus >
+ ("", ES_UNSUPPORTED_OPERATION);
+ m_securityProvStatusCb(securityProvisioningStatus);
+#endif
+ }
+
+ void RemoteEnrollee::getStatus(GetStatusCb callback)
+ {
+ if(!callback)
{
- if (easySetupStatus)
- {
- m_easySetupStatusCb(easySetupStatus);
- }
- else
- {
- m_easySetupStatusCb(nullptr);
- }
+ throw ESInvalidParameterException("Callback is empty");
}
- return;
+ if (m_enrolleeResource == nullptr)
+ {
+ throw ESBadRequestException ("Device not created");
+ }
+
+ m_getStatusCb = callback;
- FAILURE:
+ GetStatusCb getStatusCb = std::bind(
+ &RemoteEnrollee::getStatusHandler, this, std::placeholders::_1);
+ m_enrolleeResource->registerGetStatusCallback(getStatusCb);
+ m_enrolleeResource->getStatus();
- easySetupStatus = std::make_shared< EasySetupStatus >(DEVICE_NOT_PROVISIONED,
- m_ProvConfig);
+ }
- if (easySetupStatus)
+ void RemoteEnrollee::getConfiguration(GetConfigurationStatusCb callback)
+ {
+ if(!callback)
{
- m_easySetupStatusCb(easySetupStatus);
+ throw ESInvalidParameterException("Callback is empty");
}
- else
+
+ if (m_enrolleeResource == nullptr)
{
- m_easySetupStatusCb(nullptr);
+ throw ESBadRequestException ("Device not created");
}
- return;
+
+ m_getConfigurationStatusCb = callback;
+
+ GetConfigurationStatusCb getConfigurationStatusCb = std::bind(
+ &RemoteEnrollee::getConfigurationStatusHandler, this, std::placeholders::_1);
+ m_enrolleeResource->registerGetConfigurationStatusCallback(getConfigurationStatusCb);
+ m_enrolleeResource->getConfiguration();
}
- void RemoteEnrollee::startProvisioning()
+ void RemoteEnrollee::provisionDeviceProperties(const DeviceProp& deviceProp,
+ DevicePropProvStatusCb callback)
{
- OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Entering startProvisioning");
- if (m_remoteResource == nullptr)
+ OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Enter provisionDeviceProperties");
+
+ if(!callback)
+ {
+ throw ESInvalidParameterException("Callback is empty");
+ }
+
+ m_devicePropProvStatusCb = callback;
+
+ if (m_enrolleeResource == nullptr)
{
throw ESBadRequestException ("Device not created");
}
+ if(deviceProp.getSsid().empty())
+ {
+ throw ESBadRequestException ("Invalid Provisiong Data.");
+ }
+
+ DevicePropProvStatusCb devicePropProvStatusCb = std::bind(
+ &RemoteEnrollee::devicePropProvisioningStatusHandler,
+ this, std::placeholders::_1);
+
+ m_enrolleeResource->registerDevicePropProvStatusCallback(devicePropProvStatusCb);
+ m_enrolleeResource->provisionEnrollee(deviceProp);
+ }
+
+ void RemoteEnrollee::initCloudResource()
+ {
ESResult result = ES_ERROR;
- result = m_remoteResource->constructResourceObject();
+ if (m_cloudResource != nullptr)
+ {
+ throw ESBadRequestException ("Already created");
+ }
+
+ result = discoverResource();
if (result == ES_ERROR)
{
OIC_LOG(ERROR,ES_REMOTE_ENROLLEE_TAG,
- "Failed to create device using constructResourceObject");
- throw ESBadRequestException ("Device not created");
+ "Failed to create resource object using discoverResource");
+ throw ESBadRequestException ("Resource object not created");
}
- m_currentESState = CurrentESState::ES_ONBOARDED;
-
-#ifdef __WITH_DTLS__
- if (m_isSecured && m_currentESState < CurrentESState::ES_OWNED)
+ else
{
- EnrolleeSecStatusCb securityProvStatusCb = std::bind(
- &RemoteEnrollee::easySetupSecurityStatusCallback,
- this,
- std::placeholders::_1);
- //TODO : DBPath is passed empty as of now. Need to take dbpath from application.
- m_enrolleeSecurity = std::make_shared <EnrolleeSecurity> (m_remoteResource, "");
-
- m_enrolleeSecurity->registerCallbackHandler(securityProvStatusCb,
- m_securityPinCb, m_secProvisioningDbPathCb);
-
- try
+ if(m_ocResource != nullptr)
{
- EasySetupState easySetupState = m_enrolleeSecurity->performOwnershipTransfer();
- if (easySetupState == DEVICE_NOT_OWNED)
- {
- OIC_LOG_V(DEBUG, ES_REMOTE_ENROLLEE_TAG,
- "performOwnershipTransfer returned : %d",
- easySetupState);
- return;
- }
- else if (easySetupState == DEVICE_OWNED)
- {
- OIC_LOG_V(DEBUG, ES_REMOTE_ENROLLEE_TAG,
- "performOwnershipTransfer returned : %d",
- easySetupState);
- OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Before ProvisionEnrollee");
+ m_cloudResource = std::make_shared<CloudResource>(m_ocResource);
- RemoteEnrolleeResource::ProvStatusCb provStatusCb = std::bind(
- &RemoteEnrollee::provisioningStatusHandler,
- this, std::placeholders::_1);
+ std::shared_ptr< CloudPropProvisioningStatus > provStatus = std::make_shared<
+ CloudPropProvisioningStatus >(ESResult::ES_OK,
+ ESCloudProvState::ES_CLOUD_ENROLLEE_FOUND);
- m_remoteResource->registerProvStatusCallback(provStatusCb);
- m_remoteResource->provisionEnrollee();
- }
+ m_cloudPropProvStatusCb(provStatus);
}
- catch (OCException & e)
+ else
{
- OIC_LOG_V(ERROR, ES_REMOTE_ENROLLEE_TAG,
- "Exception for performOwnershipTransfer : %s", e.reason().c_str());
- return ;
+ throw ESBadGetException ("Resource handle is invalid");
}
}
-#else
- OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Before ProvisionEnrollee");
-
- RemoteEnrolleeResource::ProvStatusCb provStatusCb = std::bind(
- &RemoteEnrollee::provisioningStatusHandler, this, std::placeholders::_1);
-
- m_remoteResource->registerProvStatusCallback(provStatusCb);
- m_remoteResource->provisionEnrollee();
-#endif
}
- void RemoteEnrollee::stopProvisioning()
+ void RemoteEnrollee::provisionCloudProperties(const CloudProp& cloudProp,
+ CloudPropProvStatusCb callback)
{
- m_currentESState = CurrentESState::ES_UNKNOWN;
+ OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Enter provisionCloudProperties");
+ ESResult res = ES_OK;
- m_remoteResource->unprovisionEnrollee();
- }
+ if(!callback)
+ {
+ throw ESInvalidParameterException("Callback is empty");
+ }
- bool RemoteEnrollee::isEnrolleeProvisioned()
- {
- if(m_currentESState >= CurrentESState::ES_PROVISIONED)
+ m_cloudPropProvStatusCb = callback;
+
+ if(cloudProp.getAuthCode().empty() ||
+ cloudProp.getAuthProvider().empty() ||
+ cloudProp.getCiServer().empty())
{
- return true;
+ throw ESBadRequestException ("Invalid Cloud Provisiong Info.");
}
- else
+
+ try
{
- return false;
+ initCloudResource();
}
- }
- ProvConfig RemoteEnrollee::getProvConfig ()
- {
- return m_ProvConfig;
- }
+ catch (const std::exception& e)
+ {
+ OIC_LOG_V(ERROR, ES_REMOTE_ENROLLEE_TAG,
+ "Exception caught in provisionCloudProperties = %s", e.what());
+
+ std::shared_ptr< CloudPropProvisioningStatus > provStatus = std::make_shared<
+ CloudPropProvisioningStatus >(ESResult::ES_ERROR,
+ ESCloudProvState::ES_CLOUD_ENROLLEE_NOT_FOUND);
+ m_cloudPropProvStatusCb(provStatus);
+ return;
+ }
+
+#ifdef __WITH_DTLS__
+ try
+ {
+ m_enrolleeSecurity = std::make_shared <EnrolleeSecurity> (m_ocResource, "");
+
+ if(cloudProp.getCloudID().empty())
+ {
+ throw ESBadRequestException("Invalid Cloud Server UUID.");
+ }
+
+ res = m_enrolleeSecurity->performACLProvisioningForCloudServer(cloudProp.getCloudID());
+
+ if(res == ESResult::ES_ERROR)
+ {
+ throw ESBadRequestException("Error in provisioning operation!");
+ }
+
+ }
- WiFiOnboadingConnection RemoteEnrollee::getOnboardConn()
- {
- return m_wifiOnboardingconn;
- }
+ catch (const std::exception& e)
+ {
+ OIC_LOG_V(ERROR, ES_REMOTE_ENROLLEE_TAG,
+ "Exception caught in provisionCloudProperties = %s", e.what());
+
+ m_cloudResource = nullptr;
+
+ std::shared_ptr< CloudPropProvisioningStatus > provStatus = std::make_shared<
+ CloudPropProvisioningStatus >(ESResult::ES_ERROR,
+ ESCloudProvState::ES_CLOUD_PROVISIONING_ERROR);
+ m_cloudPropProvStatusCb(provStatus);
+ return;
+ }
+#endif
+ if (m_cloudResource == nullptr)
+ {
+ throw ESBadRequestException ("Cloud Resource not created");
+ }
+
+ CloudPropProvStatusCb cloudPropProvStatusCb = std::bind(
+ &RemoteEnrollee::cloudPropProvisioningStatusHandler,
+ this, std::placeholders::_1);
+
+ m_cloudResource->registerCloudPropProvisioningStatusCallback(cloudPropProvStatusCb);
+ m_cloudResource->provisionEnrollee(cloudProp);
+ }
}
}
+++ /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 <functional>
-#include <time.h>
-
-#include "RemoteEnrolleeResource.h"
-
-#include "OCPlatform.h"
-#include "ESException.h"
-#include "OCResource.h"
-#include "logger.h"
-
-namespace OIC
-{
- namespace Service
- {
- #define ES_REMOTE_ENROLLEE_RES_TAG "ES_REMOTE_ENROLLEE_RES"
- #define DISCOVERY_TIMEOUT 5
-
- static const char ES_BASE_RES_URI[] = "/oic/res";
- static const char ES_PROV_RES_URI[] = "/oic/prov";
- static const char ES_PROV_RES_TYPE[] = "oic.r.prov";
-
- RemoteEnrolleeResource::RemoteEnrolleeResource(const ProvConfig &provConfig,
- const WiFiOnboadingConnection &onboardingconn)
- {
- m_ProvConfig = provConfig;
- m_wifiOnboardingconn = onboardingconn;
- m_discoveryResponse = false;
- }
-
- void RemoteEnrolleeResource::triggerNetworkConnectionCb(
- const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep,
- const int eCode)
- {
- OC_UNUSED(rep);
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "checkProvInformationCb : %s, eCode = %d",
- rep.getUri().c_str(),
- eCode);
-
- if (eCode != 0)
- {
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
- "triggerNetworkConnectionCb : Trigger action failed ");
- std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
- ProvisioningStatus >(ESResult::ES_ERROR, ESState::ES_PROVISIONING_ERROR);
- m_provStatusCb(provStatus);
- return;
- }
- else
- {
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
- "triggerNetworkConnectionCb : Provisioning is success ");
- std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
- ProvisioningStatus >(ESResult::ES_OK, ESState::ES_PROVISIONING_SUCCESS);
- m_provStatusCb(provStatus);
- return;
- }
- }
-
- void RemoteEnrolleeResource::triggerNetworkConnection()
- {
- if (m_ocResource == nullptr)
- {
- throw ESBadRequestException("Resource is not initialized");
- }
-
- OCRepresentation provisioningRepresentation;
-
- provisioningRepresentation.setValue(OC_RSRVD_ES_TR, 1);
-
- m_ocResource->post(provisioningRepresentation, QueryParamsMap(),
- std::function<
- void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
- const int eCode) >(
- std::bind(&RemoteEnrolleeResource::triggerNetworkConnectionCb, this,
- std::placeholders::_1, std::placeholders::_2,
- std::placeholders::_3)));
- }
-
- void RemoteEnrolleeResource::checkProvInformationCb(const HeaderOptions& /*headerOptions*/,
- const OCRepresentation& rep, const int eCode)
- {
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "checkProvInformationCb : %s, eCode = %d",
- rep.getUri().c_str(),
- eCode);
-
- if (eCode != 0)
- {
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
- "checkProvInformationCb : Provisioning is failed ");
- std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
- ProvisioningStatus >(ESResult::ES_ERROR, ESState::ES_PROVISIONING_ERROR);
- m_provStatusCb(provStatus);
- return;
- }
-
- int ps = -1;
-
- rep.getValue(OC_RSRVD_ES_PS, ps);
-
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "checkProvInformationCb : ps - %d", ps);
-
- //Provisioning status check
- if (ps == ES_PS_PROVISIONING_COMPLETED)
- {
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
- "checkProvInformationCb : Provisioning is success. "
- "Now trigger network connection ");
-
- #ifdef REMOTE_ARDUINO_ENROLEE
- std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
- ProvisioningStatus >(ESResult::ES_OK, ESState::ES_PROVISIONING_SUCCESS);
- m_provStatusCb(provStatus);
- #endif
-
- triggerNetworkConnection();
- return;
- }
- else
- {
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
- "checkProvInformationCb : Provisioning is failed ");
- std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
- ProvisioningStatus >(ESResult::ES_ERROR, ESState::ES_PROVISIONING_ERROR);
- m_provStatusCb(provStatus);
- return;
- }
- }
-
- void RemoteEnrolleeResource::getProvStatusResponse(const HeaderOptions& /*headerOptions*/,
- const OCRepresentation& rep, const int eCode)
- {
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "getProvStatusResponse : %s, eCode = %d",
- rep.getUri().c_str(),
- eCode);
-
- if (eCode != 0)
- {
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
- "getProvStatusResponse : Provisioning is failed ");
- std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
- ProvisioningStatus >(ESResult::ES_ERROR, ESState::ES_PROVISIONING_ERROR);
- m_provStatusCb(provStatus);
- return;
- }
-
- int ps = -1;
-
- rep.getValue(OC_RSRVD_ES_PS, ps);
-
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "getProvStatusResponse : ps - %d",
- ps);
-
- if (ps == ES_PS_NEED_PROVISIONING) //Indicates the need for provisioning
- {
- OCRepresentation provisioningRepresentation;
-
- provisioningRepresentation.setValue(OC_RSRVD_ES_TNN,
- std::string(m_ProvConfig.provData.WIFI.ssid));
- provisioningRepresentation.setValue(OC_RSRVD_ES_CD,
- std::string(m_ProvConfig.provData.WIFI.pwd));
-
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "getProvStatusResponse : ssid - %s",
- m_ProvConfig.provData.WIFI.ssid);
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "getProvStatusResponse : pwd - %s",
- m_ProvConfig.provData.WIFI.pwd);
-
- m_ocResource->post(provisioningRepresentation, QueryParamsMap(),
- std::function<
- void(const HeaderOptions& headerOptions,
- const OCRepresentation& rep, const int eCode) >(
- std::bind(&RemoteEnrolleeResource::checkProvInformationCb, this,
- std::placeholders::_1, std::placeholders::_2,
- std::placeholders::_3)));
- }
- else if (ps == ES_PS_PROVISIONING_COMPLETED) //Indicates that provisioning is completed
- {
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
- "getProvStatusResponse : Provisioning is successful");
- std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
- ProvisioningStatus >(ESResult::ES_OK, ESState::ES_PROVISIONED_ALREADY);
- m_provStatusCb(provStatus);
- }
- }
-
- void RemoteEnrolleeResource::registerProvStatusCallback(ProvStatusCb provStatusCb)
- {
- m_provStatusCb = provStatusCb;
- }
-
- ESResult RemoteEnrolleeResource::ESDiscoveryTimeout(unsigned short waittime)
- {
- struct timespec startTime;
- startTime.tv_sec=0;
- startTime.tv_sec=0;
- struct timespec currTime;
- currTime.tv_sec=0;
- currTime.tv_nsec=0;
-
- ESResult res = ES_OK;
- #ifdef _POSIX_MONOTONIC_CLOCK
- int clock_res = clock_gettime(CLOCK_MONOTONIC, &startTime);
- #else
- int clock_res = clock_gettime(CLOCK_REALTIME, &startTime);
- #endif
-
- if (0 != clock_res)
- {
- return ES_ERROR;
- }
-
- while (ES_OK == res || m_discoveryResponse == false)
- {
- #ifdef _POSIX_MONOTONIC_CLOCK
- clock_res = clock_gettime(CLOCK_MONOTONIC, &currTime);
- #else
- clock_res = clock_gettime(CLOCK_REALTIME, &currTime);
- #endif
-
- if (0 != clock_res)
- {
- return ES_ERROR;
- }
- long elapsed = (currTime.tv_sec - startTime.tv_sec);
- if (elapsed > waittime)
- {
- return ES_OK;
- }
- if (m_discoveryResponse)
- {
- res = ES_OK;
- }
- }
- return res;
- }
-
- void RemoteEnrolleeResource::onDeviceDiscovered(std::shared_ptr<OC::OCResource> resource)
- {
- OIC_LOG (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "onDeviceDiscovered");
-
- std::string resourceURI;
- std::string hostAddress;
- try
- {
- if(resource)
- {
- // Get the resource URI
- resourceURI = resource->uri();
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
- "URI of the resource: %s", resourceURI.c_str());
-
- // Get the resource host address
- hostAddress = resource->host();
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
- "Host address of the resource: %s", hostAddress.c_str());
-
- /*
- * Easysetup is always performed with a single Enrollee device and
- * in a private network (SoftAP or BLE), so the assumption is that
- * only the intended device will respond for the discovery.
- * With the above assumption the below two statements are written.
- */
- m_ocResource = resource;
- m_discoveryResponse = true;
- }
- else
- {
- OIC_LOG (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "Resource is invalid");
- }
-
- }
- catch(std::exception& e)
- {
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
- "Exception in foundResource: %s", e.what());
- }
- }
-
-
- ESResult RemoteEnrolleeResource::constructResourceObject()
- {
- if (m_ocResource != nullptr)
- {
- throw ESBadRequestException("Remote resource is already created");
- }
-
-#ifdef REMOTE_ARDUINO_ENROLEE
- //This process will create OCResource with port 55555 which is specific
- // to Arduino WiFi enrollee
- try
- {
-
- std::vector< std::string > interface =
- { DEFAULT_INTERFACE};
- std::vector< std::string > resTypes =
- { ES_PROV_RES_TYPE};
-
- OIC_LOG(DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "Before OCPlatform::constructResourceObject");
-
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "m_host = %s",
- m_wifiOnboardingconn.ipAddress);
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "ES_PROV_RES_URI = %s", ES_PROV_RES_URI);
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "m_connectivityType = %d",
- m_ProvConfig.connType);
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "resTypes = %s",
- resTypes.at(0).c_str());
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "interface = %s", interface.at(0).c_str());
-
- std::string host;
- if(m_wifiOnboardingconn.isSecured)
- {
- host.append("coaps://");
- }
- else
- {
- host.append("coap://");
- }
-
- if(m_ProvConfig.connType == CT_ADAPTER_IP)
- {
- // TODO : RemoteEnrollee is current handling easysetup on IP transport.
- // WiFiRemoteEnrollee need to extend RemoteEnrollee for providing IP specific
- // Enrollee easysetup.
-
- host.append(m_wifiOnboardingconn.ipAddress);
- //TODO : If the target Enrollee is not a Arduino Wi-Fi device,
- // then the port number will be found during resource discovery instead of
- // using 55555
- host.append(":55555");
- }
-
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "HOST = %s", host.c_str());
-
- m_ocResource = OC::OCPlatform::constructResourceObject(host,
- ES_PROV_RES_URI,
- m_ProvConfig.connType,
- true,
- resTypes,
- interface);
- OIC_LOG_V(DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
- "created OCResource : %s", m_ocResource->uri().c_str());
-
- return ES_OK;
- }
- catch (OCException & e)
- {
- OIC_LOG_V(ERROR, ES_REMOTE_ENROLLEE_RES_TAG,
- "Exception for constructResourceObject : %s", e.reason().c_str());
- return ES_ERROR;
- }
-#else
- std::string host("");
- std::string query("");
-
- if (m_wifiOnboardingconn.isSecured)
- {
- host.append("coaps://");
- }
- else
- {
- host.append("coap://");
- }
-
- if (m_ProvConfig.connType == CT_ADAPTER_IP)
- {
- // TODO : RemoteEnrollee is current handling easysetup on IP transport.
- // WiFiRemoteEnrollee need to extend RemoteEnrollee for providing IP specific
- // Enrollee easysetup.
-
- host.append(m_wifiOnboardingconn.ipAddress);
- }
-
- query.append(ES_BASE_RES_URI);
- query.append("?rt=");
- query.append(ES_PROV_RES_TYPE);
-
- OIC_LOG(DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "Before OCPlatform::constructResourceObject");
-
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "host = %s",
- host.c_str());
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "query = %s", query.c_str());
- OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "m_connectivityType = %d",
- m_ProvConfig.connType);
-
- m_discoveryResponse = false;
- std::function< void (std::shared_ptr<OC::OCResource>) > onDeviceDiscoveredCb =
- std::bind(&RemoteEnrolleeResource::onDeviceDiscovered, this,
- std::placeholders::_1);
- OCStackResult result = OC::OCPlatform::findResource("", query, CT_DEFAULT,
- onDeviceDiscoveredCb);
-
- if (result != OCStackResult::OC_STACK_OK)
- {
- OIC_LOG(ERROR,ES_REMOTE_ENROLLEE_RES_TAG,
- "Failed to create device using constructResourceObject");
- return ES_ERROR;
- }
-
-
- ESResult foundResponse = ESDiscoveryTimeout (DISCOVERY_TIMEOUT);
-
- if (foundResponse ==ES_ERROR || !m_discoveryResponse)
- {
- OIC_LOG(ERROR,ES_REMOTE_ENROLLEE_RES_TAG,
- "Failed to create device using constructResourceObject");
- return ES_ERROR;
- }
-
- return ES_OK;
-#endif
- }
-
- void RemoteEnrolleeResource::provisionEnrollee()
-
- {
- if (m_ocResource == nullptr)
- {
- throw ESBadRequestException("Resource is not initialized");
- }
-
- OC::QueryParamsMap query;
- OC::OCRepresentation rep;
-
- std::function< OCStackResult(void) > getProvisioingStatus = [&]
- { return m_ocResource->get(m_ocResource->getResourceTypes().at(0),
- m_ocResource->getResourceInterfaces().at(0), query,
- std::function<
- void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
- const int eCode) >(
- std::bind(&RemoteEnrolleeResource::getProvStatusResponse, this,
- std::placeholders::_1, std::placeholders::_2,
- std::placeholders::_3)));
- };
-
- OCStackResult result = getProvisioingStatus();
-
- if (result != OCStackResult::OC_STACK_OK)
- {
- std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
- ProvisioningStatus >(ESResult::ES_ERROR, ESState::ES_PROVISIONING_ERROR);
- m_provStatusCb(provStatus);
- return;
- }
- }
-
- void RemoteEnrolleeResource::unprovisionEnrollee()
- {
- if (m_ocResource == nullptr)
- {
- throw ESBadRequestException("Resource is not initialized");
- }
-
- OCRepresentation provisioningRepresentation;
-
- provisioningRepresentation.setValue(OC_RSRVD_ES_TNN, "");
- provisioningRepresentation.setValue(OC_RSRVD_ES_CD, "");
-
- m_ocResource->post(provisioningRepresentation, QueryParamsMap(),
- std::function<
- void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
- const int eCode) >(
- std::bind(&RemoteEnrolleeResource::checkProvInformationCb, this,
- std::placeholders::_1, std::placeholders::_2,
- std::placeholders::_3)));
- }
- }
-}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 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_MEDIATOR_SIMULATOR_H_
+#define _ES_MEDIATOR_SIMULATOR_H_
+
+#include <iostream>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "oic_malloc.h"
+
+#include "escommon.h"
+#include "ESEnrolleeCommon.h"
+#include "easysetup.h"
+
+#define PROV_RESOURCE_TYPE "ocf.wk.prov"
+
+class ESEnrolleeSimulator
+{
+public:
+ ESEnrolleeSimulator()
+ {
+ };
+ ~ESEnrolleeSimulator() = default;
+
+ ESEnrolleeSimulator(const ESEnrolleeSimulator &) = delete;
+ ESEnrolleeSimulator & operator = (const ESEnrolleeSimulator &) = delete;
+
+ ESEnrolleeSimulator(ESEnrolleeSimulator &&) = delete;
+ ESEnrolleeSimulator & operator = (ESEnrolleeSimulator &&) = delete;
+
+ ESResult initEnrollee()
+ {
+ ESResourceMask resourcemMask = (ESResourceMask)(ES_WIFI_RESOURCE |
+ ES_CLOUD_RESOURCE |
+ ES_DEVCONF_RESOURCE);
+ ESProvisioningCallbacks callbacks;
+
+ callbacks.WiFiProvCb = &onWiFiProvisioning;
+ callbacks.DevConfProvCb = &onDevConfProvisioning;
+ callbacks.CloudDataProvCb = &onCloudProvisioning;
+
+ return ESInitEnrollee(false, resourcemMask, callbacks);
+ }
+
+ ESResult setDeviceProperty()
+ {
+ ESDeviceProperty deviceProperty = {
+ {{WIFI_11G, WiFi_EOF}, WIFI_5G}, {"Test Device"}
+ };
+
+ return ESSetDeviceProperty(&deviceProperty);
+ }
+
+ ESResult setESState()
+ {
+ return ESSetState(ES_STATE_CONNECTED_TO_ENROLLER);
+ }
+
+ ESResult setESErrorCode()
+ {
+ return ESSetErrorCode(ES_ERRCODE_NO_INTERNETCONNECTION);
+ }
+
+private:
+ static void onWiFiProvisioning(ESWiFiProvData* /*data*/)
+ {
+ }
+
+ static void onDevConfProvisioning(ESDevConfProvData* /*data*/)
+ {
+ }
+
+ static void onCloudProvisioning(ESCloudProvData* /*data*/)
+ {
+ }
+};
+
+#endif //_NS_CONSUMER_SIMULATOR_H_
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 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 <gtest/gtest.h>
+#include <HippoMocks/hippomocks.h>
+#include <atomic>
+#include <functional>
+#include <condition_variable>
+#include <mutex>
+#include <chrono>
+
+#include "ESEnrolleeSimulator.h"
+#include "escommon.h"
+#include "ESRichCommon.h"
+#include "EasySetup.h"
+#include "RemoteEnrollee.h"
+
+#include "ESEnrolleeCommon.h"
+#include "easysetup.h"
+
+#define PROV_RESOURCE_TYPE "ocf.wk.prov"
+
+using namespace OC;
+using namespace OIC::Service;
+
+namespace
+{
+ std::atomic_bool g_isStartedStack(false);
+
+ std::chrono::milliseconds g_waitForResponse(1000);
+
+ std::condition_variable responseCon;
+ std::mutex mutexForCondition;
+
+ ESEnrolleeSimulator g_enrolleeSimul;
+ std::shared_ptr<RemoteEnrollee> g_remoteEnrollee;
+}
+
+class TestWithMock: public testing::Test
+{
+public:
+ MockRepository mocks;
+
+protected:
+ virtual ~TestWithMock() noexcept(noexcept(std::declval<Test>().~Test()))
+ {
+ }
+
+ virtual void TearDown()
+ {
+ try
+ {
+ mocks.VerifyAll();
+ }
+ catch (...)
+ {
+ mocks.reset();
+ throw;
+ }
+ }
+};
+
+class EasysetupMediatorTest : public TestWithMock
+{
+public:
+ std::shared_ptr<OC::OCResource> m_enrolleeResource;
+
+public:
+ EasysetupMediatorTest() = default;
+ ~EasysetupMediatorTest() = default;
+
+ std::shared_ptr<OC::OCResource> CreateNotProvResource()
+ {
+ OCConnectivityType connectivityType = CT_DEFAULT;
+ std::vector<std::string> types = {"ocf.wk.notprov"};
+ std::vector<std::string> ifaces = {DEFAULT_INTERFACE};
+
+ return OCPlatform::constructResourceObject("coap://192.168.1.2:5000",
+ "/NotProvisioningResURI",
+ connectivityType,
+ false,
+ types,
+ ifaces);
+ }
+
+ void discoverRemoteEnrollee()
+ {
+ std::string uri = std::string("/oic/res?rt=") + PROV_RESOURCE_TYPE;
+ OC::OCPlatform::findResource("", uri,
+ OCConnectivityType::CT_DEFAULT,
+ std::bind(&EasysetupMediatorTest::discoverRemoteEnrolleeCb,
+ this, std::placeholders::_1));
+
+ std::unique_lock< std::mutex > lock{ mutexForCondition };
+ responseCon.wait_for(lock, g_waitForResponse);
+ }
+
+protected:
+ void SetUp()
+ {
+ TestWithMock::SetUp();
+ if (g_isStartedStack == false)
+ {
+ if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
+ {
+ printf("OCStack init error!!\n");
+ return;
+ }
+ g_enrolleeSimul.initEnrollee();
+ g_isStartedStack = true;
+ }
+ }
+
+ void TearDown()
+ {
+ TestWithMock::TearDown();
+ }
+
+private:
+ void discoverRemoteEnrolleeCb(std::shared_ptr<OC::OCResource> resource)
+ {
+ if(!resource->getResourceTypes().at(0).compare(PROV_RESOURCE_TYPE))
+ {
+ m_enrolleeResource = resource;
+ }
+ }
+};
+
+TEST_F(EasysetupMediatorTest, createremoteenrolleeFailedWithNotProvResource)
+{
+ auto remoteEnrollee = EasySetup::getInstance()->createRemoteEnrollee(CreateNotProvResource());
+
+ EXPECT_EQ(nullptr, remoteEnrollee);
+}
+
+TEST_F(EasysetupMediatorTest, createremoteenrolleeSucceedWithProvResource)
+{
+ discoverRemoteEnrollee();
+ g_remoteEnrollee = EasySetup::getInstance()->createRemoteEnrollee(m_enrolleeResource);
+
+ ASSERT_NE(nullptr, g_remoteEnrollee);
+}
+
+class GetConfigurationTest : public EasysetupMediatorTest
+{
+public:
+ GetConfigurationTest() = default;
+ ~GetConfigurationTest() = default;
+
+ static void onGetConfigurationCb(shared_ptr< GetConfigurationStatus > /*status*/)
+ {
+ }
+
+protected:
+ void SetUp()
+ {
+ TestWithMock::SetUp();
+ }
+
+ void TearDown()
+ {
+ TestWithMock::TearDown();
+ }
+};
+
+TEST_F(GetConfigurationTest, ThrowExceptionWhenGetConfigurationFailedByCallbackIsNull)
+{
+ EXPECT_ANY_THROW(g_remoteEnrollee->getConfiguration(nullptr));
+}
+
+TEST_F(GetConfigurationTest, GetConfigurationSucceed)
+{
+ bool isWellConstructed = false;
+
+ g_enrolleeSimul.setDeviceProperty();
+
+ mocks.ExpectCallFunc(onGetConfigurationCb).Do(
+ [&isWellConstructed](std::shared_ptr< GetConfigurationStatus > status)
+ {
+ if(status->getESResult() == ES_OK)
+ {
+ EnrolleeConf conf = status->getEnrolleeConf();
+ if(!conf.getWiFiModes().empty())
+ {
+ if(conf.getWiFiModes().at(0) == WIFI_11G &&
+ conf.getWiFiFreq() == WIFI_5G &&
+ !strcmp(conf.getDeviceName().c_str(), "Test Device"))
+ {
+ isWellConstructed = true;
+ }
+ }
+ }
+ });
+
+ g_remoteEnrollee->getConfiguration(onGetConfigurationCb);
+
+ std::unique_lock< std::mutex > lock{ mutexForCondition };
+ responseCon.wait_for(lock, g_waitForResponse);
+
+ EXPECT_TRUE(isWellConstructed);
+}
+
+class GetStatusTest : public EasysetupMediatorTest
+{
+
+public:
+ GetStatusTest() = default;
+ ~GetStatusTest() = default;
+
+ static void onGetStatusCb(shared_ptr< GetEnrolleeStatus > /*status*/)
+ {
+ }
+
+protected:
+ void SetUp()
+ {
+ TestWithMock::SetUp();
+ }
+
+ void TearDown()
+ {
+ TestWithMock::TearDown();
+ }
+};
+
+TEST_F(GetStatusTest, ThrowExceptionWhenGetStatusFailedByCallbackIsNull)
+{
+ EXPECT_ANY_THROW(g_remoteEnrollee->getStatus(nullptr));
+}
+
+TEST_F(GetStatusTest, GetStatusSucceed)
+{
+ g_enrolleeSimul.setESState();
+ g_enrolleeSimul.setESErrorCode();
+
+ bool isWellConstructed = false;
+ mocks.ExpectCallFunc(onGetStatusCb).Do(
+ [&isWellConstructed](std::shared_ptr< GetEnrolleeStatus > status)
+ {
+ if(status->getESResult() == ES_OK)
+ {
+ EnrolleeStatus enrolleeStatus = status->getEnrolleeStatus();
+
+ if(enrolleeStatus.getProvStatus() == ES_STATE_CONNECTED_TO_ENROLLER &&
+ enrolleeStatus.getLastErrCode() == ES_ERRCODE_NO_INTERNETCONNECTION)
+ {
+ isWellConstructed = true;
+ }
+ }
+ });
+
+ g_remoteEnrollee->getStatus(onGetStatusCb);
+
+ std::unique_lock< std::mutex > lock{ mutexForCondition };
+ responseCon.wait_for(lock, g_waitForResponse);
+
+ EXPECT_TRUE(isWellConstructed);
+}
+
+class ProvisionDevicePropertiesTest : public EasysetupMediatorTest
+{
+
+public:
+ ProvisionDevicePropertiesTest() = default;
+ ~ProvisionDevicePropertiesTest() = default;
+
+ static void deviceProvisioningStatusCb(
+ shared_ptr< DevicePropProvisioningStatus > /*status*/)
+ {
+ }
+
+protected:
+ void SetUp()
+ {
+ TestWithMock::SetUp();
+ }
+
+ void TearDown()
+ {
+ TestWithMock::TearDown();
+ }
+};
+
+TEST_F(ProvisionDevicePropertiesTest,
+ ThrowExceptionWhenProvisionDeviceProperiesFailedByCallbackIsNull)
+{
+ DeviceProp devProp;
+ devProp.setWiFiProp("Iotivity_SSID", "Iotivity_PWD", WPA2_PSK, TKIP_AES);
+ devProp.setDevConfProp("korean", "Korea");
+
+ EXPECT_ANY_THROW(g_remoteEnrollee->provisionDeviceProperties(devProp, nullptr));
+}
+
+TEST_F(ProvisionDevicePropertiesTest,
+ ThrowExceptionWhenProvisionDeviceProperiesFailedWithoutSSID)
+{
+ DeviceProp devProp;
+ devProp.setWiFiProp("", "Iotivity_PWD", WPA2_PSK, TKIP_AES);
+ devProp.setDevConfProp("korean", "Korea");
+ EXPECT_ANY_THROW(g_remoteEnrollee->provisionDeviceProperties(devProp,
+ deviceProvisioningStatusCb));
+}
+
+TEST_F(ProvisionDevicePropertiesTest,
+ ProvisionDeviceProperiesSucceed)
+{
+ DeviceProp devProp;
+ devProp.setWiFiProp("Iotivity_SSID", "Iotivity_PWD", WPA2_PSK, TKIP_AES);
+ devProp.setDevConfProp("korean", "Korea");
+
+ int cntForReceivedCallbackWithSuccess = 0;
+
+ mocks.OnCallFunc(deviceProvisioningStatusCb).Do(
+ [&cntForReceivedCallbackWithSuccess]
+ (std::shared_ptr< DevicePropProvisioningStatus > status)
+ {
+ if(status->getESResult() == ES_OK)
+ {
+ cntForReceivedCallbackWithSuccess++;
+ }
+
+ });
+
+ g_remoteEnrollee->provisionDeviceProperties(devProp, deviceProvisioningStatusCb);
+
+ std::unique_lock< std::mutex > lock{ mutexForCondition };
+ responseCon.wait_for(lock, g_waitForResponse);
+
+ EXPECT_EQ(cntForReceivedCallbackWithSuccess, 1);
+}
+
+class ProvisionCloudPropertiesTest : public EasysetupMediatorTest
+{
+
+public:
+ ProvisionCloudPropertiesTest() = default;
+ ~ProvisionCloudPropertiesTest() = default;
+
+ static void cloudPropProvStatusCb(shared_ptr< CloudPropProvisioningStatus > /*status*/)
+ {
+ }
+
+protected:
+ void SetUp()
+ {
+ TestWithMock::SetUp();
+ }
+
+ void TearDown()
+ {
+ TestWithMock::TearDown();
+ }
+};
+
+TEST_F(ProvisionCloudPropertiesTest,
+ ThrowExceptionWhenProvisionCloudPropertiesFailedByCallbackIsNull)
+{
+ CloudProp cloudProp;
+ cloudProp.setCloudProp("authCode", "authProvider", "ciServer");
+ cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3");
+
+ EXPECT_ANY_THROW(g_remoteEnrollee->provisionCloudProperties(cloudProp, nullptr));
+}
+
+TEST_F(ProvisionCloudPropertiesTest,
+ ThrowExceptionWhenProvisionCloudPropertiesFailedWithoutAuthCode)
+{
+ CloudProp cloudProp;
+ cloudProp.setCloudProp("", "authProvider", "ciServer");
+ cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3");
+ EXPECT_ANY_THROW(g_remoteEnrollee->provisionCloudProperties(cloudProp,
+ cloudPropProvStatusCb));
+}
+
+TEST_F(ProvisionCloudPropertiesTest,
+ ThrowExceptionWhenProvisionCloudPropertiesFailedWithoutAuthProvider)
+{
+ CloudProp cloudProp;
+ cloudProp.setCloudProp("authCode", "", "ciServer");
+ cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3");
+ EXPECT_ANY_THROW(g_remoteEnrollee->provisionCloudProperties(cloudProp,
+ cloudPropProvStatusCb));
+}
+
+TEST_F(ProvisionCloudPropertiesTest,
+ ThrowExceptionWhenProvisionCloudPropertiesFailedWithoutCIServer)
+{
+ CloudProp cloudProp;
+ cloudProp.setCloudProp("authCode", "authProvider", "");
+ cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3");
+ EXPECT_ANY_THROW(g_remoteEnrollee->provisionCloudProperties(cloudProp,
+ cloudPropProvStatusCb));
+}
+
+TEST_F(ProvisionCloudPropertiesTest, ProvisionCloudPropertiesSucceed)
+{
+ CloudProp cloudProp;
+ cloudProp.setCloudProp("authCode", "authProvider", "ciServer");
+ cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3");
+
+ int cntForReceivedCallbackWithSuccess = 0;
+
+ mocks.OnCallFunc(cloudPropProvStatusCb).Do(
+ [& cntForReceivedCallbackWithSuccess](std::shared_ptr< CloudPropProvisioningStatus > status)
+ {
+ // Will called twice
+ if(status->getESResult() == ES_OK)
+ {
+ cntForReceivedCallbackWithSuccess++;
+ }
+ });
+
+ g_remoteEnrollee->provisionCloudProperties(cloudProp, cloudPropProvStatusCb);
+
+ std::unique_lock< std::mutex > lock{ mutexForCondition };
+ responseCon.wait_for(lock, g_waitForResponse);
+
+ EXPECT_EQ(cntForReceivedCallbackWithSuccess, 2);
+
+ ESTerminateEnrollee();
+}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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 "UnitTestHelper.h"
-
-#include "ocstack.h"
-#include "OCPlatform.h"
-#include "OCApi.h"
-#include "oic_string.h"
-#include "logger.h"
-
-#include "EasySetup.h"
-#include "RemoteEnrollee.h"
-#include "ESException.h"
-
-#include <iostream>
-#include <functional>
-#include <pthread.h>
-#include <condition_variable>
-
-using namespace OIC::Service;
-
-const std::string ipaddress = "1.1.1.1";
-const std::string ssid = "test";
-const std::string pwd = "test@123";
-
-class MediatorRichTest: public TestWithMock
-{
- protected:
- void SetUp()
- {
- TestWithMock::SetUp();
- }
-
- void TearDown()
- {
- TestWithMock::TearDown();
- }
-};
-
-//callbacks
-void easySetupStatusCallback (std::shared_ptr< EasySetupStatus > /*easySetupStatus*/)
-{
-
-
-}
-
-/* Test cases for easysetyup class*/
-
-//getInstance
-TEST_F(MediatorRichTest, testGetInstance)
-{
- EasySetup *easySetupIntance1 = EasySetup::getInstance();
- EasySetup *easySetupIntance2 = EasySetup::getInstance();
-
- EXPECT_EQ(easySetupIntance1, easySetupIntance2);
-}
-
-//createEnrolleeDevice [positive]
-TEST_F(MediatorRichTest, testCreateEnrolleeDevice)
-{
- RemoteEnrollee::shared_ptr remoteEnrollee = NULL;
- ProvConfig netInfo;
- WiFiOnboadingConnection onboardingConn;
-
- netInfo.connType = CT_ADAPTER_IP;
-
- OICStrcpy(netInfo.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
- OICStrcpy(netInfo.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
-
- onboardingConn.isSecured = false;
- OICStrcpy(onboardingConn.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
-
- remoteEnrollee = EasySetup::getInstance()->createEnrolleeDevice(netInfo, onboardingConn);
-
- EXPECT_TRUE(remoteEnrollee != NULL);
-}
-
-//createEnrolleeDevice [Negative]
-TEST_F(MediatorRichTest, testCreateEnrolleeDeviceNegative)
-{
- RemoteEnrollee::shared_ptr remoteEnrollee = NULL;
- ProvConfig netInfo;
- WiFiOnboadingConnection onboardingConn;
- EasySetup *easysetupInstance = EasySetup::getInstance();
-
- netInfo.connType = CT_ADAPTER_IP;
-
- OICStrcpy(netInfo.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
- OICStrcpy(netInfo.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
-
- onboardingConn.isSecured = false;
- OICStrcpy(onboardingConn.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
-
- //calling the createEnrolleeDevice
- remoteEnrollee = easysetupInstance->createEnrolleeDevice(netInfo, onboardingConn);
- //calling again the createEnrolleeDevice with same config & connection info [API throws the exception]
- EXPECT_ANY_THROW(easysetupInstance->createEnrolleeDevice(netInfo, onboardingConn));
-}
-
-//createEnrolleeDevice [positive (creating the two RemoteEnrolleeDevice with different config)]
-TEST_F(MediatorRichTest, testCreateEnrolleeMultipleDevice)
-{
- RemoteEnrollee::shared_ptr remoteEnrollee1 = NULL;
- RemoteEnrollee::shared_ptr remoteEnrollee2 = NULL;
- WiFiOnboadingConnection onboardingConn1;
- WiFiOnboadingConnection onboardingConn2;
- ProvConfig netInfo1;
- ProvConfig netInfo2;
- std::string ipaddress2 = "0.0.0.0";
-
- //calling the API for the first device
- netInfo1.connType = CT_ADAPTER_IP;
- OICStrcpy(netInfo1.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
- OICStrcpy(netInfo1.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
-
- onboardingConn1.isSecured = false;
- OICStrcpy(onboardingConn1.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
- remoteEnrollee1 = EasySetup::getInstance()->createEnrolleeDevice(netInfo1, onboardingConn1);
-
- //calling the API for the second device
- netInfo1.connType = CT_ADAPTER_IP;
- OICStrcpy(netInfo1.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
- OICStrcpy(netInfo1.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
-
- onboardingConn1.isSecured = false;
- OICStrcpy(onboardingConn1.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress2.c_str());
- remoteEnrollee2 = EasySetup::getInstance()->createEnrolleeDevice(netInfo2, onboardingConn2);
-
- EXPECT_TRUE(remoteEnrollee1 != NULL);
- EXPECT_TRUE(remoteEnrollee2 != NULL);
-}
-
-/*Test cases for RemoteEnrollee class*/
-
-//registerEasySetupStatusHandler [positive]
-TEST_F(MediatorRichTest, testRegisterEasySetupStatusHandler)
-{
- //creation of the Remote Enrollee Device
- RemoteEnrollee::shared_ptr remoteEnrollee = NULL;
- ProvConfig netInfo;
- WiFiOnboadingConnection onboardingConn;
-
- netInfo.connType = CT_ADAPTER_IP;
-
- OICStrcpy(netInfo.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
- OICStrcpy(netInfo.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
-
- onboardingConn.isSecured = false;
- OICStrcpy(onboardingConn.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
-
- remoteEnrollee = EasySetup::getInstance()->createEnrolleeDevice(netInfo, onboardingConn);
-
- //calling the API
- EXPECT_NO_THROW( remoteEnrollee->registerEasySetupStatusHandler(&easySetupStatusCallback));
-}
-
-//registerEasySetupStatusHandler [Negative]
-TEST_F(MediatorRichTest, testRegisterEasySetupStatusHandlerNegative)
-{
- //creation of the Remote Enrollee Device
- RemoteEnrollee::shared_ptr remoteEnrollee = NULL;
- ProvConfig netInfo;
- WiFiOnboadingConnection onboardingConn;
-
- netInfo.connType = CT_ADAPTER_IP;
-
- OICStrcpy(netInfo.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
- OICStrcpy(netInfo.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
-
- onboardingConn.isSecured = false;
- OICStrcpy(onboardingConn.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
-
- remoteEnrollee = EasySetup::getInstance()->createEnrolleeDevice(netInfo, onboardingConn);
-
- //calling the API
- EXPECT_ANY_THROW( remoteEnrollee->registerEasySetupStatusHandler(NULL));
-}
-
-//isEnrolleeProvisioned
-TEST_F(MediatorRichTest, testIsEnrolleeProvisioned)
-{
- //creation of the Remote Enrollee Device
- RemoteEnrollee::shared_ptr remoteEnrollee = NULL;
- ProvConfig netInfo;
- WiFiOnboadingConnection onboardingConn;
-
- netInfo.connType = CT_ADAPTER_IP;
-
- OICStrcpy(netInfo.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
- OICStrcpy(netInfo.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
-
- onboardingConn.isSecured = false;
- OICStrcpy(onboardingConn.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
-
- remoteEnrollee = EasySetup::getInstance()->createEnrolleeDevice(netInfo, onboardingConn);
-
- //calling the API
- bool isEnrolleeProvisioned = remoteEnrollee->isEnrolleeProvisioned();
-
- EXPECT_TRUE(false == isEnrolleeProvisioned);
-}
-
-//startProvisioning [positive]
-TEST_F(MediatorRichTest, testStartProvisioning)
-{
- //creation of the Remote Enrollee Device
- RemoteEnrollee::shared_ptr remoteEnrollee = NULL;
- ProvConfig netInfo;
- WiFiOnboadingConnection onboardingConn;
-
- netInfo.connType = CT_ADAPTER_IP;
-
- OICStrcpy(netInfo.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
- OICStrcpy(netInfo.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
-
- onboardingConn.isSecured = false;
- OICStrcpy(onboardingConn.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
-
- remoteEnrollee = EasySetup::getInstance()->createEnrolleeDevice(netInfo, onboardingConn);
- remoteEnrollee->registerEasySetupStatusHandler(&easySetupStatusCallback);
-
-#ifdef REMOTE_ARDUINO_ENROLEE
- EXPECT_NO_THROW(remoteEnrollee->startProvisioning());
-
-#else
- /* It will throw the exception
- * as it will not able to discover the provisioning resource in the network
- */
- EXPECT_ANY_THROW(remoteEnrollee->startProvisioning());
-#endif
-}
-
-//startProvisioning [Negative]
-TEST_F(MediatorRichTest, testStartProvisioningNegative)
-{
- //creation of the Remote Enrollee Device
- RemoteEnrollee::shared_ptr remoteEnrollee = NULL;
- ProvConfig netInfo;
- WiFiOnboadingConnection onboardingConn;
-
- netInfo.connType = CT_ADAPTER_IP;
-
- OICStrcpy(netInfo.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
- OICStrcpy(netInfo.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
-
- onboardingConn.isSecured = false;
- OICStrcpy(onboardingConn.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
-
- remoteEnrollee = EasySetup::getInstance()->createEnrolleeDevice(netInfo, onboardingConn);
-
- /* We are not registering the EasySetupStatusHandler, so startProvisioning
- * will throw the Exception & we are checking the same
- */
- EXPECT_ANY_THROW(remoteEnrollee->startProvisioning());
-}
-
-//stopProvisioning [positive]
-TEST_F(MediatorRichTest, testStopProvisioning)
-{
- //creation of the Remote Enrollee Device
- RemoteEnrollee::shared_ptr remoteEnrollee = NULL;
- ProvConfig netInfo;
- WiFiOnboadingConnection onboardingConn;
-
- netInfo.connType = CT_ADAPTER_IP;
-
- OICStrcpy(netInfo.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
- OICStrcpy(netInfo.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
-
- onboardingConn.isSecured = false;
- OICStrcpy(onboardingConn.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
-
- remoteEnrollee = EasySetup::getInstance()->createEnrolleeDevice(netInfo, onboardingConn);
- remoteEnrollee->registerEasySetupStatusHandler(&easySetupStatusCallback);
-
-#ifdef REMOTE_ARDUINO_ENROLEE
- EXPECT_NO_THROW(remoteEnrollee->startProvisioning());
- EXPECT_NO_THROW(remoteEnrollee->stopProvisioning());
-
-#else
- /* It will throw the exception as
- * it will not able to discover the provisioning resource in the network
- */
- EXPECT_ANY_THROW(remoteEnrollee->startProvisioning());
-
- /* It will throw an exception
- * as internally resource will be empty [startProvisioning is not succeed]
- */
- EXPECT_ANY_THROW(remoteEnrollee->stopProvisioning());
-#endif
-}
-
-//stopProvisioning [Negative]
-TEST_F(MediatorRichTest, testStopProvisioningNegative)
-{
- //creation of the Remote Enrollee Device
- RemoteEnrollee::shared_ptr remoteEnrollee = NULL;
- ProvConfig netInfo;
- WiFiOnboadingConnection onboardingConn;
-
- netInfo.connType = CT_ADAPTER_IP;
-
- OICStrcpy(netInfo.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
- OICStrcpy(netInfo.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
-
- onboardingConn.isSecured = false;
- OICStrcpy(onboardingConn.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
-
- remoteEnrollee = EasySetup::getInstance()->createEnrolleeDevice(netInfo, onboardingConn);
- remoteEnrollee->registerEasySetupStatusHandler(&easySetupStatusCallback);
-
- /* we didn't call the start provisioning API and directly calling stopProvisioning API.
- * In this case API will throw the exception & we are checking the same.
- */
- EXPECT_ANY_THROW(remoteEnrollee->stopProvisioning());
-}
-
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
##
-# Mediator[RichSDK] Unit Test build script
+# Notification Unit Test build script
##
-import os
-# SConscript file for Local PKI google tests
-gtest_env = SConscript('#extlibs/gtest/SConscript')
-lib_env = gtest_env.Clone()
+Import('env')
-if lib_env.get('RELEASE'):
- lib_env.AppendUnique(CCFLAGS = ['-Os'])
- lib_env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+if env.get('RELEASE'):
+ env.AppendUnique(CCFLAGS = ['-Os'])
+ env.AppendUnique(CPPDEFINES = ['NDEBUG'])
else:
- lib_env.AppendUnique(CCFLAGS = ['-g'])
+ env.AppendUnique(CCFLAGS = ['-g'])
-if lib_env.get('LOGGING'):
- lib_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+if env.get('LOGGING'):
+ env.AppendUnique(CPPDEFINES = ['TB_LOG'])
-# Add third party libraries
-SConscript('#service/third_party_libs.scons', 'lib_env')
-
-target_os = lib_env.get('TARGET_OS')
-if target_os in ['linux']:
- # Verify that 'hippomocks' mocking code is installed. If not,
- # get it and install it
- SConscript('#extlibs/hippomocks.scons')
-
-mediator_rich_test_env = lib_env.Clone()
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
######################################################################
#unit test setting
######################################################################
src_dir = lib_env.get('SRC_DIR')
+gtest_dir = src_dir + '/extlibs/gtest/gtest-1.7.0'
+
+easysetup_test_env = lib_env.Clone()
+target_os = env.get('TARGET_OS')
######################################################################
# Build flags
######################################################################
+GTest = File(gtest_dir + '/lib/.libs/libgtest.a')
+GTest_Main = File(gtest_dir + '/lib/.libs/libgtest_main.a')
+
+easysetup_test_env.AppendUnique(LIBPATH = [lib_env.get('BUILD_DIR')])
+easysetup_test_env.AppendUnique(LIBS = [
+ 'connectivity_abstraction', 'oc', 'octbstack', 'oc_logger', 'coap',
+ GTest_Main, GTest])
-mediator_rich_test_env.AppendUnique(
- CPPPATH = [
- src_dir + '/extlibs/hippomocks-master',
- '../inc',
- '../../../inc',
- ])
+if target_os not in ['windows', 'winrt']:
+ easysetup_test_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
-if mediator_rich_test_env.get('SECURED') == '1':
- mediator_rich_test_env.PrependUnique(LIBS = ['tinydtls','ocprovision', 'ocpmapi', 'timer'])
+easysetup_test_env.AppendUnique(CXXFLAGS = ['-pthread'])
+easysetup_test_env.AppendUnique(LIBS = ['pthread'])
-mediator_rich_test_env.PrependUnique(LIBS = [
- 'ESMediatorRich',
- 'oc',
- 'octbstack',
- 'oc_logger'])
+easysetup_test_env.PrependUnique(CPPPATH = [ src_dir + '/extlibs/hippomocks-master', gtest_dir + '/include'])
+
+easysetup_test_env.AppendUnique(CPPPATH = [ src_dir + '/resource/include',
+ src_dir + '/service/easy-setup/mediator/richsdk/inc',
+ src_dir + '/service/easy-setup/inc',
+ src_dir + '/service/easy-setup/enrollee/inc'])
######################################################################
# Build Test
######################################################################
-mediator_richsdk_test_src = mediator_rich_test_env.Glob('./*.cpp')
-mediator_richsdk_test = mediator_rich_test_env.Program('mediator_richsdk_test', mediator_richsdk_test_src)
-Alias("mediator_richsdk_test", mediator_richsdk_test)
-mediator_rich_test_env.AppendTarget('mediator_richsdk_test')
+easysetup_mediator_test_env = easysetup_test_env.Clone()
+easysetup_mediator_test_env.AppendUnique(LIBS = ['ESEnrolleeSDK', 'ESMediatorRich'])
+
+easysetup_mediator_test_src = env.Glob(src_dir + '/service/easy-setup/mediator/richsdk/unittests/ESMediatorTest.cpp')
+easysetup_mediator_test = easysetup_mediator_test_env.Program('easysetup_mediator_test', easysetup_mediator_test_src)
+Alias("easysetup_mediator_test", easysetup_mediator_test)
+env.AppendTarget('easysetup_mediator_test')
+
+if env.get('TEST') == '1':
+ if target_os == 'linux':
+ from tools.scons.RunTest import *
+ run_test(easysetup_mediator_test_env, '', 'service/easy-setup/mediator/richsdk/unittests/easysetup_mediator_test')
-if mediator_rich_test_env.get('TEST') == '1':
- if target_os in ['linux']:
- from tools.scons.RunTest import *
- run_test(mediator_rich_test_env, '', 'service/easy-setup/mediator/richsdk/unittests/mediator_richsdk_test')
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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 COMMON_UTILS_UNITTESTHELPER_H
-#define COMMON_UTILS_UNITTESTHELPER_H
-
-#include <gtest/gtest.h>
-#include <HippoMocks/hippomocks.h>
-
-class TestWithMock: public testing::Test
-{
- public:
- MockRepository mocks;
-
- protected:
- virtual ~TestWithMock() noexcept(noexcept(std::declval<Test>().~Test())) {}
-
- virtual void TearDown()
- {
- try
- {
- mocks.VerifyAll();
- }
- catch (...)
- {
- mocks.reset();
- throw;
- }
- }
-};
-#endif // COMMON_UTILS_UNITTESTHELPER_H
if enrollee_env.get('SECURED') == '1':
enrollee_env.PrependUnique(LIBS = ['ocpmapi', 'ocprovision'])
-enrollee = enrollee_env.Program('enrollee', 'enrolleewifi.c')
+enrollee = enrollee_env.Program('enrollee', ['enrolleewifi.c', 'easysetup_x.c'])
i_enrollee = enrollee_env.Install(env.get('BUILD_DIR'), enrollee)
-Alias('enrollee', i_enrollee)
+justworksdat = enrollee_env.Install(env.get('BUILD_DIR') + '/service/easy-setup/sampleapp/enrollee/linux/',
+ env.get('SRC_DIR') + '/service/easy-setup/sampleapp/enrollee/linux/oic_svr_db_server.dat')
+
+Alias('enrollee', [i_enrollee, justworksdat])
env.AppendTarget('enrollee')
--- /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 "easysetup_x.h"
+#include "string.h"
+#include "oic_malloc.h"
+#include "logger.h"
+
+/**
+ * @var ESX_ENROLLEE_TAG
+ * @brief Logging tag for module name.
+ */
+#define ESX_ENROLLEE_TAG "ESX"
+
+UserProperties g_userProperties;
+
+void SetUserProperties(const UserProperties *prop)
+{
+ if(prop != NULL)
+ {
+ strncpy(g_userProperties.userValue_str, prop->userValue_str, MAXLEN_STRING);
+ g_userProperties.userValue_int = prop->userValue_int;
+ }
+}
+
+void ReadUserdataCb(OCRepPayload* payload, char* resourceType, void** userdata)
+{
+ OIC_LOG(DEBUG, ESX_ENROLLEE_TAG, "ReadUserdataCb IN");
+
+ if(payload != NULL)
+ {
+ if(strstr(resourceType, OC_RSRVD_ES_RES_TYPE_WIFI))
+ {
+ int64_t value = -1;
+ if (OCRepPayloadGetPropInt(payload, USERPROPERTY_KEY_INT, &value))
+ {
+ if(*userdata != NULL)
+ {
+ *userdata = (void*)OICMalloc(sizeof(UserProperties));
+ }
+ OIC_LOG_V(INFO, ESX_ENROLLEE_TAG, "[User specific property] %s : %ld",
+ USERPROPERTY_KEY_INT, value);
+ ((UserProperties*)(*userdata))->userValue_int = value;
+ g_userProperties.userValue_int = value;
+ }
+ }
+ }
+
+ OIC_LOG(DEBUG, ESX_ENROLLEE_TAG, "ReadUserdataCb OUT");
+}
+
+void WriteUserdataCb(OCRepPayload* payload, char* resourceType)
+{
+ OIC_LOG(DEBUG, ESX_ENROLLEE_TAG, "WriteUserdataCb IN");
+
+ if(payload != NULL)
+ {
+ if(strstr(resourceType, OC_RSRVD_ES_RES_TYPE_WIFI))
+ {
+ OCRepPayloadSetPropInt(payload, USERPROPERTY_KEY_INT, g_userProperties.userValue_int);
+ }
+
+ if(strstr(resourceType, OC_RSRVD_ES_RES_TYPE_DEVCONF))
+ {
+ OCRepPayloadSetPropString(payload, USERPROPERTY_KEY_STR, g_userProperties.userValue_str);
+ }
+ }
+
+ OIC_LOG(DEBUG, ESX_ENROLLEE_TAG, "WriteUserdataCb OUT");
+}
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-/**
- * @file
- *
- * This file contains the API declaration for creating & configuration for SoftAP
- */
+#include "easysetup.h"
+#include "escommon.h"
-#ifndef EASYSETUP_ENROLLEE_SOFTAP_H__
-#define EASYSETUP_ENROLLEE_SOFTAP_H__
+#ifndef EASYSETUPX_ENROLLEE_H__
+#define EASYSETUPX_ENROLLEE_H__
-#ifdef __cplusplus
-extern "C" {
-#endif // __cplusplus
+#define MAXLEN_STRING 100
+typedef struct UserProperties_t
+{
+ int userValue_int; /**< User-specific property in WiFi resource **/
+ char userValue_str[MAXLEN_STRING]; /**< User-specific property in DevConf resource **/
+} UserProperties;
-#define SOFTAP_SUCCESS 1
-#define SOFTAP_FAILED 0
+#define USERPROPERTY_KEY_INT "x.user.property.int"
+#define USERPROPERTY_KEY_STR "x.user.property.str"
+void ReadUserdataCb(OCRepPayload* payload, char* resourceType, void** userdata);
+void WriteUserdataCb(OCRepPayload* payload, char* resourceType);
-//This callback signagure may get changed as per the native implementation.
-typedef void (*SoftAPCallbackNative)(int result, const char *ip, const char* mac_addr,
- const char*device_name);
-
-void ESCreateSoftapNative(const char * ssid, const char* passwd, SoftAPCallbackNative cb);
-
-#ifdef __cplusplus
-}
-#endif // __cplusplus
-
-
-#endif /* EASYSETUP_ENROLLEE_SOFTAP_H__ */
-
+void SetUserProperties(const UserProperties *prop);
+#endif /* EASYSETUPX_ENROLLEE_H__ */
#include "easysetup.h"
+#include "easysetup_x.h"
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <pthread.h>
+#include <oic_string.h>
+#include "oic_malloc.h"
-#define TAG "TS"
+#define TAG "ENROLLEE_SAMPLE"
void *listeningFunc(void *);
/**
- * @var ssid
- * @brief Target SSID of the Soft Access point to which the device has to connect
- */
-static char ssid[] = "EasySetup123";
-
-/**
- * @var passwd
- * @brief Password of the Soft Access point to which the device has to connect
- */
-static char passwd[] = "EasySetup123";
-
-/**
* Secure Virtual Resource database for Iotivity Server
* It contains Server's Identity and the PSK credentials
* of other devices which the server trusts
*/
static char CRED_FILE[] = "oic_svr_db_server.dat";
-OCPersistentStorage ps ;
-
+OCPersistentStorage ps;
/**
* @var gIsSecured
*/
static bool gIsSecured = false;
+UserProperties g_userProperties;
+
void PrintMenu()
{
printf("============\n");
printf("S: Enabled Security\n");
- printf("I: Init easy setup\n");
- printf("P: start provisioning resources\n");
- printf("T: terminate\n");
- printf("Q: quit\n");
+ printf("I: Init & Start EasySetup\n");
+ printf("D: Set DeviceInfo\n");
+ printf("T: Terminate\n");
+ printf("U: set Callback for userdata\n");
+ printf("Q: Quit\n");
printf("============\n");
}
-void EventCallbackInApp(ESResult esResult, ESEnrolleeState enrolleeState)
+void WiFiProvCbInApp(ESWiFiProvData *eventData)
{
- printf("Easy setup event callback\n");
+ printf("WiFiProvCbInApp IN\n");
- if(esResult == ES_OK)
+ if(eventData == NULL)
{
- if(enrolleeState == ES_ON_BOARDED_STATE)
- {
- printf("Device is successfully OnBoared on Adhoc network\n");
- }
- else if (enrolleeState == ES_PROVISIONED_STATE)
- {
- printf("Device is provisioned with target network's credentials\n");
- }
- else if (enrolleeState == ES_ON_BOARDED_TARGET_NETWORK_STATE)
- {
- printf("Device is onboarded/connected with target network\n");
- }
- else
- {
- printf("Wrong state !! Easy setup is failed at Enrollee state = %d\n",enrolleeState);
- }
+ printf("ESWiFiProvData is NULL\n");
+ return ;
+ }
+
+ printf("SSID : %s\n", eventData->ssid);
+ printf("Password : %s\n", eventData->pwd);
+ printf("AuthType : %d\n", eventData->authtype);
+ printf("EncType : %d\n", eventData->enctype);
+
+ if(eventData->userdata != NULL)
+ {
+ printf("userValue : %d\n", ((UserProperties *)(eventData->userdata))->userValue_int);
}
- else
+
+ printf("WiFiProvCbInApp OUT\n");
+}
+
+void DevConfProvCbInApp(ESDevConfProvData *eventData)
+{
+ printf("DevConfProvCbInApp IN\n");
+
+ if(eventData == NULL)
{
- printf("Easy stup is failed at Enrollee state = %d\n",enrolleeState);;
+ printf("ESDevConfProvData is NULL\n");
+ return ;
}
- PrintMenu();
+ printf("Language : %s\n", eventData->language);
+ printf("Country : %s\n", eventData->country);
+
+ printf("DevConfProvCbInApp OUT\n");
}
+void CloudDataProvCbInApp(ESCloudProvData *eventData)
+{
+ printf("CloudDataProvCbInApp IN\n");
+
+ if(eventData == NULL)
+ {
+ printf("ESCloudProvData is NULL\n");
+ return ;
+ }
+
+ printf("AuthCode : %s\n", eventData->authCode);
+ printf("AuthProvider : %s\n", eventData->authProvider);
+ printf("CI Server : %s\n", eventData->ciServer);
+
+ printf("CloudDataProvCbInApp OUT\n");
+}
+
+ESProvisioningCallbacks gCallbacks = {
+ .WiFiProvCb = &WiFiProvCbInApp,
+ .DevConfProvCb = &DevConfProvCbInApp,
+ .CloudDataProvCb = &CloudDataProvCbInApp
+};
+
FILE* server_fopen(const char *path, const char *mode)
{
(void) path;
void StartEasySetup()
{
- printf("StartEasySetup and onboarding started..\n");
-
- if(ESInitEnrollee(CT_ADAPTER_IP, ssid, passwd, gIsSecured, EventCallbackInApp) == ES_ERROR)
- {
- printf("StartEasySetup and onboarding Fail!!\n");
- return;
- }
-}
-
-void ESInitResources()
-{
- printf("Starting Enrollee Provisioning\n");
+ printf("StartEasySetup IN\n");
- // Initialize the OC Stack in Server mode
if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
{
printf("OCStack init error!!\n");
return;
}
- if (ESInitProvisioning() == ES_ERROR)
+ ESResourceMask resourcemMask = ES_WIFI_RESOURCE | ES_CLOUD_RESOURCE | ES_DEVCONF_RESOURCE;
+ if(ESInitEnrollee(gIsSecured, resourcemMask, gCallbacks) != ES_OK)
{
- printf("Init Provisioning Failed!!\n");
+ printf("OCStack init error!!\n");
return;
}
+ printf("ESInitEnrollee Success\n");
- pthread_t thread_handle;
+ pthread_t thread_handle = NULL;
if (pthread_create(&thread_handle, NULL, listeningFunc, NULL))
{
printf("Thread creation failed\n");
}
- printf("ESInitProvisioning Success\n");
+ printf("StartEasySetup OUT\n");
+}
+
+void SetDeviceInfo()
+{
+ printf("SetDeviceInfo IN\n");
+
+ ESDeviceProperty deviceProperty = {
+ {{WIFI_11G, WIFI_11N, WIFI_11AC, WiFi_EOF}, WIFI_5G}, {"Test Device"}
+ };
+
+ // Set user properties if needed
+ char userValue_str[] = "user_str";
+ g_userProperties.userValue_int = 0;
+ strcpy(g_userProperties.userValue_str, userValue_str);
+ SetUserProperties(&g_userProperties);
+
+ if(ESSetDeviceProperty(&deviceProperty) == ES_ERROR)
+ {
+ printf("ESSetDeviceProperty Error\n");
+ }
+
+ printf("SetDeviceInfo OUT\n");
}
void StopEasySetup()
printf("StopEasySetup OUT\n");
}
+void SetCallbackForUserdata()
+{
+ ESSetCallbackForUserdata(&ReadUserdataCb, &WriteUserdataCb);
+}
+
int main()
{
printf("#########################\n");
printf("EasySetup Enrollee SAMPLE\n");
printf("#########################\n");
PrintMenu();
- char option = 'T';
+ char option;
while(true)
{
- scanf("%c",&option);
+ if(scanf("%c", &option) != 1)
+ {
+ printf("Failed to read input data\n");
+ continue;
+ }
- if(option!= '\n')
- {
+ if(option!= '\n')
+ {
switch (option)
{
case 'H': // help
case 'S': // Enable Security
case 's':
EnableSecurity();
+ PrintMenu();
break;
case 'I': // Init EasySetup
case 'i':
StartEasySetup();
+ PrintMenu();
break;
- case 'P': // start provisioning
- case 'p':
- ESInitResources();
+ case 'D': // Set Device Info
+ case 'd':
+ SetDeviceInfo();
+ PrintMenu();
break;
-
case 'T': // stop easy setup
case 't':
StopEasySetup();
+ PrintMenu();
+ break;
+ case 'U': // set callback
+ case 'u':
+ SetCallbackForUserdata();
+ PrintMenu();
break;
default:
printf("wrong option\n");
+ PrintMenu();
break;
}
- if (option == 'Q' || option == 'q') break;
+ if (option == 'Q' || option == 'q') { break; }
}
}
return 0;
}
-void *listeningFunc(void * a)
+void *listeningFunc(void * data)
{
- OCStackResult result;
+ (void)data;
+ OCStackResult result = OC_STACK_ERROR;
while (true)
{
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>\r
+<module external.linked.project.id="EasySetup" 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">\r
+ <component name="FacetManager">\r
+ <facet type="java-gradle" name="Java-Gradle">\r
+ <configuration>\r
+ <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />\r
+ <option name="BUILDABLE" value="false" />\r
+ </configuration>\r
+ </facet>\r
+ </component>\r
+ <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="true">\r
+ <exclude-output />\r
+ <content url="file://$MODULE_DIR$">\r
+ <excludeFolder url="file://$MODULE_DIR$/.gradle" />\r
+ </content>\r
+ <orderEntry type="inheritedJdk" />\r
+ <orderEntry type="sourceFolder" forTests="false" />\r
+ </component>\r
+</module>\r
-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
+//******************************************************************
+//
+// Copyright 2016 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+apply plugin: 'com.android.application'
+
+android {
+ compileSdkVersion 21
+ buildToolsVersion "20.0.0"
+
+ defaultConfig {
+ applicationId "org.iotivity.service.easysetup"
+ minSdkVersion 21
+ targetSdkVersion 21
+ versionCode 1
+ versionName "1.0"
+ }
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+ }
+ }
+ lintOptions {
+ abortOnError false
+ }
+}
+repositories {
+ flatDir {
+ dirs "../../../../../../../android/android_api/base/build/outputs/aar/", "../../../../../mediator/richsdk/android/EasySetupCore/build/outputs/aar/"
+ }
+}
+
+try {
+ dependencies {
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
+ compile ":EasySetupCore-${RELEASE}@aar"
+ }
+} catch (all) {
+ print "${ERROR_MSG}"
+ assert all
+}
--- /dev/null
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in /home/rahul/sdk/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the proguardFiles
+# directive in build.gradle.
+#
+# For more details, see
+# http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+# public *;
+#}
<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-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature
- android:name="android.hardware.camera"
- android:required="true" />
- <uses-feature
- android:name="android.hardware.camera.autofocus"
- android:required="false" />
- <uses-feature
android:name="android.hardware.touchscreen"
android:required="false" />
- <uses-permission android:name="android.permission.CAMERA" />
-
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
- android:name=".MainActivity"
+ android:name=".LoginActivity"
android:label="@string/app_name">
-
<intent-filter>
<action android:name="android.intent.action.MAIN" />
-
- <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+ <activity android:name=".EasysetupActivity" android:label="@string/app_name">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN"/>
+ <category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
--- /dev/null
+/**
+ * ***************************************************************
+ * <p/>
+ * Copyright 2016 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;
+
+import android.app.Activity;
+import android.content.Context;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.os.Bundle;
+import android.preference.PreferenceManager;
+import android.util.Log;
+import android.view.View;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.RadioButton;
+import android.widget.RadioGroup;
+import android.widget.Spinner;
+import android.widget.TextView;
+import android.widget.Toast;
+import android.widget.ToggleButton;
+
+import org.iotivity.base.ErrorCode;
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcConnectivityType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcPresenceStatus;
+import org.iotivity.base.OcProvisioning;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+import org.iotivity.service.easysetup.mediator.CloudProp;
+import org.iotivity.service.easysetup.mediator.CloudPropProvisioningCallback;
+import org.iotivity.service.easysetup.mediator.CloudPropProvisioningStatus;
+import org.iotivity.service.easysetup.mediator.DeviceProp;
+import org.iotivity.service.easysetup.mediator.DevicePropProvisioningCallback;
+import org.iotivity.service.easysetup.mediator.DevicePropProvisioningStatus;
+import org.iotivity.service.easysetup.mediator.ESException;
+import org.iotivity.service.easysetup.mediator.EasySetup;
+import org.iotivity.service.easysetup.mediator.EnrolleeConf;
+import org.iotivity.service.easysetup.mediator.GetConfigurationCallback;
+import org.iotivity.service.easysetup.mediator.GetConfigurationStatus;
+import org.iotivity.service.easysetup.mediator.RemoteEnrollee;
+import org.iotivity.service.easysetup.mediator.SecurityProvisioningCallback;
+import org.iotivity.service.easysetup.mediator.SecurityProvisioningStatus;
+import org.iotivity.service.easysetup.mediator.enums.ESCloudProvState;
+import org.iotivity.service.easysetup.mediator.enums.ESResult;
+import org.iotivity.service.easysetup.mediator.enums.WIFI_AUTHTYPE;
+import org.iotivity.service.easysetup.mediator.enums.WIFI_ENCTYPE;
+import org.iotivity.service.easysetup.mediator.enums.WIFI_FREQ;
+import org.iotivity.service.easysetup.mediator.enums.WIFI_MODE;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.List;
+
+
+public class EasysetupActivity extends Activity implements OcPlatform.OnPresenceListener {
+ private static final String TAG = "Easysetup Mediator: ";
+ PlatformConfig cfg;
+ final String deviceID = "9E09F4FE-978A-4BC3-B356-1F93BCA37829";
+ final String samsungCIServer = "coap+tcp://52.69.149.85:5683";
+
+ private static final int BUFFER_SIZE = 1024;
+
+ private String filePath = "";
+ public static final String OIC_CLIENT_JSON_DB_FILE = "oic_svr_db_client.dat";
+ public static final String OIC_SQL_DB_FILE = "PDM.db";
+
+ private boolean isFirstTime = true;
+ String mEnrolleeDeviceID;
+ String mAuthCode;
+ String mAuthProvider;
+ String mRefreshtoken;
+ String mUserID;
+ String mAccessToken;
+ String mEnrolleeAuthCode;
+
+
+ ToggleButton mSecurityMode;
+
+ RadioGroup mEasysetupProcess;
+ RadioButton mConfigureSecProcess;
+ RadioButton mGetConfigurationProcess;
+ RadioButton mProvisionDevPropProcess;
+ RadioButton mProvisionCloudPropProcess;
+
+ Button mDiscoverResource;
+ Button mStartGetConfiguration;
+ Button mStartConfigureSec;
+ Button mStartProvisionDevProp;
+ Button mStartProvisionCloudProp;
+
+ TextView mGetconfigurationStateText;
+ TextView mDevNameText;
+ TextView mLanguageText;
+ TextView mCountryText;
+ TextView mWifiModeText;
+ TextView mWifiFreqText;
+ TextView mCloudAccessableText;
+ TextView mSecStateText;
+ TextView mSecDevIDText;
+ TextView mProvisionDevPropState;
+ TextView mProvisionCloudPropState;
+
+ EditText mEnrollerSsidText;
+ EditText mEnrollerPWText;
+ EditText mInputLanguageText;
+ EditText mInputCountryText;
+ EditText mAuthCodeText;
+ EditText mAuthProviderText;
+ EditText mCIServerText;
+
+ LinearLayout mGetConfigurationInfo;
+ LinearLayout mConfigureSecInfo;
+ LinearLayout mProvisionDevPropInfo;
+ LinearLayout mProvisionCloudPropInfo;
+
+ Spinner mAuthType;
+ Spinner mEncType;
+
+ EasySetup mEasySetup;
+ RemoteEnrollee mRemoteEnrollee;
+
+ Activity mActivity;
+ Context mContext;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.easysetup_main);
+
+ mActivity = EasysetupActivity.this;
+ mContext = mActivity.getBaseContext();
+
+ mSecurityMode = (ToggleButton) findViewById(R.id.btn_Security);
+
+ mEasysetupProcess = (RadioGroup) findViewById(R.id.rg_EasysetupProcess);
+
+ mConfigureSecProcess = (RadioButton) findViewById(R.id.btn_configurSec);
+ mGetConfigurationProcess = (RadioButton) findViewById(R.id.btn_getConfiguration);
+ mProvisionDevPropProcess = (RadioButton) findViewById(R.id.btn_provisionDevConf);
+ mProvisionCloudPropProcess =
+ (RadioButton) findViewById(R.id.btn_provisionCloudConf);
+
+ mDiscoverResource = (Button) findViewById(R.id.btn_discoverResource);
+ mStartGetConfiguration =
+ (Button) findViewById(R.id.btn_startGetConfiguration);
+ mStartConfigureSec = (Button) findViewById(R.id.btn_startConfigureSec);
+ mStartProvisionDevProp = (Button) findViewById(R.id.btn_startProvisionDevConf);
+ mStartProvisionCloudProp = (Button) findViewById(R.id.btn_startProvisionCloudConf);
+
+ mGetconfigurationStateText =
+ (TextView) findViewById(R.id.txt_getConfigurationState);
+ mDevNameText = (TextView) findViewById(R.id.txt_devName);
+ mLanguageText = (TextView) findViewById(R.id.txt_language);
+ mCountryText = (TextView) findViewById(R.id.txt_country);
+ mWifiModeText = (TextView) findViewById(R.id.txt_wifiMode);
+ mWifiFreqText = (TextView) findViewById(R.id.txt_wifiFreq);
+ mCloudAccessableText = (TextView) findViewById(R.id.txt_cloudAccessable);
+ mSecStateText = (TextView) findViewById(R.id.txt_secState);
+ mSecDevIDText = (TextView) findViewById(R.id.txt_secDevID);
+ mProvisionDevPropState = (TextView) findViewById(R.id.txt_provisionDevConfState);
+ mProvisionCloudPropState =
+ (TextView) findViewById(R.id.txt_provisionCloudConfState);
+
+ mEnrollerSsidText = (EditText) findViewById(R.id.editText_EnrollerSSID);
+ mEnrollerPWText = (EditText) findViewById(R.id.editText_EnrollerPW);
+ mInputLanguageText = (EditText) findViewById(R.id.editText_Language);
+ mInputCountryText = (EditText) findViewById(R.id.editText_Country);
+ mAuthCodeText = (EditText) findViewById(R.id.editText_authcode);
+ mAuthProviderText = (EditText) findViewById(R.id.editText_authprovider);
+ mCIServerText = (EditText) findViewById(R.id.editText_ciserver);
+
+ mGetConfigurationInfo =
+ (LinearLayout) findViewById(R.id.layout_GetConfiguration);
+ mConfigureSecInfo = (LinearLayout) findViewById(R.id.layout_ConfigurSec);
+ mProvisionDevPropInfo = (LinearLayout) findViewById(R.id.layout_ProvisionDevConf);
+ mProvisionCloudPropInfo = (LinearLayout) findViewById(R.id.layout_ProvisionCloudConf);
+
+ mAuthType = (Spinner) findViewById(R.id.spinner_authType);
+ mEncType = (Spinner) findViewById(R.id.spinner_encType);
+
+ mEasysetupProcess.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
+ @Override
+ public void onCheckedChanged(RadioGroup group, int checkedId) {
+ mGetConfigurationInfo.setVisibility(View.GONE);
+ mConfigureSecInfo.setVisibility(View.GONE);
+ mProvisionDevPropInfo.setVisibility(View.GONE);
+ mProvisionCloudPropInfo.setVisibility(View.GONE);
+
+ switch (checkedId) {
+ case R.id.btn_configurSec:
+ mConfigureSecInfo.setVisibility(View.VISIBLE);
+ break;
+
+ case R.id.btn_getConfiguration:
+ mGetConfigurationInfo.setVisibility(View.VISIBLE);
+ break;
+
+ case R.id.btn_provisionDevConf:
+ mProvisionDevPropInfo.setVisibility(View.VISIBLE);
+ break;
+
+ case R.id.btn_provisionCloudConf:
+ Log.d(TAG, "Starting login activity");
+ Intent intent = new Intent(EasysetupActivity.this, LoginActivity.class);
+ startActivityForResult(intent, 2);
+ mProvisionCloudPropInfo.setVisibility(View.VISIBLE);
+ break;
+ }
+ }
+ });
+
+ ArrayAdapter<CharSequence> adAuthType, adEnctype;
+
+ adAuthType = ArrayAdapter.createFromResource(this, R.array.auth_type,
+ android.R.layout.simple_spinner_item);
+ adAuthType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+
+ adEnctype = ArrayAdapter.createFromResource(this, R.array.enc_type,
+ android.R.layout.simple_spinner_item);
+ adEnctype.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+
+ mAuthType.setAdapter(adAuthType);
+ mAuthType.setSelection(0);
+
+ mEncType.setAdapter(adEnctype);
+ mEncType.setSelection(0);
+
+ addListenerForDiscoverEnrollee();
+ addListenerForStartConfigureSec();
+ addListenerForStartGetConfiguration();
+ addListenerForStartProvisionDevProp();
+ addListenerForStartProvisionCloudProp();
+
+ mSecurityMode.setClickable(false);
+ mConfigureSecProcess.setEnabled(false);
+ mGetConfigurationProcess.setEnabled(false);
+ mProvisionDevPropProcess.setEnabled(false);
+ mProvisionCloudPropProcess.setEnabled(false);
+
+ mEasySetup = EasySetup.getInstance(getApplicationContext());
+
+ initOICStack();
+
+ SharedPreferences settings =
+ getApplicationContext().getSharedPreferences("IoTivityCloud", 0);
+ mAccessToken = settings.getString("accesstoken", null);
+ mRefreshtoken = settings.getString("refreshtoken", null);
+ mUserID = settings.getString("uid", null);
+
+ if(mRefreshtoken == null)
+ {
+ Log.d(TAG, "Can not find refresh token");
+ }
+
+ if(mAccessToken == null && mRefreshtoken == null)
+ {
+ Log.d(TAG, "Starting login activity");
+ Intent intent = new Intent(EasysetupActivity.this, LoginActivity.class);
+ startActivityForResult(intent, 1);
+ }
+ else if(mAccessToken != null)
+ {
+ SignInDevice();
+ }
+ }
+
+ private void initOICStack() {
+ filePath = getFilesDir().getPath() + "/";
+
+ SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences
+ (getApplicationContext());
+ boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
+ if (isFirstRun) {
+ if(!copyJsonFromAsset())
+ {
+ Log.e(TAG, "initOICStack error: " + "copyJsonFromAsset()");
+ Toast.makeText(this,"Can't Copy DB file from asset, please retry start SampleApp.",
+ Toast.LENGTH_LONG).show();
+ return;
+ }
+ SharedPreferences.Editor editor = wmbPreference.edit();
+ editor.putBoolean("FIRSTRUN", false);
+ editor.commit();
+ }
+
+ cfg = new PlatformConfig(
+ this,
+ ServiceType.IN_PROC,
+ ModeType.CLIENT_SERVER,
+ "0.0.0.0", // bind to all available interfaces
+ 0,
+ QualityOfService.LOW, filePath + OIC_CLIENT_JSON_DB_FILE);
+ try {
+ /*
+ * Initialize DataBase
+ */
+
+ OcPlatform.Configure(cfg);
+
+ String sqlDbPath = getFilesDir().getAbsolutePath().replace("files", "databases") +
+ File.separator;
+ File file = new File(sqlDbPath);
+ //check files directory exists
+ if (!(file.isDirectory())) {
+ file.mkdirs();
+ Log.d(TAG, "Sql db directory created at " + sqlDbPath);
+ }
+ Log.d(TAG, "Sql db directory exists at " + sqlDbPath);
+
+ //SQLiteDatabase.openOrCreateDatabase(sqlDbPath+ OIC_SQL_DB_FILE, null);
+ OcProvisioning.provisionInit(sqlDbPath + OIC_SQL_DB_FILE);
+ mSecurityMode.setChecked(true);
+ } catch (OcException e) {
+ logMessage(TAG + "provisionInit error: " + e.getMessage());
+ Log.e(TAG, e.getMessage());
+ Toast.makeText(this,"provisionInit error: " + e.getMessage(),
+ Toast.LENGTH_LONG).show();
+ mSecurityMode.setChecked(false);
+ return;
+ } catch (UnsatisfiedLinkError e) {
+
+ // Note : Easy setup is built with SECURED = 0, but user still selects Security feature
+ // while running the Mediator App it couldn't find "libocprovision.so".
+ // As per the programmer guide, security feature should be invoked only if build is done with SECURED = 1.
+ mSecurityMode.setChecked(false);
+ Log.e(TAG, " Easy setup is built with secured = 0, but executed with security feature");
+ Toast.makeText(this,"Security is not enabled [Easy setup is built with SECURED = 0]",
+ Toast.LENGTH_LONG).show();
+ return;
+ }
+ }
+
+ OcPlatform.OnResourceFoundListener listener =
+ new OcPlatform.OnResourceFoundListener() {
+ @Override
+ public void onFindResourceFailed(Throwable throwable, String s) {
+ Log.e(TAG, "Failed found resource, ecode: " + s);
+ }
+ @Override
+ public void onResourceFound(OcResource ocResource) {
+ synchronized (mActivity) {
+ if(isFirstTime){
+ if (null == ocResource) {
+ Log.e(TAG, "Found resource is invalid");
+ return;
+ }
+
+ if(ocResource.getHost().contains("coap+tcp")) {
+ Log.d(TAG, "Recv Found resource event from tcp port," +
+ "ignoring URI : " + ocResource.getUri());
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mDiscoverResource.setEnabled(true);
+ }
+ });
+ return;
+ }
+
+ // Get the resource URI
+ String resourceUri = ocResource.getUri();
+ // Get the resource host address
+ String hostAddress = ocResource.getHost();
+ Log.d(TAG,"URI of the resource: " + resourceUri);
+ Log.d(TAG,"Host address of the resource: " + hostAddress);
+
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mDiscoverResource.setText("Found");
+ if(mSecurityMode.isChecked()) {
+ mConfigureSecProcess.setEnabled(true);
+ }
+ mGetConfigurationProcess.setEnabled(true);
+ mProvisionDevPropProcess.setEnabled(true);
+ mProvisionCloudPropProcess.setEnabled(true);
+ }
+ });
+ isFirstTime = false;
+ mRemoteEnrollee = mEasySetup.createRemoteEnrollee(ocResource);
+ mEnrolleeDeviceID = ocResource.getServerId();
+ }
+ }
+ }
+ };
+
+ private void addListenerForDiscoverEnrollee() {
+ mDiscoverResource.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ Thread thread = new Thread() {
+ boolean result = true;
+ @Override
+ public void run() {
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mDiscoverResource.setEnabled(false);
+ }
+ });
+
+ try {
+ String requestUri = OcPlatform.WELL_KNOWN_QUERY + "?rt=ocf.wk.prov";
+ OcPlatform.findResource("",
+ requestUri,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ listener
+ );
+ }
+ catch (OcException e) {
+ e.printStackTrace();
+ result = false;
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mDiscoverResource.setEnabled(true);
+ }
+ });
+ }
+ }
+ };
+
+ thread.start();
+ }
+ });
+ }
+
+ private void addListenerForStartConfigureSec() {
+ mStartConfigureSec.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ Thread thread = new Thread() {
+ @Override
+ public void run() {
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mStartConfigureSec.setEnabled(false);
+ }
+ });
+
+ try {
+ mRemoteEnrollee.provisionSecurity(new SecurityProvisioningCallback() {
+ @Override
+ public void onProgress(final SecurityProvisioningStatus securityProvisioningStatus) {
+ if(securityProvisioningStatus.getESResult() == ESResult.ES_OK) {
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mSecStateText.setText("Success");
+ mSecDevIDText.setText(securityProvisioningStatus.getDevUUID());
+ }
+ });
+ }
+ else {
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mSecStateText.setText("Failed");
+ mStartConfigureSec.setEnabled(true);
+ }
+ });
+ }
+ }
+ });
+ } catch (ESException e) {
+ e.printStackTrace();
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mStartConfigureSec.setEnabled(true);
+ }
+ });
+ }
+ }
+ };
+
+ thread.start();
+ }
+ });
+ }
+
+ private void addListenerForStartGetConfiguration(){
+ mStartGetConfiguration.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ Thread thread = new Thread() {
+ @Override
+ public void run() {
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mGetconfigurationStateText.setText("Process");
+ mStartGetConfiguration.setEnabled(false);
+ }
+ });
+
+ try {
+ mRemoteEnrollee.getConfiguration(new GetConfigurationCallback() {
+ @Override
+ public void onProgress(GetConfigurationStatus getConfigurationStatus) {
+ if(getConfigurationStatus.getESResult() == ESResult.ES_OK) {
+
+ final EnrolleeConf enrolleeConf = getConfigurationStatus.getEnrolleeConf();
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mGetconfigurationStateText.setText("Success");
+ mDevNameText.setText(enrolleeConf.getDeviceName());
+ setWifiModes(enrolleeConf.getWiFiModes());
+ setWifiFreq(enrolleeConf.getWiFiFreq());
+
+ if(enrolleeConf.isCloudAccessible()) {
+ mCloudAccessableText.setText("TRUE");
+ }
+ else {
+ mCloudAccessableText.setText("FALSE");
+ }
+ }
+ });
+
+ }
+ else {
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mGetconfigurationStateText.setText("Failed");
+ mStartGetConfiguration.setEnabled(true);
+ }
+ });
+ }
+ }
+ });
+ } catch (ESException e) {
+ e.printStackTrace();
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mGetconfigurationStateText.setText("Failed");
+ mStartGetConfiguration.setEnabled(true);
+ }
+ });
+ }
+ }
+ };
+
+ thread.start();
+ }
+ });
+ }
+
+ private void addListenerForStartProvisionDevProp() {
+ mStartProvisionDevProp.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ Thread thread = new Thread() {
+ @Override
+ public void run() {
+ try {
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mProvisionDevPropState.setText("Progress");
+ mStartProvisionDevProp.setEnabled(false);
+ }
+ });
+
+ String enrollerSSID = mEnrollerSsidText.getText().toString();
+ String enrollerPW = mEnrollerPWText.getText().toString();
+ WIFI_AUTHTYPE authType =
+ WIFI_AUTHTYPE.fromInt(mAuthType.getSelectedItemPosition());
+ WIFI_ENCTYPE encType =
+ WIFI_ENCTYPE.fromInt(mEncType.getSelectedItemPosition());
+ String inputLanguage = mInputLanguageText.getText().toString();
+ String inputCountry = mInputCountryText.getText().toString();
+
+ DeviceProp deviceProp = new DeviceProp();
+ deviceProp.setWiFiProp(enrollerSSID, enrollerPW, authType, encType);
+ deviceProp.setDevConfProp(inputLanguage, inputCountry);
+
+ mRemoteEnrollee.provisionDeviceProperties(deviceProp, new DevicePropProvisioningCallback() {
+ @Override
+ public void onProgress(DevicePropProvisioningStatus devPropProvisioningStatus) {
+ final ESResult result = devPropProvisioningStatus.getESResult();
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ if(result.equals(ESResult.ES_OK)) {
+ mProvisionDevPropState.setText("Success");
+ }
+ else if(result.equals(ESResult.ES_ERROR)) {
+ mProvisionDevPropState.setText("Failed");
+ }
+ else if(result.equals(ESResult.ES_UNAUTHORIZED)) {
+ mProvisionDevPropState.setText("Failed. Need SecProv");
+ }
+ mStartProvisionDevProp.setEnabled(true);
+ }
+ });
+ }
+ });
+ } catch (ESException e) {
+ e.printStackTrace();
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mProvisionDevPropState.setText("Failed");
+ mStartProvisionDevProp.setEnabled(true);
+ }
+ });
+ }
+ }
+ };
+
+ thread.start();
+ }
+ });
+ }
+
+ private void addListenerForStartProvisionCloudProp() {
+ mStartProvisionCloudProp.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ Thread thread = new Thread() {
+ @Override
+ public void run() {
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mProvisionCloudPropState.setText("Progress");
+ mStartProvisionCloudProp.setEnabled(false);
+ }
+ });
+
+ try {
+ String authCode = mAuthCodeText.getText().toString();
+ String authProvider = mAuthProviderText.getText().toString();
+ String ciserver = mCIServerText.getText().toString();
+
+ CloudProp cloudProp = new CloudProp();
+ cloudProp.setCloudProp(authCode, authProvider, ciserver);
+ cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3");
+
+ mRemoteEnrollee.provisionCloudProperties(cloudProp, new CloudPropProvisioningCallback() {
+ @Override
+ public void onProgress(CloudPropProvisioningStatus cloudProvisioningStatus) {
+ final ESResult result = cloudProvisioningStatus.getESResult();
+ final ESCloudProvState state = cloudProvisioningStatus.getESCloudState();
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ if(result.equals(ESResult.ES_OK)) {
+ if(state.equals(ESCloudProvState.ES_CLOUD_ENROLLEE_FOUND)) {
+ mProvisionCloudPropState.setText("Found Resource");
+ }
+ else if(state.equals(ESCloudProvState.ES_CLOUD_PROVISIONING_SUCCESS)) {
+ mProvisionCloudPropState.setText("Success");
+ }
+ }
+ else {
+ if(state.equals(ESCloudProvState.ES_CLOUD_ENROLLEE_NOT_FOUND)) {
+ mProvisionCloudPropState.setText("Not Found Resource");
+ }
+ else if(state.equals(ESCloudProvState.ES_CLOUD_PROVISIONING_ERROR)) {
+ mProvisionCloudPropState.setText("Failed");
+ }
+ mStartProvisionCloudProp.setEnabled(true);
+ }
+ }
+ });
+ }
+ });
+ } catch (ESException e) {
+ e.printStackTrace();
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mProvisionCloudPropState.setText("Failed");
+ mStartProvisionCloudProp.setEnabled(true);
+ }
+ });
+ }
+ }
+ };
+
+ thread.start();
+ }
+ });
+ }
+
+ private boolean copyJsonFromAsset() {
+ InputStream inputStream = null;
+ OutputStream outputStream = null;
+ int length;
+ byte[] buffer = new byte[BUFFER_SIZE];
+ try {
+ inputStream = getAssets().open(OIC_CLIENT_JSON_DB_FILE);
+ File file = new File(filePath);
+ //check files directory exists
+ if (!(file.exists() && file.isDirectory())) {
+ file.mkdirs();
+ }
+ outputStream = new FileOutputStream(filePath + OIC_CLIENT_JSON_DB_FILE);
+ while ((length = inputStream.read(buffer)) != -1) {
+ outputStream.write(buffer, 0, length);
+ }
+ } catch (NullPointerException e) {
+ logMessage(TAG + "Null pointer exception " + e.getMessage());
+ Log.e(TAG, e.getMessage());
+ return false;
+ } catch (FileNotFoundException e) {
+ logMessage(TAG + "Json svr db file not found " + e.getMessage());
+ Log.e(TAG, e.getMessage());
+ return false;
+ } catch (IOException e) {
+ logMessage(TAG + OIC_CLIENT_JSON_DB_FILE + " file copy failed");
+ Log.e(TAG, e.getMessage());
+ return false;
+ } finally {
+ if (inputStream != null) {
+ try {
+ inputStream.close();
+ } catch (IOException e) {
+ Log.e(TAG, e.getMessage());
+ return false;
+ }
+ }
+ if (outputStream != null) {
+ try {
+ outputStream.close();
+ } catch (IOException e) {
+ Log.e(TAG, e.getMessage());
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ public void logMessage(String text) {
+
+ }
+
+ public void setWifiModes(ArrayList<WIFI_MODE> types) {
+ String temp = "WIFI - ";
+
+ for(WIFI_MODE type : types) {
+ if(type.equals(WIFI_MODE.WIFI_11A)) {
+ temp = temp + "11A ";
+ }
+ else if(type.equals(WIFI_MODE.WIFI_11B)) {
+ temp = temp + "11B ";
+ }
+ else if(type.equals(WIFI_MODE.WIFI_11G)) {
+ temp = temp + "11G ";
+ }
+ else if(type.equals(WIFI_MODE.WIFI_11N)) {
+ temp = temp + "11N ";
+ }
+ else if(type.equals(WIFI_MODE.WIFI_11AC)) {
+ temp = temp + "11AC ";
+ }
+ }
+ final String modeTypes = temp;
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mWifiModeText.setText(modeTypes);
+ }
+ });
+ }
+
+ public void setWifiFreq(final WIFI_FREQ freq) {
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ if(freq.equals(WIFI_FREQ.WIFI_24G)) {
+ mWifiFreqText.setText("2.4G");
+ }
+ else if(freq.equals(WIFI_FREQ.WIFI_5G)) {
+ mWifiFreqText.setText("5G");
+ }
+ else if(freq.equals(WIFI_FREQ.WIFI_BOTH)) {
+ mWifiFreqText.setText("2.4G & 5G");
+ }
+ }
+ });
+ }
+
+ @Override
+ public void onPresence(OcPresenceStatus status, int sequence, String host) {
+ final String strStaus = status.getValue();
+ Log.d(TAG, "Presence response: " + strStaus + " sequence: " + sequence + " host: " + host);
+ runOnUiThread(new Runnable()
+ {
+ public void run() {
+ Toast.makeText(EasysetupActivity.this, "Easy-Setup completed", Toast.LENGTH_SHORT).show();
+ }
+ });
+ }
+
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ super.onActivityResult(requestCode, resultCode, data);
+ if(resultCode==RESULT_OK && requestCode==1){
+ mAuthCode = data.getStringExtra("authCode");
+ mAuthProvider = data.getStringExtra("authProvider");
+ String text = "Received authCode= " + mAuthCode;
+ Log.d(TAG, text);
+ SignUpDevice();
+ }
+ else if(resultCode==RESULT_OK && requestCode==2)
+ {
+ mEnrolleeAuthCode = data.getStringExtra("authCode");
+ mAuthProvider = data.getStringExtra("authProvider");
+ mAuthCodeText.setText(mEnrolleeAuthCode);
+ mAuthProviderText.setText(mAuthProvider);
+ mAuthCodeText.setEnabled(false);
+ mAuthProviderText.setEnabled(false);
+
+ try
+ {
+ OcPlatform.subscribePresence(samsungCIServer, "oic.res&di=" + mEnrolleeDeviceID,
+ EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP, OcConnectivityType.CT_IP_USE_V4), this);
+ }
+ catch (Exception e)
+ {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ OcResource.OnPostListener onRefreshTokenPost = new OcResource.OnPostListener() {
+ @Override
+ public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
+ Log.d(TAG, "onRefreshTokenPost..");
+ try {
+ mAccessToken = ocRepresentation.getValue("accesstoken");
+ mRefreshtoken = ocRepresentation.getValue("refreshtoken");
+
+ saveCloudTokenAtSharedPreferences();
+ }
+ catch (OcException e)
+ {
+ e.printStackTrace();
+ }
+
+ SignInDevice();
+ }
+
+ @Override
+ public void onPostFailed(Throwable throwable) {
+ Log.d(TAG, "onRefreshTokenPost failed..");
+ }
+ };
+
+ public void RefreshToken() {
+ try {
+ OcResource authResource = OcPlatform.constructResourceObject(samsungCIServer, "/.well-known/ocf/account/tokenrefresh",
+ EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP, OcConnectivityType.CT_IP_USE_V4),
+ false, Arrays.asList("oic.wk.account"), Arrays.asList(OcPlatform.DEFAULT_INTERFACE));
+ OcRepresentation rep = new OcRepresentation();
+
+ runOnUiThread(new Runnable()
+ {
+ public void run() {
+ Toast.makeText(EasysetupActivity.this, "RefreshToken in progress..", Toast.LENGTH_SHORT).show();
+ }
+ });
+
+ rep.setValue("di", deviceID);
+ rep.setValue("granttype", "refresh_token");
+ rep.setValue("refreshtoken", mRefreshtoken);
+ rep.setValue("uid", mUserID);
+ authResource.post(rep, new HashMap<String, String>(), onRefreshTokenPost);
+ }
+ catch(OcException e)
+ {
+ e.printStackTrace();
+ }
+
+ Log.d(TAG, "No error while executing login");
+ }
+
+ private void saveCloudTokenAtSharedPreferences() {
+ Log.d(TAG, "accesstoken: " + mAccessToken);
+ SharedPreferences settings = getApplicationContext().getSharedPreferences("IoTivityCloud", 0);
+ SharedPreferences.Editor editor = settings.edit();
+ editor.putString("accesstoken", mAccessToken);
+ editor.putString("refreshtoken", mRefreshtoken);
+ editor.putString("uid", mUserID);
+
+ if(editor.commit() == true)
+ Log.d(TAG, "accesstoken saved");
+ else
+ Log.d(TAG, "accesstoken not saved");
+ }
+
+ OcResource.OnPostListener onSignUpPost = new OcResource.OnPostListener() {
+ @Override
+ public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
+ Log.d(TAG, "onSignUpPost..");
+ try {
+ runOnUiThread(new Runnable()
+ {
+ public void run() {
+ Toast.makeText(EasysetupActivity.this, "Sign-up completed", Toast.LENGTH_SHORT).show();
+ }
+ });
+
+ mAccessToken = ocRepresentation.getValue("accesstoken");
+ mRefreshtoken = ocRepresentation.getValue("refreshtoken");
+ mUserID = ocRepresentation.getValue("uid");
+
+ if(mAccessToken != null)
+ {
+ saveCloudTokenAtSharedPreferences();
+ SignInDevice();
+ }
+ }
+ catch (OcException e)
+ {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void onPostFailed(Throwable throwable) {
+ Log.d(TAG, "onSignUpPost failed.. : " + throwable.getMessage());
+ }
+ };
+
+ private void SignUpDevice() {
+ try {
+ OcResource authResource = OcPlatform.constructResourceObject(samsungCIServer, "/.well-known/ocf/account",
+ EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP, OcConnectivityType.CT_IP_USE_V4),
+ false, Arrays.asList("oic.wk.account"), Arrays.asList(OcPlatform.DEFAULT_INTERFACE));
+ OcRepresentation rep = new OcRepresentation();
+
+ runOnUiThread(new Runnable()
+ {
+ public void run() {
+ Toast.makeText(EasysetupActivity.this, "SignUpDevice in progress..", Toast.LENGTH_SHORT).show();
+ }
+ });
+
+ rep.setValue("di", deviceID);
+ rep.setValue("authprovider", mAuthProvider);
+ rep.setValue("authcode", mAuthCode);
+ authResource.post(rep, new HashMap<String, String>(), onSignUpPost);
+ }
+ catch(OcException e)
+ {
+ e.printStackTrace();
+ }
+
+ Log.d(TAG, "No error while executing SignUp");
+ }
+
+ OcResource.OnPostListener onSignInPost = new OcResource.OnPostListener() {
+ @Override
+ public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
+ Log.d(TAG, "onSignInPost..");
+
+ runOnUiThread(new Runnable()
+ {
+ public void run() {
+ Toast.makeText(EasysetupActivity.this, "Sign-in completed", Toast.LENGTH_SHORT).show();
+ }
+ });
+ }
+
+ @Override
+ public void onPostFailed(Throwable ex) {
+ if (ex instanceof OcException) {
+ OcException ocEx = (OcException) ex;
+ ErrorCode errCode = ocEx.getErrorCode();
+ Log.e(TAG, ocEx.getMessage());
+ if (ErrorCode.UNAUTHORIZED_REQ != errCode) {
+ RefreshToken();
+ }
+ }
+ }
+ };
+
+ private void SignInDevice() {
+ try {
+ OcResource authResource = OcPlatform.constructResourceObject(samsungCIServer, "/.well-known/ocf/account/session",
+ EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP, OcConnectivityType.CT_IP_USE_V4),
+ false, Arrays.asList("oic.wk.account"), Arrays.asList(OcPlatform.DEFAULT_INTERFACE));
+ OcRepresentation rep = new OcRepresentation();
+
+ runOnUiThread(new Runnable()
+ {
+ public void run() {
+ Toast.makeText(EasysetupActivity.this, "SignInDevice in progress..", Toast.LENGTH_SHORT).show();
+ }
+ });
+
+ rep.setValue("di", deviceID);
+ rep.setValue("accesstoken", mAccessToken);
+ rep.setValue("login", true);
+ rep.setValue("uid", mUserID);
+ authResource.post(rep, new HashMap<String, String>(), onSignInPost);
+
+ }
+ catch(OcException e)
+ {
+ e.printStackTrace();
+ }
+
+ Log.d(TAG, "No error while executing login");
+ }
+
+ @Override
+ protected void onDestroy() {
+ super.onDestroy();
+ }
+}
--- /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;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.net.ConnectivityManager;
+import android.net.NetworkInfo;
+import android.net.UrlQuerySanitizer;
+import android.net.wifi.WifiConfiguration;
+import android.net.wifi.WifiManager;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.preference.PreferenceManager;
+import android.util.Log;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.webkit.WebView;
+import android.webkit.WebViewClient;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.ProgressBar;
+import android.widget.RadioButton;
+import android.widget.RelativeLayout;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcProvisioning;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+
+public class LoginActivity extends Activity {
+ private static final String TAG = "Easysetup Login: ";
+
+ /* Samsung account */
+ private WebView mWebView = null;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_login);
+
+ /* For Samsung account authentifaction */
+ mWebView = (WebView) findViewById(R.id.webView);
+ mWebView.setVisibility(View.VISIBLE);
+ mWebView.setInitialScale(200);
+ mWebView.getSettings().setJavaScriptEnabled(true);
+ //mWebView.getSettings().setSupportZoom(true);
+ mWebView.getSettings().setBuiltInZoomControls(true);
+ mWebView.setWebViewClient(new WebViewClientClass());
+
+ mWebView.loadUrl("https://github.com/login?return_to=%2Flogin%2Foauth%2Fauthorize%3Fclient_id%3Dea9c18f540323b0213d0%26redirect_uri%3Dhttp%253A%252F%252Fwww.example.com%252Foauth_callback%252F");
+ }
+
+ public void onDestroy() {
+ super.onDestroy();
+ }
+
+ private class WebViewClientClass extends WebViewClient {
+
+ @Override
+ public void onPageFinished(WebView view, String url) {
+ Log.e(TAG, "called!!! url=" + url);
+
+ if(url.contains("http://www.example.com/oauth_callback/")){
+
+ mWebView.setVisibility(View.INVISIBLE);
+
+ //parsing url
+ UrlQuerySanitizer sanitizer = new UrlQuerySanitizer();
+ sanitizer.setAllowUnregisteredParamaters(true);
+ sanitizer.parseUrl(url);
+
+ String mAuthCode = null;
+ mAuthCode = sanitizer.getValue("code");
+
+ Intent intent = getIntent();
+ intent.putExtra("authCode", mAuthCode);
+ intent.putExtra("authProvider", "github");
+
+ setResult(RESULT_OK, intent);
+
+ finish();
+ }
+ }
+ }
+}
+++ /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 android.app.Activity;\r
-import android.app.AlertDialog;\r
-import android.content.DialogInterface;\r
-import android.content.Intent;\r
-import android.content.SharedPreferences;\r
-import android.database.sqlite.SQLiteDatabase;\r
-import android.net.ConnectivityManager;\r
-import android.net.NetworkInfo;\r
-import android.net.wifi.WifiConfiguration;\r
-import android.net.wifi.WifiManager;\r
-import android.os.Bundle;\r
-import android.os.Handler;\r
-import android.os.Message;\r
-import android.preference.PreferenceManager;\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.LinearLayout;\r
-import android.widget.ProgressBar;\r
-import android.widget.RadioButton;\r
-import android.widget.RelativeLayout;\r
-import android.widget.TextView;\r
-import android.widget.Toast;\r
-\r
-import org.iotivity.base.ModeType;\r
-import org.iotivity.base.OcException;\r
-import org.iotivity.base.OcPlatform;\r
-import org.iotivity.base.OcProvisioning;\r
-import org.iotivity.base.PlatformConfig;\r
-import org.iotivity.base.QualityOfService;\r
-import org.iotivity.base.ServiceType;\r
-import org.iotivity.service.easysetup.mediator.EasySetupService;\r
-import org.iotivity.service.easysetup.mediator.EasySetupStatus;\r
-import org.iotivity.service.easysetup.mediator.EnrolleeDevice;\r
-import org.iotivity.service.easysetup.mediator.IpOnBoardingConnection;\r
-import org.iotivity.service.easysetup.mediator.EnrolleeDeviceFactory;\r
-import org.iotivity.service.easysetup.mediator.WiFiOnBoardingConfig;\r
-import org.iotivity.service.easysetup.mediator.WiFiProvConfig;\r
-\r
-import java.io.File;\r
-import java.io.FileNotFoundException;\r
-import java.io.FileOutputStream;\r
-import java.io.IOException;\r
-import java.io.InputStream;\r
-import java.io.OutputStream;\r
-\r
-\r
-public class MainActivity extends Activity {\r
- private static final String TAG = "Easysetup Mediator: ";\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
- public static final String OIC_CLIENT_JSON_DB_FILE = "oic_svr_db_client.dat";\r
- public static final String OIC_SQL_DB_FILE = "PDM.db";\r
-\r
- private static final int BUFFER_SIZE = 1024;\r
- private String filePath = "";\r
- private boolean isSecurityEnabled = false;\r
- //create platform config\r
- PlatformConfig cfg;\r
-\r
-\r
- String mSoftAPSsid;\r
- String mSoftAPPassword;\r
- String mEnrollerSsid;\r
- String mEnrollerPassword;\r
-\r
- EditText mSoftAPSsidText;\r
- EditText mSoftAPPassText;\r
- EditText mEnrollerSsidText;\r
- EditText mEnrollerPasswordPassText;\r
-\r
- TextView mDeviceIpTextView;\r
- TextView mDeviceMacTextView;\r
- TextView mResultTextView;\r
-\r
- ProgressBar mProgressbar;\r
-\r
- Button mStartButton;\r
- Button mStopButton;\r
-\r
- RadioButton mEnrollee;\r
- RadioButton mMediator;\r
- RadioButton mEnableSecurity;\r
-\r
- LinearLayout mSoftAP;\r
- RelativeLayout mDeviceInfo;\r
- TextView mDeviceText;\r
-\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
- /*\r
- * Initialize widgets to get user input for target network's SSID &\r
- * password\r
- */\r
- mSoftAP = (LinearLayout) findViewById(R.id.softAP);\r
- mDeviceInfo = (RelativeLayout) findViewById(R.id.deviceInfo);\r
- mDeviceText = (TextView) findViewById(R.id.textViewDeviceinfo);\r
-\r
- mSoftAPSsidText = (EditText) findViewById(R.id.ssid);\r
- mSoftAPPassText = (EditText) findViewById(R.id.password);\r
- mEnrollerSsidText = (EditText) findViewById(R.id.enrolleeSsid);\r
- mEnrollerPasswordPassText = (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
- mEnrollee = (RadioButton) findViewById(R.id.enrollee);\r
- mMediator = (RadioButton) findViewById(R.id.mediator);\r
- mEnableSecurity = (RadioButton) findViewById(R.id.enablesecurity);\r
-\r
- mStartButton = (Button) findViewById(R.id.startSetup);\r
-\r
- mEnrollee.setChecked(false);\r
- mMediator.setChecked(false);\r
- mStartButton.setEnabled(false);\r
-\r
- /* Create EnrolleeDevice Factory instance */\r
- mDeviceFactory = EnrolleeDeviceFactory\r
- .newInstance(getApplicationContext());\r
-\r
- addListenerForStartAP();\r
- addListenerForStopAP();\r
-\r
- // default values for target network\r
- mEnrollerSsidText.setText(R.string.target_default_ssid);\r
- mEnrollerPasswordPassText.setText(R.string.target_default_pwd);\r
- mSoftAPSsidText.setEnabled(false);\r
- mSoftAPPassText.setEnabled(false);\r
-\r
- mEnrollee.setOnClickListener(new OnClickListener() {\r
- @Override\r
- public void onClick(View v) {\r
-\r
- mMediator.setChecked(false);\r
- AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(\r
- MainActivity.this);\r
- alertDialogBuilder.setTitle("Network selection");\r
- alertDialogBuilder\r
- .setMessage("Proceed to select the network!")\r
- .setCancelable(false)\r
- .setPositiveButton("Yes",\r
- new DialogInterface.OnClickListener() {\r
- public void onClick(DialogInterface dialog,\r
- int id) {\r
- MainActivity.this\r
- .startActivity(new Intent(\r
- WifiManager.ACTION_PICK_WIFI_NETWORK));\r
-\r
- mStartButton.setEnabled(true);\r
- mSoftAP.setVisibility(View.INVISIBLE);\r
- mDeviceInfo\r
- .setVisibility(View.INVISIBLE);\r
- mDeviceText\r
- .setVisibility(View.INVISIBLE);\r
- }\r
- })\r
- .setNegativeButton("No",\r
- new DialogInterface.OnClickListener() {\r
- public void onClick(DialogInterface dialog,\r
- int id) {\r
- mEnrollee.setChecked(false);\r
- mStartButton.setEnabled(false);\r
- dialog.cancel();\r
- }\r
- });\r
- alertDialogBuilder.create().show();\r
- }\r
- });\r
-\r
- mMediator.setOnClickListener(new OnClickListener() {\r
- @Override\r
- public void onClick(View v) {\r
- mStartButton.setEnabled(true);\r
- mEnrollee.setChecked(false);\r
- mSoftAPSsidText.setEnabled(false);\r
- mSoftAPPassText.setEnabled(false);\r
- mSoftAPSsidText.setText(R.string.softAP_ssid);\r
- mSoftAPPassText.setText(R.string.softAP_pwd);\r
- mDeviceIpTextView.setText(R.string.not_available);\r
- mDeviceMacTextView.setText(R.string.not_available);\r
- mResultTextView.setText(R.string.not_started);\r
- mSoftAP.setVisibility(View.VISIBLE);\r
- mDeviceInfo.setVisibility(View.VISIBLE);\r
- mDeviceText.setVisibility(View.VISIBLE);\r
- }\r
- });\r
-\r
- mEnableSecurity.setOnClickListener(new OnClickListener() {\r
- @Override\r
- public void onClick(View v) {\r
- filePath = getFilesDir().getPath() + "/";\r
- if (isSecurityEnabled) {\r
- isSecurityEnabled = false;\r
- mEnableSecurity.setChecked(false);\r
- }\r
- else {\r
- isSecurityEnabled = true;\r
- mEnableSecurity.setChecked(true);\r
- }\r
- //copy json when application runs first time\r
- SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences\r
- (getApplicationContext());\r
- boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);\r
- if (isFirstRun) {\r
- copyJsonFromAsset();\r
- SharedPreferences.Editor editor = wmbPreference.edit();\r
- editor.putBoolean("FIRSTRUN", false);\r
- editor.commit();\r
- }\r
-\r
- initOICStack();\r
- }\r
- });\r
- /* Create Easy Setup Service instance */\r
- mEasySetupService = EasySetupService.getInstance(\r
- getApplicationContext(), new EasySetupStatus() {\r
-\r
- @Override\r
- public void onFinished(final EnrolleeDevice enrolledevice) {\r
- Log.i("MainActivity", "onFinished() is received "\r
- + enrolledevice.isSetupSuccessful());\r
- if (enrolledevice.isSetupSuccessful()) {\r
- mHandler.sendEmptyMessage(SUCCESS);\r
- } else {\r
- mHandler.sendEmptyMessage(FAILED);\r
- }\r
- }\r
-\r
- @Override\r
- public void onProgress(EnrolleeDevice enrolleeDevice) {\r
- Log.i("MainActivity", "onProgress() is received ");\r
- mHandler.sendEmptyMessage(STATE_CHANGED);\r
- }\r
- });\r
- }\r
-\r
- /**\r
- * configure OIC platform and call findResource\r
- */\r
- private void initOICStack() {\r
- cfg = new PlatformConfig(\r
- this,\r
- ServiceType.IN_PROC,\r
- ModeType.CLIENT_SERVER,\r
- "0.0.0.0", // bind to all available interfaces\r
- 0,\r
- QualityOfService.LOW, filePath + OIC_CLIENT_JSON_DB_FILE);\r
- try {\r
- /*\r
- * Initialize DataBase\r
- */\r
-\r
- OcPlatform.Configure(cfg);\r
-\r
- String sqlDbPath = getFilesDir().getAbsolutePath().replace("files", "databases") +\r
- File.separator;\r
- File file = new File(sqlDbPath);\r
- //check files directory exists\r
- if (!(file.isDirectory())) {\r
- file.mkdirs();\r
- Log.d(TAG, "Sql db directory created at " + sqlDbPath);\r
- }\r
- Log.d(TAG, "Sql db directory exists at " + sqlDbPath);\r
-\r
- //SQLiteDatabase.openOrCreateDatabase(sqlDbPath+ OIC_SQL_DB_FILE, null);\r
- OcProvisioning.provisionInit(sqlDbPath + OIC_SQL_DB_FILE);\r
- } catch (OcException e) {\r
- logMessage(TAG + "provisionInit error: " + e.getMessage());\r
- Log.e(TAG, e.getMessage());\r
- } catch (UnsatisfiedLinkError e) {\r
-\r
- // Note : Easy setup is built with SECURED = 0, but user still selects Security feature\r
- // while running the Mediator App it couldn't find "libocprovision.so".\r
- // As per the programmer guide, security feature should be invoked only if build is done with SECURED = 1.\r
- Log.e(TAG, " Easy setup is built with secured = 0, but executed with security feature");\r
- Toast.makeText(this,"Security is not enabled [Easy setup is built with SECURED = 0]",\r
- Toast.LENGTH_LONG).show();\r
- mEnableSecurity.setChecked(false);\r
- }\r
- }\r
- /**\r
- * Copy svr db json file from assets folder to app data files dir\r
- */\r
- private void copyJsonFromAsset() {\r
- InputStream inputStream = null;\r
- OutputStream outputStream = null;\r
- int length;\r
- byte[] buffer = new byte[BUFFER_SIZE];\r
- try {\r
- inputStream = getAssets().open(OIC_CLIENT_JSON_DB_FILE);\r
- File file = new File(filePath);\r
- //check files directory exists\r
- if (!(file.exists() && file.isDirectory())) {\r
- file.mkdirs();\r
- }\r
- outputStream = new FileOutputStream(filePath + OIC_CLIENT_JSON_DB_FILE);\r
- while ((length = inputStream.read(buffer)) != -1) {\r
- outputStream.write(buffer, 0, length);\r
- }\r
- } catch (NullPointerException e) {\r
- logMessage(TAG + "Null pointer exception " + e.getMessage());\r
- Log.e(TAG, e.getMessage());\r
- } catch (FileNotFoundException e) {\r
- logMessage(TAG + "Json svr db file not found " + e.getMessage());\r
- Log.e(TAG, e.getMessage());\r
- } catch (IOException e) {\r
- logMessage(TAG + OIC_CLIENT_JSON_DB_FILE + " file copy failed");\r
- Log.e(TAG, e.getMessage());\r
- } finally {\r
- if (inputStream != null) {\r
- try {\r
- inputStream.close();\r
- } catch (IOException e) {\r
- Log.e(TAG, e.getMessage());\r
- }\r
- }\r
- if (outputStream != null) {\r
- try {\r
- outputStream.close();\r
- } catch (IOException e) {\r
- Log.e(TAG, e.getMessage());\r
- }\r
- }\r
- }\r
- }\r
-\r
- public void logMessage(String text) {\r
-\r
- }\r
-\r
-\r
- public void onDestroy() {\r
- super.onDestroy();\r
- /* Reset the Easy setup process */\r
- if (mEasySetupService != null) {\r
- mEasySetupService.finish();\r
- }\r
- }\r
-\r
- public void addListenerForStartAP() {\r
- mStartButton = (Button) findViewById(R.id.startSetup);\r
- mStartButton.setOnClickListener(new OnClickListener() {\r
- @Override\r
- public void onClick(View arg0) {\r
- try {\r
- if (mEnrollee.isChecked()) {\r
- // Check the wifi connectivity\r
- if (!isConnectedTowifi()) {\r
- return;\r
- }\r
-\r
- mEnrollerSsid = mEnrollerSsidText.getText().toString();\r
- mEnrollerPassword = mEnrollerPasswordPassText.getText()\r
- .toString();\r
-\r
- mWiFiProvConfig = new WiFiProvConfig(mEnrollerSsid,\r
- mEnrollerPassword);\r
- mWiFiProvConfig.setSecured(isSecurityEnabled);\r
- mDevice = mDeviceFactory\r
- .newEnrolleeDevice(mWiFiProvConfig);\r
- Thread thread = new Thread() {\r
- @Override\r
- public void run() {\r
- try {\r
- mEasySetupService.startSetup(mDevice);\r
- }catch (Exception e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- };\r
- thread.start();\r
- } else {\r
- mSoftAPSsid = mSoftAPSsidText.getText().toString();\r
- mSoftAPPassword = mSoftAPPassText.getText().toString();\r
- mEnrollerSsid = mEnrollerSsidText.getText().toString();\r
- mEnrollerPassword = mEnrollerPasswordPassText.getText()\r
- .toString();\r
-\r
- mWiFiProvConfig = new WiFiProvConfig(mEnrollerSsid,\r
- mEnrollerPassword);\r
- mWiFiProvConfig.setSecured(isSecurityEnabled);\r
- mWiFiOnBoardingConfig = new WiFiOnBoardingConfig();\r
-\r
- /*\r
- * Provide the target credentials to be provisioned to\r
- * the Enrollee by Mediator\r
- */\r
- mWiFiOnBoardingConfig.setSSId("EasySetup123");\r
- mWiFiOnBoardingConfig.setSharedKey("EasySetup123");\r
- mWiFiOnBoardingConfig\r
- .setAuthAlgo(WifiConfiguration.AuthAlgorithm.OPEN);\r
- mWiFiOnBoardingConfig\r
- .setKms(WifiConfiguration.KeyMgmt.WPA_PSK);\r
- mDevice = mDeviceFactory.newEnrolleeDevice(\r
- mWiFiProvConfig, mWiFiOnBoardingConfig);\r
- mEasySetupService.startSetup(mDevice);\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
- mStopButton.setEnabled(true);\r
-\r
- } catch (Exception e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- });\r
- }\r
-\r
- public void addListenerForStopAP() {\r
- mStopButton = (Button) findViewById(R.id.stopSetup);\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
- try {\r
- Thread thread = new Thread() {\r
- @Override\r
- public void run() {\r
- try {\r
- mEasySetupService.stopSetup(mDevice);\r
- }catch (Exception e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- };\r
- thread.start();\r
-\r
- }catch(Exception e){\r
- Log.i("Stop setup", "Exception");\r
- }\r
- }\r
- });\r
- }\r
-\r
- private boolean isConnectedTowifi() {\r
-\r
- AlertDialog dialog;\r
- ConnectivityManager connManager;\r
- NetworkInfo wifi;\r
-\r
- // Check the wifi connectivity\r
- connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);\r
- wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);\r
- if (false == wifi.isConnected()) {\r
-\r
- AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);\r
- dialogBuilder.setTitle("Error");\r
- dialogBuilder\r
- .setMessage("WiFi is not enabled/connected! Please connect the WiFi..");\r
- dialogBuilder.setCancelable(false);\r
- dialogBuilder.setPositiveButton("OK",\r
- new DialogInterface.OnClickListener() {\r
- @Override\r
- public void onClick(DialogInterface dialog, int which) {\r
-\r
- MainActivity.this.startActivity(new Intent(\r
- WifiManager.ACTION_PICK_WIFI_NETWORK));\r
-\r
- }\r
- });\r
- dialogBuilder.setNegativeButton("Cancel",\r
- new DialogInterface.OnClickListener() {\r
- @Override\r
- public void onClick(DialogInterface dialog, int which) {\r
- }\r
- });\r
-\r
- dialog = dialogBuilder.create();\r
- dialog.show();\r
- return false;\r
- }\r
- return true;\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,\r
- 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,\r
- Toast.LENGTH_SHORT).show();\r
- break;\r
- }\r
-\r
- case STATE_CHANGED: {\r
- String resultMsg = "Device state changed";\r
- Toast.makeText(getApplicationContext(), resultMsg,\r
- Toast.LENGTH_SHORT).show();\r
- break;\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:orientation="vertical"
+ android:id="@+id/loginlayout"
+ tools:context="org.iotivity.service.easysetup.mediator.LoginActivity">
+
+ <WebView
+ android:id="@+id/webView"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:visibility="visible" />
+
+</LinearLayout>
+++ /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:orientation="horizontal">
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_vertical"
- android:textStyle="bold"
- android:textColor="@android:color/holo_red_dark"
- android:textSize="20dp"
- android:text="Soft AP "/>
-
- <RadioButton
-
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Enrollee "
- android:id="@+id/enrollee"
- android:textStyle="bold"
- android:layout_gravity="center_horizontal"
- android:checked="false"
- />
-
- <RadioButton
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Mediator"
- android:id="@+id/mediator"
- android:textStyle="bold"
- android:layout_gravity="center_horizontal"
- android:checked="false"
- />
- </LinearLayout>
-
- <LinearLayout
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center"
- 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="10dp" />
-
- </LinearLayout>
-
- <RadioButton
- android:layout_width="120dp"
- android:layout_height="wrap_content"
- android:text="Enable Security"
- android:id="@+id/enablesecurity"
- android:textStyle="bold"
- android:layout_gravity="center_horizontal"
- android:checked="false"/>
-
- <LinearLayout
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerHorizontal="true"
- android:layout_gravity="center"
- android:layout_marginTop="5dp"
- 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="5dp"
- 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:id="@+id/softAP"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerHorizontal="true"
- android:layout_gravity="center"
- android:layout_marginTop="5dp"
- 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="5dp"
- 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:id="@+id/textViewDeviceinfo"
- 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:id="@+id/deviceInfo"
- 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_marginTop="5dp"
- android:orientation="horizontal"
- android:weightSum="1">
-
- <Button
- android:id="@+id/startSetup"
- android:layout_width="160dp"
- android:layout_height="50dp"
- android:layout_alignParentTop="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="160dp"
- android:layout_height="50dp"
- 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
+<?xml version="1.0" encoding="utf-8"?>\r
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"\r
+ android:orientation="vertical" android:layout_width="match_parent"\r
+ android:layout_height="match_parent"\r
+ android:baselineAligned="true"\r
+ android:weightSum="1"\r
+ android:nestedScrollingEnabled="false">\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content">\r
+\r
+ <Button\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:text="Discovery"\r
+ android:id="@+id/btn_discoverResource"\r
+ android:layout_marginLeft="20dp"\r
+ android:layout_marginTop="10dp" />\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="match_parent"\r
+ android:weightSum="1"\r
+ android:baselineAligned="true"\r
+ android:layout_marginLeft="20dp"\r
+ android:id="@+id/layout_Security"\r
+ android:layout_marginRight="20dp">\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:text="@string/security_mode"\r
+ android:id="@+id/text_EnableSecurity"\r
+ android:phoneNumber="false"\r
+ android:textSize="16sp"\r
+ android:layout_marginTop="10dp"\r
+ android:layout_marginLeft="20dp" />\r
+\r
+ <ToggleButton\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/btn_Security"\r
+ android:layout_marginLeft="40dp"\r
+ android:layout_weight="0"\r
+ android:textOff="Disable"\r
+ android:textOn="Enable"\r
+ android:layout_marginTop="10dp" />\r
+\r
+ </LinearLayout>\r
+\r
+ </LinearLayout>\r
+\r
+ <View\r
+ android:layout_height="2dip"\r
+ android:background="#FF909090"\r
+ android:layout_marginTop="10dp"\r
+ android:layout_marginBottom="10dp"\r
+ android:layout_marginLeft="15dp"\r
+ android:layout_marginRight="15dp"\r
+ android:layout_width="match_parent" />\r
+\r
+ <LinearLayout\r
+ android:orientation="vertical"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/layout_Excution"\r
+ android:layout_marginLeft="10dp"\r
+ android:layout_marginRight="10dp">\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:text="@string/easysetup_sequence"\r
+ android:id="@+id/textView22"\r
+ android:layout_marginLeft="10dp"\r
+ android:textSize="16sp" />\r
+\r
+ <RadioGroup\r
+ android:layout_width="match_parent"\r
+ android:layout_height="match_parent"\r
+ android:layout_marginTop="5dp"\r
+ android:id="@+id/rg_EasysetupProcess"\r
+ android:layout_marginLeft="20dp">\r
+\r
+ <RadioButton\r
+ android:layout_width="160dp"\r
+ android:layout_height="32dp"\r
+ android:text="@string/securityprovisioning"\r
+ android:id="@+id/btn_configurSec"\r
+ android:checked="false"\r
+ android:textSize="12sp" />\r
+\r
+ <RadioButton\r
+ android:layout_width="160dp"\r
+ android:layout_height="32dp"\r
+ android:text="GetConfiguration"\r
+ android:id="@+id/btn_getConfiguration"\r
+ android:checked="false"\r
+ android:textSize="12sp" />\r
+\r
+ <RadioButton\r
+ android:layout_width="173dp"\r
+ android:layout_height="32dp"\r
+ android:text="ProvisionDeviceConfig"\r
+ android:id="@+id/btn_provisionDevConf"\r
+ android:textSize="12sp" />\r
+\r
+ <RadioButton\r
+ android:layout_width="160dp"\r
+ android:layout_height="32dp"\r
+ android:text="@string/cloudprovisioning"\r
+ android:id="@+id/btn_provisionCloudConf"\r
+ android:textSize="12sp" />\r
+ </RadioGroup>\r
+\r
+ </LinearLayout>\r
+\r
+ <View\r
+ android:layout_height="2dip"\r
+ android:background="#FF909090"\r
+ android:layout_marginTop="10dp"\r
+ android:layout_marginBottom="10dp"\r
+ android:layout_marginLeft="15dp"\r
+ android:layout_marginRight="15dp"\r
+ android:layout_width="match_parent" />\r
+\r
+ <ScrollView\r
+ android:layout_width="fill_parent"\r
+ android:layout_height="fill_parent"\r
+ android:id="@+id/scrollView" >\r
+\r
+ <LinearLayout\r
+ android:orientation="vertical"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="match_parent"\r
+ android:id="@+id/layout_Infomation"\r
+ android:gravity="center_horizontal"\r
+ android:weightSum="1">\r
+\r
+ <LinearLayout\r
+ android:orientation="vertical"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="match_parent"\r
+ android:layout_marginLeft="20dp"\r
+ android:layout_marginRight="20dp"\r
+ android:id="@+id/layout_ConfigurSec"\r
+ android:layout_marginTop="10dp"\r
+ android:weightSum="1"\r
+ android:visibility="gone">\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:textAppearance="?android:attr/textAppearanceSmall"\r
+ android:text="@string/security_provisioning_state"\r
+ android:id="@+id/textView10" />\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/layout_secState"\r
+ android:weightSum="1"\r
+ android:layout_marginLeft="10dp"\r
+ android:layout_marginTop="10dp" >\r
+\r
+ <TextView\r
+ android:layout_width="80dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="State"\r
+ android:id="@+id/textView12"\r
+ android:layout_gravity="center_vertical" />\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:text="empty"\r
+ android:id="@+id/txt_secState" />\r
+\r
+ </LinearLayout>\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/linearLayout2"\r
+ android:weightSum="1"\r
+ android:layout_marginLeft="10dp"\r
+ android:layout_marginTop="10dp" >\r
+\r
+ <TextView\r
+ android:layout_width="80dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="Device ID"\r
+ android:id="@+id/textView"\r
+ android:layout_gravity="center_vertical" />\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:text="empty"\r
+ android:id="@+id/txt_secDevID" />\r
+ </LinearLayout>\r
+\r
+ <FrameLayout\r
+ android:layout_width="match_parent"\r
+ android:layout_height="82dp"\r
+ android:layout_weight="0.64"></FrameLayout>\r
+\r
+ <Button\r
+ android:layout_width="90dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="START"\r
+ android:id="@+id/btn_startConfigureSec"\r
+ android:layout_marginTop="10dp"\r
+ android:layout_gravity="bottom|right" />\r
+\r
+ </LinearLayout>\r
+\r
+ <LinearLayout\r
+ android:orientation="vertical"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="match_parent"\r
+ android:layout_marginLeft="20dp"\r
+ android:layout_marginRight="20dp"\r
+ android:id="@+id/layout_GetConfiguration"\r
+ android:layout_marginTop="10dp"\r
+ android:visibility="gone">\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content">\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:textAppearance="?android:attr/textAppearanceSmall"\r
+ android:text="@string/enrollee_property_data"\r
+ android:id="@+id/textView4" />\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:text="state : "\r
+ android:id="@+id/textView18"\r
+ android:layout_marginLeft="80dp" />\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:text="wait"\r
+ android:id="@+id/txt_getConfigurationState" />\r
+ </LinearLayout>\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/layout_devID"\r
+ android:weightSum="1"\r
+ android:layout_marginLeft="10dp"\r
+ android:layout_marginTop="10dp" >\r
+\r
+ <TextView\r
+ android:layout_width="130dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="devID"\r
+ android:id="@+id/textView6"\r
+ android:layout_gravity="center_vertical" />\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:text="empty"\r
+ android:id="@+id/txt_devID" />\r
+\r
+ </LinearLayout>\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/layout_devName"\r
+ android:weightSum="1"\r
+ android:layout_marginLeft="10dp"\r
+ android:layout_marginTop="10dp" >\r
+\r
+ <TextView\r
+ android:layout_width="130dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="devName"\r
+ android:id="@+id/textView7"\r
+ android:layout_gravity="center_vertical" />\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:text="empty"\r
+ android:id="@+id/txt_devName" />\r
+\r
+ </LinearLayout>\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/layout_Language"\r
+ android:weightSum="1"\r
+ android:layout_marginLeft="10dp"\r
+ android:layout_marginTop="10dp" >\r
+\r
+ <TextView\r
+ android:layout_width="130dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="language"\r
+ android:id="@+id/textView8"\r
+ android:layout_gravity="center_vertical" />\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:text="empty"\r
+ android:id="@+id/txt_language" />\r
+\r
+ </LinearLayout>\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/layout_Country"\r
+ android:weightSum="1"\r
+ android:layout_marginLeft="10dp"\r
+ android:layout_marginTop="10dp" >\r
+\r
+ <TextView\r
+ android:layout_width="130dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="country"\r
+ android:id="@+id/textView9"\r
+ android:layout_gravity="center_vertical" />\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:text="empty"\r
+ android:id="@+id/txt_country" />\r
+\r
+ </LinearLayout>\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/layout_wifimode"\r
+ android:weightSum="1"\r
+ android:layout_marginLeft="10dp"\r
+ android:layout_marginTop="10dp" >\r
+\r
+ <TextView\r
+ android:layout_width="130dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="wifi mode"\r
+ android:id="@+id/textView20"\r
+ android:layout_gravity="center_vertical" />\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:text="empty"\r
+ android:id="@+id/txt_wifiMode" />\r
+\r
+ </LinearLayout>\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/layout_wififreq"\r
+ android:weightSum="1"\r
+ android:layout_marginLeft="10dp"\r
+ android:layout_marginTop="10dp" >\r
+\r
+ <TextView\r
+ android:layout_width="130dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="wifi freq"\r
+ android:id="@+id/textView21"\r
+ android:layout_gravity="center_vertical" />\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:text="empty"\r
+ android:id="@+id/txt_wifiFreq" />\r
+\r
+ </LinearLayout>\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/layout_coludAccessAble"\r
+ android:weightSum="1"\r
+ android:layout_marginLeft="10dp"\r
+ android:layout_marginTop="10dp" >\r
+\r
+ <TextView\r
+ android:layout_width="130dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="CloudAccessable"\r
+ android:id="@+id/textView14"\r
+ android:layout_gravity="center_vertical" />\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:text="empty"\r
+ android:id="@+id/txt_cloudAccessable" />\r
+\r
+ </LinearLayout>\r
+\r
+ <Button\r
+ android:layout_width="90dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="@string/start"\r
+ android:id="@+id/btn_startGetConfiguration"\r
+ android:layout_gravity="bottom|right" />\r
+\r
+ </LinearLayout>\r
+\r
+ <LinearLayout\r
+ android:orientation="vertical"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="match_parent"\r
+ android:layout_marginLeft="20dp"\r
+ android:layout_marginRight="20dp"\r
+ android:id="@+id/layout_ProvisionDevConf"\r
+ android:layout_marginTop="10dp"\r
+ android:visibility="gone">\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content">\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:textAppearance="?android:attr/textAppearanceSmall"\r
+ android:text="@string/enroller_infomation"\r
+ android:id="@+id/textView_DataProvisioning" />\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:text="state : "\r
+ android:id="@+id/textView19"\r
+ android:layout_marginLeft="80dp" />\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:text="wait"\r
+ android:id="@+id/txt_provisionDevConfState" />\r
+ </LinearLayout>\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/layout_EnrollerSSID"\r
+ android:weightSum="1"\r
+ android:layout_marginLeft="10dp"\r
+ android:layout_marginTop="10dp">\r
+\r
+ <TextView\r
+ android:layout_width="130dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="@string/enroller_ssid"\r
+ android:id="@+id/txt_ssid"\r
+ android:layout_gravity="center_vertical" />\r
+\r
+ <EditText\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/editText_EnrollerSSID"\r
+ android:text="Test_SSID"\r
+ android:layout_marginLeft="20dp"\r
+ android:layout_gravity="center_vertical" />\r
+ </LinearLayout>\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/layout_EnrollerPW"\r
+ android:weightSum="1"\r
+ android:layout_marginLeft="10dp"\r
+ android:layout_marginTop="10dp" >\r
+\r
+ <TextView\r
+ android:layout_width="130dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="Enter Enroller's PW"\r
+ android:id="@+id/txt_pass"\r
+ android:layout_gravity="center_vertical" />\r
+\r
+ <EditText\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/editText_EnrollerPW"\r
+ android:text="Test_PW"\r
+ android:layout_marginLeft="20dp"\r
+ android:layout_gravity="center_vertical" />\r
+ </LinearLayout>\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/layout_InputLanguage"\r
+ android:weightSum="1"\r
+ android:layout_marginLeft="10dp"\r
+ android:layout_marginTop="10dp" >\r
+\r
+ <TextView\r
+ android:layout_width="130dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="language"\r
+ android:id="@+id/textView25"\r
+ android:layout_gravity="center_vertical" />\r
+\r
+ <EditText\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/editText_Language"\r
+ android:text="Test_Language"\r
+ android:layout_marginLeft="20dp"\r
+ android:layout_gravity="center_vertical" />\r
+\r
+ </LinearLayout>\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/layout_InputCountry"\r
+ android:weightSum="1"\r
+ android:layout_marginLeft="10dp"\r
+ android:layout_marginTop="10dp" >\r
+\r
+ <TextView\r
+ android:layout_width="130dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="country"\r
+ android:id="@+id/textView23"\r
+ android:layout_gravity="center_vertical" />\r
+\r
+ <EditText\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/editText_Country"\r
+ android:text="Test_Country"\r
+ android:layout_marginLeft="20dp"\r
+ android:layout_gravity="center_vertical" />\r
+ </LinearLayout>\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/layout_EnrollerAuthType"\r
+ android:weightSum="1"\r
+ android:layout_marginLeft="10dp"\r
+ android:layout_marginTop="10dp" >\r
+\r
+ <TextView\r
+ android:layout_width="130dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="@string/select_enroller_authentication_type"\r
+ android:id="@+id/txt_authtype"\r
+ android:layout_gravity="center_vertical" />\r
+\r
+ <Spinner\r
+ android:layout_width="fill_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/spinner_authType"\r
+ android:layout_marginLeft="20dp"\r
+ android:layout_gravity="center_vertical"\r
+ android:spinnerMode="dropdown" />\r
+\r
+ </LinearLayout>\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/layout_EnrollerEncType"\r
+ android:weightSum="1"\r
+ android:layout_marginLeft="10dp"\r
+ android:layout_marginTop="10dp" >\r
+\r
+ <TextView\r
+ android:layout_width="130dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="@string/select_enroller_encription_type"\r
+ android:id="@+id/textView5"\r
+ android:layout_gravity="center_vertical" />\r
+\r
+ <Spinner\r
+ android:layout_width="fill_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/spinner_encType"\r
+ android:layout_marginLeft="20dp"\r
+ android:layout_gravity="center_vertical"\r
+ android:spinnerMode="dropdown" />\r
+\r
+ </LinearLayout>\r
+\r
+ <Button\r
+ android:layout_width="90dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="START"\r
+ android:id="@+id/btn_startProvisionDevConf"\r
+ android:layout_marginTop="10dp"\r
+ android:layout_gravity="bottom|right" />\r
+\r
+ </LinearLayout>\r
+\r
+ <LinearLayout\r
+ android:orientation="vertical"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="match_parent"\r
+ android:layout_marginLeft="20dp"\r
+ android:layout_marginRight="20dp"\r
+ android:id="@+id/layout_ProvisionCloudConf"\r
+ android:layout_marginTop="10dp"\r
+ android:visibility="gone">\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content">\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:textAppearance="?android:attr/textAppearanceSmall"\r
+ android:text="Cloud Information"\r
+ android:id="@+id/textView15" />\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:text="state : "\r
+ android:id="@+id/textView24"\r
+ android:layout_marginLeft="80dp" />\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:text="wait"\r
+ android:id="@+id/txt_provisionCloudConfState" />\r
+ </LinearLayout>\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/linearLayout11"\r
+ android:weightSum="1"\r
+ android:layout_marginLeft="10dp"\r
+ android:layout_marginTop="10dp" >\r
+\r
+ <TextView\r
+ android:layout_width="130dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="Enter Target Cloud's Authcode"\r
+ android:id="@+id/textView16"\r
+ android:layout_gravity="center_vertical" />\r
+\r
+ <EditText\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/editText_authcode"\r
+ android:layout_marginLeft="20dp"\r
+ android:layout_gravity="center_vertical"\r
+ android:text="authcode" />\r
+ </LinearLayout>\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/linearLayout12"\r
+ android:weightSum="1"\r
+ android:layout_marginLeft="10dp"\r
+ android:layout_marginTop="10dp" >\r
+\r
+ <TextView\r
+ android:layout_width="130dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="Enter Target Cloud's AuthProvider"\r
+ android:id="@+id/textView17"\r
+ android:layout_gravity="center_vertical" />\r
+\r
+ <EditText\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/editText_authprovider"\r
+ android:layout_marginLeft="20dp"\r
+ android:layout_gravity="center_vertical"\r
+ android:text="authprovider" />\r
+ </LinearLayout>\r
+\r
+ <LinearLayout\r
+ android:orientation="horizontal"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/linearLayout"\r
+ android:weightSum="1"\r
+ android:layout_marginLeft="10dp"\r
+ android:layout_marginTop="10dp" >\r
+\r
+ <TextView\r
+ android:layout_width="130dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="Enter Target Cloud's Interface server"\r
+ android:id="@+id/textView3"\r
+ android:layout_gravity="center_vertical" />\r
+\r
+ <EditText\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:id="@+id/editText_ciserver"\r
+ android:layout_marginLeft="20dp"\r
+ android:layout_gravity="center_vertical"\r
+ android:text="coap+tcp://52.69.149.85:5683" />\r
+ </LinearLayout>\r
+\r
+ <Button\r
+ android:layout_width="90dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="START"\r
+ android:id="@+id/btn_startProvisionCloudConf"\r
+ android:layout_marginTop="10dp"\r
+ android:layout_gravity="bottom|right" />\r
+\r
+ </LinearLayout>\r
+ </LinearLayout>\r
+ </ScrollView>\r
+\r
+</LinearLayout>
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>\r
+<resources>\r
+ <string-array name="auth_type">\r
+ <item>NONE_AUTH</item>\r
+ <item>WEP</item>\r
+ <item>WPA_PSK</item>\r
+ <item>WPA2_PSK</item>\r
+ </string-array>\r
+ <string-array name="enc_type">\r
+ <item>NONE_ENC</item>\r
+ <item>WEP_64</item>\r
+ <item>WEP_128</item>\r
+ <item>TKIP</item>\r
+ <item>AES</item>\r
+ <item>TKIP_AES</item>\r
+ </string-array>\r
+</resources>
\ No newline at end of file
<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="softAP_ssid">EasySetup123</string>
- <string name="softAP_pwd">EasySetup123</string>
- <string name="target_default_ssid">DLNA_LISMORE1</string>
- <string name="target_default_pwd">dlna@010203</string>
- <string name="not_available">Not available</string>
+ <string name="security_mode">Security Mode</string>
+ <string name="enroller_ssid">Enter Enroller\'s SSID</string>
+ <string name="select_enroller_authentication_type">Select Enroller\'s Authentication Type</string>
+ <string name="select_enroller_encription_type">Select Enroller\'s Encription Type</string>
+ <string name="enroller_infomation">Enroller\'s Infomation</string>
+ <string name="requsetpropertydata">RequsetPropertyData</string>
+ <string name="securityprovisioning">SecurityProvisioning</string>
+ <string name="dataprovisioning">DataProvisioning</string>
+ <string name="cloudprovisioning">CloudProvisioning</string>
+ <string name="log">log</string>
+ <string name="start">START</string>
+ <string name="enrollee_property_data">Enrollee\'s Property Data</string>
+ <string name="enter_enroller_apos_s_pw">Enter Enroller\'s PW</string>
+ <string name="easysetup_sequence">Easysetup Sequence</string>
+ <string name="security_provisioning_state">Security Provisioning State</string>
</resources>
+//******************************************************************\r
+//\r
+// Copyright 2016 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
// Top-level build file where you can add configuration options common to all sub-projects/modules.\r
+\r
buildscript {\r
repositories {\r
jcenter()\r
}\r
dependencies {\r
- classpath 'com.android.tools.build:gradle:1.2.3'\r
+ classpath 'com.android.tools.build:gradle:1.3.0'\r
+\r
+ // NOTE: Do not place your application dependencies here; they belong\r
+ // in the individual module build.gradle files\r
}\r
}\r
\r
--- /dev/null
+#
+# //******************************************************************
+# //
+# // Copyright 2016 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.
+# //
+# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+
+# Project-wide Gradle settings.
+
+# IDE (e.g. Android Studio) users:
+# Gradle settings configured through the IDE *will override*
+# any settings specified in this file.
+
+# For more details on how to configure your build environment visit
+# http://www.gradle.org/docs/current/userguide/build_environment.html
+
+# Specifies the JVM arguments used for the daemon process.
+# The setting is particularly useful for tweaking memory settings.
+# Default value: -Xmx10248m -XX:MaxPermSize=256m
+# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
+
+# When configured, Gradle will run in incubating parallel mode.
+# This option should only be used with decoupled projects. More details, visit
+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
+# org.gradle.parallel=true
+TARGET_ARCH=armeabi
+RELEASE=release
+SECURED=1
+ERROR_MSG="if building examples from android-studio, you might need to modify the default TARGET_ARCH\
+ and RELEASE in <iotivity>/android/examples/gradle.properties,\
+ if your aar file has different values for TARGET_ARCH and RELEASE"
+
-include ':app'\r
+//******************************************************************
+//
+// Copyright 2016 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 ':app'
--- /dev/null
+#//******************************************************************
+#//
+#// Copyright 2016 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.
+#//
+#//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+import os
+import platform
+Import('env')
+
+android_home = env.get('ANDROID_HOME')
+
+ANDROID_TARGET_ARCH = env.get('TARGET_ARCH')
+if env.get('RELEASE'):
+ ANDROID_RELEASE="release"
+else:
+ ANDROID_RELEASE="debug"
+
+os.environ['ANDROID_HOME'] = env.get('ANDROID_HOME')
+os.environ['ANDROID_NDK_HOME'] = env.get('ANDROID_NDK')
+
+if not os.path.exists(android_home + '/platforms/android-21') or not os.path.exists(android_home + '/build-tools/20.0.0'):
+ print '''
+***************************************** Info ********************************
+* Either 'Android API 21' is not installed or 'Android SDK Build Tools *
+* 20.0.0' is not installed. The Android SDK Manager will now open. Please *
+* be sure to deselect all options, then select the following 2 packages: *
+* 1. Under "Tools" select "Android SDK Build-tools" Revision 20. *
+* 2. Under "Android 5.0.1 (API 21)" select "SDK Platform" *
+* 3. Continue by selecting "Install 2 Packages" *
+* *
+* NOTE: If you have an http proxy, please press ctrl+c now and edit/create *
+* the following file in your $HOME directory as follows: *
+* *
+* Edit/Create file: "$HOME/.android/androidtool.cfg" *
+* *
+* http.proxyPort=<YOUR_PORT_NUMBER> *
+* sdkman.monitor.density=108 *
+* http.proxyHost=<YOUR_HTTP_PROXY_ADDRESS> *
+* sdkman.show.update.only=true *
+* sdkman.ask.adb.restart=false *
+* sdkman.force.http=true *
+* sdkman.show.updateonly=true *
+* *
+*******************************************************************************
+
+...Opening Android SDK Manager now. Once you are finished, the build will continue.
+'''
+ os.system(android_home + '/tools/android')
+
+#SConscript("../../../../../../android/android_api/SConscript")
+
+def ensure_libs(target, source, env):
+ return target, [source, env.get('BUILD_DIR') + 'liboc.so', env.get('BUILD_DIR') + 'liboc_logger.so']
+
+jdk_env = Environment(ENV=os.environ)
+jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') +
+ ' build -bservice/easy-setup/sampleapp/mediator/android/EasySetup/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s --stacktrace' %(ANDROID_TARGET_ARCH, ANDROID_RELEASE),
+ emitter = ensure_libs)
+jdk_env['BUILD_DIR'] = env.get('BUILD_DIR')
+cmdBuildEasysetupApp=jdk_env.Gradle(target="EasySetup/app/apk",
+ source="EasySetup/app/src/main/java/org/iotivity/service/easysetup/EasysetupActivity.java")
+
+Depends(cmdBuildEasysetupApp, env.get('baseAAR'))
\ No newline at end of file
+++ /dev/null
-#******************************************************************
-#
-# Copyright 2016 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.
-#
-#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-Import('env')
-
-mediator_env = env.Clone()
-
-target_os = env.get('TARGET_OS')
-
-######################################################################
-# Build flags
-######################################################################
-mediator_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-mediator_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
-
-mediator_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',
- env.get('SRC_DIR') + '/service/easy-setup/mediator/csdk/inc',
- env.get('SRC_DIR') + '/service/easy-setup/inc'])
-
-mediator_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction', 'coap', 'ESMediatorCSDK'])
-
-mediator = mediator_env.Program('mediator_c', 'mediator.cpp')
-
-i_mediator = mediator_env.Install(env.get('BUILD_DIR'), mediator)
-
-Alias('mediator_c', i_mediator)
-env.AppendTarget('mediator_c')
-
-
-
-
-
-
-
-
-
-
-
-
-
+++ /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 "provisioningapi.h"
-#include "logger.h"
-
-#define ES_MEDIATOR_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, ES_MEDIATOR_TAG, "Enrollee connectivity: %d", provInfo->provDeviceInfo.connType);
- if (provInfo->provStatus == DEVICE_PROVISIONED) {
- OIC_LOG_V(INFO, ES_MEDIATOR_TAG, "Successfully provisioned the Enrollee with IP : %s ",
- provInfo->provDeviceInfo.addr->addr);
- }
- else {
- OIC_LOG_V(INFO, ES_MEDIATOR_TAG, "Provisioing Failed for the Enrollee with IP : %s",
- provInfo->provDeviceInfo.addr->addr);
- }
-}
-
-static void PrintUsage() {
- OIC_LOG(INFO, ES_MEDIATOR_TAG, "Usage : occlient -d \"192.168.0.20\"");
-}
-
-int main(int argc, char **argv) {
- int opt;
-
- ProvConfig provConfig;
- //WiFiOnboardingConfig onboardConfig;
- WiFiOnboadingConnection onboardConn;
-
- PrintUsage();
- InitProvProcess();
-
-
- RegisterCallback(&ProvisioningStatusCallback);
-
- while ((opt = getopt(argc, argv, "d:s:p:")) != -1) {
- switch (opt) {
- case 'd':
- strncpy(onboardConn.ipAddress, optarg, IPV4_ADDR_SIZE - 1);
- break;
- case 's':
- strncpy(provConfig.provData.WIFI.ssid, optarg, NET_WIFI_SSID_SIZE - 1);
- break;
- case 'p':
- strncpy(provConfig.provData.WIFI.pwd, optarg, NET_WIFI_PWD_SIZE - 1);
- break;
- default:
- PrintUsage();
- return -1;
- }
- }
-
- provConfig.connType = CT_ADAPTER_IP;
- OIC_LOG_V(INFO, ES_MEDIATOR_TAG, "IP Address of the Provisioning device is =%s\n",
- onboardConn.ipAddress);
- OIC_LOG_V(INFO, ES_MEDIATOR_TAG, "SSID of the Enroller is =%s\n", provConfig.provData.WIFI.ssid);
- OIC_LOG_V(INFO, ES_MEDIATOR_TAG, "Password of the Enroller is =%s\n", provConfig.provData.WIFI.pwd);
-
- StartProvisioning(&provConfig, &onboardConn);
-
- signal(SIGINT, handleSigInt);
- while (!quitFlag) {
- OCStackResult result;
-
- result = OCProcess();
-
- if (result != OC_STACK_OK)
- {
- OIC_LOG(ERROR, "Mediator_CSDK", "OCStack stop error");
- }
-
- // To minimize CPU utilization we may wish to do this with sleep
- sleep(1);
- }
-
- ResetProvProcess();
- OIC_LOG(INFO, ES_MEDIATOR_TAG, "Exiting occlient main loop...");
-
- return 0;
-}
-
i_mediator = mediator_env.Install(env.get('BUILD_DIR'), mediator)
-Alias('mediator_rich', i_mediator)
+clientdat = mediator_env.Install(env.get('BUILD_DIR') + '/service/easy-setup/sampleapp/mediator/linux/richsdk_sample',
+ env.get('SRC_DIR') + '/service/easy-setup/sampleapp/mediator/linux/richsdk_sample/oic_svr_db_client.dat')
+
+
+Alias('mediator_rich', [i_mediator, clientdat])
env.AppendTarget('mediator_rich')
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include <iostream>
-#include<stdio.h>
+#include <condition_variable>
-#include "oic_string.h"
-#include "EasySetup.h"
#include "OCPlatform.h"
-#include "logger.h"
+#include "OCApi.h"
#include "OCProvisioningManager.h"
+#include "EasySetup.h"
+#include "ESRichCommon.h"
#define ES_SAMPLE_APP_TAG "ES_SAMPLE_APP_TAG"
#define DECLARE_MENU(FUNC, ...) { #FUNC, FUNC }
using namespace OC;
using namespace OIC::Service;
-static EasySetup *easySetupIntance = nullptr;
-static ProvConfig netInfo;
-static WiFiOnboadingConnection onboardingConn;
-static RemoteEnrollee::shared_ptr remoteEnrollee = nullptr;
+static std::shared_ptr<RemoteEnrollee> remoteEnrollee = nullptr;
+static std::shared_ptr<OC::OCResource> curResource = nullptr;
-static std::string ipaddress, ssid, pwd;
-char security;
+static std::mutex g_discoverymtx;
+static std::condition_variable g_cond;
-struct CloseApp
-{
-};
+#define PROV_RESOURCE_TYPE "ocf.wk.prov"
typedef void (*Runner)();
Runner g_currentRun;
-int processUserInput(int min, int max)
+int processUserInput(int min = std::numeric_limits<int>::min(),
+ int max = std::numeric_limits<int>::max())
{
assert(min <= max);
int input;
std::cin >> input;
+ std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
- if (!std::cin.fail())
- {
- if(input == max + 1) throw CloseApp();
- if(min <= input && input <= max) return input;
- }
+ if (!std::cin.fail() && min <= input && input <= max) return input;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
throw std::runtime_error("Invalid Input, please try again");
}
-void easySetupStatusCallback (std::shared_ptr< EasySetupStatus > easySetupStatus)
+void printConfiguration(EnrolleeConf conf)
{
- OIC_LOG_V(DEBUG, ES_SAMPLE_APP_TAG, "easySetupStatusCallback status is Status = %d",
- easySetupStatus->getEasySetupState());
+ cout << "===========================================" << endl;
+ cout << "\tDevice Name : " << conf.getDeviceName() << endl;
+
+ for(auto it : conf.getWiFiModes())
+ {
+ cout << "\tSupported WiFi modes : " << it << endl;
+ }
+ cout << "\tSupported WiFi freq : " << static_cast<int>(conf.getWiFiFreq()) << endl;
+ cout << "\tCloud accessibility: " << conf.isCloudAccessible() << endl;
+ cout << "===========================================" << endl;
}
-void startProvisioning()
+void printStatus(EnrolleeStatus status)
{
- try
+ cout << "===========================================" << endl;
+ cout << "\tProvStatus : " << status.getProvStatus() << endl;
+ cout << "\tLastErrCode : " << status.getLastErrCode() << endl;
+ cout << "===========================================" << endl;
+}
+
+void provisionSecurityStatusCallback(std::shared_ptr<SecProvisioningStatus> secProvisioningStatus)
+{
+ if(secProvisioningStatus->getESResult() != ES_OK)
{
- remoteEnrollee->startProvisioning();
+ cout << "provisionSecurity is failed." << endl;
+ return;
}
- catch(OCException &exception)
+ else
{
- std::cout << "Exception : " << exception.reason();
+ cout << "provisionSecurity is success." << endl;
+ cout << "uuid : " << secProvisioningStatus->getDeviceUUID()<< endl;
}
}
-void initEasySetup()
+void provisionSecurity()
{
+ remoteEnrollee->provisionSecurity(provisionSecurityStatusCallback);
+}
+
+void getStatusCallback(std::shared_ptr< GetEnrolleeStatus > getEnrolleeStatus)
+{
+ if(getEnrolleeStatus->getESResult() != ES_OK)
+ {
+ cout << "getStatus is failed." << endl;
+ return;
+ }
+ else
+ {
+ cout << "getStatus is success." << endl;
+ printStatus(getEnrolleeStatus->getEnrolleeStatus());
+ }
+}
- easySetupIntance = EasySetup::getInstance();
- cout<<"\n Enter the IP address : ";
- cin>>ipaddress;
- cout<<"\n Enter the Target Network SSID : ";
- cin>>ssid;
- cout<<"\n Enter the Target Network Password : ";
- cin>>pwd;
- cout<<"\n Enable Security: [Y/N] ";
- cin>>security;
+void getStatus()
+{
+ if(!remoteEnrollee)
+ {
+ return;
+ }
- if ( ipaddress.size() == 0 || ssid.size() == 0 || pwd.size()==0 )
+ try
{
- cout<<"\n Invalid information try again !!!";
+ remoteEnrollee->getStatus(getStatusCallback);
+ }
+ catch (OCException &e)
+ {
+ std::cout << "Exception during getConfiguration call" << e.reason();
+ return;
+ }
+}
+
+void getConfigurationCallback(std::shared_ptr< GetConfigurationStatus > getConfigurationStatus)
+{
+ if(getConfigurationStatus->getESResult() != ES_OK)
+ {
+ cout << "GetConfigurationStatus is failed." << endl;
+ return;
}
else
- {
- cout <<"\n Entered details are : \n";
- cout<<"\n IP address : "<<ipaddress;
- cout<<"\n Target Network SSID : "<<ssid;
- cout<<"\n Target Network Password : "<<pwd;
+ {
+ cout << "GetConfigurationStatus is success." << endl;
+ printConfiguration(getConfigurationStatus->getEnrolleeConf());
+ }
+}
- if (security == 'Y' || security == 'y' )
- {
- onboardingConn.isSecured = true;
- cout<<"\n Security is Enabled\n\n\n";
- }
- else
- {
- onboardingConn.isSecured = false;
- cout<<"\n Security is not Enabled\n\n\n";
- }
+void getConfiguration()
+{
+ if(!remoteEnrollee)
+ {
+ return;
+ }
- netInfo.connType = CT_ADAPTER_IP;
+ try
+ {
+ remoteEnrollee->getConfiguration(getConfigurationCallback);
+ }
+ catch (OCException &e)
+ {
+ std::cout << "Exception during getConfiguration call" << e.reason();
+ return;
+ }
+}
- OICStrcpy(netInfo.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
- OICStrcpy(netInfo.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
+void deviceProvisioningStatusCallback(std::shared_ptr< DevicePropProvisioningStatus > provStatus)
+{
+ if(provStatus->getESResult() != ES_OK)
+ {
+ cout << "Device Provisioning is failed." << endl;
+ return;
+ }
+ else
+ {
+ cout << "Device Provisioning is success." << endl;
+ }
+}
- OICStrcpy(onboardingConn.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
+void provisionDeviceProperty()
+{
+ if(!remoteEnrollee)
+ {
+ return;
+ }
+
+ DeviceProp devProp;
+ devProp.setWiFiProp("Iotivity_SSID", "Iotivity_PWD", WPA2_PSK, TKIP_AES);
+ devProp.setDevConfProp("korean", "Korea");
- try
- {
- remoteEnrollee = easySetupIntance->createEnrolleeDevice(netInfo,onboardingConn);
- }
- catch (OCException &e)
- {
- std::cout << "Exception during createEnrolleeDevice call" << e.reason();
- return;
- }
+ try
+ {
+ //remoteEnrollee->provisionDeviceProperties(deviceProp, deviceProvisioningStatusCallback);
+ remoteEnrollee->provisionDeviceProperties(devProp, deviceProvisioningStatusCallback);
+ }
+ catch (OCException &e)
+ {
+ std::cout << "Exception during provisionDeviceProperties call" << e.reason();
+ return;
+ }
+}
+
+void cloudProvisioningStatusCallback(std::shared_ptr< CloudPropProvisioningStatus > provStatus)
+{
+ switch (provStatus->getESCloudState())
+ {
+ case ES_CLOUD_PROVISIONING_ERROR:
+ cout << "Cloud Provisioning is failed." << endl;
+ break;
+ case ES_CLOUD_PROVISIONING_SUCCESS:
+ cout << "Cloud Provisioning is success." << endl;
+ break;
+ case ES_CLOUD_ENROLLEE_FOUND:
+ cout << "Enrollee is found in a given network." << endl;
+ break;
+ case ES_CLOUD_ENROLLEE_NOT_FOUND:
+ cout << "Enrollee is not found in a given network." << endl;
+ break;
+ }
+}
- remoteEnrollee->registerEasySetupStatusHandler(&easySetupStatusCallback);
+void provisionCloudProperty()
+{
+ if(!remoteEnrollee)
+ {
+ return;
}
+ CloudProp cloudProp;
+ cloudProp.setCloudProp("authCode", "authProvider", "ciServer");
+ cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3");
+
+ try
+ {
+ remoteEnrollee->provisionCloudProperties(cloudProp, cloudProvisioningStatusCallback);
+ }
+ catch (OCException &e)
+ {
+ std::cout << "Exception during provisionCloudProperties call" << e.reason();
+ return;
+ }
}
-void runEasySetupMenu()
+
+void DisplayMenu()
{
- constexpr int EASY_SETUP_INIT = 1;
- constexpr int START_PROVISIONING = 2;
- constexpr int STOP_PROVISIONING = 3;
- constexpr int STOP_EASY_SETUP = 4;
+ constexpr int PROVISION_SECURITY = 1;
+ constexpr int GET_STATUS = 2;
+ constexpr int GET_CONFIGURATION = 3;
+ constexpr int PROVISION_DEVICE_PROPERTY = 4;
+ constexpr int PROVISION_CLOUD_PROPERTY = 5;
std::cout << "========================================================\n";
- std::cout << EASY_SETUP_INIT << ". Easy Setup Init \n";
- std::cout << START_PROVISIONING << ". Start Provisioning \n";
- std::cout << STOP_PROVISIONING << ". Stop Provisioning \n";
- std::cout << STOP_EASY_SETUP << ". Stop Easy Setup \n";
- std::cout << STOP_EASY_SETUP + 1 << ". Quit \n";
+ std::cout << PROVISION_SECURITY << ". Provision Security to Enrollee \n";
+ std::cout << GET_STATUS << ". Get Status from Enrollee \n";
+ std::cout << GET_CONFIGURATION << ". Get Configuration from Enrollee \n";
+ std::cout << PROVISION_DEVICE_PROPERTY << ". Provision Device Property\n";
+ std::cout << PROVISION_CLOUD_PROPERTY << ". Provision Cloud Property \n";
std::cout << "========================================================\n";
- int selection = processUserInput(EASY_SETUP_INIT, STOP_EASY_SETUP);
+ int selection = processUserInput(PROVISION_SECURITY, PROVISION_CLOUD_PROPERTY);
switch (selection)
{
- case EASY_SETUP_INIT:
- initEasySetup();
+ case PROVISION_SECURITY:
+ provisionSecurity();
break;
- case START_PROVISIONING:
- startProvisioning();
+ case GET_STATUS:
+ getStatus();
break;
- case STOP_PROVISIONING:
- //stopProvisioning();
+ case GET_CONFIGURATION:
+ getConfiguration();
break;
- case STOP_EASY_SETUP:
- //stopEasySetup();
+ case PROVISION_DEVICE_PROPERTY:
+ provisionDeviceProperty();
+ break;
+ case PROVISION_CLOUD_PROPERTY:
+ provisionCloudProperty();
break;
default:
break;
};
}
+// Callback to found resources
+void foundResource(std::shared_ptr<OC::OCResource> resource)
+{
+ std::string resourceURI;
+ std::string hostAddress;
+ try
+ {
+ // Do some operations with resource object.
+ if(resource &&
+ !curResource &&
+ resource->getResourceTypes().at(0) == PROV_RESOURCE_TYPE)
+ {
+ std::cout<<"DISCOVERED Resource:"<<std::endl;
+ // Get the resource URI
+ resourceURI = resource->uri();
+ std::cout << "\tURI of the resource: " << resourceURI << std::endl;
+
+ // Get the resource host address
+ hostAddress = resource->host();
+ std::cout << "\tHost address of the resource: " << hostAddress << std::endl;
+
+ // Get the resource types
+ std::cout << "\tList of resource types: " << std::endl;
+ for(auto &resourceTypes : resource->getResourceTypes())
+ {
+ std::cout << "\t\t" << resourceTypes << std::endl;
+ }
+
+ // Get the resource interfaces
+ std::cout << "\tList of resource interfaces: " << std::endl;
+ for(auto &resourceInterfaces : resource->getResourceInterfaces())
+ {
+ std::cout << "\t\t" << resourceInterfaces << std::endl;
+ }
+
+ if(curResource == nullptr)
+ {
+ remoteEnrollee = EasySetup::getInstance()->createRemoteEnrollee(resource);
+ if(!remoteEnrollee)
+ {
+ std::cout << "RemoteEnrollee object is failed for some reasons!" << std::endl;
+ }
+ else
+ {
+ curResource = resource;
+ std::cout << "RemoteEnrollee object is successfully created!" << std::endl;
+ g_cond.notify_all();
+ }
+ }
+ }
+ }
+ catch(std::exception& e)
+ {
+ std::cerr << "Exception in foundResource: "<< e.what() << std::endl;
+ }
+}
+
static FILE* client_open(const char *UNUSED_PARAM, const char *mode)
{
(void)UNUSED_PARAM;
int main()
{
+ std::ostringstream requestURI;
OCPersistentStorage ps {client_open, fread, fwrite, fclose, unlink };
PlatformConfig config
OCPlatform::Configure(config);
+ try
+ {
#ifdef __WITH_DTLS__
- //Initializing the provisioning client stack using the db path provided by the application.
- OCStackResult result = OCSecure::provisionInit("");
+ //Initializing the provisioning client stack using the db path provided by the application.
+ OCStackResult result = OCSecure::provisionInit("");
- if (result != OC_STACK_OK)
- {
- return -1;
- }
+ if (result != OC_STACK_OK)
+ {
+ return -1;
+ }
#endif
+ requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=" << PROV_RESOURCE_TYPE;
+
+ OCPlatform::findResource("", requestURI.str(), CT_DEFAULT, &foundResource);
+ std::cout<< "Finding Resource... " <<std::endl;
- g_currentRun = runEasySetupMenu;
+ std::unique_lock<std::mutex> lck(g_discoverymtx);
+ g_cond.wait_for(lck, std::chrono::seconds(4));
+
+ }catch(OCException& e)
+ {
+ std::cout << "Exception in main: "<<e.what();
+ }
while (true)
{
try
{
- g_currentRun();
+ DisplayMenu();
}
catch (const std::exception& e)
{
std::cout << "Exception caught in main " << e.what() << std::endl;
}
- catch (const CloseApp&)
- {
- break;
- }
}
std::cout << "Stopping the client" << std::endl;