04703a9361f64b19e932771534022be3a08f4f2e
[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 "cafragmentation.h"
26
27 #include "caleinterface.h"
28 #include "cacommon.h"
29 #include "camutex.h"
30 #include "caadapterutils.h"
31 #ifndef SINGLE_THREAD
32 #include "caqueueingthread.h"
33 #endif
34 #if defined(__TIZEN__) || defined(__ANDROID__)
35 #include "caleserver.h"
36 #include "caleclient.h"
37 #endif
38 #include "oic_malloc.h"
39 #include "oic_string.h"
40 #include "caremotehandler.h"
41 #include <coap/pdu.h>
42
43 /**
44  * Logging tag for module name.
45  */
46 #define CALEADAPTER_TAG "OIC_CA_LE_ADAP"
47
48 /**
49  * Stores information of all the senders.
50  *
51  * This structure will be used to track and defragment all incoming
52  * data packet.
53  */
54 typedef struct
55 {
56     uint32_t recvDataLen;
57     uint32_t totalDataLen;
58     uint8_t *defragData;
59     CAEndpoint_t *remoteEndpoint;
60  } CABLESenderInfo_t;
61
62 typedef enum
63 {
64     ADAPTER_EMPTY = 1,
65     ADAPTER_BOTH_CLIENT_SERVER,
66     ADAPTER_CLIENT,
67     ADAPTER_SERVER
68 } CABLEAdapter_t;
69
70 /**
71  * Callback to provide the status of the network change to CA layer.
72  */
73 static CAAdapterChangeCallback g_networkCallback = NULL;
74
75 /**
76  * Callback to provide the status of the connection change to CA layer.
77  */
78 static CAConnectionChangeCallback g_connectionCallback = NULL;
79
80 /**
81  * Own port value to identify packet owner. Default port value is 1.
82  */
83 static uint8_t g_localBLESourcePort = 1;
84
85 /**
86  * bleAddress of the local adapter. Value will be initialized to zero,
87  * and will be updated later.
88  */
89 static char g_localBLEAddress[18] = { 0 };
90
91 /**
92  * Variable to differentiate btw GattServer and GattClient.
93  */
94 static CABLEAdapter_t g_adapterType = ADAPTER_EMPTY;
95
96 /**
97  * Mutex to synchronize the task to be executed on the GattServer
98  * function calls.
99  */
100 static ca_mutex g_bleIsServerMutex = NULL;
101
102 /**
103  * Mutex to synchronize the callback to be called for the network
104  * changes.
105  */
106 static ca_mutex g_bleNetworkCbMutex = NULL;
107
108 /**
109  * Mutex to synchronize the updates of the local LE address of the
110  * adapter.
111  */
112 static ca_mutex g_bleLocalAddressMutex = NULL;
113
114 /**
115  * Reference to thread pool.
116  */
117 static ca_thread_pool_t g_bleAdapterThreadPool = NULL;
118
119 /**
120  * Mutex to synchronize the task to be pushed to thread pool.
121  */
122 static ca_mutex g_bleAdapterThreadPoolMutex = NULL;
123
124 /**
125  * Mutex to synchronize the queing of the data from SenderQueue.
126  */
127 static ca_mutex g_bleClientSendDataMutex = NULL;
128
129 /**
130  * Mutex to synchronize the queing of the data from ReceiverQueue.
131  */
132 static ca_mutex g_bleReceiveDataMutex = NULL;
133
134 /**
135  * Mutex to synchronize the queing of the data from SenderQueue.
136  */
137 static ca_mutex g_bleServerSendDataMutex = NULL;
138
139 /**
140  * Mutex to synchronize the callback to be called for the
141  * adapterReqResponse.
142  */
143 static ca_mutex g_bleAdapterReqRespCbMutex = NULL;
144
145 /**
146  * Callback to be called when network packet received from either
147  * GattServer or GattClient.
148  */
149 static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
150
151 /**
152  * Callback to notify error from the BLE adapter.
153  */
154 static CAErrorHandleCallback g_errorHandler = NULL;
155
156 #ifdef SINGLE_THREAD
157 /**
158  * Pointer to defragment received data from single threaded routine.
159  */
160 static CABLESenderInfo_t *g_singleThreadReceiveData = NULL;
161
162 /**
163  * This function will be associated with the receive for single thread.
164  *
165  * This function will defragment the received data from sender
166  * respectively and will send it up to CA layer. Respective sender's
167  * header will provide the length of the data sent.
168  *
169  * @param[in] data       Actual data received from the remote
170  *                       device.
171  * @param[in] dataLen    Length of the data received from the
172  *                       remote device.
173  */
174 static void CALEDataReceiverHandlerSingleThread(const uint8_t *data,
175                                                 uint32_t dataLen);
176
177 /**
178  * This function will be associated with the send for single threaded
179  * GattServer.
180  *
181  * This function will fragment the data to the MTU of the transport
182  * and send the data in fragments to the adapters. The function will
183  * be blocked until all data is sent out from the adapter.
184  *
185  * @param[in] data       Data to be transmitted from LE.
186  * @param[in] dataLen    Length of the Data being transmitted.
187  */
188 static CAResult_t CALEServerSendDataSingleThread(const uint8_t *data,
189                                                  uint32_t dataLen);
190 #endif
191
192 /**
193  * Register network change notification callback.
194  *
195  * @param[in]  netCallback  CAAdapterChangeCallback callback which will
196  *                          be set for the change in adapter.
197  * @param[in]  connCallback CAConnectionChangeCallback callback which will
198  *                          be set for the change in connection.
199  *
200  * @return  0 on success otherwise a positive error value.
201  * @retval  ::CA_STATUS_OK  Successful.
202  * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
203  * @retval  ::CA_STATUS_FAILED Operation failed.
204  *
205  */
206 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
207                                                    CAConnectionChangeCallback connCallback);
208
209 /**
210  * Set the thread pool handle which is required for spawning new
211  * thread.
212  *
213  * @param[in] handle Thread pool handle which is given by above layer
214  *                   for using thread creation task.
215  *
216  */
217 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle);
218
219 /**
220  * Call the callback to the upper layer when the adapter state gets
221  * changed.
222  *
223  * @param[in] adapter_state New state of the adapter to be notified to
224  *                          the upper layer.
225  */
226 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state);
227
228 /**
229  * Call the callback to the upper layer when the device connection state gets
230  * changed.
231  *
232  * @param[in] address      LE address of the device to be notified to the upper layer.
233  * @param[in] isConnected  whether connection state is connected or not.
234  */
235 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
236                                          bool isConnected);
237
238 /**
239  * Used to initialize all required mutex variable for LE Adapter
240  * implementation.
241  *
242  * @return  0 on success otherwise a positive error value.
243  * @retval  ::CA_STATUS_OK  Successful.
244  * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
245  * @retval  ::CA_STATUS_FAILED Operation failed.
246  *
247  */
248 static CAResult_t CAInitLEAdapterMutex();
249
250 /**
251  * Terminate all required mutex variables for LE adapter
252  * implementation.
253  */
254 static void CATerminateLEAdapterMutex();
255
256 /**
257  * Prepares and notify error through error callback.
258  */
259 static void CALEErrorHandler(const char *remoteAddress,
260                              const uint8_t *data,
261                              uint32_t dataLen,
262                              CAResult_t result);
263
264 #ifndef SINGLE_THREAD
265 /**
266  * Stop condition of recvhandler.
267  */
268 static bool g_dataBleReceiverHandlerState = false;
269
270 /**
271  * Sender information.
272  */
273 static u_arraylist_t *g_bleServerSenderInfo = NULL;
274
275 static u_arraylist_t *g_bleClientSenderInfo = NULL;
276
277 /**
278  * Queue to process the outgoing packets from GATTClient.
279  */
280 static CAQueueingThread_t *g_bleClientSendQueueHandle = NULL;
281
282 /**
283  * Queue to process the incoming packets.
284  */
285 static CAQueueingThread_t *g_bleReceiverQueue = NULL;
286
287 /**
288  * Queue to process the outgoing packets from GATTServer.
289  */
290 static CAQueueingThread_t *g_bleServerSendQueueHandle = NULL;
291
292 /**
293  * This function will be associated with the sender queue for
294  * GattServer.
295  *
296  * This function will fragment the data to the MTU of the transport
297  * and send the data in fragments to the adapters. The function will
298  * be blocked until all data is sent out from the adapter.
299  *
300  * @param[in] threadData Data pushed to the queue which contains the
301  *                       info about RemoteEndpoint and Data.
302  */
303 static void CALEServerSendDataThread(void *threadData);
304
305 /**
306  * This function will be associated with the sender queue for
307  * GattClient.
308  *
309  * This function will fragment the data to the MTU of the transport
310  * and send the data in fragments to the adapters. The function will
311  * be blocked until all data is sent out from the adapter.
312  *
313  * @param[in] threadData Data pushed to the queue which contains the
314  *                       info about RemoteEndpoint and Data.
315  */
316 static void CALEClientSendDataThread(void *threadData);
317
318 /**
319  * This function will be associated with the receiver queue.
320  *
321  * This function will defragment the received data from each sender
322  * respectively and will send it up to CA layer.  Respective sender's
323  * header will provide the length of the data sent.
324  *
325  * @param[in] threadData Data pushed to the queue which contains the
326  *                       info about RemoteEndpoint and Data.
327  */
328 static void CALEDataReceiverHandler(void *threadData);
329
330 /**
331  * This function will stop all queues created for GattServer and
332  * GattClient. All four queues will be be stopped with this function
333  * invocations.
334  */
335 static void CAStopLEQueues();
336
337 /**
338  * This function will terminate all queues created for GattServer and
339  * GattClient. All four queues will be be terminated with this
340  * function invocations.
341  */
342 static void CATerminateLEQueues();
343
344 /**
345  * This function will initalize the Receiver and Sender queues for
346  * GattServer. This function will in turn call the functions
347  * CAInitBleServerReceiverQueue() and CAInitBleServerSenderQueue() to
348  * initialize the queues.
349  *
350  * @return ::CA_STATUS_OK or Appropriate error code.
351  * @retval ::CA_STATUS_OK  Successful.
352  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
353  * @retval ::CA_STATUS_FAILED Operation failed.
354  */
355 static CAResult_t CAInitLEServerQueues();
356
357 /**
358  * This function will initalize the Receiver and Sender queues for
359  * GattClient. This function will inturn call the functions
360  * CAInitBleClientReceiverQueue() and CAInitBleClientSenderQueue() to
361  * initialize the queues.
362  *
363  * @return ::CA_STATUS_OK or Appropriate error code.
364  * @retval ::CA_STATUS_OK  Successful.
365  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
366  * @retval ::CA_STATUS_FAILED Operation failed.
367  *
368  */
369 static CAResult_t CAInitLEClientQueues();
370
371 /**
372  * This function will initalize the Receiver queue for
373  * GattServer. This will initialize the queue to process the function
374  * CABLEServerSendDataThread() when ever the task is added to this
375  * queue.
376  *
377  * @return ::CA_STATUS_OK or Appropriate error code.
378  * @retval ::CA_STATUS_OK  Successful.
379  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
380  * @retval ::CA_STATUS_FAILED Operation failed.
381  */
382 static CAResult_t CAInitLEServerSenderQueue();
383
384 /**
385  * This function will initalize the Receiver queue for
386  * GattClient. This will initialize the queue to process the function
387  * CABLEClientSendDataThread() when ever the task is added to this
388  * queue.
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 CAInitLEClientSenderQueue();
396
397 /**
398  * This function will initialize the Receiver queue for
399  * LEAdapter. This will initialize the queue to process the function
400  * CABLEDataReceiverHandler() when ever the task is added to this
401  * queue.
402  *
403  * @return ::CA_STATUS_OK or Appropriate error code
404  * @retval ::CA_STATUS_OK  Successful
405  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments
406  * @retval ::CA_STATUS_FAILED Operation failed
407  *
408  */
409 static CAResult_t CAInitLEReceiverQueue();
410
411 /**
412  * This function will create the Data required to send it in the
413  * queue.
414  *
415  * @param[in] remoteEndpoint Remote endpoint information of the
416  *                           server.
417  * @param[in] data           Data to be transmitted from LE.
418  * @param[in] dataLength     Length of the Data being transmitted.
419  *
420  * @return ::CA_STATUS_OK or Appropriate error code.
421  * @retval ::CA_STATUS_OK  Successful.
422  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
423  * @retval ::CA_STATUS_FAILED Operation failed.
424  */
425 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
426                                   const uint8_t *data,
427                                   uint32_t dataLength,
428                                   u_arraylist_t *senderInfo);
429
430 /**
431  * Used to free the BLE information stored in the sender/receiver
432  * queues.
433  *
434  * @param[in] bleData Information for a particular data segment.
435  */
436 static void CAFreeLEData(CALEData_t *bleData);
437
438 /**
439  * Free data.
440  */
441 static void CALEDataDestroyer(void *data, uint32_t size);
442
443 #ifndef SINGLE_THREAD
444 /**
445  * remove request or response data of send queue.
446  *
447  * @param[in] queueHandle    queue to process the outgoing packets.
448  * @param[in] mutex          mutex related to sender for client / server.
449  * @param[in] address        target address to remove data in queue.
450  */
451 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle,
452                                     ca_mutex mutex,
453                                     const char* address);
454
455 /**
456  * remove all received data of data list from receive queue.
457  *
458  * @param[in] dataInfoList   received data list to remove for client / server.
459  * @param[in] address        target address to remove data in queue.
460  */
461 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList,
462                                        const char* address);
463
464 /**
465  * get received data info and positioned index from the received data list
466  * for client / server which is matched same leAddress and port.
467  *
468  * @param[in]  leAddress       target address to get serderInfo.
469  * @param[in]  port            target port to get serderInfo.
470  * @param[in]  senderInfoList  received data list for client / server.
471  * @param[out] senderInfo      Pointer to contain matched(leAddress and port)
472  *                             received data info.
473  * @param[out] senderIndex     Pointer to contain matched(leAddress and port)
474  *                             received data info index.
475  */
476 static CAResult_t CALEGetSenderInfo(const char *leAddress,
477                                     const uint16_t port,
478                                     u_arraylist_t *senderInfoList,
479                                     CABLESenderInfo_t **senderInfo,
480                                     uint32_t *senderIndex);
481
482 /**
483  * get ports related to remote address. It is need because multi application
484  * can have more than 2 senderInfo using same BLE address. So before remove
485  * receive queue data, should get port list from sender Info.
486  *
487  * @param[in]  leAddress       target address to get port in serderInfo.
488  * @param[in]  senderInfoList  received data list to remove for client / server.
489  * @param[out] portList        target port list related to leAddress.
490  */
491 static CAResult_t CALEGetPortsFromSenderInfo(const char *leAddress,
492                                             u_arraylist_t *senderInfoList,
493                                             u_arraylist_t *portList);
494 #endif
495
496 static CAResult_t CAInitLEServerQueues()
497 {
498     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
499
500     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
501
502     CAResult_t result = CAInitLEServerSenderQueue();
503     if (CA_STATUS_OK != result)
504     {
505         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerSenderQueue failed");
506         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
507         return CA_STATUS_FAILED;
508     }
509
510     g_bleServerSenderInfo = u_arraylist_create();
511     if (!g_bleServerSenderInfo)
512     {
513         OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
514         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
515         return CA_MEMORY_ALLOC_FAILED;
516     }
517
518     result = CAInitLEReceiverQueue();
519     if (CA_STATUS_OK != result)
520     {
521         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEReceiverQueue failed");
522         u_arraylist_free(&g_bleServerSenderInfo);
523         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
524         return CA_STATUS_FAILED;
525     }
526
527     g_dataBleReceiverHandlerState = true;
528
529     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
530
531     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
532     return CA_STATUS_OK;
533 }
534
535 static CAResult_t CAInitLEClientQueues()
536 {
537     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
538
539     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
540
541     CAResult_t result = CAInitLEClientSenderQueue();
542     if (CA_STATUS_OK != result)
543     {
544         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientSenderQueue failed");
545         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
546         return CA_STATUS_FAILED;
547     }
548
549     g_bleClientSenderInfo = u_arraylist_create();
550     if (!g_bleClientSenderInfo)
551     {
552         OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
553         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
554         return CA_MEMORY_ALLOC_FAILED;
555     }
556
557     result = CAInitLEReceiverQueue();
558     if (CA_STATUS_OK != result)
559     {
560         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEReceiverQueue failed");
561         u_arraylist_free(&g_bleClientSenderInfo);
562         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
563         return CA_STATUS_FAILED;
564     }
565
566     g_dataBleReceiverHandlerState = true;
567
568     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
569
570     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
571     return CA_STATUS_OK;
572 }
573
574 static CAResult_t CAInitLEReceiverQueue()
575 {
576     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAInitLEReceiverQueue");
577     // Check if the message queue is already initialized
578     if (g_bleReceiverQueue)
579     {
580         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
581         return CA_STATUS_OK;
582     }
583
584     // Create recv message queue
585     g_bleReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
586     if (!g_bleReceiverQueue)
587     {
588         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
589         return CA_MEMORY_ALLOC_FAILED;
590     }
591
592     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleReceiverQueue,
593                                                    g_bleAdapterThreadPool,
594                                                    CALEDataReceiverHandler,
595                                                    CALEDataDestroyer))
596     {
597         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
598         OICFree(g_bleReceiverQueue);
599         g_bleReceiverQueue = NULL;
600         return CA_STATUS_FAILED;
601     }
602
603     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleReceiverQueue))
604     {
605         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
606         OICFree(g_bleReceiverQueue);
607         g_bleReceiverQueue = NULL;
608         return CA_STATUS_FAILED;
609     }
610
611     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
612     return CA_STATUS_OK;
613 }
614
615 static CAResult_t CAInitLEServerSenderQueue()
616 {
617     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAInitLEServerSenderQueue");
618     // Check if the message queue is already initialized
619     if (g_bleServerSendQueueHandle)
620     {
621         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Queue is already initialized!");
622         return CA_STATUS_OK;
623     }
624
625     // Create send message queue
626     g_bleServerSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
627     if (!g_bleServerSendQueueHandle)
628     {
629         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
630         return CA_MEMORY_ALLOC_FAILED;
631     }
632
633     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerSendQueueHandle,
634                                                    g_bleAdapterThreadPool,
635                                                    CALEServerSendDataThread,
636                                                    CALEDataDestroyer))
637     {
638         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
639         OICFree(g_bleServerSendQueueHandle);
640         g_bleServerSendQueueHandle = NULL;
641         return CA_STATUS_FAILED;
642     }
643
644     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
645     return CA_STATUS_OK;
646 }
647
648 static void CALEClearSenderInfoImpl(u_arraylist_t ** list)
649 {
650     const size_t length = u_arraylist_length(*list);
651     for (size_t i = 0; i < length; ++i)
652     {
653         CABLESenderInfo_t * const info =
654                 (CABLESenderInfo_t *) u_arraylist_get(*list, i);
655         if (info)
656          {
657              OICFree(info->defragData);
658              CAFreeEndpoint(info->remoteEndpoint);
659              OICFree(info);
660          }
661     }
662     u_arraylist_free(list);
663 }
664
665 static void CALEClearSenderInfo()
666 {
667     CALEClearSenderInfoImpl(&g_bleServerSenderInfo);
668     CALEClearSenderInfoImpl(&g_bleClientSenderInfo);
669 }
670
671 static CAResult_t CAInitLEClientSenderQueue()
672 {
673     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAInitLEClientSenderQueue");
674
675     if (g_bleClientSendQueueHandle)
676     {
677         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
678         return CA_STATUS_OK;
679     }
680
681     // Create send message queue
682     g_bleClientSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
683     if (!g_bleClientSendQueueHandle)
684     {
685         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
686         return CA_MEMORY_ALLOC_FAILED;
687     }
688
689     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientSendQueueHandle,
690                                                    g_bleAdapterThreadPool,
691                                                    CALEClientSendDataThread, CALEDataDestroyer))
692     {
693         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
694         OICFree(g_bleClientSendQueueHandle);
695         g_bleClientSendQueueHandle = NULL;
696         return CA_STATUS_FAILED;
697     }
698
699     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CAInitLEClientSenderQueue");
700     return CA_STATUS_OK;
701 }
702
703 static void CAStopLEQueues()
704 {
705     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAStopLEQueues");
706
707     ca_mutex_lock(g_bleReceiveDataMutex);
708     if (NULL != g_bleReceiverQueue)
709     {
710         CAQueueingThreadStop(g_bleReceiverQueue);
711     }
712     ca_mutex_unlock(g_bleReceiveDataMutex);
713
714     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CAStopLEQueues");
715 }
716
717 static void CATerminateLEQueues()
718 {
719     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
720
721     CAQueueingThreadDestroy(g_bleClientSendQueueHandle);
722     OICFree(g_bleClientSendQueueHandle);
723     g_bleClientSendQueueHandle = NULL;
724
725     CAQueueingThreadDestroy(g_bleServerSendQueueHandle);
726     OICFree(g_bleServerSendQueueHandle);
727     g_bleServerSendQueueHandle = NULL;
728
729     CAQueueingThreadDestroy(g_bleReceiverQueue);
730     OICFree(g_bleReceiverQueue);
731     g_bleReceiverQueue = NULL;
732
733     CALEClearSenderInfo();
734
735     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
736 }
737
738 static CAResult_t CALEGetSenderInfo(const char *leAddress,
739                                     const uint16_t port,
740                                     u_arraylist_t *senderInfoList,
741                                     CABLESenderInfo_t **senderInfo,
742                                     uint32_t *senderIndex)
743 {
744     VERIFY_NON_NULL_RET(leAddress,
745                         CALEADAPTER_TAG,
746                         "NULL BLE address argument",
747                         CA_STATUS_INVALID_PARAM);
748     VERIFY_NON_NULL_RET(senderIndex,
749                         CALEADAPTER_TAG,
750                         "NULL index argument",
751                         CA_STATUS_INVALID_PARAM);
752
753     const uint32_t listLength = u_arraylist_length(senderInfoList);
754     const uint32_t addrLength = strlen(leAddress);
755     for (uint32_t index = 0; index < listLength; index++)
756     {
757         CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
758         if (!info || !(info->remoteEndpoint))
759         {
760             continue;
761         }
762
763         if (!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
764         {
765             if (info->remoteEndpoint->port == port)
766             {
767                 *senderIndex = index;
768                 if (senderInfo)
769                 {
770                     *senderInfo = info;
771                 }
772                 return CA_STATUS_OK;
773             }
774         }
775     }
776
777     return CA_STATUS_FAILED;
778 }
779
780 static void CALEDataReceiverHandler(void *threadData)
781 {
782     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEDataReceiverHandler");
783
784     ca_mutex_lock(g_bleReceiveDataMutex);
785
786     if (g_dataBleReceiverHandlerState)
787     {
788         OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
789
790         CALEData_t *bleData = (CALEData_t *) threadData;
791         if (!bleData)
792         {
793             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bleData!");
794             ca_mutex_unlock(g_bleReceiveDataMutex);
795             return;
796         }
797
798         if (!(bleData->senderInfo))
799         {
800             OIC_LOG(ERROR, CALEADAPTER_TAG, "sender info is not available");
801             ca_mutex_unlock(g_bleReceiveDataMutex);
802             return;
803         }
804
805         if (!(bleData->remoteEndpoint))
806         {
807             OIC_LOG(ERROR, CALEADAPTER_TAG, "Client RemoteEndPoint NULL!!");
808             ca_mutex_unlock(g_bleReceiveDataMutex);
809             return;
810         }
811
812         CABLESenderInfo_t *senderInfo = NULL;
813         uint32_t senderIndex = 0;
814
815         //packet parsing
816         CABLEPacketStart_t startFlag = CA_BLE_PACKET_NOT_START;
817         CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
818         uint16_t sourcePort = 0;
819         uint16_t destPort = 0;
820
821         CAParseHeader(bleData->data, &startFlag, &sourcePort, &secureFlag, &destPort);
822         OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
823                   "header info: startFlag[%X] sourcePort[%d] secureFlag[%X] destPort[%d]",
824                   startFlag, sourcePort, secureFlag, destPort);
825
826         if (destPort != g_localBLESourcePort && destPort != CA_BLE_MULTICAST_PORT)
827         {
828             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
829                       "this packet is not valid for this app(port mismatch[mine:%d, packet:%d])",
830                       g_localBLESourcePort, destPort);
831             ca_mutex_unlock(g_bleReceiveDataMutex);
832             return;
833         }
834
835         bleData->remoteEndpoint->port = sourcePort;
836
837         if (CA_STATUS_OK != CALEGetSenderInfo(bleData->remoteEndpoint->addr,
838                                               bleData->remoteEndpoint->port,
839                                               bleData->senderInfo,
840                                               &senderInfo, &senderIndex))
841         {
842             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This is a new client [%s:%X]",
843                       bleData->remoteEndpoint->addr, bleData->remoteEndpoint->port);
844         }
845         else
846         {
847             if (startFlag)
848             {
849                 OIC_LOG(ERROR, CALEADAPTER_TAG,
850                         "This packet is start packet but exist senderInfo. Remove senderInfo");
851                 u_arraylist_remove(bleData->senderInfo, senderIndex);
852                 OICFree(senderInfo->defragData);
853                 OICFree(senderInfo);
854                 senderInfo = NULL;
855                 senderIndex = 0;
856             }
857         }
858
859         if (!senderInfo)
860         {
861             uint32_t totalLength = 0;
862             if (startFlag)
863             {
864                 CAParseHeaderPayloadLength(bleData->data, CA_BLE_LENGTH_HEADER_SIZE, &totalLength);
865             }
866             else
867             {
868                 OIC_LOG(ERROR, CALEADAPTER_TAG, "This packet is wrong packet! ignore.");
869                 ca_mutex_unlock(g_bleReceiveDataMutex);
870                 return;
871             }
872
873             CABLESenderInfo_t *newSender = OICMalloc(sizeof(CABLESenderInfo_t));
874             if (!newSender)
875             {
876                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
877                 ca_mutex_unlock(g_bleReceiveDataMutex);
878                 return;
879             }
880             newSender->recvDataLen = 0;
881             newSender->totalDataLen = 0;
882             newSender->defragData = NULL;
883             newSender->remoteEndpoint = NULL;
884
885             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
886
887             newSender->totalDataLen = totalLength;
888
889             if (!(newSender->totalDataLen))
890             {
891                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
892                 OICFree(newSender);
893                 ca_mutex_unlock(g_bleReceiveDataMutex);
894                 return;
895             }
896
897             size_t dataOnlyLen =
898                 bleData->dataLen - (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE);
899             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
900                       newSender->totalDataLen);
901             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%zu] bytes",
902                       dataOnlyLen);
903
904             newSender->defragData = OICCalloc(newSender->totalDataLen + 1,
905                                               sizeof(*newSender->defragData));
906
907             if (NULL == newSender->defragData)
908             {
909                 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
910                 OICFree(newSender);
911                 ca_mutex_unlock(g_bleReceiveDataMutex);
912                 return;
913             }
914
915             const char *remoteAddress = bleData->remoteEndpoint->addr;
916             newSender->remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
917                                                                CA_ADAPTER_GATT_BTLE,
918                                                                remoteAddress,
919                                                                bleData->remoteEndpoint->port);
920
921             if (NULL == newSender->remoteEndpoint)
922             {
923                 OIC_LOG(ERROR, CALEADAPTER_TAG, "remoteEndpoint is NULL!");
924                 OICFree(newSender->defragData);
925                 OICFree(newSender);
926                 ca_mutex_unlock(g_bleReceiveDataMutex);
927                 return;
928             }
929
930             if (newSender->recvDataLen + dataOnlyLen > newSender->totalDataLen)
931             {
932                 OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
933                 OICFree(newSender->defragData);
934                 CAFreeEndpoint(newSender->remoteEndpoint);
935                 OICFree(newSender);
936                 ca_mutex_unlock(g_bleReceiveDataMutex);
937                 return;
938             }
939             memcpy(newSender->defragData,
940                    bleData->data + (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE),
941                    dataOnlyLen);
942             newSender->recvDataLen += dataOnlyLen;
943
944             u_arraylist_add(bleData->senderInfo,(void *)newSender);
945
946             //Getting newSender index position in bleSenderInfo array list
947             if (CA_STATUS_OK !=
948                     CALEGetSenderInfo(newSender->remoteEndpoint->addr,
949                                       newSender->remoteEndpoint->port,
950                                       bleData->senderInfo,
951                                       NULL, &senderIndex))
952             {
953                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Existing sender index not found!!");
954                 OICFree(newSender->defragData);
955                 CAFreeEndpoint(newSender->remoteEndpoint);
956                 OICFree(newSender);
957                 ca_mutex_unlock(g_bleReceiveDataMutex);
958                 return;
959             }
960             senderInfo = newSender;
961         }
962         else
963         {
964             size_t dataOnlyLen = bleData->dataLen - CA_BLE_HEADER_SIZE;
965             if (senderInfo->recvDataLen + dataOnlyLen > senderInfo->totalDataLen)
966             {
967                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
968                           "Data Length exceeding error!! Receiving [%zu] total length [%u]",
969                           senderInfo->recvDataLen + dataOnlyLen, senderInfo->totalDataLen);
970                 u_arraylist_remove(bleData->senderInfo, senderIndex);
971                 OICFree(senderInfo->defragData);
972                 OICFree(senderInfo);
973                 ca_mutex_unlock(g_bleReceiveDataMutex);
974                 return;
975             }
976             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%zu]",
977                       dataOnlyLen);
978             memcpy(senderInfo->defragData + senderInfo->recvDataLen,
979                    bleData->data + CA_BLE_HEADER_SIZE,
980                    dataOnlyLen);
981             senderInfo->recvDataLen += dataOnlyLen;
982             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "totalDatalength  [%d] received Datalen [%d]",
983                                                 senderInfo->totalDataLen, senderInfo->recvDataLen);
984         }
985
986         if (senderInfo->totalDataLen == senderInfo->recvDataLen)
987         {
988             ca_mutex_lock(g_bleAdapterReqRespCbMutex);
989             if (NULL == g_networkPacketReceivedCallback)
990             {
991                 OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
992
993                 u_arraylist_remove(bleData->senderInfo, senderIndex);
994                 OICFree(senderInfo->defragData);
995                 OICFree(senderInfo);
996                 ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
997                 ca_mutex_unlock(g_bleReceiveDataMutex);
998                 return;
999             }
1000
1001             OIC_LOG(DEBUG, CALEADAPTER_TAG, "[CALEDataReceiverHandler] Sending data up !");
1002
1003             const CASecureEndpoint_t tmp =
1004                 {
1005                     .endpoint = *senderInfo->remoteEndpoint
1006                 };
1007
1008             g_networkPacketReceivedCallback(&tmp,
1009                                             senderInfo->defragData,
1010                                             senderInfo->recvDataLen);
1011             ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
1012             u_arraylist_remove(bleData->senderInfo, senderIndex);
1013             senderInfo->remoteEndpoint = NULL;
1014             senderInfo->defragData = NULL;
1015             OICFree(senderInfo);
1016         }
1017     }
1018     ca_mutex_unlock(g_bleReceiveDataMutex);
1019     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1020 }
1021
1022 static void CALEServerSendDataThread(void *threadData)
1023 {
1024     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEServerSendDataThread");
1025
1026     CALEData_t * const bleData = (CALEData_t *) threadData;
1027     if (!bleData)
1028     {
1029         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
1030         return;
1031     }
1032
1033     uint32_t midPacketCount = 0;
1034     size_t remainingLen = 0;
1035     size_t totalLength = 0;
1036     CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1037
1038     CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
1039                                                            &midPacketCount,
1040                                                            &remainingLen,
1041                                                            &totalLength);
1042
1043     if (CA_STATUS_OK != result)
1044     {
1045         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1046                   "CAGenerateVariableForFragmentation failed, result [%d]", result);
1047         g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1048         return;
1049     }
1050
1051     OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1052               "Packet info: data size[%d] midPacketCount[%u] remainingLen[%zu] totalLength[%zu]",
1053               bleData->dataLen, midPacketCount, remainingLen, totalLength);
1054
1055     OIC_LOG_V(DEBUG,
1056               CALEADAPTER_TAG,
1057               "Server total Data length with header is [%zu]",
1058               totalLength);
1059
1060     uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1061     uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1062
1063     if (NULL != bleData->remoteEndpoint) //Unicast Data
1064     {
1065         secureFlag = bleData->remoteEndpoint->flags == CA_SECURE ?
1066             CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
1067
1068         result = CAGenerateHeader(dataHeader,
1069                                   CA_BLE_PACKET_START,
1070                                   g_localBLESourcePort,
1071                                   secureFlag,
1072                                   bleData->remoteEndpoint->port);
1073     }
1074     else                                //Multicast Data
1075     {
1076         result = CAGenerateHeader(dataHeader,
1077                                   CA_BLE_PACKET_START,
1078                                   g_localBLESourcePort,
1079                                   secureFlag,
1080                                   CA_BLE_MULTICAST_PORT);
1081     }
1082
1083     if (CA_STATUS_OK != result)
1084     {
1085         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1086                   "CAGenerateHeader failed, result [%d]", result);
1087         g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1088         return;
1089     }
1090
1091     uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1092     result = CAGenerateHeaderPayloadLength(lengthHeader,
1093                                            CA_BLE_LENGTH_HEADER_SIZE,
1094                                            bleData->dataLen);
1095
1096     if (CA_STATUS_OK != result)
1097     {
1098         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1099                   "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1100         g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1101         return;
1102     }
1103
1104     uint32_t length = 0;
1105     uint32_t dataLen = 0;
1106     if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
1107     {
1108         length = totalLength;
1109         dataLen = bleData->dataLen;
1110     }
1111     else
1112     {
1113         length = CA_SUPPORTED_BLE_MTU_SIZE;
1114         dataLen = CA_SUPPORTED_BLE_MTU_SIZE - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1115     }
1116
1117     result = CAMakeFirstDataSegment(dataSegment,
1118                                     bleData->data, dataLen,
1119                                     dataHeader, lengthHeader);
1120
1121     if (CA_STATUS_OK != result)
1122     {
1123         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1124                   "Making data segment failed, result [%d]", result);
1125         g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1126         return;
1127     }
1128
1129     const uint32_t iter = midPacketCount;
1130     uint32_t index = 0;
1131
1132     // Send the first segment with the header.
1133     if (NULL != bleData->remoteEndpoint) // Sending Unicast Data
1134     {
1135         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Unicast Data");
1136
1137         result = CAUpdateCharacteristicsToGattClient(
1138                     bleData->remoteEndpoint->addr, dataSegment, length);
1139
1140         if (CA_STATUS_OK != result)
1141         {
1142             OIC_LOG_V(ERROR,
1143                       CALEADAPTER_TAG,
1144                       "Update characteristics failed, result [%d]",
1145                       result);
1146
1147             g_errorHandler(bleData->remoteEndpoint,
1148                            bleData->data,
1149                            bleData->dataLen,
1150                            result);
1151             return;
1152         }
1153
1154         OIC_LOG_V(DEBUG,
1155                   CALEADAPTER_TAG,
1156                   "Server Sent data length [%u]",
1157                   length);
1158
1159         result = CAGenerateHeader(dataHeader,
1160                                   CA_BLE_PACKET_NOT_START,
1161                                   g_localBLESourcePort,
1162                                   secureFlag,
1163                                   bleData->remoteEndpoint->port);
1164
1165         if (CA_STATUS_OK != result)
1166         {
1167             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1168                       "CAGenerateHeader failed, result [%d]", result);
1169             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1170             return;
1171         }
1172
1173         for (index = 0; index < iter; index++)
1174         {
1175             // Send the remaining header.
1176             OIC_LOG_V(DEBUG,
1177                       CALEADAPTER_TAG,
1178                       "Sending the chunk number [%u]",
1179                       index);
1180
1181             result = CAMakeRemainDataSegment(dataSegment,
1182                                              bleData->data,
1183                                              CA_SUPPORTED_BLE_MTU_SIZE - CA_BLE_HEADER_SIZE,
1184                                              index,
1185                                              dataHeader);
1186
1187             if (CA_STATUS_OK != result)
1188             {
1189                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1190                             "Making data segment failed, result [%d]", result);
1191                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1192                 return;
1193             }
1194
1195             result =
1196                 CAUpdateCharacteristicsToGattClient(
1197                     bleData->remoteEndpoint->addr,
1198                     dataSegment,
1199                     CA_SUPPORTED_BLE_MTU_SIZE);
1200
1201             if (CA_STATUS_OK != result)
1202             {
1203                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1204                             "Update characteristics failed, result [%d]", result);
1205                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1206                 return;
1207             }
1208             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]",
1209                                                CA_SUPPORTED_BLE_MTU_SIZE);
1210         }
1211
1212         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1213         {
1214             // send the last segment of the data (Ex: 22 bytes of 622
1215             // bytes of data when MTU is 200)
1216             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1217
1218             result = CAMakeRemainDataSegment(dataSegment,
1219                                              bleData->data,
1220                                              remainingLen,
1221                                              index,
1222                                              dataHeader);
1223
1224             if (CA_STATUS_OK != result)
1225             {
1226                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1227                             "Making data segment failed, result [%d]", result);
1228                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1229                 return;
1230             }
1231
1232             result = CAUpdateCharacteristicsToGattClient(
1233                          bleData->remoteEndpoint->addr,
1234                          dataSegment,
1235                          remainingLen + CA_BLE_HEADER_SIZE);
1236
1237             if (CA_STATUS_OK != result)
1238             {
1239                 OIC_LOG_V(ERROR,
1240                           CALEADAPTER_TAG,
1241                           "Update characteristics failed, result [%d]",
1242                           result);
1243                 g_errorHandler(bleData->remoteEndpoint,
1244                                bleData->data,
1245                                bleData->dataLen,
1246                                result);
1247                 return;
1248             }
1249             OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1250                       "Server Sent data length [%zu]", remainingLen + CA_BLE_HEADER_SIZE);
1251         }
1252      }
1253     else
1254     {
1255         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
1256         result = CAUpdateCharacteristicsToAllGattClients(dataSegment, length);
1257         if (CA_STATUS_OK != result)
1258         {
1259             OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1260                       result);
1261             CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1262             return;
1263         }
1264         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
1265
1266         result = CAGenerateHeader(dataHeader,
1267                                   CA_BLE_PACKET_NOT_START,
1268                                   g_localBLESourcePort,
1269                                   secureFlag,
1270                                   CA_BLE_MULTICAST_PORT);
1271
1272         if (CA_STATUS_OK != result)
1273         {
1274             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1275                       "CAGenerateHeader failed, result [%d]", result);
1276             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1277             return;
1278         }
1279
1280         for (index = 0; index < iter; index++)
1281         {
1282             // Send the remaining header.
1283             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Sending the chunk number [%d]", index);
1284
1285             result = CAMakeRemainDataSegment(dataSegment,
1286                                              bleData->data,
1287                                              CA_SUPPORTED_BLE_MTU_SIZE - CA_BLE_HEADER_SIZE,
1288                                              index,
1289                                              dataHeader);
1290
1291             if (CA_STATUS_OK != result)
1292             {
1293                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1294                             "Making data segment failed, result [%d]", result);
1295                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1296                 return;
1297             }
1298
1299             result = CAUpdateCharacteristicsToAllGattClients(
1300                          dataSegment,
1301                          CA_SUPPORTED_BLE_MTU_SIZE);
1302
1303             if (CA_STATUS_OK != result)
1304             {
1305                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1306                           result);
1307                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1308                 return;
1309             }
1310             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%u]",
1311                       CA_SUPPORTED_BLE_MTU_SIZE);
1312         }
1313
1314         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1315         {
1316             // send the last segment of the data
1317             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1318
1319             result = CAMakeRemainDataSegment(dataSegment,
1320                                              bleData->data,
1321                                              remainingLen,
1322                                              index,
1323                                              dataHeader);
1324
1325             if (CA_STATUS_OK != result)
1326             {
1327                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1328                             "Making data segment failed, result [%d]", result);
1329                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1330                 return;
1331             }
1332
1333             result = CAUpdateCharacteristicsToAllGattClients(
1334                          dataSegment,
1335                          remainingLen + CA_BLE_HEADER_SIZE);
1336
1337             if (CA_STATUS_OK != result)
1338             {
1339                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1340                           result);
1341                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1342                 return;
1343             }
1344             OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1345                       "Server Sent data length [%zu]", remainingLen + CA_BLE_HEADER_SIZE);
1346         }
1347     }
1348
1349     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CALEServerSendDataThread");
1350 }
1351
1352 static void CALEClientSendDataThread(void *threadData)
1353 {
1354     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEClientSendDataThread");
1355
1356     CALEData_t *bleData = (CALEData_t *) threadData;
1357     if (!bleData)
1358     {
1359         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
1360         return;
1361     }
1362
1363     uint32_t midPacketCount = 0;
1364     size_t remainingLen = 0;
1365     size_t totalLength = 0;
1366     CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1367
1368     CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
1369                                                            &midPacketCount,
1370                                                            &remainingLen,
1371                                                            &totalLength);
1372
1373     if (CA_STATUS_OK != result)
1374     {
1375         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1376                   "CAGenerateVariableForFragmentation failed, result [%d]", result);
1377         g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1378         return;
1379     }
1380
1381     OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1382               "Packet info: data size[%d] midPacketCount[%u] remainingLen[%zu] totalLength[%zu]",
1383               bleData->dataLen, midPacketCount, remainingLen, totalLength);
1384
1385     uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1386     uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1387
1388     if (NULL != bleData->remoteEndpoint) //Unicast Data
1389     {
1390         secureFlag = bleData->remoteEndpoint->flags == CA_SECURE ?
1391             CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
1392
1393         result = CAGenerateHeader(dataHeader,
1394                                   CA_BLE_PACKET_START,
1395                                   g_localBLESourcePort,
1396                                   secureFlag,
1397                                   bleData->remoteEndpoint->port);
1398     }
1399     else                                //Multicast Data
1400     {
1401         result = CAGenerateHeader(dataHeader,
1402                                   CA_BLE_PACKET_START,
1403                                   g_localBLESourcePort,
1404                                   secureFlag,
1405                                   CA_BLE_MULTICAST_PORT);
1406     }
1407
1408     if (CA_STATUS_OK != result)
1409     {
1410         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1411                   "CAGenerateHeader failed, result [%d]", result);
1412         g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1413         return;
1414     }
1415
1416     uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1417     result = CAGenerateHeaderPayloadLength(lengthHeader,
1418                                            CA_BLE_LENGTH_HEADER_SIZE,
1419                                            bleData->dataLen);
1420
1421     if (CA_STATUS_OK != result)
1422     {
1423         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1424                   "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1425         g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1426         return;
1427     }
1428
1429     uint32_t length = 0;
1430     uint32_t dataLen = 0;
1431     if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
1432     {
1433         length = totalLength;
1434         dataLen = bleData->dataLen;
1435     }
1436     else
1437     {
1438         length = CA_SUPPORTED_BLE_MTU_SIZE;
1439         dataLen = CA_SUPPORTED_BLE_MTU_SIZE - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1440     }
1441
1442     result = CAMakeFirstDataSegment(dataSegment,
1443                                     bleData->data, dataLen,
1444                                     dataHeader, lengthHeader);
1445
1446     if (CA_STATUS_OK != result)
1447     {
1448         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1449                   "Making data segment failed, result [%d]", result);
1450         g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1451         return;
1452     }
1453
1454     const uint32_t iter = midPacketCount;
1455     uint32_t index = 0;
1456     if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
1457     {
1458         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
1459         // Send the first segment with the header.
1460         result =
1461             CAUpdateCharacteristicsToGattServer(
1462                 bleData->remoteEndpoint->addr,
1463                 dataSegment,
1464                 length,
1465                 LE_UNICAST,
1466                 0);
1467
1468         if (CA_STATUS_OK != result)
1469         {
1470             OIC_LOG_V(ERROR,
1471                       CALEADAPTER_TAG,
1472                       "Update characteristics failed, result [%d]",
1473                       result);
1474             g_errorHandler(bleData->remoteEndpoint,
1475                            bleData->data,
1476                            bleData->dataLen,
1477                            result);
1478             return;
1479         }
1480
1481         OIC_LOG_V(DEBUG,
1482                   CALEADAPTER_TAG,
1483                   "Client Sent Data length  is [%u]",
1484                   length);
1485
1486         result = CAGenerateHeader(dataHeader,
1487                                   CA_BLE_PACKET_NOT_START,
1488                                   g_localBLESourcePort,
1489                                   secureFlag,
1490                                   bleData->remoteEndpoint->port);
1491
1492         if (CA_STATUS_OK != result)
1493         {
1494             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1495                       "CAGenerateHeader failed, result [%d]", result);
1496             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1497             return;
1498         }
1499
1500         for (index = 0; index < iter; index++)
1501         {
1502             result = CAMakeRemainDataSegment(dataSegment,
1503                                              bleData->data,
1504                                              CA_SUPPORTED_BLE_MTU_SIZE - CA_BLE_HEADER_SIZE,
1505                                              index,
1506                                              dataHeader);
1507
1508             if (CA_STATUS_OK != result)
1509             {
1510                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1511                             "Making data segment failed, result [%d]", result);
1512                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1513                 return;
1514             }
1515
1516             // Send the remaining header.
1517             result = CAUpdateCharacteristicsToGattServer(
1518                      bleData->remoteEndpoint->addr,
1519                      dataSegment,
1520                      CA_SUPPORTED_BLE_MTU_SIZE,
1521                      LE_UNICAST, 0);
1522
1523             if (CA_STATUS_OK != result)
1524             {
1525                 OIC_LOG_V(ERROR,
1526                           CALEADAPTER_TAG,
1527                           "Update characteristics failed, result [%d]",
1528                           result);
1529                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1530                 return;
1531             }
1532             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]",
1533                                                CA_SUPPORTED_BLE_MTU_SIZE);
1534         }
1535
1536         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1537         {
1538             // send the last segment of the data (Ex: 22 bytes of 622
1539             // bytes of data when MTU is 200)
1540             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1541
1542             result = CAMakeRemainDataSegment(dataSegment,
1543                                              bleData->data,
1544                                              remainingLen,
1545                                              index,
1546                                              dataHeader);
1547
1548             if (CA_STATUS_OK != result)
1549             {
1550                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1551                             "Making data segment failed, result [%d]", result);
1552                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1553                 return;
1554             }
1555
1556             result = CAUpdateCharacteristicsToGattServer(
1557                      bleData->remoteEndpoint->addr,
1558                      dataSegment,
1559                      remainingLen + CA_BLE_HEADER_SIZE,
1560                      LE_UNICAST, 0);
1561
1562             if (CA_STATUS_OK != result)
1563             {
1564                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1565                                                    result);
1566                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1567                 return;
1568             }
1569             OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1570                       "Client Sent Data length  is [%zu]", remainingLen + CA_BLE_HEADER_SIZE);
1571         }
1572     }
1573     else
1574     {
1575         //Sending Mulitcast Data
1576         // Send the first segment with the header.
1577         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Multicast Data");
1578         result = CAUpdateCharacteristicsToAllGattServers(dataSegment, length);
1579         if (CA_STATUS_OK != result)
1580         {
1581             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1582                       "Update characteristics (all) failed, result [%d]", result);
1583             CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1584             return ;
1585         }
1586         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", length);
1587
1588         result = CAGenerateHeader(dataHeader,
1589                                   CA_BLE_PACKET_NOT_START,
1590                                   g_localBLESourcePort,
1591                                   secureFlag,
1592                                   0);
1593
1594         if (CA_STATUS_OK != result)
1595         {
1596             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1597                       "CAGenerateHeader failed, result [%d]", result);
1598             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1599             return;
1600         }
1601
1602         // Send the remaining header.
1603         for (index = 0; index < iter; index++)
1604         {
1605             result = CAMakeRemainDataSegment(dataSegment,
1606                                              bleData->data,
1607                                              CA_SUPPORTED_BLE_MTU_SIZE - CA_BLE_HEADER_SIZE,
1608                                              index,
1609                                              dataHeader);
1610
1611             if (CA_STATUS_OK != result)
1612             {
1613                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1614                             "Making data segment failed, result [%d]", result);
1615                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1616                 return;
1617             }
1618
1619             result = CAUpdateCharacteristicsToAllGattServers(
1620                          dataSegment,
1621                          CA_SUPPORTED_BLE_MTU_SIZE);
1622
1623             if (CA_STATUS_OK != result)
1624             {
1625                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1626                           result);
1627                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1628                 return;
1629             }
1630             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]",
1631                       CA_SUPPORTED_BLE_MTU_SIZE);
1632         }
1633
1634         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1635         {
1636             // send the last segment of the data (Ex: 22 bytes of 622
1637             // bytes of data when MTU is 200)
1638             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1639
1640             result = CAMakeRemainDataSegment(dataSegment,
1641                                              bleData->data,
1642                                              remainingLen,
1643                                              index,
1644                                              dataHeader);
1645
1646             if (CA_STATUS_OK != result)
1647             {
1648                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1649                             "Making data segment failed, result [%d]", result);
1650                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1651                 return;
1652             }
1653
1654             result =
1655                 CAUpdateCharacteristicsToAllGattServers(
1656                     dataSegment,
1657                     remainingLen + CA_BLE_HEADER_SIZE);
1658
1659             if (CA_STATUS_OK != result)
1660             {
1661                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1662                           "Update characteristics (all) failed, result [%d]", result);
1663                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1664                 return;
1665             }
1666             OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1667                       "Client Sent Data length  is [%zu]", remainingLen + CA_BLE_HEADER_SIZE);
1668         }
1669     }
1670
1671     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CABLEClientSendDataThread");
1672 }
1673
1674 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
1675                                   const uint8_t *data,
1676                                   uint32_t dataLength,
1677                                   u_arraylist_t *senderInfo)
1678 {
1679     CALEData_t * const bleData = OICMalloc(sizeof(CALEData_t));
1680
1681     if (!bleData)
1682     {
1683         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1684         return NULL;
1685     }
1686
1687     bleData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
1688     bleData->data = OICCalloc(dataLength + 1, 1);
1689
1690     if (NULL == bleData->data)
1691     {
1692         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1693         CAFreeLEData(bleData);
1694         return NULL;
1695     }
1696
1697     memcpy(bleData->data, data, dataLength);
1698     bleData->dataLen = dataLength;
1699     if (senderInfo)
1700     {
1701         bleData->senderInfo = senderInfo;
1702     }
1703
1704     return bleData;
1705 }
1706
1707 static void CAFreeLEData(CALEData_t *bleData)
1708 {
1709     VERIFY_NON_NULL_VOID(bleData, CALEADAPTER_TAG, "Param bleData is NULL");
1710
1711     CAFreeEndpoint(bleData->remoteEndpoint);
1712     OICFree(bleData->data);
1713     OICFree(bleData);
1714 }
1715
1716 static void CALEDataDestroyer(void *data, uint32_t size)
1717 {
1718     if ((size_t)size < sizeof(CALEData_t *))
1719     {
1720         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1721                   "Destroy data too small %p %d", data, size);
1722     }
1723     CALEData_t *ledata = (CALEData_t *) data;
1724
1725     CAFreeLEData(ledata);
1726 }
1727 #endif
1728
1729 #ifdef SINGLE_THREAD
1730 static void CALEDataReceiverHandlerSingleThread(const uint8_t *data,
1731                                                 uint32_t dataLen)
1732 {
1733     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1734
1735     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1736
1737     //packet parsing
1738     CABLEPacketStart_t startFlag = CA_BLE_PACKET_NOT_START;
1739     CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1740     uint16_t sourcePort = 0;
1741     uint16_t destPort = 0;
1742
1743     CAParseHeader(data, &startFlag, &sourcePort, &secureFlag, &destPort);
1744     OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1745               "header info: startFlag[%X] sourcePort[%d] secureFlag[%X] destPort[%d]",
1746               startFlag, sourcePort, secureFlag, destPort);
1747
1748     if (destPort != g_localBLESourcePort && destPort != CA_BLE_MULTICAST_PORT)
1749     {
1750         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1751                   "this packet is not valid for this app(port mismatch[mine:%d, packet:%d])",
1752                   g_localBLESourcePort, destPort);
1753         return;
1754     }
1755
1756     if (startFlag)
1757     {
1758         if (g_singleThreadReceiveData)
1759         {
1760             OIC_LOG(ERROR, CALEADAPTER_TAG,
1761                     "This packet is start packet but exist senderInfo. Remove senderInfo");
1762             OICFree(g_singleThreadReceiveData->defragData);
1763             OICFree(g_singleThreadReceiveData);
1764             g_singleThreadReceiveData = NULL;
1765         }
1766
1767         uint32_t totalLength = 0;
1768         CAParseHeaderPayloadLength(data, CA_BLE_LENGTH_HEADER_SIZE, &totalLength);
1769
1770         g_singleThreadReceiveData = OICMalloc(sizeof(CABLESenderInfo_t));
1771
1772         if (!g_singleThreadReceiveData)
1773         {
1774             OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
1775             return;
1776         }
1777         g_singleThreadReceiveData->recvDataLen = 0;
1778         g_singleThreadReceiveData->totalDataLen = 0;
1779         g_singleThreadReceiveData->defragData = NULL;
1780         g_singleThreadReceiveData->remoteEndpoint = NULL;
1781
1782         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
1783
1784         g_singleThreadReceiveData->totalDataLen = totalLength;
1785
1786         if (!(g_singleThreadReceiveData->totalDataLen))
1787         {
1788             OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
1789             OICFree(g_singleThreadReceiveData);
1790             return;
1791         }
1792
1793         size_t dataOnlyLen = dataLen - (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE);
1794         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
1795                   g_singleThreadReceiveData->totalDataLen);
1796         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%u] bytes",
1797                   dataOnlyLen);
1798
1799         g_singleThreadReceiveData->defragData =
1800             OICCalloc(g_singleThreadReceiveData->totalDataLen + 1,
1801                     sizeof(*g_singleThreadReceiveData->defragData));
1802
1803         if (NULL == g_singleThreadReceiveData->defragData)
1804         {
1805             OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
1806             OICFree(g_singleThreadReceiveData);
1807             return;
1808         }
1809
1810         if (g_singleThreadReceiveData->recvDataLen + dataOnlyLen
1811                 > g_singleThreadReceiveData->totalDataLen)
1812         {
1813             OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
1814             OICFree(g_singleThreadReceiveData->defragData);
1815             OICFree(g_singleThreadReceiveData);
1816             return;
1817         }
1818         memcpy(g_singleThreadReceiveData->defragData,
1819                data + (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE),
1820                dataOnlyLen);
1821         g_singleThreadReceiveData->recvDataLen += dataOnlyLen;
1822     }
1823     else
1824     {
1825         size_t dataOnlyLen = dataLen - CA_BLE_HEADER_SIZE;
1826         if (g_singleThreadReceiveData->recvDataLen + dataOnlyLen
1827                 > g_singleThreadReceiveData->totalDataLen)
1828         {
1829             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1830                       "Data Length exceeding error!! Receiving [%d] total length [%d]",
1831                       g_singleThreadReceiveData->recvDataLen + dataOnlyLen,
1832                       g_singleThreadReceiveData->totalDataLen);
1833             OICFree(g_singleThreadReceiveData->defragData);
1834             OICFree(g_singleThreadReceiveData);
1835             return;
1836         }
1837         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]",
1838                   dataOnlyLen);
1839         memcpy(g_singleThreadReceiveData->defragData + g_singleThreadReceiveData->recvDataLen,
1840                data + CA_BLE_HEADER_SIZE,
1841                dataOnlyLen);
1842         g_singleThreadReceiveData->recvDataLen += dataOnlyLen;
1843         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "totalDatalength  [%d] received Datalen [%d]",
1844                 g_singleThreadReceiveData->totalDataLen, g_singleThreadReceiveData->recvDataLen);
1845     }
1846 }
1847
1848 static CAResult_t CALEServerSendDataSingleThread(const uint8_t *data,
1849                                                  uint32_t dataLen)
1850 {
1851     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1852
1853     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1854
1855     uint32_t midPacketCount = 0;
1856     size_t remainingLen = 0;
1857     size_t totalLength = 0;
1858     CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1859
1860     CAResult_t result = CAGenerateVariableForFragmentation(dataLen,
1861                                                            &midPacketCount,
1862                                                            &remainingLen,
1863                                                            &totalLength);
1864
1865     if (CA_STATUS_OK != result)
1866     {
1867         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1868                   "CAGenerateVariableForFragmentation failed, result [%d]", result);
1869         return result;
1870     }
1871
1872     OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1873               "Packet info: data size[%d] midPacketCount[%d] remainingLen[%d] totalLength[%d]",
1874               dataLen, midPacketCount, remainingLen, totalLength);
1875
1876     OIC_LOG_V(DEBUG,
1877               CALEADAPTER_TAG,
1878               "Server total Data length with header is [%u]",
1879               totalLength);
1880
1881     uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1882     uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1883
1884     result = CAGenerateHeader(dataHeader,
1885                               CA_BLE_PACKET_START,
1886                               g_localBLESourcePort,
1887                               CA_BLE_PACKET_NON_SECURE,
1888                               CA_BLE_MULTICAST_PORT);
1889
1890     if (CA_STATUS_OK != result)
1891     {
1892         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1893                   "CAGenerateHeader failed, result [%d]", result);
1894         return result;
1895     }
1896
1897     uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1898     result = CAGenerateHeaderPayloadLength(lengthHeader,
1899                                            CA_BLE_LENGTH_HEADER_SIZE,
1900                                            dataLen);
1901
1902     if (CA_STATUS_OK != result)
1903     {
1904         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1905                   "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1906         return result;
1907     }
1908
1909     uint32_t length = 0;
1910     uint32_t dataOnlyLen = 0;
1911     if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
1912     {
1913         length = totalLength;
1914         dataOnlyLen = dataLen;
1915     }
1916     else
1917     {
1918         length = CA_SUPPORTED_BLE_MTU_SIZE;
1919         dataOnlyLen = CA_SUPPORTED_BLE_MTU_SIZE - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1920     }
1921
1922     result = CAMakeFirstDataSegment(dataSegment,
1923                                     data, dataOnlyLen,
1924                                     dataHeader, lengthHeader);
1925
1926     if (CA_STATUS_OK != result)
1927     {
1928         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1929                   "Making data segment failed, result [%d]", result);
1930         return result;
1931     }
1932
1933     OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
1934     result = CAUpdateCharacteristicsToAllGattClients(dataSegment, length);
1935     if (CA_STATUS_OK != result)
1936     {
1937         OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1938                 result);
1939         return result;
1940     }
1941
1942     CALEDoEvents();
1943
1944     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
1945
1946     result = CAGenerateHeader(dataHeader,
1947                               CA_BLE_PACKET_NOT_START,
1948                               g_localBLESourcePort,
1949                               CA_BLE_PACKET_NON_SECURE,
1950                               CA_BLE_MULTICAST_PORT);
1951
1952     if (CA_STATUS_OK != result)
1953     {
1954         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1955                   "CAGenerateHeader failed, result [%d]", result);
1956         return result;
1957     }
1958
1959     const uint32_t dataLimit = midPacketCount;
1960     for (uint32_t iter = 0; iter < dataLimit; iter++)
1961     {
1962         result = CAMakeRemainDataSegment(dataSegment,
1963                                          data,
1964                                          CA_SUPPORTED_BLE_MTU_SIZE - CA_BLE_HEADER_SIZE,
1965                                          iter,
1966                                          dataHeader);
1967
1968         if (CA_STATUS_OK != result)
1969         {
1970             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1971                     "Making data segment failed, result [%d]", result);
1972             return result;
1973         }
1974
1975         result = CAUpdateCharacteristicsToAllGattClients(
1976                      dataSegment,
1977                      CA_SUPPORTED_BLE_MTU_SIZE);
1978
1979         if (CA_STATUS_OK != result)
1980         {
1981             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
1982             return result;
1983         }
1984
1985         CALEDoEvents();
1986     }
1987
1988     if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1989     {
1990         // send the last segment of the data
1991         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1992
1993         result = CAMakeRemainDataSegment(dataSegment,
1994                                          data,
1995                                          remainingLen,
1996                                          dataLimit,
1997                                          dataHeader);
1998
1999         if (CA_STATUS_OK != result)
2000         {
2001             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2002                     "Making data segment failed, result [%d]", result);
2003             return result;
2004         }
2005
2006         result = CAUpdateCharacteristicsToAllGattClients(
2007                      dataSegment,
2008                      remainingLen + CA_BLE_HEADER_SIZE);
2009
2010         if (CA_STATUS_OK != result)
2011         {
2012             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2013             return result;
2014         }
2015         CALEDoEvents();
2016     }
2017
2018     return result;
2019 }
2020 #endif
2021
2022 static CAResult_t CAInitLEAdapterMutex()
2023 {
2024     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAInitLEAdapterMutex");
2025
2026     if (NULL == g_bleIsServerMutex)
2027     {
2028         g_bleIsServerMutex = ca_mutex_new();
2029         if (NULL == g_bleIsServerMutex)
2030         {
2031             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
2032             return CA_STATUS_FAILED;
2033         }
2034     }
2035
2036     if (NULL == g_bleNetworkCbMutex)
2037     {
2038         g_bleNetworkCbMutex = ca_mutex_new();
2039         if (NULL == g_bleNetworkCbMutex)
2040         {
2041             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
2042             CATerminateLEAdapterMutex();
2043             return CA_STATUS_FAILED;
2044         }
2045     }
2046
2047     if (NULL == g_bleLocalAddressMutex)
2048     {
2049         g_bleLocalAddressMutex = ca_mutex_new();
2050         if (NULL == g_bleLocalAddressMutex)
2051         {
2052             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
2053             CATerminateLEAdapterMutex();
2054             return CA_STATUS_FAILED;
2055         }
2056     }
2057
2058     if (NULL == g_bleAdapterThreadPoolMutex)
2059     {
2060         g_bleAdapterThreadPoolMutex = ca_mutex_new();
2061         if (NULL == g_bleAdapterThreadPoolMutex)
2062         {
2063             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
2064             CATerminateLEAdapterMutex();
2065             return CA_STATUS_FAILED;
2066         }
2067     }
2068
2069     if (NULL == g_bleClientSendDataMutex)
2070     {
2071         g_bleClientSendDataMutex = ca_mutex_new();
2072         if (NULL == g_bleClientSendDataMutex)
2073         {
2074             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
2075             CATerminateLEAdapterMutex();
2076             return CA_STATUS_FAILED;
2077         }
2078     }
2079
2080     if (NULL == g_bleServerSendDataMutex)
2081     {
2082         g_bleServerSendDataMutex = ca_mutex_new();
2083         if (NULL == g_bleServerSendDataMutex)
2084         {
2085             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
2086             CATerminateLEAdapterMutex();
2087             return CA_STATUS_FAILED;
2088         }
2089     }
2090
2091     if (NULL == g_bleAdapterReqRespCbMutex)
2092     {
2093         g_bleAdapterReqRespCbMutex = ca_mutex_new();
2094         if (NULL == g_bleAdapterReqRespCbMutex)
2095         {
2096             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
2097             CATerminateLEAdapterMutex();
2098             return CA_STATUS_FAILED;
2099         }
2100     }
2101
2102     if (NULL == g_bleReceiveDataMutex)
2103     {
2104         g_bleReceiveDataMutex = ca_mutex_new();
2105         if (NULL == g_bleReceiveDataMutex)
2106         {
2107             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
2108             return CA_STATUS_FAILED;
2109         }
2110     }
2111
2112     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2113     return CA_STATUS_OK;
2114 }
2115
2116 static void CATerminateLEAdapterMutex()
2117 {
2118     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CATerminateLEAdapterMutex");
2119
2120     ca_mutex_free(g_bleIsServerMutex);
2121     g_bleIsServerMutex = NULL;
2122
2123     ca_mutex_free(g_bleNetworkCbMutex);
2124     g_bleNetworkCbMutex = NULL;
2125
2126     ca_mutex_free(g_bleLocalAddressMutex);
2127     g_bleLocalAddressMutex = NULL;
2128
2129     ca_mutex_free(g_bleAdapterThreadPoolMutex);
2130     g_bleAdapterThreadPoolMutex = NULL;
2131
2132     ca_mutex_free(g_bleClientSendDataMutex);
2133     g_bleClientSendDataMutex = NULL;
2134
2135     ca_mutex_free(g_bleServerSendDataMutex);
2136     g_bleServerSendDataMutex = NULL;
2137
2138     ca_mutex_free(g_bleAdapterReqRespCbMutex);
2139     g_bleAdapterReqRespCbMutex = NULL;
2140
2141     ca_mutex_free(g_bleReceiveDataMutex);
2142     g_bleReceiveDataMutex = NULL;
2143
2144     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2145 }
2146
2147 /**
2148  * Starting LE connectivity adapters.
2149  *
2150  * As its peer to peer it does not require to start any servers.
2151  *
2152  * @return ::CA_STATUS_OK or Appropriate error code.
2153  */
2154 static CAResult_t CAStartLE();
2155
2156 /**
2157  * Start listening server for receiving multicast search requests.
2158  *
2159  * Transport Specific Behavior:
2160  *   LE  Starts GATT Server with prefixed UUID and Characteristics
2161  *   per OIC Specification.
2162  * @return  ::CA_STATUS_OK or Appropriate error code.
2163  */
2164 static CAResult_t CAStartLEListeningServer();
2165
2166 /**
2167  * Stops listening server from receiving multicast search requests.
2168  *
2169  * Transport Specific Behavior:
2170  *   LE  Starts GATT Server with prefixed UUID and Characteristics
2171  *   per OIC Specification.
2172  * @return  ::CA_STATUS_OK or Appropriate error code.
2173  */
2174 static CAResult_t CAStopLEListeningServer();
2175
2176 /**
2177  * Sarting discovery of servers for receiving multicast
2178  * advertisements.
2179  *
2180  * Transport Specific Behavior:
2181  *   LE  Starts GATT Server with prefixed UUID and Characteristics
2182  *   per OIC Specification.
2183  *
2184  * @return ::CA_STATUS_OK or Appropriate error code
2185  */
2186 static CAResult_t CAStartLEDiscoveryServer();
2187
2188 /**
2189  * Send data to the endpoint using the adapter connectivity.
2190  *
2191  * @param[in] endpoint Remote Endpoint information (like MAC address,
2192  *                     reference URI and connectivity type) to which
2193  *                     the unicast data has to be sent.
2194  * @param[in] data     Data which required to be sent.
2195  * @param[in] dataLen  Size of data to be sent.
2196  *
2197  * @note  dataLen must be > 0.
2198  *
2199  * @return The number of bytes sent on the network, or -1 on error.
2200  */
2201 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2202                                    const void *data,
2203                                    uint32_t dataLen,
2204                                    CADataType_t dataType);
2205
2206 /**
2207  * Send multicast data to the endpoint using the LE connectivity.
2208  *
2209  * @param[in] endpoint Remote Endpoint information to which the
2210  *                     multicast data has to be sent.
2211  * @param[in] data     Data which required to be sent.
2212  * @param[in] dataLen  Size of data to be sent.
2213  *
2214  * @note  dataLen must be > 0.
2215  *
2216  * @return The number of bytes sent on the network, or -1 on error.
2217  */
2218 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
2219                                      const void *data,
2220                                      uint32_t dataLen,
2221                                      CADataType_t dataType);
2222
2223 /**
2224  * Get LE Connectivity network information.
2225  *
2226  * @param[out] info Local connectivity information structures.
2227  * @param[out] size Number of local connectivity structures.
2228  *
2229  * @return ::CA_STATUS_OK or Appropriate error code.
2230  */
2231 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info,
2232                                               uint32_t *size);
2233
2234 /**
2235  * Read Synchronous API callback.
2236  *
2237  * @return  ::CA_STATUS_OK or Appropriate error code.
2238  */
2239 static CAResult_t CAReadLEData();
2240
2241 /**
2242  * Stopping the adapters and close socket connections.
2243  *
2244  * LE Stops all GATT servers and GATT Clients.
2245  *
2246  * @return ::CA_STATUS_OK or Appropriate error code.
2247  */
2248 static CAResult_t CAStopLE();
2249
2250 /**
2251  * Terminate the LE connectivity adapter.
2252  *
2253  * Configuration information will be deleted from further use.
2254  */
2255 static void CATerminateLE();
2256
2257 /**
2258  * This function will receive the data from the GattServer and add the
2259  * data to the Server receiver queue.
2260  *
2261  * @param[in] remoteAddress Remote address of the device from where
2262  *                          data is received.
2263  * @param[in] data          Actual data received from the remote
2264  *                          device.
2265  * @param[in] dataLength    Length of the data received from the
2266  *                          remote device.
2267  * @param[in] sentLength    Length of the data sent from the remote
2268  *                          device.
2269  *
2270  * @return ::CA_STATUS_OK or Appropriate error code.
2271  * @retval ::CA_STATUS_OK  Successful.
2272  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
2273  * @retval ::CA_STATUS_FAILED Operation failed.
2274  *
2275  */
2276 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
2277                                                 const uint8_t *data,
2278                                                 uint32_t dataLength,
2279                                                 uint32_t *sentLength);
2280
2281 /**
2282  * This function will receive the data from the GattClient and add the
2283  * data into the Client receiver queue.
2284  *
2285  * @param[in] remoteAddress Remote address of the device from where
2286  *                          data is received.
2287  * @param[in] data          Actual data recevied from the remote
2288  *                          device.
2289  * @param[in] dataLength    Length of the data received from the
2290  *                          remote device.
2291  * @param[in] sentLength    Length of the data sent from the remote
2292  *                          device.
2293  *
2294  * @return ::CA_STATUS_OK or Appropriate error code.
2295  * @retval ::CA_STATUS_OK  Successful.
2296  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
2297  * @retval ::CA_STATUS_FAILED Operation failed.
2298  */
2299 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
2300                                                 const uint8_t *data,
2301                                                 uint32_t dataLength,
2302                                                 uint32_t *sentLength);
2303
2304 /**
2305  * Set the NetworkPacket received callback to CA layer from adapter
2306  * layer.
2307  *
2308  * @param[in] callback Callback handle sent from the upper layer.
2309  */
2310 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
2311
2312 /**
2313  * Push the data from CA layer to the Sender processor queue.
2314  *
2315  * @param[in] remoteEndpoint Remote endpoint information of the
2316  *                           server.
2317  * @param[in] data           Data to be transmitted from LE.
2318  * @param[in] dataLen        Length of the Data being transmitted.
2319  *
2320  * @return ::CA_STATUS_OK or Appropriate error code.
2321  * @retval ::CA_STATUS_OK  Successful.
2322  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
2323  * @retval ::CA_STATUS_FAILED Operation failed.
2324  */
2325 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
2326                                             const uint8_t *data,
2327                                             uint32_t dataLen);
2328
2329 /**
2330  * Push the data from CA layer to the Sender processor queue.
2331  *
2332  * @param[in] remoteEndpoint Remote endpoint information of the
2333  *                           server.
2334  * @param[in] data           Data to be transmitted from LE.
2335  * @param[in] dataLen        Length of the Data being transmitted.
2336  *
2337  * @return ::CA_STATUS_OK or Appropriate error code.
2338  * @retval ::CA_STATUS_OK  Successful.
2339  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
2340  * @retval ::CA_STATUS_FAILED Operation failed.
2341  */
2342 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
2343                                             const uint8_t *data,
2344                                             uint32_t dataLen);
2345
2346 static CAResult_t CALEAdapterGattServerStart()
2347 {
2348     OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartLEGattServer");
2349
2350     CAResult_t result = CAStartLEGattServer();
2351
2352 #ifndef SINGLE_THREAD
2353     /*
2354       Don't start the server side sending queue thread until the
2355       server itself has actually started.
2356     */
2357     if (CA_STATUS_OK == result)
2358     {
2359         ca_mutex_lock(g_bleServerSendDataMutex);
2360         result = CAQueueingThreadStart(g_bleServerSendQueueHandle);
2361         ca_mutex_unlock(g_bleServerSendDataMutex);
2362
2363         if (CA_STATUS_OK != result)
2364         {
2365             OIC_LOG_V(ERROR,
2366                       CALEADAPTER_TAG,
2367                       "Unable to start server queuing thread (%d)",
2368                       result);
2369         }
2370     }
2371 #endif
2372
2373     return result;
2374 }
2375
2376 static CAResult_t CALEAdapterGattServerStop()
2377 {
2378 #ifndef SINGLE_THREAD
2379     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEAdapterGattServerStop");
2380
2381     CAResult_t result = CAStopLEGattServer();
2382     ca_mutex_lock(g_bleServerSendDataMutex);
2383     if (CA_STATUS_OK == result)
2384     {
2385         result = CAQueueingThreadStop(g_bleServerSendQueueHandle);
2386     }
2387     ca_mutex_unlock(g_bleServerSendDataMutex);
2388
2389     return result;
2390 #else
2391     return CAStopLEGattServer();
2392 #endif
2393 }
2394
2395 static CAResult_t CALEAdapterGattClientStart()
2396 {
2397     OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartLEGattClient");
2398
2399     CAResult_t result = CAStartLEGattClient();
2400
2401 #ifndef SINGLE_THREAD
2402     /*
2403       Don't start the client side sending queue thread until the
2404       client itself has actually started.
2405     */
2406     if (CA_STATUS_OK == result)
2407     {
2408         ca_mutex_lock(g_bleClientSendDataMutex);
2409         result = CAQueueingThreadStart(g_bleClientSendQueueHandle);
2410         ca_mutex_unlock(g_bleClientSendDataMutex);
2411
2412         if (CA_STATUS_OK != result)
2413         {
2414             OIC_LOG(ERROR,
2415                     CALEADAPTER_TAG,
2416                     "Unable to start client queuing thread");
2417         }
2418     }
2419 #endif
2420
2421     return result;
2422 }
2423
2424 static CAResult_t CALEAdapterGattClientStop()
2425 {
2426 #ifndef SINGLE_THREAD
2427     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEAdapterGattClientStop");
2428     CAStopLEGattClient();
2429
2430     ca_mutex_lock(g_bleClientSendDataMutex);
2431     CAResult_t result = CAQueueingThreadStop(g_bleClientSendQueueHandle);
2432     ca_mutex_unlock(g_bleClientSendDataMutex);
2433
2434     return result;
2435 #else
2436     CAStopLEGattClient();
2437
2438     return CA_STATUS_OK;
2439 #endif
2440 }
2441
2442 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
2443                           CANetworkPacketReceivedCallback reqRespCallback,
2444                           CAAdapterChangeCallback netCallback,
2445                           CAConnectionChangeCallback connCallback,
2446                           CAErrorHandleCallback errorCallback,
2447                           ca_thread_pool_t handle)
2448 {
2449     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2450
2451     //Input validation
2452     VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null");
2453     VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null");
2454     VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null");
2455     VERIFY_NON_NULL(connCallback, CALEADAPTER_TAG, "ConnectionChange Callback is null");
2456
2457     CAResult_t result = CA_STATUS_OK;
2458     result = CAInitLEAdapterMutex();
2459     if (CA_STATUS_OK != result)
2460     {
2461         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
2462         return CA_STATUS_FAILED;
2463     }
2464
2465     result = CAInitializeLENetworkMonitor();
2466     if (CA_STATUS_OK != result)
2467     {
2468         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
2469         return CA_STATUS_FAILED;
2470     }
2471     CAInitializeLEAdapter();
2472
2473     CASetLEClientThreadPoolHandle(handle);
2474
2475     result = CAInitializeLEGattClient();
2476     if (CA_STATUS_OK != result)
2477     {
2478         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattClient() failed");
2479         return CA_STATUS_FAILED;
2480     }
2481
2482     CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
2483     CASetLEServerThreadPoolHandle(handle);
2484     result = CAInitializeLEGattServer();
2485     if (CA_STATUS_OK != result)
2486     {
2487         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattServer() failed");
2488         return CA_STATUS_FAILED;
2489     }
2490
2491     CASetLEAdapterThreadPoolHandle(handle);
2492     CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
2493     CASetLEReqRespAdapterCallback(reqRespCallback);
2494
2495     CASetBLEClientErrorHandleCallback(CALEErrorHandler);
2496     CASetBLEServerErrorHandleCallback(CALEErrorHandler);
2497     CALERegisterNetworkNotifications(netCallback, connCallback);
2498
2499     g_errorHandler = errorCallback;
2500
2501     static const CAConnectivityHandler_t connHandler =
2502         {
2503             .startAdapter = CAStartLE,
2504             .stopAdapter = CAStopLE,
2505             .startListenServer = CAStartLEListeningServer,
2506             .stopListenServer = CAStopLEListeningServer,
2507             .startDiscoveryServer = CAStartLEDiscoveryServer,
2508             .sendData = CASendLEUnicastData,
2509             .sendDataToAll = CASendLEMulticastData,
2510             .GetnetInfo = CAGetLEInterfaceInformation,
2511             .readData = CAReadLEData,
2512             .terminate = CATerminateLE,
2513             .cType = CA_ADAPTER_GATT_BTLE
2514         };
2515
2516     registerCallback(connHandler);
2517
2518     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2519
2520     return CA_STATUS_OK;
2521 }
2522
2523 static CAResult_t CAStartLE()
2524 {
2525     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAStartLE");
2526
2527     return CAStartLEAdapter();
2528 }
2529
2530 static CAResult_t CAStopLE()
2531 {
2532     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2533 #ifndef SINGLE_THREAD
2534     CAStopLEQueues();
2535 #endif
2536
2537     ca_mutex_lock(g_bleIsServerMutex);
2538     switch (g_adapterType)
2539     {
2540         case ADAPTER_SERVER:
2541             CALEAdapterGattServerStop();
2542             break;
2543         case ADAPTER_CLIENT:
2544             CALEAdapterGattClientStop();
2545             break;
2546         case ADAPTER_BOTH_CLIENT_SERVER:
2547             CALEAdapterGattServerStop();
2548             CALEAdapterGattClientStop();
2549             break;
2550         default:
2551             break;
2552     }
2553     ca_mutex_unlock(g_bleIsServerMutex);
2554
2555     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2556
2557     return CAStopLEAdapter();
2558 }
2559
2560 static void CATerminateLE()
2561 {
2562     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2563
2564     CASetLEReqRespServerCallback(NULL);
2565     CASetLEReqRespClientCallback(NULL);
2566     CALERegisterNetworkNotifications(NULL, NULL);
2567     CASetLEReqRespAdapterCallback(NULL);
2568     CATerminateLENetworkMonitor();
2569
2570     ca_mutex_lock(g_bleIsServerMutex);
2571     switch (g_adapterType)
2572     {
2573         case ADAPTER_SERVER:
2574             CATerminateLEGattServer();
2575             break;
2576         case ADAPTER_CLIENT:
2577             CATerminateLEGattClient();
2578             break;
2579         case ADAPTER_BOTH_CLIENT_SERVER:
2580             CATerminateLEGattServer();
2581             CATerminateLEGattClient();
2582             break;
2583         default:
2584             break;
2585     }
2586     g_adapterType = ADAPTER_EMPTY;
2587     ca_mutex_unlock(g_bleIsServerMutex);
2588
2589 #ifndef SINGLE_THREAD
2590     CATerminateLEQueues();
2591 #endif
2592     CATerminateLEAdapterMutex();
2593
2594     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2595 }
2596
2597 static CAResult_t CAStartLEListeningServer()
2598 {
2599     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAStartLEListeningServer");
2600 #ifndef ROUTING_GATEWAY
2601     CAResult_t result = CA_STATUS_OK;
2602 #ifndef SINGLE_THREAD
2603     result = CAInitLEServerQueues();
2604     if (CA_STATUS_OK != result)
2605     {
2606         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
2607         return result;
2608     }
2609 #endif
2610
2611     ca_mutex_lock(g_bleIsServerMutex);
2612     switch (g_adapterType)
2613     {
2614         case ADAPTER_CLIENT:
2615             g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2616             break;
2617         case ADAPTER_BOTH_CLIENT_SERVER:
2618             break;
2619         default:
2620             g_adapterType = ADAPTER_SERVER;
2621     }
2622     ca_mutex_unlock(g_bleIsServerMutex);
2623
2624     result = CAGetLEAdapterState();
2625     if (CA_STATUS_OK != result)
2626     {
2627         if (CA_ADAPTER_NOT_ENABLED == result)
2628         {
2629             OIC_LOG(DEBUG,
2630                     CALEADAPTER_TAG,
2631                     "Listen Server will be started once BT Adapter is enabled");
2632             result = CA_STATUS_OK;
2633         }
2634     }
2635     else
2636     {
2637         result = CALEAdapterGattServerStart();
2638     }
2639
2640     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2641     return result;
2642 #else
2643     // Routing Gateway only supports BLE client mode.
2644     OIC_LOG(ERROR, CALEADAPTER_TAG, "LE server not supported in Routing Gateway");
2645     return CA_NOT_SUPPORTED;
2646 #endif
2647 }
2648
2649 static CAResult_t CAStopLEListeningServer()
2650 {
2651     OIC_LOG(ERROR, CALEADAPTER_TAG, "Listen server stop not supported.");
2652     return CA_NOT_SUPPORTED;
2653 }
2654
2655 static CAResult_t CAStartLEDiscoveryServer()
2656 {
2657     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAStartLEDiscoveryServer");
2658     CAResult_t result = CA_STATUS_OK;
2659 #ifndef SINGLE_THREAD
2660     result = CAInitLEClientQueues();
2661     if (CA_STATUS_OK != result)
2662     {
2663         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
2664         return result;
2665     }
2666 #endif
2667
2668     ca_mutex_lock(g_bleIsServerMutex);
2669     switch (g_adapterType)
2670     {
2671         case ADAPTER_SERVER:
2672             g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2673             break;
2674         case ADAPTER_BOTH_CLIENT_SERVER:
2675             break;
2676         default:
2677             g_adapterType = ADAPTER_CLIENT;
2678     }
2679     ca_mutex_unlock(g_bleIsServerMutex);
2680
2681     result = CAGetLEAdapterState();
2682     if (CA_STATUS_OK != result)
2683     {
2684         if (CA_ADAPTER_NOT_ENABLED == result)
2685         {
2686             OIC_LOG(DEBUG,
2687                     CALEADAPTER_TAG,
2688                     "Discovery Server will be started once BT Adapter is enabled");
2689             result = CA_STATUS_OK;
2690         }
2691     }
2692     else
2693     {
2694         result = CALEAdapterGattClientStart();
2695     }
2696
2697     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2698     return result;
2699 }
2700
2701 static CAResult_t CAReadLEData()
2702 {
2703     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2704 #ifdef SINGLE_THREAD
2705     CACheckLEData();
2706 #endif
2707     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2708     return CA_STATUS_OK;
2709 }
2710
2711 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2712                                    const void *data,
2713                                    uint32_t dataLen,
2714                                    CADataType_t dataType)
2715 {
2716     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN - CASendLEUnicastData : type(%d)", dataType);
2717
2718     //Input validation
2719     VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
2720     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2721
2722     CAResult_t result = CA_STATUS_FAILED;
2723
2724     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2725     if (ADAPTER_EMPTY == g_adapterType)
2726     {
2727         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2728     }
2729
2730     ca_mutex_lock(g_bleIsServerMutex);
2731     if (ADAPTER_SERVER == g_adapterType ||
2732             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2733     {
2734         result = CALEAdapterServerSendData(endpoint, data, dataLen);
2735         if (CA_STATUS_OK != result)
2736         {
2737             ca_mutex_unlock(g_bleIsServerMutex);
2738             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed");
2739             if (g_errorHandler)
2740             {
2741                 g_errorHandler(endpoint, data, dataLen, result);
2742             }
2743
2744             return -1;
2745         }
2746     }
2747
2748     if (ADAPTER_CLIENT == g_adapterType ||
2749             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
2750             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
2751     {
2752         result = CALEAdapterClientSendData(endpoint, data, dataLen);
2753         if (CA_STATUS_OK != result)
2754         {
2755             ca_mutex_unlock(g_bleIsServerMutex);
2756             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
2757
2758              if (g_errorHandler)
2759              {
2760                  g_errorHandler(endpoint, data, dataLen, result);
2761              }
2762             return -1;
2763         }
2764     }
2765     ca_mutex_unlock(g_bleIsServerMutex);
2766
2767     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2768     return dataLen;
2769 }
2770
2771 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
2772                                      const void *data,
2773                                      uint32_t dataLen,
2774                                      CADataType_t dataType)
2775 {
2776     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CASendLEMulticastData");
2777
2778     //Input validation
2779     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2780
2781     if (0 >= dataLen)
2782     {
2783         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
2784         return -1;
2785     }
2786
2787     CAResult_t result = CA_STATUS_FAILED;
2788
2789     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2790     if (ADAPTER_EMPTY == g_adapterType)
2791     {
2792         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2793     }
2794
2795     ca_mutex_lock(g_bleIsServerMutex);
2796     if (ADAPTER_SERVER == g_adapterType ||
2797             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2798     {
2799         result = CALEAdapterServerSendData(NULL, data, dataLen);
2800         if (CA_STATUS_OK != result)
2801         {
2802             ca_mutex_unlock(g_bleIsServerMutex);
2803
2804             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data for server failed" );
2805
2806             if (g_errorHandler)
2807             {
2808                 g_errorHandler(endpoint, data, dataLen, result);
2809             }
2810             return -1;
2811         }
2812     }
2813
2814     if (ADAPTER_CLIENT == g_adapterType ||
2815             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
2816             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
2817     {
2818         result = CALEAdapterClientSendData(NULL, data, dataLen);
2819         if (CA_STATUS_OK != result)
2820         {
2821             ca_mutex_unlock(g_bleIsServerMutex);
2822
2823             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data for client failed" );
2824
2825             if (g_errorHandler)
2826             {
2827                 g_errorHandler(endpoint, data, dataLen, result);
2828             }
2829             return -1;
2830         }
2831     }
2832     ca_mutex_unlock(g_bleIsServerMutex);
2833
2834     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CASendLEMulticastData");
2835     return dataLen;
2836 }
2837
2838 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
2839 {
2840     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2841
2842     VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
2843
2844     char *local_address = NULL;
2845
2846     CAResult_t res = CAGetLEAddress(&local_address);
2847     if (CA_STATUS_OK != res)
2848     {
2849         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
2850         return res;
2851     }
2852
2853     if (NULL == local_address)
2854     {
2855         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
2856         return CA_STATUS_FAILED;
2857     }
2858
2859     *size = 0;
2860     (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
2861     if (NULL == (*info))
2862     {
2863         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
2864         OICFree(local_address);
2865         return CA_STATUS_FAILED;
2866     }
2867
2868     size_t local_address_len = strlen(local_address);
2869
2870     if(local_address_len >= sizeof(g_localBLEAddress) ||
2871             local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
2872     {
2873         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
2874         OICFree(*info);
2875         OICFree(local_address);
2876         return CA_STATUS_FAILED;
2877     }
2878
2879     OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
2880     ca_mutex_lock(g_bleLocalAddressMutex);
2881     OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
2882     ca_mutex_unlock(g_bleLocalAddressMutex);
2883
2884     (*info)->adapter = CA_ADAPTER_GATT_BTLE;
2885     *size = 1;
2886     OICFree(local_address);
2887
2888     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2889     return CA_STATUS_OK;
2890 }
2891
2892 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
2893                                                    CAConnectionChangeCallback connCallback)
2894 {
2895     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2896
2897     ca_mutex_lock(g_bleNetworkCbMutex);
2898     g_networkCallback = netCallback;
2899     g_connectionCallback = connCallback;
2900     ca_mutex_unlock(g_bleNetworkCbMutex);
2901     CAResult_t res = CA_STATUS_OK;
2902     if (netCallback)
2903     {
2904         res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
2905         if (CA_STATUS_OK != res)
2906         {
2907             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
2908         }
2909     }
2910     else
2911     {
2912         res = CAUnSetLEAdapterStateChangedCb();
2913         if (CA_STATUS_OK != res)
2914         {
2915             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
2916         }
2917     }
2918
2919     if (g_connectionCallback)
2920     {
2921         res = CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCb);
2922         if (CA_STATUS_OK != res)
2923         {
2924             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLENWConnectionStateChangedCb failed!");
2925         }
2926     }
2927
2928     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2929     return res;
2930 }
2931
2932 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
2933                                          bool isConnected)
2934 {
2935     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEConnectionStateChangedCb");
2936
2937     VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
2938     (void)adapter;
2939
2940 #ifdef __TIZEN__
2941     ca_mutex_lock(g_bleIsServerMutex);
2942     switch (g_adapterType)
2943     {
2944         case ADAPTER_SERVER:
2945             CALEGattServerConnectionStateChanged(isConnected, address);
2946             break;
2947         case ADAPTER_CLIENT:
2948             CALEGattConnectionStateChanged(isConnected, address);
2949             break;
2950         case ADAPTER_BOTH_CLIENT_SERVER:
2951             CALEGattConnectionStateChanged(isConnected, address);
2952             CALEGattServerConnectionStateChanged(isConnected, address);
2953             break;
2954         default:
2955             break;
2956     }
2957     ca_mutex_unlock(g_bleIsServerMutex);
2958 #endif
2959
2960     if(!isConnected)
2961     {
2962 #ifndef SINGLE_THREAD
2963         if(g_bleClientSenderInfo)
2964         {
2965             CALERemoveReceiveQueueData(g_bleClientSenderInfo, address);
2966         }
2967
2968         if(g_bleServerSenderInfo)
2969         {
2970             CALERemoveReceiveQueueData(g_bleServerSenderInfo, address);
2971         }
2972
2973         // remove data of send queue.
2974         if (g_bleClientSendQueueHandle)
2975         {
2976             CALERemoveSendQueueData(g_bleClientSendQueueHandle,
2977                                     g_bleClientSendDataMutex,
2978                                     address);
2979         }
2980
2981         if (g_bleServerSendQueueHandle)
2982         {
2983             CALERemoveSendQueueData(g_bleServerSendQueueHandle,
2984                                     g_bleServerSendDataMutex,
2985                                     address);
2986         }
2987 #endif
2988     }
2989
2990     CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE };
2991     OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), address);
2992
2993     ca_mutex_lock(g_bleNetworkCbMutex);
2994     if (g_connectionCallback)
2995     {
2996         g_connectionCallback(&localEndpoint, isConnected);
2997     }
2998     ca_mutex_unlock(g_bleNetworkCbMutex);
2999
3000     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
3001 }
3002
3003 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
3004 {
3005     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEDeviceStateChangedCb");
3006
3007     if (CA_ADAPTER_ENABLED == adapter_state)
3008     {
3009         ca_mutex_lock(g_bleIsServerMutex);
3010         switch (g_adapterType)
3011         {
3012             case ADAPTER_SERVER:
3013                 CALEAdapterGattServerStart();
3014                 break;
3015             case ADAPTER_CLIENT:
3016                 CALEAdapterGattClientStart();
3017                 break;
3018             case ADAPTER_BOTH_CLIENT_SERVER:
3019                 CALEAdapterGattServerStart();
3020                 CALEAdapterGattClientStart();
3021                 break;
3022             default:
3023                 break;
3024         }
3025         ca_mutex_unlock(g_bleIsServerMutex);
3026     }
3027     else
3028     {
3029         ca_mutex_lock(g_bleIsServerMutex);
3030         switch (g_adapterType)
3031         {
3032             case ADAPTER_SERVER:
3033                 CALEAdapterGattServerStop();
3034                 break;
3035             case ADAPTER_CLIENT:
3036                 CALEAdapterGattClientStop();
3037                 break;
3038             case ADAPTER_BOTH_CLIENT_SERVER:
3039                 CALEAdapterGattServerStop();
3040                 CALEAdapterGattClientStop();
3041                 break;
3042             default:
3043                 break;
3044         }
3045         ca_mutex_unlock(g_bleIsServerMutex);
3046     }
3047
3048     ca_mutex_lock(g_bleNetworkCbMutex);
3049     if (NULL != g_networkCallback)
3050     {
3051         g_networkCallback(CA_ADAPTER_GATT_BTLE, adapter_state);
3052     }
3053     else
3054     {
3055         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
3056     }
3057     ca_mutex_unlock(g_bleNetworkCbMutex);
3058
3059     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
3060 }
3061
3062 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
3063                                             const uint8_t *data,
3064                                             uint32_t dataLen)
3065 {
3066     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
3067
3068     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3069 #ifndef SINGLE_THREAD
3070     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
3071                         "g_bleClientSendQueueHandle is  NULL",
3072                         CA_STATUS_FAILED);
3073     VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
3074                         "g_bleClientSendDataMutex is NULL",
3075                         CA_STATUS_FAILED);
3076
3077     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
3078                         "g_bleClientSendQueueHandle",
3079                         CA_STATUS_FAILED);
3080
3081     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%u]", dataLen);
3082
3083     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3084     if (!bleData)
3085     {
3086         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3087         return CA_MEMORY_ALLOC_FAILED;
3088     }
3089     // Add message to send queue
3090     ca_mutex_lock(g_bleClientSendDataMutex);
3091     CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData, sizeof(CALEData_t));
3092     ca_mutex_unlock(g_bleClientSendDataMutex);
3093 #endif
3094     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
3095     return CA_STATUS_OK;
3096 }
3097
3098 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
3099                                             const uint8_t *data,
3100                                             uint32_t dataLen)
3101 {
3102     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
3103
3104     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3105
3106 #ifdef SINGLE_THREAD
3107     if (!CAIsLEConnected())
3108     {
3109         OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
3110         return CA_STATUS_FAILED;
3111     }
3112
3113     CAResult_t result = CALEServerSendDataSingleThread(data, dataLen);
3114     if (CA_STATUS_OK != result)
3115     {
3116         OIC_LOG(ERROR, CALEADAPTER_TAG, "CALEServerSendDataSingleThread failed");
3117         return CA_STATUS_FAILED;
3118     }
3119 #else
3120     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
3121                         "BleClientReceiverQueue is NULL",
3122                         CA_STATUS_FAILED);
3123     VERIFY_NON_NULL_RET(g_bleServerSendDataMutex, CALEADAPTER_TAG,
3124                         "BleClientSendDataMutex is NULL",
3125                         CA_STATUS_FAILED);
3126
3127     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG, "sendQueueHandle",
3128                         CA_STATUS_FAILED);
3129
3130     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
3131
3132     CALEData_t * const bleData =
3133         CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3134
3135     if (!bleData)
3136     {
3137         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3138         return CA_MEMORY_ALLOC_FAILED;
3139     }
3140
3141     // Add message to send queue
3142     ca_mutex_lock(g_bleServerSendDataMutex);
3143     CAQueueingThreadAddData(g_bleServerSendQueueHandle,
3144                             bleData,
3145                             sizeof(CALEData_t));
3146     ca_mutex_unlock(g_bleServerSendDataMutex);
3147 #endif
3148     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
3149     return CA_STATUS_OK;
3150 }
3151
3152 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
3153                                                 const uint8_t *data,
3154                                                 uint32_t dataLength,
3155                                                 uint32_t *sentLength)
3156 {
3157     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
3158
3159     //Input validation
3160     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3161     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3162
3163 #ifdef SINGLE_THREAD
3164     CALEDataReceiverHandlerSingleThread(data, dataLength);
3165
3166     if (g_singleThreadReceiveData->totalDataLen == g_singleThreadReceiveData->recvDataLen)
3167     {
3168         if(g_networkPacketReceivedCallback)
3169         {
3170             // will be filled by upper layer
3171             const CASecureEndpoint_t endpoint =
3172                 { .endpoint = { .adapter = CA_ADAPTER_GATT_BTLE } };
3173
3174             g_networkPacketReceivedCallback(&endpoint,
3175                                             g_singleThreadReceiveData->defragData,
3176                                             g_singleThreadReceiveData->recvDataLen);
3177         }
3178         g_singleThreadReceiveData->remoteEndpoint = NULL;
3179         OICFree(g_singleThreadReceiveData->defragData);
3180         g_singleThreadReceiveData->defragData = NULL;
3181         OICFree(g_singleThreadReceiveData);
3182         g_singleThreadReceiveData = NULL;
3183     }
3184 #else
3185     VERIFY_NON_NULL_RET(g_bleReceiverQueue,
3186                         CALEADAPTER_TAG,
3187                         "g_bleReceiverQueue",
3188                         CA_STATUS_FAILED);
3189
3190     //Add message to data queue
3191     CAEndpoint_t * const remoteEndpoint =
3192         CACreateEndpointObject(CA_DEFAULT_FLAGS,
3193                                CA_ADAPTER_GATT_BTLE,
3194                                remoteAddress,
3195                                0);
3196
3197     if (NULL == remoteEndpoint)
3198     {
3199         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3200         return CA_STATUS_FAILED;
3201     }
3202
3203     // Create bleData to add to queue
3204     OIC_LOG_V(DEBUG,
3205               CALEADAPTER_TAG,
3206               "Data received from LE layer [%d]",
3207               dataLength);
3208
3209     CALEData_t * const bleData =
3210         CACreateLEData(remoteEndpoint, data, dataLength, g_bleServerSenderInfo);
3211
3212     if (!bleData)
3213     {
3214         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3215         CAFreeEndpoint(remoteEndpoint);
3216         return CA_MEMORY_ALLOC_FAILED;
3217     }
3218
3219     CAFreeEndpoint(remoteEndpoint);
3220     // Add message to receiver queue
3221     CAQueueingThreadAddData(g_bleReceiverQueue, bleData, sizeof(CALEData_t));
3222
3223     *sentLength = dataLength;
3224 #endif
3225     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
3226     return CA_STATUS_OK;
3227 }
3228
3229 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
3230                                                 const uint8_t *data,
3231                                                 uint32_t dataLength,
3232                                                 uint32_t *sentLength)
3233 {
3234     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
3235
3236     //Input validation
3237     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3238     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3239 #ifndef SINGLE_THREAD
3240     VERIFY_NON_NULL_RET(g_bleReceiverQueue, CALEADAPTER_TAG,
3241                         "g_bleReceiverQueue",
3242                         CA_STATUS_FAILED);
3243
3244     //Add message to data queue
3245     CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
3246                                                           CA_ADAPTER_GATT_BTLE,
3247                                                           remoteAddress, 0);
3248     if (NULL == remoteEndpoint)
3249     {
3250         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3251         return CA_STATUS_FAILED;
3252     }
3253
3254     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%u]", dataLength);
3255
3256     // Create bleData to add to queue
3257     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data,
3258                                          dataLength, g_bleClientSenderInfo);
3259     if (!bleData)
3260     {
3261         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3262         CAFreeEndpoint(remoteEndpoint);
3263         return CA_MEMORY_ALLOC_FAILED;
3264     }
3265
3266     CAFreeEndpoint(remoteEndpoint);
3267     // Add message to receiver queue
3268     CAQueueingThreadAddData(g_bleReceiverQueue, bleData, sizeof(CALEData_t));
3269
3270     *sentLength = dataLength;
3271 #endif
3272     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
3273     return CA_STATUS_OK;
3274 }
3275
3276 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
3277 {
3278     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
3279
3280     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
3281     g_bleAdapterThreadPool = handle;
3282     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
3283
3284     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
3285 }
3286
3287 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
3288 {
3289     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
3290
3291     ca_mutex_lock(g_bleAdapterReqRespCbMutex);
3292
3293     g_networkPacketReceivedCallback = callback;
3294
3295     ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
3296
3297     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
3298 }
3299
3300 static void CALEErrorHandler(const char *remoteAddress,
3301                              const uint8_t *data,
3302                              uint32_t dataLen,
3303                              CAResult_t result)
3304 {
3305     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler IN");
3306
3307     VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
3308
3309     CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS,
3310                                                CA_ADAPTER_GATT_BTLE,
3311                                                remoteAddress,
3312                                                0);
3313
3314     // if required, will be used to build remote endpoint
3315     g_errorHandler(rep, data, dataLen, result);
3316
3317     CAFreeEndpoint(rep);
3318
3319     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler OUT");
3320 }
3321
3322 #ifndef SINGLE_THREAD
3323 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle, ca_mutex mutex,
3324                                     const char* address)
3325 {
3326     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALERemoveSendQueueData");
3327
3328     VERIFY_NON_NULL_VOID(queueHandle, CALEADAPTER_TAG, "queueHandle");
3329     VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3330
3331     ca_mutex_lock(mutex);
3332     while (u_queue_get_size(queueHandle->dataQueue) > 0)
3333     {
3334         OIC_LOG(DEBUG, CALEADAPTER_TAG, "get data from queue");
3335         u_queue_message_t *message = u_queue_get_element(queueHandle->dataQueue);
3336         if (NULL != message)
3337         {
3338             CALEData_t *bleData = (CALEData_t *) message->msg;
3339             if (bleData && bleData->remoteEndpoint)
3340             {
3341                 if (!strcmp(bleData->remoteEndpoint->addr, address))
3342                 {
3343                     OIC_LOG(DEBUG, CALEADAPTER_TAG, "found the message of disconnected device");
3344                     if (NULL != queueHandle->destroy)
3345                     {
3346                         queueHandle->destroy(message->msg, message->size);
3347                     }
3348                     else
3349                     {
3350                         OICFree(message->msg);
3351                     }
3352
3353                     OICFree(message);
3354                 }
3355             }
3356         }
3357     }
3358     ca_mutex_unlock(mutex);
3359 }
3360
3361 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList, const char* address)
3362 {
3363     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALERemoveReceiveQueueData");
3364
3365     VERIFY_NON_NULL_VOID(dataInfoList, CALEADAPTER_TAG, "dataInfoList");
3366     VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3367
3368     CABLESenderInfo_t *senderInfo = NULL;
3369     uint32_t senderIndex = 0;
3370
3371     u_arraylist_t *portList = u_arraylist_create();
3372     if (CA_STATUS_OK == CALEGetPortsFromSenderInfo(address, dataInfoList, portList))
3373     {
3374         uint32_t arrayLength = u_arraylist_length(portList);
3375         for (uint32_t i = 0; i < arrayLength; i++)
3376         {
3377             uint16_t port = (uint16_t)(uintptr_t)u_arraylist_get(portList, i);
3378             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "port : %X", port);
3379
3380             if (CA_STATUS_OK == CALEGetSenderInfo(address, port,
3381                                                   dataInfoList, &senderInfo,
3382                                                   &senderIndex))
3383             {
3384                 u_arraylist_remove(dataInfoList, senderIndex);
3385                 OICFree(senderInfo->defragData);
3386                 OICFree(senderInfo->remoteEndpoint);
3387                 OICFree(senderInfo);
3388
3389                 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3390                         "SenderInfo is removed for disconnection");
3391             }
3392             else
3393             {
3394                 OIC_LOG(DEBUG, CALEADAPTER_TAG, "SenderInfo doesn't exist");
3395             }
3396         }
3397     }
3398     u_arraylist_destroy(portList);
3399 }
3400
3401 static CAResult_t CALEGetPortsFromSenderInfo(const char *leAddress,
3402                                             u_arraylist_t *senderInfoList,
3403                                             u_arraylist_t *portList)
3404 {
3405     VERIFY_NON_NULL(leAddress,
3406                     CALEADAPTER_TAG,
3407                     "NULL BLE address argument");
3408
3409     const uint32_t listLength = u_arraylist_length(senderInfoList);
3410     const uint32_t addrLength = strlen(leAddress);
3411
3412     for (uint32_t index = 0; index < listLength; index++)
3413     {
3414         CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
3415         if (!info || !(info->remoteEndpoint))
3416         {
3417             continue;
3418         }
3419
3420         if (!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
3421         {
3422             u_arraylist_add(portList, (void *)(uintptr_t)info->remoteEndpoint->port);
3423         }
3424     }
3425
3426     if (u_arraylist_length(portList) != 0)
3427     {
3428         return CA_STATUS_OK;
3429     }
3430     else
3431     {
3432         return CA_STATUS_FAILED;
3433     }
3434 }
3435 #endif