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