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