Merge "Map QoS to the right Connectivity Abstraction message type" into connectivity...
[platform/upstream/iotivity.git] / resource / csdk / stack / samples / linux / SimpleClientServer / occlientbasicops.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 //      http://www.apache.org/licenses/LICENSE-2.0
11 //
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
17 //
18 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <signal.h>
24 #include <unistd.h>
25
26 #include <set>
27 #include <string>
28 #include <sstream>
29 #include <iostream>
30 #include <algorithm>
31
32 #include "ocstack.h"
33 #include "logger.h"
34 #include "occlientbasicops.h"
35
36 static int UNICAST_DISCOVERY = 0;
37 static int TEST_CASE = 0;
38
39 static const char * TEST_APP_UNICAST_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core";
40
41 static std::string putPayload = "{\"state\":\"off\",\"power\":10}";
42
43 static std::string coapServerIP = "255.255.255.255";
44 static std::string coapServerPort = "5683";
45 static std::string coapServerResource = "/a/led";
46
47 #ifdef CA_INT
48 //The following variable determines the interface (wifi, ethernet etc.)
49 //to be used for sending unicast messages. Default set to WIFI.
50 static OCConnectivityType CA_CONNTYPE = OC_WIFI;
51 static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oc/core";
52 #endif
53
54 int gQuitFlag = 0;
55
56 namespace {
57     typedef std::pair<bool, std::string>    extract_result_t;
58     typedef std::string                     sid_t;
59     typedef std::set<std::string>           SID_set_t;
60 } // namespace
61
62 void collateSIDs(const OCClientResponse * clientResponse, const std::string& server_ip);
63
64 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
65 void handleSigInt(int signum)
66 {
67     if (signum == SIGINT)
68     {
69         gQuitFlag = 1;
70     }
71 }
72
73 static void PrintUsage()
74 {
75 #ifdef CA_INT
76     OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
77 #else
78     OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3>");
79 #endif
80     OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
81 #ifdef CA_INT
82     OC_LOG(INFO, TAG, "-c <0|1> : Send unicast messages over Ethernet or WIFI");
83 #endif
84     OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
85     OC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
86             " Initiate Nonconfirmable Get/Put/Post Requests");
87     OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
88 }
89
90 OCStackResult InvokeOCDoResource(std::ostringstream &query,
91         OCMethod method, OCQualityOfService qos,
92         OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
93 {
94     OCStackResult ret;
95     OCCallbackData cbData;
96     OCDoHandle handle;
97
98     cbData.cb = cb;
99     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
100     cbData.cd = NULL;
101
102 #ifdef CA_INT
103     ret = OCDoResource(&handle, method, query.str().c_str(), 0,
104             (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL,
105             CA_CONNTYPE, qos, &cbData, options, numOptions);
106 #else
107     ret = OCDoResource(&handle, method, query.str().c_str(), 0,
108             (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL,
109             qos, &cbData, options, numOptions);
110 #endif
111
112     if (ret != OC_STACK_OK)
113     {
114         OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
115     }
116
117     return ret;
118 }
119
120 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
121 {
122     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
123     {
124         OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
125     }
126
127     if(clientResponse)
128     {
129         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
130         OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response", clientResponse->resJSONPayload);
131     }
132     return OC_STACK_DELETE_TRANSACTION;
133 }
134
135 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
136 {
137     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
138     {
139         OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
140     }
141
142     if(clientResponse)
143     {
144         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
145         OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response",
146                 clientResponse->resJSONPayload);
147     }
148     return OC_STACK_DELETE_TRANSACTION;
149 }
150
151 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
152 {
153     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
154     {
155         OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
156     }
157
158     if(clientResponse)
159     {
160         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
161         OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
162         OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response",
163                 clientResponse->resJSONPayload);
164     }
165     if(clientResponse->rcvdVendorSpecificHeaderOptions &&
166             clientResponse->numRcvdVendorSpecificHeaderOptions)
167     {
168         OC_LOG (INFO, TAG, "Received vendor specific options");
169         uint8_t i = 0;
170         OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
171         for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
172         {
173             if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
174             {
175                 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
176                         ((OCHeaderOption)rcvdOptions[i]).optionID );
177                 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
178                         ((OCHeaderOption)rcvdOptions[i]).optionLength);
179             }
180         }
181     }
182     return OC_STACK_DELETE_TRANSACTION;
183 }
184
185 // This is a function called back when a device is discovered
186 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
187         OCClientResponse * clientResponse)
188 {
189     uint8_t remoteIpAddr[4];
190     uint16_t remotePortNu;
191
192     if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
193     {
194         OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
195     }
196
197     if (clientResponse)
198     {
199         OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
200
201         OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
202                 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
203         OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
204
205         OC_LOG_V(INFO, TAG,
206                 "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
207                 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
208                 remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
209
210         parseClientResponse(clientResponse);
211
212         collateSIDs(clientResponse, getIPAddrTBServer(clientResponse));
213
214         switch(TEST_CASE)
215         {
216             case TEST_NON_CON_OP:
217                 InitGetRequest(OC_LOW_QOS);
218                 InitPutRequest();
219                 InitPostRequest(OC_LOW_QOS);
220                 break;
221             case TEST_CON_OP:
222                 InitGetRequest(OC_HIGH_QOS);
223                 InitPutRequest();
224                 InitPostRequest(OC_HIGH_QOS);
225                 break;
226             default:
227                 PrintUsage();
228                 break;
229         }
230     }
231
232     return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
233 }
234
235 int InitPutRequest()
236 {
237     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
238     std::ostringstream query;
239     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
240     return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0));
241 }
242
243 int InitPostRequest(OCQualityOfService qos)
244 {
245     OCStackResult result;
246     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
247     std::ostringstream query;
248     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
249
250     // First POST operation (to create an LED instance)
251     result = InvokeOCDoResource(query, OC_REST_POST,
252             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
253             postReqCB, NULL, 0);
254     if (OC_STACK_OK != result)
255     {
256         // Error can happen if for example, network connectivity is down
257         OC_LOG(INFO, TAG, "First POST call did not succeed");
258     }
259
260     // Second POST operation (to create an LED instance)
261     result = InvokeOCDoResource(query, OC_REST_POST,
262             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
263             postReqCB, NULL, 0);
264     if (OC_STACK_OK != result)
265     {
266         OC_LOG(INFO, TAG, "Second POST call did not succeed");
267     }
268
269     // This POST operation will update the original resourced /a/led
270     return (InvokeOCDoResource(query, OC_REST_POST,
271                 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
272                 postReqCB, NULL, 0));
273 }
274
275 int InitGetRequest(OCQualityOfService qos)
276 {
277     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
278     std::ostringstream query;
279     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
280
281     return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
282             OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
283 }
284
285 int InitDiscovery()
286 {
287     OCStackResult ret;
288     OCCallbackData cbData;
289     OCDoHandle handle;
290     /* Start a discovery query*/
291     char szQueryUri[64] = { 0 };
292     if (UNICAST_DISCOVERY)
293     {
294         strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY);
295     }
296     else
297     {
298 #ifdef CA_INT
299         strcpy(szQueryUri, MULTICAST_RESOURCE_DISCOVERY_QUERY);
300 #else
301         strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
302 #endif
303     }
304     cbData.cb = discoveryReqCB;
305     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
306     cbData.cd = NULL;
307 #ifdef CA_INT
308     if (UNICAST_DISCOVERY)
309     {
310         ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, (CA_CONNTYPE),
311                 OC_LOW_QOS, &cbData, NULL, 0);
312     }
313     else
314     {
315         ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, (OC_ALL),
316                 OC_LOW_QOS, &cbData, NULL, 0);
317     }
318 #else
319     ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
320 #endif
321     if (ret != OC_STACK_OK)
322     {
323         OC_LOG(ERROR, TAG, "OCStack resource error");
324     }
325     return ret;
326 }
327
328 int main(int argc, char* argv[])
329 {
330     uint8_t addr[20] = {0};
331     uint8_t* paddr = NULL;
332     uint16_t port = USE_RANDOM_PORT;
333     uint8_t ifname[] = "eth0";
334     int opt;
335
336 #ifdef CA_INT
337     while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
338 #else
339     while ((opt = getopt(argc, argv, "u:t:")) != -1)
340 #endif
341     {
342         switch(opt)
343         {
344             case 'u':
345                 UNICAST_DISCOVERY = atoi(optarg);
346                 break;
347             case 't':
348                 TEST_CASE = atoi(optarg);
349                 break;
350             #ifdef CA_INT
351             case 'c':
352                 CA_CONNTYPE = OCConnectivityType(atoi(optarg));
353                 break;
354             #endif
355             default:
356                 PrintUsage();
357                 return -1;
358         }
359     }
360
361     if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
362             (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
363     {
364         PrintUsage();
365         return -1;
366     }
367
368
369     /*Get Ip address on defined interface and initialize coap on it with random port number
370      * this port number will be used as a source port in all coap communications*/
371     if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
372                 sizeof(addr)) == ERR_SUCCESS)
373     {
374         OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
375         paddr = addr;
376     }
377
378     /* Initialize OCStack*/
379     if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK)
380     {
381         OC_LOG(ERROR, TAG, "OCStack init error");
382         return 0;
383     }
384
385     InitDiscovery();
386
387     // Break from loop with Ctrl+C
388     signal(SIGINT, handleSigInt);
389
390     while (!gQuitFlag)
391     {
392         if (OCProcess() != OC_STACK_OK)
393         {
394             OC_LOG(ERROR, TAG, "OCStack process error");
395             return 0;
396         }
397
398         sleep(2);
399     }
400     OC_LOG(INFO, TAG, "Exiting occlient main loop...");
401
402     if (OCStop() != OC_STACK_OK)
403     {
404         OC_LOG(ERROR, TAG, "OCStack stop error");
405     }
406
407     return 0;
408 }
409
410 std::string getIPAddrTBServer(OCClientResponse * clientResponse)
411 {
412     if(!clientResponse) return "";
413     if(!clientResponse->addr) return "";
414     uint8_t a, b, c, d = 0;
415     if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
416
417     char ipaddr[16] = {'\0'};
418     // ostringstream not working correctly here, hence snprintf
419     snprintf(ipaddr,  sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d);
420     return std::string (ipaddr);
421 }
422
423
424 std::string getPortTBServer(OCClientResponse * clientResponse)
425 {
426     if(!clientResponse) return "";
427     if(!clientResponse->addr) return "";
428     uint16_t p = 0;
429     if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
430     std::ostringstream ss;
431     ss << p;
432     return ss.str();
433 }
434
435 std::string getQueryStrForGetPut(OCClientResponse * clientResponse)
436 {
437     return "/a/led";
438 }
439
440
441 /* You could do this with the JSON parser of your choice, a regular expression, PEG
442 grammar, etc.. This "sample" version does not handle cases like escaping strings,
443 but shows a simple way you might approach the task with just the C++98 library: */
444 extract_result_t extract_value(const std::string& search_key, const std::string& input)
445 {
446     const std::string key('\"' + search_key + "\":\"");
447
448     const size_t key_mark = input.find(key);
449     const size_t key_edge = key_mark + key.length();
450     const size_t val_mark = input.find_first_of("\"", key_edge);
451
452     if(std::string::npos == key_mark || std::string::npos == val_mark) {
453        std::ostringstream os;
454
455        os << "extract_value(): \"" << search_key << "\" not found in input";
456        OC_LOG(ERROR, TAG, os.str().c_str());
457
458        return std::make_pair(false, "");
459      }
460
461     return std::make_pair(true, input.substr(key_edge, val_mark - key_edge));
462 }
463
464 extract_result_t parseSID(const OCClientResponse * const clientResponse)
465 {
466     const char* const& pl_in = reinterpret_cast<const char *>(clientResponse->resJSONPayload);
467
468     const std::string pl(pl_in, strlen(pl_in));
469
470     const extract_result_t sid = extract_value("sid", pl);
471     const extract_result_t uri = extract_value("href", pl);
472     //TODO-CA: It should be just enough to send the SID alone and not the combination
473     // of it.
474     return std::make_pair(sid.first and uri.first, sid.second + ':' + uri.second);
475 }
476
477 void parseClientResponse(OCClientResponse * clientResponse)
478 {
479     coapServerIP = getIPAddrTBServer(clientResponse);
480     coapServerPort = getPortTBServer(clientResponse);
481     coapServerResource = getQueryStrForGetPut(clientResponse);
482 }
483
484 void collateSIDs(const OCClientResponse * clientResponse, const std::string& server_ip)
485 {
486     static SID_set_t sids;
487
488     const extract_result_t sid_result = parseSID(clientResponse);
489
490     if(false == sid_result.first)
491      return;
492
493     const sid_t& sid = sid_result.second;
494
495     /* ...there's no need for an application to take any special action, but we can tell
496     if we've seen a resource before, regardless of the transport it arrive on: */
497     std::ostringstream msg;
498
499     if(not sids.insert(sid).second)
500      msg << "SID " << sid << " has been seen before.\n";
501     else
502      msg << "SID " << sid << " is new.\n";
503
504     OC_LOG(INFO, TAG, msg.str().c_str());
505 }