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