aa45b6c3476e4d1495791375672d01ed5a135e33
[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     ret = OCDoResource(NULL, method, query.str().c_str(), dest,
108             (method == OC_REST_PUT) ? putPayload() : NULL,
109             adapterType, qos, &cbData, options, numOptions);
110
111     if (ret != OC_STACK_OK)
112     {
113         OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
114     }
115
116     return ret;
117 }
118
119 OCStackApplicationResult getReqCB(void* ctx,
120         OCDoHandle /*handle*/, OCClientResponse * clientResponse)
121 {
122     if(clientResponse == NULL)
123     {
124         OIC_LOG(INFO, TAG, "The clientResponse is NULL");
125         return   OC_STACK_DELETE_TRANSACTION;
126     }
127     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
128     {
129         OIC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
130     }
131
132     OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
133     OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
134     OIC_LOG(INFO, TAG, "Get Response =============> ");
135     OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
136
137     if(clientResponse->rcvdVendorSpecificHeaderOptions &&
138             clientResponse->numRcvdVendorSpecificHeaderOptions)
139     {
140         OIC_LOG (INFO, TAG, "Received vendor specific options");
141         uint8_t i = 0;
142         OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
143         for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
144         {
145             if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
146             {
147                 OIC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
148                         ((OCHeaderOption)rcvdOptions[i]).optionID );
149
150                 OIC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
151                     MAX_HEADER_OPTION_DATA_LENGTH);
152             }
153         }
154     }
155     return OC_STACK_DELETE_TRANSACTION;
156 }
157
158 // This is a function called back when a device is discovered
159 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
160         OCClientResponse * clientResponse)
161 {
162     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
163     {
164         OIC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
165     }
166
167     if (clientResponse)
168     {
169         OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
170
171         OIC_LOG_V(INFO, TAG, "Discovered @ %s:%u =============> ",
172             clientResponse->devAddr.addr, clientResponse->devAddr.port);
173         OIC_LOG_PAYLOAD (INFO, clientResponse->payload);
174
175         endpoint = clientResponse->devAddr;
176
177         switch(TestCase)
178         {
179             case TEST_NON_CON_OP:
180                 InitGetRequest(OC_LOW_QOS);
181                 break;
182             case TEST_CON_OP:
183                 InitGetRequest(OC_HIGH_QOS);
184                 break;
185             case TEST_NON_CON_PUT:
186                 InitPutRequest(OC_LOW_QOS);
187                 break;
188             case TEST_CON_PUT:
189                 InitPutRequest(OC_HIGH_QOS);
190                 break;
191             default:
192                 PrintUsage();
193                 break;
194         }
195     }
196
197     return UnicastDiscovery ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
198
199 }
200
201 int InitGetRequest(OCQualityOfService qos)
202 {
203     OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
204     std::ostringstream query;
205     query << coapServerResource;
206     OIC_LOG_V (INFO, TAG, "Performing GET with query : %s", query.str().c_str());
207     return (InvokeOCDoResource(query, OC_REST_GET, &endpoint,
208                                (qos == OC_HIGH_QOS)? OC_HIGH_QOS : OC_LOW_QOS,
209                                getReqCB, NULL, 0));
210 }
211
212 int InitPutRequest(OCQualityOfService qos)
213 {
214     OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
215     std::ostringstream query;
216     query << coapServerResource;
217     OIC_LOG_V (INFO, TAG, "Performing PUT with query : %s", query.str().c_str());
218     return (InvokeOCDoResource(query, OC_REST_PUT, &endpoint,
219                                (qos == OC_HIGH_QOS)?  OC_HIGH_QOS:OC_LOW_QOS,
220                                getReqCB, NULL, 0));
221 }
222
223 int InitDiscovery()
224 {
225     OCStackResult ret;
226     OCCallbackData cbData;
227     char queryUri[200];
228     char ipaddr[100] = { '\0' };
229
230     if (UnicastDiscovery)
231     {
232         OIC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
233         OIC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
234         OIC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
235
236         if (fgets(ipaddr, sizeof (ipaddr), stdin))
237         {
238             StripNewLineChar(ipaddr); //Strip newline char from ipaddr
239         }
240         else
241         {
242             OIC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
243             return OC_STACK_INVALID_PARAM;
244         }
245     }
246
247     snprintf(queryUri, sizeof (queryUri), RESOURCE_DISCOVERY_QUERY, ipaddr);
248
249     cbData.cb = discoveryReqCB;
250     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
251     cbData.cd = NULL;
252
253     ret = OCDoResource(NULL, OC_REST_DISCOVER, queryUri, 0, 0, CT_DEFAULT,
254                        OC_LOW_QOS, &cbData, NULL, 0);
255     if (ret != OC_STACK_OK)
256     {
257         OIC_LOG(ERROR, TAG, "OCStack resource error");
258     }
259     return ret;
260 }
261
262 int main(int argc, char* argv[])
263 {
264     int opt;
265
266     while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
267     {
268         switch(opt)
269         {
270             case 'u':
271                 UnicastDiscovery = atoi(optarg);
272                 break;
273             case 't':
274                 TestCase = atoi(optarg);
275                 break;
276             case 'c':
277                 ConnectivityType = atoi(optarg);
278                 break;
279             default:
280                 PrintUsage();
281                 return -1;
282         }
283     }
284
285     if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||
286             (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS) ||
287             (ConnectivityType < CT_ADAPTER_DEFAULT || ConnectivityType >= MAX_CT))
288     {
289         PrintUsage();
290         return -1;
291     }
292
293     /* Initialize OCStack*/
294     if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
295     {
296         OIC_LOG(ERROR, TAG, "OCStack init error");
297         return 0;
298     }
299
300     if(ConnectivityType == CT_ADAPTER_DEFAULT || ConnectivityType == CT_IP)
301     {
302         adapterType = CT_ADAPTER_IP;
303     }
304     else
305     {
306         OIC_LOG(INFO, TAG, "Default Connectivity type selected...");
307         adapterType = CT_ADAPTER_IP;
308     }
309
310     InitDiscovery();
311
312     // Break from loop with Ctrl+C
313     OIC_LOG(INFO, TAG, "Entering occlient main loop...");
314     signal(SIGINT, handleSigInt);
315     while (!gQuitFlag)
316     {
317         if (OCProcess() != OC_STACK_OK)
318         {
319             OIC_LOG(ERROR, TAG, "OCStack process error");
320             return 0;
321         }
322
323         sleep(2);
324     }
325     OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
326
327     if (OCStop() != OC_STACK_OK)
328     {
329         OIC_LOG(ERROR, TAG, "OCStack stop error");
330     }
331
332     return 0;
333 }
334
335 std::string getQueryStrForGetPut(OCClientResponse * /*clientResponse*/)
336 {
337     return "/a/led";
338 }
339