Merge branch 'security-CKM' into 'master'
[platform/upstream/iotivity.git] / resource / csdk / stack / samples / linux / SimpleClientServer / occlientslow.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 "occlientslow.h"
31 #include "oic_string.h"
32 #include "ocpayload.h"
33 #include "payload_logging.h"
34
35 // Tracking user input
36 static int UnicastDiscovery = 0;
37 static int TestCase = 0;
38 static int ConnectivityType = 0;
39
40 static std::string coapServerResource = "/a/led";
41
42 //The following variable determines the interface protocol (IP, etc)
43 //to be used for sending unicast messages. Default set to IP.
44 static OCConnectivityType AdapterType = CT_ADAPTER_IP;
45 static OCDevAddr endpoint;
46 static const char *RESOURCE_DISCOVERY_QUERY = "%s/oic/res";
47 void StripNewLineChar(char* str);
48
49 int gQuitFlag = 0;
50
51 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
52 void handleSigInt(int signum)
53 {
54     if (signum == SIGINT)
55     {
56         gQuitFlag = 1;
57     }
58 }
59
60 static void PrintUsage()
61 {
62     OC_LOG(INFO, TAG, "Usage : occlient -c <0|1> -u <0|1> -t <1|2|3>");
63     OC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
64     OC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
65     OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
66     OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
67     OC_LOG(INFO, TAG, "-t 2 : Discover Resources and Initiate Nonconfirmable Get Request");
68     OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get Request");
69     OC_LOG(INFO, TAG, "-t 4 : Discover Resources and Initiate NonConfirmable Put Request");
70     OC_LOG(INFO, TAG, "-t 5 : Discover Resources and Initiate Confirmable Put Request");
71 }
72
73 OCPayload* putPayload()
74 {
75     OCRepPayload* payload = OCRepPayloadCreate();
76
77     if(!payload)
78     {
79         std::cout << "Failed to create put payload object"<<std::endl;
80         std::exit(1);
81     }
82
83     OCRepPayloadSetPropInt(payload, "power", 15);
84     OCRepPayloadSetPropBool(payload, "state", true);
85
86     return (OCPayload*) payload;
87 }
88
89 OCStackResult InvokeOCDoResource(std::ostringstream &query,
90         OCMethod method, OCDevAddr *dest, OCQualityOfService qos,
91         OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
92 {
93     OCStackResult ret;
94     OCCallbackData cbData;
95
96     cbData.cb = cb;
97     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
98     cbData.cd = NULL;
99
100     ret = OCDoResource(NULL, method, query.str().c_str(), dest,
101             (method == OC_REST_PUT) ? putPayload() : NULL,
102             AdapterType, qos, &cbData, options, numOptions);
103
104     if (ret != OC_STACK_OK)
105     {
106         OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
107     }
108
109     return ret;
110 }
111
112 OCStackApplicationResult getReqCB(void* ctx,
113         OCDoHandle /*handle*/, OCClientResponse * clientResponse)
114 {
115     if(clientResponse == NULL)
116     {
117         OC_LOG(INFO, TAG, "The clientResponse is NULL");
118         return   OC_STACK_DELETE_TRANSACTION;
119     }
120     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
121     {
122         OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
123     }
124
125     OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
126     OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
127     OC_LOG(INFO, TAG, "Get Response =============> ");
128     OC_LOG_PAYLOAD(INFO, clientResponse->payload);
129
130     if(clientResponse->rcvdVendorSpecificHeaderOptions &&
131             clientResponse->numRcvdVendorSpecificHeaderOptions)
132     {
133         OC_LOG (INFO, TAG, "Received vendor specific options");
134         uint8_t i = 0;
135         OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
136         for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
137         {
138             if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
139             {
140                 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
141                         ((OCHeaderOption)rcvdOptions[i]).optionID );
142
143                 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
144                     MAX_HEADER_OPTION_DATA_LENGTH);
145             }
146         }
147     }
148     return OC_STACK_DELETE_TRANSACTION;
149 }
150
151 // This is a function called back when a device is discovered
152 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
153         OCClientResponse * clientResponse)
154 {
155     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
156     {
157         OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
158     }
159
160     if (clientResponse)
161     {
162         OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
163
164         OC_LOG_V(INFO, TAG, "Discovered @ %s:%u =============> ",
165             clientResponse->devAddr.addr, clientResponse->devAddr.port);
166         OC_LOG_PAYLOAD (INFO, clientResponse->payload);
167
168         endpoint = clientResponse->devAddr;
169
170         switch(TestCase)
171         {
172             case TEST_NON_CON_OP:
173                 InitGetRequest(OC_LOW_QOS);
174                 break;
175             case TEST_CON_OP:
176                 InitGetRequest(OC_HIGH_QOS);
177                 break;
178             case TEST_NON_CON_PUT:
179                 InitPutRequest(OC_LOW_QOS);
180                 break;
181             case TEST_CON_PUT:
182                 InitPutRequest(OC_HIGH_QOS);
183                 break;
184             default:
185                 PrintUsage();
186                 break;
187         }
188     }
189
190     return UnicastDiscovery ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
191
192 }
193
194 int InitGetRequest(OCQualityOfService qos)
195 {
196     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
197     std::ostringstream query;
198     query << coapServerResource;
199     OC_LOG_V (INFO, TAG, "Performing GET with query : %s", query.str().c_str());
200     return (InvokeOCDoResource(query, OC_REST_GET, &endpoint,
201                                (qos == OC_HIGH_QOS)? OC_HIGH_QOS : OC_LOW_QOS,
202                                getReqCB, NULL, 0));
203 }
204
205 int InitPutRequest(OCQualityOfService qos)
206 {
207     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
208     std::ostringstream query;
209     query << coapServerResource;
210     OC_LOG_V (INFO, TAG, "Performing PUT with query : %s", query.str().c_str());
211     return (InvokeOCDoResource(query, OC_REST_PUT, &endpoint,
212                                (qos == OC_HIGH_QOS)?  OC_HIGH_QOS:OC_LOW_QOS,
213                                getReqCB, NULL, 0));
214 }
215
216 int InitDiscovery()
217 {
218     OCStackResult ret;
219     OCCallbackData cbData;
220     char queryUri[200];
221     char ipaddr[100] = { '\0' };
222
223     if (UnicastDiscovery)
224     {
225         OC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
226         OC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
227         OC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
228
229         if (fgets(ipaddr, sizeof (ipaddr), stdin))
230         {
231             StripNewLineChar(ipaddr); //Strip newline char from ipaddr
232         }
233         else
234         {
235             OC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
236             return OC_STACK_INVALID_PARAM;
237         }
238     }
239
240     snprintf(queryUri, sizeof (queryUri), RESOURCE_DISCOVERY_QUERY, ipaddr);
241
242     cbData.cb = discoveryReqCB;
243     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
244     cbData.cd = NULL;
245
246     ret = OCDoResource(NULL, OC_REST_DISCOVER, queryUri, 0, 0, CT_DEFAULT,
247                        OC_LOW_QOS, &cbData, NULL, 0);
248     if (ret != OC_STACK_OK)
249     {
250         OC_LOG(ERROR, TAG, "OCStack resource error");
251     }
252     return ret;
253 }
254
255 int main(int argc, char* argv[])
256 {
257     int opt;
258
259     while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
260     {
261         switch(opt)
262         {
263             case 'u':
264                 UnicastDiscovery = atoi(optarg);
265                 break;
266             case 't':
267                 TestCase = atoi(optarg);
268                 break;
269             case 'c':
270                 ConnectivityType = atoi(optarg);
271                 break;
272             default:
273                 PrintUsage();
274                 return -1;
275         }
276     }
277
278     if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||
279             (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS) ||
280             (ConnectivityType < CT_ADAPTER_DEFAULT || ConnectivityType >= MAX_CT))
281     {
282         PrintUsage();
283         return -1;
284     }
285
286     /* Initialize OCStack*/
287     if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
288     {
289         OC_LOG(ERROR, TAG, "OCStack init error");
290         return 0;
291     }
292
293     if(ConnectivityType == CT_ADAPTER_DEFAULT || ConnectivityType == CT_IP)
294     {
295         AdapterType = CT_ADAPTER_IP;
296     }
297     else
298     {
299         OC_LOG(INFO, TAG, "Default Connectivity type selected...");
300         AdapterType = CT_ADAPTER_IP;
301     }
302
303     InitDiscovery();
304
305     // Break from loop with Ctrl+C
306     OC_LOG(INFO, TAG, "Entering occlient main loop...");
307     signal(SIGINT, handleSigInt);
308     while (!gQuitFlag)
309     {
310         if (OCProcess() != OC_STACK_OK)
311         {
312             OC_LOG(ERROR, TAG, "OCStack process error");
313             return 0;
314         }
315
316         sleep(2);
317     }
318     OC_LOG(INFO, TAG, "Exiting occlient main loop...");
319
320     if (OCStop() != OC_STACK_OK)
321     {
322         OC_LOG(ERROR, TAG, "OCStack stop error");
323     }
324
325     return 0;
326 }
327
328 std::string getQueryStrForGetPut(OCClientResponse * /*clientResponse*/)
329 {
330     return "/a/led";
331 }
332