iotivity 0.9.0
[platform/upstream/iotivity.git] / resource / csdk / stack / samples / linux / SimpleClientServer / occlientbasicops.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 <iostream>
27 #include <sstream>
28 #include "ocstack.h"
29 #include "logger.h"
30 #include "occlientbasicops.h"
31
32 static int UNICAST_DISCOVERY = 0;
33 static int TEST_CASE = 0;
34 static const char * TEST_APP_UNICAST_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core";
35 static std::string putPayload = "{\"state\":\"off\",\"power\":10}";
36 static std::string coapServerIP = "255.255.255.255";
37 static std::string coapServerPort = "5683";
38 static std::string coapServerResource = "/a/led";
39
40 int gQuitFlag = 0;
41
42 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
43 void handleSigInt(int signum)
44 {
45     if (signum == SIGINT)
46     {
47         gQuitFlag = 1;
48     }
49 }
50
51 static void PrintUsage()
52 {
53     OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3>");
54     OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
55     OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
56     OC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
57             " Initiate Nonconfirmable Get/Put/Post Requests");
58     OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
59 }
60
61 OCStackResult InvokeOCDoResource(std::ostringstream &query,
62         OCMethod method, OCQualityOfService qos,
63         OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
64 {
65     OCStackResult ret;
66     OCCallbackData cbData;
67     OCDoHandle handle;
68
69     cbData.cb = cb;
70     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
71     cbData.cd = NULL;
72
73     ret = OCDoResource(&handle, method, query.str().c_str(), 0,
74             (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL,
75             qos, &cbData, options, numOptions);
76
77     if (ret != OC_STACK_OK)
78     {
79         OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
80     }
81
82     return ret;
83 }
84
85 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
86 {
87     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
88     {
89         OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
90     }
91
92     if(clientResponse)
93     {
94         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
95         OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response", clientResponse->resJSONPayload);
96     }
97     return OC_STACK_DELETE_TRANSACTION;
98 }
99
100 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
101 {
102     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
103     {
104         OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
105     }
106
107     if(clientResponse)
108     {
109         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
110         OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response",
111                 clientResponse->resJSONPayload);
112     }
113     return OC_STACK_DELETE_TRANSACTION;
114 }
115
116 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
117 {
118     if(clientResponse == NULL)
119     {
120         OC_LOG(INFO, TAG, "The clientResponse is NULL");
121         return   OC_STACK_DELETE_TRANSACTION;
122     }
123     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
124     {
125         OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
126     }
127
128     OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
129     OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
130     OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response",
131             clientResponse->resJSONPayload);
132
133     if(clientResponse->rcvdVendorSpecificHeaderOptions &&
134             clientResponse->numRcvdVendorSpecificHeaderOptions)
135     {
136         OC_LOG (INFO, TAG, "Received vendor specific options");
137         uint8_t i = 0;
138         OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
139         for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
140         {
141             if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
142             {
143                 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
144                         ((OCHeaderOption)rcvdOptions[i]).optionID );
145                 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
146                         ((OCHeaderOption)rcvdOptions[i]).optionLength);
147             }
148         }
149     }
150     return OC_STACK_DELETE_TRANSACTION;
151 }
152
153 // This is a function called back when a device is discovered
154 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
155         OCClientResponse * clientResponse)
156 {
157     uint8_t remoteIpAddr[4];
158     uint16_t remotePortNu;
159
160     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
161     {
162         OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
163     }
164
165     if (clientResponse)
166     {
167         OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
168
169         OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
170                 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
171         OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
172
173         OC_LOG_V(INFO, TAG,
174                 "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
175                 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
176                 remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
177
178         parseClientResponse(clientResponse);
179
180         switch(TEST_CASE)
181         {
182             case TEST_NON_CON_OP:
183                 InitGetRequest(OC_LOW_QOS);
184                 InitPutRequest();
185                 InitPostRequest(OC_LOW_QOS);
186                 break;
187             case TEST_CON_OP:
188                 InitGetRequest(OC_HIGH_QOS);
189                 InitPutRequest();
190                 InitPostRequest(OC_HIGH_QOS);
191                 break;
192             default:
193                 PrintUsage();
194                 break;
195         }
196     }
197
198     return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
199
200 }
201
202 int InitPutRequest()
203 {
204     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
205     std::ostringstream query;
206     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
207     return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0));
208 }
209
210 int InitPostRequest(OCQualityOfService qos)
211 {
212     OCStackResult result;
213     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
214     std::ostringstream query;
215     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
216
217     // First POST operation (to create an LED instance)
218     result = InvokeOCDoResource(query, OC_REST_POST,
219             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
220             postReqCB, NULL, 0);
221     if (OC_STACK_OK != result)
222     {
223         // Error can happen if for example, network connectivity is down
224         OC_LOG(INFO, TAG, "First POST call did not succeed");
225     }
226
227     // Second POST operation (to create an LED instance)
228     result = InvokeOCDoResource(query, OC_REST_POST,
229             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
230             postReqCB, NULL, 0);
231     if (OC_STACK_OK != result)
232     {
233         OC_LOG(INFO, TAG, "Second POST call did not succeed");
234     }
235
236     // This POST operation will update the original resourced /a/led
237     return (InvokeOCDoResource(query, OC_REST_POST,
238                 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
239                 postReqCB, NULL, 0));
240 }
241
242 int InitGetRequest(OCQualityOfService qos)
243 {
244     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
245     std::ostringstream query;
246     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
247
248     return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
249             OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
250 }
251
252 int InitDiscovery()
253 {
254     OCStackResult ret;
255     OCCallbackData cbData;
256     OCDoHandle handle;
257     /* Start a discovery query*/
258     char szQueryUri[64] = { 0 };
259     if (UNICAST_DISCOVERY)
260     {
261         strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY);
262     }
263     else
264     {
265         strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
266     }
267     cbData.cb = discoveryReqCB;
268     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
269     cbData.cd = NULL;
270     ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, 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 int main(int argc, char* argv[])
279 {
280     uint8_t addr[20] = {0};
281     uint8_t* paddr = NULL;
282     uint16_t port = USE_RANDOM_PORT;
283     uint8_t ifname[] = "eth0";
284     int opt;
285
286     while ((opt = getopt(argc, argv, "u:t:")) != -1)
287     {
288         switch(opt)
289         {
290             case 'u':
291                 UNICAST_DISCOVERY = atoi(optarg);
292                 break;
293             case 't':
294                 TEST_CASE = atoi(optarg);
295                 break;
296             default:
297                 PrintUsage();
298                 return -1;
299         }
300     }
301
302     if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
303             (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
304     {
305         PrintUsage();
306         return -1;
307     }
308
309
310     /*Get Ip address on defined interface and initialize coap on it with random port number
311      * this port number will be used as a source port in all coap communications*/
312     if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
313                 sizeof(addr)) == ERR_SUCCESS)
314     {
315         OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
316         paddr = addr;
317     }
318
319     /* Initialize OCStack*/
320     if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK)
321     {
322         OC_LOG(ERROR, TAG, "OCStack init error");
323         return 0;
324     }
325
326     InitDiscovery();
327
328     // Break from loop with Ctrl+C
329     OC_LOG(INFO, TAG, "Entering occlient main loop...");
330     signal(SIGINT, handleSigInt);
331     while (!gQuitFlag)
332     {
333         if (OCProcess() != OC_STACK_OK)
334         {
335             OC_LOG(ERROR, TAG, "OCStack process error");
336             return 0;
337         }
338
339         sleep(2);
340     }
341     OC_LOG(INFO, TAG, "Exiting occlient main loop...");
342
343     if (OCStop() != OC_STACK_OK)
344     {
345         OC_LOG(ERROR, TAG, "OCStack stop error");
346     }
347
348     return 0;
349 }
350
351 std::string getIPAddrTBServer(OCClientResponse * clientResponse)
352 {
353     if(!clientResponse) return "";
354     if(!clientResponse->addr) return "";
355     uint8_t a, b, c, d = 0;
356     if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
357
358     char ipaddr[16] = {'\0'};
359     // ostringstream not working correctly here, hence snprintf
360     snprintf(ipaddr,  sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d);
361     return std::string (ipaddr);
362 }
363
364
365 std::string getPortTBServer(OCClientResponse * clientResponse)
366 {
367     if(!clientResponse) return "";
368     if(!clientResponse->addr) return "";
369     uint16_t p = 0;
370     if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
371     std::ostringstream ss;
372     ss << p;
373     return ss.str();
374 }
375
376 std::string getQueryStrForGetPut(OCClientResponse * clientResponse)
377 {
378     return "/a/led";
379 }
380
381 void parseClientResponse(OCClientResponse * clientResponse)
382 {
383     coapServerIP = getIPAddrTBServer(clientResponse);
384     coapServerPort = getPortTBServer(clientResponse);
385     coapServerResource = getQueryStrForGetPut(clientResponse);
386 }