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