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