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