Imported Upstream version 0.9.2
[platform/upstream/iotivity.git] / resource / csdk / stack / samples / linux / SimpleClientServer / occlientbasicops.cpp
index 30f79d9..70c69a1 100644 (file)
 #include <unistd.h>
 #include <stdint.h>
 #include <sstream>
+#include <iostream>
 
 #include "ocstack.h"
 #include "logger.h"
 #include "occlientbasicops.h"
-#include "cJSON.h"
-#include "ocmalloc.h"
+#include "ocpayload.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
 
 #define MAX_IP_ADDR_ST_SZ  16 //string size of "155.255.255.255" (15 + 1)
 #define MAX_PORT_ST_SZ  6     //string size of "65535" (5 + 1)
 
-static int IPV4_ADDR_SIZE = 16;
+static int IPV4_ADDR_SIZE = 24;
 static int UNICAST_DISCOVERY = 0;
 static int TEST_CASE = 0;
+static int CONNECTIVITY = 0;
 
-static const char UNICAST_DISCOVERY_QUERY[] = "coap://%s:6298/oc/core";
-static std::string putPayload = "{\"state\":\"off\",\"power\":10}";
+static const char UNICAST_DISCOVERY_QUERY[] = "coap://%s/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 = OC_IPV4;
-static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oc/core";
+//The following variable determines the interface protocol (IP, etc)
+//to be used for sending unicast messages. Default set to IP.
+static OCConnectivityType OC_CONNTYPE = CT_ADAPTER_IP;
+static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oic/res";
 
 int gQuitFlag = 0;
 
@@ -60,6 +62,22 @@ void handleSigInt(int signum)
     }
 }
 
+OCPayload* putPayload()
+{
+    OCRepPayload* payload = OCRepPayloadCreate();
+
+    if(!payload)
+    {
+        std::cout << "Failed to create put payload object"<<std::endl;
+        std::exit(1);
+    }
+
+    OCRepPayloadSetPropInt(payload, "power", 15);
+    OCRepPayloadSetPropBool(payload, "state", true);
+
+    return (OCPayload*) payload;
+}
+
 static void PrintUsage()
 {
     OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
@@ -69,8 +87,8 @@ static void PrintUsage()
             " Initiate Nonconfirmable Get/Put/Post Requests");
     OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate "
             "Confirmable Get/Put/Post Requests");
-    OC_LOG(INFO, TAG, "-c <0|1> : IPv4/IPv6 (IPv6 not currently supported)");
-    OC_LOG(INFO, TAG, "Default connectivityType IPv4");
+    OC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
+    OC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
 }
 
 /*
@@ -93,7 +111,7 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query, OCMethod method,
     cbData.cd = NULL;
 
     ret = OCDoResource(NULL, method, query.str().c_str(), 0,
-        (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL,
+        (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL,
          connType, qos, &cbData, options, numOptions);
 
     if (ret != OC_STACK_OK)
@@ -108,9 +126,6 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query, OCMethod method,
 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle,
                                 OCClientResponse * clientResponse)
 {
-    uint8_t remoteIpAddr[4];
-    uint16_t remotePortNu;
-
     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
         OC_LOG(INFO, TAG, "<====Callback Context for PUT received successfully====>");
@@ -122,13 +137,8 @@ OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle,
 
     if(clientResponse)
     {
-        OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
-                            remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
-        OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
-
-        OC_LOG_V(INFO, TAG,"PUT Response: %s \nFrom %d.%d.%d.%d:%d\n",
-                 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
-                remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
+        OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
+        OC_LOG(INFO, TAG, PCF("=============> Put Response"));
     }
     else
     {
@@ -140,9 +150,6 @@ OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle,
 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle,
                           OCClientResponse *clientResponse)
 {
-    uint8_t remoteIpAddr[4];
-    uint16_t remotePortNu;
-
     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
         OC_LOG(INFO, TAG, "<====Callback Context for POST received successfully====>");
@@ -154,13 +161,8 @@ OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle,
 
     if(clientResponse)
     {
-        OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
-                            remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
-        OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
-
-        OC_LOG_V(INFO, TAG,"POST Response: %s \nFrom %d.%d.%d.%d:%d\n",
-                    clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
-                    remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
+        OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
+        OC_LOG(INFO, TAG, PCF("=============> Post Response"));
     }
     else
     {
@@ -173,9 +175,6 @@ OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle,
 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle,
                            OCClientResponse * clientResponse)
 {
-    uint8_t remoteIpAddr[4];
-    uint16_t remotePortNu;
-
     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
     {
         OC_LOG(INFO, TAG, "<====Callback Context for GET received successfully====>");
@@ -187,16 +186,12 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle,
 
     if (clientResponse)
     {
-        OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr, remoteIpAddr + 1,
-                remoteIpAddr + 2, remoteIpAddr + 3);
-        OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
-
-        OC_LOG_V(INFO, TAG,"Get Response: %s \nFrom %d.%d.%d.%d:%d\n",
-                clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
-                remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
+        OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
+        OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
+        OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
+        OC_LOG(INFO, TAG, PCF("=============> Get Response"));
 
-        if (clientResponse->rcvdVendorSpecificHeaderOptions
-                && clientResponse->numRcvdVendorSpecificHeaderOptions)
+        if (clientResponse->numRcvdVendorSpecificHeaderOptions > 0 )
         {
             OC_LOG (INFO, TAG, "Received vendor specific options");
             uint8_t i = 0;
@@ -227,8 +222,6 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle,
 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
         OCClientResponse * clientResponse)
 {
-    uint8_t remoteIpAddr[4];
-    uint16_t remotePortNu;
     if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
         OC_LOG(INFO, TAG, "\n<====Callback Context for DISCOVERY query "
@@ -241,14 +234,11 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
 
     if (clientResponse)
     {
-        OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
-                remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
-        OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
-
         OC_LOG_V(INFO, TAG,
-                "Device Discovered %s \n @ %d.%d.%d.%d:%d\n",
-                clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
-                remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
+                "Device =============> Discovered @ %s:%d",
+                clientResponse->devAddr.addr,
+                clientResponse->devAddr.port);
+        OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
 
         collectUniqueResource(clientResponse);
     }
@@ -347,8 +337,9 @@ int InitDiscovery()
     if (UNICAST_DISCOVERY)
     {
         char ipv4addr[IPV4_ADDR_SIZE];
-        printf("Enter IPv4 address of the Server hosting "
-               "resource (Ex: 192.168.0.15)\n");
+        OC_LOG(INFO, TAG, "Enter IP address with port of the Server hosting resource"\
+                    "(Ex: 192.168.0.15:1234) ");
+
         if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
         {
             //Strip newline char from ipv4addr
@@ -375,7 +366,7 @@ int InitDiscovery()
     }
     else
     {
-        ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, (OC_ALL),
+        ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, CT_DEFAULT,
                 OC_LOW_QOS, &cbData, NULL, 0);
     }
 
@@ -386,20 +377,18 @@ int InitDiscovery()
     return ret;
 }
 
-
-
-const char * getIPAddr(const OCClientResponse * clientResponse)
+const char *getIPAddr(const OCClientResponse *clientResponse)
 {
-    uint8_t a, b, c, d;
-   if(!clientResponse || 0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d))
+    if (!clientResponse)
     {
         return "";
     }
 
-    char * ipaddr = NULL;
-    if((ipaddr = (char *) OCCalloc(1, MAX_IP_ADDR_ST_SZ)))
+    const OCDevAddr *devAddr = &clientResponse->devAddr;
+    char *ipaddr = (char *) OICCalloc(1, strlen(devAddr->addr) +1);
+    if (ipaddr)
     {
-        snprintf(ipaddr, MAX_IP_ADDR_ST_SZ, "%d.%d.%d.%d", a,b,c,d);
+        snprintf(ipaddr, MAX_IP_ADDR_ST_SZ, "%s", devAddr->addr);
     }
     else
     {
@@ -408,18 +397,17 @@ const char * getIPAddr(const OCClientResponse * clientResponse)
     return ipaddr;
 }
 
-const char * getPort(const OCClientResponse * clientResponse)
+const char *getPort(const OCClientResponse *clientResponse)
 {
-    uint16_t p = 0;
-    if(!clientResponse || 0 != OCDevAddrToPort(clientResponse->addr, &p) )
+    if(!clientResponse)
     {
         return "";
     }
 
-    char * port = NULL;
-    if((port = (char *) OCCalloc(1, MAX_PORT_ST_SZ)))
+    char *port = NULL;
+    if((port = (char *)OICCalloc(1, MAX_PORT_ST_SZ)))
     {
-        snprintf(port, MAX_PORT_ST_SZ, "%d", p);
+        snprintf(port, MAX_PORT_ST_SZ, "%d", clientResponse->devAddr.port);
     }
     else
     {
@@ -428,102 +416,8 @@ const char * getPort(const OCClientResponse * clientResponse)
     return port;
 }
 
-int parseJSON(const char * resJSONPayload, char ** sid_c,
-              char *** uri_c, int * totalRes)
-{
-    cJSON * root = NULL;
-    cJSON * oc = NULL;
-
-    root = cJSON_Parse((char *)(resJSONPayload));
-
-    if (!root)
-    {
-        OC_LOG(ERROR, TAG, "JSON Parsing Error");
-        return OC_STACK_INVALID_JSON;
-    }
-
-    oc = cJSON_GetObjectItem(root,"oc");
-    if (!oc)
-    {
-        OC_LOG(ERROR, TAG, "Invalid JSON : Missing oc object");
-        return OC_STACK_INVALID_JSON;
-    }
-
-    * totalRes = cJSON_GetArraySize(oc);
-
-    if(oc->type == cJSON_Array)
-    {
-        cJSON * resource = cJSON_GetArrayItem(oc, 0);
-
-        if(!resource)
-        {
-            return OC_STACK_INVALID_JSON;
-        }
-
-        if (cJSON_GetObjectItem(resource, "sid"))
-        {
-            char * sid = cJSON_GetObjectItem(resource, "sid")->valuestring;
-            if((* sid_c = (char *)OCCalloc(1, strlen (sid) + 1)))
-            {
-                memcpy(* sid_c, sid, strlen(sid) + 1);
-            }
-            else
-            {
-                OC_LOG(ERROR, TAG, "Memory not allocated to sid");
-                return OC_STACK_NO_MEMORY;
-            }
-        }
-        else
-        {
-            OC_LOG(ERROR, TAG, "Invalid JSON : Missing sid object");
-            return OC_STACK_INVALID_JSON;
-        }
-
-        if(!(* uri_c =  (char ** )OCMalloc ((* totalRes) * sizeof(char **))))
-        {
-            OC_LOG(ERROR, TAG, "Memory not allocated to sid_c array");
-            return OC_STACK_NO_MEMORY;
-        }
-
-        int i = 0;
-
-        while(true)
-        {
-            if (cJSON_GetObjectItem(resource, "href"))
-            {
-                char *uri= cJSON_GetObjectItem(resource, "href")->valuestring;
-                if(((*uri_c)[i] = (char *)OCCalloc(1, strlen (uri) + 1)))
-                {
-                    memcpy((*uri_c)[i], uri, strlen(uri) + 1);
-                }
-                else
-                {
-                    OC_LOG(ERROR, TAG, "Memory not allocated to uri");
-                    return OC_STACK_NO_MEMORY;
-                }
-                i++;
-                if(i >= (* totalRes))
-                    break;
-                resource = cJSON_GetArrayItem(oc, i);
-            }
-            else
-            {
-               OC_LOG(ERROR, TAG, "Invalid JSON : Missing uri object");
-               return OC_STACK_INVALID_JSON;
-           }
-        }
-    }
-    else
-    {
-        return OC_STACK_INVALID_JSON;
-        OC_LOG(ERROR, TAG, "Invalid JSON : oc object type is not an array");
-    }
-    return OC_STACK_OK;
-}
-
 void queryResource()
 {
-    printf("\n");
     switch(TEST_CASE)
     {
         case TEST_DISCOVER_REQ:
@@ -542,43 +436,44 @@ void queryResource()
             PrintUsage();
             break;
     }
-    printf("\n");
 }
 
 
 void collectUniqueResource(const OCClientResponse * clientResponse)
 {
-    char * sid = NULL;
-    char ** uri = NULL;
-    int totalRes = 0;
+    OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
+    char sidStr[UUID_LENGTH];
 
-    if(parseJSON(clientResponse->resJSONPayload, & sid, & uri, &totalRes)
-            != OC_STACK_OK)
-    {
-        OC_LOG(ERROR, TAG, "Error while parsing JSON payload in OCClientResponse");
-        OCFree(sid);
-        OCFree(uri);
-        return;
-    }
+    while(res) {
 
-    int i;
-    for(i = 0; i < totalRes; i++)
-    {
-        if(insertResource(sid, uri[i], clientResponse) == 1)
+        int ret = snprintf(sidStr, UUID_LENGTH,
+                "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
+                res->sid[0], res->sid[1], res->sid[2], res->sid[3],
+                res->sid[4], res->sid[5], res->sid[6], res->sid[7],
+                res->sid[8], res->sid[9], res->sid[10], res->sid[11],
+                res->sid[12], res->sid[13], res->sid[14], res->sid[15]
+                );
+
+        if (ret == UUID_LENGTH - 1)
         {
-            printf("%s%s%s%s\n",sid, ":", uri[i], " is new");
-            printResourceList();
-            queryResource();
+            if(insertResource(sidStr, res->uri, clientResponse) == 1)
+            {
+                OC_LOG_V(INFO,TAG,"%s%s%s%s\n",sidStr, ":", res->uri, " is new");
+                printResourceList();
+                queryResource();
+            }
+            else {
+                OC_LOG_V(INFO,TAG,"%s%s%s%s\n",sidStr, ":", res->uri, " is old");
+            }
         }
         else
         {
-            printf("%s%s%s%s\n\n",sid, ":", uri[i], " has been seen before");
+            OC_LOG(ERROR, TAG, "Could Not Retrieve the Server ID");
         }
-    }
 
-    OCFree(sid);
-    OCFree(uri);
- }
+        res = res->next;
+    }
+}
 
 /* This function searches for the resource(sid:uri) in the ResourceList.
  * If the Resource is found in the list then it returns 0 else insert
@@ -588,12 +483,16 @@ int insertResource(const char * sid, char const * uri,
             const OCClientResponse * clientResponse)
 {
     ResourceNode * iter = resourceList;
+    char * sid_cpy =  OICStrdup(sid);
+    char * uri_cpy = OICStrdup(uri);
 
     //Checking if the resource(sid:uri) is new
     while(iter)
     {
         if((strcmp(iter->sid, sid) == 0) && (strcmp(iter->uri, uri) == 0))
         {
+            OICFree(sid_cpy);
+            OICFree(uri_cpy);
             return 0;
         }
         else
@@ -603,10 +502,10 @@ int insertResource(const char * sid, char const * uri,
     }
 
     //Creating new ResourceNode
-    if((iter = (ResourceNode *) OCMalloc(sizeof(ResourceNode))))
+    if((iter = (ResourceNode *) OICMalloc(sizeof(ResourceNode))))
     {
-        iter->sid = sid;
-        iter->uri = uri;
+        iter->sid = sid_cpy;
+        iter->uri = uri_cpy;
         iter->ip = getIPAddr(clientResponse);
         iter->port = getPort(clientResponse);
         iter->connType = clientResponse->connType;
@@ -615,6 +514,8 @@ int insertResource(const char * sid, char const * uri,
     else
     {
         OC_LOG(ERROR, TAG, "Memory not allocated to ResourceNode");
+        OICFree(sid_cpy);
+        OICFree(uri_cpy);
         return -1;
     }
 
@@ -635,37 +536,30 @@ void printResourceList()
 {
     ResourceNode * iter;
     iter = resourceList;
-    printf("\nResource List\n");
+    OC_LOG(INFO, TAG, "Resource List: ");
     while(iter)
     {
-        printf("*****************************************************\n");
-        printf("sid = %s \n",iter->sid);
-        printf("uri = %s\n", iter->uri);
-        printf("ip = %s\n", iter->ip);
-        printf("port = %s\n", iter->port);
-        switch (iter->connType)
+        OC_LOG(INFO, TAG, "*****************************************************");
+        OC_LOG_V(INFO, TAG, "sid = %s",iter->sid);
+        OC_LOG_V(INFO, TAG, "uri = %s", iter->uri);
+        OC_LOG_V(INFO, TAG, "ip = %s", iter->ip);
+        OC_LOG_V(INFO, TAG, "port = %s", iter->port);
+        switch (iter->connType & CT_MASK_ADAPTER)
         {
-            case OC_IPV4:
-                printf("connType = %s\n","IPv4");
-                break;
-            case OC_IPV6:
-                // TODO: Allow IPv6 when support is added
-                printf("IPv6 not currently supported, default to IPv4\n");
-                //printf("connType = %s\n","IPv6");
-                printf("connType = %s\n","IPv4");
+            case CT_ADAPTER_IP:
+                OC_LOG(INFO, TAG, "connType = Default (IPv4)");
                 break;
-            case OC_LE:
-                printf("connType = %s\n","BLE");
+            case OC_ADAPTER_GATT_BTLE:
+                OC_LOG(INFO, TAG, "connType = BLE");
                 break;
-            case OC_EDR:
-                printf("connType = %s\n","BT");
+            case OC_ADAPTER_RFCOMM_BTEDR:
+                OC_LOG(INFO, TAG, "connType = BT");
                 break;
-            case OC_ALL:
             default:
-                printf("connType = %s\n","Invalid connType");
+                OC_LOG(INFO, TAG, "connType = Invalid connType");
                 break;
         }
-        printf("*****************************************************\n");
+        OC_LOG(INFO, TAG, "*****************************************************");
         iter = iter->next;
     }
 }
@@ -676,14 +570,16 @@ void freeResourceList()
     ResourceNode * temp;
     while(resourceList)
     {
+
         temp = resourceList;
         resourceList = resourceList->next;
-        OCFree((void *)temp->sid);
-        OCFree((void *)temp->uri);
-        OCFree((void *)temp->ip);
-        OCFree((void *)temp->port);
-        OCFree(temp);
+        OICFree((void *)temp->sid);
+        OICFree((void *)temp->uri);
+        OICFree((void *)temp->ip);
+        OICFree((void *)temp->port);
+        OICFree(temp);
     }
+    resourceList = NULL;
 }
 
 int main(int argc, char* argv[])
@@ -701,10 +597,8 @@ int main(int argc, char* argv[])
                 TEST_CASE = atoi(optarg);
                 break;
             case 'c':
-                // TODO: re-enable IPv4/IPv6 command line selection when IPv6 is supported
-                // OC_CONNTYPE = OCConnectivityType(atoi(optarg));
-                OC_CONNTYPE = OC_IPV4;
-                OC_LOG(INFO, TAG, "Using default IPv4, IPv6 not currently supported.");
+
+                CONNECTIVITY = atoi(optarg);
                 break;
             default:
                 PrintUsage();
@@ -713,7 +607,8 @@ int main(int argc, char* argv[])
     }
 
     if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
-            (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
+        (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) ||
+        (CONNECTIVITY < CT_ADAPTER_DEFAULT || CONNECTIVITY >= MAX_CT))
     {
         PrintUsage();
         return -1;
@@ -726,6 +621,16 @@ int main(int argc, char* argv[])
         return 0;
     }
 
+    if(CONNECTIVITY == CT_ADAPTER_DEFAULT || CONNECTIVITY ==  CT_IP)
+    {
+        OC_CONNTYPE =  CT_ADAPTER_IP;//CT_DEFAULT;
+    }
+    else
+    {
+        OC_LOG(INFO, TAG, "Default Connectivity type selected");
+        PrintUsage();
+    }
+
     InitDiscovery();
 
     // Break from loop with Ctrl+C