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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
37 #include "occlientbasicops.h"
38 #include "ocpayload.h"
39 #include "payload_logging.h"
40 #include "oic_malloc.h"
41 #include "oic_string.h"
44 #define MAX_IP_ADDR_ST_SZ 16 //string size of "155.255.255.255" (15 + 1)
45 #define MAX_PORT_ST_SZ 6 //string size of "65535" (5 + 1)
47 static int UnicastDiscovery = 0;
48 static int TestCase = 0;
49 static int Connectivity = 0;
51 //The following variable determines the interface protocol (IP, etc)
52 //to be used for sending unicast messages. Default set to IP.
53 static OCConnectivityType ConnType = CT_ADAPTER_IP;
54 static const char *RESOURCE_DISCOVERY_QUERY = "%s/oic/res";
58 struct ResourceNode *resourceList;
60 * SIGINT handler: set gQuitFlag to 1 for graceful termination
62 void handleSigInt(int signum)
70 OCPayload* putPayload()
72 OCRepPayload* payload = OCRepPayloadCreate();
76 std::cout << "Failed to create put payload object"<<std::endl;
80 OCRepPayloadSetPropInt(payload, "power", 15);
81 OCRepPayloadSetPropBool(payload, "state", true);
83 return (OCPayload*) payload;
86 static void PrintUsage()
88 OIC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
89 OIC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
90 OIC_LOG(INFO, TAG, "-t 1 : Discover Resources");
91 OIC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
92 " Initiate Nonconfirmable Get/Put/Post Requests");
93 OIC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate "
94 "Confirmable Get/Put/Post Requests");
95 OIC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
96 OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
100 * Returns the first resource in the list
102 const ResourceNode * getResource()
107 OCStackResult InvokeOCDoResource(std::ostringstream &query,
109 const OCDevAddr *dest,
110 OCQualityOfService qos,
111 OCClientResponseHandler cb,
112 OCHeaderOption * options, uint8_t numOptions)
115 OCCallbackData cbData;
118 cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
121 ret = OCDoResource(NULL, method, query.str().c_str(), dest,
122 (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL,
123 CT_DEFAULT, qos, &cbData, options, numOptions);
125 if (ret != OC_STACK_OK)
127 OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d",
134 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle /*handle*/,
135 OCClientResponse * clientResponse)
137 if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
139 OIC_LOG(INFO, TAG, "<====Callback Context for PUT received successfully====>");
143 OIC_LOG(ERROR, TAG, "<====Callback Context for PUT fail====>");
148 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
149 OIC_LOG(INFO, TAG, ("=============> Put Response"));
153 OIC_LOG(ERROR, TAG, "<====PUT Callback fail to receive clientResponse====>\n");
155 return OC_STACK_DELETE_TRANSACTION;
158 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle /*handle*/,
159 OCClientResponse *clientResponse)
161 if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
163 OIC_LOG(INFO, TAG, "<====Callback Context for POST received successfully====>");
167 OIC_LOG(ERROR, TAG, "<====Callback Context for POST fail====>");
172 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
173 OIC_LOG(INFO, TAG, ("=============> Post Response"));
177 OIC_LOG(ERROR, TAG, "<====POST Callback fail to receive clientResponse====>\n");
180 return OC_STACK_DELETE_TRANSACTION;
183 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
184 OCClientResponse * clientResponse)
186 if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
188 OIC_LOG(INFO, TAG, "<====Callback Context for GET received successfully====>");
192 OIC_LOG(ERROR, TAG, "<====Callback Context for GET fail====>");
197 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
198 OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
199 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
200 OIC_LOG(INFO, TAG, ("=============> Get Response"));
202 if (clientResponse->numRcvdVendorSpecificHeaderOptions > 0 )
204 OIC_LOG (INFO, TAG, "Received vendor specific options");
206 OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
207 for (i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
209 if (((OCHeaderOption) rcvdOptions[i]).protocolID == OC_COAP_ID)
211 OIC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
212 ((OCHeaderOption)rcvdOptions[i]).optionID );
214 OIC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
215 MAX_HEADER_OPTION_DATA_LENGTH);
222 OIC_LOG(ERROR, TAG, "<====GET Callback fail to receive clientResponse====>\n");
224 return OC_STACK_DELETE_TRANSACTION;
228 * This is a function called back when a device is discovered
230 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
231 OCClientResponse * clientResponse)
233 if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
235 OIC_LOG(INFO, TAG, "\n<====Callback Context for DISCOVERY query "
236 "received successfully====>");
240 OIC_LOG(ERROR, TAG, "\n<====Callback Context for DISCOVERY fail====>");
246 "Device =============> Discovered @ %s:%d",
247 clientResponse->devAddr.addr,
248 clientResponse->devAddr.port);
249 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
251 collectUniqueResource(clientResponse);
255 OIC_LOG(ERROR, TAG, "<====DISCOVERY Callback fail to receive clientResponse====>\n");
257 return (UnicastDiscovery) ?
258 OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
261 int InitPutRequest(OCQualityOfService qos)
263 std::ostringstream query;
264 //Get most recently inserted resource
265 const ResourceNode * resource = getResource();
269 OIC_LOG_V(ERROR, TAG, "Resource null, can't do PUT request\n");
272 query << resource->uri;
273 OIC_LOG_V(INFO, TAG,"Executing InitPutRequest, Query: %s", query.str().c_str());
275 return (InvokeOCDoResource(query, OC_REST_PUT, &resource->endpoint,
276 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
280 int InitPostRequest(OCQualityOfService qos)
282 OCStackResult result;
283 std::ostringstream query;
284 //Get most recently inserted resource
285 const ResourceNode *resource = getResource();
289 OIC_LOG_V(ERROR, TAG, "Resource null, can't do POST request\n");
293 query << resource->uri;
294 OIC_LOG_V(INFO, TAG,"Executing InitPostRequest, Query: %s", query.str().c_str());
296 // First POST operation (to create an LED instance)
297 result = InvokeOCDoResource(query, OC_REST_POST, &resource->endpoint,
298 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
300 if (OC_STACK_OK != result)
302 // Error can happen if for example, network connectivity is down
303 OIC_LOG(ERROR, TAG, "First POST call did not succeed");
306 // Second POST operation (to create an LED instance)
307 result = InvokeOCDoResource(query, OC_REST_POST, &resource->endpoint,
308 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
310 if (OC_STACK_OK != result)
312 OIC_LOG(ERROR, TAG, "Second POST call did not succeed");
315 // This POST operation will update the original resourced /a/led
316 return (InvokeOCDoResource(query, OC_REST_POST, &resource->endpoint,
317 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
318 postReqCB, NULL, 0));
321 int InitGetRequest(OCQualityOfService qos)
323 std::ostringstream query;
324 //Get most recently inserted resource
325 const ResourceNode * resource = getResource();
329 OIC_LOG_V(ERROR, TAG, "Resource null, can't do GET request\n");
332 query << resource->uri;
333 OIC_LOG_V(INFO, TAG,"Executing InitGetRequest, Query: %s", query.str().c_str());
335 return (InvokeOCDoResource(query, OC_REST_GET, &resource->endpoint,
336 (qos == OC_HIGH_QOS)?OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
342 OCCallbackData cbData;
344 char ipaddr[100] = { '\0' };
346 if (UnicastDiscovery)
348 OIC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
349 OIC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
350 OIC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
352 if (fgets(ipaddr, sizeof (ipaddr), stdin))
354 StripNewLineChar(ipaddr); //Strip newline char from ipaddr
358 OIC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
359 return OC_STACK_INVALID_PARAM;
363 snprintf(queryUri, sizeof (queryUri), RESOURCE_DISCOVERY_QUERY, ipaddr);
365 cbData.cb = discoveryReqCB;
366 cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
369 ret = OCDoResource(NULL, OC_REST_DISCOVER, queryUri, 0, 0, CT_DEFAULT,
370 OC_LOW_QOS, &cbData, NULL, 0);
371 if (ret != OC_STACK_OK)
373 OIC_LOG(ERROR, TAG, "OCStack resource error");
382 case TEST_DISCOVER_REQ:
384 case TEST_NON_CON_OP:
385 InitGetRequest(OC_LOW_QOS);
386 InitPutRequest(OC_LOW_QOS);
387 InitPostRequest(OC_LOW_QOS);
390 InitGetRequest(OC_HIGH_QOS);
391 InitPutRequest(OC_HIGH_QOS);
392 InitPostRequest(OC_HIGH_QOS);
401 void collectUniqueResource(const OCClientResponse * clientResponse)
403 OCDiscoveryPayload* pay = (OCDiscoveryPayload*) clientResponse->payload;
404 OCResourcePayload* res = pay->resources;
406 // Including the NUL terminator, length of UUID string of the form:
407 // "a62389f7-afde-00b6-cd3e-12b97d2fcf09"
408 # define UUID_LENGTH 37
410 char sidStr[UUID_LENGTH];
414 int ret = snprintf(sidStr, UUID_LENGTH,
415 "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
416 pay->sid[0], pay->sid[1], pay->sid[2], pay->sid[3],
417 pay->sid[4], pay->sid[5], pay->sid[6], pay->sid[7],
418 pay->sid[8], pay->sid[9], pay->sid[10], pay->sid[11],
419 pay->sid[12], pay->sid[13], pay->sid[14], pay->sid[15]
422 if (ret == UUID_LENGTH - 1)
424 if(insertResource(sidStr, res->uri, clientResponse) == 1)
426 OIC_LOG_V(INFO,TAG,"%s%s%s%s\n",sidStr, ":", res->uri, " is new");
431 OIC_LOG_V(INFO,TAG,"%s%s%s%s\n",sidStr, ":", res->uri, " is old");
436 OIC_LOG(ERROR, TAG, "Could Not Retrieve the Server ID");
443 /* This function searches for the resource(sid:uri) in the ResourceList.
444 * If the Resource is found in the list then it returns 0 else insert
445 * the resource to front of the list and returns 1.
447 int insertResource(const char * sid, char const * uri,
448 const OCClientResponse * clientResponse)
450 ResourceNode * iter = resourceList;
451 char * sid_cpy = OICStrdup(sid);
452 char * uri_cpy = OICStrdup(uri);
454 //Checking if the resource(sid:uri) is new
457 if((strcmp(iter->sid, sid) == 0) && (strcmp(iter->uri, uri) == 0))
469 //Creating new ResourceNode
470 if((iter = (ResourceNode *) OICMalloc(sizeof(ResourceNode))))
474 iter->endpoint = clientResponse->devAddr;
479 OIC_LOG(ERROR, TAG, "Memory not allocated to ResourceNode");
485 //Adding new ResourceNode to front of the ResourceList
492 iter->next = resourceList;
498 void printResourceList()
502 OIC_LOG(INFO, TAG, "Resource List: ");
505 OIC_LOG(INFO, TAG, "*****************************************************");
506 OIC_LOG_V(INFO, TAG, "sid = %s",iter->sid);
507 OIC_LOG_V(INFO, TAG, "uri = %s", iter->uri);
508 OIC_LOG_V(INFO, TAG, "ip = %s", iter->endpoint.addr);
509 OIC_LOG_V(INFO, TAG, "port = %d", iter->endpoint.port);
510 switch (iter->endpoint.adapter)
513 OIC_LOG(INFO, TAG, "connType = Default (IPv4)");
515 case OC_ADAPTER_GATT_BTLE:
516 OIC_LOG(INFO, TAG, "connType = BLE");
518 case OC_ADAPTER_RFCOMM_BTEDR:
519 OIC_LOG(INFO, TAG, "connType = BT");
522 OIC_LOG(INFO, TAG, "connType = Invalid connType");
525 OIC_LOG(INFO, TAG, "*****************************************************");
530 void freeResourceList()
532 OIC_LOG(INFO, TAG, "Freeing ResourceNode List");
538 resourceList = resourceList->next;
539 OICFree((void *)temp->sid);
540 OICFree((void *)temp->uri);
546 int main(int argc, char* argv[])
550 while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
555 UnicastDiscovery = atoi(optarg);
558 TestCase = atoi(optarg);
561 Connectivity = atoi(optarg);
569 if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||
570 (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS) ||
571 (Connectivity < CT_ADAPTER_DEFAULT || Connectivity >= MAX_CT))
577 /* Initialize OCStack*/
578 if (OCInit1(OC_CLIENT, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS) != OC_STACK_OK)
580 OIC_LOG(ERROR, TAG, "OCStack init error");
584 if(Connectivity == CT_ADAPTER_DEFAULT || Connectivity == CT_IP)
586 ConnType = CT_ADAPTER_IP;//CT_DEFAULT;
590 OIC_LOG(INFO, TAG, "Default Connectivity type selected");
596 // Break from loop with Ctrl+C
597 signal(SIGINT, handleSigInt);
601 if (OCProcess() != OC_STACK_OK)
603 OIC_LOG(ERROR, TAG, "OCStack process error");
610 OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
611 if (OCStop() != OC_STACK_OK)
613 OIC_LOG(ERROR, TAG, "OCStack stop error");