Merge branch 'master' into resource-manipulation
[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
32 // Tracking user input
33 static int UNICAST_DISCOVERY = 0;
34 static int TEST_CASE = 0;
35 static int CONNECTIVITY = 0;
36
37 static const char * UNICAST_DISCOVERY_QUERY = "coap://%s:6298/oic/res";
38 static std::string putPayload = "{\"state\":\"off\",\"power\":10}";
39 static std::string coapServerIP = "255.255.255.255";
40 static std::string 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 = 16;
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 IPv4 and IPv6 auto-selection");
65     OC_LOG(INFO, TAG, "-c 1 : IPv4 Connectivity Type");
66     OC_LOG(INFO, TAG, "-c 2 : IPv6 Connectivity Type (IPv6 not currently supported)");
67     OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
68     OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
69     OC_LOG(INFO, TAG, "-t 2 : Discover Resources and Initiate Nonconfirmable Get Request");
70     OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get Request");
71 }
72
73 OCStackResult InvokeOCDoResource(std::ostringstream &query,
74         OCMethod method, OCQualityOfService qos,
75         OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
76 {
77     OCStackResult ret;
78     OCCallbackData cbData;
79
80     cbData.cb = cb;
81     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
82     cbData.cd = NULL;
83
84     ret = OCDoResource(NULL, method, query.str().c_str(), 0,
85             NULL, OC_CONNTYPE, qos, &cbData, options, numOptions);
86
87     if (ret != OC_STACK_OK)
88     {
89         OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
90     }
91
92     return ret;
93 }
94
95 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
96 {
97     if(clientResponse == NULL)
98     {
99         OC_LOG(INFO, TAG, "The clientResponse is NULL");
100         return   OC_STACK_DELETE_TRANSACTION;
101     }
102     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
103     {
104         OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
105     }
106
107     OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
108     OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
109     OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response",
110             clientResponse->resJSONPayload);
111
112     if(clientResponse->rcvdVendorSpecificHeaderOptions &&
113             clientResponse->numRcvdVendorSpecificHeaderOptions)
114     {
115         OC_LOG (INFO, TAG, "Received vendor specific options");
116         uint8_t i = 0;
117         OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
118         for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
119         {
120             if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
121             {
122                 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
123                         ((OCHeaderOption)rcvdOptions[i]).optionID );
124
125                 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
126                     MAX_HEADER_OPTION_DATA_LENGTH);
127             }
128         }
129     }
130     return OC_STACK_DELETE_TRANSACTION;
131 }
132
133 // This is a function called back when a device is discovered
134 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
135         OCClientResponse * clientResponse)
136 {
137     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
138     {
139         OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
140     }
141
142     if (clientResponse)
143     {
144         OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
145
146         OC_LOG_V(INFO, TAG,
147                 "Device =============> Discovered %s @ %s:%d",
148                 clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
149
150         parseClientResponse(clientResponse);
151
152         switch(TEST_CASE)
153         {
154             case TEST_NON_CON_OP:
155                 InitGetRequest(OC_LOW_QOS);
156                 break;
157             case TEST_CON_OP:
158                 InitGetRequest(OC_HIGH_QOS);
159                 break;
160             default:
161                 PrintUsage();
162                 break;
163         }
164     }
165
166     return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
167
168 }
169
170 int InitGetRequest(OCQualityOfService qos)
171 {
172     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
173     std::ostringstream query;
174     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
175
176     return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
177             OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
178 }
179
180 int InitDiscovery()
181 {
182     OCStackResult ret;
183     OCCallbackData cbData;
184     /* Start a discovery query*/
185     char szQueryUri[64] = { 0 };
186     if (UNICAST_DISCOVERY)
187     {
188         char ipv4addr[IPV4_ADDR_SIZE];
189         OC_LOG(INFO, TAG, "Enter IPv4 address of the Server hosting resource (Ex: 192.168.0.15)");
190         if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
191         {
192             //Strip newline char from ipv4addr
193             StripNewLineChar(ipv4addr);
194             snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
195         }
196         else
197         {
198             OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
199             return OC_STACK_INVALID_PARAM;
200         }
201     }
202     else
203     {
204         strcpy(szQueryUri, MULTICAST_RESOURCE_DISCOVERY_QUERY);
205     }
206     cbData.cb = discoveryReqCB;
207     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
208     cbData.cd = NULL;
209     if(UNICAST_DISCOVERY)
210     {
211         ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
212                 OC_LOW_QOS, &cbData, NULL, 0);
213     }
214     else
215     {
216         ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, CT_DEFAULT,
217                 OC_LOW_QOS, &cbData, NULL, 0);
218     }
219     if (ret != OC_STACK_OK)
220     {
221         OC_LOG(ERROR, TAG, "OCStack resource error");
222     }
223     return ret;
224 }
225
226 int main(int argc, char* argv[])
227 {
228     int opt;
229
230     while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
231     {
232         switch(opt)
233         {
234             case 'u':
235                 UNICAST_DISCOVERY = atoi(optarg);
236                 break;
237             case 't':
238                 TEST_CASE = atoi(optarg);
239                 break;
240             case 'c':
241                 CONNECTIVITY = atoi(optarg);
242                 break;
243             default:
244                 PrintUsage();
245                 return -1;
246         }
247     }
248
249     if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
250             (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) ||
251             (CONNECTIVITY < CT_ADAPTER_DEFAULT || CONNECTIVITY >= MAX_CT))
252     {
253         PrintUsage();
254         return -1;
255     }
256
257     /* Initialize OCStack*/
258     if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
259     {
260         OC_LOG(ERROR, TAG, "OCStack init error");
261         return 0;
262     }
263
264     if(CONNECTIVITY == CT_ADAPTER_DEFAULT)
265     {
266         OC_CONNTYPE = CT_ADAPTER_IP;
267     }
268     else if(CONNECTIVITY == CT_IPV4)
269     {
270         OC_CONNTYPE = CT_IP_USE_V4;
271     }
272     else if(CONNECTIVITY == CT_IPV6)
273     {
274         OC_CONNTYPE = CT_IP_USE_V6;
275
276         //TODO: Remove when IPv6 is available.
277         OC_LOG(INFO, TAG, "Ipv6 is currently not supported...");
278         PrintUsage();
279         return -1;
280     }
281     else
282     {
283         OC_LOG(INFO, TAG, "Default Connectivity type selected...");
284         OC_CONNTYPE = CT_ADAPTER_IP;
285     }
286
287     InitDiscovery();
288
289     // Break from loop with Ctrl+C
290     OC_LOG(INFO, TAG, "Entering occlient main loop...");
291     signal(SIGINT, handleSigInt);
292     while (!gQuitFlag)
293     {
294         if (OCProcess() != OC_STACK_OK)
295         {
296             OC_LOG(ERROR, TAG, "OCStack process error");
297             return 0;
298         }
299
300         sleep(2);
301     }
302     OC_LOG(INFO, TAG, "Exiting occlient main loop...");
303
304     if (OCStop() != OC_STACK_OK)
305     {
306         OC_LOG(ERROR, TAG, "OCStack stop error");
307     }
308
309     return 0;
310 }
311
312 std::string getQueryStrForGetPut(OCClientResponse * clientResponse)
313 {
314     return "/a/led";
315 }
316
317 void parseClientResponse(OCClientResponse * clientResponse)
318 {
319     coapServerIP = clientResponse->devAddr.addr;
320     coapServerPort = clientResponse->devAddr.port;
321     coapServerResource = getQueryStrForGetPut(clientResponse);
322 }
323