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