Device Discovery - C & C++ SDK changes
[platform/upstream/iotivity.git] / resource / csdk / stack / samples / linux / SimpleClientServer / occlient.cpp
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <signal.h>
25 #include <unistd.h>
26 #include <iostream>
27 #include <sstream>
28 #include "ocstack.h"
29 #include "logger.h"
30 #include "occlient.h"
31
32 static int UNICAST_DISCOVERY = 0;
33 static int TEST_CASE = 0;
34 static const char * TEST_APP_UNICAST_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core";
35 static const char * TEST_APP_UNICAST_DEVICE_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core/d";
36 static const char * TEST_APP_MULTICAST_DEVICE_DISCOVERY_QUERY = "coap://224.0.1.187:5683/oc/core/d";
37 static std::string putPayload = "{\"state\":\"on\",\"power\":5}";
38 static std::string coapServerIP = "255.255.255.255";
39 static std::string coapServerPort = "5683";
40 static std::string coapServerResource = "/a/light";
41
42 // The handle for the observe registration
43 OCDoHandle gObserveDoHandle;
44 #ifdef WITH_PRESENCE
45 // The handle for observe registration
46 OCDoHandle gPresenceHandle;
47 #endif
48 // After this crosses a threshold client deregisters for further notifications
49 int gNumObserveNotifies = 0;
50
51 #ifdef WITH_PRESENCE
52 int gNumPresenceNotifies = 0;
53 #endif
54
55 int gQuitFlag = 0;
56 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
57 void handleSigInt(int signum) {
58     if (signum == SIGINT) {
59         gQuitFlag = 1;
60     }
61 }
62
63 static void PrintUsage()
64 {
65     OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3|4|5|6|7>");
66     OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
67     OC_LOG(INFO, TAG, "-t 1  :  Discover Resources");
68     OC_LOG(INFO, TAG, "-t 2  :  Discover Resources and Initiate Nonconfirmable Get Request");
69     OC_LOG(INFO, TAG, "-t 3  :  Discover Resources and Initiate Nonconfirmable Put Requests");
70     OC_LOG(INFO, TAG, "-t 4  :  Discover Resources and Initiate Nonconfirmable Post Requests");
71     OC_LOG(INFO, TAG, "-t 5  :  Discover Resources and Initiate Nonconfirmable Delete Requests");
72     OC_LOG(INFO, TAG, "-t 6  :  Discover Resources and Initiate Nonconfirmable Observe Requests");
73     OC_LOG(INFO, TAG, "-t 7  :  Discover Resources and Initiate Nonconfirmable Get Request for a resource which is unavailable");
74
75     OC_LOG(INFO, TAG, "-t 8  :  Discover Resources and Initiate Confirmable Get Request");
76     OC_LOG(INFO, TAG, "-t 9  :  Discover Resources and Initiate Confirmable Post Request");
77     OC_LOG(INFO, TAG, "-t 10 :  Discover Resources and Initiate Confirmable Delete Requests");
78     OC_LOG(INFO, TAG, "-t 11 :  Discover Resources and Initiate Confirmable Observe Requests");
79
80     #ifdef WITH_PRESENCE
81     OC_LOG(INFO, TAG, "-t 12 :  Discover Resources and Initiate Nonconfirmable presence");
82     OC_LOG(INFO, TAG, "-t 13 :  Discover Resources and Initiate Nonconfirmable presence with filter");
83     #endif
84
85     OC_LOG(INFO, TAG, "-t 14 :  Discover Resources and Initiate Nonconfirmable Observe Requests then cancel immediately");
86     OC_LOG(INFO, TAG, "-t 15 :  Discover Resources and Initiate Nonconfirmable Get Request and add  vendor specific header options");
87     OC_LOG(INFO, TAG, "-t 16  :  Discover Devices");
88 }
89
90 OCStackResult InvokeOCDoResource(std::ostringstream &query,
91                                  OCMethod method, OCQualityOfService qos,
92                                  OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
93 {
94     OCStackResult ret;
95     OCCallbackData cbData;
96     OCDoHandle handle;
97
98     cbData.cb = cb;
99     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
100     cbData.cd = NULL;
101
102     ret = OCDoResource(&handle, method, query.str().c_str(), 0,
103                        (method == OC_REST_PUT) ? putPayload.c_str() : NULL,
104                        qos, &cbData, options, numOptions);
105
106     if (ret != OC_STACK_OK)
107     {
108         OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
109     }
110     else if (method == OC_REST_OBSERVE || method == OC_REST_OBSERVE_ALL)
111     {
112         gObserveDoHandle = handle;
113     }
114     #ifdef WITH_PRESENCE
115     else if (method == OC_REST_PRESENCE)
116     {
117         gPresenceHandle = handle;
118     }
119     #endif
120
121     return ret;
122 }
123
124 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
125     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
126     {
127         OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
128     }
129
130     if(clientResponse)
131     {
132         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
133         OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response", clientResponse->resJSONPayload);
134     }
135     return OC_STACK_DELETE_TRANSACTION;
136 }
137
138 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
139 {
140     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
141     {
142         OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
143     }
144
145     if(clientResponse)
146     {
147         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
148         OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response", clientResponse->resJSONPayload);
149     }
150     return OC_STACK_DELETE_TRANSACTION;
151 }
152
153 OCStackApplicationResult deleteReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
154 {
155     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
156     {
157         OC_LOG(INFO, TAG, "Callback Context for DELETE recvd successfully");
158     }
159
160     if(clientResponse)
161     {
162         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
163         OC_LOG_V(INFO, TAG, "JSON = %s =============> Delete Response", clientResponse->resJSONPayload);
164     }
165     return OC_STACK_DELETE_TRANSACTION;
166 }
167
168 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
169 {
170     if(clientResponse == NULL)
171     {
172         OC_LOG(INFO, TAG, "The clientResponse is NULL");
173         return   OC_STACK_DELETE_TRANSACTION;
174     }
175     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
176     {
177         OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
178     }
179
180     OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
181     OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
182     OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response", clientResponse->resJSONPayload);
183
184     if(clientResponse->rcvdVendorSpecificHeaderOptions &&
185             clientResponse->numRcvdVendorSpecificHeaderOptions)
186     {
187         OC_LOG (INFO, TAG, "Received vendor specific options");
188         uint8_t i = 0;
189         OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
190         for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
191         {
192             if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
193             {
194                 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
195                         ((OCHeaderOption)rcvdOptions[i]).optionID );
196                 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
197                         ((OCHeaderOption)rcvdOptions[i]).optionLength);
198             }
199         }
200     }
201     return OC_STACK_DELETE_TRANSACTION;
202 }
203
204 OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
205     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
206     {
207         OC_LOG(INFO, TAG, "Callback Context for OBS query recvd successfully");
208     }
209
210     if(clientResponse)
211     {
212         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
213         OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
214         OC_LOG_V(INFO, TAG, "Callback Context for OBSERVE notification recvd successfully %d", gNumObserveNotifies);
215         OC_LOG_V(INFO, TAG, "JSON = %s =============> Obs Response", clientResponse->resJSONPayload);
216         gNumObserveNotifies++;
217         if (gNumObserveNotifies == 3)   //large number to test observing in DELETE case.
218         {
219             if(TEST_CASE == TEST_OBS_REQ_NON || TEST_CASE == TEST_OBS_REQ_CON){
220                 if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK){
221                     OC_LOG(ERROR, TAG, "Observe cancel error");
222                 }
223                 return OC_STACK_DELETE_TRANSACTION;
224             }else if(TEST_CASE == TEST_OBS_REQ_NON_CANCEL_IMM){
225                 if (OCCancel (gObserveDoHandle, OC_HIGH_QOS, NULL, 0) != OC_STACK_OK){
226                     OC_LOG(ERROR, TAG, "Observe cancel error");
227                 }
228             }
229         }
230         if(clientResponse->sequenceNumber == OC_OBSERVE_REGISTER){
231             OC_LOG(INFO, TAG, "This also serves as a registration confirmation");
232         }else if(clientResponse->sequenceNumber == OC_OBSERVE_DEREGISTER){
233             OC_LOG(INFO, TAG, "This also serves as a deregistration confirmation");
234             return OC_STACK_DELETE_TRANSACTION;
235         }else if(clientResponse->sequenceNumber == OC_OBSERVE_NO_OPTION){
236             OC_LOG(INFO, TAG, "This also tells you that registration/deregistration failed");
237             return OC_STACK_DELETE_TRANSACTION;
238         }
239     }
240     return OC_STACK_KEEP_TRANSACTION;
241 }
242 #ifdef WITH_PRESENCE
243 OCStackApplicationResult presenceCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
244     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
245     {
246         OC_LOG(INFO, TAG, "Callback Context for Presence recvd successfully");
247     }
248
249     if(clientResponse)
250     {
251         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
252         OC_LOG_V(INFO, TAG, "NONCE NUMBER: %u", clientResponse->sequenceNumber);
253         OC_LOG_V(INFO, TAG, "Callback Context for Presence notification recvd successfully %d", gNumPresenceNotifies);
254         OC_LOG_V(INFO, TAG, "JSON = %s =============> Presence Response", clientResponse->resJSONPayload);
255         gNumPresenceNotifies++;
256         if (gNumPresenceNotifies == 20)
257         {
258             if (OCCancel (gPresenceHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK){
259                 OC_LOG(ERROR, TAG, "Presence cancel error");
260             }
261             return OC_STACK_DELETE_TRANSACTION;
262         }
263     }
264     return OC_STACK_KEEP_TRANSACTION;
265 }
266 #endif
267
268 // This is a function called back when a device is discovered
269 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
270         OCClientResponse * clientResponse) {
271     uint8_t remoteIpAddr[4];
272     uint16_t remotePortNu;
273
274     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
275     {
276         OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
277     }
278
279     if (clientResponse)
280     {
281         OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
282
283         OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
284                 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
285         OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
286
287         OC_LOG_V(INFO, TAG,
288                 "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
289                 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
290                 remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
291
292         parseClientResponse(clientResponse);
293
294         switch(TEST_CASE)
295         {
296             case TEST_GET_REQ_NON:
297                 InitGetRequest(OC_LOW_QOS, 0);
298                 break;
299             case TEST_PUT_REQ_NON:
300                 InitPutRequest();
301                 break;
302             case TEST_POST_REQ_NON:
303                 InitPostRequest(OC_LOW_QOS);
304                 break;
305             case TEST_DELETE_REQ_NON:
306                 InitDeleteRequest(OC_LOW_QOS);
307                 break;
308             case TEST_OBS_REQ_NON:
309             case TEST_OBS_REQ_NON_CANCEL_IMM:
310                 InitObserveRequest(OC_LOW_QOS);
311                 break;
312             case TEST_GET_UNAVAILABLE_RES_REQ_NON:
313                 InitGetRequestToUnavailableResource();
314                 break;
315             case TEST_GET_REQ_CON:
316                 InitGetRequest(OC_HIGH_QOS, 0);
317                 break;
318             case TEST_POST_REQ_CON:
319                 InitPostRequest(OC_HIGH_QOS);
320                 break;
321             case TEST_DELETE_REQ_CON:
322                 InitDeleteRequest(OC_HIGH_QOS);
323                 break;
324             case TEST_OBS_REQ_CON:
325                 InitObserveRequest(OC_HIGH_QOS);
326                 break;
327             #ifdef WITH_PRESENCE
328             case TEST_OBS_PRESENCE:
329             case TEST_OBS_PRESENCE_WITH_FILTER:
330                 InitPresence();
331                 break;
332             #endif
333             case TEST_GET_REQ_NON_WITH_VENDOR_HEADER_OPTIONS:
334                 InitGetRequest(OC_LOW_QOS, 1);
335                 break;
336             case TEST_DISCOVER_DEV_REQ:
337                 InitDeviceDiscovery();
338                 break;
339             default:
340                 PrintUsage();
341                 break;
342         }
343     }
344
345     return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
346
347 }
348
349 OCStackApplicationResult DeviceDiscoveryReqCB (void* ctx, OCDoHandle handle,
350         OCClientResponse * clientResponse)
351 {
352     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
353     {
354         OC_LOG(INFO, TAG, "Callback Context for Device DISCOVER query recvd successfully");
355     }
356
357     if(clientResponse)
358     {
359         //OC_LOG truncates the response as it is too long.
360         fprintf(stderr, "Discovery response: \n %s\n", clientResponse->resJSONPayload);
361         fflush(stderr);
362     }
363
364     return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION;
365 }
366
367 #ifdef WITH_PRESENCE
368 int InitPresence()
369 {
370     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
371     std::ostringstream query;
372     query << "coap://" << coapServerIP << ":" << coapServerPort << OC_PRESENCE_URI;
373     if(TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTER)
374     {
375         query << "?rt=core.light";
376     }
377     return (InvokeOCDoResource(query, OC_REST_PRESENCE, OC_LOW_QOS, presenceCB, NULL, 0));
378 }
379 #endif
380 int InitGetRequestToUnavailableResource()
381 {
382     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
383     std::ostringstream query;
384     query << "coap://" << coapServerIP << ":" << coapServerPort << "/SomeUnknownResource";
385     return (InvokeOCDoResource(query, OC_REST_GET, OC_LOW_QOS, getReqCB, NULL, 0));
386 }
387
388 int InitObserveRequest(OCQualityOfService qos)
389 {
390     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
391     std::ostringstream query;
392     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
393     return (InvokeOCDoResource(query, OC_REST_OBSERVE, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, obsReqCB, NULL, 0));
394 }
395
396 int InitPutRequest()
397 {
398     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
399     std::ostringstream query;
400     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
401     return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0));
402 }
403
404 int InitPostRequest(OCQualityOfService qos)
405 {
406     OCStackResult result;
407     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
408     std::ostringstream query;
409     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
410
411     // First POST operation (to create an Light instance)
412     result = InvokeOCDoResource(query, OC_REST_POST,
413                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
414                                postReqCB, NULL, 0);
415     if (OC_STACK_OK != result)
416     {
417         // Error can happen if for example, network connectivity is down
418         OC_LOG(INFO, TAG, "First POST call did not succeed");
419     }
420
421     // Second POST operation (to create an Light instance)
422     result = InvokeOCDoResource(query, OC_REST_POST,
423                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
424                                postReqCB, NULL, 0);
425     if (OC_STACK_OK != result)
426     {
427         OC_LOG(INFO, TAG, "Second POST call did not succeed");
428     }
429
430     // This POST operation will update the original resourced /a/light
431     return (InvokeOCDoResource(query, OC_REST_POST,
432                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
433                                postReqCB, NULL, 0));
434 }
435
436 void* RequestDeleteDeathResourceTask(void* myqos)
437 {
438     sleep (30); //long enough to give the server time to finish deleting the resource.
439     std::ostringstream query;
440     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
441
442     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
443
444     // Second DELETE operation to delete the resource that might have been removed already.
445     OCQualityOfService qos;
446     if (myqos == NULL)
447         qos = OC_LOW_QOS;
448     else
449         qos = OC_HIGH_QOS;
450
451     OCStackResult result = InvokeOCDoResource(query, OC_REST_DELETE,
452                                qos,
453                                deleteReqCB, NULL, 0);
454
455     if (OC_STACK_OK != result)
456     {
457         OC_LOG(INFO, TAG, "Second DELETE call did not succeed");
458     }
459
460     return NULL;
461 }
462
463 int InitDeleteRequest(OCQualityOfService qos)
464 {
465     OCStackResult result;
466     std::ostringstream query;
467     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
468
469     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
470
471     // First DELETE operation
472     result = InvokeOCDoResource(query, OC_REST_DELETE,
473                                qos,
474                                deleteReqCB, NULL, 0);
475     if (OC_STACK_OK != result)
476     {
477         // Error can happen if for example, network connectivity is down
478         OC_LOG(INFO, TAG, "First DELETE call did not succeed");
479     }
480     else
481     {
482         //Create a thread to delete this resource again
483         pthread_t threadId;
484         pthread_create (&threadId, NULL, RequestDeleteDeathResourceTask, (void*)qos);
485     }
486
487     OC_LOG_V(INFO, TAG, "\n\nExit  %s", __func__);
488     return result;
489 }
490
491 int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptions)
492 {
493     OCHeaderOption options[MAX_HEADER_OPTIONS];
494
495     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
496     std::ostringstream query;
497     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
498
499     if(withVendorSpecificHeaderOptions)
500     {
501         uint8_t option0[] = {1,2,3,4,5,6,7,8,9,10};
502         uint8_t option1[] = {11,12,13,14,15,16,17,18,19,20};
503         memset(options, 0, sizeof(OCHeaderOption) * MAX_HEADER_OPTIONS);
504         options[0].protocolID = OC_COAP_ID;
505         options[0].optionID = 2048;
506         memcpy(options[0].optionData, option0, sizeof(option0));
507         options[0].optionLength = 10;
508         options[1].protocolID = OC_COAP_ID;
509         options[1].optionID = 3000;
510         memcpy(options[1].optionData, option1, sizeof(option1));
511         options[1].optionLength = 10;
512     }
513     if(withVendorSpecificHeaderOptions)
514     {
515         return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, getReqCB, options, 2));
516     }
517     else
518     {
519         return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
520     }
521 }
522
523 int InitDeviceDiscovery()
524 {
525     OCStackResult ret;
526     OCCallbackData cbData;
527     OCDoHandle handle;
528     char szQueryUri[64] = { 0 };
529
530     cbData.cb = DeviceDiscoveryReqCB;
531     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
532     cbData.cd = NULL;
533
534     if(UNICAST_DISCOVERY)
535     {
536         strncpy(szQueryUri, TEST_APP_UNICAST_DEVICE_DISCOVERY_QUERY,
537                         (strlen(TEST_APP_UNICAST_DEVICE_DISCOVERY_QUERY) + 1));
538     }
539     else
540     {
541         strncpy(szQueryUri, TEST_APP_MULTICAST_DEVICE_DISCOVERY_QUERY,
542                 (strlen(TEST_APP_MULTICAST_DEVICE_DISCOVERY_QUERY) + 1));
543     }
544
545     ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
546
547     if (ret != OC_STACK_OK)
548     {
549         OC_LOG(ERROR, TAG, "OCStack device error");
550     }
551
552     return ret;
553 }
554
555 int InitDiscovery()
556 {
557     OCStackResult ret;
558     OCCallbackData cbData;
559     OCDoHandle handle;
560     /* Start a discovery query*/
561     char szQueryUri[64] = { 0 };
562     if (UNICAST_DISCOVERY)
563     {
564         strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY);
565     }
566     else
567     {
568         strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
569     }
570     cbData.cb = discoveryReqCB;
571     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
572     cbData.cd = NULL;
573     ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
574     if (ret != OC_STACK_OK)
575     {
576         OC_LOG(ERROR, TAG, "OCStack resource error");
577     }
578     return ret;
579 }
580
581 int main(int argc, char* argv[]) {
582     uint8_t addr[20] = {0};
583     uint8_t* paddr = NULL;
584     uint16_t port = USE_RANDOM_PORT;
585     uint8_t ifname[] = "eth0";
586     int opt;
587
588     while ((opt = getopt(argc, argv, "u:t:")) != -1)
589     {
590         switch(opt)
591         {
592             case 'u':
593                 UNICAST_DISCOVERY = atoi(optarg);
594                 break;
595             case 't':
596                 TEST_CASE = atoi(optarg);
597                 break;
598             default:
599                 PrintUsage();
600                 return -1;
601         }
602     }
603
604     if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
605             (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
606     {
607         PrintUsage();
608         return -1;
609     }
610
611
612     /*Get Ip address on defined interface and initialize coap on it with random port number
613      * this port number will be used as a source port in all coap communications*/
614     if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
615                 sizeof(addr)) == ERR_SUCCESS)
616     {
617         OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
618         paddr = addr;
619     }
620
621     /* Initialize OCStack*/
622     if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK) {
623         OC_LOG(ERROR, TAG, "OCStack init error");
624         return 0;
625     }
626
627     InitDiscovery();
628
629     // Break from loop with Ctrl+C
630     OC_LOG(INFO, TAG, "Entering occlient main loop...");
631     signal(SIGINT, handleSigInt);
632     while (!gQuitFlag) {
633
634         if (OCProcess() != OC_STACK_OK) {
635             OC_LOG(ERROR, TAG, "OCStack process error");
636             return 0;
637         }
638
639         sleep(2);
640     }
641     OC_LOG(INFO, TAG, "Exiting occlient main loop...");
642
643     if (OCStop() != OC_STACK_OK) {
644         OC_LOG(ERROR, TAG, "OCStack stop error");
645     }
646
647     return 0;
648 }
649
650 std::string getIPAddrTBServer(OCClientResponse * clientResponse) {
651     if(!clientResponse) return "";
652     if(!clientResponse->addr) return "";
653     uint8_t a, b, c, d = 0;
654     if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
655
656     char ipaddr[16] = {'\0'};
657     snprintf(ipaddr,  sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d); // ostringstream not working correctly here, hence snprintf
658     return std::string (ipaddr);
659 }
660
661 std::string getPortTBServer(OCClientResponse * clientResponse){
662     if(!clientResponse) return "";
663     if(!clientResponse->addr) return "";
664     uint16_t p = 0;
665     if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
666     std::ostringstream ss;
667     ss << p;
668     return ss.str();
669 }
670
671 std::string getQueryStrForGetPut(OCClientResponse * clientResponse){
672
673     return "/a/light";
674 }
675
676 void parseClientResponse(OCClientResponse * clientResponse){
677     coapServerIP = getIPAddrTBServer(clientResponse);
678     coapServerPort = getPortTBServer(clientResponse);
679     coapServerResource = getQueryStrForGetPut(clientResponse);
680 }