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