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