Merge branch 'master' into extended-easysetup
[platform/upstream/iotivity.git] / service / easy-setup / mediator / richsdk / src / RemoteEnrollee.cpp
index 427556e..24c9705 100755 (executable)
 
 #include "RemoteEnrollee.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 WiFiOnboadingConnection& wifiOnboardingconn) :
-                m_wifiOnboardingconn(wifiOnboardingconn)
-        {
-            m_requestCapabilityStatusCb = nullptr;
-            m_currentESState = CurrentESState::ES_ONBOARDED;
-            m_isSecured = m_wifiOnboardingconn.isSecured;
+        static const char ES_BASE_RES_URI[] = "/oic/res";
+        #define ES_REMOTE_ENROLLEE_TAG "ES_REMOTE_ENROLLEE"
+        #define DISCOVERY_TIMEOUT 5
 
-            m_remoteResource = std::make_shared< EnrolleeResource >(m_wifiOnboardingconn);
-
-            OIC_LOG ( DEBUG, ES_REMOTE_ENROLLEE_TAG, "Inside RemoteEnrollee constr");
+        RemoteEnrollee::RemoteEnrollee(std::shared_ptr< OC::OCResource > resource)
+        {
+            m_ocResource = resource;
+            m_enrolleeResource = std::make_shared<EnrolleeResource>(m_ocResource);
+            m_securityProvStatusCb = nullptr;
+            m_getConfigurationStatusCb = nullptr;
+            m_securityPinCb = nullptr;
+            m_secProvisioningDbPathCb = nullptr;
+            m_devicePropProvStatusCb = nullptr;
+            m_cloudPropProvStatusCb = nullptr;
+
+            m_deviceId = resource->sid();
         }
 
 #ifdef __WITH_DTLS__
@@ -59,212 +66,358 @@ namespace OIC
         }
 #endif //__WITH_DTLS__
 
-        void RemoteEnrollee::easySetupSecurityStatusCallback(
-                        std::shared_ptr< SecProvisioningStatus > secProvisioningStatus)
+        void RemoteEnrollee::securityStatusHandler(
+                        std::shared_ptr< SecProvisioningStatus > status)
         {
             OIC_LOG_V(DEBUG, ES_REMOTE_ENROLLEE_TAG, "easySetupStatusCallback status is, UUID = %s, "
-                    "Status = %d", secProvisioningStatus->getDeviceUUID().c_str(),
-                    secProvisioningStatus->getResult());
+                    "Status = %d", status->getDeviceUUID().c_str(),
+                    status->getESResult());
 
-            if(secProvisioningStatus->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_currentESState = CurrentESState::ES_OWNED;
-
                 OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Before ProvisionEnrollee");
 
-                m_enrolleeSecStatusCb(secProvisioningStatus);
+                m_securityProvStatusCb(status);
             }
             else
             {
                 OIC_LOG(DEBUG, ES_REMOTE_ENROLLEE_TAG, "Ownership and ACL are fail");
 
-                m_enrolleeSecStatusCb(secProvisioningStatus);
+                m_securityProvStatusCb(status);
             }
         }
 
-        void RemoteEnrollee::InitRemoteEnrolleeStatusHandler (
-                std::shared_ptr< InitRemoteEnrolleeStatus > initRemoteEnrolleeStatus)
+        void RemoteEnrollee::getConfigurationStatusHandler (
+                std::shared_ptr< GetConfigurationStatus > status)
         {
-            OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Entering InitRemoteEnrolleeStatusHandler");
+            OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Entering getConfigurationStatusHandler");
 
-            OIC_LOG_V(DEBUG,ES_REMOTE_ENROLLEE_TAG,"initRemoteEnrolleeStatus = %d", initRemoteEnrolleeStatus->getESResult());
+            OIC_LOG_V(DEBUG,ES_REMOTE_ENROLLEE_TAG,"GetConfigurationStatus = %d", status->getESResult());
 
-            m_initRemoteEnrolleeStatusCb(initRemoteEnrolleeStatus);
+            m_getConfigurationStatusCb(status);
         }
 
-        void RemoteEnrollee::requestCapabilityStatusHandler (
-                std::shared_ptr< RequestCapabilityStatus > requestCapabilityStatus)
+        void RemoteEnrollee::devicePropProvisioningStatusHandler(
+                std::shared_ptr< DevicePropProvisioningStatus > status)
         {
-            OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Entering requestCapabilityStatusHandler");
+            OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Entering DevicePropProvisioningStatusHandler");
+
+            OIC_LOG_V(DEBUG,ES_REMOTE_ENROLLEE_TAG,"ProvStatus = %d", status->getESResult());
 
-            OIC_LOG_V(DEBUG,ES_REMOTE_ENROLLEE_TAG,"requestCapabilityStatus = %d", requestCapabilityStatus->getESResult());
+            m_devicePropProvStatusCb(status);
 
-            m_requestCapabilityStatusCb(requestCapabilityStatus);
+            return;
         }
 
-        void RemoteEnrollee::dataProvisioningStatusHandler(
-                std::shared_ptr< ProvisioningStatus > provStatus)
+        void RemoteEnrollee::cloudPropProvisioningStatusHandler (
+                std::shared_ptr< CloudPropProvisioningStatus > status)
         {
-            OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Entering dataprovisioningStatusHandler");
+            OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Entering cloudPropProvisioningStatusHandler");
 
-            OIC_LOG_V(DEBUG,ES_REMOTE_ENROLLEE_TAG,"ProvStatus = %d", provStatus->getESResult());
+            OIC_LOG_V(DEBUG,ES_REMOTE_ENROLLEE_TAG,"CloudProvStatus = %d", status->getESCloudState());
 
-            if (provStatus->getESResult() == ES_OK)
+            m_cloudPropProvStatusCb(status);
+            return;
+        }
+
+        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)
             {
-                if (provStatus->getESState() >= ESState::ES_PROVISIONED_ALREADY)
-                {
-                    OIC_LOG_V(DEBUG,ES_REMOTE_ENROLLEE_TAG,"ProvStatus = %d", provStatus->getESResult());
-                    m_currentESState = CurrentESState::ES_PROVISIONED;
-                }
+                return ES_ERROR;
             }
-            m_dataProvStatusCb(provStatus);
 
-            return;
+            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 RemoteEnrollee::initRemoteEnrollee(InitRemoteEnrolleeStatusCb callback)
+        void RemoteEnrollee::onDeviceDiscovered(std::shared_ptr<OC::OCResource> resource)
         {
-            ESResult result = ES_ERROR;
+            OIC_LOG (DEBUG, ES_REMOTE_ENROLLEE_TAG, "onDeviceDiscovered");
 
-            if(!callback)
+            std::string resourceURI;
+            std::string hostAddress;
+            std::string hostDeviceID;
+
+            try
             {
-                throw ESInvalidParameterException("Callback is empty");
+                if(resource)
+                {
+                    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() && m_deviceId == hostDeviceID)
+                        {
+                            OIC_LOG (DEBUG, ES_REMOTE_ENROLLEE_TAG, "Find matched CloudResource");
+                            m_ocResource = resource;
+                            m_discoveryResponse = true;
+                        }
+                    }
+                }
+            }
+            catch(std::exception& e)
+            {
+                OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_TAG,
+                        "Exception in foundResource: %s", e.what());
             }
+        }
+
+        ESResult RemoteEnrollee::discoverResource()
+        {
+            OIC_LOG(DEBUG, ES_REMOTE_ENROLLEE_TAG, "Enter discoverResource");
 
-            m_initRemoteEnrolleeStatusCb = callback;
+            std::string query("");
+            query.append(ES_BASE_RES_URI);
+            query.append("?rt=");
+            query.append(OC_RSRVD_ES_RES_TYPE_PROV);
 
-            if (m_remoteResource != nullptr)
+            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)
             {
-                throw ESBadRequestException ("Already created");
+                OIC_LOG(ERROR,ES_REMOTE_ENROLLEE_TAG,
+                        "Failed discoverResource");
+                return ES_ERROR;
             }
 
-            InitRemoteEnrolleeStatusCb initRemoteEnrolleeStatusCb = std::bind(
-                    &RemoteEnrollee::InitRemoteEnrolleeStatusHandler, this, std::placeholders::_1);
-            m_remoteResource->registerInitRemoteEnrolleeStatusCallback(initRemoteEnrolleeStatusCb);
-
-            result = m_remoteResource->constructResourceObject();
+            ESResult foundResponse = ESDiscoveryTimeout (DISCOVERY_TIMEOUT);
 
-            if (result == ES_ERROR)
+            if (foundResponse == ES_ERROR || !m_discoveryResponse)
             {
                 OIC_LOG(ERROR,ES_REMOTE_ENROLLEE_TAG,
-                                    "Failed to create device using constructResourceObject");
-                throw ESBadRequestException ("Device not created");
+                        "Failed discoverResource because timeout");
+                return ES_ERROR;
             }
+            return ES_OK;
         }
 
-        void RemoteEnrollee::startSecurityProvisioning(EnrolleeSecStatusCb callback)
+        void RemoteEnrollee::provisionSecurity(SecurityProvStatusCb callback)
         {
 #ifdef __WITH_DTLS__
+            m_securityProvStatusCb = callback;
 
-            m_enrolleeSecStatusCb = callback;
-
-            if (m_isSecured && m_currentESState < CurrentESState::ES_OWNED)
-            {
-                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, "");
+            SecurityProvStatusCb securityProvStatusCb = std::bind(
+                    &RemoteEnrollee::securityStatusHandler,
+                    this,
+                    std::placeholders::_1);
+            //TODO : DBPath is passed empty as of now. Need to take dbpath from application.
+            m_enrolleeSecurity = std::make_shared <EnrolleeSecurity> (m_ocResource, "");
 
-                m_enrolleeSecurity->registerCallbackHandler(securityProvStatusCb,
-                        m_securityPinCb, m_secProvisioningDbPathCb);
+            m_enrolleeSecurity->registerCallbackHandler(securityProvStatusCb, m_securityPinCb, m_secProvisioningDbPathCb);
 
-                try
-                {
-                    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");
-                    }
-                }
-                catch (OCException & e)
-                {
-                    OIC_LOG_V(ERROR, ES_REMOTE_ENROLLEE_TAG,
-                            "Exception for performOwnershipTransfer : %s", e.reason().c_str());
-                    return ;
-                }
+            try
+            {
+                m_enrolleeSecurity->performOwnershipTransfer();
+            }
+            catch (OCException & e)
+            {
+                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 ;
             }
+#else
+            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::getCapabilityData(RequestCapabilityStatusCb callback)
+        void RemoteEnrollee::getConfiguration(GetConfigurationStatusCb callback)
         {
-            ESResult result = ES_ERROR;
-
             if(!callback)
             {
                 throw ESInvalidParameterException("Callback is empty");
             }
 
-            m_requestCapabilityStatusCb = callback;
+            m_getConfigurationStatusCb = callback;
 
-            if (m_remoteResource == nullptr)
+            if (m_enrolleeResource == nullptr)
             {
                 throw ESBadRequestException ("Device not created");
             }
 
-            RequestCapabilityStatusCb requestCapabilityStatusCb = std::bind(
-                    &RemoteEnrollee::requestCapabilityStatusHandler, this, std::placeholders::_1);
-            m_remoteResource->registerCapabilityStatusCallback(requestCapabilityStatusCb);
-            m_remoteResource->getCapabilityData();
+            GetConfigurationStatusCb getConfigurationStatusCb = std::bind(
+                    &RemoteEnrollee::getConfigurationStatusHandler, this, std::placeholders::_1);
+            m_enrolleeResource->registerGetConfigurationStatusCallback(getConfigurationStatusCb);
+            m_enrolleeResource->getConfiguration();
         }
 
-        void RemoteEnrollee::startDataProvisioning(const ProvConfig& dataProvConfig, DataProvStatusCb callback)
+        void RemoteEnrollee::provisionDeviceProperties(const DeviceProp& devProp, DevicePropProvStatusCb callback)
         {
-            OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Before ProvisionEnrollee");
+            OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Enter provisionDeviceProperties");
 
-            m_ProvConfig = dataProvConfig;
-            m_dataProvStatusCb = callback;
+            if(!callback)
+            {
+                throw ESInvalidParameterException("Callback is empty");
+            }
 
-            DataProvStatusCb dataProvStatusCb = std::bind(
-                    &RemoteEnrollee::dataProvisioningStatusHandler, this, std::placeholders::_1);
+            m_devicePropProvStatusCb = callback;
 
-            m_remoteResource->registerProvStatusCallback(dataProvStatusCb);
-            m_remoteResource->provisionEnrollee();
-        }
+            if (m_enrolleeResource == nullptr)
+            {
+                throw ESBadRequestException ("Device not created");
+            }
 
-        void RemoteEnrollee::stopProvisioning()
-        {
-            m_currentESState = CurrentESState::ES_UNKNOWN;
+            if(devProp.WIFI.ssid.empty())
+            {
+                throw ESBadRequestException ("Invalid Provisiong Data.");
+            }
+
+            DevicePropProvStatusCb devicePropProvStatusCb = std::bind(
+                    &RemoteEnrollee::devicePropProvisioningStatusHandler, this, std::placeholders::_1);
 
-            m_remoteResource->unprovisionEnrollee();
+            m_enrolleeResource->registerDevicePropProvStatusCallback(devicePropProvStatusCb);
+            m_enrolleeResource->provisionEnrollee(devProp);
         }
 
-        bool RemoteEnrollee::isEnrolleeProvisioned()
+        void RemoteEnrollee::initCloudResource()
         {
-            if(m_currentESState >= CurrentESState::ES_PROVISIONED)
+            ESResult result = ES_ERROR;
+
+            if (m_cloudResource != nullptr)
+            {
+                throw ESBadRequestException ("Already created");
+            }
+
+            result = discoverResource();
+
+            if (result == ES_ERROR)
             {
-                return true;
+                OIC_LOG(ERROR,ES_REMOTE_ENROLLEE_TAG,
+                                    "Failed to create resource object using discoverResource");
+                throw ESBadRequestException ("Resource object not created");
             }
+
             else
             {
-                return false;
+                if(m_ocResource != nullptr)
+                {
+                    m_cloudResource = std::make_shared<CloudResource>(std::move(m_ocResource));
+
+                    std::shared_ptr< CloudPropProvisioningStatus > provStatus = std::make_shared<
+                        CloudPropProvisioningStatus >(ESResult::ES_OK, ESCloudProvState::ES_CLOUD_ENROLLEE_FOUND);
+
+                    m_cloudPropProvStatusCb(provStatus);
+                }
+                else
+                {
+                    throw ESBadGetException ("Resource handle is invalid");
+                }
             }
         }
 
-        ProvConfig RemoteEnrollee::getProvConfig ()
+
+        void RemoteEnrollee::provisionCloudProperties(const CloudProp& cloudProp, CloudPropProvStatusCb callback)
         {
-            return m_ProvConfig;
-        }
+            OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Enter provisionCloudProperties");
+
+            ESResult result = ES_ERROR;
+
+            if(!callback)
+            {
+                throw ESInvalidParameterException("Callback is empty");
+            }
+
+            m_cloudPropProvStatusCb = callback;
 
-       WiFiOnboadingConnection RemoteEnrollee::getOnboardConn()
-       {
-         return m_wifiOnboardingconn;
-       }
+            if(cloudProp.authCode.empty()
+                || cloudProp.authProvider.empty()
+                || cloudProp.ciServer.empty())
+            {
+                throw ESBadRequestException ("Invalid Cloud Provisiong Info.");
+            }
+
+            try
+            {
+                initCloudResource();
+            }
+
+            catch (const std::exception& e)
+            {
+                OIC_LOG_V(ERROR, ES_REMOTE_ENROLLEE_TAG,
+                    "Exception caught in provisionCloudProperties = %s", e.what());
 
+                std::shared_ptr< CloudPropProvisioningStatus > provStatus = std::make_shared<
+                        CloudPropProvisioningStatus >(ESResult::ES_ERROR, ESCloudProvState::ES_CLOUD_ENROLLEE_NOT_FOUND);
+                m_cloudPropProvStatusCb(provStatus);
+            }
+
+            if (m_cloudResource == nullptr)
+            {
+                throw ESBadRequestException ("Cloud Resource not created");
+            }
+
+            CloudPropProvStatusCb cloudPropProvStatusCb = std::bind(
+                    &RemoteEnrollee::cloudPropProvisioningStatusHandler, this, std::placeholders::_1);
+
+            m_cloudResource->registerCloudPropProvisioningStatusCallback(cloudPropProvStatusCb);
+            m_cloudResource->provisionEnrollee(cloudProp);
+        }
     }
 }