# 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
######################################################################
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']
+if target_os == '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_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')
+ 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'))
+ enrollee_env.InstallTarget(enrollee_sdk_shared, 'libESEnrollee')
enrollee_env.UserInstallTargetLib(enrollee_sdk_shared, 'libESEnrolleeSDK')
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.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.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/arduino/wifi/networkhandler.cpp'
+ ])
+
enrollee_env.InstallTarget(es_sdk_static, 'libESEnrolleeSDK')
#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')
#Build UnitTestcases for Enrollee
- SConscript('../enrollee/unittests/SConscript')
+# SConscript('../enrollee/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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-/**
- * @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
*/
typedef void (*ESEnrolleeEventCallback)(ESResult esResult, ESEnrolleeState enrolleeState);
+
+
+typedef struct
+{
+ void (*WiFiProvCb) (ESWiFiProvData *);
+ void (*DevConfProvCb) (ESDevConfProvData *);
+ void (*CloudDataProvCb) (ESCloudProvData *);
+} ESProvisioningCallbacks;
+
/**
* 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.
+ */
+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.
+ */
+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.
*/
-ESResult ESInitProvisioning();
+ESResult ESSetErrorCode(ESErrorCode esErrCode);
/**
* This function performs termination of Provisioning and Network resources.
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#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);
-}
-
+++ /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 API declaration for creating & configuration for SoftAP
- */
-
-#ifndef EASYSETUP_ENROLLEE_SOFTAP_H__
-#define EASYSETUP_ENROLLEE_SOFTAP_H__
-
-#ifdef __cplusplus
-extern "C" {
-#endif // __cplusplus
-
-
-#define SOFTAP_SUCCESS 1
-#define SOFTAP_FAILED 0
-
-
-//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__ */
-
-
-
*/
#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
* @var gTargetSsid
* @brief Target SSID of the Soft Access point to which the device has to connect
*/
-static char gTargetSsid[MAXSSIDLEN];
+// static char gTargetSsid[MAXSSIDLEN];
/**
* @var gTargetPass
* @brief Password of the target access point to which the device has to connect
*/
-static char gTargetPass[MAXNETCREDLEN];
+// static char gTargetPass[MAXNETCREDLEN];
/**
* @var gEnrolleeStatusCb
* @brief Fucntion pointer holding the callback for intimation of EasySetup Enrollee status callback
*/
-static ESEnrolleeEventCallback gEnrolleeStatusCb = NULL;
+// static ESEnrolleeEventCallback gEnrolleeStatusCb = NULL;
/**
* @var gIsSecured
*/
static bool gIsSecured = false;
-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);
- }
-}
+static ESProvisioningCallbacks gESProvisioningCb;
+static ESDeviceProperty gESDeviceProperty;
-void ESProvisioningCallback(ESResult esResult)
+void ESWiFiRsrcCallback(ESResult esResult, ESWiFiProvData *eventData)
{
- OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "ESProvisioningCallback with result = %d", esResult);
+ OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "ESWiFiRsrcCallback 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, "ESWiFiRsrcCallback Error Occured");
+ return;
+ }
- // Connecting/onboarding to target network
- ConnectToWiFiNetwork(gTargetSsid, gTargetPass, ESOnboardingCallbackTargetNet);
+ // deliver data to ESProvisioningCallbacks
+ if(gESProvisioningCb.WiFiProvCb != NULL)
+ {
+ gESProvisioningCb.WiFiProvCb(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, "WiFiProvCb is NULL");
+ return;
}
}
-void ESOnboardingCallbackTargetNet(ESResult esResult)
+void ESCloudRsrcCallback(ESResult esResult, ESCloudProvData *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, "ESCloudRsrcCallback IN");
+
+ if(esResult != ES_OK)
+ {
+ OIC_LOG_V(ERROR, ES_ENROLLEE_TAG, "ESCloudRsrcCallback Error Occured");
+ return;
+ }
+
+ if(gESProvisioningCb.CloudDataProvCb != NULL)
{
- gEnrolleeStatusCb(esResult, ES_ON_BOARDED_TARGET_NETWORK_STATE);
+ gESProvisioningCb.CloudDataProvCb(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, "CloudDataProvCb is NULL");
+ return;
}
}
-ESResult ESInitEnrollee(OCConnectivityType networkType, const char *ssid, const char *passwd,
- bool isSecured,
- ESEnrolleeEventCallback cb)
+void ESDevconfRsrcallback(ESResult esResult, ESDevConfProvData *eventData)
{
- OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitEnrollee IN");
- if(!ESEnrolleeValidateParam(networkType,ssid,passwd,cb))
+ OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "ESDevconfRsrcallback IN");
+
+ if(esResult != ES_OK)
{
- OIC_LOG(ERROR, ES_ENROLLEE_TAG,
- "ESInitEnrollee::Stopping Easy setup due to invalid parameters");
- return ES_ERROR;
+ OIC_LOG_V(ERROR, ES_ENROLLEE_TAG, "ESDevconfRsrcallback Error Occured");
+ return;
}
- //Init callback
- gEnrolleeStatusCb = cb;
+ if(gESProvisioningCb.DevConfProvCb != NULL)
+ {
+ gESProvisioningCb.DevConfProvCb(eventData);
+ }
+ else
+ {
+ OIC_LOG_V(ERROR, ES_ENROLLEE_TAG, "DevConfProvCb is NULL");
+ return;
+ }
+}
- gIsSecured = isSecured;
+ESResult ESInitEnrollee(bool isSecured, ESResourceMask resourceMask, ESProvisioningCallbacks callbacks)
+{
+ OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitEnrollee IN");
- // 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);
+ gIsSecured = isSecured;
- OIC_LOG(INFO, ES_ENROLLEE_TAG, "received callback");
- OIC_LOG(INFO, ES_ENROLLEE_TAG, "onboarding now..");
+ if((resourceMask & ES_WIFI_RESOURCE) == ES_WIFI_RESOURCE)
+ {
+ 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.DevConfProvCb != NULL)
+ {
+ gESProvisioningCb.CloudDataProvCb = callbacks.CloudDataProvCb;
+ RegisterCloudRsrcEventCallBack(ESCloudRsrcCallback);
+ }
+ else
+ {
+ OIC_LOG(ERROR, ES_ENROLLEE_TAG, "CloudDataProvCb NULL");
+ return ES_ERROR;
+ }
+ }
- if(!ESOnboard(ssid, passwd, ESOnboardingCallback))
+ if(CreateEasySetupResources(gIsSecured, resourceMask) != OC_STACK_OK)
{
- OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESInitEnrollee::On-boarding failed");
- cb(ES_ERROR, ES_INIT_STATE);
+ UnRegisterResourceEventCallBack();
+
+ if (DeleteEasySetupResources() != OC_STACK_OK)
+ {
+ OIC_LOG(ERROR, ES_ENROLLEE_TAG, "Deleting prov resource error!!");
+ }
+
return ES_ERROR;
}
+
OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitEnrollee OUT");
return ES_OK;
}
-ESResult ESTerminateEnrollee()
+ESResult ESSetDeviceProperty(ESDeviceProperty *deviceProperty)
{
- UnRegisterResourceEventCallBack();
+ OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESSetDeviceProperty IN");
- //Delete Prov resource
- if (DeleteProvisioningResource() != OC_STACK_OK)
+ if(SetDeviceProperty(deviceProperty) != OC_STACK_OK)
{
- OIC_LOG(ERROR, ES_ENROLLEE_TAG, "Deleting prov resource error!!");
+ OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESSetDeviceProperty Error");
return ES_ERROR;
}
- OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESTerminateEnrollee success");
+ 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 ESInitProvisioning()
+ESResult ESSetState(ESEnrolleeState esState)
{
- OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitProvisioning <<IN>>");
+ OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESSetState IN");
- if (CreateProvisioningResource(gIsSecured) != OC_STACK_OK)
+ if(esState < ES_STATE_INIT || esState > ES_STATE_REGISTRRED_FAIL_TO_CLOUD)
{
- OIC_LOG(ERROR, ES_ENROLLEE_TAG, "CreateProvisioningResource error");
+ OIC_LOG_V(ERROR, ES_ENROLLEE_TAG, "Invalid ESEnrolleeState : %d", esState);
return ES_ERROR;
}
- RegisterResourceEventCallBack(ESProvisioningCallback);
+ if(SetEnrolleeState(esState) != OC_STACK_OK)
+ {
+ OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESSetState ES_ERROR");
+ return ES_ERROR;
+ }
- OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitProvisioning <<OUT>>");
- return ES_RESOURCECREATED;
+ OIC_LOG_V(INFO, ES_ENROLLEE_TAG, "Set ESState succesfully : %d", esState);
+ OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESSetState OUT");
+ return ES_OK;
}
-static bool ESEnrolleeValidateParam(OCConnectivityType networkType, const char *ssid,
- const char *passwd, ESEnrolleeEventCallback cb)
+ESResult ESSetErrorCode(ESErrorCode esErrCode)
{
- if (!ssid || !passwd || !cb)
+ OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESSetErrorCode IN");
+
+ if(esErrCode < ES_ERRCODE_NO_ERROR || esErrCode > ES_ERRCODE_UNKNOWN)
+ {
+ OIC_LOG_V(ERROR, ES_ENROLLEE_TAG, "Invalid ESSetErrorCode : %d", esErrCode);
+ return ES_ERROR;
+ }
+
+ if(SetEnrolleeErrCode(esErrCode) != OC_STACK_OK)
{
- OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESEnrolleeValidateParam - Invalid parameters");
- return false;
+ OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESSetErrorCode ES_ERROR");
+ return ES_ERROR;
}
- return true;
+
+ OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "Set ESErrorCode succesfully : %d", esErrCode);
+ OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESSetErrorCode OUT");
+ return ES_OK;
}
+ESResult ESTerminateEnrollee()
+{
+ OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESTerminateEnrollee IN");
+
+ UnRegisterResourceEventCallBack();
+
+ //Delete Prov resource
+ if (DeleteEasySetupResources() != 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;
+}
+++ /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__ */
* connect to the target network
*/
static ProvResource gProvResource;
+static WiFiResource gWiFiResource;
+static CloudResource gCloudResource;
+static DevConfResource gDevConfResource;
/**
- * @var gNetResource
- * @brief Structure forr holding the Provisioning status of network information
+ * @var gWiFiData
+ * @brief Structure for holding the target information required to
+ * connect to the target network
+ */
+ static ESWiFiProvData gWiFiData;
+
+/**
+ * @var gDevConfData
+ * @brief Structure for holding the device information
*/
-static NetResource gNetResource;
+ static ESDevConfProvData gDevConfData;
+
+/**
+ * @var gCloudData
+ * @brief Structure for holding the cloud information required to
+ * connect to CI Server
+ */
+ static ESCloudProvData gCloudData;
+
+
//-----------------------------------------------------------------------------
// Private internal function prototypes
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);
-ESEnrolleeResourceEventCallback gNetworkInfoProvEventCb = NULL;
+ESWiFiCB gWifiRsrcEvtCb = NULL;
+ESCloudCB gCloudRsrcEvtCb = NULL;
+ESDevConfCB gDevConfRsrcEvtCb = NULL;
-void RegisterResourceEventCallBack(ESEnrolleeResourceEventCallback cb)
+void RegisterWifiRsrcEventCallBack(ESWiFiCB cb)
{
- gNetworkInfoProvEventCb = 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.errorMessage, MAX_ERRMSGLEN, "");
+ 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, "Created Prov resource with result: %s", getResult(res));
+ return res;
+ }
+ res = OCBindResourceInterfaceToResource(gProvResource.handle, OC_RSRVD_INTERFACE_BATCH);
+ if(res)
+ {
+ OIC_LOG_V(INFO, ES_RH_TAG, "Created Prov resource 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 DeleteProvisioningResource()
+OCStackResult initWiFiResource(bool isSecured)
{
- OCStackResult res = OCDeleteResource(gProvResource.handle);
- if (res != OC_STACK_OK)
+ 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)
{
- OIC_LOG_V(INFO, ES_RH_TAG, "Deleting Prov resource error with result: %s", getResult(res));
+ 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;
+
}
-OCEntityHandlerResult ProcessGetRequest(OCEntityHandlerRequest *ehRequest, OCRepPayload **payload)
+OCStackResult initCloudServerResource(bool isSecured)
{
- OCEntityHandlerResult ehResult = OC_EH_ERROR;
- if (!ehRequest)
+ 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)
{
- OIC_LOG(ERROR, ES_RH_TAG, "Request is Null");
- return ehResult;
- }
- if (ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
+ 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
{
- OIC_LOG(ERROR, ES_RH_TAG, "Incoming payload not a representation");
- return ehResult;
+ 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);
}
- OCRepPayload *getResp = constructResponse(ehRequest);
- if (!getResp)
+ 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)
{
- OIC_LOG(ERROR, ES_RH_TAG, "constructResponse failed");
- return OC_EH_ERROR;
+ 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);
}
- *payload = getResp;
- ehResult = OC_EH_OK;
+ OIC_LOG_V(INFO, ES_RH_TAG, "Created DevConf resource with result: %s", getResult(res));
+ return res;
- return ehResult;
}
-OCEntityHandlerResult ProcessPostRequest(OCEntityHandlerRequest *ehRequest, OCRepPayload** payload)
+void updateProvResource(OCEntityHandlerRequest* ehRequest, OCRepPayload* input)
{
- OIC_LOG(INFO, ES_RH_TAG, "ProcessPostRequest enter");
- OCEntityHandlerResult ehResult = OC_EH_ERROR;
- if (ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
+ OIC_LOG_V(INFO, ES_RH_TAG, "gProvResource.status %d", gProvResource.status);
+
+ if(ehRequest->query)
{
- OIC_LOG(ERROR, ES_RH_TAG, "Incoming payload not a representation");
- return ehResult;
+ if(strstr(ehRequest->query, OC_RSRVD_INTERFACE_BATCH))
+ {
+ // When Provisioning resource has a POST with BatchInterface
+ updateCloudResource(input);
+ updateWiFiResource(input);
+ updateDevConfResource(input);
+ }
}
+}
- OCRepPayload* input = (OCRepPayload*) (ehRequest->payload);
- if (!input)
+void updateWiFiResource(OCRepPayload* input)
+{
+ char* ssid = NULL;
+ if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_SSID, &ssid))
{
- OIC_LOG(ERROR, ES_RH_TAG, "Failed to parse");
- return ehResult;
+ OICStrcpy(gWiFiResource.ssid, sizeof(gWiFiResource.ssid), ssid);
+ OICStrcpy(gWiFiData.ssid, sizeof(gWiFiData.ssid), ssid);
+ OIC_LOG_V(INFO, ES_RH_TAG, "gWiFiResource.ssid : %s", gWiFiResource.ssid);
}
- char* tnn;
- if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_TNN, &tnn))
+ char* cred = NULL;
+ if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_CRED, &cred))
{
- OICStrcpy(gProvResource.tnn, sizeof(gProvResource.tnn), tnn);
- OIC_LOG_V(INFO, ES_RH_TAG, "gProvResource.tnn %s", gProvResource.tnn);
+ OICStrcpy(gWiFiResource.cred, sizeof(gWiFiResource.cred), cred);
+ OICStrcpy(gWiFiData.pwd, sizeof(gWiFiData.pwd), cred);
+ OIC_LOG_V(INFO, ES_RH_TAG, "gWiFiResource.cred %s", gWiFiResource.cred);
+ }
- gProvResource.ps = ES_PS_PROVISIONING_COMPLETED;
+ int64_t authType = -1;
+ if (OCRepPayloadGetPropInt(input, OC_RSRVD_ES_AUTHTYPE, &authType))
+ {
+ gWiFiResource.authType = authType;
+ gWiFiData.authtype = gWiFiResource.authType;
+ OIC_LOG_V(INFO, ES_RH_TAG, "gWiFiResource.authType %u", gWiFiResource.authType);
}
- char* cd;
- if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_CD, &cd))
+ int64_t encType = -1;
+ if (OCRepPayloadGetPropInt(input, OC_RSRVD_ES_ENCTYPE, &encType))
{
- OICStrcpy(gProvResource.cd, sizeof(gProvResource.cd), cd);
- OIC_LOG_V(INFO, ES_RH_TAG, "gProvResource.cd %s", gProvResource.cd);
+ gWiFiResource.encType = encType;
+ gWiFiData.enctype = gWiFiResource.encType;
+ OIC_LOG_V(INFO, ES_RH_TAG, "gWiFiResource.encType %u", gWiFiResource.encType);
}
- OIC_LOG_V(INFO, ES_RH_TAG, "gProvResource.ps %lld", gProvResource.ps);
+ if(ssid || cred || authType!= -1 || encType != -1)
+ {
+ OIC_LOG(INFO, ES_RH_TAG, "Send WiFiRsrc Callback To ES");
- int64_t tr;
- if (OCRepPayloadGetPropInt(input, OC_RSRVD_ES_TR, &tr))
+ // TODO : Need to check appropriateness of gWiFiData
+ if(gWifiRsrcEvtCb != NULL)
+ {
+ gWifiRsrcEvtCb(ES_OK, &gWiFiData);
+ }
+ else
+ {
+ OIC_LOG(ERROR, ES_RH_TAG, "gWifiRsrcEvtCb is NULL");
+ }
+ }
+
+}
+
+void updateCloudResource(OCRepPayload* input)
+{
+ char *authCode = NULL;
+ if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_AUTHCODE, &authCode))
+ {
+ OICStrcpy(gCloudResource.authCode, sizeof(gCloudResource.authCode), authCode);
+ OICStrcpy(gCloudData.authCode, sizeof(gCloudData.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(gCloudData.authProvider, sizeof(gCloudData.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))
{
- // Triggering
- gProvResource.tr = tr;
+ OICStrcpy(gCloudResource.ciServer, sizeof(gCloudResource.ciServer), ciServer);
+ OICStrcpy(gCloudData.ciServer, sizeof(gCloudData.ciServer), ciServer);
+ OIC_LOG_V(INFO, ES_RH_TAG, "gCloudResource.ciServer %s", gCloudResource.ciServer);
}
- //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)
+ if(authCode || authProvider || ciServer)
{
- OIC_LOG(DEBUG, ES_RH_TAG, "Provisioning already completed."
- "Tiggering the network connection");
+ OIC_LOG(INFO, ES_RH_TAG, "Send CloudRsrc Callback To ES");
- if (gNetworkInfoProvEventCb)
+ // TODO : Need to check appropriateness of gCloudData
+ if(gCloudRsrcEvtCb != NULL)
{
- gNetworkInfoProvEventCb(ES_RECVTRIGGEROFPROVRES);
- ehResult = OC_EH_OK;
+ gCloudRsrcEvtCb(ES_OK, &gCloudData);
}
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;
+ OIC_LOG(ERROR, ES_RH_TAG, "gCloudRsrcEvtCb is NULL");
}
+ }
+}
- return ehResult;
+void updateDevConfResource(OCRepPayload* input)
+{
+ char *country = NULL;
+ if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_COUNTRY, &country))
+ {
+ OICStrcpy(gDevConfResource.country, sizeof(gDevConfResource.country), country);
+ OICStrcpy(gDevConfData.country, sizeof(gDevConfData.country), country);
+ OIC_LOG_V(INFO, ES_RH_TAG, "gDevConfResource.country %s", gDevConfResource.country);
}
- else if (gProvResource.ps == ES_PS_PROVISIONING_COMPLETED)
+
+ char *language = NULL;
+ if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_LANGUAGE, &language))
{
- OIC_LOG(DEBUG, ES_RH_TAG, "Provisioning already completed. "
- "This a request to override the existing the network provisioning information");
+ OICStrcpy(gDevConfResource.language, sizeof(gDevConfResource.language), language);
+ OICStrcpy(gDevConfData.language, sizeof(gDevConfData.language), language);
+ OIC_LOG_V(INFO, ES_RH_TAG, "gDevConfResource.language %s", gDevConfResource.language);
}
- else
+
+ if(country || language)
{
- OIC_LOG(DEBUG, ES_RH_TAG, "Provisioning the network information to the Enrollee.");
+ OIC_LOG(INFO, ES_RH_TAG, "Send DevConfRsrc Callback To ES");
+
+ // TODO : Need to check appropriateness of gDevConfData
+ if(gDevConfRsrcEvtCb != NULL)
+ {
+ gDevConfRsrcEvtCb(ES_OK, &gDevConfData);
+ }
+ else
+ {
+ OIC_LOG(ERROR, ES_RH_TAG, "gDevConfRsrcEvtCb is NULL");
+ }
}
+}
- OCRepPayload *getResp = constructResponse(ehRequest);
- if (!getResp)
+OCRepPayload* constructResponseOfWiFi()
+{
+ OCRepPayload* payload = OCRepPayloadCreate();
+ if (!payload)
{
- OIC_LOG(ERROR, ES_RH_TAG, "constructResponse failed");
- return OC_EH_ERROR;
+ OIC_LOG(ERROR, ES_RH_TAG, "Failed to allocate Payload");
+ return NULL;
}
- *payload = getResp;
- ehResult = OC_EH_OK;
+ OIC_LOG(INFO, ES_RH_TAG, "constructResponse wifi res");
+ OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_WIFI);
- return ehResult;
+ size_t dimensions[MAX_REP_ARRAY_DEPTH] = {gWiFiResource.numMode, 0, 0};
+ int64_t *modes_64 = (int64_t *)malloc(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);
+
+ return payload;
}
-OCEntityHandlerResult ProcessPutRequest(OCEntityHandlerRequest * ehRequest,
- OCRepPayload** payload)
+OCRepPayload* constructResponseOfCloud()
{
- OCEntityHandlerResult ehResult = OC_EH_ERROR;
+ OCRepPayload* payload = OCRepPayloadCreate();
+ if (!payload)
+ {
+ OIC_LOG(ERROR, ES_RH_TAG, "Failed to allocate Payload");
+ return NULL;
+ }
- return ehResult;
+ 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);
+
+ return payload;
}
-OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest)
+OCRepPayload* constructResponseOfDevConf()
{
OCRepPayload* payload = OCRepPayloadCreate();
if (!payload)
return NULL;
}
- if (ehRequest->resource == gProvResource.handle)
+ 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);
+
+ return payload;
+}
+
+OCRepPayload* constructResponseOfProv(OCEntityHandlerRequest *ehRequest)
+{
+ OCRepPayload* payload = OCRepPayloadCreate();
+ if (!payload)
{
- 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);
+ OIC_LOG(ERROR, ES_RH_TAG, "Failed to allocate Payload");
+ return NULL;
}
- else if (ehRequest->requestHandle == gNetResource.handle)
+
+ 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(ehRequest->query)
{
+ if(strstr(ehRequest->query, OC_RSRVD_INTERFACE_BATCH))
+ {// When Provisioning resource has a GET with BatchInterface
+ payload->next = constructResponseOfWiFi();
- OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_NET);
- OCRepPayloadSetPropInt(payload, "ant", gNetResource.ant[0]);
+ if(payload->next)
+ payload->next->next = constructResponseOfCloud();
+ else
+ return payload;
+
+ if(payload->next->next)
+ payload->next->next->next = constructResponseOfDevConf();
+ else
+ return payload;
+ }
}
+
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);
+ if (res != OC_STACK_OK)
+ {
+ OIC_LOG_V(INFO, ES_RH_TAG, "Deleting Prov resource error with result: %s", getResult(res));
+ }
+
+ return res;
+}
+
+OCStackResult DeleteEasySetupResources()
+{
+ OCStackResult 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));
+ }
+ 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));
+ }
+ 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));
+ }
+
+ 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;
+ 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 = 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 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;
+ }
+
+ // TBD : Discuss about triggering flag (to be existed or not)
+ // ES_PS_PROVISIONING_COMPLETED state indicates that already provisioning is completed.
+ // A new request for provisioning means overriding existing network provisioning information.
+
+ if(ehRequest->resource == gProvResource.handle)
+ updateProvResource(ehRequest, input);
+ else if(ehRequest->resource == gWiFiResource.handle)
+ updateWiFiResource(input);
+ else if(ehRequest->resource == gCloudResource.handle)
+ updateCloudResource(input);
+ else if(ehRequest->resource == gDevConfResource.handle)
+ updateDevConfResource(input);
+
+ 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 OC_EH_ERROR;
+ }
+
+ *payload = getResp;
+ ehResult = OC_EH_OK;
+
+ return ehResult;
+}
+
+OCEntityHandlerResult ProcessPutRequest(OCEntityHandlerRequest * ehRequest,
+ OCRepPayload** payload)
+{
+ (void) ehRequest;
+ (void) payload;
+ OCEntityHandlerResult ehResult = OC_EH_ERROR;
+
+ return ehResult;
+}
/**
* 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)
#include "logger.h"
#include "ocstack.h"
#include "escommon.h"
-#include "networkhandler.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 *);
/* 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 errorMessage[MAX_ERRMSGLEN];
+ char ocfWebLinks[MAX_WEBLINKLEN];
} ProvResource;
-/* Structure to represent a Light resource */
-typedef struct NETRESOURCE
+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;
+ WIFI_MODE supportedMode[NUM_WIFIMODE];
+ uint8_t numMode; // the number of device's supported wifi modes
+ WIFI_FREQ supportedFreq;
+ char ssid[MAX_SSIDLEN]; // target network name, i.e. SSID for WLAN, MAC address for BT.
+ char cred[MAX_CREDLEN]; // credential information.
+ WIFI_AUTHTYPE authType;
+ WIFI_ENCTYPE encType;
+} WiFiResource;
+
+typedef struct
+{
+ OCResourceHandle handle;
+ 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);
#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__ */
-
-
-
#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 "cisurl"
+#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.r.prov"
+#define OC_RSRVD_ES_URI_PROV "/.well-known/ocf/prov"
+#define OC_RSRVD_ES_RES_TYPE_WIFI "ocf.r.wifi"
+#define OC_RSRVD_ES_URI_WIFI "/.well-known/ocf/prov/wifi"
+#define OC_RSRVD_ES_RES_TYPE_CLOUDSERVER "ocf.r.cloudserver"
+#define OC_RSRVD_ES_URI_CLOUDSERVER "/.well-known/ocf/prov/cloudserver"
+#define OC_RSRVD_ES_RES_TYPE_DEVCONF "ocf.r.devconf"
+#define OC_RSRVD_ES_URI_DEVCONF "/.well-known/ocf/prov/devconf"
+
+#define NUM_WIFIMODE 10
+#define MAX_SSIDLEN 33
+#define MAX_CREDLEN 20
+
+#define MAX_DEVICELEN 100
+#define MAX_ERRMSGLEN 100
+#define MAX_WEBLINKLEN 100
-/**
- * @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
+typedef enum
+{
+ WiFi_11A = 0,
+ WiFi_11B,
+ WiFi_11G,
+ WiFi_11N,
+ WiFi_11AC,
+ WiFi_EOF = 999,
+} WIFI_MODE;
+typedef enum
+{
+ WiFi_24G = 0,
+ WiFi_5G,
+ WiFi_BOTH
+} WIFI_FREQ;
-/**
-* Device Roles defined for each device type used in easy setup
-*/
typedef enum
{
- ENROLLEE,
- MEDIATOR,
- ENROLLER,
-} DeviceRole;
+ NONE_AUTH = 0,
+ WEP,
+ WPA_PSK,
+ WPA2_PSK
+} WIFI_AUTHTYPE;
-/**
-* On-boarding connection to create Adhoc network.
-*/
typedef enum
{
- SOFTAP,
- BLE,
-} OBConnection;
+ NONE_ENC = 0,
+ WEP_64,
+ WEP_128,
+ TKIP,
+ AES,
+ TKIP_AES
+} WIFI_ENCTYPE;
typedef enum
{
ES_RECVREQOFNETRES,
ES_RECVUPDATEOFPROVRES,
ES_RECVTRIGGEROFPROVRES,
+ ES_UNAUTHORIZED = 31
} ESResult;
typedef enum
{
- /**
- * Default state of the device
- */
- ES_INIT_STATE,
+ ES_WIFI_RESOURCE = 0x01,
+ ES_CLOUD_RESOURCE = 0x02,
+ ES_DEVCONF_RESOURCE = 0x04
+} ESResourceMask;
- /**
- * Device will move to this state once the on boarding begins
- */
- ES_ON_BOARDING_STATE,
+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**/
+} ESWiFiProvData;
- /**
- * Device will move to this state after successful on-boarding of the device
- */
- ES_ON_BOARDED_STATE,
+typedef struct
+{
+ char language[OIC_STRING_MAX_VALUE];
+ char country[OIC_STRING_MAX_VALUE];
+} ESDevConfProvData;
- /**
- * Device will move to this state once the on boarding is done
- */
- ES_PROVISIONING_STATE,
+typedef struct
+{
+ char authCode[OIC_STRING_MAX_VALUE];
+ char authProvider[OIC_STRING_MAX_VALUE];
+ char ciServer[OIC_STRING_MAX_VALUE];
+} ESCloudProvData;
- /**
- * Easy setup process is successful.
- */
- ES_PROVISIONED_STATE,
+typedef struct
+{
+ struct
+ {
+ WIFI_MODE mode[NUM_WIFIMODE];
+ WIFI_FREQ freq;
+ } WiFi;
+ struct
+ {
+ char deviceName[MAX_DEVICELEN];
+ } DevConf;
+} ESDeviceProperty;
+typedef enum
+{
/**
- * 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
+ * Default state of the device
*/
- ES_OWNERSHIP_TRANSFERRING_STATE,
+ ES_STATE_INIT = 0,
/**
- * 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 cnnection 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 once the Application factory reset the device
- */
- ES_FACTORY_RESET_STATE,
+ * Status indicating failure connection to target network
+ */
+ ES_STATE_CONNECTED_FAIL_TO_ENROLLER,
/**
- * Enrollee moves to this state after connecting to target network
- */
- ES_ON_BOARDED_TARGET_NETWORK_STATE,
-}ESEnrolleeState;
+ * Status indicating successful registration to cloud
+ */
+ ES_STATE_REGISTERED_TO_CLOUD,
-/**
- * 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
- */
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;
+ * Error Code that given WiFi's Password is wrong
+ */
+ ES_ERRCODE_PW_WRONG,
-/**
- * Client applications implement this callback to consume responses received from Servers.
- */
-typedef void (*OCProvisioningStatusCB)(EasySetupInfo *easySetupInfo);
-
-/**
- * @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 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[64] =
-{ 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[64] =
- { 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[64] =
- { 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#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
easy_setup_env.AppendUnique(LIBS = ['ocpmapi', 'ocprovision'])
if target_os in ['android','linux']:
+#if target_os in ['linux']:
easy_setup_env.PrependUnique(CPPPATH = [
env.get('SRC_DIR') + '/resource/c_common/oic_malloc/include',
env.get('SRC_DIR') + '/resource/include',
es_src = None
if target_os in ['android','linux']:
+#if target_os in ['linux']:
if env.get('SECURED') == '1':
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']
######################################################################
#Build UnitTestcases for Mediator[RichSDK]
################################################ ######################
-if target_os in ['linux']:
- SConscript('unittests/SConscript')
+#if target_os == 'linux':
+# SConscript('unittests/SConscript')
+++ /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
-//******************************************************************
-//
-// 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;
-
-
-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();
- }
- }
- }
-}
+++ /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;
+
+/**
+ * This class contains on cloud provisioning information.
+ * It implements ProvisioningInfo interface and provide configuration object specific to cloud registration
+ */
+public class CloudProvInfo {
+
+ private final String mAuthCode;
+ private final String mAuthProvider;
+ private final String mCiServer;
+
+ public CloudProvInfo(String authCode, String authProvider, String ciServer) {
+ mAuthCode = authCode;
+ mAuthProvider = authProvider;
+ mCiServer = ciServer;
+ }
+
+ /**
+ * This method returns the authCode used for the first registration to IoTivity cloud
+ * @return AuthCode for sign-up to IoTivity cloud
+ */
+ public String getAuthCode() {
+ return mAuthCode;
+ }
+
+ /**
+ * This method returns the auth provider which issued the given AuthCode
+ * @return Auth provider which issued the given AuthCode
+ */
+ public String getAuthProvider() {
+ return mAuthProvider;
+ }
+
+ /**
+ * This method returns the Cloud Interface server's URL to be registered
+ * @return CI server's URL to be registered
+ */
+ public String getCiServer() {
+ return mCiServer;
+ }
+}
/**
* ***************************************************************
- * <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);
+import org.iotivity.service.easysetup.mediator.CloudProvisioningStatus;
+public abstract class CloudProvisioningCallback {
+ public abstract void onProgress(CloudProvisioningStatus 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 CloudProvisioningStatus
+{
+ private ESResult m_result;
+ private ESCloudProvState m_esCloudState;
+
+ public CloudProvisioningStatus(int result, int state)
+ {
+ m_result = ESResult.fromInt(result);
+ m_esCloudState = ESCloudProvState.fromInt(state);
+ }
+
+ public ESResult getESResult()
+ {
+ return m_result;
+ }
+
+ 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 org.iotivity.service.easysetup.mediator.enums.WIFI_AUTHTYPE;
+import org.iotivity.service.easysetup.mediator.enums.WIFI_ENCTYPE;
+
+/**
+ * This class contains on data provisioning information.
+ * It implements ProvisioningInfo interface and provide configuration object specific to data registration
+ */
+public class DataProvInfo {
+
+ private final String mSsid;
+ private final String mPwd;
+ private final WIFI_AUTHTYPE mAuthType;
+ private final WIFI_ENCTYPE mEncType;
+ private final String mLanguage;
+ private final String mCountry;
+
+ public DataProvInfo(String ssid, String pwd, WIFI_AUTHTYPE authType, WIFI_ENCTYPE encType,
+ String language, String country)
+ {
+ mSsid = ssid;
+ mPwd = pwd;
+ mAuthType = authType;
+ mEncType = encType;
+ mLanguage = language;
+ mCountry = country;
+ }
+
+ public String getSsid()
+ {
+ return mSsid;
+ }
+
+ public String getPwd()
+ {
+ return mPwd;
+ }
+
+ public WIFI_AUTHTYPE getAuthType()
+ {
+ return mAuthType;
+ }
+
+ public WIFI_ENCTYPE getEncType()
+ {
+ return mEncType;
+ }
+
+ public String getLanguage()
+ {
+ return mLanguage;
+ }
+
+ public String getCountry()
+ {
+ return mCountry;
+ }
+}
/**
* ***************************************************************
- * <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.DataProvisioningCallback;
+
+public abstract class DataProvisioningCallback {
+ public abstract void onProgress(DataProvisioningStatus 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.ESDataProvState;
+import org.iotivity.service.easysetup.mediator.enums.ESResult;
+
+public class DataProvisioningStatus
+{
+ private ESResult m_result;
+ private ESDataProvState m_state;
+
+ public DataProvisioningStatus(int result, int state)
+ {
+ m_result = ESResult.fromInt(result);
+ m_state = ESDataProvState.fromInt(state);
+ }
+
+ public ESResult getESResult()
+ {
+ return m_result;
+ }
+
+ public ESDataProvState getESDataProvState()
+ {
+ return m_state;
+ }
+};
-/**
- * ***************************************************************
- * <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 contains the connection details of the enrollee device
- */
-public interface OnBoardingConnection {
-
- /**
- * This method returns the implementation of the Connection
- *
- * @return implementation
- */
- public Object getConnection();
-
- /**
- * This method returns description on the connectivity.
- *
- * @return description
- */
- public String getDesc();
-
- /**
- * This method is used to know if the device is connected or not
- *
- * @return True if connected or False
- */
- public boolean isConnected();
-
-}
+/**\r
+ * ***************************************************************\r
+ *\r
+ * Copyright 2016 Samsung Electronics All Rights Reserved.\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
+\r
+package org.iotivity.service.easysetup.mediator;\r
+\r
+public class DeviceConfig\r
+{\r
+ private final String mId;\r
+ private final String mName;\r
+ private final String mLanguage;\r
+ private final String mCountry;\r
+\r
+ public DeviceConfig(String id, String name, String language, String country)\r
+ {\r
+ mId = id;\r
+ mName = name;\r
+ mLanguage = language;\r
+ mCountry = country;\r
+ }\r
+\r
+ public String getId()\r
+ {\r
+ return mId;\r
+ }\r
+\r
+ public String getName()\r
+ {\r
+ return mName;\r
+ }\r
+\r
+ public String getLanguage()\r
+ {\r
+ return mLanguage;\r
+ }\r
+\r
+ public String getCountry()\r
+ {\r
+ return mCountry;\r
+ }\r
+}\r
--- /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 java.io.IOException;
+import java.util.ArrayList;
+
+/**
+ * <To be modified>
+ * 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 EasySetup {
+
+ private static final String TAG = EasySetup.class.getName();
+
+ 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();
+
+ static {
+ // Load Easy Setup JNI interface
+ 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;
+ }
+
+ /**
+ * API to create a new RemoteEnrollee instance
+ */
+ public synchronized RemoteEnrollee createRemoteEnrollee()
+ {
+ // native call
+ mRemoteEnrollee = nativeCreateRemoteEnrollee();
+ mRemoteEnrolleeList.add(mRemoteEnrollee);
+ return mRemoteEnrollee;
+ }
+
+ /**
+ * Reset the Easy setup
+ */
+ public void finish() {
+ //Call the stop Provisioning
+ //for (RemoteEnrollee remoteEnrollee : mRemoteEnrolleeList)
+ // remoteEnrollee.stopProvisioningProcess();
+ }
+}
+++ /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
-/**
- * ***************************************************************
- * <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
-/**
- * ***************************************************************
- * <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
+/**\r
+ * ***************************************************************\r
+ *\r
+ * Copyright 2016 Samsung Electronics All Rights Reserved.\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
+\r
+package org.iotivity.service.easysetup.mediator;\r
+\r
+import android.util.Log;\r
+\r
+import org.iotivity.service.easysetup.mediator.enums.WIFI_FREQ;\r
+import org.iotivity.service.easysetup.mediator.enums.WIFI_MODE;\r
+\r
+import java.util.ArrayList;\r
+\r
+public class NetworkInfo\r
+{\r
+ public static final String TAG = NetworkInfo.class.getName();\r
+ private final ArrayList<WIFI_MODE> mWifiModeTypes;\r
+ private final WIFI_FREQ mWifiFreq;\r
+\r
+ public NetworkInfo(ArrayList<Integer> types, int wifiFreq)\r
+ {\r
+ mWifiModeTypes = convertWifiModeTypes(types);\r
+ mWifiFreq = WIFI_FREQ.fromInt(wifiFreq);\r
+ }\r
+\r
+ private ArrayList<WIFI_MODE> convertWifiModeTypes(ArrayList<Integer> types)\r
+ {\r
+ ArrayList<WIFI_MODE> wifiModeTypes = new ArrayList<>();\r
+ for (Integer type: types) {\r
+ wifiModeTypes.add(WIFI_MODE.fromInt(type.intValue()));\r
+ };\r
+ return wifiModeTypes;\r
+ }\r
+\r
+ public ArrayList<WIFI_MODE> getWifiModeTypes()\r
+ {\r
+ return mWifiModeTypes;\r
+ }\r
+\r
+ public WIFI_FREQ getWifiFreq()\r
+ {\r
+ return mWifiFreq;\r
+ }\r
+}\r
+++ /dev/null
-/**
- * ***************************************************************
- * <p/>
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- * <p/>
- * <p/>
- * <p/>
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * <p/>
- * ****************************************************************
- */
-
-package org.iotivity.service.easysetup.mediator;
-
-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
+/**
+ * ***************************************************************
+ *
+ * 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.WIFI_FREQ;
+import org.iotivity.service.easysetup.mediator.enums.WIFI_MODE;
+
+import java.util.ArrayList;
+
+public class PropertyData
+{
+ private final DeviceConfig mDevConf;
+ private final NetworkInfo mNetInfo;
+ private final boolean mCloudable;
+
+ public PropertyData(DeviceConfig devConf, NetworkInfo netInfo, boolean cloudable)
+ {
+ mDevConf = devConf;
+ mNetInfo = netInfo;
+ mCloudable = cloudable;
+ }
+
+ public DeviceConfig getDeviceConfig()
+ {
+ return mDevConf;
+ }
+
+ public NetworkInfo getNetworkInfo()
+ {
+ return mNetInfo;
+ }
+
+ public boolean isCloudable()
+ {
+ return mCloudable;
+ }
+}
+
+
+++ /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/>
+ *
* ****************************************************************
*/
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 nativeInitRemoteEnrollee();
+ private native void nativeRequestPropertyData(RequestPropertyDataCallback callback);
+ private native void nativeStartSecurityProvision(SecurityProvisioningCallback callback);
+ private native void nativeSetDataProvInfo(String ssid, String pwd, int authType, int encType,
+ String language, String country);
+ private native void nativeStartDataProvision(DataProvisioningCallback callback);
+ private native void nativeSetCloudProvInfo(String authCode, String autoProvider,
+ String ciServer);
+ private native void nativeStartCloudProvisioning(CloudProvisioningCallback 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");
+ /* native setCloudProvInfo */
+ public void initRemoteEnrollee() throws ESException
+ {
+ nativeInitRemoteEnrollee();
}
- /* native StartProvision */
- public void startProvision() throws ESException{
- nativeStartProvision();
-}
+ public void requestPropertyData(RequestPropertyDataCallback callback) throws ESException
+ {
+ if(callback != null)
+ {
+ nativeRequestPropertyData(callback);
+ return;
+ }
+ Log.d(TAG, "RequestPropertyDataCallback is null ");
+ }
- /* native stopProvision */
- public void stopProvision() throws ESException{
- nativeStopProvision();
-}
+ public void startSecurityProvisioning(SecurityProvisioningCallback callback) throws ESException
+ {
+ if(callback != null)
+ {
+ nativeStartSecurityProvision(callback);
+ return;
+ }
+ Log.d(TAG, "SecurityProvisioningCallback is null ");
+ }
+
+ public void setDataProvInfo(DataProvInfo dataInfo) throws ESException
+ {
+ nativeSetDataProvInfo(dataInfo.getSsid(), dataInfo.getPwd(),
+ dataInfo.getAuthType().getValue(), dataInfo.getEncType().getValue(),
+ dataInfo.getLanguage(), dataInfo.getCountry());
+ }
+ public void startDataProvisioning(DataProvisioningCallback callback) throws ESException
+ {
+ if(callback != null)
+ {
+ nativeStartDataProvision(callback);
+ return;
+ }
+ Log.d(TAG, "DataProvisioningCallback is null ");
+ }
+
+ public void setCloudProvInfo(CloudProvInfo cloudInfo) throws ESException{
+ nativeSetCloudProvInfo(cloudInfo.getAuthCode(), cloudInfo.getAuthProvider(),
+ cloudInfo.getCiServer());
+ }
+
+ /* native startCloudProvisioning */
+ public void startCloudProvisioning(CloudProvisioningCallback callback) throws ESException{
+ if(callback != null)
+ {
+ nativeStartCloudProvisioning(callback);
+ return;
+ }
+ Log.d(TAG, "CloudProvisioningCallback is 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.mediator;
-public abstract class ProvisioningCallback {
- public abstract void onFinished(EnrolleeDevice enrolledevice);
- public abstract void onProgress(EnrolleeDevice enrolledevice);
+import org.iotivity.service.easysetup.mediator.RequestPropertyDataCallback;
+
+public abstract class RequestPropertyDataCallback {
+ public abstract void onProgress(RequestPropertyDataStatus 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;
+
+public class RequestPropertyDataStatus
+{
+ private ESResult m_result;
+ private PropertyData m_propertyData;
+
+ public RequestPropertyDataStatus(int result, PropertyData data)
+ {
+ m_result = ESResult.fromInt(result);
+ m_propertyData = data;
+ }
+
+ public ESResult getESResult()
+ {
+ return m_result;
+ }
+
+ public PropertyData getPropertyData()
+ {
+ return m_propertyData;
+ }
+};
/**
* ***************************************************************
- * <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
- */
-public enum EnrolleeSetupError {
- /**
- * Device setup successful
- */
- DEVICE_SETUP_SUCCESSFUL,
- /**
- * Device setup failed
- */
- DEVICE_SETUP_FAILED,
+import org.iotivity.service.easysetup.mediator.SecurityProvisioningCallback;
+
+public abstract class SecurityProvisioningCallback {
+ 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;
+
+public class SecurityProvisioningStatus
+{
+ private ESResult mResult;
+ private String mDevUUID;
+
+ public SecurityProvisioningStatus(int result, String uuid)
+ {
+ mResult = ESResult.fromInt(result);
+ mDevUUID = uuid;
+ }
+
+ public ESResult getESResult()
+ {
+ return mResult;
+ }
+
+ 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;
+
+public enum ESDataProvState
+{
+ ES_PROVISIONING_ERROR(-1),
+ ES_NEED_PROVISIONING(0),
+ ES_PROVISIONED_ALREADY(1),
+ ES_PROVISIONING_SUCCESS(2);
+
+ private int value;
+
+ private ESDataProvState(int value)
+ {
+ this.value = value;
+ }
+
+ public int getValue()
+ {
+ return value;
+ }
+
+ public static ESDataProvState fromInt(int i)
+ {
+ for (ESDataProvState b : ESDataProvState.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;
+
+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 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;
+
+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;
+ }
+}
/**
* ***************************************************************
- * <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}
- */
+public enum WIFI_FREQ
+{
+ WIFI_24G(0),
+ WIFI_5G(1),
+ WIFI_BOTH(2);
- public void deviceOnBoardingStatus(EnrolleeInfo clients);
+ private int value;
+ private WIFI_FREQ(int value)
+ {
+ this.value = value;
+ }
+
+ public int getValue()
+ {
+ return 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;
+
+public enum WIFI_MODE
+{
+ WIFI_11A(0),
+ WIFI_11B(1),
+ WIFI_11G(2),
+ WIFI_11N(3),
+ WIFI_11AC(4);
+
+ private int value;
+
+ private WIFI_MODE(int value)
+ {
+ this.value = value;
+ }
+
+ public int getValue()
+ {
+ return value;
+ }
+
+ public static WIFI_MODE fromInt(int i)
+ {
+ for (WIFI_MODE b : WIFI_MODE.values())
+ {
+ if (b.getValue() == i)
+ return b;
+ }
+ return null;
+ }
+}
DEFINE_FLAG = -DWITH_POSIX -D__ANDROID__
#Add Debug flags here
-DEBUG_FLAG = -DTB_LOG
+DEBUG_FLAG = -DTB_LOG
BUILD_FLAG = $(DEFINE_FLAG) $(DEBUG_FLAG)
$(LOCAL_PATH)/../../src \
$(LOCAL_PATH)/../../../../inc \
$(LOCAL_PATH)/../../../../../../resource/csdk/logger/include \
- $(LOCAL_PATH)/../../../../../../resource/csdk/connectivity/common/inc \
+ $(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/csdk/security/include \
$(LOCAL_PATH)/../../../../../../extlibs/cjson \
$(LOCAL_PATH)/../../../../../../extlibs/boost/boost_1_58_0 \
- $(LOCAL_PATH)/../../../../../../extlibs/timer \
+ $(LOCAL_PATH)/../../../../../../extlibs/timer \
$(LOCAL_PATH)/../../../../../../android/android_api/base/jni \
LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/*.cpp))
--- /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 "JniCloudProvisioningStatusListener.h"
+#include "JniRemoteEnrollee.h"
+
+using namespace OIC::Service;
+
+JniCloudProvisioningStatusListener::JniCloudProvisioningStatusListener(JNIEnv *env, jobject jListener,
+ JniRemoteEnrollee *owner)
+ : m_ownerResource(owner)
+{
+ m_jwListener = env->NewWeakGlobalRef(jListener);
+}
+
+JniCloudProvisioningStatusListener::~JniCloudProvisioningStatusListener()
+{
+ LOGI("~JniCloudProvisioningStatusListener()");
+ 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 JniCloudProvisioningStatusListener::onCloudProvisioningStatus(std::shared_ptr<CloudProvisioningStatus>
+ cloudProvisioningStatus)
+{
+
+ LOGI("JniCloudProvisioningStatusListener::onCloudProvisioningStatus 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/"
+ "CloudProvisioningStatus;"
+ ")V");
+ if (!midL)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ ESResult esResult = cloudProvisioningStatus->getESResult();
+ ESCloudProvState cloudProvisionState = cloudProvisioningStatus->getESCloudState();
+
+ //create the java object
+ jobject jCloudProvisioningStatus = NULL;
+ jCloudProvisioningStatus = env->NewObject(g_cls_CloudProvisioningStatus,
+ g_mid_CloudProvisioningStatus_ctor,
+ (jint)esResult,
+ (jint)cloudProvisionState);
+
+ LOGI("JniCloudProvisioningStatus::onCloudProvisioningStatus - %d, %d", esResult, cloudProvisionState);
+ if (!jCloudProvisioningStatus)
+ {
+ LOGE("JniCloudProvisioningStatus::onCloudProvisioningStatus Unable to create the java object");
+ return ;
+ }
+
+ env->CallVoidMethod(jListener, midL, jCloudProvisioningStatus);
+
+ bool needRemoveListener = false;
+
+ if(cloudProvisionState == ES_CLOUD_PROVISIONING_ERROR ||
+ cloudProvisionState == ES_CLOUD_PROVISIONING_SUCCESS )
+ {
+ needRemoveListener = true;
+ }
+
+ if (env->ExceptionCheck())
+ {
+ 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 JniCloudProvisioningStatusListener::checkExAndRemoveListener(JNIEnv *env)
+{
+ if (env->ExceptionCheck())
+ {
+ jthrowable ex = env->ExceptionOccurred();
+ env->ExceptionClear();
+ m_ownerResource->removeStatusListener<JniCloudProvisioningStatusListener>(env, m_jwListener);
+ env->Throw((jthrowable)ex);
+ }
+ else
+ {
+ m_ownerResource->removeStatusListener<JniCloudProvisioningStatusListener>(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_PROVISIONING_STATUS_LISTENER_H_
+#define __JNI_ES_CLOUD_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 JniCloudProvisioningStatusListener
+ * @brief This class provides functions for handling the cloud provisioning status callback between the Java and native layer
*
*/
-class JniProvisioningStatusListener
+class JniCloudProvisioningStatusListener
{
public:
/**
* @brief constructor
*/
- JniProvisioningStatusListener(JNIEnv *env, jobject jListener, JniRemoteEnrollee *resource);
+ JniCloudProvisioningStatusListener(JNIEnv *env, jobject jListener, JniRemoteEnrollee *resource);
/**
* @brief destructor
*/
- ~JniProvisioningStatusListener();
+ ~JniCloudProvisioningStatusListener();
/**
* @brief callback function that will be passed to Native layer
*/
- void provisionStatusCallback (std::shared_ptr<EasySetupStatus> easySetupStatus);
+ void onCloudProvisioningStatus (std::shared_ptr<CloudProvisioningStatus> cloudProvisioningStatus);
private:
jweak m_jwListener;
};
#endif //__JNI_ES_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 "JniDataProvisioningStatusListener.h"
+#include "JniRemoteEnrollee.h"
+
+using namespace OIC::Service;
+
+JniDataProvisioningStatusListener::JniDataProvisioningStatusListener(JNIEnv *env, jobject jListener,
+ JniRemoteEnrollee *owner)
+ : m_ownerResource(owner)
+{
+ m_jwListener = env->NewWeakGlobalRef(jListener);
+}
+
+JniDataProvisioningStatusListener::~JniDataProvisioningStatusListener()
+{
+ LOGI("~JniDataProvisioningStatusListener()");
+ 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 JniDataProvisioningStatusListener::dataProvisionStatusCallback (std::shared_ptr<DataProvisioningStatus>
+ dataProvStatusCb)
+{
+
+ LOGI("JniDataProvisioningStatusListener::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;
+ }
+ //TODO:
+ jmethodID midL = env->GetMethodID(clsL, "onProgress",
+ "(Lorg/iotivity/service/easysetup/mediator/"
+ "DataProvisioningStatus;"
+ ")V");
+
+ if (!midL)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ int nativeESResult = convertNativeDataProvResultToInt(dataProvStatusCb->getESResult());
+ int nativeESDataProvState = convertNativeDataProvStateToInt(dataProvStatusCb->getESDataProvState());
+
+ jobject jDataProvisioningStatus = NULL;
+ jDataProvisioningStatus = env->NewObject(g_cls_DataProvisioningStatus,
+ g_mid_DataProvisioningStatus_ctor,
+ (jint)nativeESResult,
+ (jint)nativeESDataProvState);
+
+ LOGI("JniDataProvisioningStatus::onDataProvisioningStatus - %d, %d", nativeESResult, nativeESDataProvState);
+ if (!jDataProvisioningStatus)
+ {
+ LOGE("JniDataProvisioningStatus::onDataProvisioningStatus Unable to create the java object");
+ return ;
+ }
+
+ env->CallVoidMethod(jListener, midL, jDataProvisioningStatus);
+
+ if (env->ExceptionCheck())
+ {
+ LOGE("Java exception is thrown");
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+}
+
+void JniDataProvisioningStatusListener::checkExAndRemoveListener(JNIEnv *env)
+{
+ if (env->ExceptionCheck())
+ {
+ jthrowable ex = env->ExceptionOccurred();
+ env->ExceptionClear();
+ m_ownerResource->removeStatusListener<JniDataProvisioningStatusListener>(env, m_jwListener);
+ env->Throw((jthrowable)ex);
+ }
+ else
+ {
+ m_ownerResource->removeStatusListener<JniDataProvisioningStatusListener>(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_DATA_PROVISIONING_STATUS_LISTENER_H_
+#define __JNI_ES_DATA_PROVISIONING_STATUS_LISTENER_H_
+
+#include <jni.h>
+
+#include "RemoteEnrollee.h"
+#include "ESRichCommon.h"
+
+#include "JniJvm.h"
+
+class JniRemoteEnrollee;
+
+using namespace OIC::Service;
+
+class JniDataProvisioningStatusListener
+{
+ public:
+ /**
+ * @brief constructor
+ */
+ JniDataProvisioningStatusListener(JNIEnv *env, jobject jListener, JniRemoteEnrollee *resource);
+
+ /**
+ * @brief destructor
+ */
+ ~JniDataProvisioningStatusListener();
+
+ /**
+ * @brief callback function that will be passed to Native layer
+ */
+ void dataProvisionStatusCallback (std::shared_ptr<DataProvisioningStatus> dataProvisioningStatus);
+
+ private:
+ jweak m_jwListener;
+ JniRemoteEnrollee *m_ownerResource;
+ void checkExAndRemoveListener(JNIEnv *env);
+};
+
+#endif //__JNI_ES_DATA_PROVISIONING_STATUS_LISTENER_H_
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 interfaceClass)
{
- LOGI("JniEasySetup::nativeCreateEnrolleeDevice enter");
+ 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);
-
- 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());
try
{
- nativeRemoteEnrollee = EasySetup::getInstance()->createEnrolleeDevice(netInfo,onboardConn);
+ nativeRemoteEnrollee = EasySetup::getInstance()->createRemoteEnrollee();
//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");
+ LOGE("JniEasySetup::nativeCreateRemoteEnrollee Unable to create the java object");
return NULL;
}
}
catch (ESBadRequestException exception)
{
- LOGE("JniEasySetup::nativeCreateEnrolleeDevice Unable to create the Native EnrolleeDevice");
+ LOGE("JniEasySetup::nativeCreateRemoteEnrollee Unable to create the Native EnrolleeDevice");
//throw the exception to java layer
throwESException( env, exception.what());
}
- LOGI("JniEasySetup::nativeCreateEnrolleeDevice exit");
+ 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 interfaceClass);
#ifdef __cplusplus
}
return CT_DEFAULT;
}
-int convertNativeProvisionStateToInt(EasySetupState nativeState)
+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 convertNativeDataProvStateToInt(ESDataProvState nativeState)
{
switch (nativeState)
{
- case EasySetupState::DEVICE_PROVISIONED:
+ case ESDataProvState::ES_PROVISIONING_ERROR:
+ return -1;
+ case ESDataProvState::ES_NEED_PROVISIONING:
+ return 0;
+ case ESDataProvState::ES_PROVISIONED_ALREADY:
+ return 1;
+ case ESDataProvState::ES_PROVISIONING_SUCCESS:
+ return 2;
+ }
+}
+
+int convertNativeDataProvResultToInt(ESResult nativeResult)
+{
+ switch (nativeResult)
+ {
+ case ESResult::ES_ERROR:
+ return -1;
+ case ESResult::ES_OK:
return 0;
- case EasySetupState::DEVICE_NOT_PROVISIONED:
+ case ESResult::ES_NETWORKFOUND:
return 1;
- case EasySetupState::DEVICE_OWNED:
+ case ESResult::ES_NETWORKCONNECTED:
return 2;
- case EasySetupState::DEVICE_NOT_OWNED:
+ 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;
}
- return -1;
}
\ 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 convertNativeDataProvStateToInt(ESDataProvState nativeState);
+int convertNativeDataProvResultToInt(ESResult nativeResult);
#endif //__JNI_ES_UTILS_H_
JavaVM *g_jvm = NULL;
jclass g_cls_RemoteEnrollee = NULL;
+jclass g_cls_PropertyData = NULL;
+jclass g_cls_DeviceConfig = NULL;
+jclass g_cls_NetworkInfo = NULL;
+jclass g_cls_RequestPropertyDataStatus = NULL;
+jclass g_cls_SecurityProvisioningStatus = NULL;
+jclass g_cls_DataProvisioningStatus = NULL;
jclass g_cls_ESException = NULL;
+jclass g_cls_CloudProvisioningStatus = NULL;
+jclass g_cls_Integer = NULL;
jmethodID g_mid_RemoteEnrollee_ctor = NULL;
jmethodID g_mid_ESException_ctor = NULL;
+jmethodID g_mid_PropertyData_ctor = NULL;
+jmethodID g_mid_DeviceConfig_ctor = NULL;
+jmethodID g_mid_NetworkInfo_ctor = NULL;
+jmethodID g_mid_RequestPropertyDataStatus_ctor = NULL;
+jmethodID g_mid_SecurityProvisioningStatus_ctor = NULL;
+jmethodID g_mid_DataProvisioningStatus_ctor = NULL;
+jmethodID g_mid_CloudProvisioningStatus_ctor = NULL;
+jmethodID g_mid_Integer_ctor = NULL;
// JNI OnLoad
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
jclass clazz = nullptr;
- //Remote Enrollee
+ // Remote Enrollee
clazz = env->FindClass("org/iotivity/service/easysetup/mediator/RemoteEnrollee");
if (!clazz) return JNI_ERR;
g_cls_RemoteEnrollee = (jclass)env->NewGlobalRef(clazz);
"(J)V");
if (!g_mid_RemoteEnrollee_ctor) return JNI_ERR;
- //ESException
+ // ESException
clazz = env->FindClass("org/iotivity/service/easysetup/mediator/ESException");
if (!clazz) return JNI_ERR;
g_cls_ESException = (jclass)env->NewGlobalRef(clazz);
g_mid_ESException_ctor = env->GetMethodID(g_cls_ESException, "<init>", "(Ljava/lang/String;)V");
if (!g_mid_ESException_ctor) return JNI_ERR;
+ // DeviceConfig
+ clazz = env->FindClass("org/iotivity/service/easysetup/mediator/DeviceConfig");
+ if (!clazz) return JNI_ERR;
+
+ g_cls_DeviceConfig = (jclass)env->NewGlobalRef(clazz);
+ env->DeleteLocalRef(clazz);
+
+ g_mid_DeviceConfig_ctor = env->GetMethodID(g_cls_DeviceConfig, "<init>",
+ "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
+ if (!g_mid_DeviceConfig_ctor) return JNI_ERR;
+
+ // NetworkInfo
+ clazz = env->FindClass("org/iotivity/service/easysetup/mediator/NetworkInfo");
+ if (!clazz) return JNI_ERR;
+
+ g_cls_NetworkInfo = (jclass)env->NewGlobalRef(clazz);
+ env->DeleteLocalRef(clazz);
+
+ g_mid_NetworkInfo_ctor = env->GetMethodID(g_cls_NetworkInfo, "<init>",
+ "(Ljava/util/ArrayList;I)V");
+ if (!g_mid_NetworkInfo_ctor) return JNI_ERR;
+
+ // PropertyData
+ clazz = env->FindClass("org/iotivity/service/easysetup/mediator/PropertyData");
+ if (!clazz) return JNI_ERR;
+
+ g_cls_PropertyData = (jclass)env->NewGlobalRef(clazz);
+ env->DeleteLocalRef(clazz);
+
+ g_mid_PropertyData_ctor = env->GetMethodID(g_cls_PropertyData, "<init>",
+ "(Lorg/iotivity/service/easysetup/mediator/DeviceConfig;Lorg/iotivity/service/easysetup/mediator/NetworkInfo;Z)V");
+ if (!g_mid_PropertyData_ctor) return JNI_ERR;
+
+ // RequestPropertyDataStatus
+ clazz = env->FindClass("org/iotivity/service/easysetup/mediator/RequestPropertyDataStatus");
+ if (!clazz) return JNI_ERR;
+
+ g_cls_RequestPropertyDataStatus = (jclass)env->NewGlobalRef(clazz);
+ env->DeleteLocalRef(clazz);
+
+ g_mid_RequestPropertyDataStatus_ctor = env->GetMethodID(g_cls_RequestPropertyDataStatus, "<init>",
+ "(ILorg/iotivity/service/easysetup/mediator/PropertyData;)V");
+ if (!g_mid_RequestPropertyDataStatus_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;
+
+ // DataProvisioningStatus
+ clazz = env->FindClass("org/iotivity/service/easysetup/mediator/DataProvisioningStatus");
+ if (!clazz) return JNI_ERR;
+
+ g_cls_DataProvisioningStatus = (jclass)env->NewGlobalRef(clazz);
+ env->DeleteLocalRef(clazz);
+
+ g_mid_DataProvisioningStatus_ctor = env->GetMethodID(g_cls_DataProvisioningStatus, "<init>",
+ "(II)V");
+ if (!g_mid_DataProvisioningStatus_ctor) return JNI_ERR;
+
+ // CloudProvisioningStatus
+ clazz = env->FindClass("org/iotivity/service/easysetup/mediator/CloudProvisioningStatus");
+ if (!clazz) return JNI_ERR;
+ g_cls_CloudProvisioningStatus = (jclass)env->NewGlobalRef(clazz);
+ env->DeleteLocalRef(clazz);
+
+ g_mid_CloudProvisioningStatus_ctor = env->GetMethodID(g_cls_CloudProvisioningStatus, "<init>",
+ "(II)V");
+ if (!g_mid_CloudProvisioningStatus_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;
+
return JNI_CURRENT_VERSION;
}
#define __JNI_ES_JVM_H
#include <jni.h>
-#include<string>
+#include <string>
#include <android/log.h>
#define ESTAG "ES-JNI"
extern jclass g_cls_RemoteEnrollee;
extern jclass g_cls_ESException;
-
-extern jmethodID g_mid_RemoteEnrollee_ctor ;
+extern jclass g_cls_PropertyData;
+extern jclass g_cls_DeviceConfig;
+extern jclass g_cls_NetworkInfo;
+extern jclass g_cls_RequestPropertyDataStatus;
+extern jclass g_cls_SecurityProvisioningStatus;
+extern jclass g_cls_DataProvisioningStatus;
+extern jclass g_cls_CloudProvisioningStatus;
+extern jclass g_cls_Integer;
+
+extern jmethodID g_mid_RemoteEnrollee_ctor;
extern jmethodID g_mid_ESException_ctor;
+extern jmethodID g_mid_PropertyData_ctor;
+extern jmethodID g_mid_DeviceConfig_ctor;
+extern jmethodID g_mid_NetworkInfo_ctor;
+extern jmethodID g_mid_RequestPropertyDataStatus_ctor;
+extern jmethodID g_mid_SecurityProvisioningStatus_ctor;
+extern jmethodID g_mid_DataProvisioningStatus_ctor;
+extern jmethodID g_mid_CloudProvisioningStatus_ctor;
+extern jmethodID g_mid_Integer_ctor;
typedef void(*RemoveListenerCallback)(JNIEnv *env, jobject jListener);
if (NULL == env) return;
if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
-
}
JniRemoteEnrollee *JniRemoteEnrollee::getJniRemoteEnrollee(JNIEnv *env, jobject thiz)
return remoteEnrollee;
}
-void JniRemoteEnrollee::startProvisioning(JNIEnv *env)
+void JniRemoteEnrollee::initRemoteEnrollee(JNIEnv *env)
{
try
{
- m_sharedResource->startProvisioning();
+ m_sharedResource->initRemoteEnrollee();
}
catch (ESBadRequestException exception)
{
- LOGE("JNI startProvisioning :: Exception occured");
+ LOGE("JNI initRemoteEnrollee :: Exception occured");
//throw the exception to java
throwESException( env, exception.what());
}
}
-void JniRemoteEnrollee::stopProvisioning(JNIEnv *env)
+
+void JniRemoteEnrollee::requestPropertyData(JNIEnv *env, jobject jListener)
{
+ JniRequestPropertyDataStatusListener *onRequestPropertyDataStatusReceived =
+ addStatusListener<JniRequestPropertyDataStatusListener>(env, jListener);
+
+ RequestPropertyDataStatusCb requestPropertyDataStatusCallback = [onRequestPropertyDataStatusReceived]
+ (std::shared_ptr<OIC::Service::RequestPropertyDataStatus > requestPropertyDataStatus)
+ {
+ onRequestPropertyDataStatusReceived->requestPropertyDataStatusCallback(requestPropertyDataStatus);
+ };
+
try
{
- m_sharedResource->stopProvisioning();
+ m_sharedResource->requestPropertyData(requestPropertyDataStatusCallback);
}
catch (ESBadRequestException exception)
{
- LOGE("JNI stopProvisioning :: Exception occured");
+ LOGE("JNI requestPropertyData :: Exception occured");
//throw the exception to java
throwESException( env, exception.what());
}
}
-void JniRemoteEnrollee::registerProvisioningHandler(JNIEnv *env, jobject jListener)
+void JniRemoteEnrollee::startSecurityProvisioning(JNIEnv *env, jobject jListener)
{
- JniProvisioningStatusListener *onProvisioningStatusReceived = addProvisioningStatusListener(env,
- jListener);
+ JniSecurityStatusListener *onSecurityProvStatusReceived =
+ addStatusListener<JniSecurityStatusListener>(env, jListener);
+
+ SecurityProvStatusCb secProvStatusCallback = [onSecurityProvStatusReceived]
+ (std::shared_ptr<OIC::Service::SecProvisioningStatus > SecProvisioningStatus)
+ {
+ onSecurityProvStatusReceived->secProvisionStatusCallback(SecProvisioningStatus);
+ };
+
+ try
+ {
+ m_sharedResource->startSecurityProvisioning(secProvStatusCallback);
+ }
+ catch (ESBadRequestException exception)
+ {
+ LOGE("JNI startSecurityProvisioning :: Exception occured");
+ //throw the exception to java
+ throwESException( env, exception.what());
+ }
+}
- RemoteEnrollee::EasySetupStatusCB provisionStatusCallback = [onProvisioningStatusReceived]
- (std::shared_ptr< OIC::Service::EasySetupStatus > easySetupStatus)
+void JniRemoteEnrollee::startDataProvisioning(JNIEnv *env, jobject jListener)
+{
+ JniDataProvisioningStatusListener *onDataProvStatusReceived =
+ addStatusListener<JniDataProvisioningStatusListener>(env, jListener);
+ DataProvStatusCb dataProvStatusCallback = [onDataProvStatusReceived]
+ (std::shared_ptr<OIC::Service::DataProvisioningStatus > dataProvisioningStatus)
{
- onProvisioningStatusReceived->provisionStatusCallback(easySetupStatus);
+ onDataProvStatusReceived->dataProvisionStatusCallback(dataProvisioningStatus);
};
try
{
- m_sharedResource->registerEasySetupStatusHandler(provisionStatusCallback);
+ m_sharedResource->startDataProvisioning(dataProvStatusCallback);
}
- catch (ESException exception)
+ catch (ESBadRequestException exception)
{
- LOGE("JNI stopProvisioning :: Exception occured");
+ LOGE("JNI startDataProvisioning :: Exception occured");
//throw the exception to java
throwESException( env, exception.what());
}
+}
+
+void JniRemoteEnrollee::setDataProvInfo(JNIEnv *env, jstring jssid, jstring jpwd, jint jauthType,
+ jint jencType, jstring jlanguage, jstring jcountry)
+{
+ DataProvInfo info;
+
+ info.WIFI.ssid = env->GetStringUTFChars(jssid, NULL);
+ info.WIFI.pwd = env->GetStringUTFChars(jpwd, NULL);
+ info.WIFI.authtype = getWifiAuthTypeFromInt(jauthType);
+ info.WIFI.enctype = getWifiEncTypeFromInt(jencType);
+ info.Device.language = env->GetStringUTFChars(jlanguage, NULL);
+ info.Device.country = env->GetStringUTFChars(jcountry, NULL);
+ m_sharedResource->setDataProvInfo(info);
}
-JniProvisioningStatusListener *JniRemoteEnrollee::addProvisioningStatusListener(JNIEnv *env,
- jobject jListener)
+void JniRemoteEnrollee::setCloudProvInfo(JNIEnv *env, jstring jauthCode, jstring jauthProvider, jstring jciServer)
{
- return this->m_provisioingStatus.addListener(env, jListener, this);
+ CloudProvInfo info;
+ info.authCode = env->GetStringUTFChars(jauthCode, NULL);
+ info.authProvider = env->GetStringUTFChars(jauthProvider, NULL);
+ info.ciServer = env->GetStringUTFChars(jciServer, NULL);
+
+ m_sharedResource->setCloudProvInfo(info);
}
-void JniRemoteEnrollee::removeProvisioningStatusListener(JNIEnv *env, jobject jListener)
+void JniRemoteEnrollee::startCloudProvisioning(JNIEnv *env, jobject jListener)
{
- this->m_provisioingStatus.removeListener(env, jListener);
+ JniCloudProvisioningStatusListener *onCloudProvisioningStatusReceived =
+ addStatusListener<JniCloudProvisioningStatusListener>(env, jListener);
+
+ CloudProvStatusCb provisionStatusCallback = [onCloudProvisioningStatusReceived]
+ (std::shared_ptr< OIC::Service::CloudProvisioningStatus > cloudProvisioningStatus)
+
+ {
+ onCloudProvisioningStatusReceived->onCloudProvisioningStatus(cloudProvisioningStatus);
+ };
+
+ try
+ {
+ m_sharedResource->startCloudProvisioning(provisionStatusCallback);
+ }
+ catch (ESBadRequestException exception)
+ {
+ 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_nativeStartProvision
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeInitRemoteEnrollee
(JNIEnv *env, jobject jClass)
{
- LOGD("nativeStartProvision Enter");
+ LOGD("nativeInitRemoteEnrollee Enter");
JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
- remoteEnrollee->startProvisioning(env);
+ remoteEnrollee->initRemoteEnrollee(env);
- LOGD("nativeStartProvision Exit");
+ LOGD("nativeInitRemoteEnrollee Exit");
}
JNIEXPORT void JNICALL
-Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeStopProvision
-(JNIEnv *env, jobject jClass)
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeRequestPropertyData
+(JNIEnv *env, jobject jClass, jobject jListener)
{
+ LOGD("nativeRequestPropertyData Enter");
- LOGD("nativeStopProvision Enter");
+ JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
+ remoteEnrollee->requestPropertyData(env, jListener);
+
+ LOGD("nativeRequestPropertyData Exit");
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeStartSecurityProvision
+(JNIEnv *env, jobject jClass, jobject jListener)
+{
+ LOGD("nativeStartSecurityProvision Enter");
JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
- remoteEnrollee->stopProvisioning(env);
+ remoteEnrollee->startSecurityProvisioning(env, jListener);
- LOGD("nativeStopProvision Exit");
+ LOGD("nativeStartSecurityProvision Exit");
}
JNIEXPORT void JNICALL
-Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeRegisterProvisioningHandler
-(JNIEnv *env, jobject jClass, jobject provisiongListener)
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeStartDataProvision
+(JNIEnv *env, jobject jClass, jobject jListener)
{
- LOGD("nativeRegisterProvisioningHandler Enter");
+ LOGD("nativeStartDataProvision Enter");
+
+ JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
+ remoteEnrollee->startDataProvisioning(env, jListener);
+
+ LOGD("nativeStartDataProvision Exit");
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeSetDataProvInfo
+(JNIEnv *env, jobject jClass, jstring jssid, jstring jpwd, jint jauthType, jint jencType,
+ jstring jlanguage, jstring jcountry)
+{
+ LOGD("nativeSetDataProvInfo Enter");
- if (!provisiongListener)
- {
- LOGE("nativeRegisterProvisioningHandler : listener is NULL");
- return;
- }
JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
- remoteEnrollee->registerProvisioningHandler(env, provisiongListener);
+ remoteEnrollee->setDataProvInfo(env, jssid, jpwd, jauthType, jencType, jlanguage, jcountry);
- LOGD("nativeRegisterProvisioningHandler Exit");
+ LOGD("nativeSetDataProvInfo Exit");
}
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeSetCloudProvInfo
+(JNIEnv *env, jobject jClass, jstring jauthCode, jstring jauthProvider, jstring jciServer)
+{
+ LOGD("nativeSetCloudProvInfo Enter");
+
+ // TODO
+ JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
+ remoteEnrollee->setCloudProvInfo(env, jauthCode, jauthProvider, jciServer);
+
+ LOGD("nativeSetCloudProvInfo Exit");
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeStartCloudProvisioning
+(JNIEnv *env, jobject jClass, jobject jListener)
+{
+ LOGD("nativeStartCloudProvisioning Enter");
+
+ JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
+ remoteEnrollee->startCloudProvisioning(env, jListener);
+
+ LOGD("nativeStartCloudProvisioning Exit");
+}
\ No newline at end of file
#include "JniJvm.h"
#include "JniEsUtils.h"
-#include "JniProvisioningStatusListener.h"
+#include "JniRequestPropertyDataStatusListener.h"
+#include "JniSecurityStatusListener.h"
+#include "JniDataProvisioningStatusListener.h"
+#include "JniCloudProvisioningStatusListener.h"
#include "JniEsListenerManager.h"
using namespace OIC::Service;
~JniRemoteEnrollee();
// ***** JNI APIs internally call the APIs of this class ***** //
+ void initRemoteEnrollee(JNIEnv *env);
+ void requestPropertyData(JNIEnv *env, jobject jListener);
+ void startSecurityProvisioning(JNIEnv *env, jobject jListener);
+ void startDataProvisioning(JNIEnv *env, jobject jListener);
+ void startCloudProvisioning(JNIEnv *env, jobject jListener);
+ void setDataProvInfo(JNIEnv *env, jstring jssid, jstring jpwd, jint jauthType,
+ jint jencType, jstring jlanguage, jstring jcountry);
+ void setCloudProvInfo(JNIEnv *env, jstring authCode, jstring authProvider, jstring ciServer);
- 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;
};
#endif
/**
- * API for starting the provisioning process.
+ * API for starting the initRemoteEnrollee process.
*/
JNIEXPORT void JNICALL
-Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeStartProvision
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeInitRemoteEnrollee
(JNIEnv *env, jobject jClass);
/**
- * API for stopping the provisioning process.
+ * API for starting the Request PropertyData process.
*/
JNIEXPORT void JNICALL
-Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeStopProvision
-(JNIEnv *env, jobject jClass);
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeRequestPropertyData
+(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_nativeStartSecurityProvision
+(JNIEnv *env, jobject jClass, jobject jListener);
+
+/**
+ * API for starting the Data provisioning process.
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeStartDataProvision
+(JNIEnv *env, jobject jClass, jobject jListener);
+
+/**
+ * API for setting data provisioning information.
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeSetDataProvInfo
+(JNIEnv *env, jobject jClass, jstring jssid, jstring jpwd, jint jauthType, jint jencType,
+ jstring jlanguage, jstring jcountry);
+
+/**
+ * API for setting cloud provisioning information.
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeSetCloudProvInfo
+(JNIEnv *env, jobject jClass, jstring jauthCode, jstring jauthProvider, jstring jciServer);
+
+/**
+ * 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_nativeStartCloudProvisioning
+(JNIEnv *env, jobject jClass, jobject jListener);
#ifdef __cplusplus
}
--- /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 "JniRequestPropertyDataStatusListener.h"
+#include "JniRemoteEnrollee.h"
+
+using namespace OIC::Service;
+
+JniRequestPropertyDataStatusListener::JniRequestPropertyDataStatusListener(JNIEnv *env, jobject jListener,
+ JniRemoteEnrollee *owner)
+ : m_ownerResource(owner)
+{
+ m_jwListener = env->NewWeakGlobalRef(jListener);
+}
+
+JniRequestPropertyDataStatusListener::~JniRequestPropertyDataStatusListener()
+{
+ LOGI("~JniRequestPropertyDataStatusListener()");
+ 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 JniRequestPropertyDataStatusListener::requestPropertyDataStatusCallback (
+ std::shared_ptr<RequestPropertyDataStatus> requestPropertyDataStatusCb)
+{
+ LOGI("JniRequestPropertyDataStatusListener::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/"
+ "RequestPropertyDataStatus;"
+ ")V");
+
+ if (!midL)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ const PropertyData propertyData = requestPropertyDataStatusCb->getPropertyData();
+ DeviceConfig devConf = propertyData.getDevConf();
+ NetworkInfo netInfo = propertyData.getNetInfo();
+
+ jobject jDevConf = NULL;
+ jDevConf = env->NewObject(g_cls_DeviceConfig,
+ g_mid_DeviceConfig_ctor,
+ (jstring)env->NewStringUTF(devConf.id.c_str()),
+ (jstring)env->NewStringUTF(devConf.name.c_str()),
+ (jstring)env->NewStringUTF(devConf.language.c_str()),
+ (jstring)env->NewStringUTF(devConf.country.c_str()));
+ if (!jDevConf) {
+ LOGE("JniRequestPropertyDataStatusListener::requestPropertyDataStatusCallback Unable to create the jDevConf");
+ return ;
+ }
+
+ jclass clazz = env->FindClass("java/util/ArrayList");
+ jobject wifiModeTypes = env->NewObject(clazz, env->GetMethodID(clazz, "<init>", "()V"));
+ jmethodID arraylist_add = env->GetMethodID(clazz, "add", "(Ljava/lang/Object;)Z");
+
+ for (int n=0; n<netInfo.types.size(); n++)
+ {
+ jobject value = env->NewObject(g_cls_Integer,
+ g_mid_Integer_ctor,
+ convertNativeWifiModeToInt(static_cast<WIFI_MODE>(netInfo.types[n])));
+ env->CallBooleanMethod(wifiModeTypes, arraylist_add, value);
+ }
+ if (!wifiModeTypes) {
+ LOGE("JniRequestPropertyDataStatusListener::requestPropertyDataStatusCallback Unable to create the wifiModeTypes");
+ return ;
+ }
+
+
+ jobject jNetInfo = NULL;
+ jNetInfo = env->NewObject(g_cls_NetworkInfo,
+ g_mid_NetworkInfo_ctor,
+ (jobject)wifiModeTypes,
+ (jint)convertNativeWifiFreqToInt(netInfo.freq));
+ if (!jNetInfo) {
+ LOGE("JniRequestPropertyDataStatusListener::requestPropertyDataStatusCallback Unable to create the jNetInfo");
+ return ;
+ }
+
+ jobject jPropertyData = NULL;
+ jPropertyData = env->NewObject(g_cls_PropertyData,
+ g_mid_PropertyData_ctor,
+ (jobject)jDevConf,
+ (jobject)jNetInfo,
+ (jboolean)propertyData.isCloudable());
+ if (!jPropertyData) {
+ LOGE("JniRequestPropertyDataStatusListener::requestPropertyDataStatusCallback Unable to create the jPropertyData");
+ return ;
+ }
+
+ ESResult esResult = requestPropertyDataStatusCb->getESResult();
+ jobject jRequestPropertyDataStatus = NULL;
+ jRequestPropertyDataStatus = env->NewObject(g_cls_RequestPropertyDataStatus,
+ g_mid_RequestPropertyDataStatus_ctor,
+ (jint)esResult,
+ (jobject)jPropertyData);
+LOGI("4");
+ if (!jRequestPropertyDataStatus)
+ {
+ LOGE("JniRequestPropertyDataStatusListener::requestPropertyDataStatusCallback Unable to create the java object");
+ return ;
+ }
+
+ env->CallVoidMethod(jListener, midL, jRequestPropertyDataStatus);
+
+ if (env->ExceptionCheck())
+ {
+ LOGE("Java exception is thrown");
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+}
+
+void JniRequestPropertyDataStatusListener::checkExAndRemoveListener(JNIEnv *env)
+{
+ if (env->ExceptionCheck())
+ {
+ jthrowable ex = env->ExceptionOccurred();
+ env->ExceptionClear();
+ m_ownerResource->removeStatusListener<JniRequestPropertyDataStatusListener>(env, m_jwListener);
+
+ env->Throw((jthrowable)ex);
+ }
+ else
+ {
+ m_ownerResource->removeStatusListener<JniRequestPropertyDataStatusListener>(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_REQUEST_PROPERTY_DATA_STATUS_LISTENER_H_
+#define __JNI_ES_REQUEST_PROPERTY_DATA_STATUS_LISTENER_H_
+
+#include <jni.h>
+
+#include "RemoteEnrollee.h"
+#include "ESRichCommon.h"
+
+#include "JniJvm.h"
+
+class JniRemoteEnrollee;
+
+using namespace OIC::Service;
+
+class JniRequestPropertyDataStatusListener
+{
+ public:
+ /**
+ * @brief constructor
+ */
+ JniRequestPropertyDataStatusListener(JNIEnv *env, jobject jListener, JniRemoteEnrollee *resource);
+
+ /**
+ * @brief destructor
+ */
+ ~JniRequestPropertyDataStatusListener();
+
+ /**
+ * @brief callback function that will be passed to Native layer
+ */
+ void requestPropertyDataStatusCallback (std::shared_ptr<RequestPropertyDataStatus> requestPropertyDataStatus);
+
+ private:
+ jweak m_jwListener;
+ JniRemoteEnrollee *m_ownerResource;
+ void checkExAndRemoveListener(JNIEnv *env);
+};
+
+#endif //__JNI_ES_REQUEST_PROPERTY_DATA_STATUS_LISTENER_H_
*
******************************************************************/
-#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()");
+ 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");
+ 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()));
+
+ LOGE("JniSecurityStatusListener::onSecurityProvisioningStatus UUID : %s", secProvisioningStatus->getDeviceUUID().c_str());
+
+ if (!jSecurityProvisioningStatus)
+ {
+ LOGE("JniSecurityStatusListener::onSecurityProvisioningStatus Unable to create the java object");
+ return ;
+ }
+
+ env->CallVoidMethod(jListener, midL, jSecurityProvisioningStatus);
+
if (env->ExceptionCheck())
{
LOGE("Java exception is thrown");
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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#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 registerCloudProvisioningStatusCallback (CloudProvStatusCb callback);
+ void provisionEnrollee(const CloudProvInfo& cloudProvInfo);
+
+ private:
+ void onCloudProvResponse(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+ const int eCode);
+
+ private:
+ std::shared_ptr< OC::OCResource > m_ocResource;
+ CloudProvStatusCb m_cloudProvStatusCb;
+
+ DataProvInfo m_dataProvInfo;
+ };
+ }
+}
+#endif
#include <string>
#ifndef WITH_ARDUINO
#include <memory>
+#include <vector>
#endif
#include "ocstack.h"
using namespace std;
// 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 NET_MACADDR_SIZE 18
+#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 "cisurl"
+#define OC_RSRVD_ES_DEVNAME "dn"
+#define OC_RSRVD_ES_LANGUAGE "lang"
+#define OC_RSRVD_ES_COUNTRY "ctry"
/**
- * Attributes used to form a proper easysetup conforming JSON message.
+ * Easysetup defined resoruce types and uris
*/
-#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
+#define OC_RSRVD_ES_RES_TYPE_PROV "ocf.r.prov"
+#define OC_RSRVD_ES_URI_PROV "/.well-known/ocf/prov"
+#define OC_RSRVD_ES_RES_TYPE_WIFI "ocf.r.wifi"
+#define OC_RSRVD_ES_URI_WIFI "/.well-known/ocf/prov/wifi"
+#define OC_RSRVD_ES_RES_TYPE_CLOUDSERVER "ocf.r.cloudserver"
+#define OC_RSRVD_ES_URI_CLOUDSERVER "/.well-known/ocf/prov/cloudserver"
+#define OC_RSRVD_ES_RES_TYPE_DEVCONF "ocf.r.devconf"
+#define OC_RSRVD_ES_URI_DEVCONF "/.well-known/ocf/prov/devconf"
#ifndef WITH_ARDUINO
namespace OIC
{
namespace Service
{
-
- /**
- * Device Roles defined for each device type used in easy setup
- */
- typedef enum
- {
- ENROLLEE,
- MEDIATOR,
- ENROLLER,
- } DeviceRole;
-
- /**
- * On-boarding connection to create Adhoc network.
- */
- typedef enum
- {
- SOFTAP,
- BLE,
- } OBConnection;
-
typedef enum
{
ES_ERROR = -1,
ES_RECVREQOFNETRES,
ES_RECVUPDATEOFPROVRES,
ES_RECVTRIGGEROFPROVRES,
+ ES_UNAUTHORIZED = 31
} ESResult;
+ /**
+ * @brief WIFI Authentication tlype of the Enroller
+ */
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,
-
- /**
- * Device will move to this state after successful on-boarding of the device
- */
- ES_ON_BOARDED_STATE,
-
- /**
- * Device will move to this state once the on boarding is done
- */
- ES_PROVISIONING_STATE,
-
- /**
- * Easy setup process is successful.
- */
- ES_PROVISIONED_STATE,
-
- /**
- * This state is arbitrary one, any time device can come into this state
- * Device will move to this state if the ownership transfer initiated by the Application
- */
- ES_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
- */
- ES_OWNERSHIP_TRANSFERRED_STATE,
-
- /**
- * This state is arbitrary one, any time device can come into this state
- * Device will move to this state once the Application factory reset the device
- */
- ES_FACTORY_RESET_STATE,
-
- /**
- * Enrollee moves to this state after connecting to target network
- */
- ES_ON_BOARDED_TARGET_NETWORK_STATE,
- }EnrolleeState;
+ NONE_AUTH = 0,
+ WEP,
+ WPA_PSK,
+ WPA2_PSK
+ } WIFI_AUTHTYPE;
/**
- * Provisioning Device Status
+ * @brief WIFI encryption type of the Enroller
*/
- typedef struct
+ typedef enum
{
- // Address of remote server
- OCDevAddr * addr;
- // Indicates adaptor type on which the response was received
- OCConnectivityType connType;
- } EasySetupDeviceInfo;
+ NONE_ENC = 0,
+ WEP_64,
+ WEP_128,
+ TKIP,
+ AES,
+ TKIP_AES
+ } WIFI_ENCTYPE;
- /**
- * Provosioning Status
- */
typedef enum
{
- DEVICE_PROVISIONED = 0,
- DEVICE_NOT_PROVISIONED,
- DEVICE_OWNED,
- DEVICE_NOT_OWNED
- } EasySetupState, ProvStatus;
+ WIFI_24G = 0,
+ WIFI_5G,
+ WIFI_BOTH
+ } WIFI_FREQ;
- /**
- * Response from queries to remote servers.
- */
- typedef struct
+ typedef enum
{
- // EasySetup Status
- EasySetupState provStatus;
- // EasySetup Device Info
- EasySetupDeviceInfo provDeviceInfo;
- } EasySetupInfo, ProvisioningInfo;
+ WIFI_11A = 0,
+ WIFI_11B,
+ WIFI_11G,
+ WIFI_11N,
+ WIFI_11AC
+ } WIFI_MODE;
- /**
- * @brief Network information of the Enroller
- */
- typedef union
+ typedef struct
{
- /**
- * @brief BT Mac Information
- */
- struct
- {
- char btMacAddress[NET_MACADDR_SIZE]; /**< BT mac address **/
- } BT;
+ string authCode;
+ string authProvider;
+ string ciServer;
+ } CloudProvInfo;
- /**
- * @brief LE MAC Information
- */
+ typedef struct
+ {
struct
{
- char leMacAddress[NET_MACADDR_SIZE]; /**< BLE mac address **/
- } LE;
+ string ssid; /**< ssid of the Enroller**/
+ string pwd; /**< pwd of the Enroller**/
+ WIFI_AUTHTYPE authtype; /**< auth type of the Enroller**/
+ WIFI_ENCTYPE enctype; /**< encryption type of the Enroller**/
+ } WIFI;
- /**
- * @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);
+ string language;
+ string country;
+ } Device;
+ } DataProvInfo;
- /**
- * @brief This structure represent configuration information to create wifi onboarding SoftAP or connection.
- */
-
- // 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;
+ string id;
+ string name;
+ string language;
+ string country;
+ } DeviceConfig;
- /**
- * @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;
+ vector<WIFI_MODE> types;
+ WIFI_FREQ freq;
+ } NetworkInfo;
typedef enum
{
ES_NEED_PROVISIONING,
ES_PROVISIONED_ALREADY,
ES_PROVISIONING_SUCCESS
- } ESState;
+ } ESDataProvState;
typedef enum
{
- ES_UNKNOWN = 0,
- ES_ONBOARDED,
- ES_OWNED,
- ES_PROVISIONED
- } CurrentESState;
+ ES_CLOUD_PROVISIONING_ERROR = -1,
+ ES_CLOUD_PROVISIONING_SUCCESS,
+ ES_CLOUD_ENROLLEE_FOUND,
+ ES_CLOUD_ENROLLEE_NOT_FOUND
+ }ESCloudProvState;
typedef enum
{
/**
* 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 .
- */
- typedef std::function< void(std::shared_ptr<SecProvisioningResult>) > EnrolleeSecStatusCb;
+ class PropertyData
+ {
+ public:
+ PropertyData()
+ {
+ }
- /**
- * Callback definition to be invoked when the security stack expects a pin from application.
- */
- typedef std::function< void(std::string&) > SecurityPinCb;
+ PropertyData(DeviceConfig devConfig, NetworkInfo netInfo, bool cloudable) :
+ m_devConfig(devConfig), m_netInfo(netInfo), m_cloudable(cloudable)
+ {
+ }
- /**
- * Callback definition to be invoked when the stack expects a db path.
- */
- typedef std::function< void(std::string&) > SecProvisioningDbPathCb;
+ const DeviceConfig& getDevConf() const
+ {
+ return m_devConfig;
+ }
+
+ const NetworkInfo& getNetInfo() const
+ {
+ return m_netInfo;
+ }
+
+ bool isCloudable() const
+ {
+ return m_cloudable;
+ }
+
+ private:
+ DeviceConfig m_devConfig;
+ NetworkInfo m_netInfo;
+ bool m_cloudable;
+ };
- class ProvisioningStatus
+ class RequestPropertyDataStatus
{
public:
- std::shared_ptr< ProvisioningStatus > shared_ptr;
- ProvisioningStatus(ESResult result, ESState esState) :
- m_result(result), m_esState(esState)
+ RequestPropertyDataStatus(ESResult result, const PropertyData& data) :
+ m_result(result), m_propertyData(data)
{
-
}
ESResult getESResult()
return m_result;
}
- ESState getESState()
+ const PropertyData& getPropertyData()
{
- return m_esState;
+ return m_propertyData;
}
+
private:
ESResult m_result;
- ESState m_esState;
+ PropertyData m_propertyData;
};
- class EasySetupStatus
+ class DataProvisioningStatus
{
public:
- std::shared_ptr< EasySetupStatus > shared_ptr;
- EasySetupStatus(const EasySetupState& easySetupState,
- const ProvConfig& provConfig) :
- m_easySetupState(easySetupState), m_ProvConfig(provConfig)
+ DataProvisioningStatus(ESResult result, ESDataProvState dataProvState) :
+ m_result(result), m_state(dataProvState)
{
+ }
+ ESResult getESResult()
+ {
+ return m_result;
}
- ProvConfig getProvConfig()
+ ESDataProvState getESDataProvState()
{
- return m_ProvConfig;
+ return m_state;
}
- EasySetupState getEasySetupState()
+ private:
+ ESResult m_result;
+ ESDataProvState m_state;
+ };
+
+ class CloudProvisioningStatus
+ {
+ public:
+ CloudProvisioningStatus(ESResult result, ESCloudProvState state) :
+ m_result(result), m_esCloudState(state)
{
- return m_easySetupState;
}
+
+ ESResult getESResult()
+ {
+ return m_result;
+ }
+
+ ESCloudProvState getESCloudState()
+ {
+ return m_esCloudState;
+ }
+
private:
- EasySetupState m_easySetupState;
- ProvConfig m_ProvConfig;
+ ESResult m_result;
+ ESCloudProvState m_esCloudState;
};
+
+ /**
+ * Callback function definition for providing Enrollee security status
+ */
+ typedef function< void(shared_ptr< RequestPropertyDataStatus >) > RequestPropertyDataStatusCb;
+
+ /**
+ * Callback function definition for providing Enrollee security status
+ */
+ typedef function< void(shared_ptr< DataProvisioningStatus >) > DataProvStatusCb;
+
+ /**
+ * Callback function definition for providing Enrollee security status
+ */
+ typedef function< void(shared_ptr< CloudProvisioningStatus >) > CloudProvStatusCb;
+
+ /**
+ * Callback function definition for providing Enrollee security 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
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.
*
* @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();
+
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;
static EasySetup *s_instance;
};
}
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#ifndef REMOTE_ENROLLEE_RESOURCE_H_
-#define REMOTE_ENROLLEE_RESOURCE_H_
+#ifndef ENROLLEE_RESOURCE_H_
+#define ENROLLEE_RESOURCE_H_
#include <mutex>
#include <memory>
/**
* This class contains the resource discovery methods.
*
- * @see RemoteEnrolleeResource
+ * @see EnrolleeResource
*/
- class RemoteEnrolleeResource
+ class EnrolleeResource
{
friend class EnrolleeSecurity;
public:
- typedef std::shared_ptr< RemoteEnrolleeResource > Ptr;
-
- typedef std::function< void(std::shared_ptr< ProvisioningStatus >) > ProvStatusCb;
/**
- * RemoteEnrolleeResource constructor
+ * EnrolleeResource constructor
*
* @param enrolleeNWProvInfo Provisioning information for the Enrollee
*
* @throw ESBadRequestException is thrown if the parameters are invalid
*/
- RemoteEnrolleeResource(const ProvConfig &enrolleeNWProvInfo,
- const WiFiOnboadingConnection &onboardingconn);
+ EnrolleeResource(std::shared_ptr< OC::OCResource > resource);
+ // EnrolleeResource(const DataProvInfo &enrolleeNWProvInfo,
+ // const WiFiOnboadingConnection &onboardingconn);
- ~RemoteEnrolleeResource() = default;
+ ~EnrolleeResource() = default;
/**
* Register provisioning status handler.
* @throws InvalidParameterException If callback is an empty function or null.
* @throws ESBadRequestException If registration is already completed.
*
- * @see ProvisioningStatus
+ * @see DataProvisioningStatus
*/
- void registerProvStatusCallback (ProvStatusCb provStatusCb);
+ void registerRequestPropertyDataStatusCallback (RequestPropertyDataStatusCb callback);
+ void registerProvStatusCallback (DataProvStatusCb callback);
- /**
- * 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();
+ void RequestPropertyData();
/**
* Function for provisioning of Remote Enrollee resource using the information provided.
*
* @throws InvalidParameterException If cb is empty.
*/
- void provisionEnrollee();
+ void provisionEnrollee(const DataProvInfo& dataProvInfo);
/**
* Function for unprovisioning of Remote Enrollee and bring to unprovisioned state
*/
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);
+ RequestPropertyDataStatusCb m_RequestPropertyDataStatusCb;
+ DataProvStatusCb m_dataProvStatusCb;
- void onDeviceDiscovered(std::shared_ptr<OC::OCResource> resource);
+ DataProvInfo m_dataProvInfo;
- void triggerNetworkConnection();
-
- void triggerNetworkConnectionCb(
- const HeaderOptions& headerOptions, const OCRepresentation& rep,
+ private:
+ void onRequestPropertyDataResponse(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+ const int eCode);
+ void checkProvInformationCb(const HeaderOptions& headerOptions, const OCRepresentation& rep,
const int eCode);
+ PropertyData parsePropertyDataFromRepresentation(const OCRepresentation& rep);
};
}
}
{
#define ENROLEE_SECURITY_TAG "ENROLEE_SECURITY"
- class RemoteEnrolleeResource;
+ class EnrolleeResource;
class OCSecureResource;
/**
class EnrolleeSecurity
{
public:
- EnrolleeSecurity(std::shared_ptr< RemoteEnrolleeResource > remoteEnrolleeResource,
+ EnrolleeSecurity(std::shared_ptr< EnrolleeResource > EnrolleeResource,
std::string secDbPath);
- ESResult registerCallbackHandler(EnrolleeSecStatusCb enrolleeSecStatusCb,
+ void registerCallbackHandler(SecurityProvStatusCb securityProvStatusCb,
SecurityPinCb securityPinCb, SecProvisioningDbPathCb secProvisioningDbPathCb);
- EasySetupState performOwnershipTransfer();
+ void performOwnershipTransfer();
+ void setTargetDevID(const std::string devID);
private:
- std::shared_ptr< RemoteEnrolleeResource > m_remoteEnrolleeResource;
- EnrolleeSecStatusCb m_enrolleeSecStatusCb;
+ std::shared_ptr< EnrolleeResource > m_EnrolleeResource;
+ SecurityProvStatusCb m_securityProvStatusCb;
SecurityPinCb m_securityPinCb;
SecProvisioningDbPathCb m_secProvisioningDbPathCb;
std::shared_ptr< OC::OCSecureResource > m_unownedDevice;
+ std::string m_deviceId;
+
EnrolleeSecState m_enrolleeSecState;std::shared_ptr< OC::OCSecureResource > m_securedResource;
std::shared_ptr< OC::OCSecureResource > getEnrollee(OC::DeviceList_t &list);
#ifndef REMOTE_ENROLLEE_H_
#define REMOTE_ENROLLEE_H_
+#include <memory>
+
#include "ESRichCommon.h"
+#include "OCApi.h"
+
+using namespace OC;
namespace OIC
{
namespace Service
{
- class RemoteEnrolleeResource;
+ class OCResource;
+ class EnrolleeResource;
+ class CloudResource;
class EnrolleeSecurity;
/**
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.
- *
- * @param callback Callback to get EasySetup status.
- * @param secProvisioningDbCB Callback to be invoked when the stack expects a
- * path for the provisioning db.
+ * Start provisioning of target Enrollers information to the Enrollee.
*
- * @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 RemoteEnrollee
*/
- void registerEasySetupStatusHandler(EasySetupStatusCB callback);
+ void initRemoteEnrollee();
/**
* Start provisioning of target Enrollers information to the Enrollee.
*
* @see RemoteEnrollee
*/
- void startProvisioning();
+ void requestPropertyData(RequestPropertyDataStatusCb callback);
- /**
- * Stop provisioning process that is currently in progress.
+ /**
+ * Start provisioning of target Enrollers information to the Enrollee.
*
- * @throws BadRequestException If provisioning is not in progress.
+ * @throws ESBadRequestException If RemoteEnrollee device not created prior to this call.
+ *
+ * @see RemoteEnrollee
*/
- void stopProvisioning();
+ void startSecurityProvisioning(SecurityProvStatusCb callback);
/**
- * Check if the Enrollee device provisioned.
+ * Start provisioning of target Enrollers information to the Enrollee.
+ *
+ * @throws ESBadRequestException If RemoteEnrollee device not created prior to this call.
+ *
+ * @see RemoteEnrollee
*/
- bool isEnrolleeProvisioned();
+ void startDataProvisioning(DataProvStatusCb callback);
/**
- * Get the Provisioning information provided for the current Enrollee.
+ * Start provisioning of target Enrollers information to the Enrollee.
+ *
+ * @throws ESBadRequestException If RemoteEnrollee device not created prior to this call.
*
- * @return ProvConfig Provisioning information provided for the current Enrollee.
+ * @see RemoteEnrollee
*/
- ProvConfig getProvConfig ();
+ void startCloudProvisioning(CloudProvStatusCb callback);
/**
- * Get the Onboarding connection information between Mediator and Enrollee.
+ * Get the Provisioning information provided for the current Enrollee.
*
- * @return WiFiOnboadingConnection information between Mediator and Enrollee.
+ * @return DataProvInfo Provisioning information provided for the current Enrollee.
*/
+ DataProvInfo getDataProvInfo();
+
+ void setDataProvInfo(const DataProvInfo& );
+ void setCloudProvInfo(const CloudProvInfo& );
+
+ private:
+ RemoteEnrollee();
- WiFiOnboadingConnection getOnboardConn();
+ ESResult discoverResource();
+ ESResult ESDiscoveryTimeout(unsigned short waittime);
+ void onDeviceDiscovered(std::shared_ptr<OC::OCResource> resource);
+ void initCloudResource();
+
+ void RequestPropertyDataStatusHandler (std::shared_ptr< RequestPropertyDataStatus > status);
+ void dataProvisioningStatusHandler (std::shared_ptr< DataProvisioningStatus > status);
+ void cloudProvisioningStatusHandler (std::shared_ptr< CloudProvisioningStatus > 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;
+
+ SecurityProvStatusCb m_securityProvStatusCb;
+ RequestPropertyDataStatusCb m_requestPropertyDataStatusCb;
SecurityPinCb m_securityPinCb;
SecProvisioningDbPathCb m_secProvisioningDbPathCb;
- ProvConfig m_ProvConfig;
- WiFiOnboadingConnection m_wifiOnboardingconn;
+ DataProvStatusCb m_dataProvStatusCb;
+ CloudProvStatusCb m_cloudProvStatusCb;
- std::shared_ptr< EnrolleeSecurity > m_enrolleeSecurity;
- CurrentESState m_currentESState;
- bool m_isSecured;
+ DataProvInfo m_dataProvInfo;
+ CloudProvInfo m_cloudProvInfo;
+ PropertyData m_propertyData;
- 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#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 CloudProvInfo& cloudProvInfo)
+ {
+ OIC_LOG_V (DEBUG, ES_CLOUD_RES_TAG, "Enter provisionEnrollee.");
+
+ OCRepresentation provisioningRepresentation;
+
+ provisioningRepresentation.setValue(OC_RSRVD_ES_AUTHCODE, cloudProvInfo.authCode);
+ provisioningRepresentation.setValue(OC_RSRVD_ES_AUTHPROVIDER, cloudProvInfo.authProvider);
+ provisioningRepresentation.setValue(OC_RSRVD_ES_CISERVER, cloudProvInfo.ciServer);
+
+ OIC_LOG_V (DEBUG, ES_CLOUD_RES_TAG, "provisionEnrollee : authCode - %s",
+ (cloudProvInfo.authCode).c_str());
+ OIC_LOG_V (DEBUG, ES_CLOUD_RES_TAG, "provisionEnrollee : authProvider - %s",
+ (cloudProvInfo.authProvider).c_str());
+ OIC_LOG_V (DEBUG, ES_CLOUD_RES_TAG, "provisionEnrollee : ciServer - %s",
+ (cloudProvInfo.ciServer).c_str());
+
+ 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 != 0)
+ {
+ 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< CloudProvisioningStatus > provStatus = std::make_shared<
+ CloudProvisioningStatus >(result, ESCloudProvState::ES_CLOUD_PROVISIONING_ERROR);
+ m_cloudProvStatusCb(provStatus);
+ }
+ else
+ {
+ OIC_LOG(DEBUG, ES_CLOUD_RES_TAG,"onCloudProvResponse : onCloudProvResponse is success");
+ std::shared_ptr< CloudProvisioningStatus > provStatus = std::make_shared<
+ CloudProvisioningStatus >(ESResult::ES_OK, ESCloudProvState::ES_CLOUD_PROVISIONING_SUCCESS);
+ m_cloudProvStatusCb(provStatus);
+ }
+ }
+
+ void CloudResource::registerCloudProvisioningStatusCallback(CloudProvStatusCb callback)
+ {
+ OIC_LOG_V (DEBUG, ES_CLOUD_RES_TAG, "Enter registerCloudProvisioningStatusCallback");
+ m_cloudProvStatusCb = callback;
+ }
+ }
+}
return s_instance;
}
- RemoteEnrollee::shared_ptr EasySetup::findDeviceInProvisioningList (
- const ProvConfig& provConfig, const WiFiOnboadingConnection& onboardingconn)
+ std::shared_ptr<RemoteEnrollee> EasySetup::createRemoteEnrollee ()
{
- 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)
- {
- ProvConfig remoteEnrolleConfig = remoteEnrollee->getProvConfig();
- WiFiOnboadingConnection remoteEnrolleConn = remoteEnrollee->getOnboardConn();
-
- for (auto it : m_activeEnrolleeList)
- {
- 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)))
- )
- {
- return false;
- }
- }
-
- OIC_LOG_V(DEBUG,EASYSETUP_TAG,"Adding new device RemoteEnrollee list");
- m_activeEnrolleeList.push_back(remoteEnrollee);
- return true;
+ return std::shared_ptr< RemoteEnrollee > (new RemoteEnrollee());
}
-
- 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;
- }
-
-
}
}
--- /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 != 0)
+ {
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
+ "checkProvInformationCb : Provisioning is failed ");
+ std::shared_ptr< DataProvisioningStatus > provStatus = std::make_shared<
+ DataProvisioningStatus >(ESResult::ES_ERROR, ESDataProvState::ES_PROVISIONING_ERROR);
+ m_dataProvStatusCb(provStatus);
+ return;
+ }
+
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
+ "checkProvInformationCb : Provisioning is success. ");
+
+ std::shared_ptr< DataProvisioningStatus > provStatus = std::make_shared<
+ DataProvisioningStatus >(ESResult::ES_OK, ESDataProvState::ES_PROVISIONING_SUCCESS);
+ m_dataProvStatusCb(provStatus);
+ }
+
+ void EnrolleeResource::onRequestPropertyDataResponse(const HeaderOptions& /*headerOptions*/,
+ const OCRepresentation& rep, const int eCode)
+ {
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "onRequestPropertyDataResponse : %s, eCode = %d",
+ rep.getUri().c_str(), eCode);
+
+ if (eCode != 0)
+ {
+ ESResult result = ESResult::ES_ERROR;
+
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,"onRequestPropertyDataResponse : onRequestPropertyDataResponse 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;
+ }
+
+ PropertyData propertyData;
+ std::shared_ptr< RequestPropertyDataStatus > requestPropertyDataStatus = std::make_shared<
+ RequestPropertyDataStatus >(result, propertyData );
+ m_RequestPropertyDataStatusCb(requestPropertyDataStatus);
+ }
+ else
+ {
+ PropertyData propertyData = parsePropertyDataFromRepresentation(rep);
+
+ std::shared_ptr< RequestPropertyDataStatus > requestPropertyDataStatus = std::make_shared<
+ RequestPropertyDataStatus >(ESResult::ES_OK, propertyData);
+ m_RequestPropertyDataStatusCb(requestPropertyDataStatus);
+ }
+ }
+
+ void EnrolleeResource::registerRequestPropertyDataStatusCallback(RequestPropertyDataStatusCb callback)
+ {
+ m_RequestPropertyDataStatusCb = callback;
+ }
+
+ void EnrolleeResource::registerProvStatusCallback(DataProvStatusCb callback)
+ {
+ m_dataProvStatusCb = callback;
+ }
+
+ void EnrolleeResource::RequestPropertyData()
+ {
+ if (m_ocResource == nullptr)
+ {
+ throw ESBadRequestException("Resource is not initialized");
+ }
+
+ OC::QueryParamsMap query;
+ OC::OCRepresentation rep;
+
+ std::function< OCStackResult(void) > requestPropertyDataStatus = [&]
+ { 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::onRequestPropertyDataResponse, this,
+ std::placeholders::_1, std::placeholders::_2,
+ std::placeholders::_3)));
+ };
+
+ OCStackResult result = requestPropertyDataStatus();
+
+ if (result != OCStackResult::OC_STACK_OK)
+ {
+ PropertyData propertyData;
+ std::shared_ptr< RequestPropertyDataStatus > requestPropertyDataStatus = std::make_shared<
+ RequestPropertyDataStatus >(ESResult::ES_ERROR, propertyData);
+ m_RequestPropertyDataStatusCb(requestPropertyDataStatus);
+ return;
+ }
+ }
+
+ void EnrolleeResource::provisionEnrollee(const DataProvInfo& dataProvInfo)
+
+ {
+ if (m_ocResource == nullptr)
+ {
+ throw ESBadRequestException("Resource is not initialized");
+ }
+
+ m_dataProvInfo = dataProvInfo;
+
+ OC::QueryParamsMap query;
+ OC::OCRepresentation provisioningRepresentation;
+
+ provisioningRepresentation.setValue(OC_RSRVD_ES_SSID, m_dataProvInfo.WIFI.ssid);
+ provisioningRepresentation.setValue(OC_RSRVD_ES_CRED, m_dataProvInfo.WIFI.pwd);
+ provisioningRepresentation.setValue(OC_RSRVD_ES_AUTHTYPE, m_dataProvInfo.WIFI.authtype);
+ provisioningRepresentation.setValue(OC_RSRVD_ES_ENCTYPE, m_dataProvInfo.WIFI.enctype);
+ provisioningRepresentation.setValue(OC_RSRVD_ES_LANGUAGE, m_dataProvInfo.Device.language);
+ provisioningRepresentation.setValue(OC_RSRVD_ES_COUNTRY, m_dataProvInfo.Device.country);
+
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "getProvStatusResponse : ssid - %s",
+ (m_dataProvInfo.WIFI.ssid).c_str());
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "getProvStatusResponse : pwd - %s",
+ (m_dataProvInfo.WIFI.pwd).c_str());
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "getProvStatusResponse : authtype - %d",
+ m_dataProvInfo.WIFI.authtype);
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "getProvStatusResponse : enctype - %d",
+ m_dataProvInfo.WIFI.enctype);
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "getProvStatusResponse : language - %s",
+ (m_dataProvInfo.Device.language).c_str());
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "getProvStatusResponse : country - %s",
+ (m_dataProvInfo.Device.country).c_str());
+
+ 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)));
+ }
+
+ void EnrolleeResource::unprovisionEnrollee()
+ {
+ if (m_ocResource == nullptr)
+ {
+ throw ESBadRequestException("Resource is not initialized");
+ }
+
+ OCRepresentation provisioningRepresentation;
+
+ provisioningRepresentation.setValue(OC_RSRVD_ES_SSID, "");
+ provisioningRepresentation.setValue(OC_RSRVD_ES_CRED, "");
+
+ m_ocResource->post(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)));
+ }
+
+ PropertyData EnrolleeResource::parsePropertyDataFromRepresentation(const OCRepresentation& rep)
+ {
+ OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_RES_TAG, "Enter parsePropertyDataFromRepresentation");
+
+ DeviceConfig devInfo;
+ NetworkInfo netInfo;
+ bool cloudable = false;
+
+ std::vector<OCRepresentation> children = rep.getChildren();
+
+ for(auto prop = children.begin(); prop != children.end(); ++prop)
+ {
+ if(prop->getUri().find(OC_RSRVD_ES_URI_WIFI) != std::string::npos)
+ {
+ OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_RES_TAG, "Find wifi resource");
+ if(prop->hasAttribute(OC_RSRVD_ES_SUPPORTEDWIFIMODE)
+ && prop->hasAttribute(OC_RSRVD_ES_SUPPORTEDWIFIFREQ))
+ {
+ std::vector<int> types = prop->getValue<std::vector<int>>(OC_RSRVD_ES_SUPPORTEDWIFIMODE);
+
+ for(auto type = types.begin(); type != types.end(); ++type)
+ {
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "OC_RSRVD_ES_SUPPORTEDWIFIMODE = %d",
+ *type);
+ netInfo.types.push_back(static_cast<WIFI_MODE>(*type));
+ }
+
+ netInfo.freq = static_cast<WIFI_FREQ>(prop->getValue<int>(OC_RSRVD_ES_SUPPORTEDWIFIFREQ));
+
+
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "OC_RSRVD_ES_SUPPORTEDWIFIFREQ = %d",
+ netInfo.freq);
+ }
+ }
+
+ else if(prop->getUri().find(OC_RSRVD_ES_URI_DEVCONF) != std::string::npos)
+ {
+ OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_RES_TAG, "Find devconf");
+ if(prop->hasAttribute(OC_RSRVD_ES_DEVNAME)
+ && prop->hasAttribute(OC_RSRVD_ES_LANGUAGE)
+ && prop->hasAttribute(OC_RSRVD_ES_COUNTRY))
+ {
+ //TODO:: setting DeviceID.
+ //devInfo.id = devId;
+ devInfo.name = prop->getValue<std::string>(OC_RSRVD_ES_DEVNAME);
+ devInfo.language = prop->getValue<std::string>(OC_RSRVD_ES_LANGUAGE);
+ devInfo.country = prop->getValue<std::string>(OC_RSRVD_ES_COUNTRY);
+
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "OC_RSRVD_ES_DEVNAME = %s",
+ devInfo.name.c_str());
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "OC_RSRVD_ES_LANGUAGE = %s",
+ devInfo.language.c_str());
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "OC_RSRVD_ES_COUNTRY = %s",
+ devInfo.country.c_str());
+ }
+ }
+
+ else if(prop->getUri().find(OC_RSRVD_ES_URI_CLOUDSERVER) != std::string::npos)
+ {
+ OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_RES_TAG, "Find cloudserver");
+ cloudable = true;
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "cloudable = %d",
+ cloudable);
+ }
+ }
+
+ return PropertyData(devInfo, netInfo, cloudable);
+ }
+
+ }
+}
#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"
#define ES_SEC_DISCOVERY_TIMEOUT 5
EnrolleeSecurity::EnrolleeSecurity(
- std::shared_ptr< RemoteEnrolleeResource > remoteEnrolleeResource,
+ std::shared_ptr< EnrolleeResource > EnrolleeResource,
std::string secDbPath)
{
m_enrolleeSecState = EnrolleeSecState::ES_SEC_UNKNOWN;
- m_remoteEnrolleeResource = remoteEnrolleeResource;
+ m_EnrolleeResource = EnrolleeResource;
}
- 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());
-
+ if(m_deviceId == 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];
+ }
//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];
+
}
OIC_LOG(ERROR, ENROLEE_SECURITY_TAG,"Error!!! DeviceList_t is NULL");
return NULL;
{
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::setTargetDevID(const std::string devID)
{
- EasySetupState ownershipStatus = DEVICE_NOT_OWNED;
+ m_deviceId = devID;
+ }
+ void EnrolleeSecurity::performOwnershipTransfer()
+ {
OC::DeviceList_t pUnownedDevList, pOwnedDevList;
pOwnedDevList.clear();
pUnownedDevList.clear();
OCStackResult result;
-
- //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 unSecure devices found.");
- ownershipStatus = DEVICE_NOT_OWNED;
-
- return ownershipStatus;
+ OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "No unOwned devices found.");
+ throw ESException("No unOwned devices found.");
}
-
- return ownershipStatus;
}
}
}
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#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"
#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()
+ {
+ m_securityProvStatusCb = nullptr;
+ m_requestPropertyDataStatusCb = nullptr;
+ m_securityPinCb = nullptr;
+ m_secProvisioningDbPathCb = nullptr;
+ m_dataProvStatusCb = nullptr;
+ m_cloudProvStatusCb = nullptr;
+
+ //m_deviceId = nullptr;
}
#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::RequestPropertyDataStatusHandler (
+ std::shared_ptr< RequestPropertyDataStatus > 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 RequestPropertyDataStatusHandler");
+
+ OIC_LOG_V(DEBUG,ES_REMOTE_ENROLLEE_TAG,"RequestPropertyDataStatus = %d", status->getESResult());
- if(secProvisioningResult->getResult() == ES_OK)
+ if(status->getESResult() == ES_OK)
{
- OIC_LOG(DEBUG, ES_REMOTE_ENROLLEE_TAG, "Ownership and ACL are successful. "
- "Continue with Network information provisioning");
+ m_propertyData = status->getPropertyData();
+ }
- m_currentESState = CurrentESState::ES_OWNED;
+ m_requestPropertyDataStatusCb(status);
+ }
- OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Before ProvisionEnrollee");
+ void RemoteEnrollee::dataProvisioningStatusHandler(
+ std::shared_ptr< DataProvisioningStatus > status)
+ {
+ OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Entering dataProvisioningStatusHandler");
- RemoteEnrolleeResource::ProvStatusCb provStatusCb = std::bind(
- &RemoteEnrollee::provisioningStatusHandler, this, std::placeholders::_1);
+ OIC_LOG_V(DEBUG,ES_REMOTE_ENROLLEE_TAG,"ProvStatus = %d", status->getESResult());
- m_remoteResource->registerProvStatusCallback(provStatusCb);
- m_remoteResource->provisionEnrollee();
- }
- else
+ if (status->getESResult() == ES_OK)
{
- 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 (status->getESDataProvState() >= ESDataProvState::ES_PROVISIONED_ALREADY)
{
- if (easySetupStatus)
- {
- m_easySetupStatusCb(easySetupStatus);
- }
- else
- {
- m_easySetupStatusCb(nullptr);
- }
+ OIC_LOG_V(DEBUG,ES_REMOTE_ENROLLEE_TAG,"ProvStatus = %d", status->getESResult());
}
}
+ m_dataProvStatusCb(status);
+
+ return;
}
- void RemoteEnrollee::provisioningStatusHandler(
- std::shared_ptr< ProvisioningStatus > provStatus)
+ void RemoteEnrollee::cloudProvisioningStatusHandler (
+ std::shared_ptr< CloudProvisioningStatus > status)
{
- OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Entering ProvisioningStatusHandler");
+ OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Entering cloudProvisioningStatusHandler");
+
+ OIC_LOG_V(DEBUG,ES_REMOTE_ENROLLEE_TAG,"CloudProvStatus = %d", status->getESCloudState());
- OIC_LOG_V(DEBUG,ES_REMOTE_ENROLLEE_TAG,"ProvStatus = %d", provStatus->getESResult());
+ m_cloudProvStatusCb(status);
+ return;
+ }
- std::shared_ptr< EasySetupStatus > easySetupStatus = nullptr;
+ ESResult RemoteEnrollee::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;
+ }
- if (m_isSecured)
+ while (ES_OK == res || m_discoveryResponse == false)
{
- if (m_currentESState >= CurrentESState::ES_OWNED)
+ #ifdef _POSIX_MONOTONIC_CLOCK
+ clock_res = clock_gettime(CLOCK_MONOTONIC, &currTime);
+ #else
+ clock_res = clock_gettime(CLOCK_REALTIME, &currTime);
+ #endif
+
+ if (0 != clock_res)
{
- goto CALLBACK_CHECK;
+ return ES_ERROR;
}
- else
+ long elapsed = (currTime.tv_sec - startTime.tv_sec);
+ if (elapsed > waittime)
+ {
+ return ES_OK;
+ }
+ if (m_discoveryResponse)
+ {
+ res = ES_OK;
+ }
+ }
+ return res;
+ }
+
+ 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
+ {
+ if(resource)
{
- goto FAILURE;
+ if(!(resource->connectivityType() & CT_ADAPTER_TCP))
+ {
+ // 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())
+ {
+ /*
+ * 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_deviceId = resource->sid();
+ m_discoveryResponse = true;
+ }
+
+ else if(!m_deviceId.empty() && m_deviceId == hostDeviceID)
+ {
+ OIC_LOG (DEBUG, ES_REMOTE_ENROLLEE_TAG, "Find matched CloudResource");
+ m_ocResource = resource;
+ m_discoveryResponse = true;
+ }
+ }
}
}
- else
+ catch(std::exception& e)
{
- goto CALLBACK_CHECK;
+ OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_TAG,
+ "Exception in foundResource: %s", e.what());
}
+ }
- CALLBACK_CHECK:
+ ESResult RemoteEnrollee::discoverResource()
+ {
+ OIC_LOG(DEBUG, ES_REMOTE_ENROLLEE_TAG, "Enter discoverResource");
- if (provStatus->getESResult() == ES_OK)
+ if (m_ocResource != nullptr)
{
- 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);
- }
+ throw ESBadRequestException("resource is already created");
}
- else
+
+ 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());
+
+ m_discoveryResponse = false;
+
+ 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 (result != OCStackResult::OC_STACK_OK)
+ {
+ OIC_LOG(ERROR,ES_REMOTE_ENROLLEE_TAG,
+ "Failed discoverResource");
+ return ES_ERROR;
+ }
+
+ ESResult foundResponse = ESDiscoveryTimeout (DISCOVERY_TIMEOUT);
+
+ if (foundResponse == ES_ERROR || !m_discoveryResponse)
+ {
+ OIC_LOG(ERROR,ES_REMOTE_ENROLLEE_TAG,
+ "Failed discoverResource because timeout");
+ return ES_ERROR;
+ }
+ return ES_OK;
+ }
+
+ void RemoteEnrollee::initRemoteEnrollee()
+ {
+ ESResult result = ES_ERROR;
+
+ if (m_enrolleeResource != nullptr)
+ {
+ throw ESBadRequestException ("Already created");
+ }
+
+ result = discoverResource();
+
+ if (result == ES_ERROR)
{
- easySetupStatus = std::make_shared< EasySetupStatus >(DEVICE_NOT_PROVISIONED,
- m_ProvConfig);
+ OIC_LOG(ERROR,ES_REMOTE_ENROLLEE_TAG,
+ "Failed to create resource object using discoverResource");
+ throw ESBadRequestException ("Resource object not created");
}
- if (m_easySetupStatusCb)
+ else
{
- if (easySetupStatus)
+ if(m_ocResource != nullptr)
{
- m_easySetupStatusCb(easySetupStatus);
+ m_enrolleeResource = std::make_shared<EnrolleeResource>(std::move(m_ocResource));
}
else
{
- m_easySetupStatusCb(nullptr);
+ throw ESBadGetException ("Resource handle is invalid");
}
}
+ }
- return;
+ void RemoteEnrollee::startSecurityProvisioning(SecurityProvStatusCb callback)
+ {
+#ifdef __WITH_DTLS__
+ m_securityProvStatusCb = callback;
- FAILURE:
+ 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_enrolleeResource, "");
- easySetupStatus = std::make_shared< EasySetupStatus >(DEVICE_NOT_PROVISIONED,
- m_ProvConfig);
+ m_enrolleeSecurity->setTargetDevID(m_deviceId);
+ m_enrolleeSecurity->registerCallbackHandler(securityProvStatusCb, m_securityPinCb, m_secProvisioningDbPathCb);
- if (easySetupStatus)
+ try
{
- m_easySetupStatusCb(easySetupStatus);
+ m_enrolleeSecurity->performOwnershipTransfer();
}
- else
+ catch (OCException & e)
{
- m_easySetupStatusCb(nullptr);
+ OIC_LOG_V(ERROR, ES_REMOTE_ENROLLEE_TAG,
+ "Exception for performOwnershipTransfer : %s", e.reason().c_str());
+
+ OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Fail performOwnershipTransfer");
+ std::shared_ptr< SecProvisioningStatus > securityProvisioningStatus =
+ std::make_shared< SecProvisioningStatus >(nullptr, ES_ERROR);
+ m_securityProvStatusCb(securityProvisioningStatus);
+ return ;
}
- return;
+#else
+ (void) callback;
+ OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Mediator is unsecured.");
+
+ std::shared_ptr< SecProvisioningStatus > securityProvisioningStatus =
+ std::make_shared< SecProvisioningStatus >(nullptr, ES_ERROR);
+ m_securityProvStatusCb(securityProvisioningStatus);
+#endif
}
- void RemoteEnrollee::startProvisioning()
+ void RemoteEnrollee::requestPropertyData(RequestPropertyDataStatusCb callback)
{
- OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Entering startProvisioning");
- if (m_remoteResource == nullptr)
+ if(!callback)
+ {
+ throw ESInvalidParameterException("Callback is empty");
+ }
+
+ m_requestPropertyDataStatusCb = callback;
+
+ if (m_enrolleeResource == nullptr)
{
throw ESBadRequestException ("Device not created");
}
- ESResult result = ES_ERROR;
+ RequestPropertyDataStatusCb RequestPropertyDataStatusCb = std::bind(
+ &RemoteEnrollee::RequestPropertyDataStatusHandler, this, std::placeholders::_1);
+ m_enrolleeResource->registerRequestPropertyDataStatusCallback(RequestPropertyDataStatusCb);
+ m_enrolleeResource->RequestPropertyData();
+ }
- result = m_remoteResource->constructResourceObject();
+ void RemoteEnrollee::startDataProvisioning(DataProvStatusCb callback)
+ {
+ OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Enter startDataProvisioning");
- if (result == ES_ERROR)
+ if(!callback)
+ {
+ throw ESInvalidParameterException("Callback is empty");
+ }
+
+ m_dataProvStatusCb = callback;
+
+ if (m_enrolleeResource == nullptr)
{
- OIC_LOG(ERROR,ES_REMOTE_ENROLLEE_TAG,
- "Failed to create device using constructResourceObject");
throw ESBadRequestException ("Device not created");
}
- m_currentESState = CurrentESState::ES_ONBOARDED;
+ if(m_dataProvInfo.WIFI.ssid.empty())
+ {
+ throw ESBadRequestException ("Invalid Provisiong Data.");
+ }
-#ifdef __WITH_DTLS__
- if (m_isSecured && m_currentESState < CurrentESState::ES_OWNED)
+ m_dataProvStatusCb = callback;
+
+ DataProvStatusCb dataProvStatusCb = std::bind(
+ &RemoteEnrollee::dataProvisioningStatusHandler, this, std::placeholders::_1);
+
+ m_enrolleeResource->registerProvStatusCallback(dataProvStatusCb);
+ m_enrolleeResource->provisionEnrollee(m_dataProvInfo);
+ }
+
+ void RemoteEnrollee::initCloudResource()
+ {
+ ESResult result = ES_ERROR;
+
+ if (m_cloudResource != nullptr)
{
- 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, "");
+ throw ESBadRequestException ("Already created");
+ }
+
+ result = discoverResource();
- m_enrolleeSecurity->registerCallbackHandler(securityProvStatusCb,
- m_securityPinCb, m_secProvisioningDbPathCb);
+ if (result == ES_ERROR)
+ {
+ OIC_LOG(ERROR,ES_REMOTE_ENROLLEE_TAG,
+ "Failed to create resource object using discoverResource");
+ throw ESBadRequestException ("Resource object not created");
+ }
- try
+ else
+ {
+ 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>(std::move(m_ocResource));
- RemoteEnrolleeResource::ProvStatusCb provStatusCb = std::bind(
- &RemoteEnrollee::provisioningStatusHandler,
- this, std::placeholders::_1);
+ std::shared_ptr< CloudProvisioningStatus > provStatus = std::make_shared<
+ CloudProvisioningStatus >(ESResult::ES_OK, ESCloudProvState::ES_CLOUD_ENROLLEE_FOUND);
- m_remoteResource->registerProvStatusCallback(provStatusCb);
- m_remoteResource->provisionEnrollee();
- }
+ m_cloudProvStatusCb(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::startCloudProvisioning(CloudProvStatusCb callback)
{
- m_currentESState = CurrentESState::ES_UNKNOWN;
+ OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Enter startCloudProvisioning");
- m_remoteResource->unprovisionEnrollee();
- }
+ if(!callback)
+ {
+ throw ESInvalidParameterException("Callback is empty");
+ }
- bool RemoteEnrollee::isEnrolleeProvisioned()
- {
- if(m_currentESState >= CurrentESState::ES_PROVISIONED)
+ m_cloudProvStatusCb = callback;
+
+ try
{
- return true;
+ initCloudResource();
}
- else
+
+ catch (const std::exception& e)
+ {
+ OIC_LOG_V(ERROR, ES_REMOTE_ENROLLEE_TAG,
+ "Exception caught in startCloudProvisioning = %s", e.what());
+
+ std::shared_ptr< CloudProvisioningStatus > provStatus = std::make_shared<
+ CloudProvisioningStatus >(ESResult::ES_ERROR, ESCloudProvState::ES_CLOUD_ENROLLEE_NOT_FOUND);
+ m_cloudProvStatusCb(provStatus);
+ }
+
+ if (m_cloudResource == nullptr)
{
- return false;
+ throw ESBadRequestException ("Cloud Resource not created");
}
+
+ if(m_cloudProvInfo.authCode.empty()
+ || m_cloudProvInfo.authProvider.empty()
+ || m_cloudProvInfo.ciServer.empty())
+ {
+ throw ESBadRequestException ("Invalid Cloud Provisiong Info.");
+ }
+
+ CloudProvStatusCb cloudProvStatusCb = std::bind(
+ &RemoteEnrollee::cloudProvisioningStatusHandler, this, std::placeholders::_1);
+
+ m_cloudResource->registerCloudProvisioningStatusCallback(cloudProvStatusCb);
+ m_cloudResource->provisionEnrollee(m_cloudProvInfo);
}
- ProvConfig RemoteEnrollee::getProvConfig ()
+ void RemoteEnrollee::setDataProvInfo(const DataProvInfo& dataProvInfo)
{
- return m_ProvConfig;
+ m_dataProvInfo = dataProvInfo;
}
- WiFiOnboadingConnection RemoteEnrollee::getOnboardConn()
- {
- return m_wifiOnboardingconn;
- }
+ void RemoteEnrollee::setCloudProvInfo(const CloudProvInfo& cloudProvInfo)
+ {
+ m_cloudProvInfo = cloudProvInfo;
+ }
+ DataProvInfo RemoteEnrollee::getDataProvInfo()
+ {
+ return m_dataProvInfo;
+ }
}
}
+++ /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)));
- }
- }
-}
#include <string.h>
#include <stdio.h>
#include <pthread.h>
+#include <oic_string.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
{
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("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->ssid != 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("SSID : %s\n", eventData->ssid);
}
else
{
- printf("Easy stup is failed at Enrollee state = %d\n",enrolleeState);;
+ printf("ERROR! SSID IS NULL\n");
+ return;
}
- PrintMenu();
+ if(eventData->pwd != NULL)
+ {
+ printf("Password : %s\n", eventData->pwd);
+ }
+ else
+ {
+ printf("ERROR! Password IS NULL\n");
+ return;
+ }
+
+ if(eventData->authtype == NONE_AUTH || eventData->authtype == WEP || \
+ eventData->authtype == WPA_PSK || eventData->authtype == WPA2_PSK)
+ {
+ printf("AuthType : %d\n", eventData->authtype);
+ }
+ else
+ {
+ printf("ERROR! AuthType IS NULL\n");
+ return;
+ }
+
+ if(eventData->enctype == NONE_ENC || eventData->enctype == WEP_64 || \
+ eventData->enctype == WEP_128 || eventData->enctype == TKIP || \
+ eventData->enctype == AES || eventData->enctype == TKIP_AES)
+ {
+ printf("EncType : %d\n", eventData->enctype);
+ }
+ else
+ {
+ printf("ERROR! EncType IS NULL\n");
+ return;
+ }
+
+ printf("WiFiProvCbInApp OUT\n");
}
+void DevConfProvCbInApp(ESDevConfProvData *eventData)
+{
+ printf("DevConfProvCbInApp IN\n");
+
+ if(eventData->language != NULL)
+ {
+ printf("Language : %s\n", eventData->language);
+ }
+ else
+ {
+ printf("ERROR! Language IS NULL\n");
+ return;
+ }
+
+ if(eventData->country != NULL)
+ {
+ printf("Country : %s\n", eventData->country);
+ }
+ else
+ {
+ printf("ERROR! Country IS NULL\n");
+ return;
+ }
+
+ printf("DevConfProvCbInApp OUT\n");
+}
+
+void CloudDataProvCbInApp(ESCloudProvData *eventData)
+{
+ printf("CloudDataProvCbInApp IN\n");
+
+ if(eventData->authCode != NULL)
+ {
+ printf("AuthCode : %s\n", eventData->authCode);
+ }
+ else
+ {
+ printf("ERROR! AuthCode IS NULL\n");
+ return;
+ }
+
+ if(eventData->authProvider != NULL)
+ {
+ printf("AuthProvider : %s\n", eventData->authProvider);
+ }
+ else
+ {
+ printf("ERROR! AuthProvider IS NULL\n");
+ return;
+ }
+
+ if(eventData->ciServer != NULL)
+ {
+ printf("CI Server : %s\n", eventData->ciServer);
+ }
+ else
+ {
+ printf("ERROR! CI Server IS NULL\n");
+ return;
+ }
+
+ 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;
- }
-}
+ printf("StartEasySetup IN\n");
-void ESInitResources()
-{
- printf("Starting Enrollee Provisioning\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;
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"}
+ } ;
+
+ if(ESSetDeviceProperty(&deviceProperty) == ES_ERROR)
+ printf("ESSetDeviceProperty Error\n");
+
+ printf("SetDeviceInfo OUT\n");
}
void StopEasySetup()
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;
default:
printf("wrong option\n");
+ PrintMenu();
break;
}
if (option == 'Q' || option == 'q') break;
return 0;
}
-void *listeningFunc(void * a)
+void *listeningFunc(void * data)
{
OCStackResult result;
<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:label="@string/app_name">
-
+ <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" />
+ <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.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.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 org.iotivity.service.easysetup.mediator.CloudProvInfo;
+import org.iotivity.service.easysetup.mediator.CloudProvisioningCallback;
+import org.iotivity.service.easysetup.mediator.CloudProvisioningStatus;
+import org.iotivity.service.easysetup.mediator.DataProvInfo;
+import org.iotivity.service.easysetup.mediator.DataProvisioningCallback;
+import org.iotivity.service.easysetup.mediator.DataProvisioningStatus;
+import org.iotivity.service.easysetup.mediator.DeviceConfig;
+import org.iotivity.service.easysetup.mediator.ESException;
+import org.iotivity.service.easysetup.mediator.EasySetup;
+import org.iotivity.service.easysetup.mediator.NetworkInfo;
+import org.iotivity.service.easysetup.mediator.PropertyData;
+import org.iotivity.service.easysetup.mediator.RemoteEnrollee;
+import org.iotivity.service.easysetup.mediator.RequestPropertyDataCallback;
+import org.iotivity.service.easysetup.mediator.RequestPropertyDataStatus;
+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;
+
+
+public class EasysetupActivity extends Activity {
+ private static final String TAG = "Easysetup Mediator: ";
+ PlatformConfig cfg;
+
+ 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 isSecurityEnabled = false;
+
+ ToggleButton mSecurityMode;
+
+ RadioGroup mEasysetupProcess;
+ RadioButton mSecProvProcess;
+ RadioButton mReqPropertyDataProcess;
+ RadioButton mDataProvProcess;
+ RadioButton mCloudProvProcess;
+
+ Button mInitRemoteEnrollee;
+ Button mStartRequsetPropertyData;
+ Button mStartSecProvisioning;
+ Button mStartDataProvisioning;
+ Button mStartCloudProvisioning;
+
+ TextView mRequesetPropertyDataStateText;
+ TextView mDevIDText;
+ TextView mDevNameText;
+ TextView mLanguageText;
+ TextView mCountryText;
+ TextView mWifiModeText;
+ TextView mWifiFreqText;
+ TextView mCloudAccessableText;
+ TextView mSecStateText;
+ TextView mSecDevIDText;
+ TextView mDataProvStateText;
+ TextView mCloudProvStaeText;
+
+ EditText mEnrollerSsidText;
+ EditText mEnrollerPWText;
+ EditText mInputLanguageText;
+ EditText mInputCountryText;
+ EditText mAuthCodeText;
+ EditText mAuthProviderText;
+ EditText mCIServerText;
+
+ LinearLayout mRequsetPropertyDataInfo;
+ LinearLayout mSecProvisioningState;
+ LinearLayout mDataProvisioningInfo;
+ LinearLayout mCloudProvisioningInfo;
+
+ Spinner mAuthType;
+ Spinner mEncType;
+
+ EasySetup mEasySetup;
+ RemoteEnrollee mRemoteEnrollee;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.easysetup_main);
+
+ mSecurityMode = (ToggleButton) findViewById(R.id.btn_Security);
+
+ mEasysetupProcess = (RadioGroup) findViewById(R.id.rg_EasysetupProcess);
+
+ mSecProvProcess = (RadioButton) findViewById(R.id.btn_SecurityProv);
+ mReqPropertyDataProcess = (RadioButton) findViewById(R.id.btn_requestPropertyData);
+ mDataProvProcess = (RadioButton) findViewById(R.id.btn_DataProv);
+ mCloudProvProcess = (RadioButton) findViewById(R.id.btn_CloudProv);
+
+ mInitRemoteEnrollee = (Button) findViewById(R.id.btn_initRemoteEnrollee);
+ mStartRequsetPropertyData =
+ (Button) findViewById(R.id.btn_startRequsetPropertyData);
+ mStartSecProvisioning = (Button) findViewById(R.id.btn_startSecProv);
+ mStartDataProvisioning = (Button) findViewById(R.id.btn_startDataProv);
+ mStartCloudProvisioning = (Button) findViewById(R.id.btn_startCloudProv);
+
+ mRequesetPropertyDataStateText =
+ (TextView) findViewById(R.id.txt_requesetPropertyDataState);
+ mDevIDText = (TextView) findViewById(R.id.txt_devID);
+ 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);
+ mDataProvStateText = (TextView) findViewById(R.id.txt_dataProvisioningState);
+ mCloudProvStaeText = (TextView) findViewById(R.id.txt_cloudProvisioningState);
+
+ 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);
+
+ mRequsetPropertyDataInfo =
+ (LinearLayout) findViewById(R.id.layout_RequestPropertyData);
+ mSecProvisioningState = (LinearLayout) findViewById(R.id.layout_SecProvisioning);
+ mDataProvisioningInfo = (LinearLayout) findViewById(R.id.layout_DataProvisioning);
+ mCloudProvisioningInfo = (LinearLayout) findViewById(R.id.layout_CloudProvisioning);
+
+ 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) {
+ mRequsetPropertyDataInfo.setVisibility(View.GONE);
+ mSecProvisioningState.setVisibility(View.GONE);
+ mDataProvisioningInfo.setVisibility(View.GONE);
+ mCloudProvisioningInfo.setVisibility(View.GONE);
+
+ switch (checkedId) {
+ case R.id.btn_SecurityProv:
+ mSecProvisioningState.setVisibility(View.VISIBLE);
+ break;
+
+ case R.id.btn_requestPropertyData:
+ mRequsetPropertyDataInfo.setVisibility(View.VISIBLE);
+ break;
+
+ case R.id.btn_DataProv:
+ mDataProvisioningInfo.setVisibility(View.VISIBLE);
+ break;
+
+ case R.id.btn_CloudProv:
+ mCloudProvisioningInfo.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();
+ addListenerForStartSecProvisioning();
+ addListenerForStartRequsetPropertyData();
+ addListenerForStartDataProvisioning();
+ addListenerForStartCloudProvisioning();
+
+ mSecurityMode.setClickable(false);
+ mSecProvProcess.setEnabled(false);
+ mReqPropertyDataProcess.setEnabled(false);
+ mDataProvProcess.setEnabled(false);
+ mCloudProvProcess.setEnabled(false);
+
+ mEasySetup = EasySetup.getInstance(getApplicationContext());
+ mRemoteEnrollee = mEasySetup.createRemoteEnrollee();
+
+ initOICStack();
+ }
+
+ 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);
+ } 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();
+ } 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.
+ 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();
+ mSecurityMode.setChecked(false);
+ }
+ mSecurityMode.setChecked(true);
+ }
+
+ private void addListenerForDiscoverEnrollee() {
+ mInitRemoteEnrollee.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() {
+ mInitRemoteEnrollee.setEnabled(false);
+ }
+ });
+
+ try {
+ mRemoteEnrollee.initRemoteEnrollee();
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mInitRemoteEnrollee.setText("Founded");
+ mSecProvProcess.setEnabled(true);
+ mReqPropertyDataProcess.setEnabled(true);
+ mDataProvProcess.setEnabled(true);
+ mCloudProvProcess.setEnabled(true);
+ }
+ });
+ }
+ catch (ESException e) {
+ e.printStackTrace();
+ result = false;
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mInitRemoteEnrollee.setEnabled(true);
+ }
+ });
+ }
+ }
+ };
+
+ thread.start();
+ }
+ });
+ }
+
+ private void addListenerForStartSecProvisioning() {
+ mStartSecProvisioning.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() {
+ mStartSecProvisioning.setEnabled(false);
+ }
+ });
+
+ try {
+ mRemoteEnrollee.startSecurityProvisioning(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");
+ mStartSecProvisioning.setEnabled(true);
+ }
+ });
+ }
+ }
+ });
+ } catch (ESException e) {
+ e.printStackTrace();
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mStartSecProvisioning.setEnabled(true);
+ }
+ });
+ }
+ }
+ };
+
+ thread.start();
+ }
+ });
+ }
+
+ private void addListenerForStartRequsetPropertyData(){
+ mStartRequsetPropertyData.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() {
+ mRequesetPropertyDataStateText.setText("Process");
+ mStartRequsetPropertyData.setEnabled(false);
+ }
+ });
+
+ try {
+ mRemoteEnrollee.requestPropertyData(new RequestPropertyDataCallback() {
+ @Override
+ public void onProgress(RequestPropertyDataStatus requestPropertyDataStatus) {
+ if(requestPropertyDataStatus.getESResult() == ESResult.ES_OK) {
+
+ final PropertyData propertyData = requestPropertyDataStatus.getPropertyData();
+ final DeviceConfig devConf = propertyData.getDeviceConfig();
+ final NetworkInfo netInfo = propertyData.getNetworkInfo();
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mRequesetPropertyDataStateText.setText("Success");
+ mDevIDText.setText(devConf.getId());
+ mDevNameText.setText(devConf.getName());
+ mLanguageText.setText(devConf.getLanguage());
+ mCountryText.setText(devConf.getCountry());
+ setWifiModeTypes(netInfo.getWifiModeTypes());
+ setWifiFreq(netInfo.getWifiFreq());
+
+ if(propertyData.isCloudable()) {
+ mCloudAccessableText.setText("TRUE");
+ }
+ else {
+ mCloudAccessableText.setText("FALSE");
+ }
+ }
+ });
+
+ }
+ else {
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mRequesetPropertyDataStateText.setText("Failed");
+ mStartRequsetPropertyData.setEnabled(true);
+ }
+ });
+ }
+ }
+ });
+ } catch (ESException e) {
+ e.printStackTrace();
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mRequesetPropertyDataStateText.setText("Failed");
+ mStartRequsetPropertyData.setEnabled(true);
+ }
+ });
+ }
+ }
+ };
+
+ thread.start();
+ }
+ });
+ }
+
+ private void addListenerForStartDataProvisioning() {
+ mStartDataProvisioning.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() {
+ mDataProvStateText.setText("Progress");
+ mStartDataProvisioning.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();
+
+ DataProvInfo dataProvInfo =
+ new DataProvInfo(enrollerSSID, enrollerPW, authType, encType,
+ inputLanguage, inputCountry);
+
+ mRemoteEnrollee.setDataProvInfo(dataProvInfo);
+
+ mRemoteEnrollee.startDataProvisioning(new DataProvisioningCallback() {
+ @Override
+ public void onProgress(DataProvisioningStatus dataProvisioningStatus) {
+ final ESResult result = dataProvisioningStatus.getESResult();
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ if(result.equals(ESResult.ES_OK)) {
+ mDataProvStateText.setText("Success");
+ }
+ else if(result.equals(ESResult.ES_ERROR)) {
+ mDataProvStateText.setText("Failed");
+ }
+ else if(result.equals(ESResult.ES_UNAUTHORIZED)) {
+ mDataProvStateText.setText("Failed. Need SecProv");
+ }
+ mStartDataProvisioning.setEnabled(true);
+ }
+ });
+ }
+ });
+ } catch (ESException e) {
+ e.printStackTrace();
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mDataProvStateText.setText("Failed");
+ mStartDataProvisioning.setEnabled(true);
+ }
+ });
+ }
+ }
+ };
+
+ thread.start();
+ }
+ });
+ }
+
+ private void addListenerForStartCloudProvisioning() {
+ mStartCloudProvisioning.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() {
+ mCloudProvStaeText.setText("Progress");
+ mStartCloudProvisioning.setEnabled(false);
+ }
+ });
+
+ try {
+ String authCode = mAuthCodeText.getText().toString();
+ String authProvider = mAuthProviderText.getText().toString();
+ String ciserver = mCIServerText.getText().toString();
+
+ CloudProvInfo cloudProvInfo =
+ new CloudProvInfo(authCode, authProvider, ciserver);
+ mRemoteEnrollee.setCloudProvInfo(cloudProvInfo);
+
+ mRemoteEnrollee.startCloudProvisioning(new CloudProvisioningCallback() {
+ @Override
+ public void onProgress(CloudProvisioningStatus 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)) {
+ mCloudProvStaeText.setText("Found Resource");
+ }
+ else if(state.equals(ESCloudProvState.ES_CLOUD_PROVISIONING_SUCCESS)) {
+ mCloudProvStaeText.setText("Success");
+ }
+ }
+ else {
+ if(state.equals(ESCloudProvState.ES_CLOUD_ENROLLEE_NOT_FOUND)) {
+ mCloudProvStaeText.setText("Not Found Resource");
+ }
+ else if(state.equals(ESCloudProvState.ES_CLOUD_PROVISIONING_ERROR)) {
+ mCloudProvStaeText.setText("Failed");
+ }
+ mStartCloudProvisioning.setEnabled(true);
+ }
+ }
+ });
+ }
+ });
+ } catch (ESException e) {
+ e.printStackTrace();
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mCloudProvStaeText.setText("Failed");
+ mStartCloudProvisioning.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 setWifiModeTypes(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
+ protected void onDestroy() {
+ super.onDestroy();
+ }
+}
+++ /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: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_initRemoteEnrollee"\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_SecurityProv"\r
+ android:checked="false"\r
+ android:textSize="12sp" />\r
+\r
+ <RadioButton\r
+ android:layout_width="160dp"\r
+ android:layout_height="32dp"\r
+ android:text="@string/requsetpropertydata"\r
+ android:id="@+id/btn_requestPropertyData"\r
+ android:checked="false"\r
+ android:textSize="12sp" />\r
+\r
+ <RadioButton\r
+ android:layout_width="160dp"\r
+ android:layout_height="32dp"\r
+ android:text="@string/dataprovisioning"\r
+ android:id="@+id/btn_DataProv"\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_CloudProv"\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_SecProvisioning"\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_startSecProv"\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_RequestPropertyData"\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_requesetPropertyDataState" />\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_startRequsetPropertyData"\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_DataProvisioning"\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_dataProvisioningState" />\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: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: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: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: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_startDataProv"\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_CloudProvisioning"\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_cloudProvisioningState" />\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
+ </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
+ </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
+ </LinearLayout>\r
+\r
+ <Button\r
+ android:layout_width="90dp"\r
+ android:layout_height="wrap_content"\r
+ android:text="START"\r
+ android:id="@+id/btn_startCloudProv"\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>
#include "oic_string.h"
#include "EasySetup.h"
+#include "ESRichCommon.h"
#include "OCPlatform.h"
#include "logger.h"
#include "OCProvisioningManager.h"
-
#define ES_SAMPLE_APP_TAG "ES_SAMPLE_APP_TAG"
#define DECLARE_MENU(FUNC, ...) { #FUNC, FUNC }
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::string ipaddress, ssid, pwd;
char security;
-struct CloseApp
-{
-};
-
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 printPropertyData(PropertyData propData)
{
- OIC_LOG_V(DEBUG, ES_SAMPLE_APP_TAG, "easySetupStatusCallback status is Status = %d",
- easySetupStatus->getEasySetupState());
+ cout << "===========================================" << endl;
+ DeviceConfig devConfig = propData.getDevConf();
+ NetworkInfo netInfo = propData.getNetInfo();
+
+ cout << "\tDeviceConfig.id : " << devConfig.id << endl;
+ cout << "\tDeviceConfig.name : " << devConfig.name << endl;
+ cout << "\tDeviceConfig.language : " << devConfig.language << endl;
+ cout << "\tDeviceConfig.country : " << devConfig.country << endl;
+ for(auto type = netInfo.types.begin(); type != netInfo.types.end(); ++type)
+ {
+ cout << "\tnetInfo.types : " << static_cast<int>(*type) << endl;
+ }
+ cout << "\tnetInfo.freq : " << static_cast<int>(netInfo.freq) << endl;
+ cout << "===========================================" << endl;
}
-void startProvisioning()
+void RequestPropertyDataStatusCallback(std::shared_ptr< RequestPropertyDataStatus > requestPropertyDataStatus)
{
- try
+ cout << "Enter RequestPropertyDataStatusCb." << endl;
+
+ if(requestPropertyDataStatus->getESResult() != ES_OK)
{
- remoteEnrollee->startProvisioning();
+ cout << "requestPropertyDataStatus is failed." << endl;
+ return;
}
- catch(OCException &exception)
+ else
{
- std::cout << "Exception : " << exception.reason();
+ cout << "requestPropertyDataStatus is success." << endl;
+ printPropertyData(requestPropertyDataStatus->getPropertyData());
}
}
-void initEasySetup()
+void dataProvisioningStatusCallback(std::shared_ptr< DataProvisioningStatus > provStatus)
{
+ cout << "Enter dataProvisioningStatusCallback." << endl;
+ if(provStatus->getESResult() != ES_OK)
+ {
+ cout << "dataProvisioningStatusCallback is failed." << endl;
+ return;
+ }
+ else
+ {
+ cout << "dataProvisioningStatusCallback is success." << endl;
+ cout << "ESDataProvState : " << provStatus->getESDataProvState() << endl;
+ }
+}
+
+void cloudProvisioningStatusCallback(std::shared_ptr< CloudProvisioningStatus > status)
+{
+ cout << "Enter cloudProvisioningStatusCallback." << endl;
+ cout << "CloudProvStatus : " << status->getESCloudState() << endl;
+}
+
+void createRemoteEnrollee()
+{
easySetupIntance = EasySetup::getInstance();
+ try
+ {
+ remoteEnrollee = easySetupIntance->createRemoteEnrollee();
+ }
+ catch (OCException &e)
+ {
+ std::cout << "Exception during createEnrolleeDevice call" << e.reason();
+ return;
+ }
+ cout << "createRemoteEnrollee is success." << endl;
+}
+
+void initRemoteEnrollee()
+{
+ try
+ {
+ remoteEnrollee->initRemoteEnrollee();
+ }
+ catch (OCException &e)
+ {
+ std::cout << "Exception during initRemoteEnrollee call" << e.reason();
+ return;
+ }
+}
+
+void requestPropertyData()
+{
+ try
+ {
+ remoteEnrollee->requestPropertyData(RequestPropertyDataStatusCallback);
+ }
+ catch (OCException &e)
+ {
+ std::cout << "Exception during requestPropertyData call" << e.reason();
+ return;
+ }
+}
- 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 setDataProvInfo()
+{
+ DataProvInfo dataProvInfo;
+ dataProvInfo.WIFI.ssid = "Iotivity_2.4G";
+ dataProvInfo.WIFI.pwd = "1234567890";
+ dataProvInfo.WIFI.authtype = WPA2_PSK;
+ dataProvInfo.WIFI.enctype = TKIP_AES;
+ dataProvInfo.Device.language = "korean";
+ dataProvInfo.Device.country = "korea";
+
+ remoteEnrollee->setDataProvInfo(dataProvInfo);
+}
+
+void setCloudProvInfo()
+{
+ CloudProvInfo cloudProvInfo;
+ cloudProvInfo.authCode = "authCode";
+ cloudProvInfo.authProvider = "authProvider";
+ cloudProvInfo.ciServer = "ciServer";
- if ( ipaddress.size() == 0 || ssid.size() == 0 || pwd.size()==0 )
+ remoteEnrollee->setCloudProvInfo(cloudProvInfo);
+}
+
+void startDataProvisioning()
+{
+ try
{
- cout<<"\n Invalid information try again !!!";
+ remoteEnrollee->startDataProvisioning(dataProvisioningStatusCallback);
}
- else
- {
- cout <<"\n Entered details are : \n";
- cout<<"\n IP address : "<<ipaddress;
- cout<<"\n Target Network SSID : "<<ssid;
- cout<<"\n Target Network Password : "<<pwd;
-
- 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";
- }
-
- 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());
-
- OICStrcpy(onboardingConn.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
-
- try
- {
- remoteEnrollee = easySetupIntance->createEnrolleeDevice(netInfo,onboardingConn);
- }
- catch (OCException &e)
- {
- std::cout << "Exception during createEnrolleeDevice call" << e.reason();
- return;
- }
-
- remoteEnrollee->registerEasySetupStatusHandler(&easySetupStatusCallback);
+ catch (OCException &e)
+ {
+ std::cout << "Exception during startDataProvisioning call" << e.reason();
+ return;
}
+}
+void startCloudProvisioning()
+{
+ try
+ {
+ remoteEnrollee->startCloudProvisioning(cloudProvisioningStatusCallback);
+ }
+ catch (OCException &e)
+ {
+ std::cout << "Exception during startDataProvisioning 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 CREATE_REMOTE_ENROLLEE = 1;
+ constexpr int EASY_SETUP_INIT = 2;
+ constexpr int REQUEST_PROPERTY_DATA = 3;
+ constexpr int SET_DATA_PROVISIONING_INFO = 4;
+ constexpr int START_DATA_PROVISIONING = 5;
+ constexpr int SET_CLOUD_PROVISIONING_INFO = 6;
+ constexpr int START_CLOUD_PROVISIONING = 7;
std::cout << "========================================================\n";
+ std::cout << CREATE_REMOTE_ENROLLEE << ". Create Remote Enrollee \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 << REQUEST_PROPERTY_DATA << ". Request PropertyData \n";
+ std::cout << SET_DATA_PROVISIONING_INFO << ". Set Data Provisioning Info \n";
+ std::cout << START_DATA_PROVISIONING << ". Start Data Provisioning \n";
+ std::cout << SET_CLOUD_PROVISIONING_INFO << ". Set Cloud Provisioning Info \n";
+ std::cout << START_CLOUD_PROVISIONING << ". Start Cloud Provisioning \n";
std::cout << "========================================================\n";
- int selection = processUserInput(EASY_SETUP_INIT, STOP_EASY_SETUP);
+ int selection = processUserInput(CREATE_REMOTE_ENROLLEE, START_CLOUD_PROVISIONING);
switch (selection)
{
+ case CREATE_REMOTE_ENROLLEE:
+ createRemoteEnrollee();
+ break;
case EASY_SETUP_INIT:
- initEasySetup();
+ initRemoteEnrollee();
+ break;
+ case REQUEST_PROPERTY_DATA:
+ requestPropertyData();
+ break;
+ case SET_DATA_PROVISIONING_INFO:
+ setDataProvInfo();
break;
- case START_PROVISIONING:
- startProvisioning();
+ case START_DATA_PROVISIONING:
+ startDataProvisioning();
break;
- case STOP_PROVISIONING:
- //stopProvisioning();
+ case SET_CLOUD_PROVISIONING_INFO:
+ setCloudProvInfo();
break;
- case STOP_EASY_SETUP:
- //stopEasySetup();
+ case START_CLOUD_PROVISIONING:
+ startCloudProvisioning();
break;
default:
break;
}
#endif
- g_currentRun = runEasySetupMenu;
-
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;