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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
36 #include "occlientbasicops.h"
37 #include "ocpayload.h"
38 #include "payload_logging.h"
39 #include "oic_malloc.h"
40 #include "oic_string.h"
42 #define MAX_IP_ADDR_ST_SZ 16 //string size of "155.255.255.255" (15 + 1)
43 #define MAX_PORT_ST_SZ 6 //string size of "65535" (5 + 1)
45 static int UnicastDiscovery = 0;
46 static int TestCase = 0;
47 static int Connectivity = 0;
49 //The following variable determines the interface protocol (IP, etc)
50 //to be used for sending unicast messages. Default set to IP.
51 static OCConnectivityType ConnType = CT_ADAPTER_IP;
52 static const char *RESOURCE_DISCOVERY_QUERY = "%s/oic/res";
56 struct ResourceNode *resourceList;
58 * SIGINT handler: set gQuitFlag to 1 for graceful termination
60 void handleSigInt(int signum)
68 OCPayload* putPayload()
70 OCRepPayload* payload = OCRepPayloadCreate();
74 std::cout << "Failed to create put payload object"<<std::endl;
78 OCRepPayloadSetPropInt(payload, "power", 15);
79 OCRepPayloadSetPropBool(payload, "state", true);
81 return (OCPayload*) payload;
84 static void PrintUsage()
86 OIC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
87 OIC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
88 OIC_LOG(INFO, TAG, "-t 1 : Discover Resources");
89 OIC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
90 " Initiate Nonconfirmable Get/Put/Post Requests");
91 OIC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate "
92 "Confirmable Get/Put/Post Requests");
93 OIC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
94 OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
98 * Returns the first resource in the list
100 const ResourceNode * getResource()
105 OCStackResult InvokeOCDoResource(std::ostringstream &query,
107 const OCDevAddr *dest,
108 OCQualityOfService qos,
109 OCClientResponseHandler cb,
110 OCHeaderOption * options, uint8_t numOptions)
113 OCCallbackData cbData;
116 cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
119 ret = OCDoResource(NULL, method, query.str().c_str(), dest,
120 (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL,
121 CT_DEFAULT, qos, &cbData, options, numOptions);
123 if (ret != OC_STACK_OK)
125 OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d",
132 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle /*handle*/,
133 OCClientResponse * clientResponse)
135 if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
137 OIC_LOG(INFO, TAG, "<====Callback Context for PUT received successfully====>");
141 OIC_LOG(ERROR, TAG, "<====Callback Context for PUT fail====>");
146 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
147 OIC_LOG(INFO, TAG, ("=============> Put Response"));
151 OIC_LOG(ERROR, TAG, "<====PUT Callback fail to receive clientResponse====>\n");
153 return OC_STACK_DELETE_TRANSACTION;
156 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle /*handle*/,
157 OCClientResponse *clientResponse)
159 if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
161 OIC_LOG(INFO, TAG, "<====Callback Context for POST received successfully====>");
165 OIC_LOG(ERROR, TAG, "<====Callback Context for POST fail====>");
170 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
171 OIC_LOG(INFO, TAG, ("=============> Post Response"));
175 OIC_LOG(ERROR, TAG, "<====POST Callback fail to receive clientResponse====>\n");
178 return OC_STACK_DELETE_TRANSACTION;
181 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
182 OCClientResponse * clientResponse)
184 if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
186 OIC_LOG(INFO, TAG, "<====Callback Context for GET received successfully====>");
190 OIC_LOG(ERROR, TAG, "<====Callback Context for GET fail====>");
195 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
196 OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
197 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
198 OIC_LOG(INFO, TAG, ("=============> Get Response"));
200 if (clientResponse->numRcvdVendorSpecificHeaderOptions > 0 )
202 OIC_LOG (INFO, TAG, "Received vendor specific options");
204 OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
205 for (i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
207 if (((OCHeaderOption) rcvdOptions[i]).protocolID == OC_COAP_ID)
209 OIC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
210 ((OCHeaderOption)rcvdOptions[i]).optionID );
212 OIC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
213 MAX_HEADER_OPTION_DATA_LENGTH);
220 OIC_LOG(ERROR, TAG, "<====GET Callback fail to receive clientResponse====>\n");
222 return OC_STACK_DELETE_TRANSACTION;
226 * This is a function called back when a device is discovered
228 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
229 OCClientResponse * clientResponse)
231 if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
233 OIC_LOG(INFO, TAG, "\n<====Callback Context for DISCOVERY query "
234 "received successfully====>");
238 OIC_LOG(ERROR, TAG, "\n<====Callback Context for DISCOVERY fail====>");
244 "Device =============> Discovered @ %s:%d",
245 clientResponse->devAddr.addr,
246 clientResponse->devAddr.port);
247 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
249 collectUniqueResource(clientResponse);
253 OIC_LOG(ERROR, TAG, "<====DISCOVERY Callback fail to receive clientResponse====>\n");
255 return (UnicastDiscovery) ?
256 OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
259 int InitPutRequest(OCQualityOfService qos)
261 std::ostringstream query;
262 //Get most recently inserted resource
263 const ResourceNode * resource = getResource();
267 OIC_LOG_V(ERROR, TAG, "Resource null, can't do PUT request\n");
270 query << resource->uri;
271 OIC_LOG_V(INFO, TAG,"Executing InitPutRequest, Query: %s", query.str().c_str());
273 return (InvokeOCDoResource(query, OC_REST_PUT, &resource->endpoint,
274 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
278 int InitPostRequest(OCQualityOfService qos)
280 OCStackResult result;
281 std::ostringstream query;
282 //Get most recently inserted resource
283 const ResourceNode *resource = getResource();
287 OIC_LOG_V(ERROR, TAG, "Resource null, can't do POST request\n");
291 query << resource->uri;
292 OIC_LOG_V(INFO, TAG,"Executing InitPostRequest, Query: %s", query.str().c_str());
294 // First POST operation (to create an LED instance)
295 result = InvokeOCDoResource(query, OC_REST_POST, &resource->endpoint,
296 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
298 if (OC_STACK_OK != result)
300 // Error can happen if for example, network connectivity is down
301 OIC_LOG(ERROR, TAG, "First POST call did not succeed");
304 // Second POST operation (to create an LED instance)
305 result = InvokeOCDoResource(query, OC_REST_POST, &resource->endpoint,
306 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
308 if (OC_STACK_OK != result)
310 OIC_LOG(ERROR, TAG, "Second POST call did not succeed");
313 // This POST operation will update the original resourced /a/led
314 return (InvokeOCDoResource(query, OC_REST_POST, &resource->endpoint,
315 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
316 postReqCB, NULL, 0));
319 int InitGetRequest(OCQualityOfService qos)
321 std::ostringstream query;
322 //Get most recently inserted resource
323 const ResourceNode * resource = getResource();
327 OIC_LOG_V(ERROR, TAG, "Resource null, can't do GET request\n");
330 query << resource->uri;
331 OIC_LOG_V(INFO, TAG,"Executing InitGetRequest, Query: %s", query.str().c_str());
333 return (InvokeOCDoResource(query, OC_REST_GET, &resource->endpoint,
334 (qos == OC_HIGH_QOS)?OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
340 OCCallbackData cbData;
342 char ipaddr[100] = { '\0' };
344 if (UnicastDiscovery)
346 OIC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
347 OIC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
348 OIC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
350 if (fgets(ipaddr, sizeof (ipaddr), stdin))
352 StripNewLineChar(ipaddr); //Strip newline char from ipaddr
356 OIC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
357 return OC_STACK_INVALID_PARAM;
361 snprintf(queryUri, sizeof (queryUri), RESOURCE_DISCOVERY_QUERY, ipaddr);
363 cbData.cb = discoveryReqCB;
364 cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
367 ret = OCDoResource(NULL, OC_REST_DISCOVER, queryUri, 0, 0, CT_DEFAULT,
368 OC_LOW_QOS, &cbData, NULL, 0);
369 if (ret != OC_STACK_OK)
371 OIC_LOG(ERROR, TAG, "OCStack resource error");
380 case TEST_DISCOVER_REQ:
382 case TEST_NON_CON_OP:
383 InitGetRequest(OC_LOW_QOS);
384 InitPutRequest(OC_LOW_QOS);
385 InitPostRequest(OC_LOW_QOS);
388 InitGetRequest(OC_HIGH_QOS);
389 InitPutRequest(OC_HIGH_QOS);
390 InitPostRequest(OC_HIGH_QOS);
399 void collectUniqueResource(const OCClientResponse * clientResponse)
401 OCDiscoveryPayload* pay = (OCDiscoveryPayload*) clientResponse->payload;
402 OCResourcePayload* res = pay->resources;
404 // Including the NUL terminator, length of UUID string of the form:
405 // "a62389f7-afde-00b6-cd3e-12b97d2fcf09"
406 # define UUID_LENGTH 37
408 char sidStr[UUID_LENGTH];
412 int ret = snprintf(sidStr, UUID_LENGTH,
413 "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
414 pay->sid[0], pay->sid[1], pay->sid[2], pay->sid[3],
415 pay->sid[4], pay->sid[5], pay->sid[6], pay->sid[7],
416 pay->sid[8], pay->sid[9], pay->sid[10], pay->sid[11],
417 pay->sid[12], pay->sid[13], pay->sid[14], pay->sid[15]
420 if (ret == UUID_LENGTH - 1)
422 if(insertResource(sidStr, res->uri, clientResponse) == 1)
424 OIC_LOG_V(INFO,TAG,"%s%s%s%s\n",sidStr, ":", res->uri, " is new");
429 OIC_LOG_V(INFO,TAG,"%s%s%s%s\n",sidStr, ":", res->uri, " is old");
434 OIC_LOG(ERROR, TAG, "Could Not Retrieve the Server ID");
441 /* This function searches for the resource(sid:uri) in the ResourceList.
442 * If the Resource is found in the list then it returns 0 else insert
443 * the resource to front of the list and returns 1.
445 int insertResource(const char * sid, char const * uri,
446 const OCClientResponse * clientResponse)
448 ResourceNode * iter = resourceList;
449 char * sid_cpy = OICStrdup(sid);
450 char * uri_cpy = OICStrdup(uri);
452 //Checking if the resource(sid:uri) is new
455 if((strcmp(iter->sid, sid) == 0) && (strcmp(iter->uri, uri) == 0))
467 //Creating new ResourceNode
468 if((iter = (ResourceNode *) OICMalloc(sizeof(ResourceNode))))
472 iter->endpoint = clientResponse->devAddr;
477 OIC_LOG(ERROR, TAG, "Memory not allocated to ResourceNode");
483 //Adding new ResourceNode to front of the ResourceList
490 iter->next = resourceList;
496 void printResourceList()
500 OIC_LOG(INFO, TAG, "Resource List: ");
503 OIC_LOG(INFO, TAG, "*****************************************************");
504 OIC_LOG_V(INFO, TAG, "sid = %s",iter->sid);
505 OIC_LOG_V(INFO, TAG, "uri = %s", iter->uri);
506 OIC_LOG_V(INFO, TAG, "ip = %s", iter->endpoint.addr);
507 OIC_LOG_V(INFO, TAG, "port = %d", iter->endpoint.port);
508 switch (iter->endpoint.adapter)
511 OIC_LOG(INFO, TAG, "connType = Default (IPv4)");
513 case OC_ADAPTER_GATT_BTLE:
514 OIC_LOG(INFO, TAG, "connType = BLE");
516 case OC_ADAPTER_RFCOMM_BTEDR:
517 OIC_LOG(INFO, TAG, "connType = BT");
520 OIC_LOG(INFO, TAG, "connType = Invalid connType");
523 OIC_LOG(INFO, TAG, "*****************************************************");
528 void freeResourceList()
530 OIC_LOG(INFO, TAG, "Freeing ResourceNode List");
536 resourceList = resourceList->next;
537 OICFree((void *)temp->sid);
538 OICFree((void *)temp->uri);
544 int main(int argc, char* argv[])
548 while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
553 UnicastDiscovery = atoi(optarg);
556 TestCase = atoi(optarg);
559 Connectivity = atoi(optarg);
567 if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||
568 (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS) ||
569 (Connectivity < CT_ADAPTER_DEFAULT || Connectivity >= MAX_CT))
575 /* Initialize OCStack*/
576 if (OCInit1(OC_CLIENT, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS) != OC_STACK_OK)
578 OIC_LOG(ERROR, TAG, "OCStack init error");
582 if(Connectivity == CT_ADAPTER_DEFAULT || Connectivity == CT_IP)
584 ConnType = CT_ADAPTER_IP;//CT_DEFAULT;
588 OIC_LOG(INFO, TAG, "Default Connectivity type selected");
594 // Break from loop with Ctrl+C
595 signal(SIGINT, handleSigInt);
599 if (OCProcess() != OC_STACK_OK)
601 OIC_LOG(ERROR, TAG, "OCStack process error");
608 OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
609 if (OCStop() != OC_STACK_OK)
611 OIC_LOG(ERROR, TAG, "OCStack stop error");