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