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