IOT-1073 Enable AutoConf header file CPPDEFINES
[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 #ifdef HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif
27 #ifdef HAVE_WINDOWS_H
28 #include <windows.h>
29 #endif
30 #include <stdint.h>
31 #include <sstream>
32 #include <iostream>
33
34 #include "ocstack.h"
35 #include "logger.h"
36 #include "occlientbasicops.h"
37 #include "ocpayload.h"
38 #include "payload_logging.h"
39 #include "oic_malloc.h"
40 #include "oic_string.h"
41
42 #define MAX_IP_ADDR_ST_SZ  16 //string size of "155.255.255.255" (15 + 1)
43 #define MAX_PORT_ST_SZ  6     //string size of "65535" (5 + 1)
44
45 static int UnicastDiscovery = 0;
46 static int TestCase = 0;
47 static int Connectivity = 0;
48
49 //The following variable determines the interface protocol (IP, etc)
50 //to be used for sending unicast messages. Default set to IP.
51 static OCConnectivityType ConnType = CT_ADAPTER_IP;
52 static const char *RESOURCE_DISCOVERY_QUERY = "%s/oic/res";
53
54 int gQuitFlag = 0;
55
56 struct ResourceNode *resourceList;
57 /*
58  * SIGINT handler: set gQuitFlag to 1 for graceful termination
59  * */
60 void handleSigInt(int signum)
61 {
62     if (signum == SIGINT)
63     {
64         gQuitFlag = 1;
65     }
66 }
67
68 OCPayload* putPayload()
69 {
70     OCRepPayload* payload = OCRepPayloadCreate();
71
72     if(!payload)
73     {
74         std::cout << "Failed to create put payload object"<<std::endl;
75         std::exit(1);
76     }
77
78     OCRepPayloadSetPropInt(payload, "power", 15);
79     OCRepPayloadSetPropBool(payload, "state", true);
80
81     return (OCPayload*) payload;
82 }
83
84 static void PrintUsage()
85 {
86     OIC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
87     OIC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
88     OIC_LOG(INFO, TAG, "-t 1 : Discover Resources");
89     OIC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
90             " Initiate Nonconfirmable Get/Put/Post Requests");
91     OIC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate "
92             "Confirmable Get/Put/Post Requests");
93     OIC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
94     OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
95 }
96
97 /*
98  * Returns the first resource in the list
99  */
100 const ResourceNode * getResource()
101 {
102     return resourceList;
103 }
104
105 OCStackResult InvokeOCDoResource(std::ostringstream &query,
106                                  OCMethod method,
107                                  const OCDevAddr *dest,
108                                  OCQualityOfService qos,
109                                  OCClientResponseHandler cb,
110                                  OCHeaderOption * options, uint8_t numOptions)
111 {
112     OCStackResult ret;
113     OCCallbackData cbData;
114
115     cbData.cb = cb;
116     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
117     cbData.cd = NULL;
118
119     ret = OCDoResource(NULL, method, query.str().c_str(), dest,
120         (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL,
121          CT_DEFAULT, qos, &cbData, options, numOptions);
122
123     if (ret != OC_STACK_OK)
124     {
125         OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d",
126                  ret, method);
127     }
128
129     return ret;
130 }
131
132 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle /*handle*/,
133                                   OCClientResponse * clientResponse)
134 {
135     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
136     {
137         OIC_LOG(INFO, TAG, "<====Callback Context for PUT received successfully====>");
138     }
139     else
140     {
141         OIC_LOG(ERROR, TAG, "<====Callback Context for PUT fail====>");
142     }
143
144     if(clientResponse)
145     {
146         OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
147         OIC_LOG(INFO, TAG, ("=============> Put Response"));
148     }
149     else
150     {
151         OIC_LOG(ERROR, TAG, "<====PUT Callback fail to receive clientResponse====>\n");
152     }
153     return OC_STACK_DELETE_TRANSACTION;
154 }
155
156 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle /*handle*/,
157                                    OCClientResponse *clientResponse)
158 {
159     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
160     {
161         OIC_LOG(INFO, TAG, "<====Callback Context for POST received successfully====>");
162     }
163     else
164     {
165         OIC_LOG(ERROR, TAG, "<====Callback Context for POST fail====>");
166     }
167
168     if(clientResponse)
169     {
170         OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
171         OIC_LOG(INFO, TAG, ("=============> Post Response"));
172     }
173     else
174     {
175         OIC_LOG(ERROR, TAG, "<====POST Callback fail to receive clientResponse====>\n");
176     }
177
178     return OC_STACK_DELETE_TRANSACTION;
179 }
180
181 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
182                                   OCClientResponse * clientResponse)
183 {
184     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
185     {
186         OIC_LOG(INFO, TAG, "<====Callback Context for GET received successfully====>");
187     }
188     else
189     {
190         OIC_LOG(ERROR, TAG, "<====Callback Context for GET fail====>");
191     }
192
193     if (clientResponse)
194     {
195         OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
196         OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
197         OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
198         OIC_LOG(INFO, TAG, ("=============> Get Response"));
199
200         if (clientResponse->numRcvdVendorSpecificHeaderOptions > 0 )
201         {
202             OIC_LOG (INFO, TAG, "Received vendor specific options");
203             uint8_t i = 0;
204             OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
205             for (i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
206             {
207                 if (((OCHeaderOption) rcvdOptions[i]).protocolID == OC_COAP_ID)
208                 {
209                     OIC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
210                             ((OCHeaderOption)rcvdOptions[i]).optionID );
211
212                     OIC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
213                         MAX_HEADER_OPTION_DATA_LENGTH);
214                 }
215             }
216         }
217     }
218     else
219     {
220         OIC_LOG(ERROR, TAG, "<====GET Callback fail to receive clientResponse====>\n");
221     }
222     return OC_STACK_DELETE_TRANSACTION;
223 }
224
225 /*
226  * This is a function called back when a device is discovered
227  */
228 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
229                                         OCClientResponse * clientResponse)
230 {
231     if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
232     {
233         OIC_LOG(INFO, TAG, "\n<====Callback Context for DISCOVERY query "
234                "received successfully====>");
235     }
236     else
237     {
238         OIC_LOG(ERROR, TAG, "\n<====Callback Context for DISCOVERY fail====>");
239     }
240
241     if (clientResponse)
242     {
243         OIC_LOG_V(INFO, TAG,
244                 "Device =============> Discovered @ %s:%d",
245                 clientResponse->devAddr.addr,
246                 clientResponse->devAddr.port);
247         OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
248
249         collectUniqueResource(clientResponse);
250     }
251     else
252     {
253         OIC_LOG(ERROR, TAG, "<====DISCOVERY Callback fail to receive clientResponse====>\n");
254     }
255     return (UnicastDiscovery) ?
256            OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
257 }
258
259 int InitPutRequest(OCQualityOfService qos)
260 {
261     std::ostringstream query;
262     //Get most recently inserted resource
263     const ResourceNode * resource  = getResource();
264
265     if(!resource)
266     {
267         OIC_LOG_V(ERROR, TAG, "Resource null, can't do PUT request\n");
268         return -1;
269     }
270     query << resource->uri;
271     OIC_LOG_V(INFO, TAG,"Executing InitPutRequest, Query: %s", query.str().c_str());
272
273     return (InvokeOCDoResource(query, OC_REST_PUT, &resource->endpoint,
274            ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
275             putReqCB, NULL, 0));
276 }
277
278 int InitPostRequest(OCQualityOfService qos)
279 {
280     OCStackResult result;
281     std::ostringstream query;
282     //Get most recently inserted resource
283     const ResourceNode *resource  = getResource();
284
285     if(!resource)
286     {
287         OIC_LOG_V(ERROR, TAG, "Resource null, can't do POST request\n");
288         return -1;
289     }
290
291     query << resource->uri;
292     OIC_LOG_V(INFO, TAG,"Executing InitPostRequest, Query: %s", query.str().c_str());
293
294     // First POST operation (to create an LED instance)
295     result = InvokeOCDoResource(query, OC_REST_POST, &resource->endpoint,
296             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
297             postReqCB, NULL, 0);
298     if (OC_STACK_OK != result)
299     {
300         // Error can happen if for example, network connectivity is down
301         OIC_LOG(ERROR, TAG, "First POST call did not succeed");
302     }
303
304     // Second POST operation (to create an LED instance)
305     result = InvokeOCDoResource(query, OC_REST_POST, &resource->endpoint,
306             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
307             postReqCB, NULL, 0);
308     if (OC_STACK_OK != result)
309     {
310         OIC_LOG(ERROR, TAG, "Second POST call did not succeed");
311     }
312
313     // This POST operation will update the original resourced /a/led
314     return (InvokeOCDoResource(query, OC_REST_POST, &resource->endpoint,
315                 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
316                 postReqCB, NULL, 0));
317 }
318
319 int InitGetRequest(OCQualityOfService qos)
320 {
321     std::ostringstream query;
322     //Get most recently inserted resource
323     const ResourceNode * resource  = getResource();
324
325     if(!resource)
326     {
327         OIC_LOG_V(ERROR, TAG, "Resource null, can't do GET request\n");
328         return -1;
329     }
330     query << resource->uri;
331     OIC_LOG_V(INFO, TAG,"Executing InitGetRequest, Query: %s", query.str().c_str());
332
333     return (InvokeOCDoResource(query, OC_REST_GET, &resource->endpoint,
334             (qos == OC_HIGH_QOS)?OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
335 }
336
337 int InitDiscovery()
338 {
339     OCStackResult ret;
340     OCCallbackData cbData;
341     char queryUri[200];
342     char ipaddr[100] = { '\0' };
343
344     if (UnicastDiscovery)
345     {
346         OIC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
347         OIC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
348         OIC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
349
350         if (fgets(ipaddr, sizeof (ipaddr), stdin))
351         {
352             StripNewLineChar(ipaddr); //Strip newline char from ipaddr
353         }
354         else
355         {
356             OIC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
357             return OC_STACK_INVALID_PARAM;
358         }
359     }
360
361     snprintf(queryUri, sizeof (queryUri), RESOURCE_DISCOVERY_QUERY, ipaddr);
362
363     cbData.cb = discoveryReqCB;
364     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
365     cbData.cd = NULL;
366
367     ret = OCDoResource(NULL, OC_REST_DISCOVER, queryUri, 0, 0, CT_DEFAULT,
368                        OC_LOW_QOS, &cbData, NULL, 0);
369     if (ret != OC_STACK_OK)
370     {
371         OIC_LOG(ERROR, TAG, "OCStack resource error");
372     }
373     return ret;
374 }
375
376 void queryResource()
377 {
378     switch(TestCase)
379     {
380         case TEST_DISCOVER_REQ:
381             break;
382         case TEST_NON_CON_OP:
383             InitGetRequest(OC_LOW_QOS);
384             InitPutRequest(OC_LOW_QOS);
385             InitPostRequest(OC_LOW_QOS);
386             break;
387         case TEST_CON_OP:
388             InitGetRequest(OC_HIGH_QOS);
389             InitPutRequest(OC_HIGH_QOS);
390             InitPostRequest(OC_HIGH_QOS);
391             break;
392         default:
393             PrintUsage();
394             break;
395     }
396 }
397
398
399 void collectUniqueResource(const OCClientResponse * clientResponse)
400 {
401     OCDiscoveryPayload* pay = (OCDiscoveryPayload*) clientResponse->payload;
402     OCResourcePayload* res = pay->resources;
403
404     // Including the NUL terminator, length of UUID string of the form:
405     //   "a62389f7-afde-00b6-cd3e-12b97d2fcf09"
406 #   define UUID_LENGTH 37
407
408     char sidStr[UUID_LENGTH];
409
410     while(res) {
411
412         int ret = snprintf(sidStr, UUID_LENGTH,
413                 "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
414                 pay->sid[0], pay->sid[1], pay->sid[2], pay->sid[3],
415                 pay->sid[4], pay->sid[5], pay->sid[6], pay->sid[7],
416                 pay->sid[8], pay->sid[9], pay->sid[10], pay->sid[11],
417                 pay->sid[12], pay->sid[13], pay->sid[14], pay->sid[15]
418                 );
419
420         if (ret == UUID_LENGTH - 1)
421         {
422             if(insertResource(sidStr, res->uri, clientResponse) == 1)
423             {
424                 OIC_LOG_V(INFO,TAG,"%s%s%s%s\n",sidStr, ":", res->uri, " is new");
425                 printResourceList();
426                 queryResource();
427             }
428             else {
429                 OIC_LOG_V(INFO,TAG,"%s%s%s%s\n",sidStr, ":", res->uri, " is old");
430             }
431         }
432         else
433         {
434             OIC_LOG(ERROR, TAG, "Could Not Retrieve the Server ID");
435         }
436
437         res = res->next;
438     }
439 }
440
441 /* This function searches for the resource(sid:uri) in the ResourceList.
442  * If the Resource is found in the list then it returns 0 else insert
443  * the resource to front of the list and returns 1.
444  */
445 int insertResource(const char * sid, char const * uri,
446             const OCClientResponse * clientResponse)
447 {
448     ResourceNode * iter = resourceList;
449     char * sid_cpy =  OICStrdup(sid);
450     char * uri_cpy = OICStrdup(uri);
451
452     //Checking if the resource(sid:uri) is new
453     while(iter)
454     {
455         if((strcmp(iter->sid, sid) == 0) && (strcmp(iter->uri, uri) == 0))
456         {
457             OICFree(sid_cpy);
458             OICFree(uri_cpy);
459             return 0;
460         }
461         else
462         {
463             iter = iter->next;
464         }
465     }
466
467     //Creating new ResourceNode
468     if((iter = (ResourceNode *) OICMalloc(sizeof(ResourceNode))))
469     {
470         iter->sid = sid_cpy;
471         iter->uri = uri_cpy;
472         iter->endpoint = clientResponse->devAddr;
473         iter->next = NULL;
474     }
475     else
476     {
477         OIC_LOG(ERROR, TAG, "Memory not allocated to ResourceNode");
478         OICFree(sid_cpy);
479         OICFree(uri_cpy);
480         return -1;
481     }
482
483     //Adding new ResourceNode to front of the ResourceList
484     if(!resourceList)
485     {
486         resourceList = iter;
487     }
488     else
489     {
490         iter->next = resourceList;
491         resourceList = iter;
492     }
493     return 1;
494 }
495
496 void printResourceList()
497 {
498     ResourceNode * iter;
499     iter = resourceList;
500     OIC_LOG(INFO, TAG, "Resource List: ");
501     while(iter)
502     {
503         OIC_LOG(INFO, TAG, "*****************************************************");
504         OIC_LOG_V(INFO, TAG, "sid = %s",iter->sid);
505         OIC_LOG_V(INFO, TAG, "uri = %s", iter->uri);
506         OIC_LOG_V(INFO, TAG, "ip = %s", iter->endpoint.addr);
507         OIC_LOG_V(INFO, TAG, "port = %d", iter->endpoint.port);
508         switch (iter->endpoint.adapter)
509         {
510             case OC_ADAPTER_IP:
511                 OIC_LOG(INFO, TAG, "connType = Default (IPv4)");
512                 break;
513             case OC_ADAPTER_GATT_BTLE:
514                 OIC_LOG(INFO, TAG, "connType = BLE");
515                 break;
516             case OC_ADAPTER_RFCOMM_BTEDR:
517                 OIC_LOG(INFO, TAG, "connType = BT");
518                 break;
519             default:
520                 OIC_LOG(INFO, TAG, "connType = Invalid connType");
521                 break;
522         }
523         OIC_LOG(INFO, TAG, "*****************************************************");
524         iter = iter->next;
525     }
526 }
527
528 void freeResourceList()
529 {
530     OIC_LOG(INFO, TAG, "Freeing ResourceNode List");
531     ResourceNode * temp;
532     while(resourceList)
533     {
534
535         temp = resourceList;
536         resourceList = resourceList->next;
537         OICFree((void *)temp->sid);
538         OICFree((void *)temp->uri);
539         OICFree(temp);
540     }
541     resourceList = NULL;
542 }
543
544 int main(int argc, char* argv[])
545 {
546     int opt;
547     resourceList = NULL;
548     while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
549     {
550         switch(opt)
551         {
552             case 'u':
553                 UnicastDiscovery = atoi(optarg);
554                 break;
555             case 't':
556                 TestCase = atoi(optarg);
557                 break;
558             case 'c':
559                 Connectivity = atoi(optarg);
560                 break;
561             default:
562                 PrintUsage();
563                 return -1;
564         }
565     }
566
567     if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||
568         (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS) ||
569         (Connectivity < CT_ADAPTER_DEFAULT || Connectivity >= MAX_CT))
570     {
571         PrintUsage();
572         return -1;
573     }
574
575     /* Initialize OCStack*/
576     if (OCInit1(OC_CLIENT, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS) != OC_STACK_OK)
577     {
578         OIC_LOG(ERROR, TAG, "OCStack init error");
579         return 0;
580     }
581
582     if(Connectivity == CT_ADAPTER_DEFAULT || Connectivity ==  CT_IP)
583     {
584         ConnType =  CT_ADAPTER_IP;//CT_DEFAULT;
585     }
586     else
587     {
588         OIC_LOG(INFO, TAG, "Default Connectivity type selected");
589         PrintUsage();
590     }
591
592     InitDiscovery();
593
594     // Break from loop with Ctrl+C
595     signal(SIGINT, handleSigInt);
596
597     while (!gQuitFlag)
598     {
599         if (OCProcess() != OC_STACK_OK)
600         {
601             OIC_LOG(ERROR, TAG, "OCStack process error");
602             return 0;
603         }
604         sleep(2);
605     }
606
607     freeResourceList();
608     OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
609     if (OCStop() != OC_STACK_OK)
610     {
611         OIC_LOG(ERROR, TAG, "OCStack stop error");
612     }
613     return 0;
614 }
615
616