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