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