Implemented Linux BLE transport.
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / bt_le_adapter / caleadapter.c
1 /* ****************************************************************
2  *
3  * Copyright 2014 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  ******************************************************************/
20 #include "caleadapter.h"
21
22 #include <stdio.h>
23 #include <stdlib.h>
24
25 #include "caleinterface.h"
26 #include "cacommon.h"
27 #include "camutex.h"
28 #include "caadapterutils.h"
29 #ifndef SINGLE_THREAD
30 #include "caqueueingthread.h"
31 #endif
32 #include "cafragmentation.h"
33 #include "oic_malloc.h"
34 #include "oic_string.h"
35 #include "caremotehandler.h"
36
37 /**
38  * Logging tag for module name.
39  */
40 #define CALEADAPTER_TAG "LAD"
41
42
43 /**
44  * Stores the information of the Data to be sent from the queues.
45  *
46  * This structure will be pushed to the sender/receiver queue for
47  * processing.
48  */
49 typedef struct
50 {
51     CAEndpoint_t *remoteEndpoint;   /**< Remote endpoint contains the
52                                        information of remote device. */
53     void *data;        /**< Data to be transmitted over LE transport. */
54     uint32_t dataLen;  /**< Length of the data being transmitted. */
55 } CALEData_t;
56
57 /**
58  * Stores information of all the senders.
59  *
60  * This structure will be used to track and defragment all incoming
61  * data packet.
62  */
63 typedef struct
64 {
65     uint32_t recvDataLen;
66     uint32_t totalDataLen;
67     char *defragData;
68     CAEndpoint_t *remoteEndpoint;
69  } CABLESenderInfo_t;
70
71 /**
72  * Callback to provide the status of the network change to CA layer.
73  */
74 static CANetworkChangeCallback g_networkCallback = NULL;
75
76 /**
77  * bleAddress of the local adapter. Value will be initialized to zero,
78  * and will be updated later.
79  */
80 static char g_localBLEAddress[18] = { 0 };
81
82 /**
83  * Variable to differentiate btw GattServer and GattClient.
84  */
85 static bool g_isServer = false;
86
87 /**
88  * Mutex to synchronize the task to be executed on the GattServer
89  * function calls.
90  */
91 static ca_mutex g_bleIsServerMutex = NULL;
92
93 /**
94  * Mutex to synchronize the callback to be called for the network
95  * changes.
96  */
97 static ca_mutex g_bleNetworkCbMutex = NULL;
98
99 /**
100  * Mutex to synchronize the updates of the local LE address of the
101  * adapter.
102  */
103 static ca_mutex g_bleLocalAddressMutex = NULL;
104
105 /**
106  * Reference to thread pool.
107  */
108 static ca_thread_pool_t g_bleAdapterThreadPool = NULL;
109
110 /**
111  * Mutex to synchronize the task to be pushed to thread pool.
112  */
113 static ca_mutex g_bleAdapterThreadPoolMutex = NULL;
114
115 /**
116  * Mutex to synchronize the queing of the data from SenderQueue.
117  */
118 static ca_mutex g_bleClientSendDataMutex = NULL;
119
120 /**
121  * Mutex to synchronize the queing of the data from ReceiverQueue.
122  */
123 static ca_mutex g_bleReceiveDataMutex = NULL;
124
125
126 /**
127  * Mutex to synchronize the queing of the data from SenderQueue.
128  */
129 static ca_mutex g_bleServerSendDataMutex = NULL;
130
131 /**
132  * Mutex to synchronize the callback to be called for the
133  * adapterReqResponse.
134  */
135 static ca_mutex g_bleAdapterReqRespCbMutex = NULL;
136
137 /**
138  * Callback to be called when network packet received from either
139  * GattServer or GattClient.
140  */
141 static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
142
143 /**
144  * Callback to notify error from the BLE adapter.
145  */
146 static CAErrorHandleCallback g_errorHandler = NULL;
147
148 /**
149  * Storing Adapter state information.
150  */
151 static CAAdapterState_t g_bleAdapterState = CA_ADAPTER_DISABLED;
152
153 /**
154  * BLE Server Status.
155  *
156  * This enumeration provides information of LE Adapter Server status.
157  */
158 typedef enum
159 {
160     CA_SERVER_NOTSTARTED = 0,
161     CA_LISTENING_SERVER,
162     CA_DISCOVERY_SERVER
163 } CALeServerStatus;
164
165 /**
166  * Structure to maintain the status of the server.
167  */
168 static CALeServerStatus gLeServerStatus = CA_SERVER_NOTSTARTED;
169
170 /**
171  * Register network change notification callback.
172  *
173  * @param[in]  netCallback CANetworkChangeCallback callback which will
174  *                         be set for the change in network.
175  *
176  * @return  0 on success otherwise a positive error value.
177  * @retval  ::CA_STATUS_OK  Successful.
178  * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
179  * @retval  ::CA_STATUS_FAILED Operation failed.
180  *
181  */
182 static CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback);
183
184 /**
185  * Set the thread pool handle which is required for spawning new
186  * thread.
187  *
188  * @param[in] handle Thread pool handle which is given by above layer
189  *                   for using thread creation task.
190  *
191  */
192 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle);
193
194 /**
195  * Call the callback to the upper layer when the device state gets
196  * changed.
197  *
198  * @param[in] adapter_state New state of the adapter to be notified to
199  *                          the upper layer.
200  */
201 static void CALEDeviceStateChangedCb( CAAdapterState_t adapter_state);
202
203 /**
204  * Used to initialize all required mutex variable for LE Adapter
205  * implementation.
206  *
207  * @return  0 on success otherwise a positive error value.
208  * @retval  ::CA_STATUS_OK  Successful.
209  * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
210  * @retval  ::CA_STATUS_FAILED Operation failed.
211  *
212  */
213 static CAResult_t CAInitLEAdapterMutex();
214
215 /**
216  * Terminate all required mutex variables for LE adapter
217  * implementation.
218  */
219 static void CATerminateLEAdapterMutex();
220
221 /**
222  * Prepares and notify error through error callback.
223  *
224  */
225 static void CALEErrorHandler(const char *remoteAddress,
226                              const void *data,
227                              uint32_t dataLen,
228                              CAResult_t result);
229
230 #ifndef SINGLE_THREAD
231 /**
232  * Stop condition of recvhandler.
233  */
234 static bool g_dataReceiverHandlerState = false;
235
236 /**
237  * Sender information.
238  */
239 static u_arraylist_t *g_senderInfo = NULL;
240
241 /**
242  * Queue to process the outgoing packets from GATTClient.
243  */
244 static CAQueueingThread_t *g_bleClientSendQueueHandle = NULL;
245
246 /**
247  * Queue to process the incoming packets to GATT Client.
248  */
249 static CAQueueingThread_t *g_bleReceiverQueue = NULL;
250
251 /**
252  * Queue to process the outgoing packets from GATTServer.
253  */
254 static CAQueueingThread_t *g_bleServerSendQueueHandle = NULL;
255
256 /**
257  * Starting LE connectivity adapters.
258  *
259  * As its peer to peer it does not require to start any servers.
260  *
261  * @return ::CA_STATUS_OK or Appropriate error code.
262  */
263 static CAResult_t CAStartLE();
264
265 /**
266  * Start listening server for receiving multicast search requests.
267  *
268  * Transport Specific Behavior:
269  *   LE  Starts GATT Server with prefixed UUID and Characteristics
270  *   per OIC Specification.
271  * @return  ::CA_STATUS_OK or Appropriate error code.
272  */
273 static CAResult_t CAStartLEListeningServer();
274
275 /**
276  * Sarting discovery of servers for receiving multicast
277  * advertisements.
278  *
279  * Transport Specific Behavior:
280  *   LE  Starts GATT Server with prefixed UUID and Characteristics
281  *   per OIC Specification.
282  *
283  * @return ::CA_STATUS_OK or Appropriate error code
284  */
285 static CAResult_t CAStartLEDiscoveryServer();
286
287 /**
288  * Send data to the endpoint using the adapter connectivity.
289  *
290  * @param[in] endpoint Remote Endpoint information (like MAC address,
291  *                     reference URI and connectivity type) to which
292  *                     the unicast data has to be sent.
293  * @param[in] data     Data which required to be sent.
294  * @param[in] dataLen  Size of data to be sent.
295  *
296  * @note  dataLen must be > 0.
297  *
298  * @return The number of bytes sent on the network, or -1 on error.
299  */
300 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
301                                    const void *data,
302                                    uint32_t dataLen);
303
304 /**
305  * Send multicast data to the endpoint using the LE connectivity.
306  *
307  * @param[in] endpoint Remote Endpoint information to which the
308  *                     multicast data has to be sent.
309  * @param[in] data     Data which required to be sent.
310  * @param[in] dataLen  Size of data to be sent.
311  *
312  * @note  dataLen must be > 0.
313  *
314  * @return The number of bytes sent on the network, or -1 on error.
315  */
316 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
317                                      const void *data,
318                                      uint32_t dataLen);
319
320 /**
321  * Get LE Connectivity network information.
322  *
323  * @param[out] info Local connectivity information structures.
324  * @param[out] size Number of local connectivity structures.
325  *
326  * @return ::CA_STATUS_OK or Appropriate error code.
327  */
328 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info,
329                                               uint32_t *size);
330
331 /**
332  * Read Synchronous API callback.
333  *
334  * @return  ::CA_STATUS_OK or Appropriate error code.
335  */
336 static CAResult_t CAReadLEData();
337
338 /**
339  * Stopping the adapters and close socket connections.
340  *
341  * LE Stops all GATT servers and GATT Clients.
342  *
343  * @return ::CA_STATUS_OK or Appropriate error code.
344  */
345 static CAResult_t CAStopLE();
346
347 /**
348  * Terminate the LE connectivity adapter.
349  *
350  * Configuration information will be deleted from further use.
351  */
352 static void CATerminateLE();
353
354 /**
355  * This function will receive the data from the GattServer and add the
356  * data to the Server receiver queue.
357  *
358  * @param[in] remoteAddress Remote address of the device from where
359  *                          data is received.
360  * @param[in] data          Actual data recevied from the remote
361  *                          device.
362  * @param[in] dataLength    Length of the data received from the
363  *                          remote device.
364  * @param[in] sentLength    Length of the data sent from the remote
365  *                          device.
366  *
367  * @return ::CA_STATUS_OK or Appropriate error code.
368  * @retval ::CA_STATUS_OK  Successful.
369  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
370  * @retval ::CA_STATUS_FAILED Operation failed.
371  *
372  */
373 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
374                                                 const void *data,
375                                                 uint32_t dataLength,
376                                                 uint32_t *sentLength);
377
378 /**
379  * This function will receive the data from the GattClient and add the
380  * data into the Client receiver queue.
381  *
382  * @param[in] remoteAddress Remote address of the device from where
383  *                          data is received.
384  * @param[in] data          Actual data recevied from the remote
385  *                          device.
386  * @param[in] dataLength    Length of the data received from the
387  *                          remote device.
388  * @param[in] sentLength    Length of the data sent from the remote
389  *                          device.
390  *
391  * @return ::CA_STATUS_OK or Appropriate error code.
392  * @retval ::CA_STATUS_OK  Successful.
393  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
394  * @retval ::CA_STATUS_FAILED Operation failed.
395  */
396 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
397                                                 const void *data,
398                                                 uint32_t dataLength,
399                                                 uint32_t *sentLength);
400
401 /**
402  * Set the NetworkPacket received callback to CA layer from adapter
403  * layer.
404  *
405  * @param[in] callback Callback handle sent from the upper layer.
406  */
407 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
408
409 /**
410  * Push the data from CA layer to the Sender processor queue.
411  *
412  * @param[in] remoteEndpoint Remote endpoint information of the
413  *                           server.
414  * @param[in] data           Data to be transmitted from LE.
415  * @param[in] dataLen        Length of the Data being transmitted.
416  *
417  * @return ::CA_STATUS_OK or Appropriate error code.
418  * @retval ::CA_STATUS_OK  Successful.
419  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
420  * @retval ::CA_STATUS_FAILED Operation failed.
421  */
422 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
423                                             const void *data,
424                                             uint32_t dataLen);
425
426 /**
427  * Push the data from CA layer to the Sender processor queue.
428  *
429  * @param[in] remoteEndpoint Remote endpoint information of the
430  *                           server.
431  * @param[in] data           Data to be transmitted from LE.
432  * @param[in] dataLen        Length of the Data being transmitted.
433  *
434  * @return ::CA_STATUS_OK or Appropriate error code.
435  * @retval ::CA_STATUS_OK  Successful.
436  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
437  * @retval ::CA_STATUS_FAILED Operation failed.
438  */
439 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
440                                             const void *data,
441                                             uint32_t dataLen);
442
443 /**
444  * This function will be associated with the sender queue for
445  * GattServer.
446  *
447  * This function will fragment the data to the MTU of the transport
448  * and send the data in fragments to the adapters. The function will
449  * be blocked until all data is sent out from the adapter.
450  *
451  * @param[in] threadData Data pushed to the queue which contains the
452  *                       info about RemoteEndpoint and Data.
453  */
454 static void CALEServerSendDataThread(void *threadData);
455
456 /**
457  * This function will be associated with the sender queue for
458  * GattClient.
459  *
460  * This function will fragment the data to the MTU of the transport
461  * and send the data in fragments to the adapters. The function will
462  * be blocked until all data is sent out from the adapter.
463  *
464  * @param[in] threadData Data pushed to the queue which contains the
465  *                       info about RemoteEndpoint and Data.
466  */
467 static void CALEClientSendDataThread(void *threadData);
468
469 /**
470  * This function will be associated with the receiver queue.
471  *
472  * This function will defragment the received data from each sender
473  * respectively and will send it up to CA layer.  Respective sender's
474  * header will provide the length of the data sent.
475  *
476  * @param[in] threadData Data pushed to the queue which contains the
477  *                       info about RemoteEndpoint and Data.
478  */
479 static void CALEDataReceiverHandler(void *threadData);
480
481 /**
482  * This function will stop all queues created for GattServer and
483  * GattClient. All four queues will be be stopped with this function
484  * invocations.
485  */
486 static void CAStopLEQueues();
487
488 /**
489  * This function will terminate all queues created for GattServer and
490  * GattClient. All four queues will be be terminated with this
491  * function invocations.
492  */
493 static void CATerminateLEQueues();
494
495 /**
496  * This function will initalize the Receiver and Sender queues for
497  * GattServer. This function will in turn call the functions
498  * CAInitBleServerReceiverQueue() and CAInitBleServerSenderQueue() to
499  * initialize the queues.
500  *
501  * @return ::CA_STATUS_OK or Appropriate error code.
502  * @retval ::CA_STATUS_OK  Successful.
503  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
504  * @retval ::CA_STATUS_FAILED Operation failed.
505  */
506 static CAResult_t CAInitLEServerQueues();
507
508 /**
509  * This function will initalize the Receiver and Sender queues for
510  * GattClient. This function will inturn call the functions
511  * CAInitBleClientReceiverQueue() and CAInitBleClientSenderQueue() to
512  * initialize the queues.
513  *
514  * @return ::CA_STATUS_OK or Appropriate error code.
515  * @retval ::CA_STATUS_OK  Successful.
516  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
517  * @retval ::CA_STATUS_FAILED Operation failed.
518  *
519  */
520 static CAResult_t CAInitLEClientQueues();
521
522 /**
523  * This function will initalize the Receiver queue for
524  * GattServer. This will initialize the queue to process the function
525  * CABLEServerSendDataThread() when ever the task is added to this
526  * queue.
527  *
528  * @return ::CA_STATUS_OK or Appropriate error code.
529  * @retval ::CA_STATUS_OK  Successful.
530  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
531  * @retval ::CA_STATUS_FAILED Operation failed.
532  */
533 static CAResult_t CAInitLEServerSenderQueue();
534
535 /**
536  * This function will initalize the Receiver queue for
537  * GattClient. This will initialize the queue to process the function
538  * CABLEClientSendDataThread() when ever the task is added to this
539  * queue.
540  *
541  * @return ::CA_STATUS_OK or Appropriate error code.
542  * @retval ::CA_STATUS_OK  Successful.
543  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
544  * @retval ::CA_STATUS_FAILED Operation failed.
545  */
546 static CAResult_t CAInitLEClientSenderQueue();
547
548 /**
549  * This function will initialize the Receiver queue for
550  * LEAdapter. This will initialize the queue to process the function
551  * CABLEDataReceiverHandler() when ever the task is added to this
552  * queue.
553  *
554  * @return ::CA_STATUS_OK or Appropriate error code
555  * @retval ::CA_STATUS_OK  Successful
556  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments
557  * @retval ::CA_STATUS_FAILED Operation failed
558  *
559  */
560 static CAResult_t CAInitLEReceiverQueue();
561
562 /**
563  * This function will create the Data required to send it in the
564  * queue.
565  *
566  * @param[in] remoteEndpoint Remote endpoint information of the
567  *                           server.
568  * @param[in] data           Data to be transmitted from LE.
569  * @param[in] dataLength     Length of the Data being transmitted.
570  *
571  * @return ::CA_STATUS_OK or Appropriate error code.
572  * @retval ::CA_STATUS_OK  Successful.
573  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
574  * @retval ::CA_STATUS_FAILED Operation failed.
575  */
576 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
577                                   const void *data,
578                                   uint32_t dataLength);
579
580 /**
581  * Used to free the BLE information stored in the sender/receiver
582  * queues.
583  *
584  * @param[in] bleData Information for a particular data segment.
585  */
586 static void CAFreeLEData(CALEData_t *bleData);
587
588 /**
589  * Free data.
590  */
591 static void CALEDataDestroyer(void *data, uint32_t size);
592
593 static CAResult_t CAInitLEServerQueues()
594 {
595     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
596
597     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
598
599     CAResult_t result = CAInitLEServerSenderQueue();
600     if (CA_STATUS_OK != result)
601     {
602         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerSenderQueue failed");
603         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
604         return CA_STATUS_FAILED;
605     }
606
607     result = CAInitLEReceiverQueue();
608     if (CA_STATUS_OK != result)
609     {
610         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerReceiverQueue failed");
611         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
612         return CA_STATUS_FAILED;
613     }
614
615     g_dataReceiverHandlerState = true;
616
617     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
618
619     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
620     return CA_STATUS_OK;
621 }
622
623 static CAResult_t CAInitLEClientQueues()
624 {
625     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
626
627     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
628
629     CAResult_t result = CAInitLEClientSenderQueue();
630     if (CA_STATUS_OK != result)
631     {
632         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientSenderQueue failed");
633         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
634         return CA_STATUS_FAILED;
635     }
636
637     result = CAInitLEReceiverQueue();
638     if (CA_STATUS_OK != result)
639     {
640         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientReceiverQueue failed");
641         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
642         return CA_STATUS_FAILED;
643     }
644
645     g_dataReceiverHandlerState = true;
646
647     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
648
649     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
650     return CA_STATUS_OK;
651 }
652
653 static CAResult_t CAInitLEReceiverQueue()
654 {
655     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
656     // Check if the message queue is already initialized
657     if (g_bleReceiverQueue)
658     {
659         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
660         return CA_STATUS_OK;
661     }
662
663     // Create recv message queue
664     g_bleReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
665     if (!g_bleReceiverQueue)
666     {
667         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
668         return CA_MEMORY_ALLOC_FAILED;
669     }
670
671     g_senderInfo = u_arraylist_create();
672     if (!g_senderInfo)
673     {
674         OIC_LOG(ERROR, CALEADAPTER_TAG, "ClientInfo memory allcation failed!");
675         OICFree(g_bleReceiverQueue);
676         g_bleReceiverQueue = NULL;
677         return CA_MEMORY_ALLOC_FAILED;
678     }
679
680     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleReceiverQueue, g_bleAdapterThreadPool,
681             CALEDataReceiverHandler, CALEDataDestroyer))
682     {
683         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
684         OICFree(g_bleReceiverQueue);
685         g_bleReceiverQueue = NULL;
686         u_arraylist_free(&g_senderInfo);
687         return CA_STATUS_FAILED;
688     }
689
690     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleReceiverQueue))
691     {
692         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
693         OICFree(g_bleReceiverQueue);
694         g_bleReceiverQueue = NULL;
695         u_arraylist_free(&g_senderInfo);
696         return CA_STATUS_FAILED;
697     }
698
699     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
700     return CA_STATUS_OK;
701 }
702
703 static CAResult_t CAInitLEServerSenderQueue()
704 {
705     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
706     // Check if the message queue is already initialized
707     if (g_bleServerSendQueueHandle)
708     {
709         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Queue is already initialized!");
710         return CA_STATUS_OK;
711     }
712
713     // Create send message queue
714     g_bleServerSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
715     if (!g_bleServerSendQueueHandle)
716     {
717         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
718         return CA_MEMORY_ALLOC_FAILED;
719     }
720
721     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerSendQueueHandle,
722                                                    g_bleAdapterThreadPool,
723                                                    CALEServerSendDataThread, CALEDataDestroyer))
724     {
725         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
726         OICFree(g_bleServerSendQueueHandle);
727         g_bleServerSendQueueHandle = NULL;
728         return CA_STATUS_FAILED;
729     }
730
731     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleServerSendQueueHandle))
732     {
733         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
734         OICFree(g_bleServerSendQueueHandle);
735         g_bleServerSendQueueHandle = NULL;
736         return CA_STATUS_FAILED;
737     }
738
739     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
740     return CA_STATUS_OK;
741 }
742
743 static void CALEClearSenderInfo()
744 {
745     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
746
747     uint32_t listIndex = 0;
748     uint32_t listLength = u_arraylist_length(g_senderInfo);
749     for (listIndex = 0; listIndex < listLength; listIndex++)
750     {
751         CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(g_senderInfo, listIndex);
752         if(!info)
753         {
754             continue;
755         }
756
757         OICFree(info->defragData);
758         CAFreeEndpoint(info->remoteEndpoint);
759         OICFree(info);
760     }
761     u_arraylist_free(&g_senderInfo);
762     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
763 }
764
765 static CAResult_t CAInitLEClientSenderQueue()
766 {
767     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
768
769     if (g_bleClientSendQueueHandle)
770     {
771         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
772         return CA_STATUS_OK;
773     }
774
775     // Create send message queue
776     g_bleClientSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
777     if (!g_bleClientSendQueueHandle)
778     {
779         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
780         return CA_MEMORY_ALLOC_FAILED;
781     }
782
783     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientSendQueueHandle,
784                                                    g_bleAdapterThreadPool,
785                                                    CALEClientSendDataThread, CALEDataDestroyer))
786     {
787         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
788         OICFree(g_bleClientSendQueueHandle);
789         g_bleClientSendQueueHandle = NULL;
790         return CA_STATUS_FAILED;
791     }
792
793     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleClientSendQueueHandle))
794     {
795         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
796         OICFree(g_bleClientSendQueueHandle);
797         g_bleClientSendQueueHandle = NULL;
798         return CA_STATUS_FAILED;
799     }
800
801     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
802     return CA_STATUS_OK;
803 }
804
805 static void CAStopLEQueues()
806 {
807     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
808
809     ca_mutex_lock(g_bleClientSendDataMutex);
810     if (NULL != g_bleClientSendQueueHandle)
811     {
812         CAQueueingThreadStop(g_bleClientSendQueueHandle);
813     }
814     ca_mutex_unlock(g_bleClientSendDataMutex);
815
816     ca_mutex_lock(g_bleServerSendDataMutex);
817     if (NULL != g_bleServerSendQueueHandle)
818     {
819         CAQueueingThreadStop(g_bleServerSendQueueHandle);
820     }
821     ca_mutex_unlock(g_bleServerSendDataMutex);
822
823     ca_mutex_lock(g_bleReceiveDataMutex);
824     if (NULL != g_bleReceiverQueue)
825     {
826         CAQueueingThreadStop(g_bleReceiverQueue);
827     }
828     ca_mutex_unlock(g_bleReceiveDataMutex);
829
830     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
831 }
832
833 static void CATerminateLEQueues()
834 {
835     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
836
837     CAQueueingThreadDestroy(g_bleClientSendQueueHandle);
838     OICFree(g_bleClientSendQueueHandle);
839     g_bleClientSendQueueHandle = NULL;
840
841     CAQueueingThreadDestroy(g_bleServerSendQueueHandle);
842     OICFree(g_bleServerSendQueueHandle);
843     g_bleServerSendQueueHandle = NULL;
844
845     CAQueueingThreadDestroy(g_bleReceiverQueue);
846     OICFree(g_bleReceiverQueue);
847     g_bleReceiverQueue = NULL;
848
849     CALEClearSenderInfo();
850
851     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
852 }
853
854 static CAResult_t CALEGetSenderInfo(char *leAddress,
855                                     CABLESenderInfo_t **senderInfo,
856                                     uint32_t *senderIndex)
857 {
858     VERIFY_NON_NULL_RET(leAddress, CALEADAPTER_TAG, "Ble-Address in-param NULL", CA_STATUS_FAILED);
859     VERIFY_NON_NULL_RET(senderIndex, CALEADAPTER_TAG, "Index in-param NULL", CA_STATUS_FAILED);
860
861     uint32_t listLength = u_arraylist_length(g_senderInfo);
862     uint32_t addrLength = strlen(leAddress);
863     for (uint32_t index = 0; index < listLength; index++)
864     {
865         CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(g_senderInfo, index);
866         if(!info || !(info->remoteEndpoint))
867         {
868             continue;
869         }
870
871         if(!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
872         {
873             *senderIndex = index;
874             if(senderInfo)
875             {
876                 *senderInfo = info;
877             }
878             return CA_STATUS_OK;
879         }
880     }
881
882     return CA_STATUS_FAILED;
883 }
884
885 static void CALEDataReceiverHandler(void *threadData)
886 {
887     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
888
889     ca_mutex_lock(g_bleReceiveDataMutex);
890
891     if (g_dataReceiverHandlerState)
892     {
893         OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
894
895         CALEData_t *bleData = (CALEData_t *) threadData;
896         if (!bleData)
897         {
898             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bleData!");
899             ca_mutex_unlock(g_bleReceiveDataMutex);
900             return;
901         }
902
903         if(!(bleData->remoteEndpoint))
904         {
905             OIC_LOG(ERROR, CALEADAPTER_TAG, "Client RemoteEndPoint NULL!!");
906             ca_mutex_unlock(g_bleReceiveDataMutex);
907             return;
908         }
909
910         CABLESenderInfo_t *senderInfo = NULL;
911         uint32_t senderIndex = 0;
912
913         if(CA_STATUS_OK != CALEGetSenderInfo(bleData->remoteEndpoint->addr,
914                                                 &senderInfo, &senderIndex))
915         {
916             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This is a new client [%s]",
917                                                 bleData->remoteEndpoint->addr);
918         }
919
920         if(!senderInfo)
921         {
922             CABLESenderInfo_t *newSender = (CABLESenderInfo_t*)OICMalloc(sizeof(CABLESenderInfo_t));
923             if(!newSender)
924             {
925                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
926                 ca_mutex_unlock(g_bleReceiveDataMutex);
927                 return;
928             }
929             newSender->recvDataLen = 0;
930             newSender->totalDataLen = 0;
931             newSender->defragData = NULL;
932             newSender->remoteEndpoint = NULL;
933
934             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
935             newSender->totalDataLen = CAParseHeader((char*)bleData->data);
936             if(!(newSender->totalDataLen))
937             {
938                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
939                 OICFree(newSender);
940                 ca_mutex_unlock(g_bleReceiveDataMutex);
941                 return;
942             }
943
944             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
945                                                 newSender->totalDataLen);
946             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%u] bytes",
947                                                 bleData->dataLen);
948
949             newSender->defragData = (char *) OICCalloc(newSender->totalDataLen + 1, sizeof(char));
950
951             if (NULL == newSender->defragData)
952             {
953                 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
954                 OICFree(newSender);
955                 ca_mutex_unlock(g_bleReceiveDataMutex);
956                 return;
957             }
958
959             const char *remoteAddress = bleData->remoteEndpoint->addr;
960             newSender->remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
961                                                             CA_ADAPTER_GATT_BTLE, remoteAddress, 0);
962             if (NULL == newSender->remoteEndpoint)
963             {
964                 OIC_LOG(ERROR, CALEADAPTER_TAG, "remoteEndpoint is NULL!");
965                 OICFree(newSender->defragData);
966                 OICFree(newSender);
967                 ca_mutex_unlock(g_bleReceiveDataMutex);
968                 return;
969             }
970             memcpy(newSender->defragData, bleData->data + CA_HEADER_LENGTH,
971                     bleData->dataLen - CA_HEADER_LENGTH);
972             newSender->recvDataLen += bleData->dataLen - CA_HEADER_LENGTH;
973             u_arraylist_add(g_senderInfo,(void *)newSender);
974
975             //Getting newSender index position in g_senderInfo array list
976             if(CA_STATUS_OK !=
977                 CALEGetSenderInfo(newSender->remoteEndpoint->addr, NULL, &senderIndex))
978             {
979                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Existing sender index not found!!");
980                 OICFree(senderInfo->defragData);
981                 OICFree(senderInfo);
982                 ca_mutex_unlock(g_bleReceiveDataMutex);
983                 return;
984             }
985             senderInfo = newSender;
986         }
987         else
988         {
989             if(senderInfo->recvDataLen + bleData->dataLen > senderInfo->totalDataLen)
990             {
991                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
992                             "Data Length exceeding error!! Receiving [%d] total length [%d]",
993                             senderInfo->recvDataLen + bleData->dataLen, senderInfo->totalDataLen);
994                 u_arraylist_remove(g_senderInfo, senderIndex);
995                 OICFree(senderInfo->defragData);
996                 OICFree(senderInfo);
997                 ca_mutex_unlock(g_bleReceiveDataMutex);
998                 return;
999             }
1000             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]", bleData->dataLen);
1001             memcpy(senderInfo->defragData + senderInfo->recvDataLen, bleData->data,
1002                     bleData->dataLen);
1003             senderInfo->recvDataLen += bleData->dataLen ;
1004             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "totalDatalength  [%d] recveived Datalen [%d]",
1005                                                 senderInfo->totalDataLen, senderInfo->recvDataLen);
1006         }
1007
1008         if (senderInfo->totalDataLen == senderInfo->recvDataLen)
1009         {
1010             ca_mutex_lock(g_bleAdapterReqRespCbMutex);
1011             if (NULL == g_networkPacketReceivedCallback)
1012             {
1013                 OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
1014
1015                 u_arraylist_remove(g_senderInfo, senderIndex);
1016                 OICFree(senderInfo->defragData);
1017                 OICFree(senderInfo);
1018                 ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
1019                 ca_mutex_unlock(g_bleReceiveDataMutex);
1020                 return;
1021             }
1022             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending data up !");
1023             g_networkPacketReceivedCallback(senderInfo->remoteEndpoint,
1024                                                 senderInfo->defragData, senderInfo->recvDataLen);
1025             ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
1026             u_arraylist_remove(g_senderInfo, senderIndex);
1027             senderInfo->remoteEndpoint = NULL;
1028             senderInfo->defragData = NULL;
1029             OICFree(senderInfo);
1030         }
1031     }
1032     ca_mutex_unlock(g_bleReceiveDataMutex);
1033     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1034 }
1035
1036 static void CALEServerSendDataThread(void *threadData)
1037 {
1038     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1039
1040     CALEData_t *bleData = (CALEData_t *) threadData;
1041     if (!bleData)
1042     {
1043         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
1044         return;
1045     }
1046
1047     char *header = (char *) OICCalloc(CA_HEADER_LENGTH, sizeof(char));
1048     VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "Malloc failed");
1049
1050     int32_t totalLength = bleData->dataLen + CA_HEADER_LENGTH;
1051
1052     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server total Data length with header is [%d]", totalLength);
1053     char *dataSegment = (char *) OICCalloc(totalLength + 1, sizeof(char));
1054     if (NULL == dataSegment)
1055     {
1056         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
1057         OICFree(header);
1058         return;
1059     }
1060
1061     CAResult_t result = CAGenerateHeader(header, bleData->dataLen);
1062     if (CA_STATUS_OK != result )
1063     {
1064         OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
1065         OICFree(header);
1066         OICFree(dataSegment);
1067         return ;
1068     }
1069
1070     memcpy(dataSegment, header, CA_HEADER_LENGTH);
1071     OICFree(header);
1072
1073     int32_t length = 0;
1074     if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
1075     {
1076         length = totalLength;
1077         memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data, bleData->dataLen);
1078     }
1079     else
1080     {
1081         length =  CA_SUPPORTED_BLE_MTU_SIZE;
1082         memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data,
1083                CA_SUPPORTED_BLE_MTU_SIZE - CA_HEADER_LENGTH);
1084     }
1085
1086     int32_t iter = totalLength / CA_SUPPORTED_BLE_MTU_SIZE;
1087     int32_t index = 0;
1088     // Send the first segment with the header.
1089      if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
1090     {
1091         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Unicast Data");
1092         result = CAUpdateCharacteristicsToGattClient(
1093                     bleData->remoteEndpoint->addr, dataSegment, length);
1094         if (CA_STATUS_OK != result)
1095         {
1096             OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
1097             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1098             OICFree(dataSegment);
1099             return;
1100         }
1101
1102         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
1103         for (index = 1; index < iter; index++)
1104         {
1105             // Send the remaining header.
1106             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Sending the chunk number [%d]", index);
1107             result = CAUpdateCharacteristicsToGattClient(
1108                          bleData->remoteEndpoint->addr,
1109                          bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH),
1110                          CA_SUPPORTED_BLE_MTU_SIZE);
1111             if (CA_STATUS_OK != result)
1112             {
1113                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1114                             "Update characteristics failed, result [%d]", result);
1115                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1116                 OICFree(dataSegment);
1117                 return;
1118             }
1119             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]",
1120                                                CA_SUPPORTED_BLE_MTU_SIZE);
1121         }
1122
1123         int32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
1124         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1125         {
1126             // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
1127             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1128             result = CAUpdateCharacteristicsToGattClient(
1129                          bleData->remoteEndpoint->addr,
1130                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
1131                          remainingLen);
1132             if (CA_STATUS_OK != result)
1133             {
1134                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1135                                                    result);
1136                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1137                 OICFree(dataSegment);
1138                 return;
1139             }
1140             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", remainingLen);
1141         }
1142      }
1143     else
1144     {
1145         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
1146         result = CAUpdateCharacteristicsToAllGattClients(dataSegment, length);
1147         if (CA_STATUS_OK != result)
1148         {
1149             OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1150                       result);
1151             CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1152             OICFree(dataSegment);
1153             return;
1154         }
1155         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
1156         for (index = 1; index < iter; index++)
1157         {
1158             // Send the remaining header.
1159             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Sending the chunk number [%d]", index);
1160             result = CAUpdateCharacteristicsToAllGattClients(
1161                          bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH),
1162                          CA_SUPPORTED_BLE_MTU_SIZE);
1163             if (CA_STATUS_OK != result)
1164             {
1165                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1166                           result);
1167                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1168                 OICFree(dataSegment);
1169                 return;
1170             }
1171             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", CA_SUPPORTED_BLE_MTU_SIZE);
1172         }
1173
1174         int32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
1175         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1176         {
1177             // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
1178             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1179             result = CAUpdateCharacteristicsToAllGattClients(
1180                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
1181                          remainingLen);
1182             if (CA_STATUS_OK != result)
1183             {
1184                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1185                           result);
1186                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1187                 OICFree(dataSegment);
1188                 return;
1189             }
1190             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", remainingLen);
1191         }
1192     }
1193     OICFree(dataSegment);
1194
1195     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1196 }
1197
1198 static void CALEClientSendDataThread(void *threadData)
1199 {
1200     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1201
1202     CALEData_t *bleData = (CALEData_t *) threadData;
1203     if (!bleData)
1204     {
1205         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
1206         return;
1207     }
1208
1209     char *header = (char *) OICCalloc(CA_HEADER_LENGTH, sizeof(char));
1210     VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "Malloc failed");
1211
1212     uint32_t totalLength = bleData->dataLen + CA_HEADER_LENGTH;
1213     char *dataSegment = (char *) OICCalloc(totalLength + 1, sizeof(char));
1214     if (NULL == dataSegment)
1215     {
1216         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
1217         OICFree(header);
1218         return;
1219     }
1220
1221     CAResult_t result = CAGenerateHeader(header, bleData->dataLen);
1222     if (CA_STATUS_OK != result )
1223     {
1224         OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
1225         OICFree(header);
1226         OICFree(dataSegment);
1227         return ;
1228     }
1229     memcpy(dataSegment, header, CA_HEADER_LENGTH);
1230     OICFree(header);
1231
1232     uint32_t length = 0;
1233     if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
1234     {
1235         length = totalLength;
1236         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "length [%d]", length);
1237         memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data, bleData->dataLen);
1238     }
1239     else
1240     {
1241         length = CA_SUPPORTED_BLE_MTU_SIZE;
1242         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "length  [%d]", length);
1243         memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data,
1244                CA_SUPPORTED_BLE_MTU_SIZE - CA_HEADER_LENGTH);
1245     }
1246
1247     uint32_t iter = totalLength / CA_SUPPORTED_BLE_MTU_SIZE;
1248     uint32_t index = 0;
1249     if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
1250     {
1251         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
1252         // Send the first segment with the header.
1253         result = CAUpdateCharacteristicsToGattServer(bleData->remoteEndpoint->addr,
1254                  dataSegment,
1255                  length,
1256                  LE_UNICAST, 0);
1257
1258         if (CA_STATUS_OK != result)
1259         {
1260             OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
1261             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1262             OICFree(dataSegment);
1263             return ;
1264         }
1265
1266         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", length);
1267         for (index = 1; index < iter; index++)
1268         {
1269             // Send the remaining header.
1270             result = CAUpdateCharacteristicsToGattServer(
1271                      bleData->remoteEndpoint->addr,
1272                      bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
1273                      CA_SUPPORTED_BLE_MTU_SIZE,
1274                      LE_UNICAST, 0);
1275             if (CA_STATUS_OK != result)
1276             {
1277                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1278                                                    result);
1279                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1280                 OICFree(dataSegment);
1281                 return;
1282             }
1283             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]",
1284                                                CA_SUPPORTED_BLE_MTU_SIZE);
1285         }
1286
1287         uint32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
1288         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1289         {
1290             // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
1291             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1292             result = CAUpdateCharacteristicsToGattServer(
1293                      bleData->remoteEndpoint->addr,
1294                      bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
1295                      remainingLen,
1296                      LE_UNICAST, 0);
1297
1298             if (CA_STATUS_OK != result)
1299             {
1300                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1301                                                    result);
1302                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1303                 OICFree(dataSegment);
1304                 return;
1305             }
1306             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", remainingLen);
1307         }
1308     }
1309     else
1310     {
1311         //Sending Mulitcast Data
1312         // Send the first segment with the header.
1313         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Multicast Data");
1314         result = CAUpdateCharacteristicsToAllGattServers(dataSegment, length);
1315         if (CA_STATUS_OK != result)
1316         {
1317             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1318                       "Update characteristics (all) failed, result [%d]", result);
1319             CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1320             OICFree(dataSegment);
1321             return ;
1322         }
1323         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", length);
1324         // Send the remaining header.
1325         for (index = 1; index < iter; index++)
1326         {
1327             result = CAUpdateCharacteristicsToAllGattServers(
1328                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
1329                          CA_SUPPORTED_BLE_MTU_SIZE);
1330             if (CA_STATUS_OK != result)
1331             {
1332                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics (all) failed, result [%d]",
1333                           result);
1334                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1335                 OICFree(dataSegment);
1336                 return;
1337             }
1338             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]",
1339                       CA_SUPPORTED_BLE_MTU_SIZE);
1340         }
1341
1342         uint32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
1343         if ( remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1344         {
1345             // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
1346             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1347             result = CAUpdateCharacteristicsToAllGattServers(
1348                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
1349                           remainingLen);
1350             if (CA_STATUS_OK != result)
1351             {
1352                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1353                           "Update characteristics (all) failed, result [%d]", result);
1354                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1355                 OICFree(dataSegment);
1356                 return;
1357             }
1358             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", remainingLen);
1359         }
1360
1361     }
1362
1363     OICFree(dataSegment);
1364
1365     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CABLEClientSendDataThread");
1366 }
1367
1368 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
1369                                   const void *data,
1370                                   uint32_t dataLength)
1371 {
1372     CALEData_t *bleData = (CALEData_t *) OICMalloc(sizeof(CALEData_t));
1373     if (!bleData)
1374     {
1375         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1376         return NULL;
1377     }
1378
1379     bleData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
1380     bleData->data = (void *)OICCalloc(dataLength + 1, 1);
1381     if (NULL == bleData->data)
1382     {
1383         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1384         CAFreeLEData(bleData);
1385         return NULL;
1386     }
1387     memcpy(bleData->data, data, dataLength);
1388     bleData->dataLen = dataLength;
1389
1390     return bleData;
1391 }
1392
1393 static void CAFreeLEData(CALEData_t *bleData)
1394 {
1395     VERIFY_NON_NULL_VOID(bleData, CALEADAPTER_TAG, "Param bleData is NULL");
1396
1397     CAFreeEndpoint(bleData->remoteEndpoint);
1398     OICFree(bleData->data);
1399     OICFree(bleData);
1400 }
1401
1402 static void CALEDataDestroyer(void *data, uint32_t size)
1403 {
1404     CALEData_t *ledata = (CALEData_t *) data;
1405
1406     CAFreeLEData(ledata);
1407 }
1408 #endif
1409
1410 static CAResult_t CAInitLEAdapterMutex()
1411 {
1412     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1413
1414     if (NULL == g_bleIsServerMutex)
1415     {
1416         g_bleIsServerMutex = ca_mutex_new();
1417         if (NULL == g_bleIsServerMutex)
1418         {
1419             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1420             return CA_STATUS_FAILED;
1421         }
1422     }
1423
1424     if (NULL == g_bleNetworkCbMutex)
1425     {
1426         g_bleNetworkCbMutex = ca_mutex_new();
1427         if (NULL == g_bleNetworkCbMutex)
1428         {
1429             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1430             CATerminateLEAdapterMutex();
1431             return CA_STATUS_FAILED;
1432         }
1433     }
1434
1435     if (NULL == g_bleLocalAddressMutex)
1436     {
1437         g_bleLocalAddressMutex = ca_mutex_new();
1438         if (NULL == g_bleLocalAddressMutex)
1439         {
1440             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1441             CATerminateLEAdapterMutex();
1442             return CA_STATUS_FAILED;
1443         }
1444     }
1445
1446     if (NULL == g_bleAdapterThreadPoolMutex)
1447     {
1448         g_bleAdapterThreadPoolMutex = ca_mutex_new();
1449         if (NULL == g_bleAdapterThreadPoolMutex)
1450         {
1451             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1452             CATerminateLEAdapterMutex();
1453             return CA_STATUS_FAILED;
1454         }
1455     }
1456
1457     if (NULL == g_bleClientSendDataMutex)
1458     {
1459         g_bleClientSendDataMutex = ca_mutex_new();
1460         if (NULL == g_bleClientSendDataMutex)
1461         {
1462             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1463             CATerminateLEAdapterMutex();
1464             return CA_STATUS_FAILED;
1465         }
1466     }
1467
1468     if (NULL == g_bleServerSendDataMutex)
1469     {
1470         g_bleServerSendDataMutex = ca_mutex_new();
1471         if (NULL == g_bleServerSendDataMutex)
1472         {
1473             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1474             CATerminateLEAdapterMutex();
1475             return CA_STATUS_FAILED;
1476         }
1477     }
1478
1479     if (NULL == g_bleAdapterReqRespCbMutex)
1480     {
1481         g_bleAdapterReqRespCbMutex = ca_mutex_new();
1482         if (NULL == g_bleAdapterReqRespCbMutex)
1483         {
1484             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1485             CATerminateLEAdapterMutex();
1486             return CA_STATUS_FAILED;
1487         }
1488     }
1489
1490     if (NULL == g_bleReceiveDataMutex)
1491     {
1492         g_bleReceiveDataMutex = ca_mutex_new();
1493         if (NULL == g_bleReceiveDataMutex)
1494         {
1495             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1496             return CA_STATUS_FAILED;
1497         }
1498     }
1499
1500     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1501     return CA_STATUS_OK;
1502 }
1503
1504 static void CATerminateLEAdapterMutex()
1505 {
1506     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1507
1508     ca_mutex_free(g_bleIsServerMutex);
1509     g_bleIsServerMutex = NULL;
1510
1511     ca_mutex_free(g_bleNetworkCbMutex);
1512     g_bleNetworkCbMutex = NULL;
1513
1514     ca_mutex_free(g_bleLocalAddressMutex);
1515     g_bleLocalAddressMutex = NULL;
1516
1517     ca_mutex_free(g_bleAdapterThreadPoolMutex);
1518     g_bleAdapterThreadPoolMutex = NULL;
1519
1520     ca_mutex_free(g_bleClientSendDataMutex);
1521     g_bleClientSendDataMutex = NULL;
1522
1523     ca_mutex_free(g_bleServerSendDataMutex);
1524     g_bleServerSendDataMutex = NULL;
1525
1526     ca_mutex_free(g_bleAdapterReqRespCbMutex);
1527     g_bleAdapterReqRespCbMutex = NULL;
1528
1529     ca_mutex_free(g_bleReceiveDataMutex);
1530     g_bleReceiveDataMutex = NULL;
1531
1532     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1533 }
1534
1535 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
1536                           CANetworkPacketReceivedCallback reqRespCallback,
1537                           CANetworkChangeCallback netCallback,
1538                           CAErrorHandleCallback errorCallback,
1539                           ca_thread_pool_t handle)
1540 {
1541     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1542
1543     //Input validation
1544     VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null");
1545     VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null");
1546     VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null");
1547
1548     CAResult_t result = CA_STATUS_OK;
1549     result = CAInitLEAdapterMutex();
1550     if (CA_STATUS_OK != result)
1551     {
1552         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
1553         return CA_STATUS_FAILED;
1554     }
1555     result = CAInitializeLENetworkMonitor();
1556     if (CA_STATUS_OK != result)
1557     {
1558         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
1559         return CA_STATUS_FAILED;
1560     }
1561
1562     CAInitializeLEAdapter();
1563
1564     CASetLEClientThreadPoolHandle(handle);
1565     CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
1566     CASetLEServerThreadPoolHandle(handle);
1567     CASetLEAdapterThreadPoolHandle(handle);
1568     CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
1569     CASetLEReqRespAdapterCallback(reqRespCallback);
1570
1571     CASetBLEClientErrorHandleCallback(CALEErrorHandler);
1572     CASetBLEServerErrorHandleCallback(CALEErrorHandler);
1573     CALERegisterNetworkNotifications(netCallback);
1574
1575     g_errorHandler = errorCallback;
1576
1577     static const CAConnectivityHandler_t connHandler =
1578         {
1579             .startAdapter = CAStartLE,
1580             .stopAdapter = CAStopLE,
1581             .startListenServer = CAStartLEListeningServer,
1582             .startDiscoveryServer = CAStartLEDiscoveryServer,
1583             .sendData = CASendLEUnicastData,
1584             .sendDataToAll = CASendLEMulticastData,
1585             .GetnetInfo = CAGetLEInterfaceInformation,
1586             .readData = CAReadLEData,
1587             .terminate = CATerminateLE
1588         };
1589
1590     registerCallback(connHandler, CA_ADAPTER_GATT_BTLE);
1591
1592     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1593
1594     return CA_STATUS_OK;
1595 }
1596
1597 static CAResult_t CAStartLE()
1598 {
1599     OIC_LOG(DEBUG, CALEADAPTER_TAG, __func__);
1600
1601     return CAStartLEAdapter();
1602 }
1603
1604 static CAResult_t CAStopLE()
1605 {
1606     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1607 #ifndef SINGLE_THREAD
1608     CAStopLEQueues();
1609 #endif
1610
1611     ca_mutex_lock(g_bleIsServerMutex);
1612     if (true == g_isServer)
1613     {
1614         CAStopLEGattServer();
1615     }
1616     else
1617     {
1618         CAStopLEGattClient();
1619     }
1620     ca_mutex_unlock(g_bleIsServerMutex);
1621
1622     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1623
1624     return CA_STATUS_OK;
1625 }
1626
1627 static void CATerminateLE()
1628 {
1629     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1630
1631     CASetLEReqRespServerCallback(NULL);
1632     CASetLEReqRespClientCallback(NULL);
1633     CALERegisterNetworkNotifications(NULL);
1634     CASetLEReqRespAdapterCallback(NULL);
1635     CATerminateLENetworkMonitor();
1636
1637     ca_mutex_lock(g_bleIsServerMutex);
1638     if (true == g_isServer)
1639     {
1640         CATerminateLEGattServer();
1641     }
1642     else
1643     {
1644         CATerminateLEGattClient();
1645     }
1646     ca_mutex_unlock(g_bleIsServerMutex);
1647
1648 #ifndef SINGLE_THREAD
1649     CATerminateLEQueues();
1650 #endif
1651     CATerminateLEAdapterMutex();
1652
1653     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1654 }
1655
1656 static CAResult_t CAStartLEListeningServer()
1657 {
1658     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1659     CAResult_t result = CA_STATUS_OK;
1660 #ifndef SINGLE_THREAD
1661     result = CAInitLEServerQueues();
1662     if (CA_STATUS_OK != result)
1663     {
1664         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
1665         return CA_STATUS_FAILED;
1666     }
1667 #endif
1668
1669     result = CAGetLEAdapterState();
1670     if (CA_ADAPTER_NOT_ENABLED == result)
1671     {
1672         gLeServerStatus = CA_LISTENING_SERVER;
1673         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
1674         return CA_STATUS_OK;
1675     }
1676
1677     if (CA_STATUS_FAILED == result)
1678     {
1679         OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
1680         return CA_STATUS_FAILED;
1681     }
1682
1683     CAStartLEGattServer();
1684
1685     ca_mutex_lock(g_bleIsServerMutex);
1686     g_isServer = true;
1687     ca_mutex_unlock(g_bleIsServerMutex);
1688
1689     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1690     return CA_STATUS_OK;
1691 }
1692
1693 static CAResult_t CAStartLEDiscoveryServer()
1694 {
1695     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1696     CAResult_t result = CA_STATUS_OK;
1697 #ifndef SINGLE_THREAD
1698     result = CAInitLEClientQueues();
1699     if (CA_STATUS_OK != result)
1700     {
1701         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
1702         return CA_STATUS_FAILED;
1703     }
1704 #endif
1705     result = CAGetLEAdapterState();
1706     if (CA_ADAPTER_NOT_ENABLED == result)
1707     {
1708         gLeServerStatus = CA_DISCOVERY_SERVER;
1709         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
1710         return CA_STATUS_OK;
1711     }
1712
1713     if (CA_STATUS_FAILED == result)
1714     {
1715         OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
1716         return CA_STATUS_FAILED;
1717     }
1718
1719     CAStartLEGattClient();
1720
1721     ca_mutex_lock(g_bleIsServerMutex);
1722     g_isServer = false;
1723     ca_mutex_unlock(g_bleIsServerMutex);
1724
1725     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1726     return CA_STATUS_OK;
1727 }
1728
1729 static CAResult_t CAReadLEData()
1730 {
1731     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1732 #ifdef SINGLE_THREAD
1733     CACheckLEData();
1734 #endif
1735     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1736     return CA_STATUS_OK;
1737 }
1738
1739 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
1740                                    const void *data,
1741                                    uint32_t dataLen)
1742 {
1743     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1744
1745     //Input validation
1746     VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
1747     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
1748
1749     CAResult_t result = CA_STATUS_FAILED;
1750
1751     ca_mutex_lock(g_bleIsServerMutex);
1752     if (true  == g_isServer)
1753     {
1754         result = CALEAdapterServerSendData(endpoint, data, dataLen);
1755         if (CA_STATUS_OK != result)
1756         {
1757             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data failed\n");
1758             if (g_errorHandler)
1759             {
1760                 g_errorHandler((void *) endpoint, (void *) data, dataLen, result);
1761             }
1762             ca_mutex_unlock(g_bleIsServerMutex);
1763             return -1;
1764         }
1765     }
1766     else
1767     {
1768         result = CALEAdapterClientSendData(endpoint, data, dataLen);
1769         if (CA_STATUS_OK != result)
1770         {
1771             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data failed \n");
1772             if (g_errorHandler)
1773             {
1774                 g_errorHandler(endpoint, data, dataLen, result);
1775             }
1776             ca_mutex_unlock(g_bleIsServerMutex);
1777             return -1;
1778         }
1779     }
1780     ca_mutex_unlock(g_bleIsServerMutex);
1781
1782     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1783     return dataLen;
1784 }
1785
1786 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
1787                                      const void *data,
1788                                      uint32_t dataLen)
1789 {
1790     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1791
1792     //Input validation
1793     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
1794
1795     if (0 >= dataLen)
1796     {
1797         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
1798         return -1;
1799     }
1800
1801     CAResult_t result = CA_STATUS_FAILED;
1802
1803     ca_mutex_lock(g_bleIsServerMutex);
1804     if (true  == g_isServer)
1805     {
1806         result = CALEAdapterServerSendData(NULL, data, dataLen);
1807         if (CA_STATUS_OK != result)
1808         {
1809             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data failed" );
1810
1811             ca_mutex_unlock(g_bleIsServerMutex);
1812             if (g_errorHandler)
1813             {
1814                 g_errorHandler(endpoint, data, dataLen, result);
1815             }
1816             return -1;
1817         }
1818     }
1819     else
1820     {
1821         result = CALEAdapterClientSendData(NULL, data, dataLen);
1822         if (CA_STATUS_OK != result)
1823         {
1824             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data failed" );
1825             if (g_errorHandler)
1826             {
1827                 g_errorHandler(endpoint, data, dataLen, result);
1828             }
1829             ca_mutex_unlock(g_bleIsServerMutex);
1830             return -1;
1831         }
1832     }
1833     ca_mutex_unlock(g_bleIsServerMutex);
1834
1835     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1836     return dataLen;
1837 }
1838
1839 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1840 {
1841     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1842
1843     VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
1844
1845     char *local_address = NULL;
1846
1847     CAResult_t res = CAGetLEAddress(&local_address);
1848     if (CA_STATUS_OK != res)
1849     {
1850         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
1851         return res;
1852     }
1853
1854     if (NULL == local_address)
1855     {
1856         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
1857         return CA_STATUS_FAILED;
1858     }
1859
1860     *size = 0;
1861     (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
1862     if (NULL == (*info))
1863     {
1864         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
1865         OICFree(local_address);
1866         return CA_STATUS_FAILED;
1867     }
1868
1869     size_t local_address_len = strlen(local_address);
1870
1871     if(local_address_len >= sizeof(g_localBLEAddress) ||
1872             local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
1873     {
1874         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
1875         OICFree(*info);
1876         OICFree(local_address);
1877         return CA_STATUS_FAILED;
1878     }
1879
1880     OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
1881     ca_mutex_lock(g_bleLocalAddressMutex);
1882     OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
1883     ca_mutex_unlock(g_bleLocalAddressMutex);
1884
1885     (*info)->adapter = CA_ADAPTER_GATT_BTLE;
1886     *size = 1;
1887     OICFree(local_address);
1888
1889     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1890     return CA_STATUS_OK;
1891 }
1892
1893 static CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback)
1894 {
1895     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1896
1897     ca_mutex_lock(g_bleNetworkCbMutex);
1898     g_networkCallback = netCallback;
1899     ca_mutex_unlock(g_bleNetworkCbMutex);
1900     CAResult_t res = CA_STATUS_OK;
1901     if (netCallback)
1902     {
1903         res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
1904         if (CA_STATUS_OK != res)
1905         {
1906             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
1907         }
1908     }
1909     else
1910     {
1911         res = CAUnSetLEAdapterStateChangedCb();
1912         if (CA_STATUS_OK != res)
1913         {
1914             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
1915         }
1916     }
1917
1918     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1919     return res;
1920 }
1921
1922 static void CALEDeviceStateChangedCb( CAAdapterState_t adapter_state)
1923 {
1924     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1925
1926     VERIFY_NON_NULL_VOID(g_localBLEAddress, CALEADAPTER_TAG, "g_localBLEAddress is null");
1927     CAEndpoint_t localEndpoint = {};
1928
1929     ca_mutex_lock(g_bleLocalAddressMutex);
1930     OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), g_localBLEAddress);
1931     ca_mutex_unlock(g_bleLocalAddressMutex);
1932
1933     g_bleAdapterState = adapter_state;
1934     // Start a GattServer/Client if gLeServerStatus is SET
1935     if (CA_LISTENING_SERVER == gLeServerStatus)
1936     {
1937         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartLEGattServer");
1938         CAStartLEGattServer();
1939     }
1940     else if (CA_DISCOVERY_SERVER == gLeServerStatus)
1941     {
1942         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartBleGattClient");
1943         CAStartLEGattClient();
1944     }
1945     gLeServerStatus = CA_SERVER_NOTSTARTED;
1946
1947     ca_mutex_lock(g_bleNetworkCbMutex);
1948     if (NULL != g_networkCallback)
1949     {
1950         g_networkCallback(&localEndpoint, adapter_state);
1951     }
1952     else
1953     {
1954         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
1955     }
1956     ca_mutex_unlock(g_bleNetworkCbMutex);
1957
1958     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1959 }
1960
1961 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
1962                                             const void *data,
1963                                             uint32_t dataLen)
1964 {
1965     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1966
1967     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1968 #ifndef SINGLE_THREAD
1969     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
1970                         "g_bleClientSendQueueHandle is  NULL",
1971                         CA_STATUS_FAILED);
1972     VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
1973                         "g_bleClientSendDataMutex is NULL",
1974                         CA_STATUS_FAILED);
1975
1976     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG, "g_bleClientSendQueueHandle",
1977                         CA_STATUS_FAILED);
1978
1979     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
1980
1981     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen);
1982     if (!bleData)
1983     {
1984         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
1985         return CA_MEMORY_ALLOC_FAILED;
1986     }
1987     // Add message to send queue
1988     ca_mutex_lock(g_bleClientSendDataMutex);
1989     CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData, sizeof(CALEData_t));
1990     ca_mutex_unlock(g_bleClientSendDataMutex);
1991 #endif
1992     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1993     return CA_STATUS_OK;
1994 }
1995
1996 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
1997                                             const void *data,
1998                                             uint32_t dataLen)
1999 {
2000     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2001
2002     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
2003
2004 #ifdef SINGLE_THREAD
2005     char header[CA_HEADER_LENGTH] = {0};
2006
2007     CAResult_t result = CAGenerateHeader(header, dataLen);
2008
2009     if (CA_STATUS_OK != result)
2010     {
2011         OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
2012         return -1;
2013     }
2014
2015     if (!CAIsLEConnected())
2016     {
2017         OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
2018         return -1;
2019     }
2020
2021     result = CAUpdateCharacteristicsToAllGattClients(header, CA_HEADER_LENGTH);
2022     if (CA_STATUS_OK != result)
2023     {
2024         OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2025         return -1;
2026     }
2027
2028     int32_t dataLimit = dataLen / CA_SUPPORTED_BLE_MTU_SIZE;
2029     for (int32_t iter = 0; iter < dataLimit; iter++)
2030     {
2031         result = CAUpdateCharacteristicsToAllGattClients((data +
2032                                                          (iter * CA_SUPPORTED_BLE_MTU_SIZE)),
2033                                                          CA_SUPPORTED_BLE_MTU_SIZE);
2034         if (CA_STATUS_OK != result)
2035         {
2036             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2037             return -1;
2038         }
2039         CALEDoEvents();
2040     }
2041
2042     uint8_t remainingLen = dataLen % CA_SUPPORTED_BLE_MTU_SIZE;
2043     if(remainingLen)
2044     {
2045         result = CAUpdateCharacteristicsToAllGattClients((data +
2046                                                          (dataLimit * CA_SUPPORTED_BLE_MTU_SIZE)),
2047                                                          remainingLen);
2048         if (CA_STATUS_OK != result)
2049         {
2050             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2051             return -1;
2052         }
2053         CALEDoEvents();
2054     }
2055 #else
2056     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
2057                         "BleClientReceiverQueue is NULL",
2058                         CA_STATUS_FAILED);
2059     VERIFY_NON_NULL_RET(g_bleServerSendDataMutex, CALEADAPTER_TAG,
2060                         "BleClientSendDataMutex is NULL",
2061                         CA_STATUS_FAILED);
2062
2063     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG, "sendQueueHandle",
2064                         CA_STATUS_FAILED);
2065
2066     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
2067
2068     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen);
2069     if (!bleData)
2070     {
2071         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2072         return CA_MEMORY_ALLOC_FAILED;
2073     }
2074     // Add message to send queue
2075     ca_mutex_lock(g_bleServerSendDataMutex);
2076     CAQueueingThreadAddData(g_bleServerSendQueueHandle, bleData, sizeof(CALEData_t));
2077     ca_mutex_unlock(g_bleServerSendDataMutex);
2078 #endif
2079     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2080     return CA_STATUS_OK;
2081 }
2082
2083 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
2084                                                 const void *data,
2085                                                 uint32_t dataLength,
2086                                                 uint32_t *sentLength)
2087 {
2088     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2089
2090     //Input validation
2091     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
2092     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
2093
2094 #ifdef SINGLE_THREAD
2095     if(g_networkPacketReceivedCallback)
2096     {
2097         CAEndpoint_t endPoint = { 0 };   // will be filled by upper layer
2098         endPoint.adapter = CA_ADAPTER_GATT_BTLE;
2099         g_networkPacketReceivedCallback(&endPoint, data, dataLength);
2100     }
2101 #else
2102     VERIFY_NON_NULL_RET(g_bleReceiverQueue, CALEADAPTER_TAG, "g_bleReceiverQueue",
2103                         CA_STATUS_FAILED);
2104
2105     //Add message to data queue
2106     CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
2107                                                           CA_ADAPTER_GATT_BTLE,
2108                                                           remoteAddress, 0);
2109     if (NULL == remoteEndpoint)
2110     {
2111         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
2112         return CA_STATUS_FAILED;
2113     }
2114
2115     // Create bleData to add to queue
2116     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%d]", dataLength);
2117
2118     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLength);
2119     if (!bleData)
2120     {
2121         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2122         CAFreeEndpoint(remoteEndpoint);
2123         return CA_MEMORY_ALLOC_FAILED;
2124     }
2125
2126     CAFreeEndpoint(remoteEndpoint);
2127     // Add message to receiver queue
2128     CAQueueingThreadAddData(g_bleReceiverQueue, bleData, sizeof(CALEData_t));
2129
2130     *sentLength = dataLength;
2131 #endif
2132     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2133     return CA_STATUS_OK;
2134 }
2135
2136 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
2137                                                 const void *data,
2138                                                 uint32_t dataLength,
2139                                                 uint32_t *sentLength)
2140 {
2141     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2142
2143     //Input validation
2144     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
2145     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
2146 #ifndef SINGLE_THREAD
2147     VERIFY_NON_NULL_RET(g_bleReceiverQueue, CALEADAPTER_TAG, "g_bleReceiverQueue",
2148                         CA_STATUS_FAILED);
2149
2150     //Add message to data queue
2151     CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
2152                                                           CA_ADAPTER_GATT_BTLE,
2153                                                           remoteAddress, 0);
2154     if (NULL == remoteEndpoint)
2155     {
2156         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
2157         return CA_STATUS_FAILED;
2158     }
2159
2160     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%d]", dataLength);
2161
2162     // Create bleData to add to queue
2163     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLength);
2164     if (!bleData)
2165     {
2166         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2167         CAFreeEndpoint(remoteEndpoint);
2168         return CA_MEMORY_ALLOC_FAILED;
2169     }
2170
2171     CAFreeEndpoint(remoteEndpoint);
2172     // Add message to receiver queue
2173     CAQueueingThreadAddData(g_bleReceiverQueue, bleData, sizeof(CALEData_t));
2174
2175     *sentLength = dataLength;
2176 #endif
2177     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2178     return CA_STATUS_OK;
2179 }
2180
2181 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
2182 {
2183     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2184
2185     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
2186     g_bleAdapterThreadPool = handle;
2187     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
2188
2189     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2190 }
2191
2192 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
2193 {
2194     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2195
2196     ca_mutex_lock(g_bleAdapterReqRespCbMutex);
2197
2198     g_networkPacketReceivedCallback = callback;
2199
2200     ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
2201
2202     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2203 }
2204
2205 static void CALEErrorHandler(const char *remoteAddress,
2206                              const void *data,
2207                              uint32_t dataLen,
2208                              CAResult_t result)
2209 {
2210     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler IN");
2211
2212     VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
2213     CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS,
2214                                                CA_ADAPTER_GATT_BTLE,
2215                                                remoteAddress,
2216                                                0);
2217     //if required, will be used to build remote end point
2218     g_errorHandler(rep, data, dataLen, result);
2219
2220     CAFreeEndpoint(rep);
2221     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler OUT");
2222 }