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