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