Imported Upstream version 0.9.1
[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/oc/core";
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 = "/oc/core";
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     uint8_t remoteIpAddr[4];
133     uint16_t remotePortNu;
134
135     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
136     {
137         OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
138     }
139
140     if (clientResponse)
141     {
142         OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
143
144         OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
145                 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
146         OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
147
148         OC_LOG_V(INFO, TAG,
149                 "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
150                 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
151                 remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
152
153         parseClientResponse(clientResponse);
154
155         switch(TEST_CASE)
156         {
157             case TEST_NON_CON_OP:
158                 InitGetRequest(OC_LOW_QOS);
159                 break;
160             case TEST_CON_OP:
161                 InitGetRequest(OC_HIGH_QOS);
162                 break;
163             default:
164                 PrintUsage();
165                 break;
166         }
167     }
168
169     return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
170
171 }
172
173 int InitGetRequest(OCQualityOfService qos)
174 {
175     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
176     std::ostringstream query;
177     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
178
179     return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
180             OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
181 }
182
183 int InitDiscovery()
184 {
185     OCStackResult ret;
186     OCCallbackData cbData;
187     /* Start a discovery query*/
188     char szQueryUri[64] = { 0 };
189     if (UNICAST_DISCOVERY)
190     {
191         char ipv4addr[IPV4_ADDR_SIZE];
192         printf("Enter IPv4 address of the Server hosting resource (Ex: 192.168.0.15)\n");
193         if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
194         {
195             //Strip newline char from ipv4addr
196             StripNewLineChar(ipv4addr);
197             snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
198         }
199         else
200         {
201             OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
202             return OC_STACK_INVALID_PARAM;
203         }
204     }
205     else
206     {
207         strcpy(szQueryUri, MULTICAST_RESOURCE_DISCOVERY_QUERY);
208     }
209     cbData.cb = discoveryReqCB;
210     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
211     cbData.cd = NULL;
212     if(UNICAST_DISCOVERY)
213     {
214         ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
215                 OC_LOW_QOS, &cbData, NULL, 0);
216     }
217     else
218     {
219         ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_ALL,
220                 OC_LOW_QOS, &cbData, NULL, 0);
221     }
222     if (ret != OC_STACK_OK)
223     {
224         OC_LOG(ERROR, TAG, "OCStack resource error");
225     }
226     return ret;
227 }
228
229 int main(int argc, char* argv[])
230 {
231     int opt;
232
233     while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
234     {
235         switch(opt)
236         {
237             case 'u':
238                 UNICAST_DISCOVERY = atoi(optarg);
239                 break;
240             case 't':
241                 TEST_CASE = atoi(optarg);
242                 break;
243             case 'c':
244                 // TODO: re-enable IPv4/IPv6 command line selection when IPv6 is supported
245                 // OC_CONNTYPE = OCConnectivityType(atoi(optarg));
246                 OC_CONNTYPE = OC_IPV4;
247                 break;
248             default:
249                 PrintUsage();
250                 return -1;
251         }
252     }
253
254     if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
255             (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
256     {
257         PrintUsage();
258         return -1;
259     }
260
261     /* Initialize OCStack*/
262     if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
263     {
264         OC_LOG(ERROR, TAG, "OCStack init error");
265         return 0;
266     }
267
268     InitDiscovery();
269
270     // Break from loop with Ctrl+C
271     OC_LOG(INFO, TAG, "Entering occlient main loop...");
272     signal(SIGINT, handleSigInt);
273     while (!gQuitFlag)
274     {
275         if (OCProcess() != OC_STACK_OK)
276         {
277             OC_LOG(ERROR, TAG, "OCStack process error");
278             return 0;
279         }
280
281         sleep(2);
282     }
283     OC_LOG(INFO, TAG, "Exiting occlient main loop...");
284
285     if (OCStop() != OC_STACK_OK)
286     {
287         OC_LOG(ERROR, TAG, "OCStack stop error");
288     }
289
290     return 0;
291 }
292
293 std::string getIPAddrTBServer(OCClientResponse * clientResponse)
294 {
295     if(!clientResponse) return "";
296     if(!clientResponse->addr) return "";
297     uint8_t a, b, c, d = 0;
298     if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
299
300     char ipaddr[16] = {'\0'};
301     // ostringstream not working correctly here, hence snprintf
302     snprintf(ipaddr,  sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d);
303     return std::string (ipaddr);
304 }
305
306 std::string getPortTBServer(OCClientResponse * clientResponse)
307 {
308     if(!clientResponse) return "";
309     if(!clientResponse->addr) return "";
310     uint16_t p = 0;
311     if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
312     std::ostringstream ss;
313     ss << p;
314     return ss.str();
315 }
316
317 std::string getQueryStrForGetPut(OCClientResponse * clientResponse)
318 {
319     return "/a/led";
320 }
321
322 void parseClientResponse(OCClientResponse * clientResponse)
323 {
324     coapServerIP = getIPAddrTBServer(clientResponse);
325     coapServerPort = getPortTBServer(clientResponse);
326     coapServerResource = getQueryStrForGetPut(clientResponse);
327 }
328