c99f939a2f367e4162803d7ebd8a9b456dab325c
[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         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 %s in payload", coapServerResource.c_str());
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             result = InvokeOCDoResource(query, NULL, OC_REST_PRESENCE, OC_LOW_QOS,
565                     presenceCB, NULL, 0);
566         }
567     }
568     return result;
569 }
570 #endif
571
572 int InitGetRequestToUnavailableResource(OCQualityOfService qos)
573 {
574     std::ostringstream query;
575     query << "/SomeUnknownResource";
576     OIC_LOG_V(INFO, TAG, "\nExecuting %s with query %s", __func__, query.str().c_str());
577     return (InvokeOCDoResource(query, &serverAddr, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS,
578             getReqCB, NULL, 0));
579 }
580
581 int InitObserveRequest(OCQualityOfService qos)
582 {
583     std::ostringstream query;
584     query << coapServerResource;
585     OIC_LOG_V(INFO, TAG, "\nExecuting %s with query %s", __func__, query.str().c_str());
586     return (InvokeOCDoResource(query, &serverAddr, OC_REST_OBSERVE,
587               (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, obsReqCB, NULL, 0));
588 }
589
590 int InitPutRequest(OCQualityOfService qos)
591 {
592     std::ostringstream query;
593     query << coapServerResource;
594     OIC_LOG_V(INFO, TAG, "\nExecuting %s with query %s", __func__, query.str().c_str());
595     return (InvokeOCDoResource(query, &serverAddr, OC_REST_PUT, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS,
596             putReqCB, NULL, 0));
597 }
598
599 int InitPostRequest(OCQualityOfService qos)
600 {
601     OCStackResult result;
602
603     std::ostringstream query;
604     query << coapServerResource;
605
606     OIC_LOG_V(INFO, TAG, "\nExecuting %s with query %s", __func__, query.str().c_str());
607     // First POST operation (to create an Light instance)
608     result = InvokeOCDoResource(query, &serverAddr, OC_REST_POST,
609                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
610                                postReqCB, NULL, 0);
611     if (OC_STACK_OK != result)
612     {
613         // Error can happen if for example, network connectivity is down
614         OIC_LOG(INFO, TAG, "First POST call did not succeed");
615     }
616
617     // Second POST operation (to create an Light instance)
618     result = InvokeOCDoResource(query, &serverAddr, OC_REST_POST,
619                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
620                                postReqCB, NULL, 0);
621     if (OC_STACK_OK != result)
622     {
623         OIC_LOG(INFO, TAG, "Second POST call did not succeed");
624     }
625
626     // This POST operation will update the original resourced /a/light
627     return (InvokeOCDoResource(query, &serverAddr, OC_REST_POST,
628                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
629                                postReqCB, NULL, 0));
630 }
631
632 void* RequestDeleteDeathResourceTask(void* myqos)
633 {
634     sleep (30);//long enough to give the server time to finish deleting the resource.
635     std::ostringstream query;
636     query << coapServerResource;
637
638     OIC_LOG_V(INFO, TAG, "\nExecuting %s with query %s", __func__, query.str().c_str());
639
640     // Second DELETE operation to delete the resource that might have been removed already.
641     OCQualityOfService qos;
642     if (myqos == NULL)
643     {
644         qos = OC_LOW_QOS;
645     }
646     else
647     {
648         qos = OC_HIGH_QOS;
649     }
650
651     OCStackResult result = InvokeOCDoResource(query, &serverAddr, OC_REST_DELETE,
652                                qos,
653                                deleteReqCB, NULL, 0);
654
655     if (OC_STACK_OK != result)
656     {
657         OIC_LOG(INFO, TAG, "Second DELETE call did not succeed");
658     }
659
660     return NULL;
661 }
662
663 int InitDeleteRequest(OCQualityOfService qos)
664 {
665     OCStackResult result;
666     std::ostringstream query;
667     query << coapServerResource;
668
669     OIC_LOG_V(INFO, TAG, "\nExecuting %s with query %s", __func__, query.str().c_str());
670
671     // First DELETE operation
672     result = InvokeOCDoResource(query, &serverAddr, OC_REST_DELETE,
673                                qos,
674                                deleteReqCB, NULL, 0);
675     if (OC_STACK_OK != result)
676     {
677         // Error can happen if for example, network connectivity is down
678         OIC_LOG(INFO, TAG, "First DELETE call did not succeed");
679     }
680     else
681     {
682         //Create a thread to delete this resource again
683         pthread_t threadId;
684         pthread_create (&threadId, NULL, RequestDeleteDeathResourceTask, (void*)qos);
685     }
686
687     OIC_LOG_V(INFO, TAG, "\n\nExit  %s", __func__);
688     return result;
689 }
690
691 int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptions,
692                    bool getWithQuery)
693 {
694
695     OCHeaderOption options[MAX_HEADER_OPTIONS];
696
697     std::ostringstream query;
698     query << coapServerResource;
699
700     // ocserver is written to only process "power<X" query.
701     if (getWithQuery)
702     {
703         OIC_LOG(INFO, TAG, "Using query power<50");
704         query << "?power<50";
705     }
706     OIC_LOG_V(INFO, TAG, "\nExecuting %s with query %s", __func__, query.str().c_str());
707
708     if (withVendorSpecificHeaderOptions)
709     {
710         uint8_t option0[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
711         uint8_t option1[] = { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
712         memset(options, 0, sizeof(OCHeaderOption) * MAX_HEADER_OPTIONS);
713         options[0].protocolID = OC_COAP_ID;
714         options[0].optionID = 2048;
715         memcpy(options[0].optionData, option0, sizeof(option0));
716         options[0].optionLength = 10;
717         options[1].protocolID = OC_COAP_ID;
718         options[1].optionID = 3000;
719         memcpy(options[1].optionData, option1, sizeof(option1));
720         options[1].optionLength = 10;
721     }
722     if (withVendorSpecificHeaderOptions)
723     {
724         return (InvokeOCDoResource(query, &serverAddr, OC_REST_GET,
725                 (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, getReqCB, options, 2));
726     }
727     else
728     {
729         return (InvokeOCDoResource(query, &serverAddr, OC_REST_GET,
730                 (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, getReqCB, NULL, 0));
731     }
732 }
733
734 int InitPlatformDiscovery(OCQualityOfService qos)
735 {
736     OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
737
738     OCStackResult ret;
739     OCCallbackData cbData;
740     char szQueryUri[MAX_QUERY_LENGTH] = { 0 };
741
742     snprintf(szQueryUri, sizeof (szQueryUri) - 1, PLATFORM_DISCOVERY_QUERY, discoveryAddr);
743
744     cbData.cb = PlatformDiscoveryReqCB;
745     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
746     cbData.cd = NULL;
747
748     ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, NULL, 0, CT_DEFAULT,
749                        (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS,
750                        &cbData, NULL, 0);
751     if (ret != OC_STACK_OK)
752     {
753         OIC_LOG(ERROR, TAG, "OCStack device error");
754     }
755
756     return ret;
757 }
758
759 int InitDeviceDiscovery(OCQualityOfService qos)
760 {
761     OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
762
763     OCStackResult ret;
764     OCCallbackData cbData;
765     char szQueryUri[MAX_QUERY_LENGTH] = { 0 };
766
767     snprintf(szQueryUri, sizeof (szQueryUri) - 1, DEVICE_DISCOVERY_QUERY, discoveryAddr);
768
769     cbData.cb = DeviceDiscoveryReqCB;
770     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
771     cbData.cd = NULL;
772
773     ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, NULL, 0, CT_DEFAULT,
774                        (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS,
775                        &cbData, NULL, 0);
776     if (ret != OC_STACK_OK)
777     {
778         OIC_LOG(ERROR, TAG, "OCStack device error");
779     }
780
781     return ret;
782 }
783
784 int InitDiscovery(OCQualityOfService qos)
785 {
786     OCStackResult ret;
787     OCCallbackData cbData;
788     char szQueryUri[MAX_QUERY_LENGTH] = { 0 };
789
790     snprintf(szQueryUri, sizeof (szQueryUri) - 1, RESOURCE_DISCOVERY_QUERY, discoveryAddr);
791
792     cbData.cb = discoveryReqCB;
793     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
794     cbData.cd = NULL;
795
796     ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, NULL, 0, CT_DEFAULT,
797                        (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS,
798                        &cbData, NULL, 0);
799     if (ret != OC_STACK_OK)
800     {
801         OIC_LOG(ERROR, TAG, "OCStack resource error");
802     }
803     return ret;
804 }
805
806 int main(int argc, char* argv[])
807 {
808     int opt;
809
810     while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
811     {
812         switch(opt)
813         {
814             case 'u':
815                 UnicastDiscovery = atoi(optarg);
816                 break;
817             case 't':
818                 TestCase = atoi(optarg);
819                 break;
820             case 'c':
821                 Connectivity = atoi(optarg);
822                 break;
823             default:
824                 PrintUsage();
825                 return -1;
826         }
827     }
828
829     if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||
830             (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS) ||
831             (Connectivity < CT_ADAPTER_DEFAULT || Connectivity >= MAX_CT))
832     {
833         PrintUsage();
834         return -1;
835     }
836
837     if (OCInit1(OC_CLIENT, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS) != OC_STACK_OK)
838     {
839         OIC_LOG(ERROR, TAG, "OCStack init error");
840         return 0;
841     }
842
843 #ifdef ROUTING_GATEWAY
844     /*
845      * Before invoking Discover resource, we process the gateway requests
846      * and form the routing table.
847      */
848     for (int index = 0; index < MAX_NUM_GATEWAY_REQUEST; index++)
849     {
850         if (OC_STACK_OK != OCProcess())
851         {
852             OIC_LOG(ERROR, TAG, "OCStack process error");
853             return 0;
854         }
855         usleep(SLEEP_DURATION);
856     }
857 #endif
858     if (Connectivity == CT_ADAPTER_DEFAULT || Connectivity == CT_IP)
859     {
860         ConnType = CT_ADAPTER_IP;
861     }
862     else
863     {
864         OIC_LOG(INFO, TAG, "Default Connectivity type selected...");
865         PrintUsage();
866     }
867
868     discoveryAddr[0] = '\0';
869
870     if (UnicastDiscovery)
871     {
872         OIC_LOG(INFO, TAG, "Enter IP address of server with optional port number");
873         OIC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
874         OIC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
875
876         if (fgets(discoveryAddr, sizeof (discoveryAddr), stdin))
877         {
878             //Strip newline char from ipv4addr
879             StripNewLineChar(discoveryAddr);
880         }
881         else
882         {
883             OIC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
884             return OC_STACK_INVALID_PARAM;
885         }
886     }
887
888     if (UnicastDiscovery == 0 && TestCase == TEST_DISCOVER_DEV_REQ)
889     {
890         InitDeviceDiscovery(OC_LOW_QOS);
891     }
892     else if (UnicastDiscovery == 0 && TestCase == TEST_DISCOVER_PLATFORM_REQ)
893     {
894         InitPlatformDiscovery(OC_LOW_QOS);
895     }
896     else
897     {
898         InitDiscovery(OC_LOW_QOS);
899     }
900
901     // Break from loop with Ctrl+C
902     OIC_LOG(INFO, TAG, "Entering occlient main loop...");
903     signal(SIGINT, handleSigInt);
904     while (!gQuitFlag)
905     {
906
907         if (OCProcess() != OC_STACK_OK)
908         {
909             OIC_LOG(ERROR, TAG, "OCStack process error");
910             return 0;
911         }
912 #ifndef ROUTING_GATEAWAY
913         sleep(1);
914 #endif
915     }
916     OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
917
918     if (OCStop() != OC_STACK_OK)
919     {
920         OIC_LOG(ERROR, TAG, "OCStack stop error");
921     }
922
923     return 0;
924 }
925
926 std::string getConnectivityType (OCConnectivityType connType)
927 {
928     switch (connType & CT_MASK_ADAPTER)
929     {
930         case CT_ADAPTER_IP:
931             return "IP";
932
933         case CT_IP_USE_V4:
934             return "IPv4";
935
936         case CT_IP_USE_V6:
937             return "IPv6";
938
939         case CT_ADAPTER_GATT_BTLE:
940             return "GATT";
941
942         case CT_ADAPTER_RFCOMM_BTEDR:
943             return "RFCOMM";
944
945         default:
946             return "Incorrect connectivity";
947     }
948 }