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");
344 CADestroyEndpoint(endpoint);
348 Serial.println(token);
349 CAInfo_t requestData = {CA_MSG_RESET};
350 requestData.token = token;
351 requestData.tokenLength = tokenLength;
352 requestData.payload = (CAPayload_t)"Json Payload";
353 requestData.payloadSize = strlen((const char *) requestData.payload);
355 requestData.type = msgType;
356 requestData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1);
357 strcpy(requestData.resourceUri, resourceUri);
359 CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
360 requestInfo.method = CA_GET;
361 requestInfo.isMulticast = false;
362 requestInfo.info = requestData;
363 requestInfo.isMulticast = false;
366 CASendRequest(endpoint, &requestInfo);
369 CADestroyToken(token);
372 // destroy remote endpoint
373 if (endpoint != NULL)
375 CADestroyEndpoint(endpoint);
378 Serial.println("============");
381 void SendRequestAll()
383 char buf[MAX_BUF_LEN] = {0};
384 char address[MAX_BUF_LEN] = {0};
385 char resourceUri[MAX_BUF_LEN] = {0};
386 char port[PORT_LENGTH] = {0};
388 CATransportAdapter_t selectedNetwork;
389 selectedNetwork = GetConnectivityType();
391 Serial.println("\n=============================================\n");
392 Serial.println("ex) /a/light\n");
393 Serial.println("resource uri : ");
396 GetData(buf, sizeof(buf), &len);
399 Serial.println("i/p err");
403 if (!ParseData(buf, address, port, resourceUri))
405 Serial.println("bad uri");
409 // create remote endpoint
410 CAEndpoint_t *endpoint = NULL;
411 CAResult_t res = CACreateEndpoint(CA_IPV4, selectedNetwork, address, atoi(port),
414 if (res != CA_STATUS_OK)
416 Serial.println("create remote endpoint error");
417 CADestroyEndpoint(endpoint);
422 CAToken_t token = NULL;
423 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
425 res = CAGenerateToken(&token, tokenLength);
426 if (res != CA_STATUS_OK || (!token))
428 Serial.println("token error");
429 CADestroyEndpoint(endpoint);
433 Serial.println(token);
435 CAInfo_t requestData = {CA_MSG_RESET};
436 requestData.token = token;
437 requestData.tokenLength = tokenLength;
438 requestData.payload = (CAPayload_t)"Temp Json Payload";
439 requestData.payloadSize = strlen((const char *) requestData.payload);
440 requestData.type = CA_MSG_NONCONFIRM;
441 requestData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1);
442 strcpy(requestData.resourceUri, resourceUri);
444 CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
445 requestInfo.method = CA_GET;
446 requestInfo.isMulticast = true;
447 requestInfo.info = requestData;
450 CASendRequest(endpoint, &requestInfo);
454 CADestroyToken(token);
457 // destroy remote endpoint
458 if (endpoint != NULL)
460 CADestroyEndpoint(endpoint);
463 Serial.println("==========");
466 void SendNotification()
468 char buf[MAX_BUF_LEN] = {0};
469 char address[MAX_BUF_LEN] = {0};
470 char resourceUri[MAX_BUF_LEN] = {0};
471 char port[PORT_LENGTH] = {0};
472 CATransportAdapter_t selectedNetwork;
473 selectedNetwork = GetConnectivityType();
475 Serial.println("============");
476 Serial.println("10.11.12.13:4545/res_uri (for IP)");
477 Serial.println("10:11:12:13:45:45/res_uri (for BT)");
478 Serial.println("uri: ");
481 GetData(buf, sizeof(buf), &len);
484 Serial.println("i/p err");
488 if (!ParseData(buf, address, port, resourceUri))
490 Serial.println("bad uri");
494 // create remote endpoint
495 CAEndpoint_t *endpoint = NULL;
496 CAResult_t res = CACreateEndpoint(CA_DEFAULT_FLAGS, selectedNetwork, address, atoi(port),
498 if (CA_STATUS_OK != res)
500 Serial.println("Out of memory");
501 CADestroyEndpoint(endpoint);
506 CAToken_t token = NULL;
507 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
509 res = CAGenerateToken(&token, tokenLength);
510 if (res != CA_STATUS_OK || (!token))
512 Serial.println("token error");
513 CADestroyEndpoint(endpoint);
517 CAInfo_t requestData = {CA_MSG_NONCONFIRM};
518 requestData.token = token;
519 requestData.tokenLength = tokenLength;
520 requestData.payload = (CAPayload_t)"Notification Data";
521 requestData.payloadSize = strlen((const char *) requestData.payload);
522 requestData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1);
523 strcpy(requestData.resourceUri, resourceUri);
525 CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
526 requestInfo.method = CA_GET;
527 requestInfo.info = requestData;
530 CASendRequest(endpoint, &requestInfo);
531 // destroy remote endpoint
532 if (NULL != endpoint)
534 CADestroyEndpoint(endpoint);
537 CADestroyToken(token);
538 Serial.println("============");
543 char buf[MAX_BUF_LEN] = {0};
545 Serial.println("============");
546 Serial.println("Select network");
547 Serial.println("IP: 0");
548 Serial.println("LE: 1");
549 Serial.println("EDR: 2\n");
552 GetData(buf, sizeof(buf), &len);
553 int number = buf[0] - '0';
554 if (0 >= len || number < 0 || number > 3)
556 Serial.println("Wrong i/p. WIFI selected");
565 const char ssid[] = "SSID"; // your network SSID (name)
566 const char pass[] = "SSID_Password"; // your network password
567 int16_t status = WL_IDLE_STATUS; // the Wifi radio's status
569 if (WiFi.status() == WL_NO_SHIELD)
571 Serial.println("ERROR:No Shield");
575 while (status != WL_CONNECTED)
577 Serial.print("connecting: ");
578 Serial.println(ssid);
579 // WiFi.begin api is weird. ssid should also be taken as const char *
580 // Connect to WPA/WPA2 network:
581 status = WiFi.begin((char *)ssid, pass);
583 #elif defined ARDUINOETH
584 // Note: ****Update the MAC address here with your shield's MAC address****
585 uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0E, 0xC4, 0x05};
586 uint8_t error = Ethernet.begin(ETHERNET_MAC);
589 Serial.print("Failed: ");
590 Serial.println(error);
597 g_isLeSelected = true;
604 CASelectNetwork(CATransportAdapter_t(1<<number));
605 Serial.println("============");
608 void UnselectNetwork()
610 char buf[MAX_BUF_LEN] = {0};
612 Serial.println("============");
613 Serial.println("Unselect network");
614 Serial.println("IPv4: 0");
615 Serial.println("LE: 1");
616 Serial.println("EDR: 2\n");
619 GetData(buf, sizeof(buf), &len);
620 int number = buf[0] - '0';
621 Serial.println(number);
622 if (0 >= len || number < 0 || number > 3)
624 Serial.println("Wrong i/p. WIFI selected");
629 g_isLeSelected = false;
631 CAUnSelectNetwork((CATransportAdapter_t)(1 << number));
632 Serial.println("Terminate");
634 Serial.println("============");
637 void GetNetworkInfo()
639 CAEndpoint_t *tempInfo = NULL;
640 uint32_t tempSize = 0;
641 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
642 if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
644 Serial.println("Network not connected");
648 Serial.println("=========");
649 Serial.print("Network info total size is ");
650 Serial.println(tempSize);
652 for (index = 0; index < tempSize; index++)
654 Serial.print("Type: ");
655 Serial.println(tempInfo[index].adapter);
656 if (CA_ADAPTER_IP == tempInfo[index].adapter)
658 Serial.print("Address: ");
659 Serial.println(tempInfo[index].addr);
660 Serial.print("Port: ");
661 Serial.println(tempInfo[index].port);
665 Serial.println("=======");
671 Serial.println("============");
672 Serial.println("i: Initialize");
673 Serial.println("s: start listening server");
674 Serial.println("d: start discovery server");
675 Serial.println("r: send request");
676 Serial.println("e: send request to all");
677 Serial.println("b: send notification");
678 Serial.println("g: get network info");
679 Serial.println("n: select network");
680 Serial.println("x: unselect network");
681 Serial.println("h: handle request response");
682 Serial.println("t: terminate");
683 Serial.println("q: quit");
684 Serial.println("============");
687 void HandleRequestResponse()
689 CAHandleRequestResponse();
692 void RequestHandler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
696 Serial.println("endpoint is NULL!");
702 Serial.println("Request info is NULL!");
706 Serial.print("RAddr: ");
707 Serial.println(object->addr);
708 Serial.print("Port: ");
709 Serial.println(object->port);
710 Serial.print("uri: ");
711 Serial.println(requestInfo->info.resourceUri);
712 Serial.print("data: ");
713 Serial.println((char*)requestInfo->info.payload);
714 Serial.print("data size: ");
715 Serial.println(requestInfo->info.payloadSize);
716 Serial.print("Type: ");
717 Serial.println(requestInfo->info.type);
719 if (requestInfo->info.options)
721 uint32_t len = requestInfo->info.numOptions;
723 for (i = 0; i < len; i++)
725 Serial.print("Option: ");
727 Serial.print("ID: ");
728 Serial.println(requestInfo->info.options[i].optionID);
729 Serial.print("Data: ");
730 Serial.println((char*)requestInfo->info.options[i].optionData);
733 Serial.println("send response");
734 SendResponse((CAEndpoint_t *)object, (requestInfo != NULL) ? &requestInfo->info : NULL);
737 void ResponseHandler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
741 Serial.print("uri: ");
742 Serial.println(object->addr);
747 Serial.print("uri: ");
748 Serial.println(responseInfo->info.resourceUri);
749 Serial.print("data: ");
750 Serial.println((char*)responseInfo->info.payload);
751 Serial.print("data size: ");
752 Serial.println(responseInfo->info.payloadSize);
753 Serial.print("Type: ");
754 Serial.println(responseInfo->info.type);
755 Serial.print("res result=");
756 Serial.println(responseInfo->result);
760 void ErrorHandler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
762 Serial.println("ErrorInfo");
766 const CAInfo_t *info = &errorInfo->info;
767 Serial.print("result: ");
768 Serial.println(errorInfo->result);
769 Serial.print("token: ");
770 Serial.println(info->token);
771 Serial.print("messageId: ");
772 Serial.println(info->messageId);
773 Serial.print("type: ");
774 Serial.println(info->type);
775 Serial.print("resourceUri: ");
776 Serial.println(info->resourceUri);
777 Serial.print("payload: ");
778 Serial.println((char*)info->payload);
784 void SendResponse(CAEndpoint_t *endpoint, const CAInfo_t* info)
786 char buf[MAX_BUF_LEN] = {0};
788 Serial.println("============");
789 Serial.println("Select Message Type");
790 Serial.println("CON: 0");
791 Serial.println("NON: 1");
792 Serial.println("ACK: 2");
793 Serial.println("RESET: 3");
799 GetData(buf, sizeof(buf), &len);
802 messageType = buf[0] - '0';
803 if (messageType >= 0 && messageType <= 3)
808 Serial.println("Invalid type");
814 Serial.println("============");
815 Serial.println("Enter Resp Code:");
816 Serial.println("For Ex: Empty : 0");
817 Serial.println("Created: 201");
818 Serial.println("Deleted: 202");
819 Serial.println("Valid : 203");
820 Serial.println("Changed: 204");
821 Serial.println("Content: 205");
822 Serial.println("BadReq : 400");
823 Serial.println("BadOpt : 402");
824 Serial.println("NotFnd : 404");
825 Serial.println("Internal Srv Err:500");
826 Serial.println("Timeout: 504");
829 GetData(buf, sizeof(buf), &len);
832 respCode = atoi(buf);
833 if (respCode >= 0 && respCode <= 504)
838 Serial.println("Invalid response");
842 CAInfo_t responseData = {CA_MSG_RESET};
843 responseData.type = static_cast<CAMessageType_t>(messageType);
844 responseData.messageId = (info != NULL) ? info->messageId : 0;
845 responseData.resourceUri = (info != NULL) ? info->resourceUri : 0;
848 responseData.token = (info != NULL) ? info->token : NULL;
849 responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
850 responseData.payload = reinterpret_cast<CAPayload_t>(const_cast<char*>("response payload"));
851 responseData.payloadSize = strlen((const char *) responseData.payload);
853 CAResponseInfo_t responseInfo = {CA_BAD_REQ, {CA_MSG_RESET}};
854 responseInfo.result = static_cast<CAResponseResult_t>(respCode);
855 responseInfo.info = responseData;
856 // send request (transportType from remoteEndpoint of request Info)
857 CAResult_t res = CASendResponse(endpoint, &responseInfo);
858 if(res != CA_STATUS_OK)
860 Serial.println("Snd Resp error");
864 Serial.println("Snd Resp success");
867 Serial.println("============");