BLE implementation for Tizen Platform.
authork.karthick <k.karthick@samsung.com>
Tue, 28 Apr 2015 07:26:51 +0000 (12:56 +0530)
committerErich Keane <erich.keane@intel.com>
Mon, 4 May 2015 16:36:19 +0000 (16:36 +0000)
Typo errors, naming changes and fragmentation logic fixes merged.

Change-Id: I94a508f8367228fd5ecc261307a6ed7cf73be136
Signed-off-by: k.karthick <k.karthick@samsung.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/738
Tested-by: jenkins-iotivity <jenkins-iotivity@opendaylight.org>
Reviewed-by: Erich Keane <erich.keane@intel.com>
14 files changed:
resource/csdk/connectivity/inc/caadapternetdtls.h
resource/csdk/connectivity/inc/caleinterface.h
resource/csdk/connectivity/inc/camsgparser.h
resource/csdk/connectivity/lib/tizen/ble/inc/bluetooth.h
resource/csdk/connectivity/lib/tizen/ble/inc/bluetooth_type.h
resource/csdk/connectivity/samples/tizen/casample.c
resource/csdk/connectivity/src/adapter_util/caadapterutils.c
resource/csdk/connectivity/src/adapter_util/camsgparser.c
resource/csdk/connectivity/src/bt_le_adapter/caleadapter.c
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableclient.c
resource/csdk/connectivity/src/bt_le_adapter/tizen/cablenwmonitor.c
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableserver.c
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableserver.h
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableutil.c

index 3da8fd9..e93259f 100644 (file)
@@ -35,7 +35,7 @@
 /**
  * @brief The implementation will be provided by OIC RI layer.
  */
-extern void OCGetDtlsPskCredentials(OCDtlsPskCredsBlob **credInfo);
+extern void OCGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo);
 
 typedef void (*CAPacketReceivedCallback)(const char *ipAddress, const uint16_t port,
          const void *data, const uint32_t dataLength, const bool isSecured);
index a882bcc..aae6e86 100644 (file)
@@ -118,11 +118,14 @@ void CATerminateLENetworkMonitorMutexVariables();
 
 /**
  * @brief  Provides the BD address of the local adapter.
- * @param  local_address [IN] pointer to the location where bd address needs to be stored.
+ * @param  local_address [OUT] pointer to the location where bd address needs to be stored.
  *
- * @return NONE
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
  */
-void CAGetLEAddress(char **local_address);
+CAResult_t CAGetLEAddress(char **local_address);
 
 /**
  * @brief  Used to start Gatt Server thread for service creation and advertise ble service.
@@ -160,10 +163,24 @@ void CASetBLEReqRespServerCallback(CABLEServerDataReceivedCallback callback);
 
 /**
  * @brief  Used to update characteristics(Read/Write) value that we want to send to particular
- *         client. Both unicast and multicast will use the same api. In mulicast, we will be
- *         sending in loop to all clients.
+ *         client.
+ *
+ * @param  address     [IN] BD address of Gatt client
+ * @param  charValue     [IN] Data that we want to send to client(unicast)
+ * @param  charValueLen  [IN] Length of the data.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAUpdateCharacteristicsToGattClient(const char* address, const char *charValue,
+                                               const uint32_t charValueLen);
+
+/**
+ * @brief  Used to update characteristics(Read/Write) value that we want to multicast to all clients
  *
- * @param  charValue     [IN] Data that we want to send to client(unicast)/clients(multicast)
+ * @param  charValue     [IN] Data that we want to send to clients(multicast)
  * @param  charValueLen  [IN] Length of the data.
  *
  * @return #CA_STATUS_OK or Appropriate error code
@@ -171,7 +188,8 @@ void CASetBLEReqRespServerCallback(CABLEServerDataReceivedCallback callback);
  * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
  * @retval #CA_STATUS_FAILED Operation failed
  */
-CAResult_t CAUpdateCharacteristicsInGattServer(const char *charValue, const uint32_t charValueLen);
+CAResult_t CAUpdateCharacteristicsToAllGattClients(const char *charValue,
+                                                   const uint32_t charValueLen);
 
 /**
  * @brief  Used to start CAStartBleGattClientThread for initializing Gatt Client
@@ -214,7 +232,7 @@ void CATerminateBLEGattClient();
  * @retval #CA_STATUS_FAILED Operation failed
  */
 CAResult_t  CAUpdateCharacteristicsToGattServer(const char *remoteAddress, const char  *data,
-                                                const int32_t dataLen, CALETransferType_t type,
+                                                const uint32_t dataLen, CALETransferType_t type,
                                                 const int32_t position);
 
 /**
@@ -228,7 +246,7 @@ CAResult_t  CAUpdateCharacteristicsToGattServer(const char *remoteAddress, const
  * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
  * @retval #CA_STATUS_FAILED Operation failed
  */
-CAResult_t  CAUpdateCharacteristicsToAllGattServers(const char  *data, int32_t dataLen);
+CAResult_t  CAUpdateCharacteristicsToAllGattServers(const char  *data, uint32_t dataLen);
 
 /**
  * @brief  Used to store upper layer callback locally which will be used to send the data to
index 11fcf33..b932cf0 100644 (file)
@@ -34,7 +34,7 @@
 /**
  * @var MAX_DATA_LENGTH_SUPPORTED
  * @brief From the adapter level, this is the maximum data length is supported
- *           for the data transmission.
+ *        for the data transmission.
  */
 #define MAX_DATA_LENGTH_SUPPORTED 4095
 
 
 #ifdef __TIZEN__
 /**
- *  * @var PLATFORM_IDENTIFIER_BIT
- *   * @brief Reserved bit to differentiating the platform. Currently not in use.
- *    */
+ * @var PLATFORM_IDENTIFIER_BIT
+ * @brief Reserved bit to differentiating the platform. Currently not in use.
+ */
 #define PLATFORM_IDENTIFIER_BIT 1
 
 /**
- *  * @var CA_SUPPORTED_EDR_MTU_SIZE
- *   * @brief The MTU supported from Tizen platform for EDR adapter.
- *    */
+ * @var CA_SUPPORTED_EDR_MTU_SIZE
+ * @brief The MTU supported from Tizen platform for EDR adapter.
+ */
 #define CA_SUPPORTED_EDR_MTU_SIZE  512
 
 /**
- *  * @var CA_SUPPORTED_BLE_MTU_SIZE
- *   * @brief The MTU supported from Tizen platform for LE adapter.
- *    */
+ * @var CA_SUPPORTED_BLE_MTU_SIZE
+ * @brief The MTU supported from Tizen platform for LE adapter.
+ */
 #define CA_SUPPORTED_BLE_MTU_SIZE  200
 
 #elif __ANDROID__
 /**
- *  * @var PLATFORM_IDENTIFIER_BIT
- *   * @brief Reserved bit to differentiating the platform. Currently not in use.
- *    */
+ * @var PLATFORM_IDENTIFIER_BIT
+ * @brief Reserved bit to differentiating the platform. Currently not in use.
+ */
 #define PLATFORM_IDENTIFIER_BIT 0
 
 /**
- *  * @var CA_SUPPORTED_EDR_MTU_SIZE
- *   * @brief The MTU supported from Android platform for EDR adapter.
- *    */
+ * @var CA_SUPPORTED_EDR_MTU_SIZE
+ * @brief The MTU supported from Android platform for EDR adapter.
+ */
 #define CA_SUPPORTED_EDR_MTU_SIZE  200
 
 /**
- *  * @var CA_SUPPORTED_BLE_MTU_SIZE
- *   * @brief The MTU supported from Android platform for LE adapter.
- *    */
+ * @var CA_SUPPORTED_BLE_MTU_SIZE
+ * @brief The MTU supported from Android platform for LE adapter.
+ */
 #define CA_SUPPORTED_BLE_MTU_SIZE  20
 
 #elif __ARDUINO__
 /**
- *  * @var PLATFORM_IDENTIFIER_BIT
- *   * @brief Reserved bit to differentiating the platform. Currently not in use.
- *    */
+ * @var PLATFORM_IDENTIFIER_BIT
+ * @brief Reserved bit to differentiating the platform. Currently not in use.
+ */
 #define PLATFORM_IDENTIFIER_BIT 0
 
 /**
- *  * @var CA_SUPPORTED_EDR_MTU_SIZE
- *   * @brief The MTU supported from Arduino platform for EDR adapter.
- *    */
+ * @var CA_SUPPORTED_EDR_MTU_SIZE
+ * @brief The MTU supported from Arduino platform for EDR adapter.
+ */
 #define CA_SUPPORTED_EDR_MTU_SIZE  200
 
 /**
- *  * @var CA_SUPPORTED_BLE_MTU_SIZE
- *   * @brief The MTU supported from Arduino platform for LE adapter.
- *    */
+ * @var CA_SUPPORTED_BLE_MTU_SIZE
+ * @brief The MTU supported from Arduino platform for LE adapter.
+ */
 #define CA_SUPPORTED_BLE_MTU_SIZE  200
 
 #else //Other Platforms
 /**
- *  * @var PLATFORM_IDENTIFIER_BIT
- *   * @brief Reserved bit to differentiating the platform. Currently not in use.
- *    */
+ * @var PLATFORM_IDENTIFIER_BIT
+ * @brief Reserved bit to differentiating the platform. Currently not in use.
+ */
 #define PLATFORM_IDENTIFIER_BIT 0
 
 /**
- *  * @var CA_SUPPORTED_EDR_MTU_SIZE
- *   * @brief The MTU supported for EDR adapter
- *    */
+ * @var CA_SUPPORTED_EDR_MTU_SIZE
+ * @brief The MTU supported for EDR adapter
+ */
 #define CA_SUPPORTED_EDR_MTU_SIZE  200
 
 /**
- *  * @var CA_SUPPORTED_BLE_MTU_SIZE
- *   * @brief The MTU supported for BLE adapter
- *    */
+ * @var CA_SUPPORTED_BLE_MTU_SIZE
+ * @brief The MTU supported for BLE adapter
+ */
 #define CA_SUPPORTED_BLE_MTU_SIZE  200
 
 #endif
+
 /**
  * @var HEADER_VERSION
  * @brief Current Header version.
index afdec0d..a6574c7 100644 (file)
  * limitations under the License.
  */
 
-/**
- * @file
- *
- * API to control the Bluetooth adapter and devices and communications.
- *
- * @ingroup CAPI_NETWORK_BLUETOOTH_MODULE
- */
 
 #ifndef __TIZEN_NETWORK_BLUETOOTH_H__
 #define __TIZEN_NETWORK_BLUETOOTH_H__
@@ -38,6 +31,13 @@ extern "C"
 #endif /* __cplusplus */
 
 /**
+ * @file        bluetooth.h
+ * @brief       API to control the Bluetooth adapter and devices and communications.
+ * @ingroup     CAPI_NETWORK_BLUETOOTH_MODULE
+ */
+
+
+/**
  * @addtogroup CAPI_NETWORK_BLUETOOTH_MODULE
  * @{
  */
@@ -4213,6 +4213,8 @@ int bt_gatt_register_service(const char *svc_path,
  * @param[in]  char_path       characteristic path registered on the interface.
  * @param[in]  char_value      Gatt characteristic value.
  * @param[in]  value_length    Characteristic value length.
+ * @param[in]  address Remote device address, for which
+ *                       Notification/Indication need to be sent.
  *
  * @return     0 on success, otherwise a negative error value.
  * @retval     #BT_ERROR_NONE  Successful
@@ -4225,7 +4227,8 @@ int bt_gatt_register_service(const char *svc_path,
  * @see  bt_adapter_enable()
  */
 int bt_gatt_update_characteristic(const char *char_path,
-                       const char *char_value, int value_length);
+                       const char *char_value, int value_length,
+                       const char *address);
 /**
  * @internal
  * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
index 8019c36..95d195d 100644 (file)
  * limitations under the License.
  */
 
-/**
- * @file
- *
- * API to control the Bluetooth adapter, devices and communications.
- *
- * @ingroup CAPI_NETWORK_BLUETOOTH_TYPE_MODULE
- */
 
 #ifndef __TIZEN_NETWORK_BLUETOOTH_TYPE_H__
 #define __TIZEN_NETWORK_BLUETOOTH_TYPE_H__
@@ -31,6 +24,13 @@ extern "C"
 #endif /* __cplusplus */
 
 /**
+ * @file bluetooth_type.h
+ * @brief API to control the Bluetooth adapter, devices and communications.
+ * @ingroup     CAPI_NETWORK_BLUETOOTH_TYPE_MODULE
+ */
+
+
+/**
  * @ingroup CAPI_NETWORK_BLUETOOTH_MODULE
  * @brief Enumerations of Bluetooth error codes.
  */
@@ -1451,11 +1451,13 @@ typedef void (*bt_gatt_connection_state_changed_cb)(int result, bool connected,
  * @param[in] char_path Characteristic path for which the value is writtten.
  * @param[in] char_value The characteristic value
  * @param[in] value_length The length of the characteristic value written.
+ * @param[in] remote_address remote client device bd address.
  *
  * @see bt_gatt_connect()
  */
 typedef void (*bt_gatt_remote_characteristic_write_cb) (char *char_path,
                                        unsigned char* char_value, int value_length,
+                                       const char *remote_address,
                                        void *user_data);
 
 /**
index f10c1a3..e863125 100644 (file)
  *
  ******************************************************************/
 
-#include <ctype.h>
-#include <fcntl.h>
-#include <errno.h>
 #include <glib.h>
 #include <stdio.h>
 #include <stdlib.h>
-#include <unistd.h>
 #include <string.h>
+#include <unistd.h>
+#include <stdbool.h>
 #include <pthread.h>
 #include "cacommon.h"
 #include "cainterface.h"
 
-static GMainLoop *mainloop = NULL;
-
-pthread_t thread;
-
+#ifdef __WITH_DTLS__
+#include "ocsecurityconfig.h"
+#endif
+/**
+ * @def MAX_BUF_LEN
+ * @brief maximum buffer length
+ */
 #define MAX_BUF_LEN 1024
+
+/**
+ * @def MAX_OPT_LEN
+ * @brief maximum option length
+ */
 #define MAX_OPT_LEN 16
 
+/**
+ * @def PORT_LENGTH
+ * @brief maximum port length
+ */
+#define PORT_LENGTH 5
+
+/**
+ * @def SECURE_DEFAULT_PORT
+ * @brief default secured port
+ */
+#define SECURE_DEFAULT_PORT 5684
+
+#define RESOURCE_URI_LENGTH 14
 
 /**
  * @def RS_IDENTITY
@@ -48,48 +67,51 @@ pthread_t thread;
  */
 #define RS_CLIENT_PSK   ("AAAAAAAAAAAAAAAA")
 
+static GMainLoop *g_mainloop = NULL;
+pthread_t thread;
 
-int g_received = 0;
-int g_localUnicastPort = 0;
-int g_localSecurePort = 0;
-CAConnectivityType_t g_selectedNwType = CA_ETHERNET;
-const char* g_messageType[] = {"CON", "NON", "ACK", "RESET"};
-
-char PrintOptions();
-void Process();
-CAResult_t GetNetworkType();
-
-CAResult_t Initialize();
-void StartListeningServer();
-void StartDiscoveryServer();
-void FindResource();
-void SendRequest();
-void SendRequestAll();
-void SendResponse();
-void AdvertiseResource();
-void SendNotification();
-void SelectNetwork();
-void UnselectNetwork();
-void HandleRequestResponse();
-void FindFixedResource();
-void GetNetworkInfo();
-
-void RequestHandler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo);
-void ResponseHandler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo);
-void SendRequestTemp(CARemoteEndpoint_t *endpoint, CAToken_t token);
-void GetResourceUri(char *URI, char *resourceURI, int length);
-int GetSecureInformation(CAPayload_t payLoad);
-
-static CAToken_t g_lastRequestToken = NULL;
-static const char g_secureInfoData[] = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
-                                     "\"if\":[\"oc.mi.def\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
-static const char g_normalInfoData[] = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
-                                     "\"if\":[\"oc.mi.def\"],\"obs\":1}}]}";
+int g_received;
+uint16_t g_local_secure_port = SECURE_DEFAULT_PORT;
+CAConnectivityType_t g_selected_nw_type = CA_WIFI;
+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 advertise_resource();
+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 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\":[\"oc.mi.def\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
+static const char NORMAL_INFO_DATA[] =
+    "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
+    "\"if\":[\"oc.mi.def\"],\"obs\":1}}]}";
 
 #ifdef __WITH_DTLS__
 static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
 
-void ClearDtlsCredentialInfo()
+void clearDtlsCredentialInfo()
 {
     printf("clearDtlsCredentialInfo IN\n");
     if (pskCredsBlob)
@@ -108,11 +130,12 @@ void ClearDtlsCredentialInfo()
     printf("clearDtlsCredentialInfo OUT\n");
 }
 
-// Internal API. Invoked by CA stack to retrieve credentials from this module
+// Internal API. Invoked by CA stack to retrieve credentials from this module.
 void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
 {
     printf("CAGetDtlsPskCredentials IN\n");
-    if(!credInfo)
+
+    if(NULL == credInfo)
     {
         printf("Invalid credential container");
         return;
@@ -142,17 +165,17 @@ void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
     printf("CAGetDtlsPskCredentials OUT\n");
 }
 
-bool SetCredentials()
+CAResult_t SetCredentials()
 {
     printf("SetCredentials IN\n");
-    pskCredsBlob = (CADtlsPskCredsBlob_t *)calloc(1, sizeof(CADtlsPskCredsBlob_t));
+    pskCredsBlob = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
     if (NULL == pskCredsBlob)
     {
         printf("Memory allocation failed!\n");
-        return false;
+        return CA_MEMORY_ALLOC_FAILED;
     }
-
     memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
+
     pskCredsBlob->num = 1;
 
     pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
@@ -160,79 +183,105 @@ bool SetCredentials()
     {
         printf("Memory allocation failed!\n");
         free(pskCredsBlob);
-        return false;
+        return CA_MEMORY_ALLOC_FAILED;
     }
 
     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 true;
+    return CA_STATUS_OK;
 }
 #endif
 
-void pthread_func()
+void GMainLoopThread()
+{
+    g_main_loop_run(g_mainloop);
+}
+
+CAResult_t Initialize()
 {
-    g_main_loop_run(mainloop);
+    g_mainloop = g_main_loop_new(NULL, FALSE);
+    if(!g_mainloop)
+    {
+        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;
+    }
+
+    CAResult_t res = CAInitialize();
+    if (res != CA_STATUS_OK)
+    {
+        printf("CAInitialize fail\n");
+    }
+    return res;
 }
 
 int main()
 {
-    system("clear");
+    int ret = system("clear");
+    // shell invoke error: 127, others: -1
+    if (127 == ret || -1 == ret)
+    {
+        printf("Terminal Clear Error: %d\n", ret);
+    }
 
-    printf("\n=============================================\n");
+    printf("=============================================\n");
     printf("\t\tsample main\n");
     printf("=============================================\n");
 
-    CAResult_t res = CA_STATUS_FAILED;
+    CAResult_t res = Initialize();
+    if (CA_STATUS_OK != res)
+    {
+        printf("Initialization is  failed\n");
+        return -1;
+    }
+
     /*
-    * Read DTLS PSK credentials from persistent storage and
-    * set in the OC stack.
-    */
+     * Read DTLS PSK credentials from persistent storage and
+     * set in the OC stack.
+     */
 #ifdef __WITH_DTLS__
-    if (SetCredentials() == false)
+    res = SetCredentials();
+    if (CA_STATUS_OK != res)
     {
         printf("SetCredentials failed\n");
-        return 1;
+        return -1;
     }
 
     res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
-    if(CA_STATUS_OK != res)
+    if (CA_STATUS_OK != res)
     {
         printf("Set credential handler fail\n");
-        return 1;
+        return -1;
     }
 #endif
-    res = Initialize();
-    if (CA_STATUS_OK != res)
-    {
-        printf("CAInitialize fail\n");
-        return 1;
-    }
 
     // set handler.
-    CARegisterHandler(RequestHandler, ResponseHandler);
+    CARegisterHandler(request_handler, response_handler);
 
-    Process();
+    process();
 
-    if (g_lastRequestToken != NULL)
-    {
-        CADestroyToken(g_lastRequestToken);
-    }
-    g_lastRequestToken = NULL;
+    CADestroyToken(g_last_request_token);
 
     CATerminate();
 #ifdef __WITH_DTLS__
-    ClearDtlsCredentialInfo();
+    clearDtlsCredentialInfo();
 #endif
     return 0;
 }
 
-void Process()
+void process()
 {
     while (1)
     {
-        char menu = toupper(PrintOptions());
+        char menu = get_menu();
 
         switch (menu)
         {
@@ -240,59 +289,59 @@ void Process()
             case 'M':
                 break;
 
-            case 'Q': // quits the sample program
+            case 'q': // quit
+            case 'Q':
                 printf("quit..!!\n");
-                g_main_loop_quit(mainloop);
                 return;
 
             case 's': // start server
-            case 'S': // start server
-                StartListeningServer();
+            case 'S':
+                start_listening_server();
                 break;
 
             case 't': // send request
             case 'T':
-                SendRequestAll();
+                send_request_all();
                 break;
 
             case 'c': // start client
             case 'C':
-                StartDiscoveryServer();
+                start_discovery_server();
                 break;
 
             case 'f': // find resource
             case 'F':
-                FindResource();
+                find_resource();
                 break;
 
             case 'r': // send request
             case 'R':
-                SendRequest();
+                send_request();
                 break;
 
             case 'a': // advertise resource
             case 'A':
-                AdvertiseResource();
+                advertise_resource();
                 break;
 
             case 'b': // send notification
             case 'B':
-                SendNotification();
+                send_notification();
                 break;
 
             case 'n': // select network
             case 'N':
-                SelectNetwork();
+                select_network();
                 break;
 
             case 'x': // unselect network
             case 'X':
-                UnselectNetwork();
+                unselect_network();
                 break;
 
             case 'h': // handle request response
             case 'H':
-                HandleRequestResponse();
+                handle_request_response();
                 break;
 
             case 'y':
@@ -300,97 +349,83 @@ void Process()
                 while (1)
                 {
                     g_received = 0;
-                    FindFixedResource();
+                    find_fixed_resource();
                     while (g_received == 0)
                     {
                         sleep(1);
-                        HandleRequestResponse();
+                        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':
-                StartListeningServer();
+                start_listening_server();
                 while (1)
                 {
                     sleep(1);
-                    HandleRequestResponse();
+                    handle_request_response();
                 }
                 break;
 
             case 'g': // get network information
             case 'G':
-                GetNetworkInfo();
+                get_network_info();
                 break;
 
             default:
-                printf("not supported menu!!\n");
+                printf("Not supported menu!!\n");
                 break;
         }
     }
 
 }
 
-CAResult_t Initialize()
-{
-    CAResult_t res = CA_STATUS_FAILED;
-    mainloop = g_main_loop_new(NULL, FALSE);
-    if(!mainloop)
-    {
-        printf("g_main_loop_new failed\n");
-        return res;
-    }
-
-    int result = pthread_create(&thread, NULL, (void *) &pthread_func, NULL);
-    if (result < 0)
-    {
-        printf("pthread_create failed in initialize\n");
-        return res;
-    }
-
-    res = CAInitialize();
-    if (res != CA_STATUS_OK)
-    {
-        printf("CAInitialize fail\n");
-    }
-    return res;
-}
-
-void StartListeningServer()
+void start_listening_server()
 {
-    printf("start listening server!!\n");
+    printf("Start listening server!!\n");
 
     CAResult_t res = CAStartListeningServer();
-    if (res != CA_STATUS_OK)
+    if (CA_STATUS_OK != res)
     {
-        printf("start listening server fail\n");
+        printf("Start listening server fail, error code : %d\n", res);
     }
     else
     {
-        printf("start listening server success\n");
+        printf("Start listening server success\n");
     }
 }
 
-void StartDiscoveryServer()
+void start_discovery_server()
 {
-    printf("start discovery client!!\n");
+    printf("Start discovery client!!\n");
 
     CAResult_t res = CAStartDiscoveryServer();
-    if (res != CA_STATUS_OK)
+    if (CA_STATUS_OK != res)
     {
-        printf("start discovery client fail\n");
+        printf("Start discovery client fail, error code : %d\n", res);
     }
     else
     {
-        printf("start discovery client success\n");
+        printf("Start discovery client success\n");
     }
 }
 
-void FindFixedResource()
+void find_fixed_resource()
 {
-    char buf[] ="/a/light";
-
     // create token
     CAToken_t token = NULL;
     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
@@ -398,20 +433,23 @@ void FindFixedResource()
     CAResult_t res = CAGenerateToken(&token, tokenLength);
     if ((CA_STATUS_OK != res) || (!token))
     {
-        printf("token generate error!!");
+        printf("Token generate error!!");
         return;
     }
 
     printf("Generated token %s\n", token);
 
+    char buf[MAX_BUF_LEN] = { 0 };
+    strcpy(buf, "/a/light");
+
     res = CAFindResource(buf, token, tokenLength);
-    if (res != CA_STATUS_OK)
+    if (CA_STATUS_OK != res)
     {
-        printf("find resource error : %d\n", res);
+        printf("Find resource error : %d\n", res);
     }
     else
     {
-        printf("find resource to %s URI\n", buf);
+        printf("Find resource to %s URI\n", buf);
     }
 
     // delete token
@@ -420,17 +458,15 @@ void FindFixedResource()
     printf("=============================================\n");
 }
 
-void FindResource()
+void find_resource()
 {
-    char buf[MAX_BUF_LEN] = {0};
-
     printf("\n=============================================\n");
     printf("ex) /a/light\n");
     printf("reference uri : ");
 
-    if(!fgets(buf, MAX_BUF_LEN, stdin))
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
     {
-        printf("fgets error\n");
         return;
     }
 
@@ -441,93 +477,88 @@ void FindResource()
     CAResult_t res = CAGenerateToken(&token, tokenLength);
     if ((CA_STATUS_OK != res) || (!token))
     {
-        printf("token generate error!!\n");
+        printf("Token generate error!!\n");
         return;
     }
 
     printf("Generated token %s\n", token);
 
     res = CAFindResource(buf, token, tokenLength);
-    if (res != CA_STATUS_OK)
+    if (CA_STATUS_OK != res)
     {
-        printf("find resource error : %d\n", res);
+        printf("Find resource error : %d\n", res);
         CADestroyToken(token);
     }
     else
     {
-        printf("find resource to %s URI\n", buf);
-
-        CADestroyToken(g_lastRequestToken);
-
-        g_lastRequestToken = token;
+        printf("Find resource to %s URI\n", buf);
+        CADestroyToken(g_last_request_token);
+        g_last_request_token = token;
     }
 
     printf("=============================================\n");
 }
 
-void SendRequest()
+void send_request()
 {
-    char secureRequest[2] = {0};
-    CAResult_t res = CA_STATUS_FAILED;
-    char uri[MAX_BUF_LEN] = {'\0'};
-
-    res = GetNetworkType();
-    if (res != CA_STATUS_OK)
+    CAResult_t res = get_network_type();
+    if (CA_STATUS_OK != res)
     {
         return;
     }
 
-    printf("Do you want to send secure request ?.... enter (0/1): \n");
-    if(!fgets(secureRequest, 1, stdin))
+    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))
     {
-        printf("fgets error\n");
         return;
     }
 
-    if ('1' == secureRequest[0])
+    if (strcmp(secureRequest, "1") == 0)
     {
         printf("Enter the URI like below....\n");
         printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
-        printf("uri:  ");
     }
-    else
+    else if (strcmp(secureRequest, "0") == 0)
     {
         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");
-        printf("uri:  ");
+    }
+    else
+    {
+        printf("Input data is wrong value\n");
+        return;
     }
 
-    if(!fgets(uri, MAX_BUF_LEN, stdin))
+    char uri[MAX_BUF_LEN] = {'\0'};
+    if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
     {
-        printf("fgets error\n");
         return;
     }
 
     // create remote endpoint
     CARemoteEndpoint_t *endpoint = NULL;
-    if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, g_selectedNwType, &endpoint)
-        || !endpoint)
+    res = CACreateRemoteEndpoint(uri, g_selected_nw_type, &endpoint);
+    if (CA_STATUS_OK != res || !endpoint)
     {
-        printf("Failed to create remote endpoint!\n");
-        CADestroyRemoteEndpoint(endpoint);
+        printf("Failed to create remote endpoint, error code : %d\n", res);
         return;
     }
 
-    char buf[MAX_BUF_LEN]={0};
-
     printf("\n=============================================\n");
     printf("0:CON, 1:NON\n");
     printf("select message type : ");
 
-    if(!fgets(buf, MAX_BUF_LEN, stdin))
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
     {
-        printf("fgets error\n");
         CADestroyRemoteEndpoint(endpoint);
         return;
     }
 
-    CAMessageType_t msgType = (buf[0] == '0' || buf[0] == '1') ? buf[0] - '0' : 0;
+    CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0;
 
     // create token
     CAToken_t token = NULL;
@@ -536,102 +567,102 @@ void SendRequest()
     res = CAGenerateToken(&token, tokenLength);
     if ((CA_STATUS_OK != res) || (!token))
     {
-        printf("token generate error, error code : %d\n", res);
+        printf("Token generate error, error code : %d\n", res);
+        CADestroyRemoteEndpoint(endpoint);
         return;
     }
 
     printf("Generated token %s\n", token);
 
     // extract relative resourceuri from give uri
-    char resourceURI[15] = {0};
-
     printf("URI : %s\n", uri);
-    GetResourceUri(uri, resourceURI, 14);
+
+    char resourceURI[15] = {0};
+    get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH);
 
     // create request data
-    CAInfo_t requestData = {CA_MSG_RESET};
+    CAInfo_t requestData = { 0 };
     requestData.token = token;
-    if ('1' == secureRequest[0])
+    requestData.tokenLength = tokenLength;
+
+    if (strcmp(secureRequest, "1") == 0)
     {
-        int length = strlen(g_secureInfoData) + strlen(resourceURI) + 1;
-        requestData.payload = (CAPayload_t) malloc(length);
-        if(!requestData.payload)
+        uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
+        requestData.payload = (CAPayload_t) calloc(length,  sizeof(char));
+        if (NULL == requestData.payload)
         {
-            printf("Memory allocation is failed\n");
-            CADestroyToken(token);
+            printf("Memory allocation fail\n");
             CADestroyRemoteEndpoint(endpoint);
+            CADestroyToken(token);
             return;
         }
-        sprintf(requestData.payload, g_secureInfoData, resourceURI, g_localSecurePort);
+        snprintf(requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_local_secure_port);
     }
     else
     {
-        int length = strlen(g_normalInfoData) + strlen(resourceURI) + 1;
-        requestData.payload = (CAPayload_t) malloc(length);
-        if(!requestData.payload)
+        uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
+        requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
+        if (NULL == requestData.payload)
         {
-            printf("Memory allocation is failed\n");
-            CADestroyToken(token);
+            printf("Memory allocation fail\n");
             CADestroyRemoteEndpoint(endpoint);
+            CADestroyToken(token);
             return;
         }
-        sprintf(requestData.payload, g_normalInfoData, resourceURI);
+        snprintf(requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
     }
     requestData.type = msgType;
 
-    CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
+    CARequestInfo_t requestInfo = { 0 };
     requestInfo.method = CA_GET;
     requestInfo.info = requestData;
 
     // send request
-    CASendRequest(endpoint, &requestInfo);
+    res = CASendRequest(endpoint, &requestInfo);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Could not send request : %d\n", res);
+    }
 
+    //destroy token
     CADestroyToken(token);
-
-    free(requestData.payload);
-
     // destroy remote endpoint
     CADestroyRemoteEndpoint(endpoint);
+    free(requestData.payload);
+
+
     printf("=============================================\n");
 }
 
-void SendRequestAll()
+void send_request_all()
 {
-    char buf[MAX_BUF_LEN] = {0};
-
-    CAResult_t res = CA_STATUS_FAILED;
-
-    res = GetNetworkType();
-    if (res != CA_STATUS_OK)
+    CAResult_t res = get_network_type();
+    if (CA_STATUS_OK != res)
     {
         return;
     }
 
     printf("\n=============================================\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 : ");
+    printf("ex) /a/light\n");
+    printf("resource uri : ");
 
-    if(!fgets(buf, MAX_BUF_LEN, stdin))
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
     {
-        printf("fgets error\n");
         return;
     }
 
     // create remote endpoint
     CARemoteEndpoint_t *endpoint = NULL;
-    res = CACreateRemoteEndpoint(buf, g_selectedNwType, &endpoint);
-
-    if (res != CA_STATUS_OK)
+    res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint);
+    if (CA_STATUS_OK != res)
     {
-        printf("create remote endpoint error!!\n");
-        CADestroyRemoteEndpoint(endpoint);
+        printf("Create remote endpoint error, error code: %d\n", res);
         return;
     }
 
-    CAGroupEndpoint_t *group = NULL;
-    group = (CAGroupEndpoint_t *)malloc(sizeof(CAGroupEndpoint_t));
-     if (NULL == group)
+    CAGroupEndpoint_t *group = (CAGroupEndpoint_t *) malloc(sizeof(CAGroupEndpoint_t));
+    if (NULL == group)
     {
         printf("Memory allocation failed!\n");
         CADestroyRemoteEndpoint(endpoint);
@@ -647,7 +678,9 @@ void SendRequestAll()
     res = CAGenerateToken(&token, tokenLength);
     if ((CA_STATUS_OK != res) || (!token))
     {
-        printf("token generate error!!\n");
+        printf("Token generate error!!\n");
+        CADestroyRemoteEndpoint(endpoint);
+        free(group);
         return;
     }
 
@@ -663,61 +696,81 @@ void SendRequestAll()
     requestInfo.method = CA_GET;
     requestInfo.info = requestData;
 
-    // send request
-    CASendRequestToAll(group, &requestInfo);
-
-    CADestroyToken(token);
+    // send request all
+    res = CASendRequestToAll(group, &requestInfo);
+    if (CA_STATUS_OK != res)
+    {
+        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);
 
     printf("=============================================\n");
 }
 
-void AdvertiseResource()
+void advertise_resource()
 {
-    char buf[MAX_BUF_LEN] = {0};
-
     printf("\n=============================================\n");
     printf("uri : ");
 
-    if(!fgets(buf, MAX_BUF_LEN, stdin))
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
     {
-        printf("fgets error\n");
         return;
     }
 
-    int optionNum = 0;
-    char optionData[MAX_OPT_LEN] = {0};
+    char optionNumBuf[MAX_BUF_LEN] = { 0 };
+    char optionData[MAX_OPT_LEN] = { 0 } ;
 
     printf("Option Num : ");
-    scanf("%d", &optionNum);
-    CAHeaderOption_t *headerOpt = NULL;
-    headerOpt = (CAHeaderOption_t *) malloc(sizeof(CAHeaderOption_t) * optionNum);
+    if (CA_STATUS_OK != get_input_data(optionNumBuf, MAX_BUF_LEN))
+    {
+        return;
+    }
+    int optionNum = atoi(optionNumBuf);
+
+    CAHeaderOption_t * headerOpt = (CAHeaderOption_t *)
+            calloc(1, optionNum * sizeof(CAHeaderOption_t));
     if (NULL == headerOpt)
     {
         printf("Memory allocation failed!\n");
         return;
     }
-    memset(headerOpt, 0, sizeof(CAHeaderOption_t) * optionNum);
 
-    int i = 0;
-    for (i = 0 ; i < optionNum ; i++)
+    int i;
+    for (i = 0; i < optionNum; i++)
     {
-        int optionID = 0;
+        char getOptionID[MAX_BUF_LEN] = { 0 } ;
+
         printf("[%d] Option ID : ", i + 1);
-        scanf("%d", &optionID);
+        if (CA_STATUS_OK != get_input_data(getOptionID, MAX_BUF_LEN))
+        {
+            free(headerOpt);
+            return;
+        }
+        int optionID = atoi(getOptionID);
+
         headerOpt[i].optionID = optionID;
 
         printf("[%d] Option Data : ", i + 1);
-        scanf("%s", optionData);
-        int len = strlen(optionData);
-        memcpy(headerOpt[i].optionData, optionData, len + 1);
-        printf("[%d] inputed option : ID : %d, data : %s\n", i + 1, optionID, optionData );
+        if (CA_STATUS_OK != get_input_data(optionData, MAX_OPT_LEN))
+        {
+            free(headerOpt);
+            return;
+        }
+
+        memcpy(headerOpt[i].optionData, optionData, strlen(optionData));
+        printf("[%d] inputed option : ID : %d, data : %s\n", i + 1, optionID, optionData);
 
-        headerOpt[i].optionLength = (uint16_t)len;
+        headerOpt[i].optionLength = (uint16_t) strlen(optionData);
     }
     printf("\n=============================================\n");
 
@@ -728,164 +781,193 @@ void AdvertiseResource()
     CAResult_t res = CAGenerateToken(&token, tokenLength);
     if ((CA_STATUS_OK != res) || (!token))
     {
-        printf("token generate error!!\n");
+        printf("Token generate error!!\n");
+        free(headerOpt);
         return;
     }
 
-    printf("generated token %s\n", token);
-
-    CAAdvertiseResource(buf, token, tokenLength, headerOpt, (uint8_t)optionNum);
+    printf("Generated token %s\n", token);
 
-    // delete token
-    CADestroyToken(token);
+    res = CAAdvertiseResource(buf, token, tokenLength, headerOpt, (uint8_t) optionNum);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Could not start advertise resource\n");
+        CADestroyToken(token);
+    }
+    else
+    {
+        CADestroyToken(g_last_request_token);
+        g_last_request_token = token;
+    }
 
     free(headerOpt);
 }
 
-void SendNotification()
+void send_notification()
 {
-    char buf[MAX_BUF_LEN] = {0};
-
-    CAResult_t res = CA_STATUS_FAILED;
-
-    res = GetNetworkType();
-    if (res != CA_STATUS_OK)
+    CAResult_t res = get_network_type();
+    if (CA_STATUS_OK != res)
     {
         return;
     }
 
     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 : ");
 
-     if(!fgets(buf, MAX_BUF_LEN, stdin))
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
     {
-        printf("fgets error\n");
         return;
     }
 
+    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 messageTypeBuf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN))
+    {
+        return;
+    }
+
+    int messageType = messageTypeBuf[0] - '0';
+
     // create remote endpoint
     CARemoteEndpoint_t *endpoint = NULL;
-    res = CACreateRemoteEndpoint(buf, g_selectedNwType, &endpoint);
-    if (res != CA_STATUS_OK)
+    res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint);
+    if (CA_STATUS_OK != res)
     {
-        printf("create remote endpoint error!!\n");
-        CADestroyRemoteEndpoint(endpoint);
+        printf("Create remote endpoint error, error code: %d\n", res);
         return;
     }
 
-    CAInfo_t respondData = {CA_MSG_RESET};
-    respondData.tokenLength = CA_MAX_TOKEN_LEN;
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
 
-    res = CAGenerateToken(&respondData.token, respondData.tokenLength);
-    if ((CA_STATUS_OK != res) || (!respondData.token))
+    res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
     {
-        printf("token generate error!!\n");
+        printf("Token generate error!!\n");
+        CADestroyRemoteEndpoint(endpoint);
         return;
     }
 
+    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};
+    CAResponseInfo_t responseInfo = { 0 };
     responseInfo.result = CA_SUCCESS;
     responseInfo.info = respondData;
 
-    // send request
+    // send notification
     res = CASendNotification(endpoint, &responseInfo);
-    if (res != CA_STATUS_OK)
+    if (CA_STATUS_OK != res)
     {
-        printf("send notification error, error code: %d\n", res);
+        printf("Send notification error, error code: %d\n", res);
     }
     else
     {
-        printf("send notification success\n");
+        printf("Send notification success\n");
     }
 
-    // delete token
-    CADestroyToken(respondData.token);
+    // destroy token
+    CADestroyToken(token);
     // destroy remote endpoint
     CADestroyRemoteEndpoint(endpoint);
 
     printf("\n=============================================\n");
 }
-void SelectNetwork()
-{
-    char buf[MAX_BUF_LEN] = {0};
 
+void select_network()
+{
     printf("\n=============================================\n");
     printf("\tselect network\n");
-    printf("ETHERNET : 0\n");
-    printf("WIFI : 1\n");
+    printf("IPv4 : 0\n");
     printf("EDR : 2\n");
     printf("LE : 3\n");
     printf("select : ");
 
-    if(!fgets(buf, MAX_BUF_LEN, stdin))
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
     {
-        printf("fgets error\n");
         return;
     }
 
     int number = buf[0] - '0';
 
-    number = (number < 0 || number > 3) ? 0 : number;
+    if (number < 0 || number > 3)
+    {
+        printf("Invalid network type\n");
+        return;
+    }
 
     CAResult_t res = CASelectNetwork(1 << number);
-    if (res != CA_STATUS_OK)
+    if (CA_STATUS_OK != res)
     {
-        printf("select network error\n");
-        g_selectedNwType = 1 << number;
+        printf("Select network error\n");
+        g_selected_nw_type = 1 << number;
     }
     else
     {
-        printf("select network success\n");
+        printf("Select network success\n");
     }
 
     printf("=============================================\n");
 }
 
-void UnselectNetwork()
+void unselect_network()
 {
-    char buf[MAX_BUF_LEN] = {0};
-
     printf("\n=============================================\n");
     printf("\tunselect enabled network\n");
-    printf("ETHERNET : 0\n");
-    printf("WIFI : 1\n");
+    printf("IPv4 : 0\n");
     printf("EDR : 2\n");
     printf("LE : 3\n");
     printf("select : ");
 
-    if(!fgets(buf, MAX_BUF_LEN, stdin))
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
     {
-        printf("fgets error\n");
         return;
     }
 
     int number = buf[0] - '0';
 
-    number = (number < 0 || number > 3) ? 1 : number;
+    if (number < 0 || number > 3)
+    {
+        printf("Invalid network type\n");
+        return;
+    }
 
     CAResult_t res = CAUnSelectNetwork(1 << number);
-    if (res != CA_STATUS_OK)
+    if (CA_STATUS_OK != res)
     {
-        printf("unselect network error\n");
+        printf("Unselect network error\n");
     }
     else
     {
-        printf("unselect network success\n");
+        printf("Unselect network success\n");
     }
+
     printf("=============================================\n");
 }
 
-char PrintOptions()
+char get_menu()
 {
-    char buf[MAX_BUF_LEN] = {0};
-
     printf("\n=============================================\n");
     printf("\t\tMenu\n");
-    printf("\tm : show menu\n");
     printf("\ts : start server\n");
     printf("\tc : start client\n");
     printf("\tf : find resource\n");
@@ -899,105 +981,111 @@ char PrintOptions()
     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 : ");
 
-    if(!fgets(buf, MAX_BUF_LEN, stdin))
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
     {
-        printf("fgets error\n");
-        return '\0';
+        printf("Failed to get input data\n");
     }
 
     return buf[0];
 }
 
-void HandleRequestResponse()
+void handle_request_response()
 {
-    printf("handle_request_response\n");
+    printf("Handle_request_response\n");
 
     CAResult_t res = CAHandleRequestResponse();
-    if (res != CA_STATUS_OK)
+    if (CA_STATUS_OK != res)
     {
-        printf("handle request error\n");
+        printf("Handle request error, error code: %d\n", res);
     }
     else
     {
-        printf("handle request success\n");
+        printf("Handle request success\n");
     }
 }
 
-void GetNetworkInfo()
+void get_network_info()
 {
-    int index = 0;
     CALocalConnectivity_t *tempInfo = NULL;
     uint32_t tempSize = 0;
 
-    CAGetNetworkInformation(&tempInfo, &tempSize);
-    if (tempInfo == NULL || tempSize <= 0)
+    CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
+    if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
     {
-        printf("network not connected\n");
+        printf("Network not connected\n");
+        free(tempInfo);
         return;
     }
 
     printf("################## Network Information #######################\n");
-    printf("network info total size is %d\n\n", tempSize);
+    printf("Network info total size is %d\n\n", tempSize);
 
+    int index;
     for (index = 0; index < tempSize; index++)
     {
         printf("Type: %d\n", tempInfo[index].type);
-        printf("Address: %s\n", tempInfo[index].addressInfo.IP.ipAddress);
-        printf("Port: %d\n", tempInfo[index].addressInfo.IP.port);
-        printf("Secured: %d\n\n", tempInfo[index].isSecured);
-
-        if (true == tempInfo[index].isSecured)
+        if (CA_WIFI == tempInfo[index].type)
         {
-            g_localSecurePort = tempInfo[index].addressInfo.IP.port;
+            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)
         {
-            g_localUnicastPort = tempInfo[index].addressInfo.IP.port;
+            printf("Address: %s\n", tempInfo[index].addressInfo.BT.btMacAddress);
+        }
+        printf("Secured: %d\n\n", tempInfo[index].isSecured);
+
+        if (tempInfo[index].isSecured)
+        {
+            g_local_secure_port = tempInfo[index].addressInfo.IP.port;
+            printf("Secured: in global %d\n\n", g_local_secure_port);
         }
     }
 
-    // free
     free(tempInfo);
-
     printf("##############################################################");
 }
 
-void RequestHandler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
+void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
 {
-    printf("##########received request from remote device #############\n");
-    if (!object)
+    if (NULL == object || NULL == requestInfo)
     {
-        printf("Remote endpoint is NULL!\n");
+        printf("Input parameter is NULL\n");
         return;
     }
 
-    if (!requestInfo)
+    if ((NULL != g_last_request_token) && (NULL != requestInfo->info.token)
+        && (strncmp(g_last_request_token, requestInfo->info.token,
+                    requestInfo->info.tokenLength) == 0))
     {
-        printf("Request info is NULL!\n");
+        printf("Token is same. received request of it's own. skip.. \n");
         return;
     }
 
+    printf("##########received request from remote device #############\n");
     printf("Uri: %s\n", object->resourceUri);
-    printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
-           object->addressInfo.IP.port, object->isSecured);
-
-    printf("Data: %s\n", requestInfo->info.payload);
-    printf("Message type: %s\n", g_messageType[requestInfo->info.type]);
-    if (g_lastRequestToken != NULL && requestInfo->info.token != NULL
-        && (strcmp((char *)g_lastRequestToken, requestInfo->info.token) == 0))
+    if (CA_WIFI == object->connectivityType)
     {
-        printf("token is same. received request of it's own. skip.. \n");
-        return;
+        printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
+               object->addressInfo.IP.port, object->isSecured);
     }
+    else if (CA_EDR == object->connectivityType)
+    {
+        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]);
 
     if (requestInfo->info.options)
     {
         uint32_t len = requestInfo->info.numOptions;
-        uint32_t i = 0;
+        uint32_t i;
         for (i = 0; i < len; i++)
         {
             printf("Option %d\n", i + 1);
@@ -1009,27 +1097,29 @@ void RequestHandler(const CARemoteEndpoint_t *object, const CARequestInfo_t *req
     printf("############################################################\n");
 
     //Check if this has secure communication information
-    if (requestInfo->info.payload)
+    if (requestInfo->info.payload &&
+            (CA_WIFI == object->connectivityType))
     {
-        int securePort = GetSecureInformation(requestInfo->info.payload);
+        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");
-            char *uri = NULL;
-            int length = 0;
 
-            length = 8; //length of "coaps://"
-            length += strlen(object->addressInfo.IP.ipAddress) + 5; // length of "ipaddress:port"
+            //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;
 
-            uri = calloc(1, sizeof(char) * length);
+            char *uri = calloc(1, sizeof(char) * length);
             if (!uri)
             {
                 printf("Failed to create new uri\n");
                 return;
             }
-            sprintf(uri, "coaps://%s:%d/%s", object->addressInfo.IP.ipAddress,
-                    securePort, object->resourceUri);
+            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->connectivityType, &endpoint))
@@ -1037,7 +1127,6 @@ void RequestHandler(const CARemoteEndpoint_t *object, const CARequestInfo_t *req
                 printf("Failed to create duplicate of remote endpoint!\n");
                 return;
             }
-            //endpoint->connectivityType = object->connectivityType;
             endpoint->isSecured = true;
             object = endpoint;
 
@@ -1045,38 +1134,33 @@ void RequestHandler(const CARemoteEndpoint_t *object, const CARequestInfo_t *req
         }
     }
 
-    printf("send response with URI\n");
-    SendResponse(object, &requestInfo->info);
+    printf("Send response with URI\n");
+    send_response(object, &requestInfo->info);
 
     g_received = 1;
 }
 
-void ResponseHandler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
+void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
 {
     printf("##########Received response from remote device #############\n");
-    if(!object)
+    printf("Uri: %s\n", object->resourceUri);
+    if (CA_WIFI == object->connectivityType)
     {
-        printf("response_handler object is null\n");
-        return;
+        printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
+               object->addressInfo.IP.port, object->isSecured);
     }
-
-     if(!responseInfo)
+    else if (CA_EDR == object->connectivityType)
     {
-        printf("response_handler responseInfo is null\n");
-        return;
+        printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress);
     }
-
-    printf("Uri: %s\n", object->resourceUri);
-    printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
-           object->addressInfo.IP.port, object->isSecured);
     printf("response result : %d\n", responseInfo->result);
     printf("Data: %s\n", responseInfo->info.payload);
-    printf("Message type: %s\n", g_messageType[responseInfo->info.type]);
+    printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
     printf("Token: %s\n", responseInfo->info.token);
     if (responseInfo->info.options)
     {
         uint32_t len = responseInfo->info.numOptions;
-        uint32_t i = 0;
+        uint32_t i;
         for (i = 0; i < len; i++)
         {
             printf("Option %d\n", i + 1);
@@ -1091,7 +1175,7 @@ void ResponseHandler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *r
     //Check if this has secure communication information
     if (responseInfo->info.payload)
     {
-        int securePort = GetSecureInformation(responseInfo->info.payload);
+        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");
@@ -1099,98 +1183,107 @@ void ResponseHandler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *r
     }
 }
 
-void SendResponse(CARemoteEndpoint_t *endpoint, CAInfo_t *info)
+void send_response(const CARemoteEndpoint_t *endpoint, const CAInfo_t *info)
 {
     printf("entering send_response\n");
 
-     if(!endpoint)
-    {
-        printf("endpoint is null\n");
-        return;
-    }
+    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 : ");
 
-    CAInfo_t responseData = {CA_MSG_RESET};
-    responseData.type =
-        (info != NULL) ?
-        ((info->type == CA_MSG_CONFIRM) ? CA_MSG_ACKNOWLEDGE : CA_MSG_NONCONFIRM) :
-            CA_MSG_NONCONFIRM;
-    responseData.messageId = 0;
-    responseData.token = "";
-    if(info)
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
     {
-        responseData.messageId = info->messageId;
-        responseData.token = info->token;
-        responseData.tokenLength = info->tokenLength;
+        return;
     }
-    responseData.payload = "response payload";
-
-    CAResponseInfo_t responseInfo = {0};
-    responseInfo.result = 203;
-    responseInfo.info = responseData;
 
-    if (true == endpoint->isSecured)
-    {
-        printf("Sending response on secure communication\n");
-    }
-    else
-    {
-        printf("Sending response on non-secure communication\n");
+    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;
 
-    // send request (connectivityType from remoteEndpoint of request Info)
-    CAResult_t res = CASendResponse(endpoint, &responseInfo);
-    if (res != CA_STATUS_OK)
+    responseData.messageId = (info != NULL) ? info->messageId : 0;
+    if(CA_MSG_RESET != messageType)
     {
-        printf("send response failed\n");
-    }
-    else
-    {
-        printf("send response success\n");
-    }
+        responseData.token = (info != NULL) ? info->token : NULL;
+        responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
 
-    printf("=============================================\n");
-}
+        if (endpoint->isSecured)
+        {
+            printf("Sending response on secure communication\n");
 
-void SendRequestTemp(CARemoteEndpoint_t *endpoint, CAToken_t token, uint8_t tokenLength)
-{
-    printf("\n=============================================\n");
+            uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(endpoint->resourceUri);
+            responseData.payload = (CAPayload_t) calloc(length,  sizeof(char));
+            if (NULL == responseData.payload)
+            {
+                printf("Memory allocation fail\n");
+                return;
+            }
+            snprintf(responseData.payload, length, SECURE_INFO_DATA, endpoint->resourceUri,
+                     g_local_secure_port);
+        }
+        else
+        {
+            printf("Sending response on non-secure communication\n");
 
-    if(!endpoint)
-    {
-        printf("endpoint is null\n");
-        return;
+            uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(endpoint->resourceUri);
+            responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
+            if (NULL == responseData.payload)
+            {
+                printf("Memory allocation fail\n");
+                return;
+            }
+            snprintf(responseData.payload, length, NORMAL_INFO_DATA, endpoint->resourceUri);
+        }
     }
 
-    CAInfo_t requestData ={CA_MSG_RESET};
-    requestData.token = token;
-    requestData.tokenLength = tokenLength;
-    requestData.payload = "Temp Json Payload";
-
-    CARequestInfo_t requestInfo ={CA_GET, {CA_MSG_RESET}};
-    memset(&requestInfo, 0, sizeof(CARequestInfo_t));
-    requestInfo.method = CA_GET;
-    requestInfo.info = requestData;
-
-    // send request
-    endpoint->connectivityType = CA_WIFI;
+    CAResponseInfo_t responseInfo = { 0 };
+    responseInfo.result = responseCode;
+    responseInfo.info = responseData;
 
-    CAResult_t res = CASendRequest(endpoint, &requestInfo);
-    if (res != CA_STATUS_OK)
+    // send response (transportType from remoteEndpoint of request Info)
+    CAResult_t res = CASendResponse(endpoint, &responseInfo);
+    if (CA_STATUS_OK != res)
     {
-        printf("send request failed\n");
+        printf("Send response error\n");
     }
     else
     {
-        printf("send request success\n");
+        printf("Send response success\n");
     }
 
     printf("=============================================\n");
-
 }
 
-int GetSecureInformation(CAPayload_t payLoad)
+int get_secure_information(CAPayload_t payLoad)
 {
-    printf("entering get_secure_information\n");
+    printf("Entering get_secure_information\n");
 
     if (!payLoad)
     {
@@ -1238,7 +1331,7 @@ int GetSecureInformation(CAPayload_t payLoad)
     return atoi(portStr);
 }
 
-void GetResourceUri(char *URI, char *resourceURI, int length)
+void get_resource_uri(char *URI, char *resourceURI, int length)
 {
     char *startPos = URI;
     char *temp = NULL;
@@ -1260,59 +1353,48 @@ void GetResourceUri(char *URI, char *resourceURI, int length)
     endPos -= 1;
 
     if (endPos - startPos <= length)
+    {
         memcpy(resourceURI, startPos + 1, endPos - startPos);
+    }
 
     printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
 }
 
-CAResult_t GetNetworkType()
+CAResult_t get_network_type()
 {
-    char buf[MAX_BUF_LEN] = {0};
-
     printf("\n=============================================\n");
     printf("\tselect network type\n");
-    printf("ETHERNET : 0\n");
-    printf("WIFI : 1\n");
-    printf("EDR : 2\n");
+    printf("IPv4 : 0\n");
+    printf("BT : 2\n");
     printf("LE : 3\n");
     printf("select : ");
 
-    if(!fgets(buf, MAX_BUF_LEN, stdin))
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
     {
-        printf("fgets error\n");
-        return CA_STATUS_FAILED;
+        return CA_NOT_SUPPORTED ;
     }
 
     int number = buf[0] - '0';
-
     number = (number < 0 || number > 3) ? 0 : 1 << number;
 
     if (!(number & 0xf))
     {
         return CA_NOT_SUPPORTED;
     }
-
-    if (number & CA_ETHERNET)
-    {
-        g_selectedNwType = CA_ETHERNET;
-        return CA_STATUS_OK;
-    }
-
     if (number & CA_WIFI)
     {
-        g_selectedNwType = CA_WIFI;
+        g_selected_nw_type = CA_WIFI;
         return CA_STATUS_OK;
     }
-
     if (number & CA_EDR)
     {
-        g_selectedNwType = CA_EDR;
+        g_selected_nw_type = CA_EDR;
         return CA_STATUS_OK;
     }
-
     if (number & CA_LE)
     {
-        g_selectedNwType = CA_LE;
+        g_selected_nw_type = CA_LE;
         return CA_STATUS_OK;
     }
 
@@ -1321,4 +1403,19 @@ CAResult_t GetNetworkType()
     return CA_STATUS_FAILED;
 }
 
+CAResult_t get_input_data(char *buf, int32_t length)
+{
+    if (!fgets(buf, length, stdin))
+    {
+        printf("fgets error\n");
+        return CA_STATUS_FAILED;
+    }
+
+    char *p = NULL;
+    if ((p = strchr(buf, '\n')) != NULL)
+    {
+        *p = '\0';
+    }
 
+    return CA_STATUS_OK;
+}
index 7d6656d..9d60453 100644 (file)
@@ -299,53 +299,48 @@ CAResult_t CAParseIPv4AddressInternal(const char *ipAddrStr, uint8_t *ipAddr,
     return CA_STATUS_FAILED;
 }
 
-bool CAAdapterIsSameSubnet(const char *ipAddress1, const char *ipAddress2,
-                           const char *netMask)
+bool CAAdapterIsSameSubnet(const char *ipAddress1, const char *ipAddress2, const char *netMask)
 {
     VERIFY_NON_NULL_RET(ipAddress1, CA_ADAPTER_UTILS_TAG, "First address", false);
     VERIFY_NON_NULL_RET(ipAddress2, CA_ADAPTER_UTILS_TAG, "Second address", false);
     VERIFY_NON_NULL_RET(netMask, CA_ADAPTER_UTILS_TAG, "netMask", false);
 
-    uint8_t ipList1[IPV4_ADDR_ONE_OCTECT_LEN] = {0};
-    uint8_t ipList2[IPV4_ADDR_ONE_OCTECT_LEN] = {0};
-    uint8_t maskList[IPV4_ADDR_ONE_OCTECT_LEN] = {0};
+    uint8_t ipList1[IPV4_ADDR_ONE_OCTECT_LEN] = { 0 };
+    uint8_t ipList2[IPV4_ADDR_ONE_OCTECT_LEN] = { 0 };
+    uint8_t maskList[IPV4_ADDR_ONE_OCTECT_LEN] = { 0 };
     CAResult_t ret = CA_STATUS_OK;
 
     /* Local Loopback Address */
-    if (0 == strncmp(ipAddress1, "127.", 4)
-        || 0 == strncmp(ipAddress2, "127.", 4))
+    if (0 == strncmp(ipAddress1, "127.", 4) || 0 == strncmp(ipAddress2, "127.", 4))
     {
         return true;
     }
 
     uint16_t parsedPort = 0;
-    ret = CAParseIPv4AddressInternal(ipAddress1, ipList1, sizeof(ipList1),
-                                     &parsedPort);
+    ret = CAParseIPv4AddressInternal(ipAddress1, ipList1, sizeof(ipList1), &parsedPort);
     if (ret != CA_STATUS_OK)
     {
         OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG, "First ip address parse fail %d", ret);
         return false;
     }
 
-    ret = CAParseIPv4AddressInternal(ipAddress2, ipList2, sizeof(ipList2),
-                                     &parsedPort);
+    ret = CAParseIPv4AddressInternal(ipAddress2, ipList2, sizeof(ipList2), &parsedPort);
     if (ret != CA_STATUS_OK)
     {
         OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG, "Second ip address parse fail %d", ret);
         return false;
     }
 
-    ret = CAParseIPv4AddressInternal(netMask, maskList, sizeof(maskList),
-                                     &parsedPort);
+    ret = CAParseIPv4AddressInternal(netMask, maskList, sizeof(maskList), &parsedPort);
     if (ret != CA_STATUS_OK)
     {
         OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG, "Net mask parse fail %d", ret);
         return false;
     }
 
-    return ((ipList1[0] & maskList[0]) == (ipList2[0] & maskList[0]))
-        && ((ipList1[1] & maskList[1]) == (ipList2[1] & maskList[1]))
-        && ((ipList1[2] & maskList[2]) == (ipList2[2] & maskList[2]))
-        && ((ipList1[3] & maskList[3]) == (ipList2[3] & maskList[3]));
+    return ((ipList1[0] & maskList[0]) == (ipList2[0] & maskList[0])) && ((ipList1[1] & maskList[1])
+            == (ipList2[1] & maskList[1]))
+           && ((ipList1[2] & maskList[2]) == (ipList2[2] & maskList[2]))
+           && ((ipList1[3] & maskList[3]) == (ipList2[3] & maskList[3]));
 }
 
index 973efaf..16e8bde 100644 (file)
 #include "cacommon.h"
 #include "caadapterutils.h"
 
+/**
+ * @var CA_MSG_PARSER_TAG
+ * @brief debugging tag for parser module
+ */
 #define CA_MSG_PARSER_TAG "CA_MSG_PARSER"
 
-#define MAX_PARSE_DATA_LENGTH 4095
-
 CAResult_t CAGenerateHeader(char *header, uint32_t length)
 {
     OIC_LOG(DEBUG, CA_MSG_PARSER_TAG, "IN");
 
     VERIFY_NON_NULL(header, CA_MSG_PARSER_TAG, "header is NULL");
-    memset(header, 0x0, sizeof(char) * 2);
+    memset(header, 0x0, sizeof(char) * CA_HEADER_LENGTH);
 
-    if(length > MAX_PARSE_DATA_LENGTH)
+    if(length > MAX_DATA_LENGTH_SUPPORTED)
     {
         OIC_LOG(DEBUG, CA_MSG_PARSER_TAG, "Given length is more than 4095.It will be truncated");
     }
@@ -45,6 +47,7 @@ CAResult_t CAGenerateHeader(char *header, uint32_t length)
     header[1] = length & 0xFF;
     length >>= 8;
     header[0] = length & 0x0F;
+    header[0] = header[0] | 0x40; // Adding version 0100.(Not used. Future use)
 
     OIC_LOG(DEBUG, CA_MSG_PARSER_TAG, "OUT");
     return CA_STATUS_OK;
index 090bbba..efdca2a 100644 (file)
@@ -46,7 +46,7 @@ static CANetworkChangeCallback g_networkCallback = NULL;
  * @var g_localBLEAddress
  * @brief bleAddress of the local adapter. Value will be initialized to zero, and will be updated later.
  */
-static char g_localBLEAddress[16] = { 0, };
+static char g_localBLEAddress[16] = {0};
 
 /**
  * @var g_isServer
@@ -73,7 +73,7 @@ static ca_mutex g_bleNetworkCbMutex = NULL;
 static ca_mutex g_bleLocalAddressMutex = NULL;
 
 /**
- * @var gBleClientThreadPool
+ * @var g_bleAdapterThreadPool
  * @brief reference to threadpool
  */
 static ca_thread_pool_t g_bleAdapterThreadPool = NULL;
@@ -85,10 +85,10 @@ static ca_thread_pool_t g_bleAdapterThreadPool = NULL;
 static ca_mutex g_bleAdapterThreadPoolMutex = NULL;
 
 /**
- * @var g_bLEClientSendQueueHandle
+ * @var g_bleClientSendQueueHandle
  * @brief Queue to process the outgoing packets from GATTClient.
  */
-static CAQueueingThread_t *g_bLEClientSendQueueHandle = NULL;
+static CAQueueingThread_t *g_bleClientSendQueueHandle = NULL;
 
 /**
  * @var g_bleClientReceiverQueue
@@ -102,7 +102,6 @@ static CAQueueingThread_t *g_bleClientReceiverQueue = NULL;
  */
 static ca_mutex g_bleClientSendDataMutex = NULL;
 
-
 /**
  * @var g_bleClientReceiveDataMutex
  * @brief Mutex to synchronize the queing of the data from ReceiverQueue.
@@ -111,7 +110,7 @@ static ca_mutex g_bleClientReceiveDataMutex = NULL;
 
 /**
  * @var g_dataReceiverHandlerState
- * @brief Stop condition of redvhandler.
+ * @brief Stop condition of recvhandler.
  */
 static bool g_dataReceiverHandlerState = false;
 
@@ -147,14 +146,13 @@ static ca_mutex g_bleAdapterReqRespCbMutex = NULL;
 
 /**
  * @var g_networkPacketReceivedCallback
- * @brief Callback to be called when the network packet recieved from either GattServer or GattClient.
+ * @brief Callback to be called when network packet recieved from either GattServer or GattClient.
  */
 static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
 
 /**
  * @ENUM CALeServerStatus
  * @brief status of BLE Server Status
- *
  *  This ENUM provides information of LE Adapter Server status
  */
 typedef enum
@@ -176,10 +174,13 @@ static CALeServerStatus gLeServerStatus = CA_SERVER_NOTSTARTED;
 *
 * @param[in]  netCallback CANetworkChangeCallback callback which will be set for the change in nwk.
 *
-* @return  0 for success.
+* @return  0 on success otherwise a positive error value.
+* @retval  CA_STATUS_OK  Successful
+* @retval  CA_STATUS_INVALID_PARAM  Invalid input argumets
+* @retval  CA_STATUS_FAILED Operation failed
 *
 */
-int32_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback);
+CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback);
 
 /**
 * @fn  CASetBleAdapterThreadPoolHandle
@@ -194,7 +195,8 @@ void CASetBleAdapterThreadPoolHandle(ca_thread_pool_t handle);
 
 /**
 * @fn  CALEDeviceStateChangedCb
-* @brief  This function is used to call the callback to the upper layer when the device state gets changed.
+* @brief  This function is used to call the callback to the upper layer when the device state gets
+*         changed.
 *
 * @param[in]  adapter_state New state of the adapter to be notified to the upper layer.
 *
@@ -220,9 +222,15 @@ CAResult_t CAInitBleAdapterMutex();
 * @brief  Used to terminate all required mutex variable for LE adapter implementation.
 *
 * @return  void
-*
 */
 void CATerminateBleAdapterMutex();
+
+/**
+* @fn  CALEDataDestroyer
+* @brief  Used to free data
+*
+* @return  void
+*/
 static void CALEDataDestroyer(void *data, uint32_t size);
 
 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
@@ -253,8 +261,8 @@ CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
 
     CAInitializeLEAdapter();
 
-    CASetBleServerThreadPoolHandle(handle);
     CASetBleClientThreadPoolHandle(handle);
+    CASetBleServerThreadPoolHandle(handle);
     CASetBleAdapterThreadPoolHandle(handle);
     CASetBLEReqRespServerCallback(CABLEServerReceivedData);
     CASetBLEReqRespClientCallback(CABLEClientReceivedData);
@@ -263,7 +271,7 @@ CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
     CALERegisterNetworkNotifications(netCallback);
 
     CAConnectivityHandler_t connHandler;
-    connHandler.startAdapter = NULL;
+    connHandler.startAdapter = CAStartLE;
     connHandler.stopAdapter = CAStopLE;
     connHandler.startListenServer = CAStartLEListeningServer;
     connHandler.startDiscoveryServer = CAStartLEDiscoveryServer;
@@ -279,6 +287,15 @@ CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
     return CA_STATUS_OK;
 }
 
+CAResult_t CAStartLE()
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG,
+        "There is no concept of unicast/multicast in LE. So This function is not implemented");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
 CAResult_t CAStopLE()
 {
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
@@ -327,7 +344,6 @@ void CATerminateLE()
     CATerminateBleAdapterMutex();
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
-    return;
 }
 
 CAResult_t CAStartLEListeningServer()
@@ -357,10 +373,11 @@ CAResult_t CAStartLEListeningServer()
 
     CAStartBleGattServer();
 
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
     ca_mutex_lock(g_bleIsServerMutex);
     g_isServer = true;
     ca_mutex_unlock(g_bleIsServerMutex);
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
 }
 
@@ -412,7 +429,7 @@ uint32_t CASendLENotification(const CARemoteEndpoint_t *endpoint, const void *da
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
-    return CA_STATUS_OK;
+    return 0;
 }
 
 CAResult_t CAReadLEData()
@@ -514,10 +531,16 @@ CAResult_t CAGetLEInterfaceInformation(CALocalConnectivity_t **info, uint32_t *s
 
     char *local_address = NULL;
 
-    CAGetLEAddress(&local_address);
+    CAResult_t res = CAGetLEAddress(&local_address);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
+        return res;
+    }
+
     if (NULL == local_address)
     {
-        OIC_LOG(ERROR, CALEADAPTER_TAG, "Get local bt adapter address failed");
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
         return CA_STATUS_FAILED;
     }
 
@@ -526,6 +549,7 @@ CAResult_t CAGetLEInterfaceInformation(CALocalConnectivity_t **info, uint32_t *s
     if (NULL == (*info))
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
+        OICFree(local_address);
         return CA_STATUS_FAILED;
     }
 
@@ -542,17 +566,17 @@ CAResult_t CAGetLEInterfaceInformation(CALocalConnectivity_t **info, uint32_t *s
     return CA_STATUS_OK;
 }
 
-int32_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback)
+CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback)
 {
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
     ca_mutex_lock(g_bleNetworkCbMutex);
     g_networkCallback = netCallback;
     ca_mutex_unlock(g_bleNetworkCbMutex);
-
+    CAResult_t res = CA_STATUS_OK;
     if (netCallback)
     {
-        CAResult_t res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
+        res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
         if (CA_STATUS_OK != res)
         {
             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
@@ -560,7 +584,7 @@ int32_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback)
     }
     else
     {
-        CAResult_t res = CAUnSetLEAdapterStateChangedCb();
+        res = CAUnSetLEAdapterStateChangedCb();
         if (CA_STATUS_OK != res)
         {
             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
@@ -568,13 +592,14 @@ int32_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback)
     }
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
-    return CA_STATUS_OK;
+    return res;
 }
 
 void CALEDeviceStateChangedCb( CAAdapterState_t adapter_state)
 {
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
+    VERIFY_NON_NULL_VOID(g_localBLEAddress, NULL, "g_localBLEAddress is null");
     CALocalConnectivity_t localEndpoint = {};
 
     ca_mutex_lock(g_bleLocalAddressMutex);
@@ -606,7 +631,6 @@ void CALEDeviceStateChangedCb( CAAdapterState_t adapter_state)
     ca_mutex_unlock(g_bleNetworkCbMutex);
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
-    return;
 }
 
 CAResult_t CAInitBleAdapterMutex()
@@ -739,7 +763,6 @@ void CATerminateBleAdapterMutex()
     g_bleAdapterReqRespCbMutex = NULL;
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
-    return;
 }
 
 void CAInitBleQueues()
@@ -761,7 +784,6 @@ void CAInitBleQueues()
     }
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
-    return;
 }
 
 CAResult_t CAInitBleServerQueues()
@@ -867,34 +889,34 @@ CAResult_t CAInitBleClientSenderQueue()
 {
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
-    if (g_bLEClientSendQueueHandle)
+    if (g_bleClientSendQueueHandle)
     {
         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
         return CA_STATUS_OK;
     }
 
     // Create send message queue
-    g_bLEClientSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
-    if (!g_bLEClientSendQueueHandle)
+    g_bleClientSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
+    if (!g_bleClientSendQueueHandle)
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
         return CA_MEMORY_ALLOC_FAILED;
     }
 
-    if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bLEClientSendQueueHandle, g_bleAdapterThreadPool,
+    if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientSendQueueHandle, g_bleAdapterThreadPool,
             CABLEClientSendDataThread, CALEDataDestroyer))
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
-        OICFree(g_bLEClientSendQueueHandle);
-        g_bLEClientSendQueueHandle = NULL;
+        OICFree(g_bleClientSendQueueHandle);
+        g_bleClientSendQueueHandle = NULL;
         return CA_STATUS_FAILED;
     }
 
-    if (CA_STATUS_OK != CAQueueingThreadStart(g_bLEClientSendQueueHandle))
+    if (CA_STATUS_OK != CAQueueingThreadStart(g_bleClientSendQueueHandle))
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
-        OICFree(g_bLEClientSendQueueHandle);
-        g_bLEClientSendQueueHandle = NULL;
+        OICFree(g_bleClientSendQueueHandle);
+        g_bleClientSendQueueHandle = NULL;
         return CA_STATUS_FAILED;
     }
 
@@ -958,7 +980,7 @@ CAResult_t CAInitBleClientReceiverQueue()
         if (!g_bleClientReceiverQueue)
         {
             OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
-            OICFree(g_bLEClientSendQueueHandle);
+            OICFree(g_bleClientSendQueueHandle);
             return CA_MEMORY_ALLOC_FAILED;
         }
 
@@ -966,7 +988,7 @@ CAResult_t CAInitBleClientReceiverQueue()
                 CABLEClientDataReceiverHandler, NULL))
         {
             OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
-            OICFree(g_bLEClientSendQueueHandle);
+            OICFree(g_bleClientSendQueueHandle);
             OICFree(g_bleClientReceiverQueue);
             g_bleClientReceiverQueue = NULL;
             return CA_STATUS_FAILED;
@@ -989,9 +1011,9 @@ void CAStopBleQueues()
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
     ca_mutex_lock(g_bleClientSendDataMutex);
-    if (NULL != g_bLEClientSendQueueHandle)
+    if (NULL != g_bleClientSendQueueHandle)
     {
-        CAQueueingThreadStop(g_bLEClientSendQueueHandle);
+        CAQueueingThreadStop(g_bleClientSendQueueHandle);
     }
     ca_mutex_unlock(g_bleClientSendDataMutex);
 
@@ -1023,9 +1045,9 @@ void CATerminateBleQueues()
 {
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
-    CAQueueingThreadDestroy(g_bLEClientSendQueueHandle);
-    OICFree(g_bLEClientSendQueueHandle);
-    g_bLEClientSendQueueHandle = NULL;
+    CAQueueingThreadDestroy(g_bleClientSendQueueHandle);
+    OICFree(g_bleClientSendQueueHandle);
+    g_bleClientSendQueueHandle = NULL;
 
 
     CAQueueingThreadDestroy(g_bleClientReceiverQueue);
@@ -1054,7 +1076,7 @@ void CABLEServerDataReceiverHandler(void *threadData)
     static bool isHeaderAvailable = false;
     static CARemoteEndpoint_t *remoteEndpoint = NULL;
 
-    ca_mutex_lock(g_bleClientReceiveDataMutex);
+    ca_mutex_lock(g_bleServerReceiveDataMutex);
 
     if (g_dataReceiverHandlerState)
     {
@@ -1063,7 +1085,7 @@ void CABLEServerDataReceiverHandler(void *threadData)
         CALEData_t *bleData = (CALEData_t *) threadData;
         if (!bleData)
         {
-            OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid wifidata!");
+            OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bleData!");
             return;
         }
 
@@ -1130,11 +1152,11 @@ void CABLEServerDataReceiverHandler(void *threadData)
             isHeaderAvailable = false;
             OICFree(defragData);
             CAAdapterFreeRemoteEndpoint(remoteEndpoint);
-            ca_mutex_unlock(g_bleClientReceiveDataMutex);
+            u_mutex_unlock(g_bleServerReceiveDataMutex);
             return;
         }
     }
-    ca_mutex_unlock(g_bleClientReceiveDataMutex);
+    u_mutex_unlock(g_bleServerReceiveDataMutex);
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
 }
 
@@ -1247,7 +1269,10 @@ void CABLEServerSendDataThread(void *threadData)
     char *header = (char *) OICCalloc(CA_HEADER_LENGTH, sizeof(char));
     VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "Malloc failed");
 
-    char *dataSegment = (char *) OICCalloc(bleData->dataLen + CA_HEADER_LENGTH + 1, sizeof(char));
+    int32_t totalLength = bleData->dataLen + CA_HEADER_LENGTH;
+
+    OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server total Data length with header is [%d]", totalLength);
+    char *dataSegment = (char *) OICCalloc(totalLength + 1, sizeof(char));
     if (NULL == dataSegment)
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
@@ -1268,67 +1293,118 @@ void CABLEServerSendDataThread(void *threadData)
     OICFree(header);
 
     int32_t length = 0;
-    if (CA_SUPPORTED_BLE_MTU_SIZE >= bleData->dataLen)
+    if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
     {
-        length = bleData->dataLen + CA_HEADER_LENGTH;
-        OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "length [%d]", length);
+        length = totalLength;
         memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data, bleData->dataLen);
     }
     else
     {
         length =  CA_SUPPORTED_BLE_MTU_SIZE;
-        OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "length [%d]", length);
         memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data,
                CA_SUPPORTED_BLE_MTU_SIZE - CA_HEADER_LENGTH);
     }
 
-    int32_t iter = bleData->dataLen / CA_SUPPORTED_BLE_MTU_SIZE;
+    int32_t iter = totalLength / CA_SUPPORTED_BLE_MTU_SIZE;
     int32_t index = 0;
-    ca_mutex_lock(g_bleServerSendDataMutex);
     // Send the first segment with the header.
-    result = CAUpdateCharacteristicsInGattServer(dataSegment, length);
-    if (CA_STATUS_OK != result )
-    {
-        OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsInGattServer failed");
-        OICFree(dataSegment);
-        ca_mutex_unlock(g_bleServerSendDataMutex);
-        return ;
-    }
-
-    for (index = 1; index < iter; index++)
+     if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
     {
-        // Send the remaining header.
-        OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Sending the chunk number [%d]", index);
-        result = CAUpdateCharacteristicsInGattServer(
-                     bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH),
-                     CA_SUPPORTED_BLE_MTU_SIZE);
-        if (CA_STATUS_OK != result )
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Unicast Data");
+        result = CAUpdateCharacteristicsToGattClient(
+                    bleData->remoteEndpoint->addressInfo.LE.leMacAddress, dataSegment, length);
+        if (CA_STATUS_OK != result)
         {
-            OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsInGattServer failed");
+            OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
             OICFree(dataSegment);
-            ca_mutex_unlock(g_bleServerSendDataMutex);
-            return ;
+            return;
+        }
+
+        OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
+        for (index = 1; index < iter; index++)
+        {
+            // Send the remaining header.
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Sending the chunk number [%d]", index);
+            result = CAUpdateCharacteristicsToGattClient(
+                         bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
+                         bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH),
+                         CA_SUPPORTED_BLE_MTU_SIZE);
+            if (CA_STATUS_OK != result)
+            {
+                OIC_LOG_V(ERROR, CALEADAPTER_TAG,
+                            "Update characteristics failed, result [%d]", result);
+                OICFree(dataSegment);
+                return;
+            }
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]",
+                                               CA_SUPPORTED_BLE_MTU_SIZE);
         }
-    }
 
-    if (bleData->dataLen / CA_SUPPORTED_BLE_MTU_SIZE)
+        int32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
+        if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
+        {
+            // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
+            OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
+            result = CAUpdateCharacteristicsToGattClient(
+                         bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
+                         bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
+                         remainingLen);
+            if (CA_STATUS_OK != result)
+            {
+                OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
+                                                   result);
+                OICFree(dataSegment);
+                return;
+            }
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", remainingLen);
+        }
+     }
+    else
     {
-        // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
-        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
-        result = CAUpdateCharacteristicsInGattServer(
-                     bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
-                     bleData->dataLen % CA_SUPPORTED_BLE_MTU_SIZE + CA_HEADER_LENGTH);
-        if (CA_STATUS_OK != result )
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
+        result = CAUpdateCharacteristicsToAllGattClients(dataSegment, length);
+        if (CA_STATUS_OK != result)
         {
-            OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsInGattServer failed");
+            OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
             OICFree(dataSegment);
-            ca_mutex_unlock(g_bleServerSendDataMutex);
-            return ;
+            return;
+        }
+        OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
+        for (index = 1; index < iter; index++)
+        {
+            // Send the remaining header.
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Sending the chunk number [%d]", index);
+            result = CAUpdateCharacteristicsToAllGattClients(
+                         bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH),
+                         CA_SUPPORTED_BLE_MTU_SIZE);
+            if (CA_STATUS_OK != result)
+            {
+                OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
+                OICFree(dataSegment);
+                return;
+            }
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", CA_SUPPORTED_BLE_MTU_SIZE);
         }
-    }
 
+        int32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
+        if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
+        {
+            // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
+            OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
+            result = CAUpdateCharacteristicsToAllGattClients(
+                         bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
+                         remainingLen);
+            if (CA_STATUS_OK != result)
+            {
+                OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
+                                                   result);
+                OICFree(dataSegment);
+                return;
+            }
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", remainingLen);
+        }
+    }
     OICFree(dataSegment);
-    ca_mutex_unlock(g_bleServerSendDataMutex); // TODO: this mutex required  ?
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
 }
@@ -1347,7 +1423,8 @@ void CABLEClientSendDataThread(void *threadData)
     char *header = (char *) OICCalloc(CA_HEADER_LENGTH, sizeof(char));
     VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "Malloc failed");
 
-    char *dataSegment = (char *) OICCalloc(bleData->dataLen + CA_HEADER_LENGTH + 1, sizeof(char));
+    uint32_t totalLength = bleData->dataLen + CA_HEADER_LENGTH;
+    char *dataSegment = (char *) OICCalloc(totalLength + 1, sizeof(char));
     if (NULL == dataSegment)
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
@@ -1366,119 +1443,130 @@ void CABLEClientSendDataThread(void *threadData)
     memcpy(dataSegment, header, CA_HEADER_LENGTH);
     OICFree(header);
 
-    int32_t length = 0;
-    if (CA_SUPPORTED_BLE_MTU_SIZE >= bleData->dataLen)
+    uint32_t length = 0;
+    if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
     {
-        length = bleData->dataLen + CA_HEADER_LENGTH;
+        length = totalLength;
         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "length [%d]", length);
         memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data, bleData->dataLen);
     }
     else
     {
         length = CA_SUPPORTED_BLE_MTU_SIZE;
-        OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "length [%d]", length);
+        OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "length  [%d]", length);
         memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data,
                CA_SUPPORTED_BLE_MTU_SIZE - CA_HEADER_LENGTH);
     }
 
-    int32_t iter = bleData->dataLen / CA_SUPPORTED_BLE_MTU_SIZE;
-    int32_t index = 0;
-    ca_mutex_lock(g_bleClientSendDataMutex);
-    if (NULL != bleData->remoteEndpoint)
+    uint32_t iter = totalLength / CA_SUPPORTED_BLE_MTU_SIZE;
+    uint32_t index = 0;
+    if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
     {
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
         // Send the first segment with the header.
         result = CAUpdateCharacteristicsToGattServer(bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
                  dataSegment,
                  length,
                  LE_UNICAST, 0);
-        if (CA_STATUS_OK != result )
+
+        if (CA_STATUS_OK != result)
         {
-            OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsToGattServer failed");
+            OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
             OICFree(dataSegment);
-            ca_mutex_unlock(g_bleClientSendDataMutex);
             return ;
         }
 
+        OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", length);
         for (index = 1; index < iter; index++)
         {
             // Send the remaining header.
-            result = CAUpdateCharacteristicsToGattServer(bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
+            result = CAUpdateCharacteristicsToGattServer(
+                     bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
                      bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
                      CA_SUPPORTED_BLE_MTU_SIZE,
                      LE_UNICAST, 0);
-            if (CA_STATUS_OK != result )
+            if (CA_STATUS_OK != result)
             {
-                OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsToGattServer failed");
+                OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
+                                                   result);
                 OICFree(dataSegment);
-                ca_mutex_unlock(g_bleClientSendDataMutex);
-                return ;
+                return;
             }
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]",
+                                               CA_SUPPORTED_BLE_MTU_SIZE);
         }
 
-        if (bleData->dataLen / CA_SUPPORTED_BLE_MTU_SIZE)
+        uint32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
+        if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
         {
             // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
-            result = CAUpdateCharacteristicsToGattServer(bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
+            result = CAUpdateCharacteristicsToGattServer(
+                     bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
                      bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
-                     bleData->dataLen % CA_SUPPORTED_BLE_MTU_SIZE + CA_HEADER_LENGTH,
+                     remainingLen,
                      LE_UNICAST, 0);
-            if (CA_STATUS_OK != result )
+
+            if (CA_STATUS_OK != result)
             {
-                OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsToGattServer failed");
+                OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
+                                                   result);
                 OICFree(dataSegment);
-                ca_mutex_unlock(g_bleClientSendDataMutex);
-                return ;
+                return;
             }
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", remainingLen);
         }
     }
     else
     {
+        //Sending Mulitcast Data
         // Send the first segment with the header.
-        result = CAUpdateCharacteristicsToAllGattServers(dataSegment + (index * length),
-                 length);
-        if (CA_STATUS_OK != result )
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Multicast Data");
+        result = CAUpdateCharacteristicsToAllGattServers(dataSegment, length);
+        if (CA_STATUS_OK != result)
         {
-            OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsToGattServer failed");
+            OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed (all), result [%d]", result);
             OICFree(dataSegment);
-            ca_mutex_unlock(g_bleClientSendDataMutex);
             return ;
         }
+        OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", length);
         // Send the remaining header.
         for (index = 1; index < iter; index++)
         {
             result = CAUpdateCharacteristicsToAllGattServers(
                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
                          CA_SUPPORTED_BLE_MTU_SIZE);
-            if (CA_STATUS_OK != result )
+            if (CA_STATUS_OK != result)
             {
-                OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsToGattServer failed");
+                OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics (all) failed, result [%d]", result);
                 OICFree(dataSegment);
-                ca_mutex_unlock(g_bleClientSendDataMutex);
-                return ;
+                return;
             }
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", CA_SUPPORTED_BLE_MTU_SIZE);
         }
-        if (bleData->dataLen / CA_SUPPORTED_BLE_MTU_SIZE)
+
+        uint32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
+        if ( remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
         {
             // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
             result = CAUpdateCharacteristicsToAllGattServers(
                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
-                         bleData->dataLen % CA_SUPPORTED_BLE_MTU_SIZE + CA_HEADER_LENGTH);
-             if (CA_STATUS_OK != result )
+                          remainingLen);
+            if (CA_STATUS_OK != result)
             {
-                OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsToGattServer failed");
+                OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics (all) failed, result [%d]", result);
                 OICFree(dataSegment);
-                ca_mutex_unlock(g_bleClientSendDataMutex);
-                return ;
+                return;
             }
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", remainingLen);
         }
+
     }
 
     OICFree(dataSegment);
-    ca_mutex_unlock(g_bleClientSendDataMutex);
 
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CABLEClientSendDataThread");
 }
 
 CALEData_t *CACreateBLEData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
@@ -1507,8 +1595,7 @@ CALEData_t *CACreateBLEData(const CARemoteEndpoint_t *remoteEndpoint, const void
 
 void CAFreeBLEData(CALEData_t *bleData)
 {
-    if (!bleData)
-        return;
+    VERIFY_NON_NULL_VOID(bleData, NULL, "Param bleData is NULL");
 
     CAAdapterFreeRemoteEndpoint(bleData->remoteEndpoint);
     OICFree(bleData->data);
@@ -1531,14 +1618,14 @@ CAResult_t CABLEClientSendData(const CARemoteEndpoint_t *remoteEndpoint,
 
     VERIFY_NON_NULL(data, NULL, "Param data is NULL");
 
-    VERIFY_NON_NULL_RET(g_bLEClientSendQueueHandle, CALEADAPTER_TAG,
-                        "g_bLEClientSendQueueHandle is  NULL",
+    VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
+                        "g_bleClientSendQueueHandle is  NULL",
                         CA_STATUS_FAILED);
     VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
                         "g_bleClientSendDataMutex is NULL",
                         CA_STATUS_FAILED);
 
-    VERIFY_NON_NULL_RET(g_bLEClientSendQueueHandle, CALEADAPTER_TAG, "g_bLEClientSendQueueHandle",
+    VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG, "g_bleClientSendQueueHandle",
                         CA_STATUS_FAILED);
 
     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
@@ -1551,7 +1638,7 @@ CAResult_t CABLEClientSendData(const CARemoteEndpoint_t *remoteEndpoint,
     }
     // Add message to send queue
     ca_mutex_lock(g_bleClientSendDataMutex);
-    CAQueueingThreadAddData(g_bLEClientSendQueueHandle, bleData, sizeof(CALEData_t));
+    CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData, sizeof(CALEData_t));
     ca_mutex_unlock(g_bleClientSendDataMutex);
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
@@ -1570,7 +1657,7 @@ CAResult_t CABLEServerSendData(const CARemoteEndpoint_t *remoteEndpoint,
     VERIFY_NON_NULL_RET(g_sendQueueHandle, CALEADAPTER_TAG,
                         "BleClientReceiverQueue is NULL",
                         CA_STATUS_FAILED);
-    VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
+    VERIFY_NON_NULL_RET(g_bleServerSendDataMutex, CALEADAPTER_TAG,
                         "BleClientSendDataMutex is NULL",
                         CA_STATUS_FAILED);
 
index 445cee6..705b486 100644 (file)
@@ -151,23 +151,12 @@ void CABleGattCharacteristicChangedCb(bt_gatt_attribute_h characteristic,
 
     OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Changed characteristic is  [%s]", (char *)characteristic);
     OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Changed characteristic value length [%d]", valueLen);
-    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Changed characteristic value [%s]", value);
-
-    char *data = (char *)OICMalloc(sizeof(char) * (valueLen + 1));
-    if (NULL == data)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "Malloc failed!");
-        return;
-    }
-
-    strncpy(data, (char *)value, valueLen + 1);
 
     ca_mutex_lock(g_bleReqRespClientCbMutex);
     if (NULL == g_bleClientDataReceivedCallback)
     {
         OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "gReqRespCallback is NULL!");
         ca_mutex_unlock(g_bleReqRespClientCbMutex);
-        OICFree(data);
         return;
     }
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Sending data up !");
@@ -175,17 +164,14 @@ void CABleGattCharacteristicChangedCb(bt_gatt_attribute_h characteristic,
     ca_mutex_lock(g_bleServerBDAddressMutex);
     uint32_t sentLength = 0;
     g_bleClientDataReceivedCallback(g_remoteAddress, OIC_BLE_SERVICE_ID,
-                                     data, strlen(data), &sentLength);
+                                     value, valueLen, &sentLength);
 
     OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Sent data Length is %d", sentLength);
     ca_mutex_unlock(g_bleServerBDAddressMutex);
 
     ca_mutex_unlock(g_bleReqRespClientCbMutex);
 
-    OICFree(data);
-
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-    return;
 }
 
 void CABleGattCharacteristicWriteCb(int result, void *userData)
@@ -359,7 +345,6 @@ bool CABleGattCharacteristicsDiscoveredCb(int result,
     }
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
     return true;
-
 }
 
 void CABtGattBondCreatedCb(int result, bt_device_info_s *device_info, void *user_data)
@@ -384,8 +369,8 @@ void CABtGattBondCreatedCb(int result, bt_device_info_s *device_info, void *user
         BLEServiceInfo *bleServiceInfo = NULL;
 
         ca_mutex_lock(g_bleServiceListMutex);
-        CAResult_t retVal = CAGetBLEServiceInfo(g_bLEServiceList, device_info->remote_address, &bleServiceInfo);
-        ca_mutex_unlock(g_bleServiceListMutex);
+        CAResult_t retVal = CAGetBLEServiceInfo(g_bLEServiceList, device_info->remote_address,
+                                                &bleServiceInfo);
         if (CA_STATUS_OK != retVal)
         {
             OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "CAGetBLEServiceInfo failed! ");
@@ -470,12 +455,12 @@ bool CABleGattPrimaryServiceCb(bt_gatt_attribute_h service, int index, int count
     {
         OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Its OIC service");
 
-        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG , "Registering to watch characteristics changes  \n");
+        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG , "Registering to watch characteristics changes");
 
         result = CABleGattWatchCharacteristicChanges(service);
         if (CA_STATUS_OK != result)
         {
-            OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
+            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG,
                       "CABleGattWatchCharacteristicChanges failed!");
             return false;
         }
@@ -529,7 +514,6 @@ bool CABleGattPrimaryServiceCb(bt_gatt_attribute_h service, int index, int count
             OICFree(stTemp->address);
             OICFree(stTemp);
             CAFreeBLEServiceInfo(bleServiceInfo);
-            bleServiceInfo = NULL;
             return false;
         }
 
@@ -669,7 +653,7 @@ void CABtAdapterLeDeviceDiscoveryStateChangedCb(int result,
         }
         else
         {
-            for (int32_t i = discoveryInfo->service_count - 1; i > 0; i--)
+            for (int32_t i = discoveryInfo->service_count - 1; i >= 0; i--)
             {
                 OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "uuid[%d]: [%s]",
                           i, discoveryInfo->service_uuid[i]);
@@ -878,15 +862,6 @@ void CAStopBLEGattClient()
         ca_mutex_unlock(g_bleClientStateMutex);
         return;
     }
-    ca_mutex_unlock(g_bleClientStateMutex);
-
-    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "OUT");
-}
-
-void CATerminateBLEGattClient()
-{
-    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "IN");
-    ca_mutex_lock(g_bleClientStateMutex);
 
     GMainContext  *context_event_loop = NULL;
     // Required for waking up the thread which is running in gmain loop
@@ -907,7 +882,16 @@ void CATerminateBLEGattClient()
         OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "g_eventLoop context is NULL");
     }
 
-    ca_mutex_lock(g_bleServerBDAddressMutex);
+    u_mutex_unlock(g_bleClientStateMutex);
+
+    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "OUT");
+}
+
+void CATerminateBLEGattClient()
+{
+    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "IN");
+    u_mutex_lock(g_bleClientStateMutex);
+
 
     OICFree(g_remoteAddress);
 
@@ -1091,7 +1075,7 @@ CAResult_t CABleGattSetCallbacks()
         return CA_STATUS_FAILED;
     }
 
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Setting bt_device_set_bond_created_cb \n");
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Setting bt_device_set_bond_created_cb");
 
     ret = bt_device_set_bond_created_cb(CABtGattBondCreatedCb, NULL);
     if (BT_ERROR_NONE != ret)
@@ -1128,7 +1112,7 @@ CAResult_t CABleGattWatchCharacteristicChanges(bt_gatt_attribute_h service)
     if (BT_ERROR_NONE != ret)
     {
         OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                  "bt_gatt_watch_characteristic_changes failed  with [%s] \n",
+                  "bt_gatt_watch_characteristic_changes failed  with [%s]",
                   CABTGetErrorMsg(ret));
 
         return CA_STATUS_FAILED;
@@ -1376,7 +1360,7 @@ void CADiscoverDescriptorThread(void *stServiceInfo)
     CAResult_t result = CABleGattDiscoverDescriptor(stTemp->serviceInfo, NULL);
     if (CA_STATUS_OK != result)
     {
-        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG,
                   "bt_gatt_discover_characteristic_descriptor failed");
         bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
         OICFree(stTemp->address);
@@ -1402,7 +1386,7 @@ CAResult_t CABleGattDiscoverDescriptor(bt_gatt_attribute_h service, const char *
     if (BT_ERROR_NONE != ret)
     {
         OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                  "bt_gatt_discover_characteristic_descriptor failed with returns[%s] \n",
+                  "bt_gatt_discover_characteristic_descriptor failed with returns[%s]",
                   CABTGetErrorMsg(ret));
         return CA_STATUS_FAILED;
     }
@@ -1469,7 +1453,7 @@ CAResult_t CASetCharacteristicDescriptorValue(stGattCharDescriptor_t *stGattChar
         if (BT_ERROR_NONE != ret)
         {
             OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                      "bt_gatt_set_characteristic_desc_value_request failed with return[%s] \n",
+                      "bt_gatt_set_characteristic_desc_value_request failed with return[%s]",
                       CABTGetErrorMsg(ret));
             OICFree(strUUID);
             return CA_STATUS_FAILED;
@@ -1497,7 +1481,7 @@ void CAGATTCreateBondThread(void *stServiceInfo)
     CAResult_t  result = CABleGATTCreateBond(stTemp->address);
     if (CA_STATUS_OK != result)
     {
-        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG ,
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG ,
                   "CABleGattDiscoverCharacteristics failed!");
         OICFree(stTemp->address);
         OICFree(stTemp);
@@ -1535,7 +1519,7 @@ CAResult_t CABleGATTCreateBond(const char *remoteAddress)
 }
 
 CAResult_t  CAUpdateCharacteristicsToGattServer(const char *remoteAddress,
-        const char  *data, const int32_t dataLen,
+        const char  *data, const uint32_t dataLen,
         CALETransferType_t type, const int32_t position)
 {
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
@@ -1579,15 +1563,11 @@ CAResult_t  CAUpdateCharacteristicsToGattServer(const char *remoteAddress,
     OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Updating to write char [%s]",
               bleServiceInfo->read_char);
 
-    char *value = (char *) OICMalloc(sizeof(char) * (dataLen + 1));
-    VERIFY_NON_NULL_RET(value, TZ_BLE_CLIENT_TAG, "malloc failed", CA_STATUS_FAILED);
-    strncpy((char *)value, data, dataLen + 1);
-
     OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
-              "Updating the data of length [%d] to [%s] and size of data is [%d] ", dataLen,
-              bleServiceInfo->bdAddress, strlen(value));
+              "Updating the data of length [%d] to [%s]", dataLen,
+              bleServiceInfo->bdAddress);
 
-    int result = bt_gatt_set_characteristic_value_request(bleServiceInfo->read_char, (unsigned char *)value,
+    int result = bt_gatt_set_characteristic_value_request(bleServiceInfo->read_char, (unsigned char *)data,
                      dataLen,
                      CABleGattCharacteristicWriteCb);
     if (BT_ERROR_NONE != result)
@@ -1595,18 +1575,15 @@ CAResult_t  CAUpdateCharacteristicsToGattServer(const char *remoteAddress,
         OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
                   "bt_gatt_set_characteristic_value_request Failed with return val [%d]",
                   result);
-        OICFree(value);
         return CA_STATUS_FAILED;
     }
 
-    OICFree(value);
-
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
     return CA_STATUS_OK;
 }
 
 CAResult_t  CAUpdateCharacteristicsToAllGattServers(const char  *data,
-            int32_t dataLen)
+            uint32_t dataLen)
 {
     OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "IN");
 
index e309496..0acaa5b 100644 (file)
@@ -150,7 +150,7 @@ CAResult_t CAGetLEAdapterState()
     return CA_STATUS_OK;
 }
 
-void CAGetLEAddress(char **local_address)
+CAResult_t CAGetLEAddress(char **local_address)
 {
     OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
 
@@ -163,7 +163,7 @@ void CAGetLEAddress(char **local_address)
     {
         OIC_LOG_V(ERROR, TZ_LE_NWK_MONITOR_TAG, "bt_adapter_get_address failed!, error num [%x]",
                   ret);
-        return;
+        return CA_STATUS_FAILED;
     }
 
     OIC_LOG_V(DEBUG, TZ_LE_NWK_MONITOR_TAG, "bd address[%s]", address);
@@ -171,6 +171,8 @@ void CAGetLEAddress(char **local_address)
     *local_address = address;
 
     OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
+
+    return CA_STATUS_OK;
 }
 
 CAResult_t CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCallback callback)
index 02e01f4..4ea57be 100644 (file)
 
 /**
  * @def CA_BLE_SERVICE_UUID
- * @brief UUID of OIC service. This UUID is common across all platoform for LE transport.
+ * @brief UUID of OIC service. This UUID is common across all platform for LE transport.
  */
 #define CA_BLE_SERVICE_UUID  "713D0000-503E-4C75-BA94-3148F18D941E"
 
 /**
  * @def CA_BLE_READ_CHAR_UUID
- * @brief UUID of read characteristic. This UUID is common across all platoform for LE transport.
+ * @brief UUID of read characteristic. This UUID is common across all platform for LE transport.
  */
 #define CA_BLE_READ_CHAR_UUID "713D0002-503E-4C75-BA94-3148F18D941E"
 
 /**
  * @def CA_BLE_WRITE_CHAR_UUID
- * @brief UUID of write characteristic. This UUID is common across all platoform for LE transport.
+ * @brief UUID of write characteristic. This UUID is common across all platform for LE transport.
  */
 #define CA_BLE_WRITE_CHAR_UUID "713D0003-503E-4C75-BA94-3148F18D941E"
 
@@ -121,13 +121,6 @@ static  ca_mutex g_bleCharacteristicMutex = NULL;
  */
 static  ca_mutex g_bleServiceMutex = NULL;
 
- /**
- * @var g_bleClientBDAddressMutex
- * @brief Mutex to synchronize the client BD Address update on server side.
- */
-static ca_mutex g_bleClientBDAddressMutex = NULL;
-
-
 /**
  * @var g_bleReqRespCbMutex
  * @brief Mutex to synchronize access to the requestResponse callback to be called
@@ -142,13 +135,6 @@ static  ca_mutex g_bleReqRespCbMutex = NULL;
 static ca_mutex g_bleServerThreadPoolMutex = NULL;
 
 /**
- * @struct gRemoteAddress
- * @brief Remote address of Gatt client
- *
- */
-static char *g_remoteClientAddress = NULL;
-
-/**
  * @var g_eventLoop
  * @brief gmainLoop to manage the threads to receive the callback from the platfrom.
  */
@@ -172,12 +158,6 @@ void CABleGattServerConnectionStateChangedCb(int result, bool connected,
     if (connected)
     {
         OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "Connected to [%s]", remoteAddress);
-
-        ca_mutex_lock(g_bleClientBDAddressMutex);
-        g_remoteClientAddress = OICStrdup(remoteAddress);
-        ca_mutex_unlock(g_bleClientBDAddressMutex);
-
-        VERIFY_NON_NULL_VOID(g_remoteClientAddress, TZ_BLE_SERVER_TAG, "Malloc failed");
     }
     OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
 }
@@ -254,7 +234,7 @@ void CAStartBleGattServerThread(void *data)
     char charReadValue[] = {33, 44, 55, 66}; // These are initial random values
 
     ret = CAAddNewCharacteristicsToGattServer(g_gattSvcPath, charReadUUID, charReadValue,
-            CA_BLE_INITIAL_BUF_SIZE, false); // For Read Characteristics.
+            CA_BLE_INITIAL_BUF_SIZE, true); // For Read Characteristics.
     if (CA_STATUS_OK != ret )
     {
         OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "CAAddNewCharacteristicsToGattServer failed");
@@ -268,7 +248,7 @@ void CAStartBleGattServerThread(void *data)
 
 
     ret = CAAddNewCharacteristicsToGattServer(g_gattSvcPath, charWriteUUID, charWriteValue,
-            CA_BLE_INITIAL_BUF_SIZE, true); // For Write Characteristics.
+            CA_BLE_INITIAL_BUF_SIZE, false); // For Write Characteristics.
     if (CA_STATUS_OK != ret )
     {
         OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "CAAddNewCharacteristicsToGattServer failed");
@@ -348,19 +328,7 @@ CAResult_t CAStopBleGattServer()
         ca_mutex_unlock(g_bleServerStateMutex);
         return CA_STATUS_OK;
     }
-    ca_mutex_unlock(g_bleServerStateMutex);
 
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-void CATerminateBleGattServer()
-{
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
-
-    g_isBleGattServerStarted = false;
-
-    ca_mutex_lock(g_bleServerStateMutex);
     GMainContext  *context_event_loop = NULL;
     // Required for waking up the thread which is running in gmain loop
     if ( NULL != g_eventLoop)
@@ -380,6 +348,19 @@ void CATerminateBleGattServer()
         OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "g_eventLoop context is NULL");
     }
 
+    u_mutex_unlock(g_bleServerStateMutex);
+
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CATerminateBleGattServer()
+{
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
+
+    u_mutex_lock(g_bleServerStateMutex);
+
+    g_isBleGattServerStarted = false;
     if (NULL != g_hAdvertiser )
     {
         int ret = 0;
@@ -411,9 +392,6 @@ void CATerminateBleGattServer()
         OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "_bt_gatt_deinit_service failed with ret [%d]", res);
     }
 
-    ca_mutex_lock(g_bleClientBDAddressMutex);
-    OICFree(g_remoteClientAddress);
-    ca_mutex_unlock(g_bleClientBDAddressMutex);
     // free service Path(unique identifier for ble service)
     ca_mutex_lock(g_bleServiceMutex);
     OICFree(g_gattSvcPath);
@@ -477,17 +455,7 @@ CAResult_t CAInitGattServerMutexVariables()
             return CA_STATUS_FAILED;
         }
     }
-
-    if (NULL == g_bleClientBDAddressMutex)
-    {
-        g_bleClientBDAddressMutex = ca_mutex_new();
-        if (NULL == g_bleClientBDAddressMutex)
-        {
-            OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "ca_mutex_new failed");
-            return CA_STATUS_FAILED;
-        }
-    }
-
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
     return CA_STATUS_OK;
 }
 
@@ -497,8 +465,6 @@ void CATerminateGattServerMutexVariables()
     ca_mutex_free(g_bleServerStateMutex);
     g_bleServerStateMutex = NULL;
 
-    ca_mutex_free(g_bleClientBDAddressMutex);
-    g_bleClientBDAddressMutex = NULL;
 
     g_bleServerStateMutex = NULL;
     ca_mutex_free(g_bleServiceMutex);
@@ -622,11 +588,11 @@ CAResult_t CARemoveAllBleServicesFromGattServer()
 
 void CABleGattRemoteCharacteristicWriteCb(char *charPath,
         unsigned char *charValue,
-        int charValueLen, void *userData)
+        int charValueLen, const char *remoteAddress, void *userData)
 {
     OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
 
-    if (NULL == charPath || NULL == charValue)
+    if (NULL == charPath || NULL == charValue || NULL == remoteAddress)
     {
         OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "Param callback values are NULL");
         return;
@@ -654,11 +620,9 @@ void CABleGattRemoteCharacteristicWriteCb(char *charPath,
     }
 
     OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "Sending data up !");
-    ca_mutex_lock(g_bleClientBDAddressMutex);
     uint32_t sentLength = 0;
-    g_bleServerDataReceivedCallback(g_remoteClientAddress, OIC_BLE_SERVICE_ID,
+    g_bleServerDataReceivedCallback(remoteAddress, OIC_BLE_SERVICE_ID,
                                      data, charValueLen, &sentLength);
-    ca_mutex_unlock(g_bleClientBDAddressMutex);
 
     ca_mutex_unlock(g_bleReqRespCbMutex);
 
@@ -692,9 +656,17 @@ CAResult_t CAAddNewCharacteristicsToGattServer(const char *svcPath, const char *
 
     OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
 
-    static const char *charFlags[] = {"read", "write", "notify", "indicate"};
+    char *charFlags[1];
+    if(read)
+    {
+        charFlags[0] = "notify";
+    }
+    else
+    {
+        charFlags[0] = "write-without-response";
+    }
 
-    static const size_t flagLen = sizeof(charFlags) / sizeof(charFlags[0]);
+    size_t flagLen = sizeof(charFlags) / sizeof(charFlags[0]);
 
     char *charPath = NULL;
     int ret = bt_gatt_add_characteristic(charUUID, charValue, charValueLen, charFlags, flagLen,
@@ -712,7 +684,7 @@ CAResult_t CAAddNewCharacteristicsToGattServer(const char *svcPath, const char *
 
     ca_mutex_lock(g_bleCharacteristicMutex);
 
-    if (!read)
+    if (read)
     {
         if (NULL != g_gattReadCharPath)
         {
@@ -744,7 +716,58 @@ CAResult_t CARemoveCharacteristicsFromGattServer(const char *charPath)
     return CA_STATUS_OK;
 }
 
-CAResult_t CAUpdateCharacteristicsInGattServer(const char *charValue,
+CAResult_t CAUpdateCharacteristicsToGattClient(const char* address, const char *charValue,
+        const uint32_t charValueLen)
+{
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
+
+    VERIFY_NON_NULL(charValue, NULL, "Param charValue is NULL");
+
+    VERIFY_NON_NULL(address, NULL, "Param address is NULL");
+
+    OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "Client's Unicast address for sending data [%s]", address);
+
+    u_mutex_lock(g_bleCharacteristicMutex);
+
+    if (NULL  == g_gattWriteCharPath)
+    {
+        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "gGattWriteCharPath is NULL");
+        u_mutex_unlock(g_bleCharacteristicMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    char *data = (char *) OICMalloc(sizeof(char) * (charValueLen + 1));
+    if (NULL == data)
+    {
+        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "malloc failed!");
+        u_mutex_unlock(g_bleCharacteristicMutex);
+        return CA_STATUS_FAILED;
+    }
+    memset(data, 0x0, (charValueLen + 1));
+
+    strncpy(data, charValue, charValueLen);
+
+    OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "updating characteristics char [%s] data [%s] dataLen [%d]",
+              (const char *)g_gattWriteCharPath, data, charValueLen);
+
+    int ret =  bt_gatt_update_characteristic(g_gattWriteCharPath, data, charValueLen, address);
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
+                  "bt_gatt_update_characteristic failed with return [%d]", ret);
+        OICFree(data);
+        u_mutex_unlock(g_bleCharacteristicMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    OICFree(data);
+    u_mutex_unlock(g_bleCharacteristicMutex);
+
+    OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAUpdateCharacteristicsToAllGattClients(const char *charValue,
         const uint32_t charValueLen)
 {
     OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
@@ -773,13 +796,12 @@ CAResult_t CAUpdateCharacteristicsInGattServer(const char *charValue,
     OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "updating characteristics char [%s] data [%s] dataLen [%d]",
               (const char *)g_gattWriteCharPath, data, charValueLen);
 
-    int ret =  bt_gatt_update_characteristic(g_gattWriteCharPath, data, charValueLen);
+    int ret =  bt_gatt_update_characteristic(g_gattWriteCharPath, data, charValueLen, NULL);
     if (0 != ret)
     {
         OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
                   "bt_gatt_update_characteristic failed with return [%d]", ret);
         OICFree(data);
-        data = NULL;
         ca_mutex_unlock(g_bleCharacteristicMutex);
         return CA_STATUS_FAILED;
     }
index 69b3434..9d98e50 100644 (file)
@@ -165,12 +165,14 @@ CAResult_t CARemoveCharacteristicsFromGattServer(const char *charPath);
  *                            identifier for added characteristics.
  * @param  charValue     [IN] data which is send by client.
  * @param  charValueLen  [IN] length of the data.
+ * @param  remoteAddress [IN] remote device bluetooth address in which data is received.
  * @param  userData      [IN] user data
  *
  * @return NONE
  */
 void CABleGattRemoteCharacteristicWriteCb(char *charPath, unsigned char *charValue,
-                                          int charValueLen, void *userData);
+                                          int charValueLen, const char  *remoteAddress,
+                                          void *userData);
 
 /**
  * @brief  This is the callback which will be called whenever there is change in gatt connection
index cce3156..340dc14 100644 (file)
@@ -161,8 +161,6 @@ CAResult_t CAAddBLEServiceInfoToList(BLEServiceList **serviceList,
     if (NULL == node)
     {
         OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "Malloc failed!");
-        OICFree(bleServiceInfo->bdAddress);
-        OICFree(bleServiceInfo);
         return CA_STATUS_FAILED;
     }