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