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