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