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