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->rcvdVendorSpecificHeaderOptions
176 && clientResponse->numRcvdVendorSpecificHeaderOptions)
178 OC_LOG (INFO, TAG, "Received vendor specific options");
180 OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
181 for (i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
183 if (((OCHeaderOption) rcvdOptions[i]).protocolID == OC_COAP_ID)
185 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
186 ((OCHeaderOption)rcvdOptions[i]).optionID );
188 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
189 MAX_HEADER_OPTION_DATA_LENGTH);
196 OC_LOG(ERROR, TAG, "<====GET Callback fail to receive clientResponse====>\n");
198 return OC_STACK_DELETE_TRANSACTION;
202 * This is a function called back when a device is discovered
204 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
205 OCClientResponse * clientResponse)
207 if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
209 OC_LOG(INFO, TAG, "\n<====Callback Context for DISCOVERY query "
210 "received successfully====>");
214 OC_LOG(ERROR, TAG, "\n<====Callback Context for DISCOVERY fail====>");
220 "Device Discovered %s \n @ %s:%d\n",
221 clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
223 collectUniqueResource(clientResponse);
227 OC_LOG(ERROR, TAG, "<====DISCOVERY Callback fail to receive clientResponse====>\n");
229 return (UNICAST_DISCOVERY) ?
230 OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
233 int InitPutRequest(OCQualityOfService qos)
235 std::ostringstream query;
236 //Get most recently inserted resource
237 const ResourceNode * resource = getResource();
241 OC_LOG_V(ERROR, TAG, "Resource null, can't do PUT request\n");
244 query << "coap://" << resource->ip << ":" << resource->port << resource->uri ;
245 OC_LOG_V(INFO, TAG,"Executing InitPutRequest, Query: %s", query.str().c_str());
247 return (InvokeOCDoResource(query, OC_REST_PUT, resource->connType,
248 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
252 int InitPostRequest(OCQualityOfService qos)
254 OCStackResult result;
255 std::ostringstream query;
256 //Get most recently inserted resource
257 const ResourceNode * resource = getResource();
261 OC_LOG_V(ERROR, TAG, "Resource null, can't do POST request\n");
265 query << "coap://" << resource->ip << ":" << resource->port << resource->uri ;
266 OC_LOG_V(INFO, TAG,"Executing InitPostRequest, Query: %s", query.str().c_str());
268 // First POST operation (to create an LED instance)
269 result = InvokeOCDoResource(query, OC_REST_POST, resource->connType,
270 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
272 if (OC_STACK_OK != result)
274 // Error can happen if for example, network connectivity is down
275 OC_LOG(ERROR, TAG, "First POST call did not succeed");
278 // Second POST operation (to create an LED instance)
279 result = InvokeOCDoResource(query, OC_REST_POST, resource->connType,
280 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
282 if (OC_STACK_OK != result)
284 OC_LOG(ERROR, TAG, "Second POST call did not succeed");
287 // This POST operation will update the original resourced /a/led
288 return (InvokeOCDoResource(query, OC_REST_POST,resource->connType,
289 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
290 postReqCB, NULL, 0));
293 int InitGetRequest(OCQualityOfService qos)
295 std::ostringstream query;
296 //Get most recently inserted resource
297 const ResourceNode * resource = getResource();
301 OC_LOG_V(ERROR, TAG, "Resource null, can't do GET request\n");
304 query << "coap://" << resource->ip << ":" << resource->port << resource->uri ;
305 OC_LOG_V(INFO, TAG,"Executing InitGetRequest, Query: %s", query.str().c_str());
307 return (InvokeOCDoResource(query, OC_REST_GET, resource->connType,
308 (qos == OC_HIGH_QOS)?OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
314 OCCallbackData cbData;
315 /* Start a discovery query*/
316 char szQueryUri[64] = {};
317 if (UNICAST_DISCOVERY)
319 char ipv4addr[IPV4_ADDR_SIZE];
320 printf("Enter IPv4 address of the Server hosting "
321 "resource (Ex: 192.168.0.15)\n");
322 if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
324 //Strip newline char from ipv4addr
325 StripNewLineChar(ipv4addr);
326 snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
330 OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
331 return OC_STACK_INVALID_PARAM;
336 strcpy(szQueryUri, MULTICAST_RESOURCE_DISCOVERY_QUERY);
338 cbData.cb = discoveryReqCB;
339 cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
341 if (UNICAST_DISCOVERY)
343 ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
344 OC_LOW_QOS, &cbData, NULL, 0);
348 ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, CT_DEFAULT,
349 OC_LOW_QOS, &cbData, NULL, 0);
352 if (ret != OC_STACK_OK)
354 OC_LOG(ERROR, TAG, "OCStack resource error");
359 const char *getIPAddr(const OCClientResponse *clientResponse)
366 const OCDevAddr *devAddr = &clientResponse->devAddr;
367 char *ipaddr = (char *) OICCalloc(1, strlen(devAddr->addr));
370 snprintf(ipaddr, MAX_IP_ADDR_ST_SZ, "%s", devAddr->addr);
374 OC_LOG(ERROR, TAG, "Memory not allocated to ipaddr");
379 const char *getPort(const OCClientResponse *clientResponse)
387 if((port = (char *)OICCalloc(1, MAX_PORT_ST_SZ)))
389 snprintf(port, MAX_PORT_ST_SZ, "%d", clientResponse->devAddr.port);
393 OC_LOG(ERROR, TAG, "Memory not allocated to port");
398 int parseJSON(const char * resJSONPayload, char ** sid_c,
399 char *** uri_c, int * totalRes)
404 root = cJSON_Parse((char *)(resJSONPayload));
408 OC_LOG(ERROR, TAG, "JSON Parsing Error");
409 return OC_STACK_INVALID_JSON;
412 oc = cJSON_GetObjectItem(root,"oic");
415 OC_LOG(ERROR, TAG, "Invalid JSON : Missing oc object");
416 return OC_STACK_INVALID_JSON;
419 * totalRes = cJSON_GetArraySize(oc);
421 if(oc->type == cJSON_Array)
423 cJSON * resource = cJSON_GetArrayItem(oc, 0);
427 return OC_STACK_INVALID_JSON;
430 if (cJSON_GetObjectItem(resource, "sid"))
432 char * sid = cJSON_GetObjectItem(resource, "sid")->valuestring;
433 if((* sid_c = (char *)OICCalloc(1, strlen (sid) + 1)))
435 memcpy(* sid_c, sid, strlen(sid) + 1);
439 OC_LOG(ERROR, TAG, "Memory not allocated to sid");
440 return OC_STACK_NO_MEMORY;
445 OC_LOG(ERROR, TAG, "Invalid JSON : Missing sid object");
446 return OC_STACK_INVALID_JSON;
449 if(!(* uri_c = (char ** )OICMalloc ((* totalRes) * sizeof(char *))))
451 OC_LOG(ERROR, TAG, "Memory not allocated to uri_c array");
452 return OC_STACK_NO_MEMORY;
459 if (cJSON_GetObjectItem(resource, "href"))
461 char *uri= cJSON_GetObjectItem(resource, "href")->valuestring;
462 if(((*uri_c)[i] = (char *)OICCalloc(1, strlen (uri) + 1)))
464 memcpy((*uri_c)[i], uri, strlen(uri) + 1);
468 OC_LOG(ERROR, TAG, "Memory not allocated to uri");
469 return OC_STACK_NO_MEMORY;
472 if(i >= (* totalRes))
474 resource = cJSON_GetArrayItem(oc, i);
478 OC_LOG(ERROR, TAG, "Invalid JSON : Missing uri object");
479 return OC_STACK_INVALID_JSON;
485 return OC_STACK_INVALID_JSON;
486 OC_LOG(ERROR, TAG, "Invalid JSON : oc object type is not an array");
496 case TEST_DISCOVER_REQ:
498 case TEST_NON_CON_OP:
499 InitGetRequest(OC_LOW_QOS);
500 InitPutRequest(OC_LOW_QOS);
501 InitPostRequest(OC_LOW_QOS);
504 InitGetRequest(OC_HIGH_QOS);
505 InitPutRequest(OC_HIGH_QOS);
506 InitPostRequest(OC_HIGH_QOS);
516 void collectUniqueResource(const OCClientResponse * clientResponse)
523 if(parseJSON(clientResponse->resJSONPayload, & sid, & uri, &totalRes)
526 OC_LOG(ERROR, TAG, "Error while parsing JSON payload in OCClientResponse");
529 for (i = 0; i < totalRes; i++)
538 for(i = 0; i < totalRes; i++)
540 if(insertResource(sid, uri[i], clientResponse) == 1)
542 printf("%s%s%s%s\n",sid, ":", uri[i], " is new");
548 printf("%s%s%s%s\n\n",sid, ":", uri[i], " has been seen before");
553 for (i = 0; i < totalRes; i++)
560 /* This function searches for the resource(sid:uri) in the ResourceList.
561 * If the Resource is found in the list then it returns 0 else insert
562 * the resource to front of the list and returns 1.
564 int insertResource(const char * sid, char const * uri,
565 const OCClientResponse * clientResponse)
567 ResourceNode * iter = resourceList;
568 char * sid_cpy = OICStrdup(sid);
569 char * uri_cpy = OICStrdup(uri);
571 //Checking if the resource(sid:uri) is new
574 if((strcmp(iter->sid, sid) == 0) && (strcmp(iter->uri, uri) == 0))
586 //Creating new ResourceNode
587 if((iter = (ResourceNode *) OICMalloc(sizeof(ResourceNode))))
591 iter->ip = getIPAddr(clientResponse);
592 iter->port = getPort(clientResponse);
593 iter->connType = clientResponse->connType;
598 OC_LOG(ERROR, TAG, "Memory not allocated to ResourceNode");
604 //Adding new ResourceNode to front of the ResourceList
611 iter->next = resourceList;
617 void printResourceList()
621 printf("\nResource List\n");
624 printf("*****************************************************\n");
625 printf("sid = %s \n",iter->sid);
626 printf("uri = %s\n", iter->uri);
627 printf("ip = %s\n", iter->ip);
628 printf("port = %s\n", iter->port);
629 switch (iter->connType & CT_MASK_ADAPTER)
632 printf("connType = %s\n","IPv4");
634 case OC_ADAPTER_GATT_BTLE:
635 printf("connType = %s\n","BLE");
637 case OC_ADAPTER_RFCOMM_BTEDR:
638 printf("connType = %s\n","BT");
641 printf("connType = %s\n","Invalid connType");
644 printf("*****************************************************\n");
649 void freeResourceList()
651 OC_LOG(INFO, TAG, "Freeing ResourceNode List");
656 resourceList = resourceList->next;
657 OICFree((void *)temp->sid);
658 OICFree((void *)temp->uri);
659 OICFree((void *)temp->ip);
660 OICFree((void *)temp->port);
666 int main(int argc, char* argv[])
670 while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
675 UNICAST_DISCOVERY = atoi(optarg);
678 TEST_CASE = atoi(optarg);
681 OC_CONNTYPE = CT_ADAPTER_IP;
689 if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
690 (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
696 /* Initialize OCStack*/
697 if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
699 OC_LOG(ERROR, TAG, "OCStack init error");
705 // Break from loop with Ctrl+C
706 signal(SIGINT, handleSigInt);
710 if (OCProcess() != OC_STACK_OK)
712 OC_LOG(ERROR, TAG, "OCStack process error");
719 OC_LOG(INFO, TAG, "Exiting occlient main loop...");
720 if (OCStop() != OC_STACK_OK)
722 OC_LOG(ERROR, TAG, "OCStack stop error");