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