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