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