Repo Merge: Moving resource API down a directory
[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 CTX_VAL 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 : occlient -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) {}
124     if(ctx == (void*)CTX_VAL) {
125         OC_LOG_V(INFO, TAG, "Callback Context for PUT query recvd successfully");
126         OC_LOG_V(INFO, TAG, "JSON = %s =============> Discovered", clientResponse->resJSONPayload);
127     }
128
129     return OC_STACK_KEEP_TRANSACTION;
130 }
131
132 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
133     OC_LOG_V(INFO, TAG, "StackResult: %s",
134             getResult(clientResponse->result));
135     if(ctx == (void*)CTX_VAL) {
136         OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
137         if(clientResponse->sequenceNumber == 0) {
138             OC_LOG_V(INFO, TAG, "Callback Context for GET query recvd successfully");
139             OC_LOG_V(INFO, TAG, "Fnd' Rsrc': %s", clientResponse->resJSONPayload);
140         }
141         else {
142             OC_LOG_V(INFO, TAG, "Callback Context for OBSERVE notification recvd successfully %d", gNumObserveNotifies);
143             OC_LOG_V(INFO, TAG, "Fnd' Rsrc': %s", clientResponse->resJSONPayload);
144             gNumObserveNotifies++;
145             if (gNumObserveNotifies == 3)
146             {
147                 if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK){
148                     OC_LOG(ERROR, TAG, "Observe cancel error");
149                 }
150             }
151         }
152     }
153     if(TEST == TEST_PUT_DEFAULT || TEST == TEST_PUT_BATCH || TEST == TEST_PUT_LINK_LIST)
154     {
155         InitPutRequest(clientResponse);
156     }
157     return OC_STACK_KEEP_TRANSACTION;
158 }
159
160
161 // This is a function called back when a device is discovered
162 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
163         OCClientResponse * clientResponse) {
164     uint8_t remoteIpAddr[4];
165     uint16_t remotePortNu;
166
167     OC_LOG(INFO, TAG,
168             "Entering discoveryReqCB (Application Layer CB)");
169     OC_LOG_V(INFO, TAG, "StackResult: %s",
170             getResult(clientResponse->result));
171
172     if (ctx == (void*) CTX_VAL) {
173         OC_LOG_V(INFO, TAG, "Callback Context recvd successfully");
174     }
175
176     OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
177             remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
178     OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
179 #if 0
180     OC_LOG_V(INFO, TAG,
181             "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
182             clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
183             remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
184 #endif
185
186     if(TEST == TEST_UNKNOWN_RESOURCE_GET_DEFAULT || TEST == TEST_UNKNOWN_RESOURCE_GET_BATCH ||\
187             TEST == TEST_UNKNOWN_RESOURCE_GET_LINK_LIST)
188     {
189         InitGetRequestToUnavailableResource(clientResponse);
190     }
191     else
192     {
193         InitGetRequest(clientResponse);
194     }
195     return OC_STACK_KEEP_TRANSACTION;
196 }
197
198
199 int InitGetRequestToUnavailableResource(OCClientResponse * clientResponse)
200 {
201     OCStackResult ret;
202     OCCallbackData cbData;
203     OCDoHandle handle;
204     std::ostringstream getQuery;
205     getQuery << "coap://" << getIPAddrTBServer(clientResponse) << ":" << getPortTBServer(clientResponse) << "/SomeUnknownResource";
206     cbData.cb = getReqCB;
207     cbData.context = (void*)CTX_VAL;
208     cbData.cd = NULL;
209
210     ret = OCDoResource(&handle, OC_REST_GET, getQuery.str().c_str(), 0, 0, OC_LOW_QOS,
211             &cbData, NULL, 0);
212     if (ret != OC_STACK_OK)
213     {
214         OC_LOG(ERROR, TAG, "OCStack resource error");
215     }
216     return ret;
217 }
218
219
220 int InitObserveRequest(OCClientResponse * clientResponse)
221 {
222     OCStackResult ret;
223     OCCallbackData cbData;
224     OCDoHandle handle;
225     std::ostringstream obsReg;
226     obsReg << "coap://" << getIPAddrTBServer(clientResponse) << ":" << getPortTBServer(clientResponse) << getQueryStrForGetPut(clientResponse->resJSONPayload);
227     cbData.cb = getReqCB;
228     cbData.context = (void*)CTX_VAL;
229     cbData.cd = NULL;
230     OC_LOG_V(INFO, TAG, "OBSERVE payload from client = %s ", putPayload.c_str());
231
232     ret = OCDoResource(&handle, OC_REST_OBSERVE, obsReg.str().c_str(), 0, 0, OC_LOW_QOS,
233             &cbData, NULL, 0);
234     if (ret != OC_STACK_OK)
235     {
236         OC_LOG(ERROR, TAG, "OCStack resource error");
237     }
238     else
239     {
240         gObserveDoHandle = handle;
241     }
242     return ret;
243 }
244
245
246 int InitPutRequest(OCClientResponse * clientResponse)
247 {
248     OCStackResult ret;
249     OCCallbackData cbData;
250     OCDoHandle handle;
251     //* Make a PUT query*/
252     std::ostringstream getQuery;
253     getQuery << "coap://" << getIPAddrTBServer(clientResponse) << ":" << getPortTBServer(clientResponse) <<
254     "/a/room" << queryInterface[TEST].text;
255     cbData.cb = putReqCB;
256     cbData.context = (void*)CTX_VAL;
257     cbData.cd = NULL;
258     OC_LOG_V(INFO, TAG, "PUT payload from client = %s ", putPayload.c_str());
259
260     ret = OCDoResource(&handle, OC_REST_PUT, getQuery.str().c_str(), 0, putPayload.c_str(),
261             OC_LOW_QOS, &cbData, NULL, 0);
262     if (ret != OC_STACK_OK)
263     {
264         OC_LOG(ERROR, TAG, "OCStack resource error");
265     }
266     return ret;
267 }
268
269
270 int InitGetRequest(OCClientResponse * clientResponse)
271 {
272     OCStackResult ret;
273     OCCallbackData cbData;
274     OCDoHandle handle;
275
276     uint8_t remoteIpAddr[4];
277     uint16_t remotePortNu;
278
279     OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
280             remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
281     OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
282
283     //* Make a GET query*/
284     std::ostringstream getQuery;
285     getQuery << "coap://" << getIPAddrTBServer(clientResponse) << ":" << getPortTBServer(clientResponse) <<
286     "/a/room" << queryInterface[TEST].text;
287
288     std::cout << "Get Query: " << getQuery.str() << std::endl;
289
290     cbData.cb = getReqCB;
291     cbData.context = (void*)CTX_VAL;
292     cbData.cd = NULL;
293     ret = OCDoResource(&handle, OC_REST_GET, getQuery.str().c_str(), 0, 0, OC_LOW_QOS,
294             &cbData, NULL, 0);
295     if (ret != OC_STACK_OK)
296     {
297         OC_LOG(ERROR, TAG, "OCStack resource error");
298     }
299     return ret;
300 }
301
302 int InitDiscovery()
303 {
304     OCStackResult ret;
305     OCCallbackData cbData;
306     OCDoHandle handle;
307     /* Start a discovery query*/
308     char szQueryUri[64] = { 0 };
309
310     strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
311
312     cbData.cb = discoveryReqCB;
313     cbData.context = (void*)CTX_VAL;
314     cbData.cd = NULL;
315     ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS,
316             &cbData, NULL, 0);
317     if (ret != OC_STACK_OK)
318     {
319         OC_LOG(ERROR, TAG, "OCStack resource error");
320     }
321     return ret;
322 }
323
324 int main(int argc, char* argv[]) {
325     if(argc >= 2 && strcmp(argv[1], "-t") == 0)
326     {
327         TEST = atoi(argv[2]);
328         if(TEST >= MAX_TESTS || TEST < 1)
329         {
330             PrintUsage();
331             return 0;
332         }
333     }
334     else
335     {
336         PrintUsage();
337         return 0;
338     }
339     uint8_t addr[20] = {0};
340     uint8_t* paddr = NULL;
341     uint16_t port = USE_RANDOM_PORT;
342     uint8_t ifname[] = "eth0";
343
344     /*Get Ip address on defined interface and initialize coap on it with random port number
345      * this port number will be used as a source port in all coap communications*/
346     if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
347                                sizeof(addr)) == ERR_SUCCESS)
348     {
349         OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
350         paddr = addr;
351     }
352
353     /* Initialize OCStack*/
354     if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK) {
355         OC_LOG(ERROR, TAG, "OCStack init error");
356         return 0;
357     }
358
359     InitDiscovery();
360
361     // Break from loop with Ctrl+C
362     OC_LOG(INFO, TAG, "Entering occlient main loop...");
363     signal(SIGINT, handleSigInt);
364     while (!gQuitFlag) {
365
366         if (OCProcess() != OC_STACK_OK) {
367             OC_LOG(ERROR, TAG, "OCStack process error");
368             return 0;
369         }
370
371         sleep(2);
372     }
373     OC_LOG(INFO, TAG, "Exiting occlient main loop...");
374
375     if (OCStop() != OC_STACK_OK) {
376         OC_LOG(ERROR, TAG, "OCStack stop error");
377     }
378
379     return 0;
380 }
381
382 std::string getIPAddrTBServer(OCClientResponse * clientResponse) {
383     if(!clientResponse) return "";
384     if(!clientResponse->addr) return "";
385     uint8_t a, b, c, d = 0;
386     if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
387
388     char ipaddr[16] = {'\0'};
389     snprintf(ipaddr,  sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d); // ostringstream not working correctly here, hence snprintf
390     //printf("IP address string of the TB server = %s\n", *out_ipaddr);
391     return std::string (ipaddr);
392 }
393
394
395 std::string getPortTBServer(OCClientResponse * clientResponse){
396     if(!clientResponse) return "";
397     if(!clientResponse->addr) return "";
398     uint16_t p = 0;
399     if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
400     std::ostringstream ss;
401     ss << p;
402     return ss.str();
403 }
404
405 std::string getQueryStrForGetPut(unsigned  const char * responsePayload){
406
407     std::string jsonPayload(reinterpret_cast<char*>(const_cast<unsigned char*>(responsePayload)));
408
409     return "/a/room";
410 }