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