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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
31 #include "occlientbasicops.h"
32 #include "ocpayload.h"
33 #include "payload_logging.h"
34 #include "oic_malloc.h"
35 #include "oic_string.h"
37 #define MAX_IP_ADDR_ST_SZ 16 //string size of "155.255.255.255" (15 + 1)
38 #define MAX_PORT_ST_SZ 6 //string size of "65535" (5 + 1)
40 static int UnicastDiscovery = 0;
41 static int TestCase = 0;
42 static int Connectivity = 0;
44 //The following variable determines the interface protocol (IP, etc)
45 //to be used for sending unicast messages. Default set to IP.
46 static OCConnectivityType ConnType = CT_ADAPTER_IP;
47 static const char *RESOURCE_DISCOVERY_QUERY = "%s/oic/res";
51 struct ResourceNode *resourceList;
53 * SIGINT handler: set gQuitFlag to 1 for graceful termination
55 void handleSigInt(int signum)
63 OCPayload* putPayload()
65 OCRepPayload* payload = OCRepPayloadCreate();
69 std::cout << "Failed to create put payload object"<<std::endl;
73 OCRepPayloadSetPropInt(payload, "power", 15);
74 OCRepPayloadSetPropBool(payload, "state", true);
76 return (OCPayload*) payload;
79 static void PrintUsage()
81 OIC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
82 OIC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
83 OIC_LOG(INFO, TAG, "-t 1 : Discover Resources");
84 OIC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
85 " Initiate Nonconfirmable Get/Put/Post Requests");
86 OIC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate "
87 "Confirmable Get/Put/Post Requests");
88 OIC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
89 OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
93 * Returns the first resource in the list
95 const ResourceNode * getResource()
100 OCStackResult InvokeOCDoResource(std::ostringstream &query,
102 const OCDevAddr *dest,
103 OCQualityOfService qos,
104 OCClientResponseHandler cb,
105 OCHeaderOption * options, uint8_t numOptions)
108 OCCallbackData cbData;
111 cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
114 ret = OCDoResource(NULL, method, query.str().c_str(), dest,
115 (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL,
116 CT_DEFAULT, qos, &cbData, options, numOptions);
118 if (ret != OC_STACK_OK)
120 OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d",
127 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle /*handle*/,
128 OCClientResponse * clientResponse)
130 if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
132 OIC_LOG(INFO, TAG, "<====Callback Context for PUT received successfully====>");
136 OIC_LOG(ERROR, TAG, "<====Callback Context for PUT fail====>");
141 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
142 OIC_LOG(INFO, TAG, ("=============> Put Response"));
146 OIC_LOG(ERROR, TAG, "<====PUT Callback fail to receive clientResponse====>\n");
148 return OC_STACK_DELETE_TRANSACTION;
151 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle /*handle*/,
152 OCClientResponse *clientResponse)
154 if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
156 OIC_LOG(INFO, TAG, "<====Callback Context for POST received successfully====>");
160 OIC_LOG(ERROR, TAG, "<====Callback Context for POST fail====>");
165 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
166 OIC_LOG(INFO, TAG, ("=============> Post Response"));
170 OIC_LOG(ERROR, TAG, "<====POST Callback fail to receive clientResponse====>\n");
173 return OC_STACK_DELETE_TRANSACTION;
176 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
177 OCClientResponse * clientResponse)
179 if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
181 OIC_LOG(INFO, TAG, "<====Callback Context for GET received successfully====>");
185 OIC_LOG(ERROR, TAG, "<====Callback Context for GET fail====>");
190 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
191 OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
192 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
193 OIC_LOG(INFO, TAG, ("=============> Get Response"));
195 if (clientResponse->numRcvdVendorSpecificHeaderOptions > 0 )
197 OIC_LOG (INFO, TAG, "Received vendor specific options");
199 OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
200 for (i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
202 if (((OCHeaderOption) rcvdOptions[i]).protocolID == OC_COAP_ID)
204 OIC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
205 ((OCHeaderOption)rcvdOptions[i]).optionID );
207 OIC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
208 MAX_HEADER_OPTION_DATA_LENGTH);
215 OIC_LOG(ERROR, TAG, "<====GET Callback fail to receive clientResponse====>\n");
217 return OC_STACK_DELETE_TRANSACTION;
221 * This is a function called back when a device is discovered
223 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
224 OCClientResponse * clientResponse)
226 if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
228 OIC_LOG(INFO, TAG, "\n<====Callback Context for DISCOVERY query "
229 "received successfully====>");
233 OIC_LOG(ERROR, TAG, "\n<====Callback Context for DISCOVERY fail====>");
239 "Device =============> Discovered @ %s:%d",
240 clientResponse->devAddr.addr,
241 clientResponse->devAddr.port);
242 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
244 collectUniqueResource(clientResponse);
248 OIC_LOG(ERROR, TAG, "<====DISCOVERY Callback fail to receive clientResponse====>\n");
250 return (UnicastDiscovery) ?
251 OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
254 int InitPutRequest(OCQualityOfService qos)
256 std::ostringstream query;
257 //Get most recently inserted resource
258 const ResourceNode * resource = getResource();
262 OIC_LOG_V(ERROR, TAG, "Resource null, can't do PUT request\n");
265 query << resource->uri;
266 OIC_LOG_V(INFO, TAG,"Executing InitPutRequest, Query: %s", query.str().c_str());
268 return (InvokeOCDoResource(query, OC_REST_PUT, &resource->endpoint,
269 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
273 int InitPostRequest(OCQualityOfService qos)
275 OCStackResult result;
276 std::ostringstream query;
277 //Get most recently inserted resource
278 const ResourceNode *resource = getResource();
282 OIC_LOG_V(ERROR, TAG, "Resource null, can't do POST request\n");
286 query << resource->uri;
287 OIC_LOG_V(INFO, TAG,"Executing InitPostRequest, Query: %s", query.str().c_str());
289 // First POST operation (to create an LED instance)
290 result = InvokeOCDoResource(query, OC_REST_POST, &resource->endpoint,
291 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
293 if (OC_STACK_OK != result)
295 // Error can happen if for example, network connectivity is down
296 OIC_LOG(ERROR, TAG, "First POST call did not succeed");
299 // Second POST operation (to create an LED instance)
300 result = InvokeOCDoResource(query, OC_REST_POST, &resource->endpoint,
301 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
303 if (OC_STACK_OK != result)
305 OIC_LOG(ERROR, TAG, "Second POST call did not succeed");
308 // This POST operation will update the original resourced /a/led
309 return (InvokeOCDoResource(query, OC_REST_POST, &resource->endpoint,
310 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
311 postReqCB, NULL, 0));
314 int InitGetRequest(OCQualityOfService qos)
316 std::ostringstream query;
317 //Get most recently inserted resource
318 const ResourceNode * resource = getResource();
322 OIC_LOG_V(ERROR, TAG, "Resource null, can't do GET request\n");
325 query << resource->uri;
326 OIC_LOG_V(INFO, TAG,"Executing InitGetRequest, Query: %s", query.str().c_str());
328 return (InvokeOCDoResource(query, OC_REST_GET, &resource->endpoint,
329 (qos == OC_HIGH_QOS)?OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
335 OCCallbackData cbData;
337 char ipaddr[100] = { '\0' };
339 if (UnicastDiscovery)
341 OIC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
342 OIC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
343 OIC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
345 if (fgets(ipaddr, sizeof (ipaddr), stdin))
347 StripNewLineChar(ipaddr); //Strip newline char from ipaddr
351 OIC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
352 return OC_STACK_INVALID_PARAM;
356 snprintf(queryUri, sizeof (queryUri), RESOURCE_DISCOVERY_QUERY, ipaddr);
358 cbData.cb = discoveryReqCB;
359 cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
362 ret = OCDoResource(NULL, OC_REST_DISCOVER, queryUri, 0, 0, CT_DEFAULT,
363 OC_LOW_QOS, &cbData, NULL, 0);
364 if (ret != OC_STACK_OK)
366 OIC_LOG(ERROR, TAG, "OCStack resource error");
375 case TEST_DISCOVER_REQ:
377 case TEST_NON_CON_OP:
378 InitGetRequest(OC_LOW_QOS);
379 InitPutRequest(OC_LOW_QOS);
380 InitPostRequest(OC_LOW_QOS);
383 InitGetRequest(OC_HIGH_QOS);
384 InitPutRequest(OC_HIGH_QOS);
385 InitPostRequest(OC_HIGH_QOS);
394 void collectUniqueResource(const OCClientResponse * clientResponse)
396 OCDiscoveryPayload* pay = (OCDiscoveryPayload*) clientResponse->payload;
397 OCResourcePayload* res = pay->resources;
399 // Including the NUL terminator, length of UUID string of the form:
400 // "a62389f7-afde-00b6-cd3e-12b97d2fcf09"
401 # define UUID_LENGTH 37
403 char sidStr[UUID_LENGTH];
407 int ret = snprintf(sidStr, UUID_LENGTH,
408 "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
409 pay->sid[0], pay->sid[1], pay->sid[2], pay->sid[3],
410 pay->sid[4], pay->sid[5], pay->sid[6], pay->sid[7],
411 pay->sid[8], pay->sid[9], pay->sid[10], pay->sid[11],
412 pay->sid[12], pay->sid[13], pay->sid[14], pay->sid[15]
415 if (ret == UUID_LENGTH - 1)
417 if(insertResource(sidStr, res->uri, clientResponse) == 1)
419 OIC_LOG_V(INFO,TAG,"%s%s%s%s\n",sidStr, ":", res->uri, " is new");
424 OIC_LOG_V(INFO,TAG,"%s%s%s%s\n",sidStr, ":", res->uri, " is old");
429 OIC_LOG(ERROR, TAG, "Could Not Retrieve the Server ID");
436 /* This function searches for the resource(sid:uri) in the ResourceList.
437 * If the Resource is found in the list then it returns 0 else insert
438 * the resource to front of the list and returns 1.
440 int insertResource(const char * sid, char const * uri,
441 const OCClientResponse * clientResponse)
443 ResourceNode * iter = resourceList;
444 char * sid_cpy = OICStrdup(sid);
445 char * uri_cpy = OICStrdup(uri);
447 //Checking if the resource(sid:uri) is new
450 if((strcmp(iter->sid, sid) == 0) && (strcmp(iter->uri, uri) == 0))
462 //Creating new ResourceNode
463 if((iter = (ResourceNode *) OICMalloc(sizeof(ResourceNode))))
467 iter->endpoint = clientResponse->devAddr;
472 OIC_LOG(ERROR, TAG, "Memory not allocated to ResourceNode");
478 //Adding new ResourceNode to front of the ResourceList
485 iter->next = resourceList;
491 void printResourceList()
495 OIC_LOG(INFO, TAG, "Resource List: ");
498 OIC_LOG(INFO, TAG, "*****************************************************");
499 OIC_LOG_V(INFO, TAG, "sid = %s",iter->sid);
500 OIC_LOG_V(INFO, TAG, "uri = %s", iter->uri);
501 OIC_LOG_V(INFO, TAG, "ip = %s", iter->endpoint.addr);
502 OIC_LOG_V(INFO, TAG, "port = %d", iter->endpoint.port);
503 switch (iter->endpoint.adapter)
506 OIC_LOG(INFO, TAG, "connType = Default (IPv4)");
508 case OC_ADAPTER_GATT_BTLE:
509 OIC_LOG(INFO, TAG, "connType = BLE");
511 case OC_ADAPTER_RFCOMM_BTEDR:
512 OIC_LOG(INFO, TAG, "connType = BT");
515 OIC_LOG(INFO, TAG, "connType = Invalid connType");
518 OIC_LOG(INFO, TAG, "*****************************************************");
523 void freeResourceList()
525 OIC_LOG(INFO, TAG, "Freeing ResourceNode List");
531 resourceList = resourceList->next;
532 OICFree((void *)temp->sid);
533 OICFree((void *)temp->uri);
539 int main(int argc, char* argv[])
543 while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
548 UnicastDiscovery = atoi(optarg);
551 TestCase = atoi(optarg);
554 Connectivity = atoi(optarg);
562 if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||
563 (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS) ||
564 (Connectivity < CT_ADAPTER_DEFAULT || Connectivity >= MAX_CT))
570 /* Initialize OCStack*/
571 if (OCInit1(OC_CLIENT, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS) != OC_STACK_OK)
573 OIC_LOG(ERROR, TAG, "OCStack init error");
577 if(Connectivity == CT_ADAPTER_DEFAULT || Connectivity == CT_IP)
579 ConnType = CT_ADAPTER_IP;//CT_DEFAULT;
583 OIC_LOG(INFO, TAG, "Default Connectivity type selected");
589 // Break from loop with Ctrl+C
590 signal(SIGINT, handleSigInt);
594 if (OCProcess() != OC_STACK_OK)
596 OIC_LOG(ERROR, TAG, "OCStack process error");
603 OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
604 if (OCStop() != OC_STACK_OK)
606 OIC_LOG(ERROR, TAG, "OCStack stop error");