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