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