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