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 FindResource();
51 static void SendRequest();
52 static void SendRequestAll();
53 static void SendResponse(CARemoteEndpoint_t *endpoint, const CAInfo_t* info);
54 static void AdvertiseResource();
55 static void SendNotification();
56 static void SelectNetwork();
57 static void UnselectNetwork();
58 static void HandleRequestResponse();
60 static void RequestHandler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo);
61 static void ResponseHandler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo);
62 static void ErrorHandler(const CARemoteEndpoint_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 CATransportType_t GetConnectivityType()
102 Serial.println("Select network");
103 Serial.println("IPv4: 0");
104 Serial.println("EDR: 2");
105 Serial.println("LE: 3");
108 GetData(type, sizeof(type), &typeLen);
111 Serial.println("i/p err,default ethernet");
128 Serial.begin (115200);
130 Serial.println("============");
131 Serial.println("CA SAMPLE");
132 Serial.println("============");
138 char buffer[5] = {0};
140 if (Serial.available() > 0)
142 GetData(buffer, sizeof(buffer), &len);
145 Serial.println("i/p err");
148 switch (toupper(buffer[0]))
155 Serial.println("quit");
158 case 'I': // Initialize interface
162 case 'S': // start listening server
163 StartListeningServer();
166 case 'D': // start discovery server
167 StartDiscoveryServer();
170 case 'F': // find resource
174 case 'R': // send request
177 case 'E': //send request to all
180 case 'A': // advertise resource
184 case 'B': // send notification
188 case 'N': // select network
192 case 'X': // unselect network
196 case 'H': // handle request response
197 HandleRequestResponse();
200 case 'T': // handle request response
205 Serial.println("wrong menu");
209 //1:Add check for startserver before calling below api
212 HandleRequestResponse();
219 if(CAInitialize() != CA_STATUS_OK)
221 Serial.println("Initialize failed");
226 CARegisterHandler(RequestHandler, ResponseHandler, ErrorHandler);
229 void StartListeningServer()
231 Serial.println("listening server");
232 CAResult_t ret = CAStartListeningServer();
233 if(ret != CA_STATUS_OK)
235 Serial.print("listening failed: ");
241 void StartDiscoveryServer()
243 Serial.println("discovery server");
244 CAResult_t ret = CAStartDiscoveryServer();
245 if(ret != CA_STATUS_OK)
247 Serial.print("discovery failed: ");
255 char buf[MAX_BUF_LEN] = {0};
256 Serial.println("============");
257 Serial.println("ex) /a/light");
258 Serial.println("uri: ");
260 GetData(buf, sizeof(buf), &len);
263 Serial.println("i/p err");
267 CAToken_t token = NULL;
268 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
270 CAResult_t res = CAGenerateToken(&token, tokenLength);
271 if (res != CA_STATUS_OK || (!token))
273 Serial.println("token error");
277 Serial.print("token:");
278 Serial.println(token);
280 res = CAFindResource(buf, token, tokenLength);
281 if (res != CA_STATUS_OK)
283 Serial.print("find error: ");
288 Serial.println("success: ");
291 CADestroyToken(token);
296 char buf[MAX_BUF_LEN] = {0};
297 CATransportType_t selectedNetwork;
298 selectedNetwork = GetConnectivityType();
300 Serial.println("============");
301 Serial.println("10.11.12.13:4545/res_uri (for IP)");
302 Serial.println("10:11:12:13:45:45/res_uri (for BT)");
303 Serial.println("uri: ");
306 GetData(buf, sizeof(buf), &len);
309 Serial.println("i/p err");
313 // create remote endpoint
314 CARemoteEndpoint_t *endpoint = NULL;
315 CAResult_t res = CACreateRemoteEndpoint(buf,selectedNetwork,&endpoint);
316 if (res != CA_STATUS_OK)
318 Serial.println("Out of memory");
319 CADestroyRemoteEndpoint(endpoint);
323 memset(buf, 0, sizeof(buf));
325 Serial.println("\n=============================================\n");
326 Serial.println("0:CON, 1:NON\n");
327 Serial.println("select message type : ");
328 GetData(buf, sizeof(buf), &len);
329 CAMessageType_t msgType = CA_MSG_CONFIRM;
333 Serial.println("i/p err,default: 0");
335 else if(buf[0] == '1')
337 msgType = CA_MSG_NONCONFIRM;
341 CAToken_t token = NULL;
342 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
344 res = CAGenerateToken(&token, tokenLength);
345 if (res != CA_STATUS_OK || (!token))
347 Serial.println("token error");
351 Serial.println(token);
352 CAInfo_t requestData = {CA_MSG_RESET};
353 requestData.token = token;
354 requestData.tokenLength = tokenLength;
355 requestData.payload = (CAPayload_t)"Json Payload";
357 requestData.type = msgType;
359 CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
360 requestInfo.method = CA_GET;
361 requestInfo.info = requestData;
364 CASendRequest(endpoint, &requestInfo);
367 CADestroyToken(token);
370 // destroy remote endpoint
371 if (endpoint != NULL)
373 CADestroyRemoteEndpoint(endpoint);
376 Serial.println("============");
379 void SendRequestAll()
381 char buf[MAX_BUF_LEN] = {0};
383 CATransportType_t selectedNetwork;
384 selectedNetwork = GetConnectivityType();
386 Serial.println("=========");
387 Serial.println("10.11.12.13:4545/resource_uri ( for IP )");
388 Serial.println("10:11:12:13:45:45/resource_uri ( for BT )");
389 Serial.println("uri : ");
392 GetData(buf, sizeof(buf), &len);
395 Serial.println("i/p err");
399 // create remote endpoint
400 CARemoteEndpoint_t *endpoint = NULL;
401 CAResult_t res = CACreateRemoteEndpoint(buf, selectedNetwork, &endpoint);
403 if (res != CA_STATUS_OK)
405 Serial.println("create remote endpoint error");
406 CADestroyRemoteEndpoint(endpoint);
410 CAGroupEndpoint_t *group = NULL;
411 group = (CAGroupEndpoint_t *)OICMalloc(sizeof(CAGroupEndpoint_t));
412 group->transportType = endpoint->transportType;
413 group->resourceUri = endpoint->resourceUri;
416 CAToken_t token = NULL;
417 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
419 res = CAGenerateToken(&token, tokenLength);
420 if (res != CA_STATUS_OK || (!token))
422 Serial.println("token error");
426 Serial.println(token);
428 CAInfo_t requestData = {CA_MSG_RESET};
429 requestData.token = token;
430 requestData.tokenLength = tokenLength;
431 requestData.payload = "Temp Json Payload";
432 requestData.type = CA_MSG_NONCONFIRM;
434 CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
435 requestInfo.method = CA_GET;
436 requestInfo.info = requestData;
439 // CASendRequest(endpoint, &requestInfo);
440 CASendRequestToAll(group, &requestInfo);
444 CADestroyToken(token);
447 // destroy remote endpoint
448 if (endpoint != NULL)
450 CADestroyRemoteEndpoint(endpoint);
454 Serial.println("==========");
457 void AdvertiseResource()
459 char buf[MAX_BUF_LEN] = {0};
461 Serial.println("============");
462 Serial.println("uri: ");
465 GetData(buf, sizeof(buf), &len);
468 Serial.println("no i/p");
472 int16_t optionNum = 0;
473 char optionData[MAX_OPT_LEN] = {0};
474 char optionNumBuf[2] = {0};
476 Serial.println("Option Num: ");
477 GetData(optionNumBuf, sizeof(optionNumBuf), &len);
480 Serial.println("no i/p,0 option");
484 optionNum = atoi(optionNumBuf);
485 Serial.println(optionNum);
488 CAHeaderOption_t *headerOpt = NULL;
491 headerOpt = (CAHeaderOption_t *) OICCalloc(optionNum, sizeof(CAHeaderOption_t));
492 if (NULL == headerOpt)
494 Serial.println("Out of memory");
500 for (i = 0 ; i < optionNum ; i++)
504 Serial.println("Opt ID:");
505 GetData(getOptionID, sizeof(getOptionID), &len);
508 Serial.println("no i/p");
513 optionID = atoi(getOptionID);
516 memset(optionData, 0, sizeof(optionData));
517 Serial.println("Opt Data:");
518 GetData(optionData, sizeof(optionData), &len);
521 Serial.println("no i/p");
525 headerOpt[i].optionID = optionID;
526 memcpy(headerOpt[i].optionData, optionData, strlen(optionData));
527 Serial.println("ID:");
528 Serial.println(optionID);
529 Serial.println("Data:");
530 Serial.println(optionData);
532 headerOpt[i].optionLength = (uint16_t)strlen(optionData);
535 Serial.println("============");
537 CAToken_t token = NULL;
538 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
540 CAResult_t res = CAGenerateToken(&token, tokenLength);
541 if (res != CA_STATUS_OK || (!token))
543 Serial.println("token error");
547 Serial.println("token");
548 Serial.println(token);
550 CAAdvertiseResource(buf, token, tokenLength, headerOpt, (uint8_t)optionNum);
552 CADestroyToken(token);
555 void SendNotification()
557 char buf[MAX_BUF_LEN] = {0};
558 CATransportType_t selectedNetwork;
559 selectedNetwork = GetConnectivityType();
561 Serial.println("============");
562 Serial.println("10.11.12.13:4545/res_uri (for IP)");
563 Serial.println("10:11:12:13:45:45/res_uri (for BT)");
564 Serial.println("uri: ");
567 GetData(buf, sizeof(buf), &len);
570 Serial.println("i/p err");
574 // create remote endpoint
575 CARemoteEndpoint_t *endpoint = NULL;
576 CAResult_t res = CACreateRemoteEndpoint(buf,selectedNetwork,&endpoint);
577 if (CA_STATUS_OK != res)
579 Serial.println("Out of memory");
580 CADestroyRemoteEndpoint(endpoint);
585 CAToken_t token = NULL;
586 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
588 res = CAGenerateToken(&token, tokenLength);
589 if (res != CA_STATUS_OK || (!token))
591 Serial.println("token error");
595 CAInfo_t respondData = {CA_MSG_NONCONFIRM};
596 respondData.token = token;
597 respondData.tokenLength = tokenLength;
598 respondData.payload = (CAPayload_t)"Notification Data";
600 CAResponseInfo_t responseInfo = {CA_BAD_REQ, {CA_MSG_RESET}};
601 responseInfo.result = CA_SUCCESS;
602 responseInfo.info = respondData;
605 CASendNotification(endpoint, &responseInfo);
606 // destroy remote endpoint
607 if (NULL != endpoint)
609 CADestroyRemoteEndpoint(endpoint);
612 CADestroyToken(token);
613 Serial.println("============");
618 char buf[MAX_BUF_LEN] = {0};
620 Serial.println("============");
621 Serial.println("Select network");
622 Serial.println("IPv4: 0");
623 Serial.println("EDR: 2");
624 Serial.println("LE: 3\n");
627 GetData(buf, sizeof(buf), &len);
628 int number = buf[0] - '0';
629 if (0 >= len || number < 0 || number > 3)
631 Serial.println("Wrong i/p. WIFI selected");
640 const char ssid[] = "SSID"; // your network SSID (name)
641 const char pass[] = "SSID_Password"; // your network password
642 int16_t status = WL_IDLE_STATUS; // the Wifi radio's status
644 if (WiFi.status() == WL_NO_SHIELD)
646 Serial.println("ERROR:No Shield");
650 while (status != WL_CONNECTED)
652 Serial.print("connecting: ");
653 Serial.println(ssid);
654 // WiFi.begin api is weird. ssid should also be taken as const char *
655 // Connect to WPA/WPA2 network:
656 status = WiFi.begin((char *)ssid, pass);
658 #elif defined ARDUINOETH
659 // Note: ****Update the MAC address here with your shield's MAC address****
660 uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0E, 0xC4, 0x05};
661 uint8_t error = Ethernet.begin(ETHERNET_MAC);
664 Serial.print("Failed: ");
665 Serial.println(error);
675 g_isLeSelected = true;
679 CASelectNetwork(CATransportType_t(1<<number));
680 Serial.println("============");
683 void UnselectNetwork()
685 char buf[MAX_BUF_LEN] = {0};
687 Serial.println("============");
688 Serial.println("Unselect network");
689 Serial.println("IPv4: 0");
690 Serial.println("EDR: 2");
691 Serial.println("LE: 3\n");
694 GetData(buf, sizeof(buf), &len);
695 int number = buf[0] - '0';
696 Serial.println(number);
697 if (0 >= len || number < 0 || number > 3)
699 Serial.println("Wrong i/p. WIFI selected");
704 g_isLeSelected = false;
706 CAUnSelectNetwork(1 << number);
707 Serial.println("Terminate");
709 Serial.println("============");
715 Serial.println("============");
716 Serial.println("i: Initialize");
717 Serial.println("s: start listening server");
718 Serial.println("d: start discovery server");
719 Serial.println("f: find resource");
720 Serial.println("r: send request");
721 Serial.println("e: send request to all");
722 Serial.println("a: advertise resource");
723 Serial.println("b: send notification");
724 Serial.println("n: select network");
725 Serial.println("x: unselect network");
726 Serial.println("h: handle request response");
727 Serial.println("t: terminate");
728 Serial.println("q: quit");
729 Serial.println("============");
732 void HandleRequestResponse()
734 CAHandleRequestResponse();
737 void RequestHandler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
741 Serial.println("Remote endpoint is NULL!");
747 Serial.println("Request info is NULL!");
751 Serial.println("uri: ");
752 Serial.println(object->resourceUri);
753 Serial.println("RAddr: ");
754 Serial.println(object->addressInfo.IP.ipAddress);
755 Serial.println("Port: ");
756 Serial.println(object->addressInfo.IP.port);
757 Serial.println("data: ");
758 Serial.println(requestInfo->info.payload);
759 Serial.println("Type: ");
760 Serial.println(requestInfo->info.type);
762 if (requestInfo->info.options)
764 uint32_t len = requestInfo->info.numOptions;
766 for (i = 0; i < len; i++)
768 Serial.println("Option:");
770 Serial.println("ID:");
771 Serial.println(requestInfo->info.options[i].optionID);
772 Serial.println("Data:");
773 Serial.println((char*)requestInfo->info.options[i].optionData);
776 Serial.println("send response");
777 SendResponse((CARemoteEndpoint_t *)object, (requestInfo != NULL) ? &requestInfo->info : NULL);
780 void ResponseHandler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
782 if (object && object->resourceUri)
784 Serial.print("uri: ");
785 Serial.println(object->resourceUri);
790 Serial.print("data: ");
791 Serial.println(responseInfo->info.payload);
792 Serial.print("Type: ");
793 Serial.println(responseInfo->info.type);
794 Serial.print("res result=");
795 Serial.println(responseInfo->result);
799 void ErrorHandler(const CARemoteEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
801 printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
803 if(rep && rep->resourceUri )
805 printf("Error Handler, RemoteEndpoint Info resourceUri : %s\n", rep->resourceUri);
809 printf("Error Handler, RemoteEndpoint is NULL");
814 const CAInfo_t *info = &errorInfo->info;
815 printf("Error Handler, ErrorInfo :\n");
816 printf("Error Handler result : %d\n", errorInfo->result);
817 printf("Error Handler token : %s\n", info->token);
818 printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
819 printf("Error Handler type : %d\n", info->type);
820 printf("Error Handler payload : %s\n", info->payload);
822 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
824 printf("CA_ADAPTER_NOT_ENABLED, enable the adapter\n");
826 else if(CA_SEND_FAILED == errorInfo->result)
828 printf("CA_SEND_FAILED, unable to send the message, check parameters\n");
830 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
832 printf("CA_MEMORY_ALLOC_FAILED, insufficient memory\n");
834 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
836 printf("CA_SOCKET_OPERATION_FAILED, socket operation failed\n");
838 else if(CA_STATUS_FAILED == errorInfo->result)
840 printf("CA_STATUS_FAILED, message could not be delivered, internal error\n");
843 printf("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++\n");
848 void SendResponse(CARemoteEndpoint_t *endpoint, const CAInfo_t* info)
850 char buf[MAX_BUF_LEN] = {0};
852 Serial.println("============");
853 Serial.println("Select Message Type");
854 Serial.println("CON: 0");
855 Serial.println("NON: 1");
856 Serial.println("ACK: 2");
857 Serial.println("RESET: 3");
863 GetData(buf, sizeof(buf), &len);
866 messageType = buf[0] - '0';
867 if (messageType >= 0 && messageType <= 3)
872 Serial.println("Invalid type");
878 Serial.println("============");
879 Serial.println("Enter Resp Code:");
880 Serial.println("For Ex: Empty : 0");
881 Serial.println("Success: 200");
882 Serial.println("Created: 201");
883 Serial.println("Deleted: 202");
884 Serial.println("BadReq : 400");
885 Serial.println("BadOpt : 402");
886 Serial.println("NotFnd : 404");
887 Serial.println("Internal Srv Err:500");
888 Serial.println("Timeout: 504");
891 GetData(buf, sizeof(buf), &len);
894 respCode = atoi(buf);
895 if (respCode >= 0 && respCode <= 504)
900 Serial.println("Invalid response");
904 CAInfo_t responseData = {CA_MSG_RESET};
905 responseData.type = static_cast<CAMessageType_t>(messageType);
906 responseData.messageId = (info != NULL) ? info->messageId : 0;
909 responseData.token = (info != NULL) ? info->token : NULL;
910 responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
911 responseData.payload = static_cast<CAPayload_t>("response payload");
913 CAResponseInfo_t responseInfo = {CA_BAD_REQ, {CA_MSG_RESET}};
914 responseInfo.result = static_cast<CAResponseResult_t>(respCode);
915 responseInfo.info = responseData;
916 // send request (transportType from remoteEndpoint of request Info)
917 CAResult_t res = CASendResponse(endpoint, &responseInfo);
918 if(res != CA_STATUS_OK)
920 Serial.println("Snd Resp error");
924 Serial.println("Snd Resp success");
927 Serial.println("============");