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