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