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