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