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