d4ced58e3ce05dbb49cabaa5187828517d672d8b
[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     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleServerSendQueueHandle))
548     {
549         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
550         OICFree(g_bleServerSendQueueHandle);
551         g_bleServerSendQueueHandle = NULL;
552         return CA_STATUS_FAILED;
553     }
554
555     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
556     return CA_STATUS_OK;
557 }
558
559 static void CALEClearSenderInfo()
560 {
561     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
562
563     uint32_t listIndex = 0;
564     uint32_t listLength = u_arraylist_length(g_senderInfo);
565     for (listIndex = 0; listIndex < listLength; listIndex++)
566     {
567         CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(g_senderInfo, listIndex);
568         if(!info)
569         {
570             continue;
571         }
572
573         OICFree(info->defragData);
574         CAFreeEndpoint(info->remoteEndpoint);
575         OICFree(info);
576     }
577     u_arraylist_free(&g_senderInfo);
578     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
579 }
580
581 static CAResult_t CAInitLEClientSenderQueue()
582 {
583     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
584
585     if (g_bleClientSendQueueHandle)
586     {
587         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
588         return CA_STATUS_OK;
589     }
590
591     // Create send message queue
592     g_bleClientSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
593     if (!g_bleClientSendQueueHandle)
594     {
595         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
596         return CA_MEMORY_ALLOC_FAILED;
597     }
598
599     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientSendQueueHandle,
600                                                    g_bleAdapterThreadPool,
601                                                    CALEClientSendDataThread, CALEDataDestroyer))
602     {
603         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
604         OICFree(g_bleClientSendQueueHandle);
605         g_bleClientSendQueueHandle = NULL;
606         return CA_STATUS_FAILED;
607     }
608
609     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleClientSendQueueHandle))
610     {
611         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
612         OICFree(g_bleClientSendQueueHandle);
613         g_bleClientSendQueueHandle = NULL;
614         return CA_STATUS_FAILED;
615     }
616
617     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
618     return CA_STATUS_OK;
619 }
620
621 static void CAStopLEQueues()
622 {
623     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
624
625     ca_mutex_lock(g_bleClientSendDataMutex);
626     if (NULL != g_bleClientSendQueueHandle)
627     {
628         CAQueueingThreadStop(g_bleClientSendQueueHandle);
629     }
630     ca_mutex_unlock(g_bleClientSendDataMutex);
631
632     ca_mutex_lock(g_bleServerSendDataMutex);
633     if (NULL != g_bleServerSendQueueHandle)
634     {
635         CAQueueingThreadStop(g_bleServerSendQueueHandle);
636     }
637     ca_mutex_unlock(g_bleServerSendDataMutex);
638
639     ca_mutex_lock(g_bleReceiveDataMutex);
640     if (NULL != g_bleReceiverQueue)
641     {
642         CAQueueingThreadStop(g_bleReceiverQueue);
643     }
644     ca_mutex_unlock(g_bleReceiveDataMutex);
645
646     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
647 }
648
649 static void CATerminateLEQueues()
650 {
651     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
652
653     CAQueueingThreadDestroy(g_bleClientSendQueueHandle);
654     OICFree(g_bleClientSendQueueHandle);
655     g_bleClientSendQueueHandle = NULL;
656
657     CAQueueingThreadDestroy(g_bleServerSendQueueHandle);
658     OICFree(g_bleServerSendQueueHandle);
659     g_bleServerSendQueueHandle = NULL;
660
661     CAQueueingThreadDestroy(g_bleReceiverQueue);
662     OICFree(g_bleReceiverQueue);
663     g_bleReceiverQueue = NULL;
664
665     CALEClearSenderInfo();
666
667     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
668 }
669
670 static CAResult_t CALEGetSenderInfo(const char *leAddress,
671                                     CABLESenderInfo_t **senderInfo,
672                                     uint32_t *senderIndex)
673 {
674     VERIFY_NON_NULL_RET(leAddress,
675                         CALEADAPTER_TAG,
676                         "NULL BLE address argument",
677                         CA_STATUS_INVALID_PARAM);
678     VERIFY_NON_NULL_RET(senderIndex,
679                         CALEADAPTER_TAG,
680                         "NULL index argument",
681                         CA_STATUS_INVALID_PARAM);
682
683     const uint32_t listLength = u_arraylist_length(g_senderInfo);
684     const uint32_t addrLength = strlen(leAddress);
685     for (uint32_t index = 0; index < listLength; index++)
686     {
687         CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(g_senderInfo, index);
688         if(!info || !(info->remoteEndpoint))
689         {
690             continue;
691         }
692
693         if(!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
694         {
695             *senderIndex = index;
696             if(senderInfo)
697             {
698                 *senderInfo = info;
699             }
700             return CA_STATUS_OK;
701         }
702     }
703
704     return CA_STATUS_FAILED;
705 }
706
707 static void CALEDataReceiverHandler(void *threadData)
708 {
709     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
710
711     ca_mutex_lock(g_bleReceiveDataMutex);
712
713     if (g_dataReceiverHandlerState)
714     {
715         OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
716
717         CALEData_t *bleData = (CALEData_t *) threadData;
718         if (!bleData)
719         {
720             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bleData!");
721             ca_mutex_unlock(g_bleReceiveDataMutex);
722             return;
723         }
724
725         if(!(bleData->remoteEndpoint))
726         {
727             OIC_LOG(ERROR, CALEADAPTER_TAG, "Client RemoteEndPoint NULL!!");
728             ca_mutex_unlock(g_bleReceiveDataMutex);
729             return;
730         }
731
732         CABLESenderInfo_t *senderInfo = NULL;
733         uint32_t senderIndex = 0;
734
735         if(CA_STATUS_OK != CALEGetSenderInfo(bleData->remoteEndpoint->addr,
736                                                 &senderInfo, &senderIndex))
737         {
738             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This is a new client [%s]",
739                                                 bleData->remoteEndpoint->addr);
740         }
741
742         if(!senderInfo)
743         {
744             CABLESenderInfo_t *newSender = OICMalloc(sizeof(CABLESenderInfo_t));
745             if(!newSender)
746             {
747                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
748                 ca_mutex_unlock(g_bleReceiveDataMutex);
749                 return;
750             }
751             newSender->recvDataLen = 0;
752             newSender->totalDataLen = 0;
753             newSender->defragData = NULL;
754             newSender->remoteEndpoint = NULL;
755
756             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
757             newSender->totalDataLen = CAParseHeader(bleData->data,
758                                                     bleData->dataLen);
759             if(!(newSender->totalDataLen))
760             {
761                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
762                 OICFree(newSender);
763                 ca_mutex_unlock(g_bleReceiveDataMutex);
764                 return;
765             }
766
767             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
768                                                 newSender->totalDataLen);
769             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%u] bytes",
770                                                 bleData->dataLen);
771
772             newSender->defragData = OICCalloc(newSender->totalDataLen + 1,
773                                               sizeof(*newSender->defragData));
774
775             if (NULL == newSender->defragData)
776             {
777                 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
778                 OICFree(newSender);
779                 ca_mutex_unlock(g_bleReceiveDataMutex);
780                 return;
781             }
782
783             const char *remoteAddress = bleData->remoteEndpoint->addr;
784             newSender->remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
785                                                             CA_ADAPTER_GATT_BTLE, remoteAddress, 0);
786             if (NULL == newSender->remoteEndpoint)
787             {
788                 OIC_LOG(ERROR, CALEADAPTER_TAG, "remoteEndpoint is NULL!");
789                 OICFree(newSender->defragData);
790                 OICFree(newSender);
791                 ca_mutex_unlock(g_bleReceiveDataMutex);
792                 return;
793             }
794             memcpy(newSender->defragData, bleData->data + CA_HEADER_LENGTH,
795                     bleData->dataLen - CA_HEADER_LENGTH);
796             newSender->recvDataLen += bleData->dataLen - CA_HEADER_LENGTH;
797             u_arraylist_add(g_senderInfo,(void *)newSender);
798
799             //Getting newSender index position in g_senderInfo array list
800             if(CA_STATUS_OK !=
801                 CALEGetSenderInfo(newSender->remoteEndpoint->addr, NULL, &senderIndex))
802             {
803                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Existing sender index not found!!");
804                 OICFree(newSender->defragData);
805                 CAFreeEndpoint(newSender->remoteEndpoint);
806                 OICFree(newSender);
807                 ca_mutex_unlock(g_bleReceiveDataMutex);
808                 return;
809             }
810             senderInfo = newSender;
811         }
812         else
813         {
814             if(senderInfo->recvDataLen + bleData->dataLen > senderInfo->totalDataLen)
815             {
816                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
817                             "Data Length exceeding error!! Receiving [%d] total length [%d]",
818                             senderInfo->recvDataLen + bleData->dataLen, senderInfo->totalDataLen);
819                 u_arraylist_remove(g_senderInfo, senderIndex);
820                 OICFree(senderInfo->defragData);
821                 OICFree(senderInfo);
822                 ca_mutex_unlock(g_bleReceiveDataMutex);
823                 return;
824             }
825             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]", bleData->dataLen);
826             memcpy(senderInfo->defragData + senderInfo->recvDataLen, bleData->data,
827                     bleData->dataLen);
828             senderInfo->recvDataLen += bleData->dataLen ;
829             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "totalDatalength  [%d] recveived Datalen [%d]",
830                                                 senderInfo->totalDataLen, senderInfo->recvDataLen);
831         }
832
833         if (senderInfo->totalDataLen == senderInfo->recvDataLen)
834         {
835             ca_mutex_lock(g_bleAdapterReqRespCbMutex);
836             if (NULL == g_networkPacketReceivedCallback)
837             {
838                 OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
839
840                 u_arraylist_remove(g_senderInfo, senderIndex);
841                 OICFree(senderInfo->defragData);
842                 OICFree(senderInfo);
843                 ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
844                 ca_mutex_unlock(g_bleReceiveDataMutex);
845                 return;
846             }
847
848             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending data up !");
849
850             const CASecureEndpoint_t tmp =
851                 {
852                     .endpoint = *senderInfo->remoteEndpoint
853                 };
854
855             g_networkPacketReceivedCallback(&tmp,
856                                             senderInfo->defragData,
857                                             senderInfo->recvDataLen);
858             ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
859             u_arraylist_remove(g_senderInfo, senderIndex);
860             senderInfo->remoteEndpoint = NULL;
861             senderInfo->defragData = NULL;
862             OICFree(senderInfo);
863         }
864     }
865     ca_mutex_unlock(g_bleReceiveDataMutex);
866     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
867 }
868
869 static void CALEServerSendDataThread(void *threadData)
870 {
871     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
872
873     CALEData_t * const bleData = (CALEData_t *) threadData;
874     if (!bleData)
875     {
876         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
877         return;
878     }
879
880     uint8_t * const header = OICCalloc(CA_HEADER_LENGTH, 1);
881     VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "Malloc failed");
882
883     const uint32_t totalLength = bleData->dataLen + CA_HEADER_LENGTH;
884
885     OIC_LOG_V(DEBUG,
886               CALEADAPTER_TAG,
887               "Server total Data length with header is [%u]",
888               totalLength);
889
890     uint8_t * const dataSegment = OICCalloc(totalLength, 1);
891
892     if (NULL == dataSegment)
893     {
894         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
895         OICFree(header);
896         return;
897     }
898
899     CAResult_t result = CAGenerateHeader(header,
900                                          CA_HEADER_LENGTH,
901                                          bleData->dataLen);
902     if (CA_STATUS_OK != result )
903     {
904         OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
905         OICFree(header);
906         OICFree(dataSegment);
907         return;
908     }
909
910     memcpy(dataSegment, header, CA_HEADER_LENGTH);
911     OICFree(header);
912
913     uint32_t length = 0;
914     if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
915     {
916         length = totalLength;
917         memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data, bleData->dataLen);
918     }
919     else
920     {
921         length =  CA_SUPPORTED_BLE_MTU_SIZE;
922         memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data,
923                CA_SUPPORTED_BLE_MTU_SIZE - CA_HEADER_LENGTH);
924     }
925
926     uint32_t iter = totalLength / CA_SUPPORTED_BLE_MTU_SIZE;
927     uint32_t index = 0;
928
929     // Send the first segment with the header.
930     if (NULL != bleData->remoteEndpoint) // Sending Unicast Data
931     {
932         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Unicast Data");
933
934         result = CAUpdateCharacteristicsToGattClient(
935                     bleData->remoteEndpoint->addr, dataSegment, length);
936
937         if (CA_STATUS_OK != result)
938         {
939             OIC_LOG_V(ERROR,
940                       CALEADAPTER_TAG,
941                       "Update characteristics failed, result [%d]",
942                       result);
943
944             g_errorHandler(bleData->remoteEndpoint,
945                            bleData->data,
946                            bleData->dataLen,
947                            result);
948             OICFree(dataSegment);
949             return;
950         }
951
952         OIC_LOG_V(DEBUG,
953                   CALEADAPTER_TAG,
954                   "Server Sent data length [%u]",
955                   length);
956         for (index = 1; index < iter; index++)
957         {
958             // Send the remaining header.
959             OIC_LOG_V(DEBUG,
960                       CALEADAPTER_TAG,
961                       "Sending the chunk number [%u]",
962                       index);
963
964             result =
965                 CAUpdateCharacteristicsToGattClient(
966                     bleData->remoteEndpoint->addr,
967                     bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH),
968                     CA_SUPPORTED_BLE_MTU_SIZE);
969             if (CA_STATUS_OK != result)
970             {
971                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
972                             "Update characteristics failed, result [%d]", result);
973                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
974                 OICFree(dataSegment);
975                 return;
976             }
977             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]",
978                                                CA_SUPPORTED_BLE_MTU_SIZE);
979         }
980
981         const uint32_t remainingLen =
982             totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
983
984         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
985         {
986             // send the last segment of the data (Ex: 22 bytes of 622
987             // bytes of data when MTU is 200)
988             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
989             result = CAUpdateCharacteristicsToGattClient(
990                          bleData->remoteEndpoint->addr,
991                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
992                          remainingLen);
993             if (CA_STATUS_OK != result)
994             {
995                 OIC_LOG_V(ERROR,
996                           CALEADAPTER_TAG,
997                           "Update characteristics failed, result [%d]",
998                           result);
999                 g_errorHandler(bleData->remoteEndpoint,
1000                                bleData->data,
1001                                bleData->dataLen,
1002                                result);
1003                 OICFree(dataSegment);
1004                 return;
1005             }
1006             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", remainingLen);
1007         }
1008      }
1009     else
1010     {
1011         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
1012         result = CAUpdateCharacteristicsToAllGattClients(dataSegment, length);
1013         if (CA_STATUS_OK != result)
1014         {
1015             OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1016                       result);
1017             CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1018             OICFree(dataSegment);
1019             return;
1020         }
1021         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
1022         for (index = 1; index < iter; index++)
1023         {
1024             // Send the remaining header.
1025             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Sending the chunk number [%d]", index);
1026             result = CAUpdateCharacteristicsToAllGattClients(
1027                          bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH),
1028                          CA_SUPPORTED_BLE_MTU_SIZE);
1029             if (CA_STATUS_OK != result)
1030             {
1031                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1032                           result);
1033                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1034                 OICFree(dataSegment);
1035                 return;
1036             }
1037             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%u]", CA_SUPPORTED_BLE_MTU_SIZE);
1038         }
1039
1040         const uint32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
1041         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1042         {
1043             // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
1044             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1045             result = CAUpdateCharacteristicsToAllGattClients(
1046                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
1047                          remainingLen);
1048             if (CA_STATUS_OK != result)
1049             {
1050                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1051                           result);
1052                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1053                 OICFree(dataSegment);
1054                 return;
1055             }
1056             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", remainingLen);
1057         }
1058     }
1059     OICFree(dataSegment);
1060
1061     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1062 }
1063
1064 static void CALEClientSendDataThread(void *threadData)
1065 {
1066     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1067
1068     CALEData_t *bleData = (CALEData_t *) threadData;
1069     if (!bleData)
1070     {
1071         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
1072         return;
1073     }
1074
1075     uint8_t * const header = OICCalloc(CA_HEADER_LENGTH, 1);
1076     VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "Malloc failed");
1077
1078     const uint32_t totalLength = bleData->dataLen + CA_HEADER_LENGTH;
1079     uint8_t *dataSegment = OICCalloc(totalLength, 1);
1080     if (NULL == dataSegment)
1081     {
1082         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
1083         OICFree(header);
1084         return;
1085     }
1086
1087     CAResult_t result = CAGenerateHeader(header,
1088                                          CA_HEADER_LENGTH,
1089                                          bleData->dataLen);
1090     if (CA_STATUS_OK != result )
1091     {
1092         OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
1093         OICFree(header);
1094         OICFree(dataSegment);
1095         return ;
1096     }
1097     memcpy(dataSegment, header, CA_HEADER_LENGTH);
1098     OICFree(header);
1099
1100     uint32_t length = 0;
1101     if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
1102     {
1103         length = totalLength;
1104         memcpy(dataSegment + CA_HEADER_LENGTH,
1105                bleData->data,
1106                bleData->dataLen);
1107     }
1108     else
1109     {
1110         length = CA_SUPPORTED_BLE_MTU_SIZE;
1111         memcpy(dataSegment + CA_HEADER_LENGTH,
1112                bleData->data,
1113                CA_SUPPORTED_BLE_MTU_SIZE - CA_HEADER_LENGTH);
1114     }
1115
1116     const uint32_t iter = totalLength / CA_SUPPORTED_BLE_MTU_SIZE;
1117     uint32_t index = 0;
1118     if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
1119     {
1120         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
1121         // Send the first segment with the header.
1122         result =
1123             CAUpdateCharacteristicsToGattServer(
1124                 bleData->remoteEndpoint->addr,
1125                 dataSegment,
1126                 length,
1127                 LE_UNICAST,
1128                 0);
1129
1130         if (CA_STATUS_OK != result)
1131         {
1132             OIC_LOG_V(ERROR,
1133                       CALEADAPTER_TAG,
1134                       "Update characteristics failed, result [%d]",
1135                       result);
1136             g_errorHandler(bleData->remoteEndpoint,
1137                            bleData->data,
1138                            bleData->dataLen,
1139                            result);
1140             OICFree(dataSegment);
1141             return;
1142         }
1143
1144         OIC_LOG_V(DEBUG,
1145                   CALEADAPTER_TAG,
1146                   "Client Sent Data length  is [%u]",
1147                   length);
1148
1149         for (index = 1; index < iter; index++)
1150         {
1151             // Send the remaining header.
1152             result = CAUpdateCharacteristicsToGattServer(
1153                      bleData->remoteEndpoint->addr,
1154                      bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
1155                      CA_SUPPORTED_BLE_MTU_SIZE,
1156                      LE_UNICAST, 0);
1157             if (CA_STATUS_OK != result)
1158             {
1159                 OIC_LOG_V(ERROR,
1160                           CALEADAPTER_TAG,
1161                           "Update characteristics failed, result [%d]",
1162                           result);
1163                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1164                 OICFree(dataSegment);
1165                 return;
1166             }
1167             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]",
1168                                                CA_SUPPORTED_BLE_MTU_SIZE);
1169         }
1170
1171         const uint32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
1172         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1173         {
1174             // send the last segment of the data (Ex: 22 bytes of 622
1175             // bytes of data when MTU is 200)
1176             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1177             result = CAUpdateCharacteristicsToGattServer(
1178                      bleData->remoteEndpoint->addr,
1179                      bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
1180                      remainingLen,
1181                      LE_UNICAST, 0);
1182
1183             if (CA_STATUS_OK != result)
1184             {
1185                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1186                                                    result);
1187                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1188                 OICFree(dataSegment);
1189                 return;
1190             }
1191             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", remainingLen);
1192         }
1193     }
1194     else
1195     {
1196         //Sending Mulitcast Data
1197         // Send the first segment with the header.
1198         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Multicast Data");
1199         result = CAUpdateCharacteristicsToAllGattServers(dataSegment, length);
1200         if (CA_STATUS_OK != result)
1201         {
1202             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1203                       "Update characteristics (all) failed, result [%d]", result);
1204             CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1205             OICFree(dataSegment);
1206             return ;
1207         }
1208         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", length);
1209         // Send the remaining header.
1210         for (index = 1; index < iter; index++)
1211         {
1212             result = CAUpdateCharacteristicsToAllGattServers(
1213                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
1214                          CA_SUPPORTED_BLE_MTU_SIZE);
1215             if (CA_STATUS_OK != result)
1216             {
1217                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics (all) failed, result [%d]",
1218                           result);
1219                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1220                 OICFree(dataSegment);
1221                 return;
1222             }
1223             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]",
1224                       CA_SUPPORTED_BLE_MTU_SIZE);
1225         }
1226
1227         uint32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
1228         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1229         {
1230             // send the last segment of the data (Ex: 22 bytes of 622
1231             // bytes of data when MTU is 200)
1232             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1233             result =
1234                 CAUpdateCharacteristicsToAllGattServers(
1235                     bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
1236                     remainingLen);
1237             if (CA_STATUS_OK != result)
1238             {
1239                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1240                           "Update characteristics (all) failed, result [%d]", result);
1241                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1242                 OICFree(dataSegment);
1243                 return;
1244             }
1245             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", remainingLen);
1246         }
1247
1248     }
1249
1250     OICFree(dataSegment);
1251
1252     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CABLEClientSendDataThread");
1253 }
1254
1255 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
1256                                   const uint8_t *data,
1257                                   uint32_t dataLength)
1258 {
1259     CALEData_t * const bleData = OICMalloc(sizeof(CALEData_t));
1260
1261     if (!bleData)
1262     {
1263         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1264         return NULL;
1265     }
1266
1267     bleData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
1268     bleData->data = OICCalloc(dataLength + 1, 1);
1269
1270     if (NULL == bleData->data)
1271     {
1272         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1273         CAFreeLEData(bleData);
1274         return NULL;
1275     }
1276
1277     memcpy(bleData->data, data, dataLength);
1278     bleData->dataLen = dataLength;
1279
1280     return bleData;
1281 }
1282
1283 static void CAFreeLEData(CALEData_t *bleData)
1284 {
1285     VERIFY_NON_NULL_VOID(bleData, CALEADAPTER_TAG, "Param bleData is NULL");
1286
1287     CAFreeEndpoint(bleData->remoteEndpoint);
1288     OICFree(bleData->data);
1289     OICFree(bleData);
1290 }
1291
1292 static void CALEDataDestroyer(void *data, uint32_t size)
1293 {
1294     if ((size_t)size < sizeof(CALEData_t *))
1295     {
1296         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1297                   "Destroy data too small %p %d", data, size);
1298     }
1299     CALEData_t *ledata = (CALEData_t *) data;
1300
1301     CAFreeLEData(ledata);
1302 }
1303 #endif
1304
1305 static CAResult_t CAInitLEAdapterMutex()
1306 {
1307     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1308
1309     if (NULL == g_bleIsServerMutex)
1310     {
1311         g_bleIsServerMutex = ca_mutex_new();
1312         if (NULL == g_bleIsServerMutex)
1313         {
1314             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1315             return CA_STATUS_FAILED;
1316         }
1317     }
1318
1319     if (NULL == g_bleNetworkCbMutex)
1320     {
1321         g_bleNetworkCbMutex = ca_mutex_new();
1322         if (NULL == g_bleNetworkCbMutex)
1323         {
1324             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1325             CATerminateLEAdapterMutex();
1326             return CA_STATUS_FAILED;
1327         }
1328     }
1329
1330     if (NULL == g_bleLocalAddressMutex)
1331     {
1332         g_bleLocalAddressMutex = ca_mutex_new();
1333         if (NULL == g_bleLocalAddressMutex)
1334         {
1335             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1336             CATerminateLEAdapterMutex();
1337             return CA_STATUS_FAILED;
1338         }
1339     }
1340
1341     if (NULL == g_bleAdapterThreadPoolMutex)
1342     {
1343         g_bleAdapterThreadPoolMutex = ca_mutex_new();
1344         if (NULL == g_bleAdapterThreadPoolMutex)
1345         {
1346             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1347             CATerminateLEAdapterMutex();
1348             return CA_STATUS_FAILED;
1349         }
1350     }
1351
1352     if (NULL == g_bleClientSendDataMutex)
1353     {
1354         g_bleClientSendDataMutex = ca_mutex_new();
1355         if (NULL == g_bleClientSendDataMutex)
1356         {
1357             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1358             CATerminateLEAdapterMutex();
1359             return CA_STATUS_FAILED;
1360         }
1361     }
1362
1363     if (NULL == g_bleServerSendDataMutex)
1364     {
1365         g_bleServerSendDataMutex = ca_mutex_new();
1366         if (NULL == g_bleServerSendDataMutex)
1367         {
1368             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1369             CATerminateLEAdapterMutex();
1370             return CA_STATUS_FAILED;
1371         }
1372     }
1373
1374     if (NULL == g_bleAdapterReqRespCbMutex)
1375     {
1376         g_bleAdapterReqRespCbMutex = ca_mutex_new();
1377         if (NULL == g_bleAdapterReqRespCbMutex)
1378         {
1379             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1380             CATerminateLEAdapterMutex();
1381             return CA_STATUS_FAILED;
1382         }
1383     }
1384
1385     if (NULL == g_bleReceiveDataMutex)
1386     {
1387         g_bleReceiveDataMutex = ca_mutex_new();
1388         if (NULL == g_bleReceiveDataMutex)
1389         {
1390             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1391             return CA_STATUS_FAILED;
1392         }
1393     }
1394
1395     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1396     return CA_STATUS_OK;
1397 }
1398
1399 static void CATerminateLEAdapterMutex()
1400 {
1401     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1402
1403     ca_mutex_free(g_bleIsServerMutex);
1404     g_bleIsServerMutex = NULL;
1405
1406     ca_mutex_free(g_bleNetworkCbMutex);
1407     g_bleNetworkCbMutex = NULL;
1408
1409     ca_mutex_free(g_bleLocalAddressMutex);
1410     g_bleLocalAddressMutex = NULL;
1411
1412     ca_mutex_free(g_bleAdapterThreadPoolMutex);
1413     g_bleAdapterThreadPoolMutex = NULL;
1414
1415     ca_mutex_free(g_bleClientSendDataMutex);
1416     g_bleClientSendDataMutex = NULL;
1417
1418     ca_mutex_free(g_bleServerSendDataMutex);
1419     g_bleServerSendDataMutex = NULL;
1420
1421     ca_mutex_free(g_bleAdapterReqRespCbMutex);
1422     g_bleAdapterReqRespCbMutex = NULL;
1423
1424     ca_mutex_free(g_bleReceiveDataMutex);
1425     g_bleReceiveDataMutex = NULL;
1426
1427     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1428 }
1429
1430 /**
1431  * Starting LE connectivity adapters.
1432  *
1433  * As its peer to peer it does not require to start any servers.
1434  *
1435  * @return ::CA_STATUS_OK or Appropriate error code.
1436  */
1437 static CAResult_t CAStartLE();
1438
1439 /**
1440  * Start listening server for receiving multicast search requests.
1441  *
1442  * Transport Specific Behavior:
1443  *   LE  Starts GATT Server with prefixed UUID and Characteristics
1444  *   per OIC Specification.
1445  * @return  ::CA_STATUS_OK or Appropriate error code.
1446  */
1447 static CAResult_t CAStartLEListeningServer();
1448
1449 /**
1450  * Sarting discovery of servers for receiving multicast
1451  * advertisements.
1452  *
1453  * Transport Specific Behavior:
1454  *   LE  Starts GATT Server with prefixed UUID and Characteristics
1455  *   per OIC Specification.
1456  *
1457  * @return ::CA_STATUS_OK or Appropriate error code
1458  */
1459 static CAResult_t CAStartLEDiscoveryServer();
1460
1461 /**
1462  * Send data to the endpoint using the adapter connectivity.
1463  *
1464  * @param[in] endpoint Remote Endpoint information (like MAC address,
1465  *                     reference URI and connectivity type) to which
1466  *                     the unicast data has to be sent.
1467  * @param[in] data     Data which required to be sent.
1468  * @param[in] dataLen  Size of data to be sent.
1469  *
1470  * @note  dataLen must be > 0.
1471  *
1472  * @return The number of bytes sent on the network, or -1 on error.
1473  */
1474 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
1475                                    const void *data,
1476                                    uint32_t dataLen);
1477
1478 /**
1479  * Send multicast data to the endpoint using the LE connectivity.
1480  *
1481  * @param[in] endpoint Remote Endpoint information to which the
1482  *                     multicast data has to be sent.
1483  * @param[in] data     Data which required to be sent.
1484  * @param[in] dataLen  Size of data to be sent.
1485  *
1486  * @note  dataLen must be > 0.
1487  *
1488  * @return The number of bytes sent on the network, or -1 on error.
1489  */
1490 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
1491                                      const void *data,
1492                                      uint32_t dataLen);
1493
1494 /**
1495  * Get LE Connectivity network information.
1496  *
1497  * @param[out] info Local connectivity information structures.
1498  * @param[out] size Number of local connectivity structures.
1499  *
1500  * @return ::CA_STATUS_OK or Appropriate error code.
1501  */
1502 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info,
1503                                               uint32_t *size);
1504
1505 /**
1506  * Read Synchronous API callback.
1507  *
1508  * @return  ::CA_STATUS_OK or Appropriate error code.
1509  */
1510 static CAResult_t CAReadLEData();
1511
1512 /**
1513  * Stopping the adapters and close socket connections.
1514  *
1515  * LE Stops all GATT servers and GATT Clients.
1516  *
1517  * @return ::CA_STATUS_OK or Appropriate error code.
1518  */
1519 static CAResult_t CAStopLE();
1520
1521 /**
1522  * Terminate the LE connectivity adapter.
1523  *
1524  * Configuration information will be deleted from further use.
1525  */
1526 static void CATerminateLE();
1527
1528 /**
1529  * This function will receive the data from the GattServer and add the
1530  * data to the Server receiver queue.
1531  *
1532  * @param[in] remoteAddress Remote address of the device from where
1533  *                          data is received.
1534  * @param[in] data          Actual data recevied from the remote
1535  *                          device.
1536  * @param[in] dataLength    Length of the data received from the
1537  *                          remote device.
1538  * @param[in] sentLength    Length of the data sent from the remote
1539  *                          device.
1540  *
1541  * @return ::CA_STATUS_OK or Appropriate error code.
1542  * @retval ::CA_STATUS_OK  Successful.
1543  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
1544  * @retval ::CA_STATUS_FAILED Operation failed.
1545  *
1546  */
1547 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
1548                                                 const uint8_t *data,
1549                                                 uint32_t dataLength,
1550                                                 uint32_t *sentLength);
1551
1552 /**
1553  * This function will receive the data from the GattClient and add the
1554  * data into the Client receiver queue.
1555  *
1556  * @param[in] remoteAddress Remote address of the device from where
1557  *                          data is received.
1558  * @param[in] data          Actual data recevied from the remote
1559  *                          device.
1560  * @param[in] dataLength    Length of the data received from the
1561  *                          remote device.
1562  * @param[in] sentLength    Length of the data sent from the remote
1563  *                          device.
1564  *
1565  * @return ::CA_STATUS_OK or Appropriate error code.
1566  * @retval ::CA_STATUS_OK  Successful.
1567  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
1568  * @retval ::CA_STATUS_FAILED Operation failed.
1569  */
1570 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
1571                                                 const uint8_t *data,
1572                                                 uint32_t dataLength,
1573                                                 uint32_t *sentLength);
1574
1575 /**
1576  * Set the NetworkPacket received callback to CA layer from adapter
1577  * layer.
1578  *
1579  * @param[in] callback Callback handle sent from the upper layer.
1580  */
1581 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
1582
1583 /**
1584  * Push the data from CA layer to the Sender processor queue.
1585  *
1586  * @param[in] remoteEndpoint Remote endpoint information of the
1587  *                           server.
1588  * @param[in] data           Data to be transmitted from LE.
1589  * @param[in] dataLen        Length of the Data being transmitted.
1590  *
1591  * @return ::CA_STATUS_OK or Appropriate error code.
1592  * @retval ::CA_STATUS_OK  Successful.
1593  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
1594  * @retval ::CA_STATUS_FAILED Operation failed.
1595  */
1596 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
1597                                             const uint8_t *data,
1598                                             uint32_t dataLen);
1599
1600 /**
1601  * Push the data from CA layer to the Sender processor queue.
1602  *
1603  * @param[in] remoteEndpoint Remote endpoint information of the
1604  *                           server.
1605  * @param[in] data           Data to be transmitted from LE.
1606  * @param[in] dataLen        Length of the Data being transmitted.
1607  *
1608  * @return ::CA_STATUS_OK or Appropriate error code.
1609  * @retval ::CA_STATUS_OK  Successful.
1610  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
1611  * @retval ::CA_STATUS_FAILED Operation failed.
1612  */
1613 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
1614                                             const uint8_t *data,
1615                                             uint32_t dataLen);
1616
1617 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
1618                           CANetworkPacketReceivedCallback reqRespCallback,
1619                           CANetworkChangeCallback netCallback,
1620                           CAErrorHandleCallback errorCallback,
1621                           ca_thread_pool_t handle)
1622 {
1623     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1624
1625     //Input validation
1626     VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null");
1627     VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null");
1628     VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null");
1629
1630     CAResult_t result = CA_STATUS_OK;
1631     result = CAInitLEAdapterMutex();
1632     if (CA_STATUS_OK != result)
1633     {
1634         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
1635         return CA_STATUS_FAILED;
1636     }
1637     result = CAInitializeLENetworkMonitor();
1638     if (CA_STATUS_OK != result)
1639     {
1640         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
1641         return CA_STATUS_FAILED;
1642     }
1643
1644     CAInitializeLEAdapter();
1645
1646     CASetLEClientThreadPoolHandle(handle);
1647     CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
1648     CASetLEServerThreadPoolHandle(handle);
1649     CASetLEAdapterThreadPoolHandle(handle);
1650     CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
1651     CASetLEReqRespAdapterCallback(reqRespCallback);
1652
1653     CASetBLEClientErrorHandleCallback(CALEErrorHandler);
1654     CASetBLEServerErrorHandleCallback(CALEErrorHandler);
1655     CALERegisterNetworkNotifications(netCallback);
1656
1657     g_errorHandler = errorCallback;
1658
1659     static const CAConnectivityHandler_t connHandler =
1660         {
1661             .startAdapter = CAStartLE,
1662             .stopAdapter = CAStopLE,
1663             .startListenServer = CAStartLEListeningServer,
1664             .startDiscoveryServer = CAStartLEDiscoveryServer,
1665             .sendData = CASendLEUnicastData,
1666             .sendDataToAll = CASendLEMulticastData,
1667             .GetnetInfo = CAGetLEInterfaceInformation,
1668             .readData = CAReadLEData,
1669             .terminate = CATerminateLE
1670         };
1671
1672     registerCallback(connHandler, CA_ADAPTER_GATT_BTLE);
1673
1674     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1675
1676     return CA_STATUS_OK;
1677 }
1678
1679 static CAResult_t CAStartLE()
1680 {
1681     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAStartLE");
1682
1683     return CAStartLEAdapter();
1684 }
1685
1686 static CAResult_t CAStopLE()
1687 {
1688     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1689 #ifndef SINGLE_THREAD
1690     CAStopLEQueues();
1691 #endif
1692
1693     ca_mutex_lock(g_bleIsServerMutex);
1694     if (true == g_isServer)
1695     {
1696         CAStopLEGattServer();
1697     }
1698     else
1699     {
1700         CAStopLEGattClient();
1701     }
1702     ca_mutex_unlock(g_bleIsServerMutex);
1703
1704     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1705
1706     return CA_STATUS_OK;
1707 }
1708
1709 static void CATerminateLE()
1710 {
1711     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1712
1713     CASetLEReqRespServerCallback(NULL);
1714     CASetLEReqRespClientCallback(NULL);
1715     CALERegisterNetworkNotifications(NULL);
1716     CASetLEReqRespAdapterCallback(NULL);
1717     CATerminateLENetworkMonitor();
1718
1719     ca_mutex_lock(g_bleIsServerMutex);
1720     if (true == g_isServer)
1721     {
1722         CATerminateLEGattServer();
1723     }
1724     else
1725     {
1726         CATerminateLEGattClient();
1727     }
1728     ca_mutex_unlock(g_bleIsServerMutex);
1729
1730 #ifndef SINGLE_THREAD
1731     CATerminateLEQueues();
1732 #endif
1733     CATerminateLEAdapterMutex();
1734
1735     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1736 }
1737
1738 static CAResult_t CAStartLEListeningServer()
1739 {
1740     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1741     CAResult_t result = CA_STATUS_OK;
1742 #ifndef SINGLE_THREAD
1743     result = CAInitLEServerQueues();
1744     if (CA_STATUS_OK != result)
1745     {
1746         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
1747         return CA_STATUS_FAILED;
1748     }
1749 #endif
1750
1751     result = CAGetLEAdapterState();
1752     if (CA_ADAPTER_NOT_ENABLED == result)
1753     {
1754         gLeServerStatus = CA_LISTENING_SERVER;
1755         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
1756         return CA_STATUS_OK;
1757     }
1758
1759     if (CA_STATUS_FAILED == result)
1760     {
1761         OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
1762         return CA_STATUS_FAILED;
1763     }
1764
1765     CAStartLEGattServer();
1766
1767     ca_mutex_lock(g_bleIsServerMutex);
1768     g_isServer = true;
1769     ca_mutex_unlock(g_bleIsServerMutex);
1770
1771     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1772     return CA_STATUS_OK;
1773 }
1774
1775 static CAResult_t CAStartLEDiscoveryServer()
1776 {
1777     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1778     CAResult_t result = CA_STATUS_OK;
1779 #ifndef SINGLE_THREAD
1780     result = CAInitLEClientQueues();
1781     if (CA_STATUS_OK != result)
1782     {
1783         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
1784         return CA_STATUS_FAILED;
1785     }
1786 #endif
1787     result = CAGetLEAdapterState();
1788     if (CA_ADAPTER_NOT_ENABLED == result)
1789     {
1790         gLeServerStatus = CA_DISCOVERY_SERVER;
1791         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
1792         return CA_STATUS_OK;
1793     }
1794
1795     if (CA_STATUS_FAILED == result)
1796     {
1797         OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
1798         return CA_STATUS_FAILED;
1799     }
1800
1801     CAStartLEGattClient();
1802
1803     ca_mutex_lock(g_bleIsServerMutex);
1804     g_isServer = false;
1805     ca_mutex_unlock(g_bleIsServerMutex);
1806
1807     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1808     return CA_STATUS_OK;
1809 }
1810
1811 static CAResult_t CAReadLEData()
1812 {
1813     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1814 #ifdef SINGLE_THREAD
1815     CACheckLEData();
1816 #endif
1817     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1818     return CA_STATUS_OK;
1819 }
1820
1821 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
1822                                    const void *data,
1823                                    uint32_t dataLen)
1824 {
1825     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1826
1827     //Input validation
1828     VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
1829     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
1830
1831     CAResult_t result = CA_STATUS_FAILED;
1832
1833     ca_mutex_lock(g_bleIsServerMutex);
1834     if (true  == g_isServer)
1835     {
1836         result = CALEAdapterServerSendData(endpoint, data, dataLen);
1837         if (CA_STATUS_OK != result)
1838         {
1839             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data failed\n");
1840             if (g_errorHandler)
1841             {
1842                 g_errorHandler(endpoint, data, dataLen, result);
1843             }
1844             ca_mutex_unlock(g_bleIsServerMutex);
1845             return -1;
1846         }
1847     }
1848     else
1849     {
1850         result = CALEAdapterClientSendData(endpoint, data, dataLen);
1851         if (CA_STATUS_OK != result)
1852         {
1853             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data failed \n");
1854             if (g_errorHandler)
1855             {
1856                 g_errorHandler(endpoint, data, dataLen, result);
1857             }
1858             ca_mutex_unlock(g_bleIsServerMutex);
1859             return -1;
1860         }
1861     }
1862     ca_mutex_unlock(g_bleIsServerMutex);
1863
1864     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1865     return dataLen;
1866 }
1867
1868 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
1869                                      const void *data,
1870                                      uint32_t dataLen)
1871 {
1872     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1873
1874     //Input validation
1875     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
1876
1877     if (0 >= dataLen)
1878     {
1879         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
1880         return -1;
1881     }
1882
1883     CAResult_t result = CA_STATUS_FAILED;
1884
1885     ca_mutex_lock(g_bleIsServerMutex);
1886     if (true  == g_isServer)
1887     {
1888         result = CALEAdapterServerSendData(NULL, data, dataLen);
1889         if (CA_STATUS_OK != result)
1890         {
1891             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data failed" );
1892
1893             ca_mutex_unlock(g_bleIsServerMutex);
1894             if (g_errorHandler)
1895             {
1896                 g_errorHandler(endpoint, data, dataLen, result);
1897             }
1898             return -1;
1899         }
1900     }
1901     else
1902     {
1903         result = CALEAdapterClientSendData(NULL, data, dataLen);
1904         if (CA_STATUS_OK != result)
1905         {
1906             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data failed" );
1907             if (g_errorHandler)
1908             {
1909                 g_errorHandler(endpoint, data, dataLen, result);
1910             }
1911             ca_mutex_unlock(g_bleIsServerMutex);
1912             return -1;
1913         }
1914     }
1915     ca_mutex_unlock(g_bleIsServerMutex);
1916
1917     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1918     return dataLen;
1919 }
1920
1921 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1922 {
1923     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1924
1925     VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
1926
1927     char *local_address = NULL;
1928
1929     CAResult_t res = CAGetLEAddress(&local_address);
1930     if (CA_STATUS_OK != res)
1931     {
1932         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
1933         return res;
1934     }
1935
1936     if (NULL == local_address)
1937     {
1938         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
1939         return CA_STATUS_FAILED;
1940     }
1941
1942     *size = 0;
1943     (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
1944     if (NULL == (*info))
1945     {
1946         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
1947         OICFree(local_address);
1948         return CA_STATUS_FAILED;
1949     }
1950
1951     size_t local_address_len = strlen(local_address);
1952
1953     if(local_address_len >= sizeof(g_localBLEAddress) ||
1954             local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
1955     {
1956         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
1957         OICFree(*info);
1958         OICFree(local_address);
1959         return CA_STATUS_FAILED;
1960     }
1961
1962     OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
1963     ca_mutex_lock(g_bleLocalAddressMutex);
1964     OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
1965     ca_mutex_unlock(g_bleLocalAddressMutex);
1966
1967     (*info)->adapter = CA_ADAPTER_GATT_BTLE;
1968     *size = 1;
1969     OICFree(local_address);
1970
1971     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1972     return CA_STATUS_OK;
1973 }
1974
1975 static CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback)
1976 {
1977     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1978
1979     ca_mutex_lock(g_bleNetworkCbMutex);
1980     g_networkCallback = netCallback;
1981     ca_mutex_unlock(g_bleNetworkCbMutex);
1982     CAResult_t res = CA_STATUS_OK;
1983     if (netCallback)
1984     {
1985         res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
1986         if (CA_STATUS_OK != res)
1987         {
1988             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
1989         }
1990     }
1991     else
1992     {
1993         res = CAUnSetLEAdapterStateChangedCb();
1994         if (CA_STATUS_OK != res)
1995         {
1996             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
1997         }
1998     }
1999
2000     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2001     return res;
2002 }
2003
2004 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
2005 {
2006     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2007
2008     VERIFY_NON_NULL_VOID(g_localBLEAddress, CALEADAPTER_TAG, "g_localBLEAddress is null");
2009     CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE };
2010
2011     ca_mutex_lock(g_bleLocalAddressMutex);
2012     OICStrcpy(localEndpoint.addr,
2013               sizeof(localEndpoint.addr),
2014               g_localBLEAddress);
2015     ca_mutex_unlock(g_bleLocalAddressMutex);
2016
2017     g_bleAdapterState = adapter_state;
2018     // Start a GattServer/Client if gLeServerStatus is SET
2019     if (CA_LISTENING_SERVER == gLeServerStatus)
2020     {
2021         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartLEGattServer");
2022         CAStartLEGattServer();
2023     }
2024     else if (CA_DISCOVERY_SERVER == gLeServerStatus)
2025     {
2026         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartBleGattClient");
2027         CAStartLEGattClient();
2028     }
2029     gLeServerStatus = CA_SERVER_NOTSTARTED;
2030
2031     ca_mutex_lock(g_bleNetworkCbMutex);
2032     if (NULL != g_networkCallback)
2033     {
2034         g_networkCallback(&localEndpoint, adapter_state);
2035     }
2036     else
2037     {
2038         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
2039     }
2040     ca_mutex_unlock(g_bleNetworkCbMutex);
2041
2042     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2043 }
2044
2045 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
2046                                             const uint8_t *data,
2047                                             uint32_t dataLen)
2048 {
2049     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2050
2051     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
2052 #ifndef SINGLE_THREAD
2053     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
2054                         "g_bleClientSendQueueHandle is  NULL",
2055                         CA_STATUS_FAILED);
2056     VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
2057                         "g_bleClientSendDataMutex is NULL",
2058                         CA_STATUS_FAILED);
2059
2060     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG, "g_bleClientSendQueueHandle",
2061                         CA_STATUS_FAILED);
2062
2063     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%u]", dataLen);
2064
2065     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen);
2066     if (!bleData)
2067     {
2068         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2069         return CA_MEMORY_ALLOC_FAILED;
2070     }
2071     // Add message to send queue
2072     ca_mutex_lock(g_bleClientSendDataMutex);
2073     CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData, sizeof(CALEData_t));
2074     ca_mutex_unlock(g_bleClientSendDataMutex);
2075 #endif
2076     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2077     return CA_STATUS_OK;
2078 }
2079
2080 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
2081                                             const uint8_t *data,
2082                                             uint32_t dataLen)
2083 {
2084     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2085
2086     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
2087
2088 #ifdef SINGLE_THREAD
2089     uint8_t header[CA_HEADER_LENGTH] = { 0 };
2090
2091     CAResult_t result =
2092         CAGenerateHeader(header, CA_HEADER_LENGTH, dataLen);
2093
2094     if (CA_STATUS_OK != result)
2095     {
2096         OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
2097         return CA_STATUS_FAILED;
2098     }
2099
2100     if (!CAIsLEConnected())
2101     {
2102         OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
2103         return CA_STATUS_FAILED;
2104     }
2105
2106     result = CAUpdateCharacteristicsToAllGattClients(header, CA_HEADER_LENGTH);
2107     if (CA_STATUS_OK != result)
2108     {
2109         OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2110         return CA_STATUS_FAILED;
2111     }
2112
2113     const uint32_t dataLimit = dataLen / CA_SUPPORTED_BLE_MTU_SIZE;
2114     for (uint32_t iter = 0; iter < dataLimit; iter++)
2115     {
2116         result =
2117             CAUpdateCharacteristicsToAllGattClients(
2118                 data + (iter * CA_SUPPORTED_BLE_MTU_SIZE),
2119                 CA_SUPPORTED_BLE_MTU_SIZE);
2120
2121         if (CA_STATUS_OK != result)
2122         {
2123             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2124             return CA_STATUS_FAILED;
2125         }
2126
2127         CALEDoEvents();
2128     }
2129
2130     const uint32_t remainingLen = dataLen % CA_SUPPORTED_BLE_MTU_SIZE;
2131     if (remainingLen)
2132     {
2133         result =
2134             CAUpdateCharacteristicsToAllGattClients(
2135                 data + (dataLimit * CA_SUPPORTED_BLE_MTU_SIZE),
2136                 remainingLen);
2137         if (CA_STATUS_OK != result)
2138         {
2139             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2140             return CA_STATUS_FAILED;
2141         }
2142         CALEDoEvents();
2143     }
2144 #else
2145     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
2146                         "BleClientReceiverQueue is NULL",
2147                         CA_STATUS_FAILED);
2148     VERIFY_NON_NULL_RET(g_bleServerSendDataMutex, CALEADAPTER_TAG,
2149                         "BleClientSendDataMutex is NULL",
2150                         CA_STATUS_FAILED);
2151
2152     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG, "sendQueueHandle",
2153                         CA_STATUS_FAILED);
2154
2155     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
2156
2157     CALEData_t * const bleData =
2158         CACreateLEData(remoteEndpoint, data, dataLen);
2159
2160     if (!bleData)
2161     {
2162         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2163         return CA_MEMORY_ALLOC_FAILED;
2164     }
2165
2166     // Add message to send queue
2167     ca_mutex_lock(g_bleServerSendDataMutex);
2168     CAQueueingThreadAddData(g_bleServerSendQueueHandle,
2169                             bleData,
2170                             sizeof(CALEData_t));
2171     ca_mutex_unlock(g_bleServerSendDataMutex);
2172 #endif
2173     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2174     return CA_STATUS_OK;
2175 }
2176
2177 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
2178                                                 const uint8_t *data,
2179                                                 uint32_t dataLength,
2180                                                 uint32_t *sentLength)
2181 {
2182     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2183
2184     //Input validation
2185     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
2186     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
2187
2188 #ifdef SINGLE_THREAD
2189     if(g_networkPacketReceivedCallback)
2190     {
2191         // will be filled by upper layer
2192         const CASecureEndpoint_t endpoint =
2193             { .endpoint = { .adapter = CA_ADAPTER_GATT_BTLE } };
2194
2195
2196         g_networkPacketReceivedCallback(&endpoint, data, dataLength);
2197     }
2198 #else
2199     VERIFY_NON_NULL_RET(g_bleReceiverQueue,
2200                         CALEADAPTER_TAG,
2201                         "g_bleReceiverQueue",
2202                         CA_STATUS_FAILED);
2203
2204     //Add message to data queue
2205     CAEndpoint_t * const remoteEndpoint =
2206         CACreateEndpointObject(CA_DEFAULT_FLAGS,
2207                                CA_ADAPTER_GATT_BTLE,
2208                                remoteAddress,
2209                                0);
2210
2211     if (NULL == remoteEndpoint)
2212     {
2213         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
2214         return CA_STATUS_FAILED;
2215     }
2216
2217     // Create bleData to add to queue
2218     OIC_LOG_V(DEBUG,
2219               CALEADAPTER_TAG,
2220               "Data received from LE layer [%d]",
2221               dataLength);
2222
2223     CALEData_t * const bleData =
2224         CACreateLEData(remoteEndpoint, data, dataLength);
2225
2226     if (!bleData)
2227     {
2228         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2229         CAFreeEndpoint(remoteEndpoint);
2230         return CA_MEMORY_ALLOC_FAILED;
2231     }
2232
2233     CAFreeEndpoint(remoteEndpoint);
2234     // Add message to receiver queue
2235     CAQueueingThreadAddData(g_bleReceiverQueue, bleData, sizeof(CALEData_t));
2236
2237     *sentLength = dataLength;
2238 #endif
2239     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2240     return CA_STATUS_OK;
2241 }
2242
2243 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
2244                                                 const uint8_t *data,
2245                                                 uint32_t dataLength,
2246                                                 uint32_t *sentLength)
2247 {
2248     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2249
2250     //Input validation
2251     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
2252     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
2253 #ifndef SINGLE_THREAD
2254     VERIFY_NON_NULL_RET(g_bleReceiverQueue, CALEADAPTER_TAG, "g_bleReceiverQueue",
2255                         CA_STATUS_FAILED);
2256
2257     //Add message to data queue
2258     CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
2259                                                           CA_ADAPTER_GATT_BTLE,
2260                                                           remoteAddress, 0);
2261     if (NULL == remoteEndpoint)
2262     {
2263         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
2264         return CA_STATUS_FAILED;
2265     }
2266
2267     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%u]", dataLength);
2268
2269     // Create bleData to add to queue
2270     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLength);
2271     if (!bleData)
2272     {
2273         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2274         CAFreeEndpoint(remoteEndpoint);
2275         return CA_MEMORY_ALLOC_FAILED;
2276     }
2277
2278     CAFreeEndpoint(remoteEndpoint);
2279     // Add message to receiver queue
2280     CAQueueingThreadAddData(g_bleReceiverQueue, bleData, sizeof(CALEData_t));
2281
2282     *sentLength = dataLength;
2283 #endif
2284     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2285     return CA_STATUS_OK;
2286 }
2287
2288 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
2289 {
2290     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2291
2292     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
2293     g_bleAdapterThreadPool = handle;
2294     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
2295
2296     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2297 }
2298
2299 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
2300 {
2301     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2302
2303     ca_mutex_lock(g_bleAdapterReqRespCbMutex);
2304
2305     g_networkPacketReceivedCallback = callback;
2306
2307     ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
2308
2309     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2310 }
2311
2312 static void CALEErrorHandler(const char *remoteAddress,
2313                              const uint8_t *data,
2314                              uint32_t dataLen,
2315                              CAResult_t result)
2316 {
2317     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler IN");
2318
2319     VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
2320
2321     CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS,
2322                                                CA_ADAPTER_GATT_BTLE,
2323                                                remoteAddress,
2324                                                0);
2325
2326     // if required, will be used to build remote endpoint
2327     g_errorHandler(rep, data, dataLen, result);
2328
2329     CAFreeEndpoint(rep);
2330
2331     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler OUT");
2332 }