1 /******************************************************************
3 * Copyright 2014 Samsung Electronics All Rights Reserved.
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 ******************************************************************/
29 #include "cainterface.h"
34 #elif defined ARDUINOETH
38 #include "oic_malloc.h"
40 #define MAX_BUF_LEN 100 //1024
41 #define MAX_OPT_LEN 16
43 static bool g_isLeSelected = false;
45 static void PrintMenu();
46 static void Process();
47 static void Initialize();
48 static void StartListeningServer();
49 static void StartDiscoveryServer();
50 static void SendRequest();
51 static void SendRequestAll();
52 static void SendResponse(CAEndpoint_t *endpoint, const CAInfo_t* info);
53 static void SendNotification();
54 static void SelectNetwork();
55 static void UnselectNetwork();
56 static void HandleRequestResponse();
58 static void RequestHandler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo);
59 static void ResponseHandler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo);
60 static void ErrorHandler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
61 static void Terminate();
63 void GetData(char *readInput, size_t bufferLength, size_t *dataLength)
65 if (!readInput || bufferLength == 0 || !dataLength)
67 Serial.println("Invalid buffer");
71 while (!Serial.available())
76 while (Serial.available())
79 char c = Serial.read();
80 if ('\n' != c && '\r' != c && len < bufferLength - 1)
90 readInput[len] = '\0';
93 Serial.println(readInput);
97 bool ParseData(char *buf, char *url, char *resourceUri)
99 char *slash = strchr(buf, '/');
105 strcpy(resourceUri, slash);
107 char *dot = strchr(buf, '.');
108 if (dot && dot < slash)
110 char *colon = strchr(buf, ':');
111 if (colon && colon < slash)
113 strncpy(url, buf, colon - buf);
118 strncpy(url, buf, slash - buf);
122 CATransportAdapter_t GetConnectivityType()
125 Serial.println("Select network");
126 Serial.println("IP: 0");
127 Serial.println("RFCOMM (EDR): 1");
128 Serial.println("GATT (BLE): 2");
131 GetData(type, sizeof(type), &typeLen);
134 Serial.println("i/p err,default ethernet");
135 return CA_ADAPTER_IP;
140 return CA_ADAPTER_IP;
142 return CA_ADAPTER_RFCOMM_BTEDR;
144 return CA_ADAPTER_GATT_BTLE;
146 return CA_ADAPTER_IP;
151 Serial.begin (115200);
153 Serial.println("============");
154 Serial.println("CA SAMPLE");
155 Serial.println("============");
161 char buffer[5] = {0};
163 if (Serial.available() > 0)
165 GetData(buffer, sizeof(buffer), &len);
168 Serial.println("i/p err");
171 switch (toupper(buffer[0]))
178 Serial.println("quit");
181 case 'I': // Initialize interface
185 case 'S': // start listening server
186 StartListeningServer();
189 case 'D': // start discovery server
190 StartDiscoveryServer();
193 case 'F': // find resource
197 case 'R': // send request
200 case 'E': //send request to all
203 case 'B': // send notification
207 case 'N': // select network
211 case 'X': // unselect network
215 case 'H': // handle request response
216 HandleRequestResponse();
219 case 'T': // handle request response
224 Serial.println("wrong menu");
228 //1:Add check for startserver before calling below api
231 HandleRequestResponse();
238 if(CAInitialize() != CA_STATUS_OK)
240 Serial.println("Initialize failed");
245 CARegisterHandler(RequestHandler, ResponseHandler, ErrorHandler);
248 void StartListeningServer()
250 Serial.println("listening server");
251 CAResult_t ret = CAStartListeningServer();
252 if(ret != CA_STATUS_OK)
254 Serial.print("listening failed: ");
260 void StartDiscoveryServer()
262 Serial.println("discovery server");
263 CAResult_t ret = CAStartDiscoveryServer();
264 if(ret != CA_STATUS_OK)
266 Serial.print("discovery failed: ");
274 char buf[MAX_BUF_LEN] = {0};
275 char address[MAX_BUF_LEN] = {0};
276 char resourceUri[MAX_BUF_LEN] = {0};
277 CATransportAdapter_t selectedNetwork;
278 selectedNetwork = GetConnectivityType();
280 Serial.println("============");
281 Serial.println("10.11.12.13:4545/res_uri (for IP)");
282 Serial.println("10:11:12:13:45:45/res_uri (for BT)");
283 Serial.println("uri: ");
286 GetData(buf, sizeof(buf), &len);
289 Serial.println("i/p err");
293 if (!ParseData(buf, address, resourceUri))
295 Serial.println("bad uri");
299 // create remote endpoint
300 CAEndpoint_t *endpoint = NULL;
301 CAResult_t res = CACreateEndpoint(CA_DEFAULT_FLAGS, selectedNetwork, address, 0, &endpoint);
302 if (res != CA_STATUS_OK)
304 Serial.println("Out of memory");
305 CADestroyEndpoint(endpoint);
309 memset(buf, 0, sizeof(buf));
311 Serial.println("\n=============================================\n");
312 Serial.println("0:CON, 1:NON\n");
313 Serial.println("select message type : ");
314 GetData(buf, sizeof(buf), &len);
315 CAMessageType_t msgType = CA_MSG_CONFIRM;
319 Serial.println("i/p err,default: 0");
321 else if(buf[0] == '1')
323 msgType = CA_MSG_NONCONFIRM;
327 CAToken_t token = NULL;
328 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
330 res = CAGenerateToken(&token, tokenLength);
331 if (res != CA_STATUS_OK || (!token))
333 Serial.println("token error");
337 Serial.println(token);
338 CAInfo_t requestData = {CA_MSG_RESET};
339 requestData.token = token;
340 requestData.tokenLength = tokenLength;
341 requestData.payload = (CAPayload_t)"Json Payload";
343 requestData.type = msgType;
344 requestData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1);
345 strcpy(requestData.resourceUri, resourceUri);
347 CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
348 requestInfo.method = CA_GET;
349 requestInfo.isMulticast = false;
350 requestInfo.info = requestData;
353 CASendRequest(endpoint, &requestInfo);
356 CADestroyToken(token);
359 // destroy remote endpoint
360 if (endpoint != NULL)
362 CADestroyEndpoint(endpoint);
365 Serial.println("============");
368 void SendRequestAll()
370 char buf[MAX_BUF_LEN] = {0};
371 char address[MAX_BUF_LEN] = {0};
372 char resourceUri[MAX_BUF_LEN] = {0};
374 CATransportAdapter_t selectedNetwork;
375 selectedNetwork = GetConnectivityType();
377 Serial.println("=========");
378 Serial.println("10.11.12.13:4545/resource_uri ( for IP )");
379 Serial.println("10:11:12:13:45:45/resource_uri ( for BT )");
380 Serial.println("/resource_uri (any adapter)");
381 Serial.println("uri : ");
384 GetData(buf, sizeof(buf), &len);
387 Serial.println("i/p err");
391 if (!ParseData(buf, address, resourceUri))
393 Serial.println("bad uri");
397 // create remote endpoint
398 CAEndpoint_t *endpoint = NULL;
399 CAResult_t res = CACreateEndpoint(CA_DEFAULT_FLAGS, selectedNetwork, address, 0, &endpoint);
401 if (res != CA_STATUS_OK)
403 Serial.println("create remote endpoint error");
404 CADestroyEndpoint(endpoint);
409 CAToken_t token = NULL;
410 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
412 res = CAGenerateToken(&token, tokenLength);
413 if (res != CA_STATUS_OK || (!token))
415 Serial.println("token error");
419 Serial.println(token);
421 CAInfo_t requestData = {CA_MSG_RESET};
422 requestData.token = token;
423 requestData.tokenLength = tokenLength;
424 requestData.payload = "Temp Json Payload";
425 requestData.type = CA_MSG_NONCONFIRM;
426 requestData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1);
427 strcpy(requestData.resourceUri, resourceUri);
429 CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
430 requestInfo.method = CA_GET;
431 requestInfo.isMulticast = true;
432 requestInfo.info = requestData;
435 // CASendRequest(endpoint, &requestInfo);
436 CASendRequest(endpoint, &requestInfo);
440 CADestroyToken(token);
443 // destroy remote endpoint
444 if (endpoint != NULL)
446 CADestroyEndpoint(endpoint);
449 Serial.println("==========");
452 void SendNotification()
454 char buf[MAX_BUF_LEN] = {0};
455 char address[MAX_BUF_LEN] = {0};
456 char resourceUri[MAX_BUF_LEN] = {0};
457 CATransportAdapter_t selectedNetwork;
458 selectedNetwork = GetConnectivityType();
460 Serial.println("============");
461 Serial.println("10.11.12.13:4545/res_uri (for IP)");
462 Serial.println("10:11:12:13:45:45/res_uri (for BT)");
463 Serial.println("uri: ");
466 GetData(buf, sizeof(buf), &len);
469 Serial.println("i/p err");
473 if (!ParseData(buf, address, resourceUri))
475 Serial.println("bad uri");
479 // create remote endpoint
480 CAEndpoint_t *endpoint = NULL;
481 CAResult_t res = CACreateEndpoint(CA_DEFAULT_FLAGS, selectedNetwork, address, 0, &endpoint);
482 if (CA_STATUS_OK != res)
484 Serial.println("Out of memory");
485 CADestroyEndpoint(endpoint);
490 CAToken_t token = NULL;
491 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
493 res = CAGenerateToken(&token, tokenLength);
494 if (res != CA_STATUS_OK || (!token))
496 Serial.println("token error");
500 CAInfo_t respondData = {CA_MSG_NONCONFIRM};
501 respondData.token = token;
502 respondData.tokenLength = tokenLength;
503 respondData.payload = (CAPayload_t)"Notification Data";
504 respondData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1);
505 strcpy(respondData.resourceUri, resourceUri);
507 CAResponseInfo_t responseInfo = {CA_BAD_REQ, {CA_MSG_RESET}};
508 responseInfo.result = CA_CONTENT;
509 responseInfo.info = respondData;
512 CASendNotification(endpoint, &responseInfo);
513 // destroy remote endpoint
514 if (NULL != endpoint)
516 CADestroyEndpoint(endpoint);
519 CADestroyToken(token);
520 Serial.println("============");
525 char buf[MAX_BUF_LEN] = {0};
527 Serial.println("============");
528 Serial.println("Select network");
529 Serial.println("IP: 0");
530 Serial.println("EDR: 1");
531 Serial.println("LE: 2\n");
534 GetData(buf, sizeof(buf), &len);
535 int number = buf[0] - '0';
536 if (0 >= len || number < 0 || number > 3)
538 Serial.println("Wrong i/p. WIFI selected");
547 const char ssid[] = "SSID"; // your network SSID (name)
548 const char pass[] = "SSID_Password"; // your network password
549 int16_t status = WL_IDLE_STATUS; // the Wifi radio's status
551 if (WiFi.status() == WL_NO_SHIELD)
553 Serial.println("ERROR:No Shield");
557 while (status != WL_CONNECTED)
559 Serial.print("connecting: ");
560 Serial.println(ssid);
561 // WiFi.begin api is weird. ssid should also be taken as const char *
562 // Connect to WPA/WPA2 network:
563 status = WiFi.begin((char *)ssid, pass);
565 #elif defined ARDUINOETH
566 // Note: ****Update the MAC address here with your shield's MAC address****
567 uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0E, 0xC4, 0x05};
568 uint8_t error = Ethernet.begin(ETHERNET_MAC);
571 Serial.print("Failed: ");
572 Serial.println(error);
582 g_isLeSelected = true;
586 CASelectNetwork(CATransportAdapter_t(1<<number));
587 Serial.println("============");
590 void UnselectNetwork()
592 char buf[MAX_BUF_LEN] = {0};
594 Serial.println("============");
595 Serial.println("Unselect network");
596 Serial.println("IPv4: 0");
597 Serial.println("EDR: 2");
598 Serial.println("LE: 3\n");
601 GetData(buf, sizeof(buf), &len);
602 int number = buf[0] - '0';
603 Serial.println(number);
604 if (0 >= len || number < 0 || number > 3)
606 Serial.println("Wrong i/p. WIFI selected");
611 g_isLeSelected = false;
613 CAUnSelectNetwork(1 << number);
614 Serial.println("Terminate");
616 Serial.println("============");
622 Serial.println("============");
623 Serial.println("i: Initialize");
624 Serial.println("s: start listening server");
625 Serial.println("d: start discovery server");
626 Serial.println("f: find resource");
627 Serial.println("r: send request");
628 Serial.println("e: send request to all");
629 Serial.println("a: advertise resource");
630 Serial.println("b: send notification");
631 Serial.println("n: select network");
632 Serial.println("x: unselect network");
633 Serial.println("h: handle request response");
634 Serial.println("t: terminate");
635 Serial.println("q: quit");
636 Serial.println("============");
639 void HandleRequestResponse()
641 CAHandleRequestResponse();
644 void RequestHandler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
648 Serial.println("endpoint is NULL!");
654 Serial.println("Request info is NULL!");
658 Serial.println("RAddr: ");
659 Serial.println(object->addr);
660 Serial.println("Port: ");
661 Serial.println(object->port);
662 Serial.println("uri: ");
663 Serial.println(requestInfo->info.resourceUri);
664 Serial.println("data: ");
665 Serial.println(requestInfo->info.payload);
666 Serial.println("Type: ");
667 Serial.println(requestInfo->info.type);
669 if (requestInfo->info.options)
671 uint32_t len = requestInfo->info.numOptions;
673 for (i = 0; i < len; i++)
675 Serial.println("Option:");
677 Serial.println("ID:");
678 Serial.println(requestInfo->info.options[i].optionID);
679 Serial.println("Data:");
680 Serial.println((char*)requestInfo->info.options[i].optionData);
683 Serial.println("send response");
684 SendResponse((CAEndpoint_t *)object, (requestInfo != NULL) ? &requestInfo->info : NULL);
687 void ResponseHandler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
691 Serial.print("uri: ");
692 Serial.println(object->addr);
697 Serial.print("uri: ");
698 Serial.println(responseInfo->info.resourceUri);
699 Serial.print("data: ");
700 Serial.println(responseInfo->info.payload);
701 Serial.print("Type: ");
702 Serial.println(responseInfo->info.type);
703 Serial.print("res result=");
704 Serial.println(responseInfo->result);
708 void ErrorHandler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
710 printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
714 const CAInfo_t *info = &errorInfo->info;
715 printf("Error Handler, ErrorInfo :\n");
716 printf("Error Handler result : %d\n", errorInfo->result);
717 printf("Error Handler token : %s\n", info->token);
718 printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
719 printf("Error Handler type : %d\n", info->type);
720 printf("Error Handler resourceUri : %s\n", info->resourceUri);
721 printf("Error Handler payload : %s\n", info->payload);
723 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
725 printf("CA_ADAPTER_NOT_ENABLED, enable the adapter\n");
727 else if(CA_SEND_FAILED == errorInfo->result)
729 printf("CA_SEND_FAILED, unable to send the message, check parameters\n");
731 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
733 printf("CA_MEMORY_ALLOC_FAILED, insufficient memory\n");
735 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
737 printf("CA_SOCKET_OPERATION_FAILED, socket operation failed\n");
739 else if(CA_STATUS_FAILED == errorInfo->result)
741 printf("CA_STATUS_FAILED, message could not be delivered, internal error\n");
744 printf("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++\n");
749 void SendResponse(CAEndpoint_t *endpoint, const CAInfo_t* info)
751 char buf[MAX_BUF_LEN] = {0};
753 Serial.println("============");
754 Serial.println("Select Message Type");
755 Serial.println("CON: 0");
756 Serial.println("NON: 1");
757 Serial.println("ACK: 2");
758 Serial.println("RESET: 3");
764 GetData(buf, sizeof(buf), &len);
767 messageType = buf[0] - '0';
768 if (messageType >= 0 && messageType <= 3)
773 Serial.println("Invalid type");
779 Serial.println("============");
780 Serial.println("Enter Resp Code:");
781 Serial.println("For Ex: Empty : 0");
782 Serial.println("Success: 200");
783 Serial.println("Created: 201");
784 Serial.println("Deleted: 202");
785 Serial.println("Valid : 203");
786 Serial.println("Changed: 204");
787 Serial.println("Content: 205");
788 Serial.println("BadReq : 400");
789 Serial.println("BadOpt : 402");
790 Serial.println("NotFnd : 404");
791 Serial.println("Internal Srv Err:500");
792 Serial.println("Timeout: 504");
795 GetData(buf, sizeof(buf), &len);
798 respCode = atoi(buf);
799 if (respCode >= 0 && respCode <= 504)
804 Serial.println("Invalid response");
808 CAInfo_t responseData = {CA_MSG_RESET};
809 responseData.type = static_cast<CAMessageType_t>(messageType);
810 responseData.messageId = (info != NULL) ? info->messageId : 0;
813 responseData.token = (info != NULL) ? info->token : NULL;
814 responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
815 responseData.payload = static_cast<CAPayload_t>("response payload");
817 CAResponseInfo_t responseInfo = {CA_BAD_REQ, {CA_MSG_RESET}};
818 responseInfo.result = static_cast<CAResponseResult_t>(respCode);
819 responseInfo.info = responseData;
820 // send request (transportType from remoteEndpoint of request Info)
821 CAResult_t res = CASendResponse(endpoint, &responseInfo);
822 if(res != CA_STATUS_OK)
824 Serial.println("Snd Resp error");
828 Serial.println("Snd Resp success");
831 Serial.println("============");