Merge remote-tracking branch 'origin/routing-manager'
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / bt_le_adapter / caleadapter.c
1 /* ****************************************************************
2  *
3  * Copyright 2014 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  ******************************************************************/
20 #include "caleadapter.h"
21
22 #include <stdio.h>
23 #include <stdlib.h>
24
25 #include "caleinterface.h"
26 #include "cacommon.h"
27 #include "camutex.h"
28 #include "caadapterutils.h"
29 #ifndef SINGLE_THREAD
30 #include "caqueueingthread.h"
31 #endif
32 #include "cafragmentation.h"
33 #include "oic_malloc.h"
34 #include "oic_string.h"
35 #include "caremotehandler.h"
36
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 #ifndef ROUTING_GATEWAY
1742     CAResult_t result = CA_STATUS_OK;
1743 #ifndef SINGLE_THREAD
1744     result = CAInitLEServerQueues();
1745     if (CA_STATUS_OK != result)
1746     {
1747         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
1748         return CA_STATUS_FAILED;
1749     }
1750 #endif
1751
1752     result = CAGetLEAdapterState();
1753     if (CA_ADAPTER_NOT_ENABLED == result)
1754     {
1755         gLeServerStatus = CA_LISTENING_SERVER;
1756         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
1757         return CA_STATUS_OK;
1758     }
1759
1760     if (CA_STATUS_FAILED == result)
1761     {
1762         OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
1763         return CA_STATUS_FAILED;
1764     }
1765
1766     CAStartLEGattServer();
1767
1768     ca_mutex_lock(g_bleIsServerMutex);
1769     g_isServer = true;
1770     ca_mutex_unlock(g_bleIsServerMutex);
1771
1772     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1773     return CA_STATUS_OK;
1774 #else
1775     // Routing Gateway only supports BLE client mode.
1776     OIC_LOG(ERROR, CALEADAPTER_TAG, "LE server not supported in Routing Gateway");
1777     return CA_NOT_SUPPORTED;
1778 #endif
1779 }
1780
1781 static CAResult_t CAStartLEDiscoveryServer()
1782 {
1783     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1784     CAResult_t result = CA_STATUS_OK;
1785 #ifndef SINGLE_THREAD
1786     result = CAInitLEClientQueues();
1787     if (CA_STATUS_OK != result)
1788     {
1789         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
1790         return CA_STATUS_FAILED;
1791     }
1792 #endif
1793     result = CAGetLEAdapterState();
1794     if (CA_ADAPTER_NOT_ENABLED == result)
1795     {
1796         gLeServerStatus = CA_DISCOVERY_SERVER;
1797         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
1798         return CA_STATUS_OK;
1799     }
1800
1801     if (CA_STATUS_FAILED == result)
1802     {
1803         OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
1804         return CA_STATUS_FAILED;
1805     }
1806
1807     CAStartLEGattClient();
1808
1809     ca_mutex_lock(g_bleIsServerMutex);
1810     g_isServer = false;
1811     ca_mutex_unlock(g_bleIsServerMutex);
1812
1813     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1814     return CA_STATUS_OK;
1815 }
1816
1817 static CAResult_t CAReadLEData()
1818 {
1819     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1820 #ifdef SINGLE_THREAD
1821     CACheckLEData();
1822 #endif
1823     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1824     return CA_STATUS_OK;
1825 }
1826
1827 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
1828                                    const void *data,
1829                                    uint32_t dataLen)
1830 {
1831     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1832
1833     //Input validation
1834     VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
1835     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
1836
1837     CAResult_t result = CA_STATUS_FAILED;
1838
1839     ca_mutex_lock(g_bleIsServerMutex);
1840     if (true  == g_isServer)
1841     {
1842         result = CALEAdapterServerSendData(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     else
1855     {
1856         result = CALEAdapterClientSendData(endpoint, data, dataLen);
1857         if (CA_STATUS_OK != result)
1858         {
1859             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data failed \n");
1860             if (g_errorHandler)
1861             {
1862                 g_errorHandler(endpoint, data, dataLen, result);
1863             }
1864             ca_mutex_unlock(g_bleIsServerMutex);
1865             return -1;
1866         }
1867     }
1868     ca_mutex_unlock(g_bleIsServerMutex);
1869
1870     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1871     return dataLen;
1872 }
1873
1874 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
1875                                      const void *data,
1876                                      uint32_t dataLen)
1877 {
1878     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1879
1880     //Input validation
1881     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
1882
1883     if (0 >= dataLen)
1884     {
1885         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
1886         return -1;
1887     }
1888
1889     CAResult_t result = CA_STATUS_FAILED;
1890
1891     ca_mutex_lock(g_bleIsServerMutex);
1892     if (true  == g_isServer)
1893     {
1894         result = CALEAdapterServerSendData(NULL, data, dataLen);
1895         if (CA_STATUS_OK != result)
1896         {
1897             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data failed" );
1898
1899             ca_mutex_unlock(g_bleIsServerMutex);
1900             if (g_errorHandler)
1901             {
1902                 g_errorHandler(endpoint, data, dataLen, result);
1903             }
1904             return -1;
1905         }
1906     }
1907     else
1908     {
1909         result = CALEAdapterClientSendData(NULL, data, dataLen);
1910         if (CA_STATUS_OK != result)
1911         {
1912             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data failed" );
1913             if (g_errorHandler)
1914             {
1915                 g_errorHandler(endpoint, data, dataLen, result);
1916             }
1917             ca_mutex_unlock(g_bleIsServerMutex);
1918             return -1;
1919         }
1920     }
1921     ca_mutex_unlock(g_bleIsServerMutex);
1922
1923     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1924     return dataLen;
1925 }
1926
1927 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1928 {
1929     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1930
1931     VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
1932
1933     char *local_address = NULL;
1934
1935     CAResult_t res = CAGetLEAddress(&local_address);
1936     if (CA_STATUS_OK != res)
1937     {
1938         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
1939         return res;
1940     }
1941
1942     if (NULL == local_address)
1943     {
1944         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
1945         return CA_STATUS_FAILED;
1946     }
1947
1948     *size = 0;
1949     (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
1950     if (NULL == (*info))
1951     {
1952         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
1953         OICFree(local_address);
1954         return CA_STATUS_FAILED;
1955     }
1956
1957     size_t local_address_len = strlen(local_address);
1958
1959     if(local_address_len >= sizeof(g_localBLEAddress) ||
1960             local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
1961     {
1962         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
1963         OICFree(*info);
1964         OICFree(local_address);
1965         return CA_STATUS_FAILED;
1966     }
1967
1968     OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
1969     ca_mutex_lock(g_bleLocalAddressMutex);
1970     OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
1971     ca_mutex_unlock(g_bleLocalAddressMutex);
1972
1973     (*info)->adapter = CA_ADAPTER_GATT_BTLE;
1974     *size = 1;
1975     OICFree(local_address);
1976
1977     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1978     return CA_STATUS_OK;
1979 }
1980
1981 static CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback)
1982 {
1983     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1984
1985     ca_mutex_lock(g_bleNetworkCbMutex);
1986     g_networkCallback = netCallback;
1987     ca_mutex_unlock(g_bleNetworkCbMutex);
1988     CAResult_t res = CA_STATUS_OK;
1989     if (netCallback)
1990     {
1991         res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
1992         if (CA_STATUS_OK != res)
1993         {
1994             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
1995         }
1996     }
1997     else
1998     {
1999         res = CAUnSetLEAdapterStateChangedCb();
2000         if (CA_STATUS_OK != res)
2001         {
2002             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
2003         }
2004     }
2005
2006     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2007     return res;
2008 }
2009
2010 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
2011 {
2012     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2013
2014     VERIFY_NON_NULL_VOID(g_localBLEAddress, CALEADAPTER_TAG, "g_localBLEAddress is null");
2015     CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE };
2016
2017     ca_mutex_lock(g_bleLocalAddressMutex);
2018     OICStrcpy(localEndpoint.addr,
2019               sizeof(localEndpoint.addr),
2020               g_localBLEAddress);
2021     ca_mutex_unlock(g_bleLocalAddressMutex);
2022
2023     g_bleAdapterState = adapter_state;
2024     // Start a GattServer/Client if gLeServerStatus is SET
2025     if (CA_LISTENING_SERVER == gLeServerStatus)
2026     {
2027         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartLEGattServer");
2028         CAStartLEGattServer();
2029     }
2030     else if (CA_DISCOVERY_SERVER == gLeServerStatus)
2031     {
2032         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartBleGattClient");
2033         CAStartLEGattClient();
2034     }
2035     gLeServerStatus = CA_SERVER_NOTSTARTED;
2036
2037     ca_mutex_lock(g_bleNetworkCbMutex);
2038     if (NULL != g_networkCallback)
2039     {
2040         g_networkCallback(&localEndpoint, adapter_state);
2041     }
2042     else
2043     {
2044         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
2045     }
2046     ca_mutex_unlock(g_bleNetworkCbMutex);
2047
2048     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2049 }
2050
2051 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
2052                                             const uint8_t *data,
2053                                             uint32_t dataLen)
2054 {
2055     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2056
2057     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
2058 #ifndef SINGLE_THREAD
2059     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
2060                         "g_bleClientSendQueueHandle is  NULL",
2061                         CA_STATUS_FAILED);
2062     VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
2063                         "g_bleClientSendDataMutex is NULL",
2064                         CA_STATUS_FAILED);
2065
2066     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG, "g_bleClientSendQueueHandle",
2067                         CA_STATUS_FAILED);
2068
2069     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%u]", dataLen);
2070
2071     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen);
2072     if (!bleData)
2073     {
2074         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2075         return CA_MEMORY_ALLOC_FAILED;
2076     }
2077     // Add message to send queue
2078     ca_mutex_lock(g_bleClientSendDataMutex);
2079     CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData, sizeof(CALEData_t));
2080     ca_mutex_unlock(g_bleClientSendDataMutex);
2081 #endif
2082     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2083     return CA_STATUS_OK;
2084 }
2085
2086 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
2087                                             const uint8_t *data,
2088                                             uint32_t dataLen)
2089 {
2090     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2091
2092     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
2093
2094 #ifdef SINGLE_THREAD
2095     uint8_t header[CA_HEADER_LENGTH] = { 0 };
2096
2097     CAResult_t result =
2098         CAGenerateHeader(header, CA_HEADER_LENGTH, dataLen);
2099
2100     if (CA_STATUS_OK != result)
2101     {
2102         OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
2103         return CA_STATUS_FAILED;
2104     }
2105
2106     if (!CAIsLEConnected())
2107     {
2108         OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
2109         return CA_STATUS_FAILED;
2110     }
2111
2112     result = CAUpdateCharacteristicsToAllGattClients(header, CA_HEADER_LENGTH);
2113     if (CA_STATUS_OK != result)
2114     {
2115         OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2116         return CA_STATUS_FAILED;
2117     }
2118
2119     const uint32_t dataLimit = dataLen / CA_SUPPORTED_BLE_MTU_SIZE;
2120     for (uint32_t iter = 0; iter < dataLimit; iter++)
2121     {
2122         result =
2123             CAUpdateCharacteristicsToAllGattClients(
2124                 data + (iter * CA_SUPPORTED_BLE_MTU_SIZE),
2125                 CA_SUPPORTED_BLE_MTU_SIZE);
2126
2127         if (CA_STATUS_OK != result)
2128         {
2129             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2130             return CA_STATUS_FAILED;
2131         }
2132
2133         CALEDoEvents();
2134     }
2135
2136     const uint32_t remainingLen = dataLen % CA_SUPPORTED_BLE_MTU_SIZE;
2137     if (remainingLen)
2138     {
2139         result =
2140             CAUpdateCharacteristicsToAllGattClients(
2141                 data + (dataLimit * CA_SUPPORTED_BLE_MTU_SIZE),
2142                 remainingLen);
2143         if (CA_STATUS_OK != result)
2144         {
2145             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2146             return CA_STATUS_FAILED;
2147         }
2148         CALEDoEvents();
2149     }
2150 #else
2151     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
2152                         "BleClientReceiverQueue is NULL",
2153                         CA_STATUS_FAILED);
2154     VERIFY_NON_NULL_RET(g_bleServerSendDataMutex, CALEADAPTER_TAG,
2155                         "BleClientSendDataMutex is NULL",
2156                         CA_STATUS_FAILED);
2157
2158     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG, "sendQueueHandle",
2159                         CA_STATUS_FAILED);
2160
2161     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
2162
2163     CALEData_t * const bleData =
2164         CACreateLEData(remoteEndpoint, data, dataLen);
2165
2166     if (!bleData)
2167     {
2168         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2169         return CA_MEMORY_ALLOC_FAILED;
2170     }
2171
2172     // Add message to send queue
2173     ca_mutex_lock(g_bleServerSendDataMutex);
2174     CAQueueingThreadAddData(g_bleServerSendQueueHandle,
2175                             bleData,
2176                             sizeof(CALEData_t));
2177     ca_mutex_unlock(g_bleServerSendDataMutex);
2178 #endif
2179     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2180     return CA_STATUS_OK;
2181 }
2182
2183 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
2184                                                 const uint8_t *data,
2185                                                 uint32_t dataLength,
2186                                                 uint32_t *sentLength)
2187 {
2188     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2189
2190     //Input validation
2191     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
2192     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
2193
2194 #ifdef SINGLE_THREAD
2195     if(g_networkPacketReceivedCallback)
2196     {
2197         // will be filled by upper layer
2198         const CASecureEndpoint_t endpoint =
2199             { .endpoint = { .adapter = CA_ADAPTER_GATT_BTLE } };
2200
2201
2202         g_networkPacketReceivedCallback(&endpoint, data, dataLength);
2203     }
2204 #else
2205     VERIFY_NON_NULL_RET(g_bleReceiverQueue,
2206                         CALEADAPTER_TAG,
2207                         "g_bleReceiverQueue",
2208                         CA_STATUS_FAILED);
2209
2210     //Add message to data queue
2211     CAEndpoint_t * const remoteEndpoint =
2212         CACreateEndpointObject(CA_DEFAULT_FLAGS,
2213                                CA_ADAPTER_GATT_BTLE,
2214                                remoteAddress,
2215                                0);
2216
2217     if (NULL == remoteEndpoint)
2218     {
2219         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
2220         return CA_STATUS_FAILED;
2221     }
2222
2223     // Create bleData to add to queue
2224     OIC_LOG_V(DEBUG,
2225               CALEADAPTER_TAG,
2226               "Data received from LE layer [%d]",
2227               dataLength);
2228
2229     CALEData_t * const bleData =
2230         CACreateLEData(remoteEndpoint, data, dataLength);
2231
2232     if (!bleData)
2233     {
2234         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2235         CAFreeEndpoint(remoteEndpoint);
2236         return CA_MEMORY_ALLOC_FAILED;
2237     }
2238
2239     CAFreeEndpoint(remoteEndpoint);
2240     // Add message to receiver queue
2241     CAQueueingThreadAddData(g_bleReceiverQueue, bleData, sizeof(CALEData_t));
2242
2243     *sentLength = dataLength;
2244 #endif
2245     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2246     return CA_STATUS_OK;
2247 }
2248
2249 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
2250                                                 const uint8_t *data,
2251                                                 uint32_t dataLength,
2252                                                 uint32_t *sentLength)
2253 {
2254     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2255
2256     //Input validation
2257     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
2258     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
2259 #ifndef SINGLE_THREAD
2260     VERIFY_NON_NULL_RET(g_bleReceiverQueue, CALEADAPTER_TAG, "g_bleReceiverQueue",
2261                         CA_STATUS_FAILED);
2262
2263     //Add message to data queue
2264     CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
2265                                                           CA_ADAPTER_GATT_BTLE,
2266                                                           remoteAddress, 0);
2267     if (NULL == remoteEndpoint)
2268     {
2269         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
2270         return CA_STATUS_FAILED;
2271     }
2272
2273     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%u]", dataLength);
2274
2275     // Create bleData to add to queue
2276     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLength);
2277     if (!bleData)
2278     {
2279         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2280         CAFreeEndpoint(remoteEndpoint);
2281         return CA_MEMORY_ALLOC_FAILED;
2282     }
2283
2284     CAFreeEndpoint(remoteEndpoint);
2285     // Add message to receiver queue
2286     CAQueueingThreadAddData(g_bleReceiverQueue, bleData, sizeof(CALEData_t));
2287
2288     *sentLength = dataLength;
2289 #endif
2290     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2291     return CA_STATUS_OK;
2292 }
2293
2294 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
2295 {
2296     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2297
2298     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
2299     g_bleAdapterThreadPool = handle;
2300     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
2301
2302     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2303 }
2304
2305 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
2306 {
2307     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2308
2309     ca_mutex_lock(g_bleAdapterReqRespCbMutex);
2310
2311     g_networkPacketReceivedCallback = callback;
2312
2313     ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
2314
2315     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2316 }
2317
2318 static void CALEErrorHandler(const char *remoteAddress,
2319                              const uint8_t *data,
2320                              uint32_t dataLen,
2321                              CAResult_t result)
2322 {
2323     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler IN");
2324
2325     VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
2326
2327     CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS,
2328                                                CA_ADAPTER_GATT_BTLE,
2329                                                remoteAddress,
2330                                                0);
2331
2332     // if required, will be used to build remote endpoint
2333     g_errorHandler(rep, data, dataLen, result);
2334
2335     CAFreeEndpoint(rep);
2336
2337     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler OUT");
2338 }