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