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
44 static bool g_isLeSelected = false;
46 static void PrintMenu();
47 static void Process();
48 static void Initialize();
49 static void StartListeningServer();
50 static void StartDiscoveryServer();
51 static void SendRequest();
52 static void SendRequestAll();
53 static void SendResponse(CAEndpoint_t *endpoint, const CAInfo_t* info);
54 static void SendNotification();
55 static void SelectNetwork();
56 static void UnselectNetwork();
57 static void HandleRequestResponse();
58 static void GetNetworkInfo();
60 static void RequestHandler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo);
61 static void ResponseHandler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo);
62 static void ErrorHandler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
63 static void Terminate();
65 void GetData(char *readInput, size_t bufferLength, size_t *dataLength)
67 if (!readInput || bufferLength == 0 || !dataLength)
69 Serial.println("Invalid buffer");
73 while (!Serial.available())
78 while (Serial.available())
81 char c = Serial.read();
82 if ('\n' != c && '\r' != c && len < bufferLength - 1)
92 readInput[len] = '\0';
95 Serial.println(readInput);
99 bool ParseData(char *buf, char *url, char *port, char *resourceUri)
101 char *slash = strchr(buf, '/');
107 strcpy(resourceUri, slash);
109 char *dot = strchr(buf, '.');
110 if (dot && dot < slash)
112 char *colon = strchr(buf, ':');
116 strncpy(port, colon, slash - colon);
117 memmove(port, port+1, strlen(port));
119 if (colon && colon < slash)
121 strncpy(url, buf, colon - buf);
126 strncpy(url, buf, slash - buf);
130 CATransportAdapter_t GetConnectivityType()
133 Serial.println("Select network");
134 Serial.println("IP: 0");
135 Serial.println("GATT (BLE): 1");
136 Serial.println("RFCOMM (EDR): 2");
139 GetData(type, sizeof(type), &typeLen);
142 Serial.println("i/p err,default ethernet");
143 return CA_ADAPTER_IP;
148 return CA_ADAPTER_IP;
150 return CA_ADAPTER_GATT_BTLE;
152 return CA_ADAPTER_RFCOMM_BTEDR;
154 return CA_ADAPTER_IP;
159 Serial.begin (115200);
161 Serial.println("============");
162 Serial.println("CA SAMPLE");
163 Serial.println("============");
169 char buffer[5] = {0};
171 if (Serial.available() > 0)
173 GetData(buffer, sizeof(buffer), &len);
176 Serial.println("i/p err");
179 switch (toupper(buffer[0]))
186 Serial.println("quit");
189 case 'I': // Initialize interface
193 case 'S': // start listening server
194 StartListeningServer();
197 case 'D': // start discovery server
198 StartDiscoveryServer();
201 case 'R': // send request
205 case 'E': //send request to all
208 case 'B': // send notification
211 case 'G': // Get network info
215 case 'N': // select network
219 case 'X': // unselect network
223 case 'H': // handle request response
224 HandleRequestResponse();
227 case 'T': // handle request response
232 Serial.println("wrong menu");
236 //1:Add check for startserver before calling below api
239 HandleRequestResponse();
246 if(CAInitialize() != CA_STATUS_OK)
248 Serial.println("Initialize failed");
253 CARegisterHandler(RequestHandler, ResponseHandler, ErrorHandler);
256 void StartListeningServer()
258 Serial.println("listening server");
259 CAResult_t ret = CAStartListeningServer();
260 if(ret != CA_STATUS_OK)
262 Serial.print("listening failed: ");
268 void StartDiscoveryServer()
270 Serial.println("discovery server");
271 CAResult_t ret = CAStartDiscoveryServer();
272 if(ret != CA_STATUS_OK)
274 Serial.print("discovery failed: ");
282 char buf[MAX_BUF_LEN] = {0};
283 char address[MAX_BUF_LEN] = {0};
284 char resourceUri[MAX_BUF_LEN] = {0};
285 char port[PORT_LENGTH] = {0};
286 CATransportAdapter_t selectedNetwork;
287 selectedNetwork = GetConnectivityType();
289 Serial.println("============");
290 Serial.println("10.11.12.13:4545/res_uri (for IP)");
291 Serial.println("10:11:12:13:45:45/res_uri (for BT)");
292 Serial.println("uri: ");
295 GetData(buf, sizeof(buf), &len);
298 Serial.println("i/p err");
302 if (!ParseData(buf, address, port, resourceUri))
304 Serial.println("bad uri");
308 // create remote endpoint
309 CAEndpoint_t *endpoint = NULL;
310 CAResult_t res = CACreateEndpoint(CA_DEFAULT_FLAGS, selectedNetwork, address, atoi(port),
312 if (res != CA_STATUS_OK)
314 Serial.println("Out of memory");
315 CADestroyEndpoint(endpoint);
319 memset(buf, 0, sizeof(buf));
321 Serial.println("\n=============================================\n");
322 Serial.println("0:CON, 1:NON\n");
323 Serial.println("select message type : ");
324 GetData(buf, sizeof(buf), &len);
325 CAMessageType_t msgType = CA_MSG_CONFIRM;
329 Serial.println("i/p err,default: 0");
331 else if(buf[0] == '1')
333 msgType = CA_MSG_NONCONFIRM;
337 CAToken_t token = NULL;
338 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
340 res = CAGenerateToken(&token, tokenLength);
341 if (res != CA_STATUS_OK || (!token))
343 Serial.println("token error");
347 Serial.println(token);
348 CAInfo_t requestData = {CA_MSG_RESET};
349 requestData.token = token;
350 requestData.tokenLength = tokenLength;
351 requestData.payload = (CAPayload_t)"Json Payload";
353 requestData.type = msgType;
354 requestData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1);
355 strcpy(requestData.resourceUri, resourceUri);
357 CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
358 requestInfo.method = CA_GET;
359 requestInfo.isMulticast = false;
360 requestInfo.info = requestData;
361 requestInfo.isMulticast = false;
364 CASendRequest(endpoint, &requestInfo);
367 CADestroyToken(token);
370 // destroy remote endpoint
371 if (endpoint != NULL)
373 CADestroyEndpoint(endpoint);
376 Serial.println("============");
379 void SendRequestAll()
381 char buf[MAX_BUF_LEN] = {0};
382 char address[MAX_BUF_LEN] = {0};
383 char resourceUri[MAX_BUF_LEN] = {0};
384 char port[PORT_LENGTH] = {0};
386 CATransportAdapter_t selectedNetwork;
387 selectedNetwork = GetConnectivityType();
389 Serial.println("\n=============================================\n");
390 Serial.println("ex) /a/light\n");
391 Serial.println("resource uri : ");
394 GetData(buf, sizeof(buf), &len);
397 Serial.println("i/p err");
401 if (!ParseData(buf, address, port, resourceUri))
403 Serial.println("bad uri");
407 // create remote endpoint
408 CAEndpoint_t *endpoint = NULL;
409 CAResult_t res = CACreateEndpoint(CA_DEFAULT_FLAGS, selectedNetwork, address, atoi(port),
412 if (res != CA_STATUS_OK)
414 Serial.println("create remote endpoint error");
415 CADestroyEndpoint(endpoint);
420 CAToken_t token = NULL;
421 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
423 res = CAGenerateToken(&token, tokenLength);
424 if (res != CA_STATUS_OK || (!token))
426 Serial.println("token error");
430 Serial.println(token);
432 CAInfo_t requestData = {CA_MSG_RESET};
433 requestData.token = token;
434 requestData.tokenLength = tokenLength;
435 requestData.payload = "Temp Json Payload";
436 requestData.type = CA_MSG_NONCONFIRM;
437 requestData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1);
438 strcpy(requestData.resourceUri, resourceUri);
440 CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
441 requestInfo.method = CA_GET;
442 requestInfo.isMulticast = true;
443 requestInfo.info = requestData;
446 CASendRequest(endpoint, &requestInfo);
450 CADestroyToken(token);
453 // destroy remote endpoint
454 if (endpoint != NULL)
456 CADestroyEndpoint(endpoint);
459 Serial.println("==========");
462 void SendNotification()
464 char buf[MAX_BUF_LEN] = {0};
465 char address[MAX_BUF_LEN] = {0};
466 char resourceUri[MAX_BUF_LEN] = {0};
467 char port[PORT_LENGTH] = {0};
468 CATransportAdapter_t selectedNetwork;
469 selectedNetwork = GetConnectivityType();
471 Serial.println("============");
472 Serial.println("10.11.12.13:4545/res_uri (for IP)");
473 Serial.println("10:11:12:13:45:45/res_uri (for BT)");
474 Serial.println("uri: ");
477 GetData(buf, sizeof(buf), &len);
480 Serial.println("i/p err");
484 if (!ParseData(buf, address, port, resourceUri))
486 Serial.println("bad uri");
490 // create remote endpoint
491 CAEndpoint_t *endpoint = NULL;
492 CAResult_t res = CACreateEndpoint(CA_DEFAULT_FLAGS, selectedNetwork, address, atoi(port),
494 if (CA_STATUS_OK != res)
496 Serial.println("Out of memory");
497 CADestroyEndpoint(endpoint);
502 CAToken_t token = NULL;
503 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
505 res = CAGenerateToken(&token, tokenLength);
506 if (res != CA_STATUS_OK || (!token))
508 Serial.println("token error");
512 CAInfo_t respondData = {CA_MSG_NONCONFIRM};
513 respondData.token = token;
514 respondData.tokenLength = tokenLength;
515 respondData.payload = (CAPayload_t)"Notification Data";
516 respondData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1);
517 strcpy(respondData.resourceUri, resourceUri);
519 CAResponseInfo_t responseInfo = {CA_BAD_REQ, {CA_MSG_RESET}};
520 responseInfo.result = CA_CONTENT;
521 responseInfo.info = respondData;
524 CASendNotification(endpoint, &responseInfo);
525 // destroy remote endpoint
526 if (NULL != endpoint)
528 CADestroyEndpoint(endpoint);
531 CADestroyToken(token);
532 Serial.println("============");
537 char buf[MAX_BUF_LEN] = {0};
539 Serial.println("============");
540 Serial.println("Select network");
541 Serial.println("IP: 0");
542 Serial.println("LE: 1");
543 Serial.println("EDR: 2\n");
546 GetData(buf, sizeof(buf), &len);
547 int number = buf[0] - '0';
548 if (0 >= len || number < 0 || number > 3)
550 Serial.println("Wrong i/p. WIFI selected");
559 const char ssid[] = "SSID"; // your network SSID (name)
560 const char pass[] = "SSID_Password"; // your network password
561 int16_t status = WL_IDLE_STATUS; // the Wifi radio's status
563 if (WiFi.status() == WL_NO_SHIELD)
565 Serial.println("ERROR:No Shield");
569 while (status != WL_CONNECTED)
571 Serial.print("connecting: ");
572 Serial.println(ssid);
573 // WiFi.begin api is weird. ssid should also be taken as const char *
574 // Connect to WPA/WPA2 network:
575 status = WiFi.begin((char *)ssid, pass);
577 #elif defined ARDUINOETH
578 // Note: ****Update the MAC address here with your shield's MAC address****
579 uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0E, 0xC4, 0x05};
580 uint8_t error = Ethernet.begin(ETHERNET_MAC);
583 Serial.print("Failed: ");
584 Serial.println(error);
591 g_isLeSelected = true;
598 CASelectNetwork(CATransportAdapter_t(1<<number));
599 Serial.println("============");
602 void UnselectNetwork()
604 char buf[MAX_BUF_LEN] = {0};
606 Serial.println("============");
607 Serial.println("Unselect network");
608 Serial.println("IPv4: 0");
609 Serial.println("LE: 1");
610 Serial.println("EDR: 2\n");
613 GetData(buf, sizeof(buf), &len);
614 int number = buf[0] - '0';
615 Serial.println(number);
616 if (0 >= len || number < 0 || number > 3)
618 Serial.println("Wrong i/p. WIFI selected");
623 g_isLeSelected = false;
625 CAUnSelectNetwork(1 << number);
626 Serial.println("Terminate");
628 Serial.println("============");
631 void GetNetworkInfo()
633 CAEndpoint_t *tempInfo = NULL;
634 uint32_t tempSize = 0;
635 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
636 if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
638 Serial.println("Network not connected");
643 printf("Network info total size is %d\n\n", tempSize);
645 for (index = 0; index < tempSize; index++)
647 Serial.println("Type:");
648 Serial.println(tempInfo[index].adapter);
649 if (CA_ADAPTER_IP == tempInfo[index].adapter)
651 Serial.println("Address:");
652 Serial.println(tempInfo[index].addr);
653 Serial.println("Port:");
654 Serial.println(tempInfo[index].port);
658 Serial.println("=======");
664 Serial.println("============");
665 Serial.println("i: Initialize");
666 Serial.println("s: start listening server");
667 Serial.println("d: start discovery server");
668 Serial.println("r: send request");
669 Serial.println("e: send request to all");
670 Serial.println("b: send notification");
671 Serial.println("g: get network info");
672 Serial.println("n: select network");
673 Serial.println("x: unselect network");
674 Serial.println("h: handle request response");
675 Serial.println("t: terminate");
676 Serial.println("q: quit");
677 Serial.println("============");
680 void HandleRequestResponse()
682 CAHandleRequestResponse();
685 void RequestHandler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
689 Serial.println("endpoint is NULL!");
695 Serial.println("Request info is NULL!");
699 Serial.println("RAddr: ");
700 Serial.println(object->addr);
701 Serial.println("Port: ");
702 Serial.println(object->port);
703 Serial.println("uri: ");
704 Serial.println(requestInfo->info.resourceUri);
705 Serial.println("data: ");
706 Serial.println(requestInfo->info.payload);
707 Serial.println("Type: ");
708 Serial.println(requestInfo->info.type);
710 if (requestInfo->info.options)
712 uint32_t len = requestInfo->info.numOptions;
714 for (i = 0; i < len; i++)
716 Serial.println("Option:");
718 Serial.println("ID:");
719 Serial.println(requestInfo->info.options[i].optionID);
720 Serial.println("Data:");
721 Serial.println((char*)requestInfo->info.options[i].optionData);
724 Serial.println("send response");
725 SendResponse((CAEndpoint_t *)object, (requestInfo != NULL) ? &requestInfo->info : NULL);
728 void ResponseHandler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
732 Serial.print("uri: ");
733 Serial.println(object->addr);
738 Serial.print("uri: ");
739 Serial.println(responseInfo->info.resourceUri);
740 Serial.print("data: ");
741 Serial.println(responseInfo->info.payload);
742 Serial.print("Type: ");
743 Serial.println(responseInfo->info.type);
744 Serial.print("res result=");
745 Serial.println(responseInfo->result);
749 void ErrorHandler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
751 printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
755 const CAInfo_t *info = &errorInfo->info;
756 printf("Error Handler, ErrorInfo :\n");
757 printf("Error Handler result : %d\n", errorInfo->result);
758 printf("Error Handler token : %s\n", info->token);
759 printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
760 printf("Error Handler type : %d\n", info->type);
761 printf("Error Handler resourceUri : %s\n", info->resourceUri);
762 printf("Error Handler payload : %s\n", info->payload);
764 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
766 printf("CA_ADAPTER_NOT_ENABLED, enable the adapter\n");
768 else if(CA_SEND_FAILED == errorInfo->result)
770 printf("CA_SEND_FAILED, unable to send the message, check parameters\n");
772 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
774 printf("CA_MEMORY_ALLOC_FAILED, insufficient memory\n");
776 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
778 printf("CA_SOCKET_OPERATION_FAILED, socket operation failed\n");
780 else if(CA_STATUS_FAILED == errorInfo->result)
782 printf("CA_STATUS_FAILED, message could not be delivered, internal error\n");
785 printf("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++\n");
790 void SendResponse(CAEndpoint_t *endpoint, const CAInfo_t* info)
792 char buf[MAX_BUF_LEN] = {0};
794 Serial.println("============");
795 Serial.println("Select Message Type");
796 Serial.println("CON: 0");
797 Serial.println("NON: 1");
798 Serial.println("ACK: 2");
799 Serial.println("RESET: 3");
805 GetData(buf, sizeof(buf), &len);
808 messageType = buf[0] - '0';
809 if (messageType >= 0 && messageType <= 3)
814 Serial.println("Invalid type");
820 Serial.println("============");
821 Serial.println("Enter Resp Code:");
822 Serial.println("For Ex: Empty : 0");
823 Serial.println("Success: 200");
824 Serial.println("Created: 201");
825 Serial.println("Deleted: 202");
826 Serial.println("Valid : 203");
827 Serial.println("Changed: 204");
828 Serial.println("Content: 205");
829 Serial.println("BadReq : 400");
830 Serial.println("BadOpt : 402");
831 Serial.println("NotFnd : 404");
832 Serial.println("Internal Srv Err:500");
833 Serial.println("Timeout: 504");
836 GetData(buf, sizeof(buf), &len);
839 respCode = atoi(buf);
840 if (respCode >= 0 && respCode <= 504)
845 Serial.println("Invalid response");
849 CAInfo_t responseData = {CA_MSG_RESET};
850 responseData.type = static_cast<CAMessageType_t>(messageType);
851 responseData.messageId = (info != NULL) ? info->messageId : 0;
852 responseData.resourceUri = (info != NULL) ? info->resourceUri : 0;
855 responseData.token = (info != NULL) ? info->token : NULL;
856 responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
857 responseData.payload = static_cast<CAPayload_t>("response payload");
859 CAResponseInfo_t responseInfo = {CA_BAD_REQ, {CA_MSG_RESET}};
860 responseInfo.result = static_cast<CAResponseResult_t>(respCode);
861 responseInfo.info = responseData;
862 // send request (transportType from remoteEndpoint of request Info)
863 CAResult_t res = CASendResponse(endpoint, &responseInfo);
864 if(res != CA_STATUS_OK)
866 Serial.println("Snd Resp error");
870 Serial.println("Snd Resp success");
873 Serial.println("============");