Merge "[CA-Integration] Use 5298 port for MC query since CA uses 5298 as MC port...
[platform/upstream/iotivity.git] / resource / csdk / stack / samples / linux / SimpleClientServer / occlient.cpp
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
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 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <signal.h>
25 #include <unistd.h>
26 #include <iostream>
27 #include <sstream>
28 #include "ocstack.h"
29 #include "logger.h"
30 #include "occlient.h"
31
32 static int UNICAST_DISCOVERY = 0;
33 static int TEST_CASE = 0;
34 static const char * TEST_APP_UNICAST_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core";
35 static std::string putPayload = "{\"state\":\"on\",\"power\":5}";
36 static std::string coapServerIP = "255.255.255.255";
37 static std::string coapServerPort = "5683";
38 static std::string coapServerResource = "/a/light";
39
40 // The handle for the observe registration
41 OCDoHandle gObserveDoHandle;
42 #ifdef WITH_PRESENCE
43 // The handle for observe registration
44 OCDoHandle gPresenceHandle;
45 #endif
46 // After this crosses a threshold client deregisters for further notifications
47 int gNumObserveNotifies = 0;
48
49 #ifdef WITH_PRESENCE
50 int gNumPresenceNotifies = 0;
51 #endif
52
53 int gQuitFlag = 0;
54 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
55 void handleSigInt(int signum) {
56     if (signum == SIGINT) {
57         gQuitFlag = 1;
58     }
59 }
60
61 static void PrintUsage()
62 {
63     OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3|4|5|6|7>");
64     OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
65     OC_LOG(INFO, TAG, "-t 1  :  Discover Resources");
66     OC_LOG(INFO, TAG, "-t 2  :  Discover Resources and Initiate Nonconfirmable Get Request");
67     OC_LOG(INFO, TAG, "-t 3  :  Discover Resources and Initiate Nonconfirmable Put Requests");
68     OC_LOG(INFO, TAG, "-t 4  :  Discover Resources and Initiate Nonconfirmable Post Requests");
69     OC_LOG(INFO, TAG, "-t 5  :  Discover Resources and Initiate Nonconfirmable Delete Requests");
70     OC_LOG(INFO, TAG, "-t 6  :  Discover Resources and Initiate Nonconfirmable Observe Requests");
71     OC_LOG(INFO, TAG, "-t 7  :  Discover Resources and Initiate Nonconfirmable Get Request for a resource which is unavailable");
72
73     OC_LOG(INFO, TAG, "-t 8  :  Discover Resources and Initiate Confirmable Get Request");
74     OC_LOG(INFO, TAG, "-t 9  :  Discover Resources and Initiate Confirmable Post Request");
75     OC_LOG(INFO, TAG, "-t 10 :  Discover Resources and Initiate Confirmable Delete Requests");
76     OC_LOG(INFO, TAG, "-t 11 :  Discover Resources and Initiate Confirmable Observe Requests");
77
78     #ifdef WITH_PRESENCE
79     OC_LOG(INFO, TAG, "-t 12 :  Discover Resources and Initiate Nonconfirmable presence");
80     OC_LOG(INFO, TAG, "-t 13 :  Discover Resources and Initiate Nonconfirmable presence with filter");
81     #endif
82
83     OC_LOG(INFO, TAG, "-t 14 :  Discover Resources and Initiate Nonconfirmable Observe Requests then cancel immediately");
84     OC_LOG(INFO, TAG, "-t 15 :  Discover Resources and Initiate Nonconfirmable Get Request and add  vendor specific header options");
85 }
86
87 OCStackResult InvokeOCDoResource(std::ostringstream &query,
88                                  OCMethod method, OCQualityOfService qos,
89                                  OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
90 {
91     OCStackResult ret;
92     OCCallbackData cbData;
93     OCDoHandle handle;
94
95     cbData.cb = cb;
96     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
97     cbData.cd = NULL;
98
99     ret = OCDoResource(&handle, method, query.str().c_str(), 0,
100                        (method == OC_REST_PUT) ? putPayload.c_str() : NULL,
101                        qos, &cbData, options, numOptions);
102
103     if (ret != OC_STACK_OK)
104     {
105         OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
106     }
107     else if (method == OC_REST_OBSERVE || method == OC_REST_OBSERVE_ALL)
108     {
109         gObserveDoHandle = handle;
110     }
111     #ifdef WITH_PRESENCE
112     else if (method == OC_REST_PRESENCE)
113     {
114         gPresenceHandle = handle;
115     }
116     #endif
117
118     return ret;
119 }
120
121 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
122     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
123     {
124         OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
125     }
126
127     if(clientResponse)
128     {
129         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
130         OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response", clientResponse->resJSONPayload);
131     }
132     return OC_STACK_DELETE_TRANSACTION;
133 }
134
135 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
136 {
137     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
138     {
139         OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
140     }
141
142     if(clientResponse)
143     {
144         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
145         OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response", clientResponse->resJSONPayload);
146     }
147     return OC_STACK_DELETE_TRANSACTION;
148 }
149
150 OCStackApplicationResult deleteReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
151 {
152     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
153     {
154         OC_LOG(INFO, TAG, "Callback Context for DELETE recvd successfully");
155     }
156
157     if(clientResponse)
158     {
159         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
160         OC_LOG_V(INFO, TAG, "JSON = %s =============> Delete Response", clientResponse->resJSONPayload);
161     }
162     return OC_STACK_DELETE_TRANSACTION;
163 }
164
165 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
166 {
167     if(clientResponse == NULL)
168     {
169         OC_LOG(INFO, TAG, "The clientResponse is NULL");
170         return   OC_STACK_DELETE_TRANSACTION;
171     }
172     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
173     {
174         OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
175     }
176
177     OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
178     OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
179     OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response", clientResponse->resJSONPayload);
180
181     if(clientResponse->rcvdVendorSpecificHeaderOptions &&
182             clientResponse->numRcvdVendorSpecificHeaderOptions)
183     {
184         OC_LOG (INFO, TAG, "Received vendor specific options");
185         uint8_t i = 0;
186         OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
187         for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
188         {
189             if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
190             {
191                 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
192                         ((OCHeaderOption)rcvdOptions[i]).optionID );
193                 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
194                         ((OCHeaderOption)rcvdOptions[i]).optionLength);
195             }
196         }
197     }
198     return OC_STACK_DELETE_TRANSACTION;
199 }
200
201 OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
202     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
203     {
204         OC_LOG(INFO, TAG, "Callback Context for OBS query recvd successfully");
205     }
206
207     if(clientResponse)
208     {
209         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
210         OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
211         OC_LOG_V(INFO, TAG, "Callback Context for OBSERVE notification recvd successfully %d", gNumObserveNotifies);
212         OC_LOG_V(INFO, TAG, "JSON = %s =============> Obs Response", clientResponse->resJSONPayload);
213         gNumObserveNotifies++;
214         if (gNumObserveNotifies == 3)   //large number to test observing in DELETE case.
215         {
216             if(TEST_CASE == TEST_OBS_REQ_NON || TEST_CASE == TEST_OBS_REQ_CON){
217                 if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK){
218                     OC_LOG(ERROR, TAG, "Observe cancel error");
219                 }
220                 return OC_STACK_DELETE_TRANSACTION;
221             }else if(TEST_CASE == TEST_OBS_REQ_NON_CANCEL_IMM){
222                 if (OCCancel (gObserveDoHandle, OC_HIGH_QOS, NULL, 0) != OC_STACK_OK){
223                     OC_LOG(ERROR, TAG, "Observe cancel error");
224                 }
225             }
226         }
227         if(clientResponse->sequenceNumber == OC_OBSERVE_REGISTER){
228             OC_LOG(INFO, TAG, "This also serves as a registration confirmation");
229         }else if(clientResponse->sequenceNumber == OC_OBSERVE_DEREGISTER){
230             OC_LOG(INFO, TAG, "This also serves as a deregistration confirmation");
231             return OC_STACK_DELETE_TRANSACTION;
232         }else if(clientResponse->sequenceNumber == OC_OBSERVE_NO_OPTION){
233             OC_LOG(INFO, TAG, "This also tells you that registration/deregistration failed");
234             return OC_STACK_DELETE_TRANSACTION;
235         }
236     }
237     return OC_STACK_KEEP_TRANSACTION;
238 }
239 #ifdef WITH_PRESENCE
240 OCStackApplicationResult presenceCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
241     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
242     {
243         OC_LOG(INFO, TAG, "Callback Context for Presence recvd successfully");
244     }
245
246     if(clientResponse)
247     {
248         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
249         OC_LOG_V(INFO, TAG, "NONCE NUMBER: %u", clientResponse->sequenceNumber);
250         OC_LOG_V(INFO, TAG, "Callback Context for Presence notification recvd successfully %d", gNumPresenceNotifies);
251         OC_LOG_V(INFO, TAG, "JSON = %s =============> Presence Response", clientResponse->resJSONPayload);
252         gNumPresenceNotifies++;
253         if (gNumPresenceNotifies == 20)
254         {
255             if (OCCancel (gPresenceHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK){
256                 OC_LOG(ERROR, TAG, "Presence cancel error");
257             }
258             return OC_STACK_DELETE_TRANSACTION;
259         }
260     }
261     return OC_STACK_KEEP_TRANSACTION;
262 }
263 #endif
264
265 // This is a function called back when a device is discovered
266 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
267         OCClientResponse * clientResponse) {
268     uint8_t remoteIpAddr[4];
269     uint16_t remotePortNu;
270
271     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
272     {
273         OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
274     }
275
276     if (clientResponse)
277     {
278         OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
279
280         OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
281                 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
282         OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
283
284         OC_LOG_V(INFO, TAG,
285                 "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
286                 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
287                 remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
288
289         parseClientResponse(clientResponse);
290
291         switch(TEST_CASE)
292         {
293             case TEST_GET_REQ_NON:
294                 InitGetRequest(OC_LOW_QOS, 0);
295                 break;
296             case TEST_PUT_REQ_NON:
297                 InitPutRequest();
298                 break;
299             case TEST_POST_REQ_NON:
300                 InitPostRequest(OC_LOW_QOS);
301                 break;
302             case TEST_DELETE_REQ_NON:
303                 InitDeleteRequest(OC_LOW_QOS);
304                 break;
305             case TEST_OBS_REQ_NON:
306             case TEST_OBS_REQ_NON_CANCEL_IMM:
307                 InitObserveRequest(OC_LOW_QOS);
308                 break;
309             case TEST_GET_UNAVAILABLE_RES_REQ_NON:
310                 InitGetRequestToUnavailableResource();
311                 break;
312             case TEST_GET_REQ_CON:
313                 InitGetRequest(OC_HIGH_QOS, 0);
314                 break;
315             case TEST_POST_REQ_CON:
316                 InitPostRequest(OC_HIGH_QOS);
317                 break;
318             case TEST_DELETE_REQ_CON:
319                 InitDeleteRequest(OC_HIGH_QOS);
320                 break;
321             case TEST_OBS_REQ_CON:
322                 InitObserveRequest(OC_HIGH_QOS);
323                 break;
324             #ifdef WITH_PRESENCE
325             case TEST_OBS_PRESENCE:
326             case TEST_OBS_PRESENCE_WITH_FILTER:
327                 InitPresence();
328                 break;
329             #endif
330             case TEST_GET_REQ_NON_WITH_VENDOR_HEADER_OPTIONS:
331                 InitGetRequest(OC_LOW_QOS, 1);
332                 break;
333             default:
334                 PrintUsage();
335                 break;
336         }
337     }
338
339     return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
340
341 }
342 #ifdef WITH_PRESENCE
343 int InitPresence()
344 {
345     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
346     std::ostringstream query;
347     query << "coap://" << coapServerIP << ":" << coapServerPort << OC_PRESENCE_URI;
348     if(TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTER)
349     {
350         query << "?rt=core.light";
351     }
352     return (InvokeOCDoResource(query, OC_REST_PRESENCE, OC_LOW_QOS, presenceCB, NULL, 0));
353 }
354 #endif
355 int InitGetRequestToUnavailableResource()
356 {
357     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
358     std::ostringstream query;
359     query << "coap://" << coapServerIP << ":" << coapServerPort << "/SomeUnknownResource";
360     return (InvokeOCDoResource(query, OC_REST_GET, OC_LOW_QOS, getReqCB, NULL, 0));
361 }
362
363 int InitObserveRequest(OCQualityOfService qos)
364 {
365     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
366     std::ostringstream query;
367     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
368     return (InvokeOCDoResource(query, OC_REST_OBSERVE, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, obsReqCB, NULL, 0));
369 }
370
371 int InitPutRequest()
372 {
373     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
374     std::ostringstream query;
375     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
376     return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0));
377 }
378
379 int InitPostRequest(OCQualityOfService qos)
380 {
381     OCStackResult result;
382     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
383     std::ostringstream query;
384     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
385
386     // First POST operation (to create an Light instance)
387     result = InvokeOCDoResource(query, OC_REST_POST,
388                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
389                                postReqCB, NULL, 0);
390     if (OC_STACK_OK != result)
391     {
392         // Error can happen if for example, network connectivity is down
393         OC_LOG(INFO, TAG, "First POST call did not succeed");
394     }
395
396     // Second POST operation (to create an Light instance)
397     result = InvokeOCDoResource(query, OC_REST_POST,
398                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
399                                postReqCB, NULL, 0);
400     if (OC_STACK_OK != result)
401     {
402         OC_LOG(INFO, TAG, "Second POST call did not succeed");
403     }
404
405     // This POST operation will update the original resourced /a/light
406     return (InvokeOCDoResource(query, OC_REST_POST,
407                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
408                                postReqCB, NULL, 0));
409 }
410
411 void* RequestDeleteDeathResourceTask(void* myqos)
412 {
413     sleep (30); //long enough to give the server time to finish deleting the resource.
414     std::ostringstream query;
415     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
416
417     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
418
419     // Second DELETE operation to delete the resource that might have been removed already.
420     OCQualityOfService qos;
421     if (myqos == NULL)
422         qos = OC_LOW_QOS;
423     else
424         qos = OC_HIGH_QOS;
425
426     OCStackResult result = InvokeOCDoResource(query, OC_REST_DELETE,
427                                qos,
428                                deleteReqCB, NULL, 0);
429
430     if (OC_STACK_OK != result)
431     {
432         OC_LOG(INFO, TAG, "Second DELETE call did not succeed");
433     }
434
435     return NULL;
436 }
437
438 int InitDeleteRequest(OCQualityOfService qos)
439 {
440     OCStackResult result;
441     std::ostringstream query;
442     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
443
444     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
445
446     // First DELETE operation
447     result = InvokeOCDoResource(query, OC_REST_DELETE,
448                                qos,
449                                deleteReqCB, NULL, 0);
450     if (OC_STACK_OK != result)
451     {
452         // Error can happen if for example, network connectivity is down
453         OC_LOG(INFO, TAG, "First DELETE call did not succeed");
454     }
455     else
456     {
457         //Create a thread to delete this resource again
458         pthread_t threadId;
459         pthread_create (&threadId, NULL, RequestDeleteDeathResourceTask, (void*)qos);
460     }
461
462     OC_LOG_V(INFO, TAG, "\n\nExit  %s", __func__);
463     return result;
464 }
465
466 int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptions)
467 {
468     OCHeaderOption options[MAX_HEADER_OPTIONS];
469
470     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
471     std::ostringstream query;
472     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
473
474     if(withVendorSpecificHeaderOptions)
475     {
476         uint8_t option0[] = {1,2,3,4,5,6,7,8,9,10};
477         uint8_t option1[] = {11,12,13,14,15,16,17,18,19,20};
478         memset(options, 0, sizeof(OCHeaderOption) * MAX_HEADER_OPTIONS);
479         options[0].protocolID = OC_COAP_ID;
480         options[0].optionID = 2048;
481         memcpy(options[0].optionData, option0, sizeof(option0));
482         options[0].optionLength = 10;
483         options[1].protocolID = OC_COAP_ID;
484         options[1].optionID = 3000;
485         memcpy(options[1].optionData, option1, sizeof(option1));
486         options[1].optionLength = 10;
487     }
488     if(withVendorSpecificHeaderOptions)
489     {
490         return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, getReqCB, options, 2));
491     }
492     else
493     {
494         return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
495     }
496 }
497
498 int InitDiscovery()
499 {
500     OCStackResult ret;
501     OCCallbackData cbData;
502     OCDoHandle handle;
503     /* Start a discovery query*/
504     char szQueryUri[64] = { 0 };
505     if (UNICAST_DISCOVERY)
506     {
507         strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY);
508     }
509     else
510     {
511     #ifdef CA_INT
512         // TODO-CA CA is using 5298 for MC. Why 5298?
513         strcpy(szQueryUri, "coap://224.0.1.187:5298/oc/core");
514     #else
515         strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
516     #endif
517     }
518     cbData.cb = discoveryReqCB;
519     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
520     cbData.cd = NULL;
521     ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
522     if (ret != OC_STACK_OK)
523     {
524         OC_LOG(ERROR, TAG, "OCStack resource error");
525     }
526     return ret;
527 }
528
529 int main(int argc, char* argv[]) {
530     uint8_t addr[20] = {0};
531     uint8_t* paddr = NULL;
532     uint16_t port = USE_RANDOM_PORT;
533     uint8_t ifname[] = "eth0";
534     int opt;
535
536     while ((opt = getopt(argc, argv, "u:t:")) != -1)
537     {
538         switch(opt)
539         {
540             case 'u':
541                 UNICAST_DISCOVERY = atoi(optarg);
542                 break;
543             case 't':
544                 TEST_CASE = atoi(optarg);
545                 break;
546             default:
547                 PrintUsage();
548                 return -1;
549         }
550     }
551
552     if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
553             (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
554     {
555         PrintUsage();
556         return -1;
557     }
558
559
560     /*Get Ip address on defined interface and initialize coap on it with random port number
561      * this port number will be used as a source port in all coap communications*/
562     if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
563                 sizeof(addr)) == ERR_SUCCESS)
564     {
565         OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
566         paddr = addr;
567     }
568
569     /* Initialize OCStack*/
570     if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK) {
571         OC_LOG(ERROR, TAG, "OCStack init error");
572         return 0;
573     }
574
575     InitDiscovery();
576
577     // Break from loop with Ctrl+C
578     OC_LOG(INFO, TAG, "Entering occlient main loop...");
579     signal(SIGINT, handleSigInt);
580     while (!gQuitFlag) {
581
582         if (OCProcess() != OC_STACK_OK) {
583             OC_LOG(ERROR, TAG, "OCStack process error");
584             return 0;
585         }
586
587         sleep(2);
588     }
589     OC_LOG(INFO, TAG, "Exiting occlient main loop...");
590
591     if (OCStop() != OC_STACK_OK) {
592         OC_LOG(ERROR, TAG, "OCStack stop error");
593     }
594
595     return 0;
596 }
597
598 std::string getIPAddrTBServer(OCClientResponse * clientResponse) {
599     if(!clientResponse) return "";
600     if(!clientResponse->addr) return "";
601     uint8_t a, b, c, d = 0;
602     if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
603
604     char ipaddr[16] = {'\0'};
605     snprintf(ipaddr,  sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d); // ostringstream not working correctly here, hence snprintf
606     return std::string (ipaddr);
607 }
608
609 std::string getPortTBServer(OCClientResponse * clientResponse){
610     if(!clientResponse) return "";
611     if(!clientResponse->addr) return "";
612     uint16_t p = 0;
613     if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
614     std::ostringstream ss;
615     ss << p;
616     return ss.str();
617 }
618
619 std::string getQueryStrForGetPut(OCClientResponse * clientResponse){
620
621     return "/a/light";
622 }
623
624 void parseClientResponse(OCClientResponse * clientResponse){
625     coapServerIP = getIPAddrTBServer(clientResponse);
626     coapServerPort = getPortTBServer(clientResponse);
627     coapServerResource = getQueryStrForGetPut(clientResponse);
628 }