095647ccdee69351012df51d4b460119be48c02e
[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     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
167     {
168         OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
169     }
170
171     if(clientResponse)
172     {
173         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
174         OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
175         OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response", clientResponse->resJSONPayload);
176     }
177     if(clientResponse->rcvdVendorSpecificHeaderOptions &&
178             clientResponse->numRcvdVendorSpecificHeaderOptions)
179     {
180         OC_LOG (INFO, TAG, "Received vendor specific options");
181         uint8_t i = 0;
182         OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
183         for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
184         {
185             if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
186             {
187                 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
188                         ((OCHeaderOption)rcvdOptions[i]).optionID );
189                 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
190                         ((OCHeaderOption)rcvdOptions[i]).optionLength);
191             }
192         }
193     }
194     return OC_STACK_DELETE_TRANSACTION;
195 }
196
197 OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
198     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
199     {
200         OC_LOG(INFO, TAG, "Callback Context for OBS query recvd successfully");
201     }
202
203     if(clientResponse)
204     {
205         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
206         OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
207         OC_LOG_V(INFO, TAG, "Callback Context for OBSERVE notification recvd successfully %d", gNumObserveNotifies);
208         OC_LOG_V(INFO, TAG, "JSON = %s =============> Obs Response", clientResponse->resJSONPayload);
209         gNumObserveNotifies++;
210         if (gNumObserveNotifies == 3)   //large number to test observing in DELETE case.
211         {
212             if(TEST_CASE == TEST_OBS_REQ_NON || TEST_CASE == TEST_OBS_REQ_CON){
213                 if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK){
214                     OC_LOG(ERROR, TAG, "Observe cancel error");
215                 }
216                 return OC_STACK_DELETE_TRANSACTION;
217             }else if(TEST_CASE == TEST_OBS_REQ_NON_CANCEL_IMM){
218                 if (OCCancel (gObserveDoHandle, OC_HIGH_QOS, NULL, 0) != OC_STACK_OK){
219                     OC_LOG(ERROR, TAG, "Observe cancel error");
220                 }
221             }
222         }
223         if(clientResponse->sequenceNumber == OC_OBSERVE_REGISTER){
224             OC_LOG(INFO, TAG, "This also serves as a registration confirmation");
225         }else if(clientResponse->sequenceNumber == OC_OBSERVE_DEREGISTER){
226             OC_LOG(INFO, TAG, "This also serves as a deregistration confirmation");
227             return OC_STACK_DELETE_TRANSACTION;
228         }else if(clientResponse->sequenceNumber == OC_OBSERVE_NO_OPTION){
229             OC_LOG(INFO, TAG, "This also tells you that registration/deregistration failed");
230             return OC_STACK_DELETE_TRANSACTION;
231         }
232     }
233     return OC_STACK_KEEP_TRANSACTION;
234 }
235 #ifdef WITH_PRESENCE
236 OCStackApplicationResult presenceCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
237     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
238     {
239         OC_LOG(INFO, TAG, "Callback Context for Presence recvd successfully");
240     }
241
242     if(clientResponse)
243     {
244         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
245         OC_LOG_V(INFO, TAG, "NONCE NUMBER: %u", clientResponse->sequenceNumber);
246         OC_LOG_V(INFO, TAG, "Callback Context for Presence notification recvd successfully %d", gNumPresenceNotifies);
247         OC_LOG_V(INFO, TAG, "JSON = %s =============> Presence Response", clientResponse->resJSONPayload);
248         gNumPresenceNotifies++;
249         if (gNumPresenceNotifies == 20)
250         {
251             if (OCCancel (gPresenceHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK){
252                 OC_LOG(ERROR, TAG, "Presence cancel error");
253             }
254             return OC_STACK_DELETE_TRANSACTION;
255         }
256     }
257     return OC_STACK_KEEP_TRANSACTION;
258 }
259 #endif
260
261 // This is a function called back when a device is discovered
262 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
263         OCClientResponse * clientResponse) {
264     uint8_t remoteIpAddr[4];
265     uint16_t remotePortNu;
266
267     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
268     {
269         OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
270     }
271
272     if (clientResponse)
273     {
274         OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
275
276         OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
277                 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
278         OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
279
280         OC_LOG_V(INFO, TAG,
281                 "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
282                 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
283                 remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
284
285         parseClientResponse(clientResponse);
286
287         switch(TEST_CASE)
288         {
289             case TEST_GET_REQ_NON:
290                 InitGetRequest(OC_LOW_QOS, 0);
291                 break;
292             case TEST_PUT_REQ_NON:
293                 InitPutRequest();
294                 break;
295             case TEST_POST_REQ_NON:
296                 InitPostRequest(OC_LOW_QOS);
297                 break;
298             case TEST_DELETE_REQ_NON:
299                 InitDeleteRequest(OC_LOW_QOS);
300                 break;
301             case TEST_OBS_REQ_NON:
302             case TEST_OBS_REQ_NON_CANCEL_IMM:
303                 InitObserveRequest(OC_LOW_QOS);
304                 break;
305             case TEST_GET_UNAVAILABLE_RES_REQ_NON:
306                 InitGetRequestToUnavailableResource();
307                 break;
308             case TEST_GET_REQ_CON:
309                 InitGetRequest(OC_HIGH_QOS, 0);
310                 break;
311             case TEST_POST_REQ_CON:
312                 InitPostRequest(OC_HIGH_QOS);
313                 break;
314             case TEST_DELETE_REQ_CON:
315                 InitDeleteRequest(OC_HIGH_QOS);
316                 break;
317             case TEST_OBS_REQ_CON:
318                 InitObserveRequest(OC_HIGH_QOS);
319                 break;
320             #ifdef WITH_PRESENCE
321             case TEST_OBS_PRESENCE:
322             case TEST_OBS_PRESENCE_WITH_FILTER:
323                 InitPresence();
324                 break;
325             #endif
326             case TEST_GET_REQ_NON_WITH_VENDOR_HEADER_OPTIONS:
327                 InitGetRequest(OC_LOW_QOS, 1);
328                 break;
329             default:
330                 PrintUsage();
331                 break;
332         }
333     }
334
335     return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
336
337 }
338 #ifdef WITH_PRESENCE
339 int InitPresence()
340 {
341     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
342     std::ostringstream query;
343     query << "coap://" << coapServerIP << ":" << coapServerPort << OC_PRESENCE_URI;
344     if(TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTER)
345     {
346         query << "?rt=core.light";
347     }
348     return (InvokeOCDoResource(query, OC_REST_PRESENCE, OC_LOW_QOS, presenceCB, NULL, 0));
349 }
350 #endif
351 int InitGetRequestToUnavailableResource()
352 {
353     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
354     std::ostringstream query;
355     query << "coap://" << coapServerIP << ":" << coapServerPort << "/SomeUnknownResource";
356     return (InvokeOCDoResource(query, OC_REST_GET, OC_LOW_QOS, getReqCB, NULL, 0));
357 }
358
359 int InitObserveRequest(OCQualityOfService qos)
360 {
361     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
362     std::ostringstream query;
363     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
364     return (InvokeOCDoResource(query, OC_REST_OBSERVE, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, obsReqCB, NULL, 0));
365 }
366
367 int InitPutRequest()
368 {
369     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
370     std::ostringstream query;
371     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
372     return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0));
373 }
374
375 int InitPostRequest(OCQualityOfService qos)
376 {
377     OCStackResult result;
378     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
379     std::ostringstream query;
380     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
381
382     // First POST operation (to create an Light instance)
383     result = InvokeOCDoResource(query, OC_REST_POST,
384                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
385                                postReqCB, NULL, 0);
386     if (OC_STACK_OK != result)
387     {
388         // Error can happen if for example, network connectivity is down
389         OC_LOG(INFO, TAG, "First POST call did not succeed");
390     }
391
392     // Second POST operation (to create an Light instance)
393     result = InvokeOCDoResource(query, OC_REST_POST,
394                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
395                                postReqCB, NULL, 0);
396     if (OC_STACK_OK != result)
397     {
398         OC_LOG(INFO, TAG, "Second POST call did not succeed");
399     }
400
401     // This POST operation will update the original resourced /a/light
402     return (InvokeOCDoResource(query, OC_REST_POST,
403                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
404                                postReqCB, NULL, 0));
405 }
406
407 void* RequestDeleteDeathResourceTask(void* myqos)
408 {
409     sleep (30); //long enough to give the server time to finish deleting the resource.
410     std::ostringstream query;
411     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
412
413     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
414
415     // Second DELETE operation to delete the resource that might have been removed already.
416     OCQualityOfService qos;
417     if (myqos == NULL)
418         qos = OC_LOW_QOS;
419     else
420         qos = OC_HIGH_QOS;
421
422     OCStackResult result = InvokeOCDoResource(query, OC_REST_DELETE,
423                                qos,
424                                deleteReqCB, NULL, 0);
425
426     if (OC_STACK_OK != result)
427     {
428         OC_LOG(INFO, TAG, "Second DELETE call did not succeed");
429     }
430
431     return NULL;
432 }
433
434 int InitDeleteRequest(OCQualityOfService qos)
435 {
436     OCStackResult result;
437     std::ostringstream query;
438     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
439
440     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
441
442     // First DELETE operation
443     result = InvokeOCDoResource(query, OC_REST_DELETE,
444                                qos,
445                                deleteReqCB, NULL, 0);
446     if (OC_STACK_OK != result)
447     {
448         // Error can happen if for example, network connectivity is down
449         OC_LOG(INFO, TAG, "First DELETE call did not succeed");
450     }
451     else
452     {
453         //Create a thread to delete this resource again
454         pthread_t threadId;
455         pthread_create (&threadId, NULL, RequestDeleteDeathResourceTask, (void*)qos);
456     }
457
458     OC_LOG_V(INFO, TAG, "\n\nExit  %s", __func__);
459     return result;
460 }
461
462 int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptions)
463 {
464     OCHeaderOption options[MAX_HEADER_OPTIONS];
465
466     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
467     std::ostringstream query;
468     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
469
470     if(withVendorSpecificHeaderOptions)
471     {
472         uint8_t option0[] = {1,2,3,4,5,6,7,8,9,10};
473         uint8_t option1[] = {11,12,13,14,15,16,17,18,19,20};
474         memset(options, 0, sizeof(OCHeaderOption) * MAX_HEADER_OPTIONS);
475         options[0].protocolID = OC_COAP_ID;
476         options[0].optionID = 2048;
477         memcpy(options[0].optionData, option0, sizeof(option0));
478         options[0].optionLength = 10;
479         options[1].protocolID = OC_COAP_ID;
480         options[1].optionID = 3000;
481         memcpy(options[1].optionData, option1, sizeof(option1));
482         options[1].optionLength = 10;
483     }
484     if(withVendorSpecificHeaderOptions)
485     {
486         return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, getReqCB, options, 2));
487     }
488     else
489     {
490         return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
491     }
492 }
493
494 int InitDiscovery()
495 {
496     OCStackResult ret;
497     OCCallbackData cbData;
498     OCDoHandle handle;
499     /* Start a discovery query*/
500     char szQueryUri[64] = { 0 };
501     if (UNICAST_DISCOVERY)
502     {
503         strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY);
504     }
505     else
506     {
507         strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
508     }
509     cbData.cb = discoveryReqCB;
510     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
511     cbData.cd = NULL;
512     ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
513     if (ret != OC_STACK_OK)
514     {
515         OC_LOG(ERROR, TAG, "OCStack resource error");
516     }
517     return ret;
518 }
519
520 int main(int argc, char* argv[]) {
521     uint8_t addr[20] = {0};
522     uint8_t* paddr = NULL;
523     uint16_t port = USE_RANDOM_PORT;
524     uint8_t ifname[] = "eth0";
525     int opt;
526
527     while ((opt = getopt(argc, argv, "u:t:")) != -1)
528     {
529         switch(opt)
530         {
531             case 'u':
532                 UNICAST_DISCOVERY = atoi(optarg);
533                 break;
534             case 't':
535                 TEST_CASE = atoi(optarg);
536                 break;
537             default:
538                 PrintUsage();
539                 return -1;
540         }
541     }
542
543     if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
544             (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
545     {
546         PrintUsage();
547         return -1;
548     }
549
550
551     /*Get Ip address on defined interface and initialize coap on it with random port number
552      * this port number will be used as a source port in all coap communications*/
553     if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
554                 sizeof(addr)) == ERR_SUCCESS)
555     {
556         OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
557         paddr = addr;
558     }
559
560     /* Initialize OCStack*/
561     if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK) {
562         OC_LOG(ERROR, TAG, "OCStack init error");
563         return 0;
564     }
565
566     InitDiscovery();
567
568     // Break from loop with Ctrl+C
569     OC_LOG(INFO, TAG, "Entering occlient main loop...");
570     signal(SIGINT, handleSigInt);
571     while (!gQuitFlag) {
572
573         if (OCProcess() != OC_STACK_OK) {
574             OC_LOG(ERROR, TAG, "OCStack process error");
575             return 0;
576         }
577
578         sleep(2);
579     }
580     OC_LOG(INFO, TAG, "Exiting occlient main loop...");
581
582     if (OCStop() != OC_STACK_OK) {
583         OC_LOG(ERROR, TAG, "OCStack stop error");
584     }
585
586     return 0;
587 }
588
589 std::string getIPAddrTBServer(OCClientResponse * clientResponse) {
590     if(!clientResponse) return "";
591     if(!clientResponse->addr) return "";
592     uint8_t a, b, c, d = 0;
593     if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
594
595     char ipaddr[16] = {'\0'};
596     snprintf(ipaddr,  sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d); // ostringstream not working correctly here, hence snprintf
597     return std::string (ipaddr);
598 }
599
600 std::string getPortTBServer(OCClientResponse * clientResponse){
601     if(!clientResponse) return "";
602     if(!clientResponse->addr) return "";
603     uint16_t p = 0;
604     if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
605     std::ostringstream ss;
606     ss << p;
607     return ss.str();
608 }
609
610 std::string getQueryStrForGetPut(OCClientResponse * clientResponse){
611
612     return "/a/light";
613 }
614
615 void parseClientResponse(OCClientResponse * clientResponse){
616     coapServerIP = getIPAddrTBServer(clientResponse);
617     coapServerPort = getPortTBServer(clientResponse);
618     coapServerResource = getQueryStrForGetPut(clientResponse);
619 }