dd185cb6329808b516d6e096291602f398fc5bb8
[platform/upstream/iotivity.git] / 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/led";
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     #endif
81
82     OC_LOG(INFO, TAG, "-t 13 :  Discover Resources and Initiate Nonconfirmable Observe Requests then cancel immediately");
83     OC_LOG(INFO, TAG, "-t 14 :  Discover Resources and Initiate Nonconfirmable Get Request and add  vendor specific header options");
84 }
85
86 OCStackResult InvokeOCDoResource(std::ostringstream &query,
87                                  OCMethod method, OCQualityOfService qos,
88                                  OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
89 {
90     OCStackResult ret;
91     OCCallbackData cbData;
92     OCDoHandle handle;
93
94     cbData.cb = cb;
95     cbData.context = (void*)CTX_VAL;
96     cbData.cd = NULL;
97
98     ret = OCDoResource(&handle, method, query.str().c_str(), 0,
99                        (method == OC_REST_PUT) ? putPayload.c_str() : NULL,
100                        qos, &cbData, options, numOptions);
101
102     if (ret != OC_STACK_OK)
103     {
104         OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
105     }
106     else if (method == OC_REST_OBSERVE || method == OC_REST_OBSERVE_ALL)
107     {
108         gObserveDoHandle = handle;
109     }
110     #ifdef WITH_PRESENCE
111     else if (method == OC_REST_PRESENCE)
112     {
113         gPresenceHandle = handle;
114     }
115     #endif
116
117     return ret;
118 }
119
120 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
121     if(ctx == (void*)CTX_VAL)
122     {
123         OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
124     }
125
126     if(clientResponse)
127     {
128         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
129         OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response", clientResponse->resJSONPayload);
130     }
131     return OC_STACK_DELETE_TRANSACTION;
132 }
133
134 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
135 {
136     if(ctx == (void*)CTX_VAL)
137     {
138         OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
139     }
140
141     if(clientResponse)
142     {
143         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
144         OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response", clientResponse->resJSONPayload);
145     }
146     return OC_STACK_DELETE_TRANSACTION;
147 }
148
149 OCStackApplicationResult deleteReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
150 {
151     if(ctx == (void*)CTX_VAL)
152     {
153         OC_LOG(INFO, TAG, "Callback Context for DELETE recvd successfully");
154     }
155
156     if(clientResponse)
157     {
158         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
159         OC_LOG_V(INFO, TAG, "JSON = %s =============> Delete Response", clientResponse->resJSONPayload);
160     }
161     return OC_STACK_DELETE_TRANSACTION;
162 }
163
164 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
165     if(ctx == (void*)CTX_VAL)
166     {
167         OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
168     }
169
170     if(clientResponse)
171     {
172         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
173         OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
174         OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response", clientResponse->resJSONPayload);
175     }
176     if(clientResponse->rcvdVendorSpecificHeaderOptions &&
177             clientResponse->numRcvdVendorSpecificHeaderOptions)
178     {
179         OC_LOG (INFO, TAG, "Received vendor specific options");
180         uint8_t i = 0;
181         OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
182         for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
183         {
184             if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
185             {
186                 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
187                         ((OCHeaderOption)rcvdOptions[i]).optionID );
188                 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
189                         ((OCHeaderOption)rcvdOptions[i]).optionLength);
190             }
191         }
192     }
193     return OC_STACK_DELETE_TRANSACTION;
194 }
195
196 OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
197     if(ctx == (void*)CTX_VAL)
198     {
199         OC_LOG(INFO, TAG, "Callback Context for OBS query recvd successfully");
200     }
201
202     if(clientResponse)
203     {
204         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
205         OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
206         OC_LOG_V(INFO, TAG, "Callback Context for OBSERVE notification recvd successfully %d", gNumObserveNotifies);
207         OC_LOG_V(INFO, TAG, "JSON = %s =============> Obs Response", clientResponse->resJSONPayload);
208         gNumObserveNotifies++;
209         if (gNumObserveNotifies == 50)  //large number to test observing in DELETE case.
210         {
211             if(TEST_CASE == TEST_OBS_REQ_NON || TEST_CASE == TEST_OBS_REQ_CON){
212                 printf ("RESET\n");
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*)CTX_VAL)
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: %d", 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*) CTX_VAL)
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                 InitPresence();
323                 break;
324             #endif
325             case TEST_GET_REQ_NON_WITH_VENDOR_HEADER_OPTIONS:
326                 InitGetRequest(OC_LOW_QOS, 1);
327                 break;
328             default:
329                 PrintUsage();
330                 break;
331         }
332     }
333
334     return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
335
336 }
337 #ifdef WITH_PRESENCE
338 int InitPresence()
339 {
340     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
341     std::ostringstream query;
342     query << "coap://" << coapServerIP << ":" << coapServerPort << OC_PRESENCE_URI;
343     return (InvokeOCDoResource(query, OC_REST_PRESENCE, OC_LOW_QOS, presenceCB, NULL, 0));
344 }
345 #endif
346 int InitGetRequestToUnavailableResource()
347 {
348     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
349     std::ostringstream query;
350     query << "coap://" << coapServerIP << ":" << coapServerPort << "/SomeUnknownResource";
351     return (InvokeOCDoResource(query, OC_REST_GET, OC_LOW_QOS, getReqCB, NULL, 0));
352 }
353
354 int InitObserveRequest(OCQualityOfService qos)
355 {
356     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
357     std::ostringstream query;
358     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
359     return (InvokeOCDoResource(query, OC_REST_OBSERVE, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, obsReqCB, NULL, 0));
360 }
361
362 int InitPutRequest()
363 {
364     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
365     std::ostringstream query;
366     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
367     return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0));
368 }
369
370 int InitPostRequest(OCQualityOfService qos)
371 {
372     OCStackResult result;
373     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
374     std::ostringstream query;
375     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
376
377     // First POST operation (to create an LED instance)
378     result = InvokeOCDoResource(query, OC_REST_POST,
379                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
380                                postReqCB, NULL, 0);
381     if (OC_STACK_OK != result)
382     {
383         // Error can happen if for example, network connectivity is down
384         OC_LOG(INFO, TAG, "First POST call did not succeed");
385     }
386
387     // Second POST operation (to create an LED instance)
388     result = InvokeOCDoResource(query, OC_REST_POST,
389                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
390                                postReqCB, NULL, 0);
391     if (OC_STACK_OK != result)
392     {
393         OC_LOG(INFO, TAG, "Second POST call did not succeed");
394     }
395
396     // This POST operation will update the original resourced /a/led
397     return (InvokeOCDoResource(query, OC_REST_POST,
398                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
399                                postReqCB, NULL, 0));
400 }
401
402 void* RequestDeleteDeathResourceTask(void* myqos)
403 {
404     sleep (30); //long enough to give the server time to finish deleting the resource.
405     std::ostringstream query;
406     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
407
408     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
409
410     // Second DELETE operation to delete the resource that might have been removed already.
411     OCQualityOfService qos;
412     if (myqos == NULL)
413         qos = OC_LOW_QOS;
414     else
415         qos = OC_HIGH_QOS;
416
417     OCStackResult result = InvokeOCDoResource(query, OC_REST_DELETE,
418                                qos,
419                                deleteReqCB, NULL, 0);
420
421     if (OC_STACK_OK != result)
422     {
423         OC_LOG(INFO, TAG, "Second DELETE call did not succeed");
424     }
425
426     return NULL;
427 }
428
429 int InitDeleteRequest(OCQualityOfService qos)
430 {
431     OCStackResult result;
432     std::ostringstream query;
433     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
434
435     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
436
437     // First DELETE operation
438     result = InvokeOCDoResource(query, OC_REST_DELETE,
439                                qos,
440                                deleteReqCB, NULL, 0);
441     if (OC_STACK_OK != result)
442     {
443         // Error can happen if for example, network connectivity is down
444         OC_LOG(INFO, TAG, "First DELETE call did not succeed");
445     }
446     else
447     {
448         //Create a thread to delete this resource again
449         pthread_t threadId;
450         pthread_create (&threadId, NULL, RequestDeleteDeathResourceTask, (void*)qos);
451     }
452
453     OC_LOG_V(INFO, TAG, "\n\nExit  %s", __func__);
454     return result;
455 }
456
457 int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptions)
458 {
459     OCHeaderOption options[MAX_HEADER_OPTIONS];
460
461     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
462     std::ostringstream query;
463     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
464
465     if(withVendorSpecificHeaderOptions)
466     {
467         uint8_t option0[] = {1,2,3,4,5,6,7,8,9,10};
468         uint8_t option1[] = {11,12,13,14,15,16,17,18,19,20};
469         memset(options, 0, sizeof(OCHeaderOption) * MAX_HEADER_OPTIONS);
470         options[0].protocolID = OC_COAP_ID;
471         options[0].optionID = 2048;
472         memcpy(options[0].optionData, option0, sizeof(option0));
473         options[0].optionLength = 10;
474         options[1].protocolID = OC_COAP_ID;
475         options[1].optionID = 3000;
476         memcpy(options[1].optionData, option1, sizeof(option1));
477         options[1].optionLength = 10;
478     }
479     if(withVendorSpecificHeaderOptions)
480     {
481         return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, getReqCB, options, 2));
482     }
483     else
484     {
485         return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
486     }
487 }
488
489 int InitDiscovery()
490 {
491     OCStackResult ret;
492     OCCallbackData cbData;
493     OCDoHandle handle;
494     /* Start a discovery query*/
495     char szQueryUri[64] = { 0 };
496     if (UNICAST_DISCOVERY)
497     {
498         strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY);
499     }
500     else
501     {
502         strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
503     }
504     cbData.cb = discoveryReqCB;
505     cbData.context = (void*)CTX_VAL;
506     cbData.cd = NULL;
507     ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
508     if (ret != OC_STACK_OK)
509     {
510         OC_LOG(ERROR, TAG, "OCStack resource error");
511     }
512     return ret;
513 }
514
515 int main(int argc, char* argv[]) {
516     uint8_t addr[20] = {0};
517     uint8_t* paddr = NULL;
518     uint16_t port = USE_RANDOM_PORT;
519     uint8_t ifname[] = "eth0";
520     int opt;
521
522     while ((opt = getopt(argc, argv, "u:t:")) != -1)
523     {
524         switch(opt)
525         {
526             case 'u':
527                 UNICAST_DISCOVERY = atoi(optarg);
528                 break;
529             case 't':
530                 TEST_CASE = atoi(optarg);
531                 break;
532             default:
533                 PrintUsage();
534                 return -1;
535         }
536     }
537
538     if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
539             (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
540     {
541         PrintUsage();
542         return -1;
543     }
544
545
546     /*Get Ip address on defined interface and initialize coap on it with random port number
547      * this port number will be used as a source port in all coap communications*/
548     if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
549                 sizeof(addr)) == ERR_SUCCESS)
550     {
551         OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
552         paddr = addr;
553     }
554
555     /* Initialize OCStack*/
556     if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK) {
557         OC_LOG(ERROR, TAG, "OCStack init error");
558         return 0;
559     }
560
561     InitDiscovery();
562
563     // Break from loop with Ctrl+C
564     OC_LOG(INFO, TAG, "Entering occlient main loop...");
565     signal(SIGINT, handleSigInt);
566     while (!gQuitFlag) {
567
568         if (OCProcess() != OC_STACK_OK) {
569             OC_LOG(ERROR, TAG, "OCStack process error");
570             return 0;
571         }
572
573         sleep(2);
574     }
575     OC_LOG(INFO, TAG, "Exiting occlient main loop...");
576
577     if (OCStop() != OC_STACK_OK) {
578         OC_LOG(ERROR, TAG, "OCStack stop error");
579     }
580
581     return 0;
582 }
583
584 std::string getIPAddrTBServer(OCClientResponse * clientResponse) {
585     if(!clientResponse) return "";
586     if(!clientResponse->addr) return "";
587     uint8_t a, b, c, d = 0;
588     if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
589
590     char ipaddr[16] = {'\0'};
591     snprintf(ipaddr,  sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d); // ostringstream not working correctly here, hence snprintf
592     return std::string (ipaddr);
593 }
594
595 std::string getPortTBServer(OCClientResponse * clientResponse){
596     if(!clientResponse) return "";
597     if(!clientResponse->addr) return "";
598     uint16_t p = 0;
599     if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
600     std::ostringstream ss;
601     ss << p;
602     return ss.str();
603 }
604
605 std::string getQueryStrForGetPut(OCClientResponse * clientResponse){
606
607     return "/a/led";
608 }
609
610 void parseClientResponse(OCClientResponse * clientResponse){
611     coapServerIP = getIPAddrTBServer(clientResponse);
612     coapServerPort = getPortTBServer(clientResponse);
613     coapServerResource = getQueryStrForGetPut(clientResponse);
614 }