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"
34 #define MAX_IP_ADDR_ST_SZ 16 //string size of "155.255.255.255" (15 + 1)
35 #define MAX_PORT_ST_SZ 6 //string size of "65535" (5 + 1)
37 static int IPV4_ADDR_SIZE = 16;
38 static int UNICAST_DISCOVERY = 0;
39 static int TEST_CASE = 0;
41 static const char UNICAST_DISCOVERY_QUERY[] = "coap://%s:6298/oic/res";
42 static std::string putPayload = "{\"oic\":[{\"rep\":{\"power\":15,\"state\":true}}]}";
44 //The following variable determines the interface protocol (IPv4, IPv6, etc)
45 //to be used for sending unicast messages. Default set to IPv4.
46 static OCConnectivityType OC_CONNTYPE = OC_IPV4;
47 static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oic/res";
51 struct ResourceNode *resourceList;
53 * SIGINT handler: set gQuitFlag to 1 for graceful termination
55 void handleSigInt(int signum)
63 static void PrintUsage()
65 OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
66 OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
67 OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
68 OC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
69 " Initiate Nonconfirmable Get/Put/Post Requests");
70 OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate "
71 "Confirmable Get/Put/Post Requests");
72 OC_LOG(INFO, TAG, "-c <0|1> : IPv4/IPv6 (IPv6 not currently supported)");
73 OC_LOG(INFO, TAG, "Default connectivityType IPv4");
77 * Returns the first resource in the list
79 const ResourceNode * getResource()
84 OCStackResult InvokeOCDoResource(std::ostringstream &query, OCMethod method,
85 OCConnectivityType connType, OCQualityOfService qos,
86 OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
89 OCCallbackData cbData;
92 cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
95 ret = OCDoResource(NULL, method, query.str().c_str(), 0,
96 (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL,
97 connType, qos, &cbData, options, numOptions);
99 if (ret != OC_STACK_OK)
101 OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d",
108 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle,
109 OCClientResponse * clientResponse)
111 uint8_t remoteIpAddr[4];
112 uint16_t remotePortNu;
114 if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
116 OC_LOG(INFO, TAG, "<====Callback Context for PUT received successfully====>");
120 OC_LOG(ERROR, TAG, "<====Callback Context for PUT fail====>");
125 OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
126 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
127 OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
129 OC_LOG_V(INFO, TAG,"PUT Response: %s \nFrom %d.%d.%d.%d:%d\n",
130 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
131 remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
135 OC_LOG(ERROR, TAG, "<====PUT Callback fail to receive clientResponse====>\n");
137 return OC_STACK_DELETE_TRANSACTION;
140 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle,
141 OCClientResponse *clientResponse)
143 uint8_t remoteIpAddr[4];
144 uint16_t remotePortNu;
146 if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
148 OC_LOG(INFO, TAG, "<====Callback Context for POST received successfully====>");
152 OC_LOG(ERROR, TAG, "<====Callback Context for POST fail====>");
157 OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
158 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
159 OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
161 OC_LOG_V(INFO, TAG,"POST Response: %s \nFrom %d.%d.%d.%d:%d\n",
162 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
163 remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
167 OC_LOG(ERROR, TAG, "<====POST Callback fail to receive clientResponse====>\n");
170 return OC_STACK_DELETE_TRANSACTION;
173 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle,
174 OCClientResponse * clientResponse)
176 uint8_t remoteIpAddr[4];
177 uint16_t remotePortNu;
179 if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
181 OC_LOG(INFO, TAG, "<====Callback Context for GET received successfully====>");
185 OC_LOG(ERROR, TAG, "<====Callback Context for GET fail====>");
190 OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr, remoteIpAddr + 1,
191 remoteIpAddr + 2, remoteIpAddr + 3);
192 OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
194 OC_LOG_V(INFO, TAG,"Get Response: %s \nFrom %d.%d.%d.%d:%d\n",
195 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
196 remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
198 if (clientResponse->rcvdVendorSpecificHeaderOptions
199 && clientResponse->numRcvdVendorSpecificHeaderOptions)
201 OC_LOG (INFO, TAG, "Received vendor specific options");
203 OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
204 for (i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
206 if (((OCHeaderOption) rcvdOptions[i]).protocolID == OC_COAP_ID)
208 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
209 ((OCHeaderOption)rcvdOptions[i]).optionID );
211 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
212 MAX_HEADER_OPTION_DATA_LENGTH);
219 OC_LOG(ERROR, TAG, "<====GET Callback fail to receive clientResponse====>\n");
221 return OC_STACK_DELETE_TRANSACTION;
225 * This is a function called back when a device is discovered
227 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
228 OCClientResponse * clientResponse)
230 uint8_t remoteIpAddr[4];
231 uint16_t remotePortNu;
232 if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
234 OC_LOG(INFO, TAG, "\n<====Callback Context for DISCOVERY query "
235 "received successfully====>");
239 OC_LOG(ERROR, TAG, "\n<====Callback Context for DISCOVERY fail====>");
244 OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
245 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
246 OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
249 "Device Discovered %s \n @ %d.%d.%d.%d:%d\n",
250 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
251 remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
253 collectUniqueResource(clientResponse);
257 OC_LOG(ERROR, TAG, "<====DISCOVERY Callback fail to receive clientResponse====>\n");
259 return (UNICAST_DISCOVERY) ?
260 OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
263 int InitPutRequest(OCQualityOfService qos)
265 std::ostringstream query;
266 //Get most recently inserted resource
267 const ResourceNode * resource = getResource();
271 OC_LOG_V(ERROR, TAG, "Resource null, can't do PUT request\n");
274 query << "coap://" << resource->ip << ":" << resource->port << resource->uri ;
275 OC_LOG_V(INFO, TAG,"Executing InitPutRequest, Query: %s", query.str().c_str());
277 return (InvokeOCDoResource(query, OC_REST_PUT, resource->connType,
278 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
282 int InitPostRequest(OCQualityOfService qos)
284 OCStackResult result;
285 std::ostringstream query;
286 //Get most recently inserted resource
287 const ResourceNode * resource = getResource();
291 OC_LOG_V(ERROR, TAG, "Resource null, can't do POST request\n");
295 query << "coap://" << resource->ip << ":" << resource->port << resource->uri ;
296 OC_LOG_V(INFO, TAG,"Executing InitPostRequest, Query: %s", query.str().c_str());
298 // First POST operation (to create an LED instance)
299 result = InvokeOCDoResource(query, OC_REST_POST, resource->connType,
300 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
302 if (OC_STACK_OK != result)
304 // Error can happen if for example, network connectivity is down
305 OC_LOG(ERROR, TAG, "First POST call did not succeed");
308 // Second POST operation (to create an LED instance)
309 result = InvokeOCDoResource(query, OC_REST_POST, resource->connType,
310 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
312 if (OC_STACK_OK != result)
314 OC_LOG(ERROR, TAG, "Second POST call did not succeed");
317 // This POST operation will update the original resourced /a/led
318 return (InvokeOCDoResource(query, OC_REST_POST,resource->connType,
319 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
320 postReqCB, NULL, 0));
323 int InitGetRequest(OCQualityOfService qos)
325 std::ostringstream query;
326 //Get most recently inserted resource
327 const ResourceNode * resource = getResource();
331 OC_LOG_V(ERROR, TAG, "Resource null, can't do GET request\n");
334 query << "coap://" << resource->ip << ":" << resource->port << resource->uri ;
335 OC_LOG_V(INFO, TAG,"Executing InitGetRequest, Query: %s", query.str().c_str());
337 return (InvokeOCDoResource(query, OC_REST_GET, resource->connType,
338 (qos == OC_HIGH_QOS)?OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
344 OCCallbackData cbData;
345 /* Start a discovery query*/
346 char szQueryUri[64] = {};
347 if (UNICAST_DISCOVERY)
349 char ipv4addr[IPV4_ADDR_SIZE];
350 printf("Enter IPv4 address of the Server hosting "
351 "resource (Ex: 192.168.0.15)\n");
352 if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
354 //Strip newline char from ipv4addr
355 StripNewLineChar(ipv4addr);
356 snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
360 OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
361 return OC_STACK_INVALID_PARAM;
366 strcpy(szQueryUri, MULTICAST_RESOURCE_DISCOVERY_QUERY);
368 cbData.cb = discoveryReqCB;
369 cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
371 if (UNICAST_DISCOVERY)
373 ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
374 OC_LOW_QOS, &cbData, NULL, 0);
378 ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, (OC_ALL),
379 OC_LOW_QOS, &cbData, NULL, 0);
382 if (ret != OC_STACK_OK)
384 OC_LOG(ERROR, TAG, "OCStack resource error");
391 const char * getIPAddr(const OCClientResponse * clientResponse)
394 if(!clientResponse || 0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d))
399 char * ipaddr = NULL;
400 if((ipaddr = (char *) OICCalloc(1, MAX_IP_ADDR_ST_SZ)))
402 snprintf(ipaddr, MAX_IP_ADDR_ST_SZ, "%d.%d.%d.%d", a,b,c,d);
406 OC_LOG(ERROR, TAG, "Memory not allocated to ipaddr");
411 const char * getPort(const OCClientResponse * clientResponse)
414 if(!clientResponse || 0 != OCDevAddrToPort(clientResponse->addr, &p) )
420 if((port = (char *) OICCalloc(1, MAX_PORT_ST_SZ)))
422 snprintf(port, MAX_PORT_ST_SZ, "%d", p);
426 OC_LOG(ERROR, TAG, "Memory not allocated to port");
431 int parseJSON(const char * resJSONPayload, char ** sid_c,
432 char *** uri_c, int * totalRes)
437 root = cJSON_Parse((char *)(resJSONPayload));
441 OC_LOG(ERROR, TAG, "JSON Parsing Error");
442 return OC_STACK_INVALID_JSON;
445 oc = cJSON_GetObjectItem(root,"oic");
448 OC_LOG(ERROR, TAG, "Invalid JSON : Missing oc object");
449 return OC_STACK_INVALID_JSON;
452 * totalRes = cJSON_GetArraySize(oc);
454 if(oc->type == cJSON_Array)
456 cJSON * resource = cJSON_GetArrayItem(oc, 0);
460 return OC_STACK_INVALID_JSON;
463 if (cJSON_GetObjectItem(resource, "sid"))
465 char * sid = cJSON_GetObjectItem(resource, "sid")->valuestring;
466 if((* sid_c = (char *)OICCalloc(1, strlen (sid) + 1)))
468 memcpy(* sid_c, sid, strlen(sid) + 1);
472 OC_LOG(ERROR, TAG, "Memory not allocated to sid");
473 return OC_STACK_NO_MEMORY;
478 OC_LOG(ERROR, TAG, "Invalid JSON : Missing sid object");
479 return OC_STACK_INVALID_JSON;
482 if(!(* uri_c = (char ** )OICMalloc ((* totalRes) * sizeof(char **))))
484 OC_LOG(ERROR, TAG, "Memory not allocated to sid_c array");
485 return OC_STACK_NO_MEMORY;
492 if (cJSON_GetObjectItem(resource, "href"))
494 char *uri= cJSON_GetObjectItem(resource, "href")->valuestring;
495 if(((*uri_c)[i] = (char *)OICCalloc(1, strlen (uri) + 1)))
497 memcpy((*uri_c)[i], uri, strlen(uri) + 1);
501 OC_LOG(ERROR, TAG, "Memory not allocated to uri");
502 return OC_STACK_NO_MEMORY;
505 if(i >= (* totalRes))
507 resource = cJSON_GetArrayItem(oc, i);
511 OC_LOG(ERROR, TAG, "Invalid JSON : Missing uri object");
512 return OC_STACK_INVALID_JSON;
518 return OC_STACK_INVALID_JSON;
519 OC_LOG(ERROR, TAG, "Invalid JSON : oc object type is not an array");
529 case TEST_DISCOVER_REQ:
531 case TEST_NON_CON_OP:
532 InitGetRequest(OC_LOW_QOS);
533 InitPutRequest(OC_LOW_QOS);
534 InitPostRequest(OC_LOW_QOS);
537 InitGetRequest(OC_HIGH_QOS);
538 InitPutRequest(OC_HIGH_QOS);
539 InitPostRequest(OC_HIGH_QOS);
549 void collectUniqueResource(const OCClientResponse * clientResponse)
555 if(parseJSON(clientResponse->resJSONPayload, & sid, & uri, &totalRes)
558 OC_LOG(ERROR, TAG, "Error while parsing JSON payload in OCClientResponse");
565 for(i = 0; i < totalRes; i++)
567 if(insertResource(sid, uri[i], clientResponse) == 1)
569 printf("%s%s%s%s\n",sid, ":", uri[i], " is new");
575 printf("%s%s%s%s\n\n",sid, ":", uri[i], " has been seen before");
583 /* This function searches for the resource(sid:uri) in the ResourceList.
584 * If the Resource is found in the list then it returns 0 else insert
585 * the resource to front of the list and returns 1.
587 int insertResource(const char * sid, char const * uri,
588 const OCClientResponse * clientResponse)
590 ResourceNode * iter = resourceList;
592 //Checking if the resource(sid:uri) is new
595 if((strcmp(iter->sid, sid) == 0) && (strcmp(iter->uri, uri) == 0))
605 //Creating new ResourceNode
606 if((iter = (ResourceNode *) OICMalloc(sizeof(ResourceNode))))
610 iter->ip = getIPAddr(clientResponse);
611 iter->port = getPort(clientResponse);
612 iter->connType = clientResponse->connType;
617 OC_LOG(ERROR, TAG, "Memory not allocated to ResourceNode");
621 //Adding new ResourceNode to front of the ResourceList
628 iter->next = resourceList;
634 void printResourceList()
638 printf("\nResource List\n");
641 printf("*****************************************************\n");
642 printf("sid = %s \n",iter->sid);
643 printf("uri = %s\n", iter->uri);
644 printf("ip = %s\n", iter->ip);
645 printf("port = %s\n", iter->port);
646 switch (iter->connType)
649 printf("connType = %s\n","IPv4");
652 // TODO: Allow IPv6 when support is added
653 printf("IPv6 not currently supported, default to IPv4\n");
654 //printf("connType = %s\n","IPv6");
655 printf("connType = %s\n","IPv4");
658 printf("connType = %s\n","BLE");
661 printf("connType = %s\n","BT");
665 printf("connType = %s\n","Invalid connType");
668 printf("*****************************************************\n");
673 void freeResourceList()
675 OC_LOG(INFO, TAG, "Freeing ResourceNode List");
680 resourceList = resourceList->next;
681 OICFree((void *)temp->sid);
682 OICFree((void *)temp->uri);
683 OICFree((void *)temp->ip);
684 OICFree((void *)temp->port);
689 int main(int argc, char* argv[])
693 while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
698 UNICAST_DISCOVERY = atoi(optarg);
701 TEST_CASE = atoi(optarg);
704 // TODO: re-enable IPv4/IPv6 command line selection when IPv6 is supported
705 // OC_CONNTYPE = OCConnectivityType(atoi(optarg));
706 OC_CONNTYPE = OC_IPV4;
707 OC_LOG(INFO, TAG, "Using default IPv4, IPv6 not currently supported.");
715 if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
716 (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
722 /* Initialize OCStack*/
723 if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
725 OC_LOG(ERROR, TAG, "OCStack init error");
731 // Break from loop with Ctrl+C
732 signal(SIGINT, handleSigInt);
736 if (OCProcess() != OC_STACK_OK)
738 OC_LOG(ERROR, TAG, "OCStack process error");
745 OC_LOG(INFO, TAG, "Exiting occlient main loop...");
746 if (OCStop() != OC_STACK_OK)
748 OC_LOG(ERROR, TAG, "OCStack stop error");