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