Merge from master to CA branch
[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 "\
83             "filter");
84     OC_LOG(INFO, TAG, "-t 14 :  Discover Resources and Initiate Nonconfirmable presence with "\
85             "2 filters");
86     #endif
87
88     OC_LOG(INFO, TAG, "-t 15 :  Discover Resources and Initiate Nonconfirmable Observe Requests "\
89             "then cancel immediately");
90     OC_LOG(INFO, TAG, "-t 16 :  Discover Resources and Initiate Nonconfirmable Get Request and "\
91             "add  vendor specific header options");
92     OC_LOG(INFO, TAG, "-t 17 :  Discover Devices");
93 }
94
95 OCStackResult InvokeOCDoResource(std::ostringstream &query,
96                                  OCMethod method, OCQualityOfService qos,
97                                  OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
98 {
99     OCStackResult ret;
100     OCCallbackData cbData;
101     OCDoHandle handle;
102
103     cbData.cb = cb;
104     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
105     cbData.cd = NULL;
106
107 #ifdef CA_INT
108     ret = OCDoResource(&handle, method, query.str().c_str(), 0,
109                        (method == OC_REST_PUT) ? putPayload.c_str() : NULL,
110                        (OC_WIFI), qos, &cbData, options, numOptions);
111 #else
112     ret = OCDoResource(&handle, method, query.str().c_str(), 0,
113                        (method == OC_REST_PUT) ? putPayload.c_str() : NULL,
114                        qos, &cbData, options, numOptions);
115 #endif
116
117     if (ret != OC_STACK_OK)
118     {
119         OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
120     }
121     else if (method == OC_REST_OBSERVE || method == OC_REST_OBSERVE_ALL)
122     {
123         gObserveDoHandle = handle;
124     }
125     #ifdef WITH_PRESENCE
126     else if (method == OC_REST_PRESENCE)
127     {
128         gPresenceHandle = handle;
129     }
130     #endif
131
132     return ret;
133 }
134
135 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
136     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
137     {
138         OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
139     }
140
141     if(clientResponse)
142     {
143         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
144         OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response", clientResponse->resJSONPayload);
145     }
146     return OC_STACK_DELETE_TRANSACTION;
147 }
148
149 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
150 {
151     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
152     {
153         OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
154     }
155
156     if(clientResponse)
157     {
158         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
159         OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response", clientResponse->resJSONPayload);
160     }
161     return OC_STACK_DELETE_TRANSACTION;
162 }
163
164 OCStackApplicationResult deleteReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
165 {
166     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
167     {
168         OC_LOG(INFO, TAG, "Callback Context for DELETE recvd successfully");
169     }
170
171     if(clientResponse)
172     {
173         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
174         OC_LOG_V(INFO, TAG, "JSON = %s =============> Delete Response", clientResponse->resJSONPayload);
175     }
176     return OC_STACK_DELETE_TRANSACTION;
177 }
178
179 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
180 {
181     if(clientResponse == NULL)
182     {
183         OC_LOG(INFO, TAG, "The clientResponse is NULL");
184         return   OC_STACK_DELETE_TRANSACTION;
185     }
186     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
187     {
188         OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
189     }
190
191     OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
192     OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
193     OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response", clientResponse->resJSONPayload);
194
195     if(clientResponse->rcvdVendorSpecificHeaderOptions &&
196             clientResponse->numRcvdVendorSpecificHeaderOptions)
197     {
198         OC_LOG (INFO, TAG, "Received vendor specific options");
199         uint8_t i = 0;
200         OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
201         for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
202         {
203             if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
204             {
205                 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
206                         ((OCHeaderOption)rcvdOptions[i]).optionID );
207                 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
208                         ((OCHeaderOption)rcvdOptions[i]).optionLength);
209             }
210         }
211     }
212     return OC_STACK_DELETE_TRANSACTION;
213 }
214
215 OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
216     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
217     {
218         OC_LOG(INFO, TAG, "Callback Context for OBS query recvd successfully");
219     }
220
221     if(clientResponse)
222     {
223         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
224         OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
225         OC_LOG_V(INFO, TAG, "Callback Context for OBSERVE notification recvd successfully %d", gNumObserveNotifies);
226         OC_LOG_V(INFO, TAG, "JSON = %s =============> Obs Response", clientResponse->resJSONPayload);
227         gNumObserveNotifies++;
228         if (gNumObserveNotifies == 3)   //large number to test observing in DELETE case.
229         {
230             if(TEST_CASE == TEST_OBS_REQ_NON || TEST_CASE == TEST_OBS_REQ_CON){
231                 if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK){
232                     OC_LOG(ERROR, TAG, "Observe cancel error");
233                 }
234                 return OC_STACK_DELETE_TRANSACTION;
235             }else if(TEST_CASE == TEST_OBS_REQ_NON_CANCEL_IMM){
236                 if (OCCancel (gObserveDoHandle, OC_HIGH_QOS, NULL, 0) != OC_STACK_OK){
237                     OC_LOG(ERROR, TAG, "Observe cancel error");
238                 }
239             }
240         }
241         if(clientResponse->sequenceNumber == OC_OBSERVE_REGISTER){
242             OC_LOG(INFO, TAG, "This also serves as a registration confirmation");
243         }else if(clientResponse->sequenceNumber == OC_OBSERVE_DEREGISTER){
244             OC_LOG(INFO, TAG, "This also serves as a deregistration confirmation");
245             return OC_STACK_DELETE_TRANSACTION;
246         }else if(clientResponse->sequenceNumber == OC_OBSERVE_NO_OPTION){
247             OC_LOG(INFO, TAG, "This also tells you that registration/deregistration failed");
248             return OC_STACK_DELETE_TRANSACTION;
249         }
250     }
251     return OC_STACK_KEEP_TRANSACTION;
252 }
253 #ifdef WITH_PRESENCE
254 OCStackApplicationResult presenceCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
255     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
256     {
257         OC_LOG(INFO, TAG, "Callback Context for Presence recvd successfully");
258     }
259
260     if(clientResponse)
261     {
262         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
263         OC_LOG_V(INFO, TAG, "NONCE NUMBER: %u", clientResponse->sequenceNumber);
264         OC_LOG_V(INFO, TAG, "Callback Context for Presence notification recvd successfully %d", gNumPresenceNotifies);
265         OC_LOG_V(INFO, TAG, "JSON = %s =============> Presence Response", clientResponse->resJSONPayload);
266         gNumPresenceNotifies++;
267         if (gNumPresenceNotifies == 20)
268         {
269             if (OCCancel (gPresenceHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK){
270                 OC_LOG(ERROR, TAG, "Presence cancel error");
271             }
272             return OC_STACK_DELETE_TRANSACTION;
273         }
274     }
275     return OC_STACK_KEEP_TRANSACTION;
276 }
277 #endif
278
279 // This is a function called back when a device is discovered
280 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
281         OCClientResponse * clientResponse) {
282     uint8_t remoteIpAddr[4];
283     uint16_t remotePortNu;
284
285     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
286     {
287         OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
288     }
289
290     if (clientResponse)
291     {
292         OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
293
294         OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
295                 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
296         OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
297
298 #ifdef CA_INT
299         std::string connectionType = getConnectivityType (clientResponse->connType);
300         OC_LOG_V(INFO, TAG, "Discovered on %s", connectionType.c_str());
301 #endif
302         OC_LOG_V(INFO, TAG,
303                 "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
304                 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
305                 remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
306
307         parseClientResponse(clientResponse);
308
309         switch(TEST_CASE)
310         {
311             case TEST_GET_REQ_NON:
312                 InitGetRequest(OC_LOW_QOS, 0);
313                 break;
314             case TEST_PUT_REQ_NON:
315                 InitPutRequest();
316                 break;
317             case TEST_POST_REQ_NON:
318                 InitPostRequest(OC_LOW_QOS);
319                 break;
320             case TEST_DELETE_REQ_NON:
321                 InitDeleteRequest(OC_LOW_QOS);
322                 break;
323             case TEST_OBS_REQ_NON:
324             case TEST_OBS_REQ_NON_CANCEL_IMM:
325                 InitObserveRequest(OC_LOW_QOS);
326                 break;
327             case TEST_GET_UNAVAILABLE_RES_REQ_NON:
328                 InitGetRequestToUnavailableResource();
329                 break;
330             case TEST_GET_REQ_CON:
331                 InitGetRequest(OC_HIGH_QOS, 0);
332                 break;
333             case TEST_POST_REQ_CON:
334                 InitPostRequest(OC_HIGH_QOS);
335                 break;
336             case TEST_DELETE_REQ_CON:
337                 InitDeleteRequest(OC_HIGH_QOS);
338                 break;
339             case TEST_OBS_REQ_CON:
340                 InitObserveRequest(OC_HIGH_QOS);
341                 break;
342             #ifdef WITH_PRESENCE
343             case TEST_OBS_PRESENCE:
344             case TEST_OBS_PRESENCE_WITH_FILTER:
345             case TEST_OBS_PRESENCE_WITH_FILTERS:
346                 InitPresence();
347                 break;
348             #endif
349             case TEST_GET_REQ_NON_WITH_VENDOR_HEADER_OPTIONS:
350                 InitGetRequest(OC_LOW_QOS, 1);
351                 break;
352             case TEST_DISCOVER_DEV_REQ:
353                 InitDeviceDiscovery();
354                 break;
355             default:
356                 PrintUsage();
357                 break;
358         }
359     }
360 #ifdef CA_INT
361     return OC_STACK_KEEP_TRANSACTION;
362 #else
363     return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
364 #endif
365
366 }
367
368 OCStackApplicationResult DeviceDiscoveryReqCB (void* ctx, OCDoHandle handle,
369         OCClientResponse * clientResponse)
370 {
371     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
372     {
373         OC_LOG(INFO, TAG, "Callback Context for Device DISCOVER query recvd successfully");
374     }
375
376     if(clientResponse)
377     {
378         //OC_LOG truncates the response as it is too long.
379         fprintf(stderr, "Discovery response: \n %s\n", clientResponse->resJSONPayload);
380         fflush(stderr);
381     }
382
383     return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION;
384 }
385
386 #ifdef WITH_PRESENCE
387 int InitPresence()
388 {
389     OCStackResult result = OC_STACK_OK;
390     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
391     std::ostringstream query;
392     std::ostringstream querySuffix;
393     query << "coap://" << coapServerIP << ":" << coapServerPort << OC_PRESENCE_URI;
394     if(TEST_CASE == TEST_OBS_PRESENCE)
395     {
396         result = InvokeOCDoResource(query, OC_REST_PRESENCE, OC_LOW_QOS,
397                 presenceCB, NULL, 0);
398     }
399     if(TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTER || TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTERS)
400     {
401         querySuffix.str("");
402         querySuffix << query.str() << "?rt=core.light";
403         result = InvokeOCDoResource(querySuffix, OC_REST_PRESENCE, OC_LOW_QOS,
404                 presenceCB, NULL, 0);
405     }
406     if(TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTERS)
407     {
408         if(result == OC_STACK_OK)
409         {
410             querySuffix.str("");
411             querySuffix << query.str() << "?rt=core.fan";
412             result = InvokeOCDoResource(querySuffix, OC_REST_PRESENCE, OC_LOW_QOS,
413                     presenceCB, NULL, 0);
414         }
415     }
416     return result;
417 }
418 #endif
419
420 int InitGetRequestToUnavailableResource()
421 {
422     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
423     std::ostringstream query;
424     query << "coap://" << coapServerIP << ":" << coapServerPort << "/SomeUnknownResource";
425     return (InvokeOCDoResource(query, OC_REST_GET, OC_LOW_QOS, getReqCB, NULL, 0));
426 }
427
428 int InitObserveRequest(OCQualityOfService qos)
429 {
430     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
431     std::ostringstream query;
432     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
433     return (InvokeOCDoResource(query, OC_REST_OBSERVE, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, obsReqCB, NULL, 0));
434 }
435
436 int InitPutRequest()
437 {
438     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
439     std::ostringstream query;
440     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
441     return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0));
442 }
443
444 int InitPostRequest(OCQualityOfService qos)
445 {
446     OCStackResult result;
447     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
448     std::ostringstream query;
449     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
450
451     // First POST operation (to create an Light instance)
452     result = InvokeOCDoResource(query, OC_REST_POST,
453                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
454                                postReqCB, NULL, 0);
455     if (OC_STACK_OK != result)
456     {
457         // Error can happen if for example, network connectivity is down
458         OC_LOG(INFO, TAG, "First POST call did not succeed");
459     }
460
461     // Second POST operation (to create an Light instance)
462     result = InvokeOCDoResource(query, OC_REST_POST,
463                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
464                                postReqCB, NULL, 0);
465     if (OC_STACK_OK != result)
466     {
467         OC_LOG(INFO, TAG, "Second POST call did not succeed");
468     }
469
470     // This POST operation will update the original resourced /a/light
471     return (InvokeOCDoResource(query, OC_REST_POST,
472                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
473                                postReqCB, NULL, 0));
474 }
475
476 void* RequestDeleteDeathResourceTask(void* myqos)
477 {
478     sleep (30); //long enough to give the server time to finish deleting the resource.
479     std::ostringstream query;
480     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
481
482     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
483
484     // Second DELETE operation to delete the resource that might have been removed already.
485     OCQualityOfService qos;
486     if (myqos == NULL)
487         qos = OC_LOW_QOS;
488     else
489         qos = OC_HIGH_QOS;
490
491     OCStackResult result = InvokeOCDoResource(query, OC_REST_DELETE,
492                                qos,
493                                deleteReqCB, NULL, 0);
494
495     if (OC_STACK_OK != result)
496     {
497         OC_LOG(INFO, TAG, "Second DELETE call did not succeed");
498     }
499
500     return NULL;
501 }
502
503 int InitDeleteRequest(OCQualityOfService qos)
504 {
505     OCStackResult result;
506     std::ostringstream query;
507     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
508
509     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
510
511     // First DELETE operation
512     result = InvokeOCDoResource(query, OC_REST_DELETE,
513                                qos,
514                                deleteReqCB, NULL, 0);
515     if (OC_STACK_OK != result)
516     {
517         // Error can happen if for example, network connectivity is down
518         OC_LOG(INFO, TAG, "First DELETE call did not succeed");
519     }
520     else
521     {
522         //Create a thread to delete this resource again
523         pthread_t threadId;
524         pthread_create (&threadId, NULL, RequestDeleteDeathResourceTask, (void*)qos);
525     }
526
527     OC_LOG_V(INFO, TAG, "\n\nExit  %s", __func__);
528     return result;
529 }
530
531 int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptions)
532 {
533     OCHeaderOption options[MAX_HEADER_OPTIONS];
534
535     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
536     std::ostringstream query;
537     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
538
539     if(withVendorSpecificHeaderOptions)
540     {
541         uint8_t option0[] = {1,2,3,4,5,6,7,8,9,10};
542         uint8_t option1[] = {11,12,13,14,15,16,17,18,19,20};
543         memset(options, 0, sizeof(OCHeaderOption) * MAX_HEADER_OPTIONS);
544         options[0].protocolID = OC_COAP_ID;
545         options[0].optionID = 2048;
546         memcpy(options[0].optionData, option0, sizeof(option0));
547         options[0].optionLength = 10;
548         options[1].protocolID = OC_COAP_ID;
549         options[1].optionID = 3000;
550         memcpy(options[1].optionData, option1, sizeof(option1));
551         options[1].optionLength = 10;
552     }
553     if(withVendorSpecificHeaderOptions)
554     {
555         return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, getReqCB, options, 2));
556     }
557     else
558     {
559         return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
560     }
561 }
562
563 int InitDeviceDiscovery()
564 {
565     OCStackResult ret;
566     OCCallbackData cbData;
567     OCDoHandle handle;
568     char szQueryUri[64] = { 0 };
569
570     cbData.cb = DeviceDiscoveryReqCB;
571     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
572     cbData.cd = NULL;
573
574     if(UNICAST_DISCOVERY)
575     {
576         strncpy(szQueryUri, TEST_APP_UNICAST_DEVICE_DISCOVERY_QUERY,
577                         (strlen(TEST_APP_UNICAST_DEVICE_DISCOVERY_QUERY) + 1));
578     }
579     else
580     {
581         strncpy(szQueryUri, TEST_APP_MULTICAST_DEVICE_DISCOVERY_QUERY,
582                 (strlen(TEST_APP_MULTICAST_DEVICE_DISCOVERY_QUERY) + 1));
583     }
584
585 #ifdef CA_INT
586     ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, (OC_ETHERNET | OC_WIFI),
587                         OC_LOW_QOS, &cbData, NULL, 0);
588 #else
589     ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
590 #endif
591
592     if (ret != OC_STACK_OK)
593     {
594         OC_LOG(ERROR, TAG, "OCStack device error");
595     }
596
597     return ret;
598 }
599
600 int InitDiscovery()
601 {
602     OCStackResult ret;
603     OCCallbackData cbData;
604     OCDoHandle handle;
605     /* Start a discovery query*/
606     char szQueryUri[64] = { 0 };
607     if (UNICAST_DISCOVERY)
608     {
609         strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY);
610     }
611     else
612     {
613     #ifdef CA_INT
614         // TODO-CA CA is using 5298 for MC. Why 5298?
615         strcpy(szQueryUri, "coap://224.0.1.187:5298/oc/core");
616     #else
617         strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
618     #endif
619     }
620     cbData.cb = discoveryReqCB;
621     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
622     cbData.cd = NULL;
623 #ifdef CA_INT
624     ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, (OC_ETHERNET | OC_WIFI),
625                         OC_LOW_QOS, &cbData, NULL, 0);
626 #else
627     ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
628 #endif
629     if (ret != OC_STACK_OK)
630     {
631         OC_LOG(ERROR, TAG, "OCStack resource error");
632     }
633     return ret;
634 }
635
636 int main(int argc, char* argv[]) {
637     uint8_t addr[20] = {0};
638     uint8_t* paddr = NULL;
639     uint16_t port = USE_RANDOM_PORT;
640     uint8_t ifname[] = "eth0";
641     int opt;
642
643     while ((opt = getopt(argc, argv, "u:t:")) != -1)
644     {
645         switch(opt)
646         {
647             case 'u':
648                 UNICAST_DISCOVERY = atoi(optarg);
649                 break;
650             case 't':
651                 TEST_CASE = atoi(optarg);
652                 break;
653             default:
654                 PrintUsage();
655                 return -1;
656         }
657     }
658
659     if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
660             (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
661     {
662         PrintUsage();
663         return -1;
664     }
665
666
667     /*Get Ip address on defined interface and initialize coap on it with random port number
668      * this port number will be used as a source port in all coap communications*/
669     if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
670                 sizeof(addr)) == ERR_SUCCESS)
671     {
672         OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
673         paddr = addr;
674     }
675
676     /* Initialize OCStack*/
677     if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK) {
678         OC_LOG(ERROR, TAG, "OCStack init error");
679         return 0;
680     }
681
682     InitDiscovery();
683
684     // Break from loop with Ctrl+C
685     OC_LOG(INFO, TAG, "Entering occlient main loop...");
686     signal(SIGINT, handleSigInt);
687     while (!gQuitFlag) {
688
689         if (OCProcess() != OC_STACK_OK) {
690             OC_LOG(ERROR, TAG, "OCStack process error");
691             return 0;
692         }
693
694         sleep(2);
695     }
696     OC_LOG(INFO, TAG, "Exiting occlient main loop...");
697
698     if (OCStop() != OC_STACK_OK) {
699         OC_LOG(ERROR, TAG, "OCStack stop error");
700     }
701
702     return 0;
703 }
704
705 std::string getIPAddrTBServer(OCClientResponse * clientResponse) {
706     if(!clientResponse) return "";
707     if(!clientResponse->addr) return "";
708     uint8_t a, b, c, d = 0;
709     if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
710
711     char ipaddr[16] = {'\0'};
712     snprintf(ipaddr,  sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d); // ostringstream not working correctly here, hence snprintf
713     return std::string (ipaddr);
714 }
715
716 std::string getPortTBServer(OCClientResponse * clientResponse){
717     if(!clientResponse) return "";
718     if(!clientResponse->addr) return "";
719     uint16_t p = 0;
720     if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
721     std::ostringstream ss;
722     ss << p;
723     return ss.str();
724 }
725
726 std::string getConnectivityType (OCConnectivityType connType)
727 {
728     switch (connType)
729     {
730         case OC_ETHERNET:
731             return "Ethernet";
732
733         case OC_WIFI:
734             return "WiFi";
735
736         case OC_LE:
737             return "BLE";
738
739         case OC_EDR:
740             return "BT";
741
742         default:
743             return "Incorrect connectivity";
744     }
745 }
746
747 std::string getQueryStrForGetPut(OCClientResponse * clientResponse){
748
749     return "/a/light";
750 }
751
752 void parseClientResponse(OCClientResponse * clientResponse){
753     coapServerIP = getIPAddrTBServer(clientResponse);
754     coapServerPort = getPortTBServer(clientResponse);
755     coapServerResource = getQueryStrForGetPut(clientResponse);
756 }