Imported Upstream version 0.9.2
[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 "ocpayload.h"
32
33 // Tracking user input
34 static int UNICAST_DISCOVERY = 0;
35 static int TEST_CASE = 0;
36 static int CONNECTIVITY = 0;
37
38 static const char * UNICAST_DISCOVERY_QUERY = "coap://%s/oic/res";
39 static std::string coapServerIP = "255.255.255.255";
40 static uint16_t coapServerPort = 5683;
41 static std::string coapServerResource = "/a/led";
42
43 //The following variable determines the interface protocol (IP, etc)
44 //to be used for sending unicast messages. Default set to IP.
45 static OCConnectivityType OC_CONNTYPE = CT_ADAPTER_IP;
46 static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oic/res";
47 static int IPV4_ADDR_SIZE = 24;
48 void StripNewLineChar(char* str);
49
50 int gQuitFlag = 0;
51
52 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
53 void handleSigInt(int signum)
54 {
55     if (signum == SIGINT)
56     {
57         gQuitFlag = 1;
58     }
59 }
60
61 static void PrintUsage()
62 {
63     OC_LOG(INFO, TAG, "Usage : occlient -c <0|1|2> -u <0|1> -t <1|2|3>");
64     OC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
65     OC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
66     OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
67     OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
68     OC_LOG(INFO, TAG, "-t 2 : Discover Resources and Initiate Nonconfirmable Get Request");
69     OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get Request");
70     OC_LOG(INFO, TAG, "-t 4 : Discover Resources and Initiate NonConfirmable Put Request");
71     OC_LOG(INFO, TAG, "-t 5 : Discover Resources and Initiate Confirmable Put Request");
72 }
73
74 OCPayload* putPayload()
75 {
76     OCRepPayload* payload = OCRepPayloadCreate();
77
78     if(!payload)
79     {
80         std::cout << "Failed to create put payload object"<<std::endl;
81         std::exit(1);
82     }
83
84     OCRepPayloadSetPropInt(payload, "power", 15);
85     OCRepPayloadSetPropBool(payload, "state", true);
86
87     return (OCPayload*) payload;
88 }
89
90 OCStackResult InvokeOCDoResource(std::ostringstream &query,
91         OCMethod method, OCQualityOfService qos,
92         OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
93 {
94     OCStackResult ret;
95     OCCallbackData cbData;
96
97     cbData.cb = cb;
98     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
99     cbData.cd = NULL;
100
101     ret = OCDoResource(NULL, method, query.str().c_str(), 0,
102             (method == OC_REST_PUT) ? putPayload() : NULL,
103             OC_CONNTYPE, qos, &cbData, options, numOptions);
104
105     if (ret != OC_STACK_OK)
106     {
107         OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
108     }
109
110     return ret;
111 }
112
113 OCStackApplicationResult getReqCB(void* ctx, 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, TAG, 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, TAG, clientResponse->payload);
167
168         parseClientResponse(clientResponse);
169
170         switch(TEST_CASE)
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 (UNICAST_DISCOVERY) ? 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 << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
199     OC_LOG_V (INFO, TAG, "Performing GET with query : %s", query.str().c_str());
200     return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
201             OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
202 }
203
204 int InitPutRequest(OCQualityOfService qos)
205 {
206     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
207     std::ostringstream query;
208     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
209     OC_LOG_V (INFO, TAG, "Performing PUT with query : %s", query.str().c_str());
210     return (InvokeOCDoResource(query, OC_REST_PUT, (qos == OC_HIGH_QOS)?
211             OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
212 }
213
214 int InitDiscovery()
215 {
216     OCStackResult ret;
217     OCCallbackData cbData;
218     /* Start a discovery query*/
219     char szQueryUri[64] = { 0 };
220     if (UNICAST_DISCOVERY)
221     {
222         char ipv4addr[IPV4_ADDR_SIZE];
223         OC_LOG(INFO, TAG, "Enter IPv4:port of the Server hosting resource"\
224                 "(Ex: 192.168.0.15:1234)");
225         if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
226         {
227             //Strip newline char from ipv4addr
228             StripNewLineChar(ipv4addr);
229             snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
230         }
231         else
232         {
233             OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
234             return OC_STACK_INVALID_PARAM;
235         }
236     }
237     else
238     {
239         strcpy(szQueryUri, MULTICAST_RESOURCE_DISCOVERY_QUERY);
240     }
241     cbData.cb = discoveryReqCB;
242     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
243     cbData.cd = NULL;
244     if(UNICAST_DISCOVERY)
245     {
246         ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
247                 OC_LOW_QOS, &cbData, NULL, 0);
248     }
249     else
250     {
251         ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, CT_DEFAULT,
252                 OC_LOW_QOS, &cbData, NULL, 0);
253     }
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     int opt;
264
265     while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
266     {
267         switch(opt)
268         {
269             case 'u':
270                 UNICAST_DISCOVERY = atoi(optarg);
271                 break;
272             case 't':
273                 TEST_CASE = atoi(optarg);
274                 break;
275             case 'c':
276                 CONNECTIVITY = atoi(optarg);
277                 break;
278             default:
279                 PrintUsage();
280                 return -1;
281         }
282     }
283
284     if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
285             (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) ||
286             (CONNECTIVITY < CT_ADAPTER_DEFAULT || CONNECTIVITY >= 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         OC_LOG(ERROR, TAG, "OCStack init error");
296         return 0;
297     }
298
299     if(CONNECTIVITY == CT_ADAPTER_DEFAULT || CONNECTIVITY == CT_IP)
300     {
301         OC_CONNTYPE = CT_ADAPTER_IP;
302     }
303     else
304     {
305         OC_LOG(INFO, TAG, "Default Connectivity type selected...");
306         OC_CONNTYPE = CT_ADAPTER_IP;
307     }
308
309     InitDiscovery();
310
311     // Break from loop with Ctrl+C
312     OC_LOG(INFO, TAG, "Entering occlient main loop...");
313     signal(SIGINT, handleSigInt);
314     while (!gQuitFlag)
315     {
316         if (OCProcess() != OC_STACK_OK)
317         {
318             OC_LOG(ERROR, TAG, "OCStack process error");
319             return 0;
320         }
321
322         sleep(2);
323     }
324     OC_LOG(INFO, TAG, "Exiting occlient main loop...");
325
326     if (OCStop() != OC_STACK_OK)
327     {
328         OC_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
339 void parseClientResponse(OCClientResponse * clientResponse)
340 {
341     coapServerIP = clientResponse->devAddr.addr;
342     coapServerPort = clientResponse->devAddr.port;
343     coapServerResource = getQueryStrForGetPut(clientResponse);
344 }
345