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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20 #include "iotivity_config.h"
38 #include "occlientbasicops.h"
39 #include "ocpayload.h"
40 #include "payload_logging.h"
41 #include "oic_malloc.h"
42 #include "oic_string.h"
45 #define MAX_IP_ADDR_ST_SZ 16 //string size of "155.255.255.255" (15 + 1)
46 #define MAX_PORT_ST_SZ 6 //string size of "65535" (5 + 1)
48 static int UnicastDiscovery = 0;
49 static int TestCase = 0;
50 static int Connectivity = 0;
52 //The following variable determines the interface protocol (IP, etc)
53 //to be used for sending unicast messages. Default set to IP.
54 static OCConnectivityType ConnType = CT_ADAPTER_IP;
55 static const char *RESOURCE_DISCOVERY_QUERY = "%s/oic/res";
59 struct ResourceNode *resourceList;
61 * SIGINT handler: set gQuitFlag to 1 for graceful termination
63 void handleSigInt(int signum)
71 OCPayload* putPayload()
73 OCRepPayload* payload = OCRepPayloadCreate();
77 std::cout << "Failed to create put payload object"<<std::endl;
81 OCRepPayloadSetPropInt(payload, "power", 15);
82 OCRepPayloadSetPropBool(payload, "state", true);
84 return (OCPayload*) payload;
87 static void PrintUsage()
89 OIC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
90 OIC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
91 OIC_LOG(INFO, TAG, "-t 1 : Discover Resources");
92 OIC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
93 " Initiate Nonconfirmable Get/Put/Post Requests");
94 OIC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate "
95 "Confirmable Get/Put/Post Requests");
96 OIC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
97 OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
101 * Returns the first resource in the list
103 const ResourceNode * getResource()
108 OCStackResult InvokeOCDoResource(std::ostringstream &query,
110 const OCDevAddr *dest,
111 OCQualityOfService qos,
112 OCClientResponseHandler cb,
113 OCHeaderOption * options, uint8_t numOptions)
116 OCCallbackData cbData;
119 cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
122 ret = OCDoResource(NULL, method, query.str().c_str(), dest,
123 (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL,
124 CT_DEFAULT, qos, &cbData, options, numOptions);
126 if (ret != OC_STACK_OK)
128 OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d",
135 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle /*handle*/,
136 OCClientResponse * clientResponse)
138 if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
140 OIC_LOG(INFO, TAG, "<====Callback Context for PUT received successfully====>");
144 OIC_LOG(ERROR, TAG, "<====Callback Context for PUT fail====>");
149 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
150 OIC_LOG(INFO, TAG, ("=============> Put Response"));
154 OIC_LOG(ERROR, TAG, "<====PUT Callback fail to receive clientResponse====>\n");
156 return OC_STACK_DELETE_TRANSACTION;
159 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle /*handle*/,
160 OCClientResponse *clientResponse)
162 if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
164 OIC_LOG(INFO, TAG, "<====Callback Context for POST received successfully====>");
168 OIC_LOG(ERROR, TAG, "<====Callback Context for POST fail====>");
173 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
174 OIC_LOG(INFO, TAG, ("=============> Post Response"));
178 OIC_LOG(ERROR, TAG, "<====POST Callback fail to receive clientResponse====>\n");
181 return OC_STACK_DELETE_TRANSACTION;
184 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
185 OCClientResponse * clientResponse)
187 if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
189 OIC_LOG(INFO, TAG, "<====Callback Context for GET received successfully====>");
193 OIC_LOG(ERROR, TAG, "<====Callback Context for GET fail====>");
198 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
199 OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
200 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
201 OIC_LOG(INFO, TAG, ("=============> Get Response"));
203 if (clientResponse->numRcvdVendorSpecificHeaderOptions > 0 )
205 OIC_LOG (INFO, TAG, "Received vendor specific options");
207 OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
208 for (i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
210 if (((OCHeaderOption) rcvdOptions[i]).protocolID == OC_COAP_ID)
212 OIC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
213 ((OCHeaderOption)rcvdOptions[i]).optionID );
215 OIC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
216 MAX_HEADER_OPTION_DATA_LENGTH);
223 OIC_LOG(ERROR, TAG, "<====GET Callback fail to receive clientResponse====>\n");
225 return OC_STACK_DELETE_TRANSACTION;
229 * This is a function called back when a device is discovered
231 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
232 OCClientResponse * clientResponse)
234 if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
236 OIC_LOG(INFO, TAG, "\n<====Callback Context for DISCOVERY query "
237 "received successfully====>");
241 OIC_LOG(ERROR, TAG, "\n<====Callback Context for DISCOVERY fail====>");
247 "Device =============> Discovered @ %s:%d",
248 clientResponse->devAddr.addr,
249 clientResponse->devAddr.port);
250 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
252 collectUniqueResource(clientResponse);
256 OIC_LOG(ERROR, TAG, "<====DISCOVERY Callback fail to receive clientResponse====>\n");
258 return (UnicastDiscovery) ?
259 OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
262 int InitPutRequest(OCQualityOfService qos)
264 std::ostringstream query;
265 //Get most recently inserted resource
266 const ResourceNode * resource = getResource();
270 OIC_LOG_V(ERROR, TAG, "Resource null, can't do PUT request\n");
273 query << resource->uri;
274 OIC_LOG_V(INFO, TAG,"Executing InitPutRequest, Query: %s", query.str().c_str());
276 return (InvokeOCDoResource(query, OC_REST_PUT, &resource->endpoint,
277 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
281 int InitPostRequest(OCQualityOfService qos)
283 OCStackResult result;
284 std::ostringstream query;
285 //Get most recently inserted resource
286 const ResourceNode *resource = getResource();
290 OIC_LOG_V(ERROR, TAG, "Resource null, can't do POST request\n");
294 query << resource->uri;
295 OIC_LOG_V(INFO, TAG,"Executing InitPostRequest, Query: %s", query.str().c_str());
297 // First POST operation (to create an LED instance)
298 result = InvokeOCDoResource(query, OC_REST_POST, &resource->endpoint,
299 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
301 if (OC_STACK_OK != result)
303 // Error can happen if for example, network connectivity is down
304 OIC_LOG(ERROR, TAG, "First POST call did not succeed");
307 // Second POST operation (to create an LED instance)
308 result = InvokeOCDoResource(query, OC_REST_POST, &resource->endpoint,
309 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
311 if (OC_STACK_OK != result)
313 OIC_LOG(ERROR, TAG, "Second POST call did not succeed");
316 // This POST operation will update the original resourced /a/led
317 return (InvokeOCDoResource(query, OC_REST_POST, &resource->endpoint,
318 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
319 postReqCB, NULL, 0));
322 int InitGetRequest(OCQualityOfService qos)
324 std::ostringstream query;
325 //Get most recently inserted resource
326 const ResourceNode * resource = getResource();
330 OIC_LOG_V(ERROR, TAG, "Resource null, can't do GET request\n");
333 query << resource->uri;
334 OIC_LOG_V(INFO, TAG,"Executing InitGetRequest, Query: %s", query.str().c_str());
336 return (InvokeOCDoResource(query, OC_REST_GET, &resource->endpoint,
337 (qos == OC_HIGH_QOS)?OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
343 OCCallbackData cbData;
345 char ipaddr[100] = { '\0' };
347 if (UnicastDiscovery)
349 OIC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
350 OIC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
351 OIC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
353 if (fgets(ipaddr, sizeof (ipaddr), stdin))
355 StripNewLineChar(ipaddr); //Strip newline char from ipaddr
359 OIC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
360 return OC_STACK_INVALID_PARAM;
364 snprintf(queryUri, sizeof (queryUri), RESOURCE_DISCOVERY_QUERY, ipaddr);
366 cbData.cb = discoveryReqCB;
367 cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
370 ret = OCDoResource(NULL, OC_REST_DISCOVER, queryUri, 0, 0, CT_DEFAULT,
371 OC_LOW_QOS, &cbData, NULL, 0);
372 if (ret != OC_STACK_OK)
374 OIC_LOG(ERROR, TAG, "OCStack resource error");
383 case TEST_DISCOVER_REQ:
385 case TEST_NON_CON_OP:
386 InitGetRequest(OC_LOW_QOS);
387 InitPutRequest(OC_LOW_QOS);
388 InitPostRequest(OC_LOW_QOS);
391 InitGetRequest(OC_HIGH_QOS);
392 InitPutRequest(OC_HIGH_QOS);
393 InitPostRequest(OC_HIGH_QOS);
402 void collectUniqueResource(const OCClientResponse * clientResponse)
404 OCDiscoveryPayload* pay = (OCDiscoveryPayload*) clientResponse->payload;
405 OCResourcePayload* res = pay->resources;
407 // Including the NUL terminator, length of UUID string of the form:
408 // "a62389f7-afde-00b6-cd3e-12b97d2fcf09"
409 # define UUID_LENGTH 37
411 char sidStr[UUID_LENGTH];
415 int ret = snprintf(sidStr, UUID_LENGTH,
416 "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
417 pay->sid[0], pay->sid[1], pay->sid[2], pay->sid[3],
418 pay->sid[4], pay->sid[5], pay->sid[6], pay->sid[7],
419 pay->sid[8], pay->sid[9], pay->sid[10], pay->sid[11],
420 pay->sid[12], pay->sid[13], pay->sid[14], pay->sid[15]
423 if (ret == UUID_LENGTH - 1)
425 if(insertResource(sidStr, res->uri, clientResponse) == 1)
427 OIC_LOG_V(INFO,TAG,"%s%s%s%s\n",sidStr, ":", res->uri, " is new");
432 OIC_LOG_V(INFO,TAG,"%s%s%s%s\n",sidStr, ":", res->uri, " is old");
437 OIC_LOG(ERROR, TAG, "Could Not Retrieve the Server ID");
444 /* This function searches for the resource(sid:uri) in the ResourceList.
445 * If the Resource is found in the list then it returns 0 else insert
446 * the resource to front of the list and returns 1.
448 int insertResource(const char * sid, char const * uri,
449 const OCClientResponse * clientResponse)
451 ResourceNode * iter = resourceList;
452 char * sid_cpy = OICStrdup(sid);
453 char * uri_cpy = OICStrdup(uri);
455 //Checking if the resource(sid:uri) is new
458 if((strcmp(iter->sid, sid) == 0) && (strcmp(iter->uri, uri) == 0))
470 //Creating new ResourceNode
471 if((iter = (ResourceNode *) OICMalloc(sizeof(ResourceNode))))
475 iter->endpoint = clientResponse->devAddr;
480 OIC_LOG(ERROR, TAG, "Memory not allocated to ResourceNode");
486 //Adding new ResourceNode to front of the ResourceList
493 iter->next = resourceList;
499 void printResourceList()
503 OIC_LOG(INFO, TAG, "Resource List: ");
506 OIC_LOG(INFO, TAG, "*****************************************************");
507 OIC_LOG_V(INFO, TAG, "sid = %s",iter->sid);
508 OIC_LOG_V(INFO, TAG, "uri = %s", iter->uri);
509 OIC_LOG_V(INFO, TAG, "ip = %s", iter->endpoint.addr);
510 OIC_LOG_V(INFO, TAG, "port = %d", iter->endpoint.port);
511 switch (iter->endpoint.adapter)
514 OIC_LOG(INFO, TAG, "connType = Default (IPv4)");
516 case OC_ADAPTER_GATT_BTLE:
517 OIC_LOG(INFO, TAG, "connType = BLE");
519 case OC_ADAPTER_RFCOMM_BTEDR:
520 OIC_LOG(INFO, TAG, "connType = BT");
523 OIC_LOG(INFO, TAG, "connType = Invalid connType");
526 OIC_LOG(INFO, TAG, "*****************************************************");
531 void freeResourceList()
533 OIC_LOG(INFO, TAG, "Freeing ResourceNode List");
539 resourceList = resourceList->next;
540 OICFree((void *)temp->sid);
541 OICFree((void *)temp->uri);
547 int main(int argc, char* argv[])
551 while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
556 UnicastDiscovery = atoi(optarg);
559 TestCase = atoi(optarg);
562 Connectivity = atoi(optarg);
570 if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||
571 (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS) ||
572 (Connectivity < CT_ADAPTER_DEFAULT || Connectivity >= MAX_CT))
578 /* Initialize OCStack*/
579 if (OCInit1(OC_CLIENT, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS) != OC_STACK_OK)
581 OIC_LOG(ERROR, TAG, "OCStack init error");
585 if(Connectivity == CT_ADAPTER_DEFAULT || Connectivity == CT_IP)
587 ConnType = CT_ADAPTER_IP;//CT_DEFAULT;
591 OIC_LOG(INFO, TAG, "Default Connectivity type selected");
597 // Break from loop with Ctrl+C
598 signal(SIGINT, handleSigInt);
602 if (OCProcess() != OC_STACK_OK)
604 OIC_LOG(ERROR, TAG, "OCStack process error");
611 OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
612 if (OCStop() != OC_STACK_OK)
614 OIC_LOG(ERROR, TAG, "OCStack stop error");