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";
352 requestData.payloadSize = strlen((const char *) requestData.payload);
354 requestData.type = msgType;
355 requestData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1);
356 strcpy(requestData.resourceUri, resourceUri);
358 CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
359 requestInfo.method = CA_GET;
360 requestInfo.isMulticast = false;
361 requestInfo.info = requestData;
362 requestInfo.isMulticast = false;
365 CASendRequest(endpoint, &requestInfo);
368 CADestroyToken(token);
371 // destroy remote endpoint
372 if (endpoint != NULL)
374 CADestroyEndpoint(endpoint);
377 Serial.println("============");
380 void SendRequestAll()
382 char buf[MAX_BUF_LEN] = {0};
383 char address[MAX_BUF_LEN] = {0};
384 char resourceUri[MAX_BUF_LEN] = {0};
385 char port[PORT_LENGTH] = {0};
387 CATransportAdapter_t selectedNetwork;
388 selectedNetwork = GetConnectivityType();
390 Serial.println("\n=============================================\n");
391 Serial.println("ex) /a/light\n");
392 Serial.println("resource uri : ");
395 GetData(buf, sizeof(buf), &len);
398 Serial.println("i/p err");
402 if (!ParseData(buf, address, port, resourceUri))
404 Serial.println("bad uri");
408 // create remote endpoint
409 CAEndpoint_t *endpoint = NULL;
410 CAResult_t res = CACreateEndpoint(CA_IPV4, selectedNetwork, address, atoi(port),
413 if (res != CA_STATUS_OK)
415 Serial.println("create remote endpoint error");
416 CADestroyEndpoint(endpoint);
421 CAToken_t token = NULL;
422 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
424 res = CAGenerateToken(&token, tokenLength);
425 if (res != CA_STATUS_OK || (!token))
427 Serial.println("token error");
431 Serial.println(token);
433 CAInfo_t requestData = {CA_MSG_RESET};
434 requestData.token = token;
435 requestData.tokenLength = tokenLength;
436 requestData.payload = (CAPayload_t)"Temp Json Payload";
437 requestData.payloadSize = strlen((const char *) requestData.payload);
438 requestData.type = CA_MSG_NONCONFIRM;
439 requestData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1);
440 strcpy(requestData.resourceUri, resourceUri);
442 CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
443 requestInfo.method = CA_GET;
444 requestInfo.isMulticast = true;
445 requestInfo.info = requestData;
448 CASendRequest(endpoint, &requestInfo);
452 CADestroyToken(token);
455 // destroy remote endpoint
456 if (endpoint != NULL)
458 CADestroyEndpoint(endpoint);
461 Serial.println("==========");
464 void SendNotification()
466 char buf[MAX_BUF_LEN] = {0};
467 char address[MAX_BUF_LEN] = {0};
468 char resourceUri[MAX_BUF_LEN] = {0};
469 char port[PORT_LENGTH] = {0};
470 CATransportAdapter_t selectedNetwork;
471 selectedNetwork = GetConnectivityType();
473 Serial.println("============");
474 Serial.println("10.11.12.13:4545/res_uri (for IP)");
475 Serial.println("10:11:12:13:45:45/res_uri (for BT)");
476 Serial.println("uri: ");
479 GetData(buf, sizeof(buf), &len);
482 Serial.println("i/p err");
486 if (!ParseData(buf, address, port, resourceUri))
488 Serial.println("bad uri");
492 // create remote endpoint
493 CAEndpoint_t *endpoint = NULL;
494 CAResult_t res = CACreateEndpoint(CA_DEFAULT_FLAGS, selectedNetwork, address, atoi(port),
496 if (CA_STATUS_OK != res)
498 Serial.println("Out of memory");
499 CADestroyEndpoint(endpoint);
504 CAToken_t token = NULL;
505 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
507 res = CAGenerateToken(&token, tokenLength);
508 if (res != CA_STATUS_OK || (!token))
510 Serial.println("token error");
514 CAInfo_t respondData = {CA_MSG_NONCONFIRM};
515 respondData.token = token;
516 respondData.tokenLength = tokenLength;
517 respondData.payload = (CAPayload_t)"Notification Data";
518 respondData.payloadSize = strlen((const char *) respondData.payload);
519 respondData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1);
520 strcpy(respondData.resourceUri, resourceUri);
522 CAResponseInfo_t responseInfo = {CA_BAD_REQ, {CA_MSG_RESET}};
523 responseInfo.result = CA_CONTENT;
524 responseInfo.info = respondData;
527 CASendNotification(endpoint, &responseInfo);
528 // destroy remote endpoint
529 if (NULL != endpoint)
531 CADestroyEndpoint(endpoint);
534 CADestroyToken(token);
535 Serial.println("============");
540 char buf[MAX_BUF_LEN] = {0};
542 Serial.println("============");
543 Serial.println("Select network");
544 Serial.println("IP: 0");
545 Serial.println("LE: 1");
546 Serial.println("EDR: 2\n");
549 GetData(buf, sizeof(buf), &len);
550 int number = buf[0] - '0';
551 if (0 >= len || number < 0 || number > 3)
553 Serial.println("Wrong i/p. WIFI selected");
562 const char ssid[] = "SSID"; // your network SSID (name)
563 const char pass[] = "SSID_Password"; // your network password
564 int16_t status = WL_IDLE_STATUS; // the Wifi radio's status
566 if (WiFi.status() == WL_NO_SHIELD)
568 Serial.println("ERROR:No Shield");
572 while (status != WL_CONNECTED)
574 Serial.print("connecting: ");
575 Serial.println(ssid);
576 // WiFi.begin api is weird. ssid should also be taken as const char *
577 // Connect to WPA/WPA2 network:
578 status = WiFi.begin((char *)ssid, pass);
580 #elif defined ARDUINOETH
581 // Note: ****Update the MAC address here with your shield's MAC address****
582 uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0E, 0xC4, 0x05};
583 uint8_t error = Ethernet.begin(ETHERNET_MAC);
586 Serial.print("Failed: ");
587 Serial.println(error);
594 g_isLeSelected = true;
601 CASelectNetwork(CATransportAdapter_t(1<<number));
602 Serial.println("============");
605 void UnselectNetwork()
607 char buf[MAX_BUF_LEN] = {0};
609 Serial.println("============");
610 Serial.println("Unselect network");
611 Serial.println("IPv4: 0");
612 Serial.println("LE: 1");
613 Serial.println("EDR: 2\n");
616 GetData(buf, sizeof(buf), &len);
617 int number = buf[0] - '0';
618 Serial.println(number);
619 if (0 >= len || number < 0 || number > 3)
621 Serial.println("Wrong i/p. WIFI selected");
626 g_isLeSelected = false;
628 CAUnSelectNetwork((CATransportAdapter_t)(1 << number));
629 Serial.println("Terminate");
631 Serial.println("============");
634 void GetNetworkInfo()
636 CAEndpoint_t *tempInfo = NULL;
637 uint32_t tempSize = 0;
638 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
639 if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
641 Serial.println("Network not connected");
645 Serial.println("=========");
646 Serial.print("Network info total size is ");
647 Serial.println(tempSize);
649 for (index = 0; index < tempSize; index++)
651 Serial.print("Type: ");
652 Serial.println(tempInfo[index].adapter);
653 if (CA_ADAPTER_IP == tempInfo[index].adapter)
655 Serial.print("Address: ");
656 Serial.println(tempInfo[index].addr);
657 Serial.print("Port: ");
658 Serial.println(tempInfo[index].port);
662 Serial.println("=======");
668 Serial.println("============");
669 Serial.println("i: Initialize");
670 Serial.println("s: start listening server");
671 Serial.println("d: start discovery server");
672 Serial.println("r: send request");
673 Serial.println("e: send request to all");
674 Serial.println("b: send notification");
675 Serial.println("g: get network info");
676 Serial.println("n: select network");
677 Serial.println("x: unselect network");
678 Serial.println("h: handle request response");
679 Serial.println("t: terminate");
680 Serial.println("q: quit");
681 Serial.println("============");
684 void HandleRequestResponse()
686 CAHandleRequestResponse();
689 void RequestHandler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
693 Serial.println("endpoint is NULL!");
699 Serial.println("Request info is NULL!");
703 Serial.print("RAddr: ");
704 Serial.println(object->addr);
705 Serial.print("Port: ");
706 Serial.println(object->port);
707 Serial.print("uri: ");
708 Serial.println(requestInfo->info.resourceUri);
709 Serial.print("data: ");
710 Serial.println((char*)requestInfo->info.payload);
711 Serial.print("data size: ");
712 Serial.println(requestInfo->info.payloadSize);
713 Serial.print("Type: ");
714 Serial.println(requestInfo->info.type);
716 if (requestInfo->info.options)
718 uint32_t len = requestInfo->info.numOptions;
720 for (i = 0; i < len; i++)
722 Serial.print("Option: ");
724 Serial.print("ID: ");
725 Serial.println(requestInfo->info.options[i].optionID);
726 Serial.print("Data: ");
727 Serial.println((char*)requestInfo->info.options[i].optionData);
730 Serial.println("send response");
731 SendResponse((CAEndpoint_t *)object, (requestInfo != NULL) ? &requestInfo->info : NULL);
734 void ResponseHandler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
738 Serial.print("uri: ");
739 Serial.println(object->addr);
744 Serial.print("uri: ");
745 Serial.println(responseInfo->info.resourceUri);
746 Serial.print("data: ");
747 Serial.println((char*)responseInfo->info.payload);
748 Serial.print("data size: ");
749 Serial.println(responseInfo->info.payloadSize);
750 Serial.print("Type: ");
751 Serial.println(responseInfo->info.type);
752 Serial.print("res result=");
753 Serial.println(responseInfo->result);
757 void ErrorHandler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
759 Serial.println("ErrorInfo");
763 const CAInfo_t *info = &errorInfo->info;
764 Serial.print("result: ");
765 Serial.println(errorInfo->result);
766 Serial.print("token: ");
767 Serial.println(info->token);
768 Serial.print("messageId: ");
769 Serial.println(info->messageId);
770 Serial.print("type: ");
771 Serial.println(info->type);
772 Serial.print("resourceUri: ");
773 Serial.println(info->resourceUri);
774 Serial.print("payload: ");
775 Serial.println((char*)info->payload);
781 void SendResponse(CAEndpoint_t *endpoint, const CAInfo_t* info)
783 char buf[MAX_BUF_LEN] = {0};
785 Serial.println("============");
786 Serial.println("Select Message Type");
787 Serial.println("CON: 0");
788 Serial.println("NON: 1");
789 Serial.println("ACK: 2");
790 Serial.println("RESET: 3");
796 GetData(buf, sizeof(buf), &len);
799 messageType = buf[0] - '0';
800 if (messageType >= 0 && messageType <= 3)
805 Serial.println("Invalid type");
811 Serial.println("============");
812 Serial.println("Enter Resp Code:");
813 Serial.println("For Ex: Empty : 0");
814 Serial.println("Success: 200");
815 Serial.println("Created: 201");
816 Serial.println("Deleted: 202");
817 Serial.println("Valid : 203");
818 Serial.println("Changed: 204");
819 Serial.println("Content: 205");
820 Serial.println("BadReq : 400");
821 Serial.println("BadOpt : 402");
822 Serial.println("NotFnd : 404");
823 Serial.println("Internal Srv Err:500");
824 Serial.println("Timeout: 504");
827 GetData(buf, sizeof(buf), &len);
830 respCode = atoi(buf);
831 if (respCode >= 0 && respCode <= 504)
836 Serial.println("Invalid response");
840 CAInfo_t responseData = {CA_MSG_RESET};
841 responseData.type = static_cast<CAMessageType_t>(messageType);
842 responseData.messageId = (info != NULL) ? info->messageId : 0;
843 responseData.resourceUri = (info != NULL) ? info->resourceUri : 0;
846 responseData.token = (info != NULL) ? info->token : NULL;
847 responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
848 responseData.payload = reinterpret_cast<CAPayload_t>(const_cast<char*>("response payload"));
849 responseData.payloadSize = strlen((const char *) responseData.payload);
851 CAResponseInfo_t responseInfo = {CA_BAD_REQ, {CA_MSG_RESET}};
852 responseInfo.result = static_cast<CAResponseResult_t>(respCode);
853 responseInfo.info = responseData;
854 // send request (transportType from remoteEndpoint of request Info)
855 CAResult_t res = CASendResponse(endpoint, &responseInfo);
856 if(res != CA_STATUS_OK)
858 Serial.println("Snd Resp error");
862 Serial.println("Snd Resp success");
865 Serial.println("============");