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