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