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