Integrated WIFI/ETHERNET adapters to single IPAdapter.
[platform/upstream/iotivity.git] / resource / csdk / connectivity / samples / tizen / casample.c
1 /******************************************************************
2  *
3  * Copyright 2014 Samsung Electronics 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 <ctype.h>
22 #include <fcntl.h>
23 #include <errno.h>
24 #include <glib.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <string.h>
29 #include <pthread.h>
30 #include "cacommon.h"
31 #include "cainterface.h"
32
33 static GMainLoop *mainloop = NULL;
34
35 pthread_t thread;
36
37 #define MAX_BUF_LEN 1024
38 #define MAX_OPT_LEN 16
39
40
41 /**
42  * @def RS_IDENTITY
43  * @brief
44  */
45 #define IDENTITY     ("1111111111111111")
46 /* @def RS_CLIENT_PSK
47  * @brief
48  */
49 #define RS_CLIENT_PSK   ("AAAAAAAAAAAAAAAA")
50
51
52 int g_received = 0;
53 int g_localUnicastPort = 0;
54 int g_localSecurePort = 0;
55 CATransportType_t g_selected_nw_type = CA_IPV4;
56 const char* g_messageType[] = {"CON", "NON", "ACK", "RESET"};
57
58 char PrintOptions();
59 void Process();
60 CAResult_t GetNetworkType();
61
62 CAResult_t Initialize();
63 void StartListeningServer();
64 void StartDiscoveryServer();
65 void FindResource();
66 void SendRequest();
67 void SendRequestAll();
68 void SendResponse();
69 void AdvertiseResource();
70 void SendNotification();
71 void SelectNetwork();
72 void UnselectNetwork();
73 void HandleRequestResponse();
74 void FindFixedResource();
75 void GetNetworkInfo();
76
77 void RequestHandler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo);
78 void ResponseHandler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo);
79 void SendRequestTemp(CARemoteEndpoint_t *endpoint, CAToken_t token);
80 void GetResourceUri(char *URI, char *resourceURI, int length);
81 int GetSecureInformation(CAPayload_t payLoad);
82
83 static CAToken_t g_lastRequestToken = NULL;
84 static const char g_secureInfoData[] = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
85                                      "\"if\":[\"oc.mi.def\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
86 static const char g_normalInfoData[] = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
87                                      "\"if\":[\"oc.mi.def\"],\"obs\":1}}]}";
88
89 #ifdef __WITH_DTLS__
90 static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
91
92 void ClearDtlsCredentialInfo()
93 {
94     printf("clearDtlsCredentialInfo IN\n");
95     if (pskCredsBlob)
96     {
97         // Initialize sensitive data to zeroes before freeing.
98         if (pskCredsBlob->creds)
99         {
100             memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
101             free(pskCredsBlob->creds);
102         }
103
104         memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
105         free(pskCredsBlob);
106         pskCredsBlob = NULL;
107     }
108     printf("clearDtlsCredentialInfo OUT\n");
109 }
110
111 // Internal API. Invoked by CA stack to retrieve credentials from this module
112 void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
113 {
114     printf("CAGetDtlsPskCredentials IN\n");
115     if(!credInfo)
116     {
117         printf("Invalid credential container");
118         return;
119     }
120
121     *credInfo = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
122     if (NULL == *credInfo)
123     {
124         printf("Failed to allocate credential blob.");
125         return;
126     }
127
128     int16_t credLen = sizeof(OCDtlsPskCreds) * (pskCredsBlob->num);
129     (*credInfo)->creds = (OCDtlsPskCreds *)malloc(credLen);
130     if (NULL == (*credInfo)->creds)
131     {
132         printf("Failed to allocate credentials.");
133         free(*credInfo);
134         *credInfo = NULL;
135         return;
136     }
137
138     memcpy((*credInfo)->identity, pskCredsBlob->identity, DTLS_PSK_ID_LEN);
139     (*credInfo)->num = pskCredsBlob->num;
140     memcpy((*credInfo)->creds, pskCredsBlob->creds, credLen);
141
142     printf("CAGetDtlsPskCredentials OUT\n");
143 }
144
145 bool SetCredentials()
146 {
147     printf("SetCredentials IN\n");
148     pskCredsBlob = (CADtlsPskCredsBlob_t *)calloc(1, sizeof(CADtlsPskCredsBlob_t));
149     if (NULL == pskCredsBlob)
150     {
151         printf("Memory allocation failed!\n");
152         return false;
153     }
154
155     memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
156     pskCredsBlob->num = 1;
157
158     pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
159     if (NULL == pskCredsBlob->creds)
160     {
161         printf("Memory allocation failed!\n");
162         free(pskCredsBlob);
163         return false;
164     }
165
166     memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
167     memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
168
169     printf("SetCredentials OUT\n");
170     return true;
171 }
172 #endif
173
174 void pthread_func()
175 {
176     g_main_loop_run(mainloop);
177 }
178
179 int main()
180 {
181     system("clear");
182
183     printf("\n=============================================\n");
184     printf("\t\tsample main\n");
185     printf("=============================================\n");
186
187     CAResult_t res = CA_STATUS_FAILED;
188     /*
189     * Read DTLS PSK credentials from persistent storage and
190     * set in the OC stack.
191     */
192 #ifdef __WITH_DTLS__
193     if (SetCredentials() == false)
194     {
195         printf("SetCredentials failed\n");
196         return 1;
197     }
198
199     res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
200     if(CA_STATUS_OK != res)
201     {
202         printf("Set credential handler fail\n");
203         return 1;
204     }
205 #endif
206     res = Initialize();
207     if (CA_STATUS_OK != res)
208     {
209         printf("CAInitialize fail\n");
210         return 1;
211     }
212
213     // set handler.
214     CARegisterHandler(RequestHandler, ResponseHandler);
215
216     Process();
217
218     if (g_lastRequestToken != NULL)
219     {
220         CADestroyToken(g_lastRequestToken);
221     }
222     g_lastRequestToken = NULL;
223
224     CATerminate();
225 #ifdef __WITH_DTLS__
226     ClearDtlsCredentialInfo();
227 #endif
228     return 0;
229 }
230
231 void Process()
232 {
233     while (1)
234     {
235         char menu = toupper(PrintOptions());
236
237         switch (menu)
238         {
239             case 'm': // menu
240             case 'M':
241                 break;
242
243             case 'Q': // quits the sample program
244                 printf("quit..!!\n");
245                 g_main_loop_quit(mainloop);
246                 return;
247
248             case 's': // start server
249             case 'S': // start server
250                 StartListeningServer();
251                 break;
252
253             case 't': // send request
254             case 'T':
255                 SendRequestAll();
256                 break;
257
258             case 'c': // start client
259             case 'C':
260                 StartDiscoveryServer();
261                 break;
262
263             case 'f': // find resource
264             case 'F':
265                 FindResource();
266                 break;
267
268             case 'r': // send request
269             case 'R':
270                 SendRequest();
271                 break;
272
273             case 'a': // advertise resource
274             case 'A':
275                 AdvertiseResource();
276                 break;
277
278             case 'b': // send notification
279             case 'B':
280                 SendNotification();
281                 break;
282
283             case 'n': // select network
284             case 'N':
285                 SelectNetwork();
286                 break;
287
288             case 'x': // unselect network
289             case 'X':
290                 UnselectNetwork();
291                 break;
292
293             case 'h': // handle request response
294             case 'H':
295                 HandleRequestResponse();
296                 break;
297
298             case 'y':
299             case 'Y':
300                 while (1)
301                 {
302                     g_received = 0;
303                     FindFixedResource();
304                     while (g_received == 0)
305                     {
306                         sleep(1);
307                         HandleRequestResponse();
308
309                     }
310                 }
311                 break;
312             case 'z':
313             case 'Z':
314                 StartListeningServer();
315                 while (1)
316                 {
317                     sleep(1);
318                     HandleRequestResponse();
319                 }
320                 break;
321
322             case 'g': // get network information
323             case 'G':
324                 GetNetworkInfo();
325                 break;
326
327             default:
328                 printf("not supported menu!!\n");
329                 break;
330         }
331     }
332
333 }
334
335 CAResult_t Initialize()
336 {
337     CAResult_t res = CA_STATUS_FAILED;
338     mainloop = g_main_loop_new(NULL, FALSE);
339     if(!mainloop)
340     {
341         printf("g_main_loop_new failed\n");
342         return res;
343     }
344
345     int result = pthread_create(&thread, NULL, (void *) &pthread_func, NULL);
346     if (result < 0)
347     {
348         printf("pthread_create failed in initialize\n");
349         return res;
350     }
351
352     res = CAInitialize();
353     if (res != CA_STATUS_OK)
354     {
355         printf("CAInitialize fail\n");
356     }
357     return res;
358 }
359
360 void StartListeningServer()
361 {
362     printf("start listening server!!\n");
363
364     CAResult_t res = CAStartListeningServer();
365     if (res != CA_STATUS_OK)
366     {
367         printf("start listening server fail\n");
368     }
369     else
370     {
371         printf("start listening server success\n");
372     }
373 }
374
375 void StartDiscoveryServer()
376 {
377     printf("start discovery client!!\n");
378
379     CAResult_t res = CAStartDiscoveryServer();
380     if (res != CA_STATUS_OK)
381     {
382         printf("start discovery client fail\n");
383     }
384     else
385     {
386         printf("start discovery client success\n");
387     }
388 }
389
390 void FindFixedResource()
391 {
392     char buf[] ="/a/light";
393
394     // create token
395     CAToken_t token = NULL;
396     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
397
398     CAResult_t res = CAGenerateToken(&token, tokenLength);
399     if ((CA_STATUS_OK != res) || (!token))
400     {
401         printf("token generate error!!");
402         return;
403     }
404
405     printf("Generated token %s\n", token);
406
407     res = CAFindResource(buf, token, tokenLength);
408     if (res != CA_STATUS_OK)
409     {
410         printf("find resource error : %d\n", res);
411     }
412     else
413     {
414         printf("find resource to %s URI\n", buf);
415     }
416
417     // delete token
418     CADestroyToken(token);
419
420     printf("=============================================\n");
421 }
422
423 void FindResource()
424 {
425     char buf[MAX_BUF_LEN] = {0};
426
427     printf("\n=============================================\n");
428     printf("ex) /a/light\n");
429     printf("reference uri : ");
430
431     if(!fgets(buf, MAX_BUF_LEN, stdin))
432     {
433         printf("fgets error\n");
434         return;
435     }
436
437     // create token
438     CAToken_t token = NULL;
439     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
440
441     CAResult_t res = CAGenerateToken(&token, tokenLength);
442     if ((CA_STATUS_OK != res) || (!token))
443     {
444         printf("token generate error!!\n");
445         return;
446     }
447
448     printf("Generated token %s\n", token);
449
450     res = CAFindResource(buf, token, tokenLength);
451     if (res != CA_STATUS_OK)
452     {
453         printf("find resource error : %d\n", res);
454         CADestroyToken(token);
455     }
456     else
457     {
458         printf("find resource to %s URI\n", buf);
459
460         CADestroyToken(g_lastRequestToken);
461
462         g_lastRequestToken = token;
463     }
464
465     printf("=============================================\n");
466 }
467
468 void SendRequest()
469 {
470     char secureRequest[2] = {0};
471     CAResult_t res = CA_STATUS_FAILED;
472     char uri[MAX_BUF_LEN] = {'\0'};
473
474     res = GetNetworkType();
475     if (res != CA_STATUS_OK)
476     {
477         return;
478     }
479
480     printf("Do you want to send secure request ?.... enter (0/1): \n");
481     if(!fgets(secureRequest, 1, stdin))
482     {
483         printf("fgets error\n");
484         return;
485     }
486
487     if ('1' == secureRequest[0])
488     {
489         printf("Enter the URI like below....\n");
490         printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
491         printf("uri:  ");
492     }
493     else
494     {
495         printf("Enter the URI like below....\n");
496         printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
497         printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
498         printf("uri:  ");
499     }
500
501     if(!fgets(uri, MAX_BUF_LEN, stdin))
502     {
503         printf("fgets error\n");
504         return;
505     }
506
507     // create remote endpoint
508     CARemoteEndpoint_t *endpoint = NULL;
509     if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, g_selectedNwType, &endpoint)
510         || !endpoint)
511     {
512         printf("Failed to create remote endpoint!\n");
513         CADestroyRemoteEndpoint(endpoint);
514         return;
515     }
516
517     char buf[MAX_BUF_LEN]={0};
518
519     printf("\n=============================================\n");
520     printf("0:CON, 1:NON\n");
521     printf("select message type : ");
522
523     if(!fgets(buf, MAX_BUF_LEN, stdin))
524     {
525         printf("fgets error\n");
526         CADestroyRemoteEndpoint(endpoint);
527         return;
528     }
529
530     CAMessageType_t msgType = (buf[0] == '0' || buf[0] == '1') ? buf[0] - '0' : 0;
531
532     // create token
533     CAToken_t token = NULL;
534     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
535
536     res = CAGenerateToken(&token, tokenLength);
537     if ((CA_STATUS_OK != res) || (!token))
538     {
539         printf("token generate error, error code : %d\n", res);
540         return;
541     }
542
543     printf("Generated token %s\n", token);
544
545     // extract relative resourceuri from give uri
546     char resourceURI[15] = {0};
547
548     printf("URI : %s\n", uri);
549     GetResourceUri(uri, resourceURI, 14);
550
551     // create request data
552     CAInfo_t requestData = {CA_MSG_RESET};
553     requestData.token = token;
554     if ('1' == secureRequest[0])
555     {
556         int length = strlen(g_secureInfoData) + strlen(resourceURI) + 1;
557         requestData.payload = (CAPayload_t) malloc(length);
558         if(!requestData.payload)
559         {
560             printf("Memory allocation is failed\n");
561             CADestroyToken(token);
562             CADestroyRemoteEndpoint(endpoint);
563             return;
564         }
565         sprintf(requestData.payload, g_secureInfoData, resourceURI, g_localSecurePort);
566     }
567     else
568     {
569         int length = strlen(g_normalInfoData) + strlen(resourceURI) + 1;
570         requestData.payload = (CAPayload_t) malloc(length);
571         if(!requestData.payload)
572         {
573             printf("Memory allocation is failed\n");
574             CADestroyToken(token);
575             CADestroyRemoteEndpoint(endpoint);
576             return;
577         }
578         sprintf(requestData.payload, g_normalInfoData, resourceURI);
579     }
580     requestData.type = msgType;
581
582     CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
583     requestInfo.method = CA_GET;
584     requestInfo.info = requestData;
585
586     // send request
587     CASendRequest(endpoint, &requestInfo);
588
589     CADestroyToken(token);
590
591     free(requestData.payload);
592
593     // destroy remote endpoint
594     CADestroyRemoteEndpoint(endpoint);
595     printf("=============================================\n");
596 }
597
598 void SendRequestAll()
599 {
600     char buf[MAX_BUF_LEN] = {0};
601
602     CAResult_t res = CA_STATUS_FAILED;
603
604     res = GetNetworkType();
605     if (res != CA_STATUS_OK)
606     {
607         return;
608     }
609
610     printf("\n=============================================\n");
611     printf("10.11.12.13:4545/resource_uri ( for IP )\n");
612     printf("10:11:12:13:45:45/resource_uri ( for BT )\n");
613     printf("uri : ");
614
615     if(!fgets(buf, MAX_BUF_LEN, stdin))
616     {
617         printf("fgets error\n");
618         return;
619     }
620
621     // create remote endpoint
622     CARemoteEndpoint_t *endpoint = NULL;
623     res = CACreateRemoteEndpoint(buf, g_selectedNwType, &endpoint);
624
625     if (res != CA_STATUS_OK)
626     {
627         printf("create remote endpoint error!!\n");
628         CADestroyRemoteEndpoint(endpoint);
629         return;
630     }
631
632     CAGroupEndpoint_t *group = NULL;
633     group = (CAGroupEndpoint_t *)malloc(sizeof(CAGroupEndpoint_t));
634      if (NULL == group)
635     {
636         printf("Memory allocation failed!\n");
637         CADestroyRemoteEndpoint(endpoint);
638         return;
639     }
640     group->transportType = endpoint->transportType;
641     group->resourceUri = endpoint->resourceUri;
642
643     // create token
644     CAToken_t token = NULL;
645     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
646
647     res = CAGenerateToken(&token, tokenLength);
648     if ((CA_STATUS_OK != res) || (!token))
649     {
650         printf("token generate error!!\n");
651         return;
652     }
653
654     printf("generated token %s\n", token);
655
656     CAInfo_t requestData = {CA_MSG_RESET};
657     requestData.token = token;
658     requestData.tokenLength = tokenLength;
659     requestData.payload = "Temp Json Payload";
660     requestData.type = CA_MSG_NONCONFIRM;
661
662     CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
663     requestInfo.method = CA_GET;
664     requestInfo.info = requestData;
665
666     // send request
667     CASendRequestToAll(group, &requestInfo);
668
669     CADestroyToken(token);
670
671     // destroy remote endpoint
672     CADestroyRemoteEndpoint(endpoint);
673
674     free(group);
675
676     printf("=============================================\n");
677 }
678
679 void AdvertiseResource()
680 {
681     char buf[MAX_BUF_LEN] = {0};
682
683     printf("\n=============================================\n");
684     printf("uri : ");
685
686     if(!fgets(buf, MAX_BUF_LEN, stdin))
687     {
688         printf("fgets error\n");
689         return;
690     }
691
692     int optionNum = 0;
693     char optionData[MAX_OPT_LEN] = {0};
694
695     printf("Option Num : ");
696     scanf("%d", &optionNum);
697     CAHeaderOption_t *headerOpt = NULL;
698     headerOpt = (CAHeaderOption_t *) malloc(sizeof(CAHeaderOption_t) * optionNum);
699     if (NULL == headerOpt)
700     {
701         printf("Memory allocation failed!\n");
702         return;
703     }
704     memset(headerOpt, 0, sizeof(CAHeaderOption_t) * optionNum);
705
706     int i = 0;
707     for (i = 0 ; i < optionNum ; i++)
708     {
709         int optionID = 0;
710         printf("[%d] Option ID : ", i + 1);
711         scanf("%d", &optionID);
712         headerOpt[i].optionID = optionID;
713
714         printf("[%d] Option Data : ", i + 1);
715         scanf("%s", optionData);
716         int len = strlen(optionData);
717         memcpy(headerOpt[i].optionData, optionData, len + 1);
718         printf("[%d] inputed option : ID : %d, data : %s\n", i + 1, optionID, optionData );
719
720         headerOpt[i].optionLength = (uint16_t)len;
721     }
722     printf("\n=============================================\n");
723
724     // create token
725     CAToken_t token = NULL;
726     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
727
728     CAResult_t res = CAGenerateToken(&token, tokenLength);
729     if ((CA_STATUS_OK != res) || (!token))
730     {
731         printf("token generate error!!\n");
732         return;
733     }
734
735     printf("generated token %s\n", token);
736
737     CAAdvertiseResource(buf, token, tokenLength, headerOpt, (uint8_t)optionNum);
738
739     // delete token
740     CADestroyToken(token);
741
742     free(headerOpt);
743 }
744
745 void SendNotification()
746 {
747     char buf[MAX_BUF_LEN] = {0};
748
749     CAResult_t res = CA_STATUS_FAILED;
750
751     res = get_network_type();
752     if (res != CA_STATUS_OK)
753     {
754         return;
755     }
756
757     printf("\n=============================================\n");
758     printf("10.11.12.13:4545/resource_uri ( for IP )\n");
759     printf("10:11:12:13:45:45/resource_uri ( for BT )\n");
760     printf("uri : ");
761
762      if(!fgets(buf, MAX_BUF_LEN, stdin))
763     {
764         printf("fgets error\n");
765         return;
766     }
767
768     // create remote endpoint
769     CARemoteEndpoint_t *endpoint = NULL;
770     res = CACreateRemoteEndpoint(buf, g_selectedNwType, &endpoint);
771     if (res != CA_STATUS_OK)
772     {
773         printf("create remote endpoint error!!\n");
774         CADestroyRemoteEndpoint(endpoint);
775         return;
776     }
777
778     CAInfo_t respondData = {CA_MSG_RESET};
779     respondData.tokenLength = CA_MAX_TOKEN_LEN;
780
781     res = CAGenerateToken(&respondData.token, respondData.tokenLength);
782     if ((CA_STATUS_OK != res) || (!respondData.token))
783     {
784         printf("token generate error!!\n");
785         return;
786     }
787
788     respondData.payload = "Temp Notification Data";
789
790     CAResponseInfo_t responseInfo = {0};
791     responseInfo.result = CA_SUCCESS;
792     responseInfo.info = respondData;
793
794     // send request
795     res = CASendNotification(endpoint, &responseInfo);
796     if (res != CA_STATUS_OK)
797     {
798         printf("send notification error, error code: %d\n", res);
799     }
800     else
801     {
802         printf("send notification success\n");
803     }
804
805     // delete token
806     CADestroyToken(respondData.token);
807     // destroy remote endpoint
808     CADestroyRemoteEndpoint(endpoint);
809
810     printf("\n=============================================\n");
811 }
812 void SelectNetwork()
813 {
814     char buf[MAX_BUF_LEN] = {0};
815
816     printf("\n=============================================\n");
817     printf("\tselect network\n");
818     printf("IPv4 : 0\n");
819     printf("EDR : 2\n");
820     printf("LE : 3\n");
821     printf("select : ");
822
823     if(!fgets(buf, MAX_BUF_LEN, stdin))
824     {
825         printf("fgets error\n");
826         return;
827     }
828
829     int number = buf[0] - '0';
830
831     number = (number < 0 || number > 3) ? 0 : number;
832
833     CAResult_t res = CASelectNetwork(1 << number);
834     if (res != CA_STATUS_OK)
835     {
836         printf("select network error\n");
837         g_selectedNwType = 1 << number;
838     }
839     else
840     {
841         printf("select network success\n");
842     }
843
844     printf("=============================================\n");
845 }
846
847 void UnselectNetwork()
848 {
849     char buf[MAX_BUF_LEN] = {0};
850
851     printf("\n=============================================\n");
852     printf("\tunselect enabled network\n");
853     printf("ETHERNET : 0\n");
854     printf("WIFI : 1\n");
855     printf("EDR : 2\n");
856     printf("LE : 3\n");
857     printf("select : ");
858
859     if(!fgets(buf, MAX_BUF_LEN, stdin))
860     {
861         printf("fgets error\n");
862         return;
863     }
864
865     int number = buf[0] - '0';
866
867     number = (number < 0 || number > 3) ? 1 : number;
868
869     CAResult_t res = CAUnSelectNetwork(1 << number);
870     if (res != CA_STATUS_OK)
871     {
872         printf("unselect network error\n");
873     }
874     else
875     {
876         printf("unselect network success\n");
877     }
878     printf("=============================================\n");
879 }
880
881 char PrintOptions()
882 {
883     char buf[MAX_BUF_LEN] = {0};
884
885     printf("\n=============================================\n");
886     printf("\t\tMenu\n");
887     printf("\tm : show menu\n");
888     printf("\ts : start server\n");
889     printf("\tc : start client\n");
890     printf("\tf : find resource\n");
891     printf("\tr : send request\n");
892     printf("\tt : send request to all\n");
893     printf("\ta : advertise resource\n");
894     printf("\tb : send notification\n");
895     printf("\tn : select network\n");
896     printf("\tx : unselect network\n");
897     printf("\tg : get network information\n");
898     printf("\th : handle request response\n");
899     printf("\ty : run static client\n");
900     printf("\tz : run static server\n");
901     printf("\tq : quit\n");
902     printf("=============================================\n");
903     printf("select : ");
904
905     if(!fgets(buf, MAX_BUF_LEN, stdin))
906     {
907         printf("fgets error\n");
908         return '\0';
909     }
910
911     return buf[0];
912 }
913
914 void HandleRequestResponse()
915 {
916     printf("handle_request_response\n");
917
918     CAResult_t res = CAHandleRequestResponse();
919     if (res != CA_STATUS_OK)
920     {
921         printf("handle request error\n");
922     }
923     else
924     {
925         printf("handle request success\n");
926     }
927 }
928
929 void GetNetworkInfo()
930 {
931     int index = 0;
932     CALocalConnectivity_t *tempInfo = NULL;
933     uint32_t tempSize = 0;
934
935     CAGetNetworkInformation(&tempInfo, &tempSize);
936     if (tempInfo == NULL || tempSize <= 0)
937     {
938         printf("network not connected\n");
939         return;
940     }
941
942     printf("################## Network Information #######################\n");
943     printf("network info total size is %d\n\n", tempSize);
944
945     for (index = 0; index < tempSize; index++)
946     {
947         printf("Type: %d\n", tempInfo[index].type);
948         printf("Address: %s\n", tempInfo[index].addressInfo.IP.ipAddress);
949         printf("Port: %d\n", tempInfo[index].addressInfo.IP.port);
950         printf("Secured: %d\n\n", tempInfo[index].isSecured);
951
952         if (true == tempInfo[index].isSecured)
953         {
954             g_localSecurePort = tempInfo[index].addressInfo.IP.port;
955         }
956         else
957         {
958             g_localUnicastPort = tempInfo[index].addressInfo.IP.port;
959         }
960     }
961
962     // free
963     free(tempInfo);
964
965     printf("##############################################################");
966 }
967
968 void RequestHandler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
969 {
970     printf("##########received request from remote device #############\n");
971     if (!object)
972     {
973         printf("Remote endpoint is NULL!\n");
974         return;
975     }
976
977     if (!requestInfo)
978     {
979         printf("Request info is NULL!\n");
980         return;
981     }
982
983     printf("Uri: %s\n", object->resourceUri);
984     printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
985            object->addressInfo.IP.port, object->isSecured);
986
987     printf("Data: %s\n", requestInfo->info.payload);
988     printf("Message type: %s\n", g_messageType[requestInfo->info.type]);
989     if (g_lastRequestToken != NULL && requestInfo->info.token != NULL
990         && (strcmp((char *)g_lastRequestToken, requestInfo->info.token) == 0))
991     {
992         printf("token is same. received request of it's own. skip.. \n");
993         return;
994     }
995
996     if (requestInfo->info.options)
997     {
998         uint32_t len = requestInfo->info.numOptions;
999         uint32_t i = 0;
1000         for (i = 0; i < len; i++)
1001         {
1002             printf("Option %d\n", i + 1);
1003             printf("ID : %d\n", requestInfo->info.options[i].optionID);
1004             printf("Data[%d]: %s\n", requestInfo->info.options[i].optionLength,
1005                    requestInfo->info.options[i].optionData);
1006         }
1007     }
1008     printf("############################################################\n");
1009
1010     //Check if this has secure communication information
1011     if (requestInfo->info.payload)
1012     {
1013         int securePort = GetSecureInformation(requestInfo->info.payload);
1014         if (0 < securePort) //Set the remote endpoint secure details and send response
1015         {
1016             printf("This is secure resource...\n");
1017             char *uri = NULL;
1018             int length = 0;
1019
1020             length = 8; //length of "coaps://"
1021             length += strlen(object->addressInfo.IP.ipAddress) + 5; // length of "ipaddress:port"
1022             length += strlen(object->resourceUri) + 1;
1023
1024             uri = calloc(1, sizeof(char) * length);
1025             if (!uri)
1026             {
1027                 printf("Failed to create new uri\n");
1028                 return;
1029             }
1030             sprintf(uri, "coaps://%s:%d/%s", object->addressInfo.IP.ipAddress,
1031                     securePort, object->resourceUri);
1032
1033             CARemoteEndpoint_t *endpoint = NULL;
1034             if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, object->connectivityType, &endpoint))
1035             {
1036                 printf("Failed to create duplicate of remote endpoint!\n");
1037                 return;
1038             }
1039             //endpoint->connectivityType = object->connectivityType;
1040             endpoint->isSecured = true;
1041             object = endpoint;
1042
1043             free(uri);
1044         }
1045     }
1046
1047     printf("send response with URI\n");
1048     SendResponse(object, &requestInfo->info);
1049
1050     g_received = 1;
1051 }
1052
1053 void ResponseHandler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
1054 {
1055     printf("##########Received response from remote device #############\n");
1056     if(!object)
1057     {
1058         printf("response_handler object is null\n");
1059         return;
1060     }
1061
1062      if(!responseInfo)
1063     {
1064         printf("response_handler responseInfo is null\n");
1065         return;
1066     }
1067
1068     printf("Uri: %s\n", object->resourceUri);
1069     printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
1070            object->addressInfo.IP.port, object->isSecured);
1071     printf("response result : %d\n", responseInfo->result);
1072     printf("Data: %s\n", responseInfo->info.payload);
1073     printf("Message type: %s\n", g_messageType[responseInfo->info.type]);
1074     printf("Token: %s\n", responseInfo->info.token);
1075     if (responseInfo->info.options)
1076     {
1077         uint32_t len = responseInfo->info.numOptions;
1078         uint32_t i = 0;
1079         for (i = 0; i < len; i++)
1080         {
1081             printf("Option %d\n", i + 1);
1082             printf("ID : %d\n", responseInfo->info.options[i].optionID);
1083             printf("Data[%d]: %s\n", responseInfo->info.options[i].optionLength,
1084                    responseInfo->info.options[i].optionData);
1085         }
1086     }
1087     printf("############################################################\n");
1088     g_received = 1;
1089
1090     //Check if this has secure communication information
1091     if (responseInfo->info.payload)
1092     {
1093         int securePort = GetSecureInformation(responseInfo->info.payload);
1094         if (0 < securePort) //Set the remote endpoint secure details and send response
1095         {
1096             printf("This is secure resource...\n");
1097         }
1098     }
1099 }
1100
1101 void SendResponse(CARemoteEndpoint_t *endpoint, CAInfo_t *info)
1102 {
1103     printf("entering send_response\n");
1104
1105      if(!endpoint)
1106     {
1107         printf("endpoint is null\n");
1108         return;
1109     }
1110
1111     CAInfo_t responseData = {CA_MSG_RESET};
1112     responseData.type =
1113         (info != NULL) ?
1114         ((info->type == CA_MSG_CONFIRM) ? CA_MSG_ACKNOWLEDGE : CA_MSG_NONCONFIRM) :
1115             CA_MSG_NONCONFIRM;
1116     responseData.messageId = 0;
1117     responseData.token = "";
1118     if(info)
1119     {
1120         responseData.messageId = info->messageId;
1121         responseData.token = info->token;
1122         responseData.tokenLength = info->tokenLength;
1123     }
1124     responseData.payload = "response payload";
1125
1126     CAResponseInfo_t responseInfo = {0};
1127     responseInfo.result = 203;
1128     responseInfo.info = responseData;
1129
1130     if (true == endpoint->isSecured)
1131     {
1132         printf("Sending response on secure communication\n");
1133     }
1134     else
1135     {
1136         printf("Sending response on non-secure communication\n");
1137     }
1138
1139     // send request (connectivityType from remoteEndpoint of request Info)
1140     CAResult_t res = CASendResponse(endpoint, &responseInfo);
1141     if (res != CA_STATUS_OK)
1142     {
1143         printf("send response failed\n");
1144     }
1145     else
1146     {
1147         printf("send response success\n");
1148     }
1149
1150     printf("=============================================\n");
1151 }
1152
1153 void SendRequestTemp(CARemoteEndpoint_t *endpoint, CAToken_t token, uint8_t tokenLength)
1154 {
1155     printf("\n=============================================\n");
1156
1157     if(!endpoint)
1158     {
1159         printf("endpoint is null\n");
1160         return;
1161     }
1162
1163     CAInfo_t requestData ={CA_MSG_RESET};
1164     requestData.token = token;
1165     requestData.tokenLength = tokenLength;
1166     requestData.payload = "Temp Json Payload";
1167
1168     CARequestInfo_t requestInfo ={CA_GET, {CA_MSG_RESET}};
1169     memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1170     requestInfo.method = CA_GET;
1171     requestInfo.info = requestData;
1172
1173     // send request
1174     endpoint->connectivityType = CA_WIFI;
1175
1176     CAResult_t res = CASendRequest(endpoint, &requestInfo);
1177     if (res != CA_STATUS_OK)
1178     {
1179         printf("send request failed\n");
1180     }
1181     else
1182     {
1183         printf("send request success\n");
1184     }
1185
1186     printf("=============================================\n");
1187
1188 }
1189
1190 int GetSecureInformation(CAPayload_t payLoad)
1191 {
1192     printf("entering get_secure_information\n");
1193
1194     if (!payLoad)
1195     {
1196         printf("Payload is NULL\n");
1197         return -1;
1198     }
1199
1200     char *subString = NULL;
1201     if (NULL == (subString = strstr(payLoad, "\"sec\":1")))
1202     {
1203         printf("This is not secure resource\n");
1204         return -1;
1205     }
1206
1207     if (NULL == (subString = strstr(payLoad, "\"port\":")))
1208     {
1209         printf("This secure resource does not have port information\n");
1210         return -1;
1211     }
1212
1213     char *startPos = strstr(subString, ":");
1214     if (!startPos)
1215     {
1216         printf("Parsing failed !\n");
1217         return -1;
1218     }
1219
1220     char *endPos = strstr(startPos, "}");
1221     if (!endPos)
1222     {
1223         printf("Parsing failed !\n");
1224         return -1;
1225     }
1226
1227     if(((endPos - 1) - startPos) > 4)
1228     {
1229         printf("port length is not proper.Exceeding length 4\n");
1230         return -1;
1231     }
1232
1233     char portStr[4] = {0};
1234     memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
1235
1236     printf("secured port is: %s\n", portStr);
1237     return atoi(portStr);
1238 }
1239
1240 void GetResourceUri(char *URI, char *resourceURI, int length)
1241 {
1242     char *startPos = URI;
1243     char *temp = NULL;
1244     if (NULL != (temp = strstr(URI, "://")))
1245     {
1246         startPos = strchr(temp + 3, '/');
1247         if (!startPos)
1248         {
1249             printf("Resource URI is missing\n");
1250             return;
1251         }
1252     }
1253
1254     char *endPos = strchr(startPos, '?');
1255     if (!endPos)
1256     {
1257         endPos = URI + strlen(URI);
1258     }
1259     endPos -= 1;
1260
1261     if (endPos - startPos <= length)
1262         memcpy(resourceURI, startPos + 1, endPos - startPos);
1263
1264     printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
1265 }
1266
1267 CAResult_t get_network_type()
1268 {
1269     printf("\n=============================================\n");
1270     printf("\tselect network type\n");
1271     printf("IPv4 : 0\n");
1272     printf("BT : 2\n");
1273     printf("LE : 3\n");
1274     printf("select : ");
1275
1276     if(!fgets(buf, MAX_BUF_LEN, stdin))
1277     {
1278         printf("fgets error\n");
1279         return CA_STATUS_FAILED;
1280     }
1281
1282     int number = buf[0] - '0';
1283
1284     number = (number < 0 || number > 3) ? 0 : 1 << number;
1285
1286     if (!(number & 0xf))
1287     {
1288         return CA_NOT_SUPPORTED;
1289     }
1290     if (number & CA_IPV4)
1291     {
1292         g_selected_nw_type = CA_IPV4;
1293         return CA_STATUS_OK;
1294     }
1295
1296     if (number & CA_EDR)
1297     {
1298         g_selected_nw_type = CA_EDR;
1299         return CA_STATUS_OK;
1300     }
1301     if (number & CA_LE)
1302     {
1303         g_selected_nw_type = CA_LE;
1304         return CA_STATUS_OK;
1305     }
1306
1307     printf("\n=============================================\n");
1308
1309     return CA_STATUS_FAILED;
1310 }
1311
1312