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