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