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