/******************************************************************
-*
-* Copyright 2014 Samsung Electronics All Rights Reserved.
-*
-*
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*
-******************************************************************/
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
-#include <stdlib.h>
+#include <glib.h>
#include <stdio.h>
+#include <stdlib.h>
#include <string.h>
-#include <ctype.h>
-#include <fcntl.h>
-#include <errno.h>
-#include <wifi.h>
-#include <glib.h>
-
+#include <unistd.h>
+#include <stdbool.h>
+#include <pthread.h>
#include "cacommon.h"
-#include "caadapterinterface.h"
-#include "uthreadpool.h"
+#include "cainterface.h"
-#define MOD_NAME "TizenSample"
+#ifdef __WITH_DTLS__
+#include "ocsecurityconfig.h"
+#endif
+/**
+ * @def MAX_BUF_LEN
+ * @brief maximum buffer length
+ */
+#define MAX_BUF_LEN 1024
/**
- * Enable/disable one or more of the following macros to enable/disable
- * functionality of that particular adapter type in the interfacesample.
+ * @def MAX_OPT_LEN
+ * @brief maximum option length
*/
-//#define WIFI_ADAPTER_TEST
-#define BT_ADAPTER_TEST
-//#define BLE_ADAPTER_TEST
-
-#if defined(WIFI_ADAPTER_TEST)
-#include "cawifiadapter.h"
-#include "caethernetadapter.h"
-static u_thread_pool_t gWiFiThreadPool = NULL;
-#elif defined(BT_ADAPTER_TEST)
-#include "caedradapter.h"
-static u_thread_pool_t gBTThreadPool = NULL;
-#elif defined(BLE_ADAPTER_TEST)
-#include "caleadapter.h"
-static u_thread_pool_t gLEThreadPool = NULL;
-#endif
+#define MAX_OPT_LEN 16
-static GMainLoop *mainloop;
-static GIOChannel *channel;
-static guint g_test_io_watch_id;
-static GError *g_err_Sample;
+/**
+ * @def PORT_LENGTH
+ * @brief maximum port length
+ */
+#define PORT_LENGTH 5
-static CALocalConnectivity_t *localWifiEndpoint = NULL;
-//Hardcoded coap data for Test
-static char coapData[500] =
- "{\"oc:\[{href\":\"/a/light\",\"ref\":{\"power\":\"20\",\"state\":\"true\"}}]}";
+/**
+ * @def SECURE_DEFAULT_PORT
+ * @brief default secured port
+ */
+#define SECURE_DEFAULT_PORT 5684
-void testInitializeBTInterface(void);
-void testTerminateBTInterface(void);
-void testInitializeWIFIInterface(void);
-void testTerminateWIFIInterface(void);
-void testInitializeBLEInterface(void);
-void testTerminateBLEInterface(void);
+#define RESOURCE_URI_LENGTH 14
-typedef struct ConnectivityHandlerList
+/**
+ * @def RS_IDENTITY
+ * @brief
+ */
+#define IDENTITY ("1111111111111111")
+/* @def RS_CLIENT_PSK
+ * @brief
+ */
+#define RS_CLIENT_PSK ("AAAAAAAAAAAAAAAA")
+
+static GMainLoop *g_mainloop = NULL;
+pthread_t thread;
+
+int g_received;
+uint16_t g_local_secure_port = SECURE_DEFAULT_PORT;
+CATransportType_t g_selected_nw_type = CA_IPV4;
+const char *MESSAGE_TYPE[] = {"CON", "NON", "ACK", "RESET"};
+
+char get_menu();
+void process();
+CAResult_t get_network_type();
+CAResult_t get_input_data(char *buf, int32_t length);
+
+void start_listening_server();
+void start_discovery_server();
+void find_resource();
+void send_request();
+void send_request_all();
+void send_notification();
+void select_network();
+void unselect_network();
+void handle_request_response();
+void find_fixed_resource();
+void get_network_info();
+
+void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo);
+void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo);
+void error_handler(const CARemoteEndpoint_t *object, const CAErrorInfo_t* errorInfo);
+
+void send_response(const CARemoteEndpoint_t *endpoint, const CAInfo_t *info);
+void get_resource_uri(char *URI, char *resourceURI, int length);
+int get_secure_information(CAPayload_t payLoad);
+
+static CAToken_t g_last_request_token = NULL;
+static const char SECURE_COAPS_PREFIX[] = "coaps://";
+static const char SECURE_INFO_DATA[] =
+ "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
+ "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
+static const char NORMAL_INFO_DATA[] =
+ "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
+ "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
+
+#ifdef __WITH_DTLS__
+static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
+
+void clearDtlsCredentialInfo()
{
- CAConnectivityType_t type;
- CAConnectivityHandler_t handler;
- struct ConnectivityHandlerList *nextHandler;
-} ConnectivityHandlerList;
+ printf("clearDtlsCredentialInfo IN\n");
+ if (pskCredsBlob)
+ {
+ // Initialize sensitive data to zeroes before freeing.
+ if (pskCredsBlob->creds)
+ {
+ memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
+ free(pskCredsBlob->creds);
+ }
-static ConnectivityHandlerList *gConnectivityHandlers = NULL;
+ memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
+ free(pskCredsBlob);
+ pskCredsBlob = NULL;
+ }
+ printf("clearDtlsCredentialInfo OUT\n");
+}
-void initializeThreadPool(CAConnectivityType_t type)
+// Internal API. Invoked by CA stack to retrieve credentials from this module.
+void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
{
-#ifdef BT_ADAPTER_TEST
- if (CA_EDR == type && NULL == gBTThreadPool)
+ printf("CAGetDtlsPskCredentials IN\n");
+
+ if(NULL == credInfo)
{
- if (CA_STATUS_OK != u_thread_pool_init(3, &gBTThreadPool))
- {
- printf("Failed to create thread pool for BT adapter!\n");
- return;
- }
+ printf("Invalid credential container");
+ return;
}
-#endif
-#ifdef WIFI_ADAPTER_TEST
- if (CA_WIFI == type && NULL == gWiFiThreadPool)
+
+ *credInfo = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
+ if (NULL == *credInfo)
{
- if (CA_STATUS_OK != u_thread_pool_init(3, &gWiFiThreadPool))
- {
- printf("Failed to create thread pool for BT adapter!\n");
- return;
- }
+ printf("Failed to allocate credential blob.");
+ return;
}
-#endif
-#ifdef BLE_ADAPTER_TEST
- if (CA_LE == type && NULL == gLEThreadPool)
+
+ int16_t credLen = sizeof(OCDtlsPskCreds) * (pskCredsBlob->num);
+ (*credInfo)->creds = (OCDtlsPskCreds *)malloc(credLen);
+ if (NULL == (*credInfo)->creds)
{
- if (CA_STATUS_OK != u_thread_pool_init(3, &gLEThreadPool))
- {
- printf("Failed to create thread pool for BT adapter!\n");
- return;
- }
+ printf("Failed to allocate credentials.");
+ free(*credInfo);
+ *credInfo = NULL;
+ return;
}
-#endif
-}
+ memcpy((*credInfo)->identity, pskCredsBlob->identity, DTLS_PSK_ID_LEN);
+ (*credInfo)->num = pskCredsBlob->num;
+ memcpy((*credInfo)->creds, pskCredsBlob->creds, credLen);
-void storeInterfaceCallbacks(ConnectivityHandlerList *newHandler)
-{
- printf("storeInterfaceCallbacks Entry in Sample\n");
- newHandler->nextHandler = NULL;
- ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
+ printf("CAGetDtlsPskCredentials OUT\n");
+}
- if (!tempConnectivityHandlers)
+CAResult_t SetCredentials()
+{
+ printf("SetCredentials IN\n");
+ pskCredsBlob = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
+ if (NULL == pskCredsBlob)
{
- gConnectivityHandlers = newHandler;
- printf("storeInterfaceCallbacks Exit in Sample\n");
- return;
+ printf("Memory allocation failed!\n");
+ return CA_MEMORY_ALLOC_FAILED;
}
+ memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
+
+ pskCredsBlob->num = 1;
- while (tempConnectivityHandlers->nextHandler)
+ pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
+ if (NULL == pskCredsBlob->creds)
{
- tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
+ printf("Memory allocation failed!\n");
+ free(pskCredsBlob);
+ return CA_MEMORY_ALLOC_FAILED;
}
- tempConnectivityHandlers->nextHandler = newHandler;
- printf("storeInterfaceCallbacks Exit in Sample\n");
+ memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
+ memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
+
+ printf("SetCredentials OUT\n");
+ return CA_STATUS_OK;
}
+#endif
-void interfaceRegisterCallback(CAConnectivityHandler_t handler,
- CAConnectivityType_t connType)
+void GMainLoopThread()
{
- printf("interfaceRegisterCallback Entry in Sample\n");
- ConnectivityHandlerList *newConnectivityHandler = (ConnectivityHandlerList *) malloc(sizeof(
- ConnectivityHandlerList));
- if (NULL == newConnectivityHandler)
+ g_main_loop_run(g_mainloop);
+}
+
+CAResult_t Initialize()
+{
+ g_mainloop = g_main_loop_new(NULL, FALSE);
+ if(!g_mainloop)
{
- printf("Memory allocation failed\n");
- return;
+ printf("g_main_loop_new failed\n");
+ return CA_STATUS_FAILED;
+ }
+
+ int result = pthread_create(&thread, NULL, (void *) &GMainLoopThread, NULL);
+ if (result < 0)
+ {
+ printf("pthread_create failed in initialize\n");
+ return CA_STATUS_FAILED;
}
- newConnectivityHandler->type = connType;
- newConnectivityHandler->handler = handler;
- storeInterfaceCallbacks(newConnectivityHandler);
- printf("interfaceRegisterCallback Exit in Sample\n");
+ CAResult_t res = CAInitialize();
+ if (res != CA_STATUS_OK)
+ {
+ printf("CAInitialize fail\n");
+ }
+ return res;
}
-void networkPacketHandler(CARemoteEndpoint_t *object, void *data, uint32_t dataLength)
+int main()
{
- printf("networkPacketHandler Entry in Sample\n");
- if (object == NULL || data == NULL)
+ int ret = system("clear");
+ // shell invoke error: 127, others: -1
+ if (127 == ret || -1 == ret)
{
- printf("NULL Object\n");
- return;
+ printf("Terminal Clear Error: %d\n", ret);
}
- printf("Data Received from: ");
- if (CA_EDR == object->connectivityType)
+ printf("=============================================\n");
+ printf("\t\tsample main\n");
+ printf("=============================================\n");
+
+ CAResult_t res = Initialize();
+ if (CA_STATUS_OK != res)
{
- printf(object->addressInfo.BT.btMacAddress);
+ printf("Initialization is failed\n");
+ return -1;
}
- else if (CA_LE == object->connectivityType)
+
+ /*
+ * Read DTLS PSK credentials from persistent storage and
+ * set in the OC stack.
+ */
+#ifdef __WITH_DTLS__
+ res = SetCredentials();
+ if (CA_STATUS_OK != res)
{
- printf(object->addressInfo.LE.leMacAddress);
+ printf("SetCredentials failed\n");
+ return -1;
}
- else if (CA_WIFI == object->connectivityType || CA_ETHERNET == object->connectivityType)
+
+ res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
+ if (CA_STATUS_OK != res)
{
- printf(object->addressInfo.IP.ipAddress);
+ printf("Set credential handler fail\n");
+ return -1;
}
+#endif
- printf("\nReceived Data [Length: %d]: %s\n", dataLength, (char *)data);
- printf("networkPacketHandler Exit in Sample\n");
+ // set handler.
+ CARegisterHandler(request_handler, response_handler, error_handler);
+
+ process();
+
+ CADestroyToken(g_last_request_token);
+
+ CATerminate();
+#ifdef __WITH_DTLS__
+ clearDtlsCredentialInfo();
+#endif
+ return 0;
}
-void networkInterfaceCallback(CALocalConnectivity_t *localEndPoint,
- CANetworkStatus_t networkConnectivityState)
+void process()
{
- printf("networkInterfaceCallback Entry in Sample\n");
- if (localEndPoint == NULL)
+ while (1)
{
- printf("NULL Object\n");
- return;
+ char menu = get_menu();
+
+ switch (menu)
+ {
+ case 'm': // menu
+ case 'M':
+ break;
+
+ case 'q': // quit
+ case 'Q':
+ printf("quit..!!\n");
+ return;
+
+ case 's': // start server
+ case 'S':
+ start_listening_server();
+ break;
+
+ case 't': // send request
+ case 'T':
+ send_request_all();
+ break;
+
+ case 'c': // start client
+ case 'C':
+ start_discovery_server();
+ break;
+
+ case 'f': // find resource
+ case 'F':
+ find_resource();
+ break;
+
+ case 'r': // send request
+ case 'R':
+ send_request();
+ break;
+
+ case 'b': // send notification
+ case 'B':
+ send_notification();
+ break;
+
+ case 'n': // select network
+ case 'N':
+ select_network();
+ break;
+
+ case 'x': // unselect network
+ case 'X':
+ unselect_network();
+ break;
+
+ case 'h': // handle request response
+ case 'H':
+ handle_request_response();
+ break;
+
+ case 'y':
+ case 'Y':
+ while (1)
+ {
+ g_received = 0;
+ find_fixed_resource();
+ while (g_received == 0)
+ {
+ sleep(1);
+ handle_request_response();
+
+ }
+ }
+ break;
+
+ case 'w':
+ case 'W':
+ g_received = 0;
+ start_discovery_server();
+ //send_secure_request();
+ while (g_received == 0)
+ {
+ sleep(1);
+ handle_request_response();
+ }
+ break;
+
+ case 'z':
+ case 'Z':
+ start_listening_server();
+ while (1)
+ {
+ sleep(1);
+ handle_request_response();
+ }
+ break;
+
+ case 'g': // get network information
+ case 'G':
+ get_network_info();
+ break;
+
+ default:
+ printf("Not supported menu!!\n");
+ break;
+ }
}
- if (networkConnectivityState == CA_INTERFACE_UP)
+}
+
+void start_listening_server()
+{
+ printf("Start listening server!!\n");
+
+ CAResult_t res = CAStartListeningServer();
+ if (CA_STATUS_OK != res)
{
- printf("Network Status is UP\n");
+ printf("Start listening server fail, error code : %d\n", res);
}
else
{
- printf("Network Status is DOWN\n");
+ printf("Start listening server success\n");
}
+}
- printf("Address: ");
- if (CA_EDR == localEndPoint->type)
- {
- printf("%s\n", localEndPoint->addressInfo.BT.btMacAddress);
- }
- else if (CA_LE == localEndPoint->type)
+void start_discovery_server()
+{
+ printf("Start discovery client!!\n");
+
+ CAResult_t res = CAStartDiscoveryServer();
+ if (CA_STATUS_OK != res)
{
- printf("%s\n", localEndPoint->addressInfo.LE.leMacAddress);
+ printf("Start discovery client fail, error code : %d\n", res);
}
- else if (CA_WIFI == localEndPoint->type || CA_ETHERNET == localEndPoint->type)
+ else
{
- printf("%s\n", localEndPoint->addressInfo.IP.ipAddress);
+ printf("Start discovery client success\n");
}
-
- printf("networkInterfaceCallback Exit in Sample\n");
}
-
-void freeData(void *data)
+void find_fixed_resource()
{
- printf("freeData Entry in Sample\n");
- if (data)
+ // create token
+ CAToken_t token = NULL;
+ uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+ CAResult_t res = CAGenerateToken(&token, tokenLength);
+ if ((CA_STATUS_OK != res) || (!token))
{
- free(data);
+ printf("Token generate error!!");
+ return;
}
- printf("freeData Exit in Sample\n");
-}
-int16_t selectConnectivityType()
-{
- int32_t cType;
- printf("*******Select the Connectivity Type*******\n");
- printf(" [1] WIFI \n");
- printf(" [2] BT \n");
- printf(" [3] BLE \n");
+ printf("Generated token %s\n", token);
+
+ char buf[MAX_BUF_LEN] = { 0 };
+ strcpy(buf, "/a/light");
- fflush(stdin);
- scanf("%d", &cType);
- if (cType < 1 && cType > 3)
+ res = CAFindResource(buf, token, tokenLength);
+ if (CA_STATUS_OK != res)
{
- printf("Invalid Selection!!!!\n");
- return 0;
+ printf("Find resource error : %d\n", res);
}
- return (int16_t)cType;
+ else
+ {
+ printf("Find resource to %s URI\n", buf);
+ }
+
+ // delete token
+ CADestroyToken(token);
+
+ printf("=============================================\n");
}
-int16_t interfaceStartAdapter(CAConnectivityType_t connType)
+void find_resource()
{
- ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
- if (NULL == tempConnectivityHandlers)
+ printf("\n=============================================\n");
+ printf("ex) /a/light\n");
+ printf("reference uri : ");
+
+ char buf[MAX_BUF_LEN] = { 0 };
+ if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
{
- printf("None of the interface is initialized\n");
- return 0;
+ return;
}
- while (tempConnectivityHandlers && tempConnectivityHandlers->type != connType)
+ // create token
+ CAToken_t token = NULL;
+ uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+ CAResult_t res = CAGenerateToken(&token, tokenLength);
+ if ((CA_STATUS_OK != res) || (!token))
{
- tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
+ printf("Token generate error!!\n");
+ return;
}
- if (NULL == tempConnectivityHandlers)
+ printf("Generated token %s\n", token);
+
+ res = CAFindResource(buf, token, tokenLength);
+ if (CA_STATUS_OK != res)
{
- printf( "No interface handler for type %d", connType);
- return 0;
+ printf("Find resource error : %d\n", res);
+ CADestroyToken(token);
}
-
- if (CA_STATUS_OK != tempConnectivityHandlers->handler.startAdapter())
+ else
{
- printf("Failed to Start adapter\n");
- return 0;
+ printf("Find resource to %s URI\n", buf);
+ CADestroyToken(g_last_request_token);
+ g_last_request_token = token;
}
- return 1;
+ printf("=============================================\n");
}
-int16_t interfaceMulticastStartServer(CAConnectivityType_t connType, int serverType)
+void send_request()
{
- printf("interfaceMulticastStartServer Starting...\n");
- ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
- if (NULL == tempConnectivityHandlers)
+ CAResult_t res = get_network_type();
+ if (CA_STATUS_OK != res)
{
- printf("None of the interface is initialized\n");
- return 0;
+ return;
}
- while (tempConnectivityHandlers && tempConnectivityHandlers->type != connType)
+ printf("Do you want to send secure request ?.... enter (0/1): ");
+
+ char secureRequest[MAX_BUF_LEN] = {0};
+ if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN))
{
- tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
+ return;
}
- if (NULL == tempConnectivityHandlers)
+ if (strcmp(secureRequest, "1") == 0)
{
- printf( "No interface handler for type %d", connType);
- return 0;
+ printf("Enter the URI like below....\n");
+ printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
}
-
- CAAdapterStartDiscoveryServer startServer = NULL;
- switch (serverType)
+ else if (strcmp(secureRequest, "0") == 0)
{
- case 1: //Discovery server
- startServer = tempConnectivityHandlers->handler.startDiscoverServer;
- break;
- case 2: //Listening server
- startServer = tempConnectivityHandlers->handler.startListenServer;
- break;
+ printf("Enter the URI like below....\n");
+ printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
+ printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
}
-
- if (startServer)
+ else
{
- printf("Invoking start server method\n");
- startServer();
+ printf("Input data is wrong value\n");
+ return;
}
-}
-int16_t interfaceSendUnicastData(CAConnectivityType_t connType)
-{
- ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
- if (NULL == tempConnectivityHandlers)
+ char uri[MAX_BUF_LEN] = {'\0'};
+ if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
{
- printf(" None of the interface is initialized \n");
- return 0;
+ return;
}
- while (tempConnectivityHandlers && tempConnectivityHandlers->type != connType)
+ // create remote endpoint
+ CARemoteEndpoint_t *endpoint = NULL;
+ res = CACreateRemoteEndpoint(uri, g_selected_nw_type, &endpoint);
+ if (CA_STATUS_OK != res || !endpoint)
{
- tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
+ printf("Failed to create remote endpoint, error code : %d\n", res);
+ return;
}
- if (NULL == tempConnectivityHandlers)
+ printf("\n=============================================\n");
+ printf("0:CON, 1:NON\n");
+ printf("select message type : ");
+
+ char buf[MAX_BUF_LEN] = { 0 };
+ if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
{
- printf( "No interface handler for type %d", connType);
- return 0;
+ CADestroyRemoteEndpoint(endpoint);
+ return;
}
- if (CA_WIFI == connType)
- {
- CARemoteEndpoint_t endpoint;
- char remoteIPAddress[CA_IPADDR_SIZE] = {0};
- printf("\nEnter the Remote Endpoint IP: ");
- scanf("%s", remoteIPAddress);
- if (strlen(remoteIPAddress) == 0)
- {
- printf("Invalid device address\n");
- return;
- }
- endpoint.connectivityType = CA_WIFI;
- strncpy(endpoint.addressInfo.IP.ipAddress, remoteIPAddress, CA_IPADDR_SIZE);
- endpoint.addressInfo.IP.port = 5283; /* Send the corresponding port here */
+ CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0;
- int sdatalen = tempConnectivityHandlers->handler.sendData(&endpoint, coapData,
- strlen(coapData));
- if (sdatalen == strlen(coapData))
- {
- printf("Send Unicast data success\n");
- }
- else
- {
- printf("Send Unicast data failed\n");
- }
- }
- else if (CA_EDR == connType)
- {
- //create endpoint
- CARemoteEndpoint_t endpoint;
+ // create token
+ CAToken_t token = NULL;
+ uint8_t tokenLength = CA_MAX_TOKEN_LEN;
- //Get the device address from user
- char deviceaddress[100] = {0};
- printf("Enter the device address: \n");
- scanf("%s", deviceaddress);
+ res = CAGenerateToken(&token, tokenLength);
+ if ((CA_STATUS_OK != res) || (!token))
+ {
+ printf("Token generate error, error code : %d\n", res);
+ CADestroyRemoteEndpoint(endpoint);
+ return;
+ }
- if (strlen(deviceaddress) == 0)
- {
- printf("Invlaid device address\n");
- return;
- }
+ printf("Generated token %s\n", token);
- endpoint.connectivityType = CA_EDR;
- strncpy(endpoint.addressInfo.BT.btMacAddress, deviceaddress, CA_MACADDR_SIZE - 1);
- endpoint.addressInfo.BT.btMacAddress[CA_MACADDR_SIZE - 1] = '\0';
- endpoint.resourceUri = NULL;
+ // extract relative resourceuri from give uri
+ printf("URI : %s\n", uri);
- printf("Sent Unicast data to device: %s\n", endpoint.addressInfo.BT.btMacAddress);
- tempConnectivityHandlers->handler.sendData(&endpoint, coapData, strlen(coapData) + 1);
- }
- else if (CA_LE == connType)
- {
- //create endpoint
- CARemoteEndpoint_t endpoint;
+ char resourceURI[15] = {0};
+ get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH);
- //Get the device address from user
- char deviceaddress[100] = {0};
- printf("Enter the device address: \n");
- scanf("%s", deviceaddress);
+ // create request data
+ CAInfo_t requestData = { 0 };
+ requestData.token = token;
+ requestData.tokenLength = tokenLength;
- if (strlen(deviceaddress) == 0)
+ if (strcmp(secureRequest, "1") == 0)
+ {
+ uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
+ requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
+ if (NULL == requestData.payload)
{
- printf("Invlaid device address\n");
+ printf("Memory allocation fail\n");
+ CADestroyRemoteEndpoint(endpoint);
+ CADestroyToken(token);
return;
}
-
- //Get the service uuid from user
- char uuid[100] = {0};
- printf("Enter the service uuid: \n");
- scanf("%s", uuid);
-
- if (strlen(uuid) == 0)
+ snprintf(requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_local_secure_port);
+ }
+ else
+ {
+ uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
+ requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
+ if (NULL == requestData.payload)
{
- printf("Invlaid service uuid\n");
+ printf("Memory allocation fail\n");
+ CADestroyRemoteEndpoint(endpoint);
+ CADestroyToken(token);
return;
}
+ snprintf(requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
+ }
+ requestData.type = msgType;
- endpoint.connectivityType = CA_LE;
- strncpy(endpoint.addressInfo.BT.btMacAddress, deviceaddress, CA_MACADDR_SIZE - 1);
- endpoint.addressInfo.BT.btMacAddress[CA_MACADDR_SIZE - 1] = '\0';
- endpoint.resourceUri = strdup(uuid);
+ CARequestInfo_t requestInfo = { 0 };
+ requestInfo.method = CA_GET;
+ requestInfo.info = requestData;
- tempConnectivityHandlers->handler.sendData(&endpoint, coapData, strlen(coapData));
- printf("Sent Unicast data \n");
- free(endpoint.resourceUri);
+ // send request
+ res = CASendRequest(endpoint, &requestInfo);
+ if (CA_STATUS_OK != res)
+ {
+ printf("Could not send request : %d\n", res);
}
- return 1;
+ //destroy token
+ CADestroyToken(token);
+ // destroy remote endpoint
+ CADestroyRemoteEndpoint(endpoint);
+ free(requestData.payload);
+
+
+ printf("=============================================\n");
}
-int16_t interfaceSendMulticastData(CAConnectivityType_t connType)
+void send_request_all()
{
- ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
- if (NULL == tempConnectivityHandlers)
+ CAResult_t res = get_network_type();
+ if (CA_STATUS_OK != res)
{
- printf("None of the interface is initialized\n");
- return 0;
+ return;
}
- while (tempConnectivityHandlers && tempConnectivityHandlers->type != connType)
- {
- tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
- }
+ printf("\n=============================================\n");
+ printf("ex) /a/light\n");
+ printf("resource uri : ");
- if (NULL == tempConnectivityHandlers)
+ char buf[MAX_BUF_LEN] = { 0 };
+ if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
{
- printf( "No interface handler for type %d", connType);
- return 0;
+ return;
}
- if (connType == CA_WIFI)
+ // create remote endpoint
+ CARemoteEndpoint_t *endpoint = NULL;
+ res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint);
+ if (CA_STATUS_OK != res)
{
- tempConnectivityHandlers->handler.sendDataToAll(coapData,
- strlen(coapData) + 1);
+ printf("Create remote endpoint error, error code: %d\n", res);
+ return;
}
- else if (connType == CA_EDR || connType == CA_LE)
+
+ CAGroupEndpoint_t *group = (CAGroupEndpoint_t *) malloc(sizeof(CAGroupEndpoint_t));
+ if (NULL == group)
{
- tempConnectivityHandlers->handler.sendDataToAll(coapData, strlen(coapData));
+ printf("Memory allocation failed!\n");
+ CADestroyRemoteEndpoint(endpoint);
+ return;
}
-}
+ group->transportType = endpoint->transportType;
+ group->resourceUri = endpoint->resourceUri;
-void interfaceReadData(CAConnectivityType_t connType)
-{
- ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
- if (NULL == tempConnectivityHandlers)
+ // create token
+ CAToken_t token = NULL;
+ uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+ res = CAGenerateToken(&token, tokenLength);
+ if ((CA_STATUS_OK != res) || (!token))
{
- printf("None of the interface is initialized\n");
+ printf("Token generate error!!\n");
+ CADestroyRemoteEndpoint(endpoint);
+ free(group);
return;
}
- while (tempConnectivityHandlers && tempConnectivityHandlers->type != connType)
+ printf("generated token %s\n", token);
+
+ CAInfo_t requestData = {CA_MSG_RESET};
+ requestData.token = token;
+ requestData.tokenLength = tokenLength;
+ requestData.payload = "Temp Json Payload";
+ requestData.type = CA_MSG_NONCONFIRM;
+
+ CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
+ requestInfo.method = CA_GET;
+ requestInfo.info = requestData;
+
+ // send request all
+ res = CASendRequestToAll(group, &requestInfo);
+ if (CA_STATUS_OK != res)
{
- tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
+ printf("Could not send request to all\n");
+ CADestroyToken(token);
}
+ else
+ {
+ CADestroyToken(g_last_request_token);
+ g_last_request_token = token;
+ }
+
+ // destroy remote endpoint
+ CADestroyRemoteEndpoint(endpoint);
+ free(group);
- if (NULL == tempConnectivityHandlers)
+ printf("=============================================\n");
+}
+
+void send_notification()
+{
+ CAResult_t res = get_network_type();
+ if (CA_STATUS_OK != res)
{
- printf( "No interface handler for type %d", connType);
return;
}
- if (CA_STATUS_OK != tempConnectivityHandlers->handler.readData())
+ printf("\n=============================================\n");
+ printf("Enter the URI like below....\n");
+ printf("10.11.12.13:4545/resource_uri ( for IP )\n");
+ printf("10:11:12:13:45:45/resource_uri ( for BT )\n");
+ printf("uri : ");
+
+ char buf[MAX_BUF_LEN] = { 0 };
+ if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
{
- printf("Failed to Read Data\n");
return;
}
- printf("Read Data is successfull\n");
- return;
-}
+ printf("\n=============================================\n");
+ printf("\tselect message type\n");
+ printf("CON : 0\n");
+ printf("NON : 1\n");
+ printf("select : ");
-void interfaceGetNetworkInfo(CAConnectivityType_t connType)
-{
- int i = 0;
-
- ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
- if (NULL == tempConnectivityHandlers)
+ char messageTypeBuf[MAX_BUF_LEN] = { 0 };
+ if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN))
{
- printf("None of the interface is initialized\n");
return;
}
- while (tempConnectivityHandlers && tempConnectivityHandlers->type != connType)
+ int messageType = messageTypeBuf[0] - '0';
+
+ switch(messageType)
{
- tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
+ case 0:
+ printf("CONFIRM messagetype is selected\n");
+ break;
+ case 1:
+ printf("NONCONFIRM messagetype is selected\n");
+ break;
+ default:
+ printf("Invalid Selection\n");
+ return;
}
- if (NULL == tempConnectivityHandlers)
+ // create remote endpoint
+ CARemoteEndpoint_t *endpoint = NULL;
+ res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint);
+ if (CA_STATUS_OK != res)
{
- printf( "No interface handler for type %d", connType);
+ printf("Create remote endpoint error, error code: %d\n", res);
return;
}
- //Get the network interface info
- CALocalConnectivity_t *info = NULL;
- uint32_t size = 0;
- if (CA_STATUS_OK != tempConnectivityHandlers->handler.GetnetInfo(&info, &size))
+ // create token
+ CAToken_t token = NULL;
+ uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+ res = CAGenerateToken(&token, tokenLength);
+ if ((CA_STATUS_OK != res) || (!token))
{
- printf("Failed to get network info\n");
+ printf("Token generate error!!\n");
+ CADestroyRemoteEndpoint(endpoint);
return;
}
- if (0 >= size || info == NULL)
+ printf("Generated token %s\n", token);
+
+ CAInfo_t respondData = { 0 };
+ respondData.token = token;
+ respondData.tokenLength = tokenLength;
+ respondData.payload = "Temp Notification Data";
+ respondData.type = messageType;
+
+ CAResponseInfo_t responseInfo = { 0 };
+ responseInfo.result = CA_SUCCESS;
+ responseInfo.info = respondData;
+
+ // send notification
+ res = CASendNotification(endpoint, &responseInfo);
+ if (CA_STATUS_OK != res)
{
- printf("No network found !!!\n");
- return;
+ printf("Send notification error, error code: %d\n", res);
}
-
- printf("Network Information: \n");
- for (; i < size; i++)
+ else
{
- if (connType == CA_WIFI)
- {
- printf("Type : %s\n", (connType == CA_ETHERNET) ? "CA_ETHERNET" : "CA_WIFI");
- printf("Address : %s\n", info[i].addressInfo.IP.ipAddress);
- }
- else
- {
- printf("Type : %s\n", (connType == CA_EDR) ? "CA_EDR" : "CA_LE");
- printf("Address : %s\n\n", info[i].addressInfo.BT.btMacAddress);
- }
+ printf("Send notification success\n");
}
+
+ // destroy token
+ CADestroyToken(token);
+ // destroy remote endpoint
+ CADestroyRemoteEndpoint(endpoint);
+
+ printf("\n=============================================\n");
}
-int16_t interfaceStopAdapter(CAConnectivityType_t connType)
+void select_network()
{
- ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
- if (NULL == tempConnectivityHandlers)
+ printf("\n=============================================\n");
+ printf("\tselect network\n");
+ printf("IPv4 : 0\n");
+ printf("EDR : 2\n");
+ printf("LE : 3\n");
+ printf("select : ");
+
+ char buf[MAX_BUF_LEN] = { 0 };
+ if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
{
- printf("None of the interface is initialized\n");
- return 0;
+ return;
}
- while (tempConnectivityHandlers && tempConnectivityHandlers->type != connType)
+ int number = buf[0] - '0';
+
+ if (number < 0 || number > 3)
{
- tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
+ printf("Invalid network type\n");
+ return;
}
- if (NULL == tempConnectivityHandlers)
+ CAResult_t res = CASelectNetwork(1 << number);
+ if (CA_STATUS_OK != res)
{
- printf( "No interface handler for type %d", connType);
- return 0;
+ printf("Select network error\n");
+ g_selected_nw_type = 1 << number;
}
-
- if (CA_STATUS_OK != tempConnectivityHandlers->handler.stopAdapter())
+ else
{
- printf("Failed to Stop adapter\n");
- return 0;
+ printf("Select network success\n");
}
- printf("Stopped the adapter\n");
- return 1;
+ printf("=============================================\n");
}
-void testInitializeInterface()
+void unselect_network()
{
- printf("testInitializeInterface Entry\n");
+ printf("\n=============================================\n");
+ printf("\tunselect enabled network\n");
+ printf("IPv4 : 0\n");
+ printf("EDR : 2\n");
+ printf("LE : 3\n");
+ printf("select : ");
- int16_t type = selectConnectivityType();
- if (0 >= type || 3 < type)
+ char buf[MAX_BUF_LEN] = { 0 };
+ if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
{
- printf("Invalid selection...\n");
return;
}
- switch (type)
+ int number = buf[0] - '0';
+
+ if (number < 0 || number > 3)
{
-#ifdef WIFI_ADAPTER_TEST
- case 1: //WIFI
- {
- testInitializeWIFIInterface();
- }
- break;
-#endif
-#ifdef BT_ADAPTER_TEST
- case 2: //BT
- {
- testInitializeBTInterface();
- }
- break;
-#endif
-#ifdef BLE_ADAPTER_TEST
- case 3: //BLE
- {
- testInitializeBLEInterface();
- }
- break;
-#endif
- default:
- printf("Feature is not enabled or not implemented\n");
+ printf("Invalid network type\n");
+ return;
}
-}
-void testTerminateInterface()
-{
- int16_t type = selectConnectivityType();
- if (0 >= type || 3 < type)
+ CAResult_t res = CAUnSelectNetwork(1 << number);
+ if (CA_STATUS_OK != res)
{
- printf("Invalid selection...\n");
- return;
+ printf("Unselect network error\n");
}
+ else
+ {
+ printf("Unselect network success\n");
+ }
+
+ printf("=============================================\n");
+}
+
+char get_menu()
+{
+ printf("\n=============================================\n");
+ printf("\t\tMenu\n");
+ printf("\ts : start server\n");
+ printf("\tc : start client\n");
+ printf("\tf : find resource\n");
+ printf("\tr : send request\n");
+ printf("\tt : send request to all\n");
+ printf("\ta : advertise resource\n");
+ printf("\tb : send notification\n");
+ printf("\tn : select network\n");
+ printf("\tx : unselect network\n");
+ printf("\tg : get network information\n");
+ printf("\th : handle request response\n");
+ printf("\ty : run static client\n");
+ printf("\tz : run static server\n");
+ printf("\tw : send secure request\n");
+ printf("\tq : quit\n");
+ printf("=============================================\n");
+ printf("select : ");
+
+ char buf[MAX_BUF_LEN] = { 0 };
+ if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+ {
+ printf("Failed to get input data\n");
+ }
+
+ return buf[0];
+}
-#ifdef WIFI_ADAPTER_TEST
- if (1 == type) /* WIFI */
+void handle_request_response()
+{
+ printf("Handle_request_response\n");
+
+ CAResult_t res = CAHandleRequestResponse();
+ if (CA_STATUS_OK != res)
{
- testTerminateWIFIInterface();
+ printf("Handle request error, error code: %d\n", res);
}
-#endif
-#ifdef BT_ADAPTER_TEST
- if (2 == type) /*BT*/
+ else
{
- testTerminateBTInterface();
+ printf("Handle request success\n");
}
-#endif
-#ifdef BLE_ADAPTER_TEST
- if (3 == type) /*BLE*/
+}
+
+void get_network_info()
+{
+ CALocalConnectivity_t *tempInfo = NULL;
+ uint32_t tempSize = 0;
+
+ CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
+ if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
{
- testTerminateBLEInterface();
+ printf("Network not connected\n");
+ free(tempInfo);
+ return;
}
-#endif
- ConnectivityHandlerList *currentConnectivityHandler = gConnectivityHandlers;
- ConnectivityHandlerList *prevConnectivityHandler = NULL;
+ printf("################## Network Information #######################\n");
+ printf("Network info total size is %d\n\n", tempSize);
- printf("Linked list delete start\n");
- while (currentConnectivityHandler != NULL)
+ int index;
+ for (index = 0; index < tempSize; index++)
{
- printf("Iterating through the list to find the matching interface\n");
- if (currentConnectivityHandler->type == type)
+ printf("Type: %d\n", tempInfo[index].type);
+ if (CA_IPV4 == tempInfo[index].type)
{
- printf("Matching interface found\n");
- if (prevConnectivityHandler == NULL)
- {
- currentConnectivityHandler = currentConnectivityHandler->nextHandler;
- freeData(gConnectivityHandlers);
- gConnectivityHandlers = NULL;
- printf( "Node deleted with interface type %d", type);
- }
- else
- {
- prevConnectivityHandler->nextHandler = currentConnectivityHandler->nextHandler;
- freeData(currentConnectivityHandler);
- currentConnectivityHandler = prevConnectivityHandler->nextHandler;
- printf( "Node deleted with interface type %d from linked list", type);
- }
+ printf("Address: %s\n", tempInfo[index].addressInfo.IP.ipAddress);
+ printf("Port: %d\n", tempInfo[index].addressInfo.IP.port);
}
- else
+ else if (CA_EDR == tempInfo[index].type)
+ {
+ printf("Address: %s\n", tempInfo[index].addressInfo.BT.btMacAddress);
+ }
+ printf("Secured: %d\n\n", tempInfo[index].isSecured);
+
+ if (tempInfo[index].isSecured)
{
- prevConnectivityHandler = currentConnectivityHandler;
- currentConnectivityHandler = currentConnectivityHandler->nextHandler;
+ g_local_secure_port = tempInfo[index].addressInfo.IP.port;
+ printf("Secured: in global %d\n\n", g_local_secure_port);
}
}
- gConnectivityHandlers = NULL;
- return;
+
+ free(tempInfo);
+ printf("##############################################################");
}
-void testStartAdapter()
+void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
{
- int type = selectConnectivityType();
- if (0 >= type || 3 < type)
+ if (NULL == object || NULL == requestInfo)
{
- printf("Invalid selection...\n");
+ printf("Input parameter is NULL\n");
return;
}
- switch (type)
+ if ((NULL != g_last_request_token) && (NULL != requestInfo->info.token)
+ && (strncmp(g_last_request_token, requestInfo->info.token,
+ requestInfo->info.tokenLength) == 0))
{
-#ifdef WIFI_ADAPTER_TEST
- case 1: //WIFI
- {
- interfaceStartAdapter(CA_WIFI);
- }
- break;
-#endif
-#ifdef BT_ADAPTER_TEST
- case 2: //BT
- {
- interfaceStartAdapter(CA_EDR);
- }
- break;
-#endif
-#ifdef BLE_ADAPTER_TEST
- case 3: //BLE
- {
- interfaceStartAdapter(CA_LE);
- }
- break;
-#endif
- default:
- printf("Feature is not enabled or not implemented\n");
+ printf("Token is same. received request of it's own. skip.. \n");
+ return;
}
-}
-void testStartServer(int serverType)
-{
- int type = selectConnectivityType();
- if (0 >= type || 3 < type)
+ printf("##########received request from remote device #############\n");
+ printf("Uri: %s\n", object->resourceUri);
+ if (CA_IPV4 == object->transportType)
{
- printf("Invalid selection...\n");
- return;
+ printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
+ object->addressInfo.IP.port, object->isSecured);
}
-
- switch (type)
+ else if (CA_EDR == object->transportType)
{
-#ifdef WIFI_ADAPTER_TEST
- case 1: //WIFI
- {
- interfaceMulticastStartServer(CA_WIFI, serverType);
- }
- break;
-#endif
-#ifdef BT_ADAPTER_TEST
- case 2: //BT
- {
- interfaceMulticastStartServer(CA_EDR, serverType);
- }
- break;
-#endif
-#ifdef BLE_ADAPTER_TEST
- case 3: //BLE
- {
- interfaceMulticastStartServer(CA_LE, serverType);
- }
- break;
-#endif
- default:
- printf("Feature is not enabled or not implemented\n");
+ printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress);
}
-}
+ printf("Data: %s\n", requestInfo->info.payload);
+ printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
-void testSendUnicastData()
-{
- int16_t type = selectConnectivityType();
- if (0 >= type || 3 < type)
+ if (requestInfo->info.options)
{
- printf("Invalid selection...\n");
- return;
+ uint32_t len = requestInfo->info.numOptions;
+ uint32_t i;
+ for (i = 0; i < len; i++)
+ {
+ printf("Option %d\n", i + 1);
+ printf("ID : %d\n", requestInfo->info.options[i].optionID);
+ printf("Data[%d]: %s\n", requestInfo->info.options[i].optionLength,
+ requestInfo->info.options[i].optionData);
+ }
}
+ printf("############################################################\n");
- switch (type)
+ //Check if this has secure communication information
+ if (requestInfo->info.payload &&
+ (CA_IPV4 == object->transportType))
{
-#ifdef WIFI_ADAPTER_TEST
- case 1: //WIFI
- {
- interfaceSendUnicastData(CA_WIFI);
- }
- break;
-#endif
-#ifdef BT_ADAPTER_TEST
- case 2: //BT
+ int securePort = get_secure_information(requestInfo->info.payload);
+ if (0 < securePort) //Set the remote endpoint secure details and send response
+ {
+ printf("This is secure resource...\n");
+
+ //length of "coaps://"
+ int length = sizeof(SECURE_COAPS_PREFIX) - 1;
+
+ // length of "ipaddress:port"
+ length += strlen(object->addressInfo.IP.ipAddress) + PORT_LENGTH;
+ length += strlen(object->resourceUri) + 1;
+
+ char *uri = calloc(1, sizeof(char) * length);
+ if (!uri)
{
- interfaceSendUnicastData(CA_EDR);
+ printf("Failed to create new uri\n");
+ return;
}
- break;
-#endif
-#ifdef BLE_ADAPTER_TEST
- case 3: //BLE
+ sprintf(uri, "%s%s:%d/%s", SECURE_COAPS_PREFIX, object->addressInfo.IP.ipAddress,
+ object->addressInfo.IP.port, object->resourceUri);
+
+ CARemoteEndpoint_t *endpoint = NULL;
+ if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, object->transportType, &endpoint))
{
- interfaceSendUnicastData(CA_LE);
+ printf("Failed to create duplicate of remote endpoint!\n");
+ return;
}
- break;
-#endif
- default:
- printf("Feature is not enabled or not implemented\n");
+ endpoint->isSecured = true;
+ object = endpoint;
+
+ free(uri);
+ }
}
+
+ printf("Send response with URI\n");
+ send_response(object, &requestInfo->info);
+
+ g_received = 1;
}
-void testSendMulticastData()
+void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
{
- int16_t type = selectConnectivityType();
- if (0 >= type || 3 < type)
+ printf("##########Received response from remote device #############\n");
+ printf("Uri: %s\n", object->resourceUri);
+ if (CA_IPV4 == object->transportType)
{
- printf("Invalid selection...\n");
- return;
+ printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
+ object->addressInfo.IP.port, object->isSecured);
}
-
- switch (type)
+ else if (CA_EDR == object->transportType)
{
-#ifdef WIFI_ADAPTER_TEST
- case 1: //WIFI
- {
- interfaceSendMulticastData(CA_WIFI);
- }
- break;
-#endif
-#ifdef BT_ADAPTER_TEST
- case 2: //BT
- {
- interfaceSendMulticastData(CA_EDR);
- }
- break;
-#endif
-#ifdef BLE_ADAPTER_TEST
- case 3: //BLE
- {
- interfaceSendMulticastData(CA_LE);
- }
- break;
-#endif
- default:
- printf("Feature is not enabled or not implemented\n");
+ printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress);
}
-}
-
-void testReadData(void)
-{
- int16_t type = selectConnectivityType();
- if (0 >= type || 3 < type)
+ printf("response result : %d\n", responseInfo->result);
+ printf("Data: %s\n", responseInfo->info.payload);
+ printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
+ printf("Token: %s\n", responseInfo->info.token);
+ if (responseInfo->info.options)
{
- printf("Invalid selection...\n");
- return;
+ uint32_t len = responseInfo->info.numOptions;
+ uint32_t i;
+ for (i = 0; i < len; i++)
+ {
+ printf("Option %d\n", i + 1);
+ printf("ID : %d\n", responseInfo->info.options[i].optionID);
+ printf("Data[%d]: %s\n", responseInfo->info.options[i].optionLength,
+ responseInfo->info.options[i].optionData);
+ }
}
+ printf("############################################################\n");
+ g_received = 1;
- switch (type)
+ //Check if this has secure communication information
+ if (responseInfo->info.payload)
{
-#ifdef WIFI_ADAPTER_TEST
- case 1: //WIFI
- {
- interfaceReadData(CA_WIFI);
- }
- break;
-#endif
-#ifdef BT_ADAPTER_TEST
- case 2: //BT
- {
- interfaceReadData(CA_EDR);
- }
- break;
-#endif
-#ifdef BLE_ADAPTER_TEST
- case 3: //BLE
- {
- interfaceReadData(CA_LE);
- }
- break;
-#endif
- default:
- printf("Feature is not enabled or not implemented\n");
+ int securePort = get_secure_information(responseInfo->info.payload);
+ if (0 < securePort) //Set the remote endpoint secure details and send response
+ {
+ printf("This is secure resource...\n");
+ }
}
}
-void testGetNetworkInfo(void)
+void error_handler(const CARemoteEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
{
- int16_t type = selectConnectivityType();
- if (0 >= type || 3 < type)
+ printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
+
+ if(rep && rep->resourceUri )
{
- printf("Invalid selection...\n");
- return;
+ printf("Error Handler, RemoteEndpoint Info resourceUri : %s\n", rep->resourceUri);
+ }
+ else
+ {
+ printf("Error Handler, RemoteEndpoint is NULL");
}
- switch (type)
+ if(errorInfo)
{
-#ifdef WIFI_ADAPTER_TEST
- case 1: //WIFI
- {
- interfaceGetNetworkInfo(CA_WIFI);
- }
- break;
-#endif
-#ifdef BT_ADAPTER_TEST
- case 2: //BT
- {
- interfaceGetNetworkInfo(CA_EDR);
- }
- break;
-#endif
-#ifdef BLE_ADAPTER_TEST
- case 3: //BLE
- {
- interfaceGetNetworkInfo(CA_LE);
- }
- break;
-#endif
- default:
- printf("Feature is not enabled or not implemented\n");
+ const CAInfo_t *info = &errorInfo->info;
+ printf("Error Handler, ErrorInfo :\n");
+ printf("Error Handler result : %d\n", errorInfo->result);
+ printf("Error Handler token : %s\n", info->token);
+ printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
+ printf("Error Handler type : %d\n", info->type);
+ printf("Error Handler payload : %s\n", info->payload);
+
+ if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
+ {
+ printf("CA_ADAPTER_NOT_ENABLED, enable the adapter\n");
+ }
+ else if(CA_SEND_FAILED == errorInfo->result)
+ {
+ printf("CA_SEND_FAILED, unable to send the message, check parameters\n");
+ }
+ else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
+ {
+ printf("CA_MEMORY_ALLOC_FAILED, insufficient memory\n");
+ }
+ else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
+ {
+ printf("CA_SOCKET_OPERATION_FAILED, socket operation failed\n");
+ }
+ else if(CA_STATUS_FAILED == errorInfo->result)
+ {
+ printf("CA_STATUS_FAILED, message could not be delivered, internal error\n");
+ }
}
+ printf("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++\n");
+
+ return;
}
-void testStopAdapter()
+void send_response(const CARemoteEndpoint_t *endpoint, const CAInfo_t *info)
{
- int16_t type = selectConnectivityType();
- if (0 >= type || 3 < type)
+ printf("entering send_response\n");
+
+ printf("\n=============================================\n");
+ printf("\tselect message type\n");
+ printf("CON : 0\n");
+ printf("NON : 1\n");
+ printf("ACK : 2\n");
+ printf("RESET : 3\n");
+ printf("select : ");
+
+ char buf[MAX_BUF_LEN] = { 0 };
+ if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
{
- printf("Invalid selection...\n");
return;
}
- switch (type)
+ int messageType = buf[0] - '0';
+ int responseCode = 0 ;
+ char responseCodeBuf[MAX_BUF_LEN] = { 0 };
+ if (CA_MSG_RESET != messageType)
+ {
+ printf("\n=============================================\n");
+ printf("\tselect response code\n");
+ printf("EMPTY : 0\n");
+ printf("SUCCESS : 200\n");
+ printf("CREATED : 201\n");
+ printf("DELETED : 202\n");
+ printf("BAD_REQ : 400\n");
+ printf("BAD_OPT : 402\n");
+ printf("NOT_FOUND : 404\n");
+ printf("INTERNAL_SERVER_ERROR : 500\n");
+ printf("RETRANSMIT_TIMEOUT : 504\n");
+ printf("select : ");
+
+ if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN))
+ {
+ return;
+ }
+ responseCode = atoi(responseCodeBuf);
+ }
+ CAInfo_t responseData = { 0 };
+ responseData.type = messageType;
+
+ responseData.messageId = (info != NULL) ? info->messageId : 0;
+ if(CA_MSG_RESET != messageType)
{
-#ifdef WIFI_ADAPTER_TEST
- case 1: //WIFI
- {
- interfaceStopAdapter(CA_WIFI);
- }
- break;
-#endif
-#ifdef BT_ADAPTER_TEST
- case 2: //BT
+ responseData.token = (info != NULL) ? info->token : NULL;
+ responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
+
+ if (endpoint->isSecured)
+ {
+ printf("Sending response on secure communication\n");
+
+ uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(endpoint->resourceUri);
+ responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
+ if (NULL == responseData.payload)
{
- interfaceStopAdapter(CA_EDR);
+ printf("Memory allocation fail\n");
+ return;
}
- break;
-#endif
-#ifdef BLE_ADAPTER_TEST
- case 3: //BLE
+ snprintf(responseData.payload, length, SECURE_INFO_DATA, endpoint->resourceUri,
+ g_local_secure_port);
+ }
+ else
+ {
+ printf("Sending response on non-secure communication\n");
+
+ uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(endpoint->resourceUri);
+ responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
+ if (NULL == responseData.payload)
{
- interfaceStopAdapter(CA_LE);
+ printf("Memory allocation fail\n");
+ return;
}
- break;
-#endif
- default:
- printf("Feature is not enabled or not implemented\n");
+ snprintf(responseData.payload, length, NORMAL_INFO_DATA, endpoint->resourceUri);
+ }
}
-}
-#ifdef BT_ADAPTER_TEST
-void testInitializeBTInterface(void)
-{
- printf("Initiazing EDR\n");
-
- printf("Initializing BT Adapter threadpool\n");
- initializeThreadPool(CA_EDR);
+ CAResponseInfo_t responseInfo = { 0 };
+ responseInfo.result = responseCode;
+ responseInfo.info = responseData;
- //Start bluetooth communication adapter
- CAResult_t err = CAInitializeEDR(interfaceRegisterCallback, networkPacketHandler,
- networkInterfaceCallback, gBTThreadPool);
- if (CA_STATUS_OK != err && CA_ADAPTER_NOT_ENABLED != err)
+ // send response (transportType from remoteEndpoint of request Info)
+ CAResult_t res = CASendResponse(endpoint, &responseInfo);
+ if (CA_STATUS_OK != res)
{
- printf("Failed to initialize bluetooth communication adapter!\n");
+ printf("Send response error\n");
+ }
+ else
+ {
+ printf("Send response success\n");
}
-}
-
-void testTerminateBTInterface(void)
-{
- printf("Terminating EDR\n");
-
- //Terminate the Bluetooth communication adapter
- CATerminateEDR();
- printf( "Terminating BT Adapter thread pool");
- u_thread_pool_free(gBTThreadPool);
+ printf("=============================================\n");
}
-#endif //BT_ADAPTER_TEST
-#ifdef WIFI_ADAPTER_TEST
-void testInitializeWIFIInterface(void)
+int get_secure_information(CAPayload_t payLoad)
{
- printf("testInitializeWIFIInterface IN\n");
-
- printf("Initializing WIFI adapter threadpool\n");
- initializeThreadPool(CA_WIFI);
+ printf("Entering get_secure_information\n");
- //Start Wifi communication adapter
- if (0 != CAInitializeWifi(interfaceRegisterCallback, networkPacketHandler,
- networkInterfaceCallback, gWiFiThreadPool))
+ if (!payLoad)
{
- printf("testInitializeWIFIInterface Failed to initialize bluetooth communication adapter\n");
- return;
+ printf("Payload is NULL\n");
+ return -1;
}
- printf("testInitializeWIFIInterface OUT\n");
-}
+ char *subString = NULL;
+ if (NULL == (subString = strstr(payLoad, "\"sec\":1")))
+ {
+ printf("This is not secure resource\n");
+ return -1;
+ }
-void testTerminateWIFIInterface(void)
-{
- printf("testTerminateWIFIInterface IN\n");
+ if (NULL == (subString = strstr(payLoad, "\"port\":")))
+ {
+ printf("This secure resource does not have port information\n");
+ return -1;
+ }
- // Stop if Wifi communication adapter is running
- interfaceStopAdapter(CA_WIFI);
+ char *startPos = strstr(subString, ":");
+ if (!startPos)
+ {
+ printf("Parsing failed !\n");
+ return -1;
+ }
- // Freeing threadpool for wifi communication adapter
- printf( "Terminating WIFI Adapter thread pool");
- u_thread_pool_free(gWiFiThreadPool);
+ char *endPos = strstr(startPos, "}");
+ if (!endPos)
+ {
+ printf("Parsing failed !\n");
+ return -1;
+ }
- //Terminate the Wifi communication adapter
- CATerminateWIfI();
+ if(((endPos - 1) - startPos) > 4)
+ {
+ printf("port length is not proper.Exceeding length 4\n");
+ return -1;
+ }
+ char portStr[4] = {0};
+ memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
- printf("testTerminateWIFIInterface OUT\n");
+ printf("secured port is: %s\n", portStr);
+ return atoi(portStr);
}
-#endif //WIFI_ADAPTER_TEST
-#ifdef BLE_ADAPTER_TEST
-void testInitializeBLEInterface(void)
+void get_resource_uri(char *URI, char *resourceURI, int length)
{
- printf("testInitializeBLEInterface IN\n");
+ char *startPos = URI;
+ char *temp = NULL;
+ if (NULL != (temp = strstr(URI, "://")))
+ {
+ startPos = strchr(temp + 3, '/');
+ if (!startPos)
+ {
+ printf("Resource URI is missing\n");
+ return;
+ }
+ }
- printf("Initializing BLE adapter threadpool\n");
- initializeThreadPool(CA_LE);
+ char *endPos = strchr(startPos, '?');
+ if (!endPos)
+ {
+ endPos = URI + strlen(URI);
+ }
+ endPos -= 1;
- //Start bluetooth communication adapter
- if (0 != CAInitializeLE(interfaceRegisterCallback, networkPacketHandler,
- networkInterfaceCallback, gLEThreadPool))
+ if (endPos - startPos <= length)
{
- printf("testInitializeBLEInterface Failed due to CAInitializeLE\n");
- return;
+ memcpy(resourceURI, startPos + 1, endPos - startPos);
}
- printf("testInitializeBLEInterface OUT\n");
+ printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
}
-void testTerminateBLEInterface(void)
+CAResult_t get_network_type()
{
- printf("testTerminateBLEInterface IN\n");
+ printf("\n=============================================\n");
+ printf("\tselect network type\n");
+ printf("IPv4 : 0\n");
+ printf("BT : 2\n");
+ printf("LE : 3\n");
+ printf("select : ");
- //Terminate the BLE server & Client
- CATerminateLE();
+ char buf[MAX_BUF_LEN] = { 0 };
+ if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+ {
+ return CA_NOT_SUPPORTED ;
+ }
- printf( "Terminating BLE Adapter thread pool");
- u_thread_pool_free(gLEThreadPool);
+ int number = buf[0] - '0';
+ number = (number < 0 || number > 3) ? 0 : 1 << number;
- printf("testTerminateBLEInterface OUT\n");
-}
-#endif //BLE_ADAPTER_TEST
+ if (!(number & 0xf))
+ {
+ return CA_NOT_SUPPORTED;
+ }
+ if (number & CA_IPV4)
+ {
+ g_selected_nw_type = CA_IPV4;
+ return CA_STATUS_OK;
+ }
+ if (number & CA_EDR)
+ {
+ g_selected_nw_type = CA_EDR;
+ return CA_STATUS_OK;
+ }
+ if (number & CA_LE)
+ {
+ g_selected_nw_type = CA_LE;
+ return CA_STATUS_OK;
+ }
-static void testPrintHelp(void)
-{
- printf(" =====================================================================\n");
- printf("| Welcome to Connectivity Abstraction |\n");
- printf("| - CA Unit Test v1.0 - |\n");
- printf("|---------------------------------------------------------------------|\n");
- printf("| ** Options ** |\n");
- printf("| i - Initialize the Interface |\n");
- printf("| d - Terminate the Interface |\n");
- printf("| a - Start adapter |\n");
- printf("| b - Stop adapter |\n");
- printf("| sd- Start Discovery Server |\n");
- printf("| sl- Start Listening Server |\n");
- printf("| u - Send Unicast Data |\n");
- printf("| m - Send Multicast Data |\n");
- printf("| g - Get Network Info |\n");
- printf("| r - Read data synchronously |\n");
- printf("| x - quit the test. |\n");
- printf("| h - Help menu. |\n");
- printf(" =====================================================================\n");
+ printf("\n=============================================\n");
+
+ return CA_STATUS_FAILED;
}
-static gboolean testThread(GIOChannel *source, GIOCondition condition , gpointer data)
+CAResult_t get_input_data(char *buf, int32_t length)
{
- gchar buf[10] = {'\0'};
- gsize read = 0;
-
-
- if (g_io_channel_read(channel, buf, 10, &read) != G_IO_ERROR_NONE)
+ if (!fgets(buf, length, stdin))
{
- printf("g_io_channel_read error!!!\n");
- return 1;
+ printf("fgets error\n");
+ return CA_STATUS_FAILED;
}
- buf[read] = '\0';
- g_strstrip(buf);
- /*if ((!has_register) && (((buf[0]!= 'i') && (buf[0]!= 'h') && (buf[0]!= 'q')) || (read != 2))) {
- testPrintHelp();
- printf("***Warning***: You should Register firstly!\n");
- return 1;
- }*/
- switch (buf[0])
+ char *p = NULL;
+ if ((p = strchr(buf, '\n')) != NULL)
{
- case 'i':
- testInitializeInterface();
- break;
- case 'x':
- testTerminateInterface();
- if (g_source_remove(g_test_io_watch_id))
- {
- printf("g_source_remove() OK!!!\n");
- g_io_channel_shutdown(channel, TRUE, &g_err_Sample);
- g_io_channel_unref(channel);
- g_main_loop_quit(mainloop);
- }
- break;
- case 'd':
- testTerminateInterface();
- break;
- case 'a':
- testStartAdapter();
- break;
- case 'b':
- testStopAdapter();
- break;
- case 's':
- if (read == 3)
- {
- if (buf[1] == 'd')
- {
- testStartServer(1);
- }
- if (buf[1] == 'l')
- {
- testStartServer(2);
- }
- }
- break;
- case 'u':
- testSendUnicastData();
- break;
- case 'm':
- testSendMulticastData();
- break;
- case 'r':
- testReadData();
- break;
- case 'g':
- testGetNetworkInfo();
- break;
- case 'h':
- testPrintHelp();
- }
- return 1;
-}
+ *p = '\0';
+ }
-int main(int argc, char *argv[])
-{
- printf("Starting sample\n");
- mainloop = g_main_loop_new(NULL, FALSE);
- channel = g_io_channel_unix_new(0);/* read from stdin */
- g_test_io_watch_id = g_io_add_watch(channel,
- (GIOCondition)(G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL), testThread,
- NULL);
- printf("CM Test Thread created...\n");
- testPrintHelp();
- g_main_loop_run(mainloop);
- return 0;
+ return CA_STATUS_OK;
}
-