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