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