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