1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 // http://www.apache.org/licenses/LICENSE-2.0
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
18 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
30 #include "occlientbasicops.h"
32 #include "oic_malloc.h"
33 #include "oic_string.h"
35 #define MAX_IP_ADDR_ST_SZ 16 //string size of "155.255.255.255" (15 + 1)
36 #define MAX_PORT_ST_SZ 6 //string size of "65535" (5 + 1)
38 static int IPV4_ADDR_SIZE = 16;
39 static int UNICAST_DISCOVERY = 0;
40 static int TEST_CASE = 0;
42 static const char UNICAST_DISCOVERY_QUERY[] = "coap://%s:6298/oic/res";
43 static std::string putPayload = "{\"oic\":[{\"rep\":{\"power\":15,\"state\":true}}]}";
45 //The following variable determines the interface protocol (IP, etc)
46 //to be used for sending unicast messages. Default set to IP.
47 static OCConnectivityType OC_CONNTYPE = CT_ADAPTER_IP;
48 static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oic/res";
52 struct ResourceNode *resourceList;
54 * SIGINT handler: set gQuitFlag to 1 for graceful termination
56 void handleSigInt(int signum)
64 static void PrintUsage()
66 OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
67 OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
68 OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
69 OC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
70 " Initiate Nonconfirmable Get/Put/Post Requests");
71 OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate "
72 "Confirmable Get/Put/Post Requests");
73 OC_LOG(INFO, TAG, "-c <0|1> : IPv4/IPv6 (IPv6 not currently supported)");
74 OC_LOG(INFO, TAG, "Default connectivityType IPv4");
78 * Returns the first resource in the list
80 const ResourceNode * getResource()
85 OCStackResult InvokeOCDoResource(std::ostringstream &query, OCMethod method,
86 OCConnectivityType connType, OCQualityOfService qos,
87 OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
90 OCCallbackData cbData;
93 cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
96 ret = OCDoResource(NULL, method, query.str().c_str(), 0,
97 (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL,
98 connType, qos, &cbData, options, numOptions);
100 if (ret != OC_STACK_OK)
102 OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d",
109 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle,
110 OCClientResponse * clientResponse)
112 if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
114 OC_LOG(INFO, TAG, "<====Callback Context for PUT received successfully====>");
118 OC_LOG(ERROR, TAG, "<====Callback Context for PUT fail====>");
123 OC_LOG_V(INFO, TAG,"PUT Response: %s \nFrom %s:%d\n",
124 clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
128 OC_LOG(ERROR, TAG, "<====PUT Callback fail to receive clientResponse====>\n");
130 return OC_STACK_DELETE_TRANSACTION;
133 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle,
134 OCClientResponse *clientResponse)
136 if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
138 OC_LOG(INFO, TAG, "<====Callback Context for POST received successfully====>");
142 OC_LOG(ERROR, TAG, "<====Callback Context for POST fail====>");
147 OC_LOG_V(INFO, TAG,"POST Response: %s \nFrom %s:%d\n",
148 clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
152 OC_LOG(ERROR, TAG, "<====POST Callback fail to receive clientResponse====>\n");
155 return OC_STACK_DELETE_TRANSACTION;
158 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle,
159 OCClientResponse * clientResponse)
161 if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
163 OC_LOG(INFO, TAG, "<====Callback Context for GET received successfully====>");
167 OC_LOG(ERROR, TAG, "<====Callback Context for GET fail====>");
172 OC_LOG_V(INFO, TAG,"Get Response: %s \nFrom %s:%d\n",
173 clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
175 if (clientResponse->numRcvdVendorSpecificHeaderOptions > 0 )
177 OC_LOG (INFO, TAG, "Received vendor specific options");
179 OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
180 for (i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
182 if (((OCHeaderOption) rcvdOptions[i]).protocolID == OC_COAP_ID)
184 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
185 ((OCHeaderOption)rcvdOptions[i]).optionID );
187 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
188 MAX_HEADER_OPTION_DATA_LENGTH);
195 OC_LOG(ERROR, TAG, "<====GET Callback fail to receive clientResponse====>\n");
197 return OC_STACK_DELETE_TRANSACTION;
201 * This is a function called back when a device is discovered
203 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
204 OCClientResponse * clientResponse)
206 if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
208 OC_LOG(INFO, TAG, "\n<====Callback Context for DISCOVERY query "
209 "received successfully====>");
213 OC_LOG(ERROR, TAG, "\n<====Callback Context for DISCOVERY fail====>");
219 "Device Discovered %s \n @ %s:%d\n",
220 clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
222 collectUniqueResource(clientResponse);
226 OC_LOG(ERROR, TAG, "<====DISCOVERY Callback fail to receive clientResponse====>\n");
228 return (UNICAST_DISCOVERY) ?
229 OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
232 int InitPutRequest(OCQualityOfService qos)
234 std::ostringstream query;
235 //Get most recently inserted resource
236 const ResourceNode * resource = getResource();
240 OC_LOG_V(ERROR, TAG, "Resource null, can't do PUT request\n");
243 query << "coap://" << resource->ip << ":" << resource->port << resource->uri ;
244 OC_LOG_V(INFO, TAG,"Executing InitPutRequest, Query: %s", query.str().c_str());
246 return (InvokeOCDoResource(query, OC_REST_PUT, resource->connType,
247 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
251 int InitPostRequest(OCQualityOfService qos)
253 OCStackResult result;
254 std::ostringstream query;
255 //Get most recently inserted resource
256 const ResourceNode * resource = getResource();
260 OC_LOG_V(ERROR, TAG, "Resource null, can't do POST request\n");
264 query << "coap://" << resource->ip << ":" << resource->port << resource->uri ;
265 OC_LOG_V(INFO, TAG,"Executing InitPostRequest, Query: %s", query.str().c_str());
267 // First POST operation (to create an LED instance)
268 result = InvokeOCDoResource(query, OC_REST_POST, resource->connType,
269 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
271 if (OC_STACK_OK != result)
273 // Error can happen if for example, network connectivity is down
274 OC_LOG(ERROR, TAG, "First POST call did not succeed");
277 // Second POST operation (to create an LED instance)
278 result = InvokeOCDoResource(query, OC_REST_POST, resource->connType,
279 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
281 if (OC_STACK_OK != result)
283 OC_LOG(ERROR, TAG, "Second POST call did not succeed");
286 // This POST operation will update the original resourced /a/led
287 return (InvokeOCDoResource(query, OC_REST_POST,resource->connType,
288 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
289 postReqCB, NULL, 0));
292 int InitGetRequest(OCQualityOfService qos)
294 std::ostringstream query;
295 //Get most recently inserted resource
296 const ResourceNode * resource = getResource();
300 OC_LOG_V(ERROR, TAG, "Resource null, can't do GET request\n");
303 query << "coap://" << resource->ip << ":" << resource->port << resource->uri ;
304 OC_LOG_V(INFO, TAG,"Executing InitGetRequest, Query: %s", query.str().c_str());
306 return (InvokeOCDoResource(query, OC_REST_GET, resource->connType,
307 (qos == OC_HIGH_QOS)?OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
313 OCCallbackData cbData;
314 /* Start a discovery query*/
315 char szQueryUri[64] = {};
316 if (UNICAST_DISCOVERY)
318 char ipv4addr[IPV4_ADDR_SIZE];
319 printf("Enter IPv4 address of the Server hosting "
320 "resource (Ex: 192.168.0.15)\n");
321 if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
323 //Strip newline char from ipv4addr
324 StripNewLineChar(ipv4addr);
325 snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
329 OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
330 return OC_STACK_INVALID_PARAM;
335 strcpy(szQueryUri, MULTICAST_RESOURCE_DISCOVERY_QUERY);
337 cbData.cb = discoveryReqCB;
338 cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
340 if (UNICAST_DISCOVERY)
342 ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
343 OC_LOW_QOS, &cbData, NULL, 0);
347 ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, CT_DEFAULT,
348 OC_LOW_QOS, &cbData, NULL, 0);
351 if (ret != OC_STACK_OK)
353 OC_LOG(ERROR, TAG, "OCStack resource error");
358 const char *getIPAddr(const OCClientResponse *clientResponse)
365 const OCDevAddr *devAddr = &clientResponse->devAddr;
366 char *ipaddr = (char *) OICCalloc(1, strlen(devAddr->addr));
369 snprintf(ipaddr, MAX_IP_ADDR_ST_SZ, "%s", devAddr->addr);
373 OC_LOG(ERROR, TAG, "Memory not allocated to ipaddr");
378 const char *getPort(const OCClientResponse *clientResponse)
386 if((port = (char *)OICCalloc(1, MAX_PORT_ST_SZ)))
388 snprintf(port, MAX_PORT_ST_SZ, "%d", clientResponse->devAddr.port);
392 OC_LOG(ERROR, TAG, "Memory not allocated to port");
397 int parseJSON(const char * resJSONPayload, char ** sid_c,
398 char *** uri_c, int * totalRes)
403 root = cJSON_Parse((char *)(resJSONPayload));
407 OC_LOG(ERROR, TAG, "JSON Parsing Error");
408 return OC_STACK_INVALID_JSON;
411 oc = cJSON_GetObjectItem(root,"oic");
414 OC_LOG(ERROR, TAG, "Invalid JSON : Missing oc object");
415 return OC_STACK_INVALID_JSON;
418 * totalRes = cJSON_GetArraySize(oc);
420 if(oc->type == cJSON_Array)
422 cJSON * resource = cJSON_GetArrayItem(oc, 0);
426 return OC_STACK_INVALID_JSON;
429 if (cJSON_GetObjectItem(resource, "sid"))
431 char * sid = cJSON_GetObjectItem(resource, "sid")->valuestring;
432 if((* sid_c = (char *)OICCalloc(1, strlen (sid) + 1)))
434 memcpy(* sid_c, sid, strlen(sid) + 1);
438 OC_LOG(ERROR, TAG, "Memory not allocated to sid");
439 return OC_STACK_NO_MEMORY;
444 OC_LOG(ERROR, TAG, "Invalid JSON : Missing sid object");
445 return OC_STACK_INVALID_JSON;
448 if(!(* uri_c = (char ** )OICMalloc ((* totalRes) * sizeof(char *))))
450 OC_LOG(ERROR, TAG, "Memory not allocated to uri_c array");
451 return OC_STACK_NO_MEMORY;
458 if (cJSON_GetObjectItem(resource, "href"))
460 char *uri= cJSON_GetObjectItem(resource, "href")->valuestring;
461 if(((*uri_c)[i] = (char *)OICCalloc(1, strlen (uri) + 1)))
463 memcpy((*uri_c)[i], uri, strlen(uri) + 1);
467 OC_LOG(ERROR, TAG, "Memory not allocated to uri");
468 return OC_STACK_NO_MEMORY;
471 if(i >= (* totalRes))
473 resource = cJSON_GetArrayItem(oc, i);
477 OC_LOG(ERROR, TAG, "Invalid JSON : Missing uri object");
478 return OC_STACK_INVALID_JSON;
484 return OC_STACK_INVALID_JSON;
485 OC_LOG(ERROR, TAG, "Invalid JSON : oc object type is not an array");
495 case TEST_DISCOVER_REQ:
497 case TEST_NON_CON_OP:
498 InitGetRequest(OC_LOW_QOS);
499 InitPutRequest(OC_LOW_QOS);
500 InitPostRequest(OC_LOW_QOS);
503 InitGetRequest(OC_HIGH_QOS);
504 InitPutRequest(OC_HIGH_QOS);
505 InitPostRequest(OC_HIGH_QOS);
515 void collectUniqueResource(const OCClientResponse * clientResponse)
522 if(parseJSON(clientResponse->resJSONPayload, & sid, & uri, &totalRes)
525 OC_LOG(ERROR, TAG, "Error while parsing JSON payload in OCClientResponse");
528 for (i = 0; i < totalRes; i++)
537 for(i = 0; i < totalRes; i++)
539 if(insertResource(sid, uri[i], clientResponse) == 1)
541 printf("%s%s%s%s\n",sid, ":", uri[i], " is new");
547 printf("%s%s%s%s\n\n",sid, ":", uri[i], " has been seen before");
552 for (i = 0; i < totalRes; i++)
559 /* This function searches for the resource(sid:uri) in the ResourceList.
560 * If the Resource is found in the list then it returns 0 else insert
561 * the resource to front of the list and returns 1.
563 int insertResource(const char * sid, char const * uri,
564 const OCClientResponse * clientResponse)
566 ResourceNode * iter = resourceList;
567 char * sid_cpy = OICStrdup(sid);
568 char * uri_cpy = OICStrdup(uri);
570 //Checking if the resource(sid:uri) is new
573 if((strcmp(iter->sid, sid) == 0) && (strcmp(iter->uri, uri) == 0))
585 //Creating new ResourceNode
586 if((iter = (ResourceNode *) OICMalloc(sizeof(ResourceNode))))
590 iter->ip = getIPAddr(clientResponse);
591 iter->port = getPort(clientResponse);
592 iter->connType = clientResponse->connType;
597 OC_LOG(ERROR, TAG, "Memory not allocated to ResourceNode");
603 //Adding new ResourceNode to front of the ResourceList
610 iter->next = resourceList;
616 void printResourceList()
620 printf("\nResource List\n");
623 printf("*****************************************************\n");
624 printf("sid = %s \n",iter->sid);
625 printf("uri = %s\n", iter->uri);
626 printf("ip = %s\n", iter->ip);
627 printf("port = %s\n", iter->port);
628 switch (iter->connType & CT_MASK_ADAPTER)
631 printf("connType = %s\n","IPv4");
633 case OC_ADAPTER_GATT_BTLE:
634 printf("connType = %s\n","BLE");
636 case OC_ADAPTER_RFCOMM_BTEDR:
637 printf("connType = %s\n","BT");
640 printf("connType = %s\n","Invalid connType");
643 printf("*****************************************************\n");
648 void freeResourceList()
650 OC_LOG(INFO, TAG, "Freeing ResourceNode List");
655 resourceList = resourceList->next;
656 OICFree((void *)temp->sid);
657 OICFree((void *)temp->uri);
658 OICFree((void *)temp->ip);
659 OICFree((void *)temp->port);
665 int main(int argc, char* argv[])
669 while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
674 UNICAST_DISCOVERY = atoi(optarg);
677 TEST_CASE = atoi(optarg);
680 OC_CONNTYPE = CT_ADAPTER_IP;
688 if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
689 (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
695 /* Initialize OCStack*/
696 if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
698 OC_LOG(ERROR, TAG, "OCStack init error");
704 // Break from loop with Ctrl+C
705 signal(SIGINT, handleSigInt);
709 if (OCProcess() != OC_STACK_OK)
711 OC_LOG(ERROR, TAG, "OCStack process error");
718 OC_LOG(INFO, TAG, "Exiting occlient main loop...");
719 if (OCStop() != OC_STACK_OK)
721 OC_LOG(ERROR, TAG, "OCStack stop error");