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