replace : iotivity -> iotivity-sec
[platform/upstream/iotivity.git] / resource / csdk / stack / samples / tizen / SimpleClientServer / occlient.cpp
index 09d846d..6736a69 100644 (file)
@@ -20,6 +20,7 @@
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include <stdio.h>
+#include <glib.h>
 #include <stdlib.h>
 #include <string.h>
 #include <signal.h>
 #include "logger.h"
 #include "occlient.h"
 #include "ocpayload.h"
+#include "payload_logging.h"
+
 using namespace std;
 
+#ifdef ROUTING_GATEWAY
+/**
+ * Maximum number of gateway requests to form the routing table.
+ */
+#define MAX_NUM_GATEWAY_REQUEST 20
+
+/**
+ * Sleep duration after every OCProcess().
+ */
+#define SLEEP_DURATION 100000
+#endif
+
 // Tracking user input
-static int UNICAST_DISCOVERY = 0;
-static int TEST_CASE = 0;
-static int CONNECTIVITY = 0;
-
-static const char * UNICAST_DEVICE_DISCOVERY_QUERY = "coap://%s/oic/d";
-static const char * MULTICAST_DEVICE_DISCOVERY_QUERY = "/oic/d";
-static const char * UNICAST_PLATFORM_DISCOVERY_QUERY = "coap://%s/oic/p";
-static const char * MULTICAST_PLATFORM_DISCOVERY_QUERY = "/oic/p";
-
-static const char * UNICAST_RESOURCE_DISCOVERY_QUERY = "coap://%s/oic/res";
-static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oic/res";
-// The following variable determines the interface protocol (IPv4, IPv6, etc)
-//to be used for sending unicast messages. Default set to IPv4.
-static OCConnectivityType OC_CONNTYPE = CT_ADAPTER_IP;
-static std::string coapServerIP = "255.255.255.255";
-static std::string coapServerPort = "5683";
+static int g_unicastDiscovery = 0;
+static int g_testCase = 0;
+static int g_connectivity = 0;
+
+static GMainLoop *g_mainloop = NULL;
+pthread_t g_thread;
+
+static const char *DEVICE_DISCOVERY_QUERY = "%s/oic/d";
+static const char *PLATFORM_DISCOVERY_QUERY = "%s/oic/p";
+static const char *RESOURCE_DISCOVERY_QUERY = "%s/oic/res";
+
+static const char *DEFAULT_DB_FILE_PATH = "/opt/usr/etc/oic_svr_db_client.dat";
+
+//The following variable determines the interface protocol (IPv4, IPv6, etc)
+//to be used for sending unicast messages. Default set to IP dual stack.
+static OCConnectivityType g_connType = CT_ADAPTER_IP;
+static OCDevAddr g_serverAddr;
+static char g_discoveryAddr[100];
 static std::string coapServerResource = "/a/light";
-// Size to hold ADDRESS
-static const int MAX_ADDR_SIZE = 24;
-//Use unicastAddr for both InitDiscovery and InitPlatformOrDeviceDiscovery
-char unicastAddr[MAX_ADDR_SIZE];
+
 void StripNewLineChar(char* str);
 
 // The handle for the observe registration
@@ -86,7 +100,7 @@ OCPayload* putPayload()
     if(!payload)
     {
         std::cout << "Failed to create put payload object"<<std::endl;
-        std::exit(1);
+        exit(1);
     }
 
     OCRepPayloadSetPropInt(payload, "power", 15);
@@ -98,12 +112,12 @@ OCPayload* putPayload()
 static void PrintUsage()
 {
     cout << "Hello";
-    cout << "\nUsage : occlient -u <0|1> -t <1..17> -c <0|1|2>";
+    cout << "\nUsage : occlient -u <0|1> -t <1..17> -c <0|1|2|3>";
     cout << "\n-u <0|1> : Perform multicast/unicast discovery of resources";
-    cout << "\n-c 0 : Default IPv4 and IPv6 auto-selection";
-    cout << "\n-c 1 : IPv4 Connectivity Type";
-    cout << "\n-c 2 : IPv6 Connectivity Type (IPv6 not currently supported)";
-    cout << "\n-c 3 : EDR Connectivity Type (IPv6 not currently supported)";
+    cout << "\n-c 0 : Default IP selection";
+    cout << "\n-c 1 : IP Connectivity Type";
+    cout << "\n-c 2 : EDR Connectivity Type (IPv6 not currently supported)";
+    cout << "\n-c 3 : TCP Connectivity Type";
     cout << "\n-t 1  :  Discover Resources";
     cout << "\n-t 2  :  Discover Resources and Initiate Nonconfirmable Get Request";
     cout << "\n-t 3  :  Discover Resources and Initiate Nonconfirmable Get Request with query filter";
@@ -135,6 +149,7 @@ static void PrintUsage()
 }
 
 OCStackResult InvokeOCDoResource(std::ostringstream &query,
+                                 OCDevAddr *remoteAddr,
                                  OCMethod method,
                                  OCQualityOfService qos,
                                  OCClientResponseHandler cb,
@@ -149,9 +164,12 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
 
-    ret = OCDoResource(&handle, method, query.str().c_str(), 0,
-                       (method == OC_REST_PUT) ? putPayload() : NULL,
-                       (OC_CONNTYPE), qos, &cbData, options, numOptions);
+    OCPayload* payload = (method == OC_REST_PUT) ? putPayload() : NULL;
+
+    ret = OCDoRequest(&handle, method, query.str().c_str(), remoteAddr,
+                      payload, (g_connType), qos, &cbData, options, numOptions);
+
+    OCPayloadDestroy(payload);
 
     if (ret != OC_STACK_OK)
     {
@@ -172,14 +190,15 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
     return ret;
 }
 
-OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
+OCStackApplicationResult putReqCB(void* ctx, OCDoHandle /*handle*/,
+                                  OCClientResponse * clientResponse)
 {
-    if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
+    if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
         cout << "\nCallback Context for PUT recvd successfully";
     }
 
-    if(clientResponse)
+    if (clientResponse)
     {
         cout << "\nStackResult: " << getResult(clientResponse->result);
         cout << "\nJSON = " << clientResponse->payload;
@@ -191,14 +210,15 @@ OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse
     return OC_STACK_DELETE_TRANSACTION;
 }
 
-OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
+OCStackApplicationResult postReqCB(void *ctx, OCDoHandle /*handle*/,
+                                   OCClientResponse *clientResponse)
 {
-    if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
+    if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
         cout << "\nCallback Context for POST recvd successfully";
     }
 
-    if(clientResponse)
+    if (clientResponse)
     {
         cout << "\nStackResult: " << getResult(clientResponse->result);
         cout << "\nJSON = " << clientResponse->payload;
@@ -211,7 +231,8 @@ OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientRespons
 }
 
 OCStackApplicationResult deleteReqCB(void *ctx,
-        OCDoHandle handle, OCClientResponse *clientResponse)
+                                     OCDoHandle /*handle*/,
+                                     OCClientResponse *clientResponse)
 {
     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
@@ -221,7 +242,7 @@ OCStackApplicationResult deleteReqCB(void *ctx,
     if(clientResponse)
     {
         cout << "\nStackResult: " << getResult(clientResponse->result);
-        //OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
+        //OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
     }
     else
     {
@@ -230,31 +251,32 @@ OCStackApplicationResult deleteReqCB(void *ctx,
     return OC_STACK_DELETE_TRANSACTION;
 }
 
-OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
+OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
+                                  OCClientResponse * clientResponse)
 {
-    if(clientResponse == NULL)
+    if (clientResponse == NULL)
     {
         cout << "\ngetReqCB received NULL clientResponse";
         return   OC_STACK_DELETE_TRANSACTION;
     }
 
-    if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
+    if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
         cout << "\nCallback Context for GET query recvd successfully";
     }
 
     cout << "\nStackResult: " << getResult(clientResponse->result);
     cout << "\nSEQUENCE NUMBER: " << clientResponse->sequenceNumber;
-    //OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
+    //OIC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
 
-    if(clientResponse->numRcvdVendorSpecificHeaderOptions > 0)
+    if (clientResponse->numRcvdVendorSpecificHeaderOptions > 0)
     {
         cout << "\nReceived vendor specific options";
         uint8_t i = 0;
         OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
         for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
         {
-            if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
+            if (((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
             {
                 cout << "\nReceived option ID " << ((OCHeaderOption)rcvdOptions[i]).optionID;
             }
@@ -263,50 +285,52 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse
     return OC_STACK_DELETE_TRANSACTION;
 }
 
-OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
+OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle /*handle*/,
+                                  OCClientResponse * clientResponse)
 {
-    if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
+    if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
         cout << "\nCallback Context for OBS query recvd successfully";
     }
 
-    if(clientResponse)
+    if (clientResponse)
     {
-        cout << "\nStackResult: " << getResult(clientResponse->result);
-        cout << "\nSEQUENCE NUMBER: " << clientResponse->sequenceNumber;
-        cout << "\nCallback Context for OBSERVE notification recvd successfully ";
-        //OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
-        gNumObserveNotifies++;
-        if (gNumObserveNotifies == 15) //large number to test observing in DELETE case.
+        if (clientResponse->sequenceNumber <= MAX_SEQUENCE_NUMBER)
         {
-            if(TEST_CASE == TEST_OBS_REQ_NON || TEST_CASE == TEST_OBS_REQ_CON)
+            if (clientResponse->sequenceNumber == OC_OBSERVE_REGISTER)
             {
-                if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK)
-                {
-                    cout << "\nObserve cancel error";
-                }
-                return OC_STACK_DELETE_TRANSACTION;
+                cout << "This also serves as a registration confirmation" << endl;
             }
-            else if(TEST_CASE == TEST_OBS_REQ_NON_CANCEL_IMM)
+
+            cout << "\nStackResult: " << getResult(clientResponse->result);
+            cout << "\nSEQUENCE NUMBER: " << clientResponse->sequenceNumber;
+            cout << "\nCallback Context for OBSERVE notification recvd successfully ";
+            //OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
+            gNumObserveNotifies++;
+
+            if (gNumObserveNotifies == 15) //large number to test observing in DELETE case.
             {
-                if (OCCancel (gObserveDoHandle, OC_HIGH_QOS, NULL, 0) != OC_STACK_OK)
+                if (g_testCase == TEST_OBS_REQ_NON || g_testCase == TEST_OBS_REQ_CON)
+                {
+                    if (OCCancel(gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK)
+                    {
+                        cout << "Observe cancel error" << endl;
+                    }
+                    return OC_STACK_DELETE_TRANSACTION;
+                }
+                else if (g_testCase == TEST_OBS_REQ_NON_CANCEL_IMM)
                 {
-                    cout << "\nObserve cancel error";
+                    if (OCCancel(gObserveDoHandle, OC_HIGH_QOS, NULL, 0) != OC_STACK_OK)
+                    {
+                        cout << "\nObserve cancel error";
+                    }
                 }
             }
         }
-        if(clientResponse->sequenceNumber == OC_OBSERVE_REGISTER)
-        {
-            cout << "\nThis also serves as a registration confirmation";
-        }
-        else if(clientResponse->sequenceNumber == OC_OBSERVE_DEREGISTER)
-        {
-            cout << "\nThis also serves as a deregistration confirmation";
-            return OC_STACK_DELETE_TRANSACTION;
-        }
-        else if(clientResponse->sequenceNumber == OC_OBSERVE_NO_OPTION)
+        else
         {
-            cout << "\nThis also tells you that registration/deregistration failed";
+            OIC_LOG(INFO, TAG, "No observe option header is returned in the response.");
+            OIC_LOG(INFO, TAG, "For a registration request, it means the registration failed");
             return OC_STACK_DELETE_TRANSACTION;
         }
     }
@@ -317,7 +341,8 @@ OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle handle, OCClientResponse
     return OC_STACK_KEEP_TRANSACTION;
 }
 #ifdef WITH_PRESENCE
-OCStackApplicationResult presenceCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
+OCStackApplicationResult presenceCB(void* ctx, OCDoHandle /*handle*/,
+                                    OCClientResponse * clientResponse)
 {
     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
     {
@@ -329,7 +354,7 @@ OCStackApplicationResult presenceCB(void* ctx, OCDoHandle handle, OCClientRespon
         cout << "\nStackResult: " << getResult(clientResponse->result);
         cout << "\nNONCE NUMBER: " << clientResponse->sequenceNumber;
         cout << "\nCallback Context for Presence notification recvd successfully ";
-        //OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
+        //OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
         gNumPresenceNotifies++;
         if (gNumPresenceNotifies == 20)
         {
@@ -349,8 +374,8 @@ OCStackApplicationResult presenceCB(void* ctx, OCDoHandle handle, OCClientRespon
 #endif
 
 // This is a function called back when a device is discovered
-OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
-        OCClientResponse * clientResponse)
+OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
+                                        OCClientResponse * clientResponse)
 {
     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
     {
@@ -359,23 +384,74 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
 
     if (clientResponse)
     {
+        if (NULL == clientResponse->payload)
+        {
+            cout << "\nPayload is NULL, No resources found";
+            return OC_STACK_KEEP_TRANSACTION;
+        }
+
         cout << "\nStackResult: " << getResult(clientResponse->result);
 
         std::string connectionType = getConnectivityType (clientResponse->connType);
         cout << "\nDiscovered on " << connectionType.c_str();
         cout << "\nDevice ======> Discovered ";
         cout << clientResponse->devAddr.addr;
-        //TODO: Bug in RI layer.  Its returning 65600 instead of CT_ADAPTER_IP
-        if (65600 == clientResponse->connType)
+        if (CT_ADAPTER_IP == (clientResponse->connType & CT_MASK_ADAPTER))
         {
             cout << ":" << clientResponse->devAddr.port;
         }
-        //OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
+        //OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
         cout << "\nConnectivity type: " << clientResponse->connType;
-        OC_CONNTYPE = clientResponse->connType;
+        g_serverAddr = clientResponse->devAddr;
         parseClientResponse(clientResponse);
 
-        switch(TEST_CASE)
+        OCDiscoveryPayload *payload = (OCDiscoveryPayload*) clientResponse->payload;
+        if (!payload)
+        {
+            cout << "\nDiscovery payload is empty!";
+            return OC_STACK_KEEP_TRANSACTION;
+        }
+
+        OCResourcePayload *resource = (OCResourcePayload*) payload->resources;
+        int targetResourceFound = 0;
+        while(resource)
+        {
+            cout << "\nFound resource: " << resource->uri;
+            if (resource->uri && strcmp(resource->uri, coapServerResource.c_str()) == 0)
+            {
+                cout << "\nLight resource found.";
+                targetResourceFound = 1;
+
+                if (g_testCase >= TEST_OBS_PRESENCE) break;
+
+                if (resource->secure && resource->port)
+                {
+                    cout << "\nLight resource with secure flag";
+                    g_serverAddr.flags = (OCTransportFlags) (clientResponse->devAddr.flags | OC_SECURE);
+                    g_serverAddr.port = resource->port;
+                }
+
+#ifdef WITH_TCP
+                if(g_connType == CT_ADAPTER_TCP && resource->tcpPort)
+                {
+                    cout << "\nRequest will be send with TCP";
+                    g_serverAddr.port = resource->tcpPort;
+                    g_serverAddr.adapter = OC_ADAPTER_TCP;
+                }
+#endif
+
+                break;
+            }
+            resource = resource->next;
+        }
+
+        if (!targetResourceFound)
+        {
+            OIC_LOG_V(INFO, TAG, "No %s in payload", coapServerResource.c_str());
+            return OC_STACK_KEEP_TRANSACTION;
+        }
+
+        switch(g_testCase)
         {
             case TEST_GET_REQ_NON:
                 InitGetRequest(OC_LOW_QOS, 0, 0);
@@ -440,38 +516,39 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
     return OC_STACK_KEEP_TRANSACTION;
 }
 
-OCStackApplicationResult PlatformDiscoveryReqCB (void* ctx, OCDoHandle handle,
-        OCClientResponse * clientResponse)
+OCStackApplicationResult PlatformDiscoveryReqCB(void* ctx,
+                                                OCDoHandle /*handle*/,
+                                                OCClientResponse * clientResponse)
 {
     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
     {
         cout << "\nCallback Context for Platform DISCOVER query recvd successfully";
     }
 
-    if(clientResponse)
+    if (clientResponse)
     {
-        //OC_LOG truncates the response as it is too long.
-        //OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
+        //OIC_LOG truncates the response as it is too long.
+        //OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
     }
     else
     {
         cout << "\nPlatformDiscoveryReqCB received Null clientResponse";
     }
 
-    return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION;
+    return (g_unicastDiscovery) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION;
 }
 
-OCStackApplicationResult DeviceDiscoveryReqCB (void* ctx, OCDoHandle handle,
-        OCClientResponse * clientResponse)
+OCStackApplicationResult DeviceDiscoveryReqCB(void* ctx, OCDoHandle /*handle*/,
+                                              OCClientResponse * clientResponse)
 {
     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
     {
         cout << "\nCallback Context for Device DISCOVER query recvd successfully";
     }
 
-    if(clientResponse)
+    if (clientResponse)
     {
-        //OC_LOG truncates the response as it is too long.
+        //OIC_LOG truncates the response as it is too long.
         cout << "\nDiscovery response: ";
         cout << clientResponse->payload;
     }
@@ -480,7 +557,7 @@ OCStackApplicationResult DeviceDiscoveryReqCB (void* ctx, OCDoHandle handle,
         cout << "\nPlatformDiscoveryReqCB received Null clientResponse";
     }
 
-    return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION;
+    return (g_unicastDiscovery) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION;
 }
 
 #ifdef WITH_PRESENCE
@@ -490,37 +567,37 @@ int InitPresence()
     cout << "\nExecuting " << __func__;
     std::ostringstream query;
     std::ostringstream querySuffix;
-    query << "coap://" << coapServerIP << ":" << coapServerPort << OC_RSRVD_PRESENCE_URI;
-    if(TEST_CASE == TEST_OBS_PRESENCE)
+    query << OC_RSRVD_PRESENCE_URI;
+    if (g_testCase == TEST_OBS_PRESENCE)
     {
-        result = InvokeOCDoResource(query, OC_REST_PRESENCE, OC_LOW_QOS,
-                presenceCB, NULL, 0);
+        result = InvokeOCDoResource(query, &g_serverAddr, OC_REST_PRESENCE,
+                OC_LOW_QOS, presenceCB, NULL, 0);
     }
-    if(TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTER || TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTERS)
+    if (g_testCase == TEST_OBS_PRESENCE_WITH_FILTER || g_testCase == TEST_OBS_PRESENCE_WITH_FILTERS)
     {
         querySuffix.str("");
         querySuffix << query.str() << "?rt=core.led";
-        result = InvokeOCDoResource(querySuffix, OC_REST_PRESENCE, OC_LOW_QOS,
-                presenceCB, NULL, 0);
+        result = InvokeOCDoResource(querySuffix, &g_serverAddr, OC_REST_PRESENCE,
+                OC_LOW_QOS, presenceCB, NULL, 0);
     }
-    if(TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTERS)
+    if (g_testCase == TEST_OBS_PRESENCE_WITH_FILTERS)
     {
-        if(result == OC_STACK_OK)
+        if (result == OC_STACK_OK)
         {
             querySuffix.str("");
             querySuffix << query.str() << "?rt=core.fan";
-            result = InvokeOCDoResource(querySuffix, OC_REST_PRESENCE, OC_LOW_QOS,
+            result = InvokeOCDoResource(querySuffix, &g_serverAddr, OC_REST_PRESENCE, OC_LOW_QOS,
                     presenceCB, NULL, 0);
         }
     }
-    if(TEST_CASE == TEST_OBS_MULTICAST_PRESENCE)
+    if (g_testCase == TEST_OBS_MULTICAST_PRESENCE)
     {
-        if(result == OC_STACK_OK)
+        if (result == OC_STACK_OK)
         {
             std::ostringstream multicastPresenceQuery;
             multicastPresenceQuery.str("");
             multicastPresenceQuery << "coap://" << OC_MULTICAST_PREFIX << OC_RSRVD_PRESENCE_URI;
-            result = InvokeOCDoResource(multicastPresenceQuery, OC_REST_PRESENCE, OC_LOW_QOS,
+            result = InvokeOCDoResource(multicastPresenceQuery, &g_serverAddr, OC_REST_PRESENCE, OC_LOW_QOS,
                     presenceCB, NULL, 0);
         }
     }
@@ -532,18 +609,8 @@ int InitGetRequestToUnavailableResource(OCQualityOfService qos)
 {
     cout << "\nExecuting " << __func__;
     std::ostringstream query;
-
-    //TODO: Bug in RI layer.  Its returning 65600 instead of CT_ADAPTER_IP
-    if (65600 == OC_CONNTYPE)
-    {
-        query << "coap://" << coapServerIP << ":" << coapServerPort << "/SomeUnknownResource";
-    }
-    else
-    {
-        query << "coap://" << coapServerIP << "/SomeUnknownResource";
-    }
-
-    return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS,
+    query << "/SomeUnknownResource";
+    return (InvokeOCDoResource(query, &g_serverAddr, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS,
             getReqCB, NULL, 0));
 }
 
@@ -551,33 +618,17 @@ int InitObserveRequest(OCQualityOfService qos)
 {
     cout << "\nExecuting " << __func__;
     std::ostringstream query;
-    //TODO: Bug in RI layer.  Its returning 65600 instead of CT_ADAPTER_IP
-    if (65600 == OC_CONNTYPE)
-    {
-        query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
-    }
-    else
-    {
-        query << "coap://" << coapServerIP << coapServerResource;
-    }
-    return (InvokeOCDoResource(query,
-            OC_REST_OBSERVE, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, obsReqCB, NULL, 0));
+    query << coapServerResource;
+    return (InvokeOCDoResource(query, &g_serverAddr, OC_REST_OBSERVE,
+              (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, obsReqCB, NULL, 0));
 }
 
 int InitPutRequest(OCQualityOfService qos)
 {
     cout << "\nExecuting " << __func__;
     std::ostringstream query;
-    //TODO: Bug in RI layer.  Its returning 65600 instead of CT_ADAPTER_IP
-    if (65600 == OC_CONNTYPE)
-    {
-        query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
-    }
-    else
-    {
-        query << "coap://" << coapServerIP << coapServerResource;
-    }
-    return (InvokeOCDoResource(query, OC_REST_PUT, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS,
+    query << coapServerResource;
+    return (InvokeOCDoResource(query, &g_serverAddr, OC_REST_PUT, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS,
             putReqCB, NULL, 0));
 }
 
@@ -586,19 +637,10 @@ int InitPostRequest(OCQualityOfService qos)
     OCStackResult result;
     cout << "\nExecuting " << __func__;
     std::ostringstream query;
-
-    //TODO: Bug in RI layer.  Its returning 65600 instead of CT_ADAPTER_IP
-    if (65600 == OC_CONNTYPE)
-    {
-        query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
-    }
-    else
-    {
-        query << "coap://" << coapServerIP << coapServerResource;
-    }
+    query << coapServerResource;
 
     // First POST operation (to create an Light instance)
-    result = InvokeOCDoResource(query, OC_REST_POST,
+    result = InvokeOCDoResource(query, &g_serverAddr, OC_REST_POST,
                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
                                postReqCB, NULL, 0);
     if (OC_STACK_OK != result)
@@ -608,7 +650,7 @@ int InitPostRequest(OCQualityOfService qos)
     }
 
     // Second POST operation (to create an Light instance)
-    result = InvokeOCDoResource(query, OC_REST_POST,
+    result = InvokeOCDoResource(query, &g_serverAddr, OC_REST_POST,
                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
                                postReqCB, NULL, 0);
     if (OC_STACK_OK != result)
@@ -617,7 +659,7 @@ int InitPostRequest(OCQualityOfService qos)
     }
 
     // This POST operation will update the original resourced /a/light
-    return (InvokeOCDoResource(query, OC_REST_POST,
+    return (InvokeOCDoResource(query, &g_serverAddr, OC_REST_POST,
                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
                                postReqCB, NULL, 0));
 }
@@ -626,16 +668,7 @@ void* RequestDeleteDeathResourceTask(void* myqos)
 {
     sleep (30);//long enough to give the server time to finish deleting the resource.
     std::ostringstream query;
-
-    //TODO: Bug in RI layer.  Its returning 65600 instead of CT_ADAPTER_IP
-    if (65600 == OC_CONNTYPE)
-    {
-        query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
-    }
-    else
-    {
-        query << "coap://" << coapServerIP << coapServerResource;
-    }
+    query << coapServerResource;
 
     cout << "\nExecuting " << __func__;
 
@@ -650,7 +683,7 @@ void* RequestDeleteDeathResourceTask(void* myqos)
         qos = OC_HIGH_QOS;
     }
 
-    OCStackResult result = InvokeOCDoResource(query, OC_REST_DELETE,
+    OCStackResult result = InvokeOCDoResource(query, &g_serverAddr, OC_REST_DELETE,
                                qos,
                                deleteReqCB, NULL, 0);
 
@@ -666,20 +699,12 @@ int InitDeleteRequest(OCQualityOfService qos)
 {
     OCStackResult result;
     std::ostringstream query;
-    //TODO: Bug in RI layer.  Its returning 65600 instead of CT_ADAPTER_IP
-    if (65600 == OC_CONNTYPE)
-    {
-        query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
-    }
-    else
-    {
-        query << "coap://" << coapServerIP << coapServerResource;
-    }
+    query << coapServerResource;
 
     cout << "\nExecuting " << __func__;
 
     // First DELETE operation
-    result = InvokeOCDoResource(query, OC_REST_DELETE,
+    result = InvokeOCDoResource(query, &g_serverAddr, OC_REST_DELETE,
                                qos,
                                deleteReqCB, NULL, 0);
     if (OC_STACK_OK != result)
@@ -705,16 +730,7 @@ int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptio
 
     cout << "\nExecuting " << __func__;
     std::ostringstream query;
-
-    //TODO: Bug in RI layer.  Its returning 65600 instead of CT_ADAPTER_IP
-    if (65600 == OC_CONNTYPE)
-    {
-        query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
-    }
-    else
-    {
-        query << "coap://" << coapServerIP << coapServerResource;
-    }
+    query << coapServerResource;
 
     // ocserver is written to only process "power<X" query.
     if (getWithQuery)
@@ -739,12 +755,12 @@ int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptio
     }
     if (withVendorSpecificHeaderOptions)
     {
-        return (InvokeOCDoResource(query, OC_REST_GET,
+        return (InvokeOCDoResource(query, &g_serverAddr, OC_REST_GET,
                 (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, getReqCB, options, 2));
     }
     else
     {
-        return (InvokeOCDoResource(query, OC_REST_GET,
+        return (InvokeOCDoResource(query, &g_serverAddr, OC_REST_GET,
                 (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, getReqCB, NULL, 0));
     }
 }
@@ -755,34 +771,17 @@ int InitPlatformDiscovery(OCQualityOfService qos)
 
     OCStackResult ret;
     OCCallbackData cbData;
-    char szQueryUri[64] = { 0 };
+    char szQueryUri[MAX_QUERY_LENGTH] = { 0 };
+
+    snprintf(szQueryUri, sizeof (szQueryUri) - 1, PLATFORM_DISCOVERY_QUERY, g_discoveryAddr);
 
     cbData.cb = PlatformDiscoveryReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
 
-    if(UNICAST_DISCOVERY)
-    {
-        snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_PLATFORM_DISCOVERY_QUERY, unicastAddr);
-    }
-    else
-    {
-        strncpy(szQueryUri, MULTICAST_PLATFORM_DISCOVERY_QUERY, sizeof(szQueryUri) -1 );
-    }
-    szQueryUri[sizeof(szQueryUri) -1] = '\0';
-
-    if(UNICAST_DISCOVERY)
-    {
-        ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
-                (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
-    }
-    else
-    {
-
-        ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, OC_CONNTYPE,
-                        (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
-    }
-
+    ret = OCDoRequest(NULL, OC_REST_DISCOVER, szQueryUri, NULL, 0, CT_DEFAULT,
+                      (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS,
+                      &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
         cout << "\nOCStack device error";
@@ -797,33 +796,17 @@ int InitDeviceDiscovery(OCQualityOfService qos)
 
     OCStackResult ret;
     OCCallbackData cbData;
-    char szQueryUri[64] = { 0 };
+    char szQueryUri[MAX_QUERY_LENGTH] = { 0 };
+
+    snprintf(szQueryUri, sizeof (szQueryUri) - 1, DEVICE_DISCOVERY_QUERY, g_discoveryAddr);
 
     cbData.cb = DeviceDiscoveryReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
 
-    if(UNICAST_DISCOVERY)
-    {
-        snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DEVICE_DISCOVERY_QUERY, unicastAddr);
-    }
-    else
-    {
-        strncpy(szQueryUri, MULTICAST_DEVICE_DISCOVERY_QUERY, sizeof(szQueryUri) -1 );
-    }
-    szQueryUri[sizeof(szQueryUri) -1] = '\0';
-
-    if(UNICAST_DISCOVERY)
-    {
-        ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
-                (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
-    }
-    else
-    {
-        ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, OC_CONNTYPE,
-                        (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
-    }
-
+    ret = OCDoRequest(NULL, OC_REST_DISCOVER, szQueryUri, NULL, 0, CT_DEFAULT,
+                      (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS,
+                      &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
         cout << "\nOCStack device error";
@@ -836,54 +819,87 @@ int InitDiscovery(OCQualityOfService qos)
 {
     OCStackResult ret;
     OCCallbackData cbData;
-    /* Start a discovery query*/
-    char szQueryUri[64] = { 0 };
+    char szQueryUri[MAX_QUERY_LENGTH] = { 0 };
 
-    if (UNICAST_DISCOVERY)
-    {
-        snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_RESOURCE_DISCOVERY_QUERY, unicastAddr);
-    }
-    else
-    {
-        strcpy(szQueryUri, MULTICAST_RESOURCE_DISCOVERY_QUERY);
-    }
+    snprintf(szQueryUri, sizeof (szQueryUri) - 1, RESOURCE_DISCOVERY_QUERY, g_discoveryAddr);
 
     cbData.cb = discoveryReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
-    if(UNICAST_DISCOVERY)
+
+    ret = OCDoRequest(NULL, OC_REST_DISCOVER, szQueryUri, NULL, 0, CT_DEFAULT,
+                      (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS,
+                      &cbData, NULL, 0);
+    if (ret != OC_STACK_OK)
     {
-        ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
-                (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
+        cout << "\nOCStack resource error";
+    }
+    return ret;
+}
+
+void *GMainLoopThread(void *param)
+{
+
+    if (g_unicastDiscovery == 0 && g_testCase == TEST_DISCOVER_DEV_REQ)
+    {
+        InitDeviceDiscovery(OC_LOW_QOS);
+    }
+    else if (g_unicastDiscovery == 0 && g_testCase == TEST_DISCOVER_PLATFORM_REQ)
+    {
+        InitPlatformDiscovery(OC_LOW_QOS);
     }
     else
     {
-        ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, OC_CONNTYPE,
-                        (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
+        InitDiscovery(OC_LOW_QOS);
     }
-    if (ret != OC_STACK_OK)
+
+    while (!gQuitFlag)
     {
-        cout << "\nOCStack resource error";
+        if (OCProcess() != OC_STACK_OK)
+        {
+            cout << "\nOCStack process error";
+            return NULL;
+        }
+#ifndef ROUTING_GATEWAY
+        sleep(1);
+#endif
     }
-    return ret;
+
+    if (g_mainloop)
+    {
+        g_main_loop_quit(g_mainloop);
+    }
+    return NULL;
+}
+
+static FILE *client_fopen(const char */*path*/, const char *mode)
+{
+    return fopen(DEFAULT_DB_FILE_PATH, mode);
 }
 
 int main(int argc, char* argv[])
 {
     int opt;
 
+    g_mainloop = g_main_loop_new(NULL, FALSE);
+    if(!g_mainloop)
+    {
+        printf("g_main_loop_new failed\n");
+        return 0;
+    }
+
     while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
     {
         switch(opt)
         {
             case 'u':
-                UNICAST_DISCOVERY = atoi(optarg);
+                g_unicastDiscovery = atoi(optarg);
                 break;
             case 't':
-                TEST_CASE = atoi(optarg);
+                g_testCase = atoi(optarg);
                 break;
             case 'c':
-                CONNECTIVITY = atoi(optarg);
+                g_connectivity = atoi(optarg);
                 break;
             default:
                 PrintUsage();
@@ -891,9 +907,9 @@ int main(int argc, char* argv[])
         }
     }
 
-    if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
-            (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) ||
-            (CONNECTIVITY < CT_ADAPTER_DEFAULT || CONNECTIVITY >= MAX_CT))
+    if ((g_unicastDiscovery != 0 && g_unicastDiscovery != 1) ||
+            (g_testCase < TEST_DISCOVER_REQ || g_testCase >= MAX_TESTS) ||
+            (g_connectivity < CT_ADAPTER_DEFAULT || g_connectivity >= MAX_CT))
     {
         PrintUsage();
         return -1;
@@ -901,32 +917,44 @@ int main(int argc, char* argv[])
 
     cout << "\nEntering occlient main loop...\n";
 
-    /* Initialize OCStack*/
-    if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
+    OCPersistentStorage ps{ client_fopen, fread, fwrite, fclose, unlink };
+    OCRegisterPersistentStorageHandler(&ps);
+
+    if (OCInit1(OC_CLIENT_SERVER, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS) != OC_STACK_OK)
     {
         cout << "\nOCStack init error";
         return 0;
     }
 
-    if(CONNECTIVITY == CT_ADAPTER_DEFAULT || CONNECTIVITY == CT_IPV4)
+#ifdef ROUTING_GATEWAY
+    /*
+     * Before invoking Discover resource, we process the gateway requests
+     * and form the routing table.
+     */
+    for (int index = 0; index < MAX_NUM_GATEWAY_REQUEST; index++)
     {
-        OC_CONNTYPE = CT_ADAPTER_IP;
+        if (OCProcess() != OC_STACK_OK)
+        {
+            OIC_LOG(ERROR, TAG, "OCStack process error");
+            return 0;
+        }
+        usleep(SLEEP_DURATION);
     }
-    else if(CONNECTIVITY == CT_IPV6)
+#endif
+
+    if (g_connectivity == CT_ADAPTER_DEFAULT || g_connectivity == CT_IP)
     {
-        //TODO: Remove when IPv6 is available.
-        cout << "\nIPv6 is currently not supported !!!!";
-        PrintUsage();
-        return -1;
+        g_connType = CT_ADAPTER_IP;
     }
-    else if(CONNECTIVITY == CT_EDR)
+    else if(g_connectivity == CT_EDR)
     {
-        OC_CONNTYPE = CT_ADAPTER_RFCOMM_BTEDR;
-
-        cout << "\nSelected EDR Adapter!!! Device is scanning for OIC supported Servers....\n";
-        // Sleep is added as after initialization, EDR adapter needs to start scanning and find
-        // the devices.
-        sleep(10);
+        cout << "\nSelected EDR Adapter\n";
+        g_connType = CT_ADAPTER_RFCOMM_BTEDR;
+    }
+    else if(g_connectivity == CT_TCP)
+    {
+        cout << "\nSelected TCP Adapter\n";
+        g_connType = CT_ADAPTER_TCP;
     }
     else
     {
@@ -934,17 +962,19 @@ int main(int argc, char* argv[])
         PrintUsage();
     }
 
-    if (UNICAST_DISCOVERY)
+    g_discoveryAddr[0] = '\0';
+
+    if (g_unicastDiscovery)
     {
         cout << "\nEnter address of Server hosting resource as given below:";
         cout << "\nIP Adapter: 192.168.0.15:45454(IP:Port)";
         cout << "\nEDR/BLE Adapter: AB:BC:CD:DE:EF:FG(MAC Address)";
         cout << "\nInput:  ";
 
-        if (fgets(unicastAddr, MAX_ADDR_SIZE, stdin))
+        if (fgets(g_discoveryAddr, sizeof (g_discoveryAddr), stdin))
         {
             //Strip newline char from unicastAddr
-            StripNewLineChar(unicastAddr);
+            StripNewLineChar(g_discoveryAddr);
         }
         else
         {
@@ -953,33 +983,20 @@ int main(int argc, char* argv[])
         }
     }
 
-    if(UNICAST_DISCOVERY  == 0  && TEST_CASE == TEST_DISCOVER_DEV_REQ)
-    {
-        InitDeviceDiscovery(OC_LOW_QOS);
-    }
-    else if(UNICAST_DISCOVERY  == 0  && TEST_CASE == TEST_DISCOVER_PLATFORM_REQ)
-    {
-        InitPlatformDiscovery(OC_LOW_QOS);
-    }
-    else
-    {
-        InitDiscovery(OC_LOW_QOS);
-    }
 
     // Break from loop with Ctrl+C
+    OIC_LOG(INFO, TAG, "Entering occlient main loop...");
     signal(SIGINT, handleSigInt);
-    while (!gQuitFlag)
-    {
-
-        if (OCProcess() != OC_STACK_OK)
-        {
-            cout << "\nOCStack process error\n";
-            return 0;
-        }
 
-        sleep(2);
+    int result = pthread_create(&g_thread, NULL, GMainLoopThread, (void *)NULL);
+    if (result < 0)
+    {
+        printf("pthread_create failed in initialize\n");
+        return 0;
     }
 
+    g_main_loop_run(g_mainloop);
+
     cout << "\nExiting occlient main loop...\n";
 
     if (OCStop() != OC_STACK_OK)
@@ -990,35 +1007,6 @@ int main(int argc, char* argv[])
     return 0;
 }
 
-std::string getIPAddrTBServer(OCClientResponse * clientResponse)
-{
-    if (!clientResponse)
-    {
-        return "";
-    }
-    if (!clientResponse->addr)
-    {
-        return "";
-    }
-
-    return std::string(clientResponse->devAddr.addr);
-}
-
-std::string getPortTBServer(OCClientResponse * clientResponse)
-{
-    if (!clientResponse)
-    {
-        return "";
-    }
-    if (!clientResponse->addr)
-    {
-        return "";
-    }
-    std::ostringstream ss;
-    ss << clientResponse->devAddr.port;
-    return ss.str();
-}
-
 std::string getConnectivityType (OCConnectivityType connType)
 {
     switch (connType & CT_MASK_ADAPTER)
@@ -1043,16 +1031,13 @@ std::string getConnectivityType (OCConnectivityType connType)
     }
 }
 
-std::string getQueryStrForGetPut(OCClientResponse * clientResponse)
+std::string getQueryStrForGetPut(OCClientResponse * /*clientResponse*/)
 {
-
     return "/a/light";
 }
 
 void parseClientResponse(OCClientResponse * clientResponse)
 {
-    coapServerIP = getIPAddrTBServer(clientResponse);
-    coapServerPort = getPortTBServer(clientResponse);
     coapServerResource = getQueryStrForGetPut(clientResponse);
 }