replace : iotivity -> iotivity-sec
[platform/upstream/iotivity.git] / resource / csdk / stack / samples / linux / SimpleClientServer / occlientcoll.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 "iotivity_config.h"
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <signal.h>
26 #ifdef HAVE_UNISTD_H
27 #include <unistd.h>
28 #endif
29 #ifdef HAVE_WINDOWS_H
30 #include <windows.h>
31 #endif
32 #include <ocstack.h>
33 #include <iostream>
34 #include <sstream>
35 #include <getopt.h>
36 #include "ocpayload.h"
37 #include "payload_logging.h"
38 #include "logger.h"
39 #include "common.h"
40 #include "oic_string.h"
41
42 std::string getQueryStrForGetPut();
43
44 #define TAG ("occlient")
45 #define DEFAULT_CONTEXT_VALUE 0x99
46 #ifndef MAX_LENGTH_IPv4_ADDR
47 #define MAX_LENGTH_IPv4_ADDR 16
48 #endif
49
50 typedef enum
51 {
52     TEST_INVALID = 0,
53     TEST_GET_DEFAULT,
54     TEST_GET_BATCH,
55     TEST_GET_LINK_LIST,
56     TEST_PUT_DEFAULT,
57     TEST_PUT_BATCH,
58     TEST_PUT_LINK_LIST,
59     TEST_UNKNOWN_RESOURCE_GET_DEFAULT,
60     TEST_UNKNOWN_RESOURCE_GET_BATCH,
61     TEST_UNKNOWN_RESOURCE_GET_LINK_LIST,
62     TEST_GET_EMPTY,
63     TEST_GET_NULL,
64     MAX_TESTS
65 } CLIENT_TEST;
66
67 /**
68  * List of connectivity types that can be initiated from the client
69  * Required for user input validation
70  */
71 typedef enum {
72     CT_ADAPTER_DEFAULT = 0,
73     CT_IP,
74     MAX_CT
75 } CLIENT_ConnectivityType_TYPE;
76
77 unsigned static int TestType = TEST_INVALID;
78 unsigned static int ConnectivityType = 0;
79
80 typedef struct
81 {
82     char text[30];
83     CLIENT_TEST test;
84 } testToTextMap;
85
86 testToTextMap queryInterface[] = {
87         {"invalid", TEST_INVALID},
88         {"?if=oic.if.baseline", TEST_GET_DEFAULT},
89         {"?if=oic.if.b", TEST_GET_BATCH},
90         {"?if=oic.if.ll", TEST_GET_LINK_LIST},
91         {"?if=oic.if.baseline", TEST_UNKNOWN_RESOURCE_GET_DEFAULT},
92         {"?if=oic.if.b", TEST_UNKNOWN_RESOURCE_GET_BATCH},
93         {"?if=oic.if.ll", TEST_UNKNOWN_RESOURCE_GET_LINK_LIST},
94         {"?if=oic.if.baseline", TEST_PUT_DEFAULT},
95         {"?if=oic.if.b", TEST_PUT_BATCH},
96         {"?if=oic.if.ll", TEST_PUT_LINK_LIST},
97         {"", TEST_GET_EMPTY},
98         {NULL, TEST_GET_NULL},
99 };
100
101
102 //The following variable determines the interface protocol (IP, etc)
103 //to be used for sending unicast messages. Default set to IP.
104 static OCConnectivityType ConnType = CT_ADAPTER_IP;
105 static const char * RESOURCE_DISCOVERY_QUERY = "/oic/res";
106
107 // The handle for the observe registration
108 OCDoHandle gObserveDoHandle;
109 // After this crosses a threshold client deregisters for further observations
110 int gNumObserveNotifies = 1;
111
112 int gQuitFlag = 0;
113 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
114 void handleSigInt(int signum)
115 {
116     if (signum == SIGINT)
117     {
118         gQuitFlag = 1;
119     }
120 }
121
122 // Forward Declaration
123 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse);
124 int InitGetRequestToUnavailableResource(OCClientResponse * clientResponse);
125 int InitObserveRequest(OCClientResponse * clientResponse);
126 int InitPutRequest(OCClientResponse * clientResponse);
127 int InitGetRequest(OCClientResponse * clientResponse);
128 int InitDiscovery();
129
130 OCPayload* putPayload()
131 {
132     OCRepPayload* payload = OCRepPayloadCreate();
133
134     if(!payload)
135     {
136         std::cout << "Failed to create put payload object"<<std::endl;
137         std::exit(1);
138     }
139
140     OCRepPayloadSetPropInt(payload, "power", 15);
141     OCRepPayloadSetPropBool(payload, "state", true);
142
143     return (OCPayload*) payload;
144 }
145
146 void PrintUsage()
147 {
148     OIC_LOG(INFO, TAG, "Usage : occlientcoll -t <Test Case> -c <CA connectivity Type>");
149     OIC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
150     OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
151     OIC_LOG(INFO, TAG, "Test Case 1 : Discover Resources && Initiate GET Request on an "\
152             "available resource using default interface.");
153     OIC_LOG(INFO, TAG, "Test Case 2 : Discover Resources && Initiate GET Request on an "\
154                  "available resource using batch interface.");
155     OIC_LOG(INFO, TAG, "Test Case 3 : Discover Resources && Initiate GET Request on an "\
156                  "available resource using link list interface.");
157     OIC_LOG(INFO, TAG, "Test Case 4 : Discover Resources && Initiate GET & PUT Request on an "\
158                  "available resource using default interface.");
159     OIC_LOG(INFO, TAG, "Test Case 5 : Discover Resources && Initiate GET & PUT Request on an "\
160                  "available resource using batch interface.");
161     OIC_LOG(INFO, TAG, "Test Case 6 : Discover Resources && Initiate GET & PUT Request on an "\
162                  "available resource using link list interface.");
163     OIC_LOG(INFO, TAG, "Test Case 7 : Discover Resources && Initiate GET Request on an "\
164                  "unavailable resource using default interface.");
165     OIC_LOG(INFO, TAG, "Test Case 8 : Discover Resources && Initiate GET Request on an "\
166                  "unavailable resource using batch interface.");
167     OIC_LOG(INFO, TAG, "Test Case 9 : Discover Resources && Initiate GET Request on an "\
168                  "unavailable resource using link list interface.");
169     OIC_LOG(INFO, TAG, "Test Case 10 : Discover Resources && Initiate GET Request on an "\
170                  "empty resource.");
171     OIC_LOG(INFO, TAG, "Test Case 11 : Discover Resources && Initiate GET Request on an "\
172                  "NULL resource.");
173
174 }
175
176 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle /*handle*/,
177                                   OCClientResponse * clientResponse)
178 {
179     if(clientResponse == NULL)
180     {
181         OIC_LOG(INFO, TAG, "The clientResponse is NULL");
182         return   OC_STACK_DELETE_TRANSACTION;
183     }
184     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
185     {
186         OIC_LOG_V(INFO, TAG, "Callback Context for PUT query recvd successfully");
187         OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
188     }
189
190     return OC_STACK_KEEP_TRANSACTION;
191 }
192
193 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
194                                   OCClientResponse * clientResponse)
195 {
196     OIC_LOG_V(INFO, TAG, "StackResult: %s",
197             getResult(clientResponse->result));
198     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
199     {
200         OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
201         if(clientResponse->sequenceNumber == 0)
202         {
203             OIC_LOG_V(INFO, TAG, "Callback Context for GET query recvd successfully");
204             OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
205         }
206         else
207         {
208             OIC_LOG_V(INFO, TAG, "Callback Context for Get recvd successfully %d",
209                     gNumObserveNotifies);
210             OIC_LOG_PAYLOAD(INFO, clientResponse->payload);;
211             gNumObserveNotifies++;
212             if (gNumObserveNotifies == 3)
213             {
214                 if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK)
215                 {
216                     OIC_LOG(ERROR, TAG, "Observe cancel error");
217                 }
218             }
219         }
220     }
221     if(TestType == TEST_PUT_DEFAULT || TestType == TEST_PUT_BATCH || TestType == TEST_PUT_LINK_LIST)
222     {
223         InitPutRequest(clientResponse);
224     }
225     return OC_STACK_KEEP_TRANSACTION;
226 }
227
228 // This is a function called back when a device is discovered
229 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
230                                         OCClientResponse * clientResponse)
231 {
232     OIC_LOG(INFO, TAG,
233             "Entering discoveryReqCB (Application Layer CB)");
234     OIC_LOG_V(INFO, TAG, "StackResult: %s",
235             getResult(clientResponse->result));
236
237     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
238     {
239         OIC_LOG_V(INFO, TAG, "Callback Context recvd successfully");
240     }
241
242     OIC_LOG_V(INFO, TAG,
243             "Device =============> Discovered @ %s:%d",
244             clientResponse->devAddr.addr,
245             clientResponse->devAddr.port);
246     OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
247
248     ConnType = clientResponse->connType;
249
250     if(TestType == TEST_UNKNOWN_RESOURCE_GET_DEFAULT || TestType == TEST_UNKNOWN_RESOURCE_GET_BATCH ||\
251             TestType == TEST_UNKNOWN_RESOURCE_GET_LINK_LIST)
252     {
253         InitGetRequestToUnavailableResource(clientResponse);
254     }
255     else
256     {
257         InitGetRequest(clientResponse);
258     }
259     return OC_STACK_KEEP_TRANSACTION;
260 }
261
262
263 int InitGetRequestToUnavailableResource(OCClientResponse * clientResponse)
264 {
265     OCStackResult ret;
266     OCCallbackData cbData;
267     std::ostringstream getQuery;
268     getQuery << "/SomeUnknownResource";
269     cbData.cb = getReqCB;
270     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
271     cbData.cd = NULL;
272
273     ret = OCDoRequest(NULL, OC_REST_GET, getQuery.str().c_str(),
274                       &clientResponse->devAddr, 0, ConnType, OC_LOW_QOS,
275                       &cbData, NULL, 0);
276     if (ret != OC_STACK_OK)
277     {
278         OIC_LOG(ERROR, TAG, "OCStack resource error");
279     }
280     return ret;
281 }
282
283
284 int InitObserveRequest(OCClientResponse * clientResponse)
285 {
286     OCStackResult ret;
287     OCCallbackData cbData;
288     OCDoHandle handle;
289     std::ostringstream obsReg;
290     obsReg << getQueryStrForGetPut();
291     cbData.cb = getReqCB;
292     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
293     cbData.cd = NULL;
294     OIC_LOG_V(INFO, TAG, "OBSERVE payload from client =");
295     OCPayload* payload = putPayload();
296     OIC_LOG_PAYLOAD(INFO, payload);
297     OCPayloadDestroy(payload);
298
299     ret = OCDoRequest(&handle, OC_REST_OBSERVE, obsReg.str().c_str(),
300                       &clientResponse->devAddr, 0, ConnType,
301                       OC_LOW_QOS, &cbData, NULL, 0);
302     if (ret != OC_STACK_OK)
303     {
304         OIC_LOG(ERROR, TAG, "OCStack resource error");
305     }
306     else
307     {
308         gObserveDoHandle = handle;
309     }
310     return ret;
311 }
312
313
314 int InitPutRequest(OCClientResponse * clientResponse)
315 {
316     OCStackResult ret;
317     OCCallbackData cbData;
318     //* Make a PUT query*/
319     std::ostringstream getQuery;
320     getQuery << "coap://" << clientResponse->devAddr.addr << ":" <<
321             clientResponse->devAddr.port <<
322             "/a/room" << queryInterface[TestType].text;
323     cbData.cb = putReqCB;
324     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
325     cbData.cd = NULL;
326     OIC_LOG_V(INFO, TAG, "PUT payload from client = ");
327     OCPayload* payload = putPayload();
328     OIC_LOG_PAYLOAD(INFO, payload);
329
330     ret = OCDoRequest(NULL, OC_REST_PUT, getQuery.str().c_str(),
331                       &clientResponse->devAddr, payload, ConnType,
332                       OC_LOW_QOS, &cbData, NULL, 0);
333
334     OCPayloadDestroy(payload);
335
336     if (ret != OC_STACK_OK)
337     {
338         OIC_LOG(ERROR, TAG, "OCStack resource error");
339     }
340     return ret;
341 }
342
343
344 int InitGetRequest(OCClientResponse * clientResponse)
345 {
346     OCStackResult ret;
347     OCCallbackData cbData;
348
349     //* Make a GET query*/
350     std::ostringstream getQuery;
351     getQuery << "/a/room" << queryInterface[TestType].text;
352
353     std::cout << "Get Query: " << getQuery.str() << std::endl;
354
355     cbData.cb = getReqCB;
356     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
357     cbData.cd = NULL;
358     ret = OCDoRequest(NULL, OC_REST_GET, getQuery.str().c_str(),
359                       &clientResponse->devAddr, 0, ConnType, OC_LOW_QOS,
360                       &cbData, NULL, 0);
361     if (ret != OC_STACK_OK)
362     {
363         OIC_LOG(ERROR, TAG, "OCStack resource error");
364     }
365     return ret;
366 }
367
368 int InitDiscovery()
369 {
370     OCStackResult ret;
371     OCCallbackData cbData;
372     /* Start a discovery query*/
373     char szQueryUri[MAX_QUERY_LENGTH] = { 0 };
374
375     OICStrcpy(szQueryUri, sizeof(szQueryUri), RESOURCE_DISCOVERY_QUERY);
376
377     cbData.cb = discoveryReqCB;
378     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
379     cbData.cd = NULL;
380     ret = OCDoRequest(NULL, OC_REST_DISCOVER, szQueryUri, NULL, 0, ConnType,
381                       OC_LOW_QOS,
382                       &cbData, NULL, 0);
383     if (ret != OC_STACK_OK)
384     {
385         OIC_LOG(ERROR, TAG, "OCStack resource error");
386     }
387     return ret;
388 }
389
390 int main(int argc, char* argv[])
391 {
392     int opt;
393
394     while ((opt = getopt(argc, argv, "t:c:")) != -1)
395     {
396         switch (opt)
397         {
398             case 't':
399                 TestType = atoi(optarg);
400                 break;
401             case 'c':
402                 ConnectivityType = atoi(optarg);
403                 break;
404             default:
405                 PrintUsage();
406                 return -1;
407         }
408     }
409     if ((TestType <= TEST_INVALID || TestType >= MAX_TESTS) ||
410         ConnectivityType >= MAX_CT)
411     {
412         PrintUsage();
413         return -1;
414     }
415
416     /* Initialize OCStack*/
417     if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
418     {
419         OIC_LOG(ERROR, TAG, "OCStack init error");
420         return 0;
421     }
422
423     if(ConnectivityType == CT_ADAPTER_DEFAULT || ConnectivityType == CT_IP)
424     {
425         ConnType = CT_ADAPTER_IP;
426     }
427     else
428     {
429         OIC_LOG(INFO, TAG, "Default Connectivity type selected...");
430         ConnType = CT_ADAPTER_IP;
431     }
432
433     InitDiscovery();
434
435     // Break from loop with Ctrl+C
436     OIC_LOG(INFO, TAG, "Entering occlient main loop...");
437     signal(SIGINT, handleSigInt);
438     while (!gQuitFlag)
439     {
440
441         if (OCProcess() != OC_STACK_OK)
442         {
443             OIC_LOG(ERROR, TAG, "OCStack process error");
444             return 0;
445         }
446
447         sleep(2);
448     } OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
449
450     if (OCStop() != OC_STACK_OK)
451     {
452         OIC_LOG(ERROR, TAG, "OCStack stop error");
453     }
454
455     return 0;
456 }
457
458 std::string getQueryStrForGetPut()
459 {
460     return "/a/room";
461 }