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