removed unnecessary BLE interface method
[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  * Stops listening server from receiving multicast search requests.
1451  *
1452  * Transport Specific Behavior:
1453  *   LE  Starts GATT Server with prefixed UUID and Characteristics
1454  *   per OIC Specification.
1455  * @return  ::CA_STATUS_OK or Appropriate error code.
1456  */
1457 static CAResult_t CAStopLEListeningServer();
1458
1459 /**
1460  * Sarting discovery of servers for receiving multicast
1461  * advertisements.
1462  *
1463  * Transport Specific Behavior:
1464  *   LE  Starts GATT Server with prefixed UUID and Characteristics
1465  *   per OIC Specification.
1466  *
1467  * @return ::CA_STATUS_OK or Appropriate error code
1468  */
1469 static CAResult_t CAStartLEDiscoveryServer();
1470
1471 /**
1472  * Send data to the endpoint using the adapter connectivity.
1473  *
1474  * @param[in] endpoint Remote Endpoint information (like MAC address,
1475  *                     reference URI and connectivity type) to which
1476  *                     the unicast data has to be sent.
1477  * @param[in] data     Data which required to be sent.
1478  * @param[in] dataLen  Size of data to be sent.
1479  *
1480  * @note  dataLen must be > 0.
1481  *
1482  * @return The number of bytes sent on the network, or -1 on error.
1483  */
1484 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
1485                                    const void *data,
1486                                    uint32_t dataLen);
1487
1488 /**
1489  * Send multicast data to the endpoint using the LE connectivity.
1490  *
1491  * @param[in] endpoint Remote Endpoint information to which the
1492  *                     multicast data has to be sent.
1493  * @param[in] data     Data which required to be sent.
1494  * @param[in] dataLen  Size of data to be sent.
1495  *
1496  * @note  dataLen must be > 0.
1497  *
1498  * @return The number of bytes sent on the network, or -1 on error.
1499  */
1500 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
1501                                      const void *data,
1502                                      uint32_t dataLen);
1503
1504 /**
1505  * Get LE Connectivity network information.
1506  *
1507  * @param[out] info Local connectivity information structures.
1508  * @param[out] size Number of local connectivity structures.
1509  *
1510  * @return ::CA_STATUS_OK or Appropriate error code.
1511  */
1512 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info,
1513                                               uint32_t *size);
1514
1515 /**
1516  * Read Synchronous API callback.
1517  *
1518  * @return  ::CA_STATUS_OK or Appropriate error code.
1519  */
1520 static CAResult_t CAReadLEData();
1521
1522 /**
1523  * Stopping the adapters and close socket connections.
1524  *
1525  * LE Stops all GATT servers and GATT Clients.
1526  *
1527  * @return ::CA_STATUS_OK or Appropriate error code.
1528  */
1529 static CAResult_t CAStopLE();
1530
1531 /**
1532  * Terminate the LE connectivity adapter.
1533  *
1534  * Configuration information will be deleted from further use.
1535  */
1536 static void CATerminateLE();
1537
1538 /**
1539  * This function will receive the data from the GattServer and add the
1540  * data to the Server receiver queue.
1541  *
1542  * @param[in] remoteAddress Remote address of the device from where
1543  *                          data is received.
1544  * @param[in] data          Actual data recevied from the remote
1545  *                          device.
1546  * @param[in] dataLength    Length of the data received from the
1547  *                          remote device.
1548  * @param[in] sentLength    Length of the data sent from the remote
1549  *                          device.
1550  *
1551  * @return ::CA_STATUS_OK or Appropriate error code.
1552  * @retval ::CA_STATUS_OK  Successful.
1553  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
1554  * @retval ::CA_STATUS_FAILED Operation failed.
1555  *
1556  */
1557 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
1558                                                 const uint8_t *data,
1559                                                 uint32_t dataLength,
1560                                                 uint32_t *sentLength);
1561
1562 /**
1563  * This function will receive the data from the GattClient and add the
1564  * data into the Client receiver queue.
1565  *
1566  * @param[in] remoteAddress Remote address of the device from where
1567  *                          data is received.
1568  * @param[in] data          Actual data recevied from the remote
1569  *                          device.
1570  * @param[in] dataLength    Length of the data received from the
1571  *                          remote device.
1572  * @param[in] sentLength    Length of the data sent from the remote
1573  *                          device.
1574  *
1575  * @return ::CA_STATUS_OK or Appropriate error code.
1576  * @retval ::CA_STATUS_OK  Successful.
1577  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
1578  * @retval ::CA_STATUS_FAILED Operation failed.
1579  */
1580 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
1581                                                 const uint8_t *data,
1582                                                 uint32_t dataLength,
1583                                                 uint32_t *sentLength);
1584
1585 /**
1586  * Set the NetworkPacket received callback to CA layer from adapter
1587  * layer.
1588  *
1589  * @param[in] callback Callback handle sent from the upper layer.
1590  */
1591 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
1592
1593 /**
1594  * Push the data from CA layer to the Sender processor queue.
1595  *
1596  * @param[in] remoteEndpoint Remote endpoint information of the
1597  *                           server.
1598  * @param[in] data           Data to be transmitted from LE.
1599  * @param[in] dataLen        Length of the Data being transmitted.
1600  *
1601  * @return ::CA_STATUS_OK or Appropriate error code.
1602  * @retval ::CA_STATUS_OK  Successful.
1603  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
1604  * @retval ::CA_STATUS_FAILED Operation failed.
1605  */
1606 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
1607                                             const uint8_t *data,
1608                                             uint32_t dataLen);
1609
1610 /**
1611  * Push the data from CA layer to the Sender processor queue.
1612  *
1613  * @param[in] remoteEndpoint Remote endpoint information of the
1614  *                           server.
1615  * @param[in] data           Data to be transmitted from LE.
1616  * @param[in] dataLen        Length of the Data being transmitted.
1617  *
1618  * @return ::CA_STATUS_OK or Appropriate error code.
1619  * @retval ::CA_STATUS_OK  Successful.
1620  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
1621  * @retval ::CA_STATUS_FAILED Operation failed.
1622  */
1623 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
1624                                             const uint8_t *data,
1625                                             uint32_t dataLen);
1626
1627 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
1628                           CANetworkPacketReceivedCallback reqRespCallback,
1629                           CANetworkChangeCallback netCallback,
1630                           CAErrorHandleCallback errorCallback,
1631                           ca_thread_pool_t handle)
1632 {
1633     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1634
1635     //Input validation
1636     VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null");
1637     VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null");
1638     VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null");
1639
1640     CAResult_t result = CA_STATUS_OK;
1641     result = CAInitLEAdapterMutex();
1642     if (CA_STATUS_OK != result)
1643     {
1644         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
1645         return CA_STATUS_FAILED;
1646     }
1647
1648     result = CAInitializeLENetworkMonitor();
1649     if (CA_STATUS_OK != result)
1650     {
1651         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
1652         return CA_STATUS_FAILED;
1653     }
1654
1655     CAInitializeLEAdapter();
1656
1657     CASetLEClientThreadPoolHandle(handle);
1658
1659     result = CAInitializeLEGattClient();
1660     if (CA_STATUS_OK != result)
1661     {
1662         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattClient() failed");
1663         return CA_STATUS_FAILED;
1664     }
1665
1666     CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
1667     CASetLEServerThreadPoolHandle(handle);
1668     result = CAInitializeLEGattServer();
1669     if (CA_STATUS_OK != result)
1670     {
1671         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattServer() failed");
1672         return CA_STATUS_FAILED;
1673     }
1674
1675     CASetLEAdapterThreadPoolHandle(handle);
1676     CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
1677     CASetLEReqRespAdapterCallback(reqRespCallback);
1678
1679     CASetBLEClientErrorHandleCallback(CALEErrorHandler);
1680     CASetBLEServerErrorHandleCallback(CALEErrorHandler);
1681     CALERegisterNetworkNotifications(netCallback);
1682
1683     g_errorHandler = errorCallback;
1684
1685     static const CAConnectivityHandler_t connHandler =
1686         {
1687             .startAdapter = CAStartLE,
1688             .stopAdapter = CAStopLE,
1689             .startListenServer = CAStartLEListeningServer,
1690             .stopListenServer = CAStopLEListeningServer,
1691             .startDiscoveryServer = CAStartLEDiscoveryServer,
1692             .sendData = CASendLEUnicastData,
1693             .sendDataToAll = CASendLEMulticastData,
1694             .GetnetInfo = CAGetLEInterfaceInformation,
1695             .readData = CAReadLEData,
1696             .terminate = CATerminateLE
1697         };
1698
1699     registerCallback(connHandler, CA_ADAPTER_GATT_BTLE);
1700
1701     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1702
1703     return CA_STATUS_OK;
1704 }
1705
1706 static CAResult_t CAStartLE()
1707 {
1708     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAStartLE");
1709
1710     return CAStartLEAdapter();
1711 }
1712
1713 static CAResult_t CAStopLE()
1714 {
1715     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1716 #ifndef SINGLE_THREAD
1717     CAStopLEQueues();
1718 #endif
1719
1720     ca_mutex_lock(g_bleIsServerMutex);
1721     if (true == g_isServer)
1722     {
1723         CAStopLEGattServer();
1724     }
1725     else
1726     {
1727         CAStopLEGattClient();
1728     }
1729     ca_mutex_unlock(g_bleIsServerMutex);
1730
1731     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1732
1733     return CA_STATUS_OK;
1734 }
1735
1736 static void CATerminateLE()
1737 {
1738     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1739
1740     CASetLEReqRespServerCallback(NULL);
1741     CASetLEReqRespClientCallback(NULL);
1742     CALERegisterNetworkNotifications(NULL);
1743     CASetLEReqRespAdapterCallback(NULL);
1744     CATerminateLENetworkMonitor();
1745
1746     ca_mutex_lock(g_bleIsServerMutex);
1747     if (true == g_isServer)
1748     {
1749         CATerminateLEGattServer();
1750     }
1751     else
1752     {
1753         CATerminateLEGattClient();
1754     }
1755     ca_mutex_unlock(g_bleIsServerMutex);
1756
1757 #ifndef SINGLE_THREAD
1758     CATerminateLEQueues();
1759 #endif
1760     CATerminateLEAdapterMutex();
1761
1762     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1763 }
1764
1765 static CAResult_t CAStartLEListeningServer()
1766 {
1767     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1768 #ifndef ROUTING_GATEWAY
1769     CAResult_t result = CA_STATUS_OK;
1770 #ifndef SINGLE_THREAD
1771     result = CAInitLEServerQueues();
1772     if (CA_STATUS_OK != result)
1773     {
1774         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
1775         return CA_STATUS_FAILED;
1776     }
1777 #endif
1778
1779     result = CAGetLEAdapterState();
1780     if (CA_ADAPTER_NOT_ENABLED == result)
1781     {
1782         gLeServerStatus = CA_LISTENING_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     result = CAStartLEGattServer();
1794
1795     ca_mutex_lock(g_bleIsServerMutex);
1796     g_isServer = true;
1797     ca_mutex_unlock(g_bleIsServerMutex);
1798
1799     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1800     return result;
1801 #else
1802     // Routing Gateway only supports BLE client mode.
1803     OIC_LOG(ERROR, CALEADAPTER_TAG, "LE server not supported in Routing Gateway");
1804     return CA_NOT_SUPPORTED;
1805 #endif
1806 }
1807
1808 static CAResult_t CAStopLEListeningServer()
1809 {
1810     OIC_LOG(ERROR, CALEADAPTER_TAG, "Listen server stop not supported.");
1811     return CA_NOT_SUPPORTED;
1812 }
1813
1814 static CAResult_t CAStartLEDiscoveryServer()
1815 {
1816     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1817     CAResult_t result = CA_STATUS_OK;
1818 #ifndef SINGLE_THREAD
1819     result = CAInitLEClientQueues();
1820     if (CA_STATUS_OK != result)
1821     {
1822         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
1823         return CA_STATUS_FAILED;
1824     }
1825 #endif
1826     result = CAGetLEAdapterState();
1827     if (CA_ADAPTER_NOT_ENABLED == result)
1828     {
1829         gLeServerStatus = CA_DISCOVERY_SERVER;
1830         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
1831         return CA_STATUS_OK;
1832     }
1833
1834     if (CA_STATUS_FAILED == result)
1835     {
1836         OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
1837         return CA_STATUS_FAILED;
1838     }
1839
1840     result = CAStartLEGattClient();
1841
1842     ca_mutex_lock(g_bleIsServerMutex);
1843     g_isServer = false;
1844     ca_mutex_unlock(g_bleIsServerMutex);
1845
1846     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1847     return result;
1848 }
1849
1850 static CAResult_t CAReadLEData()
1851 {
1852     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1853 #ifdef SINGLE_THREAD
1854     CACheckLEData();
1855 #endif
1856     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1857     return CA_STATUS_OK;
1858 }
1859
1860 static int32_t CASendLEUnicastData(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(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
1868     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
1869
1870     CAResult_t result = CA_STATUS_FAILED;
1871
1872     ca_mutex_lock(g_bleIsServerMutex);
1873     if (true  == g_isServer)
1874     {
1875         result = CALEAdapterServerSendData(endpoint, data, dataLen);
1876         if (CA_STATUS_OK != result)
1877         {
1878             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data failed\n");
1879             if (g_errorHandler)
1880             {
1881                 g_errorHandler(endpoint, data, dataLen, result);
1882             }
1883             ca_mutex_unlock(g_bleIsServerMutex);
1884             return -1;
1885         }
1886     }
1887     else
1888     {
1889         result = CALEAdapterClientSendData(endpoint, data, dataLen);
1890         if (CA_STATUS_OK != result)
1891         {
1892             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data failed \n");
1893             if (g_errorHandler)
1894             {
1895                 g_errorHandler(endpoint, data, dataLen, result);
1896             }
1897             ca_mutex_unlock(g_bleIsServerMutex);
1898             return -1;
1899         }
1900     }
1901     ca_mutex_unlock(g_bleIsServerMutex);
1902
1903     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1904     return dataLen;
1905 }
1906
1907 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
1908                                      const void *data,
1909                                      uint32_t dataLen)
1910 {
1911     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1912
1913     //Input validation
1914     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
1915
1916     if (0 >= dataLen)
1917     {
1918         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
1919         return -1;
1920     }
1921
1922     CAResult_t result = CA_STATUS_FAILED;
1923
1924     ca_mutex_lock(g_bleIsServerMutex);
1925     if (true  == g_isServer)
1926     {
1927         result = CALEAdapterServerSendData(NULL, data, dataLen);
1928         if (CA_STATUS_OK != result)
1929         {
1930             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data failed" );
1931
1932             ca_mutex_unlock(g_bleIsServerMutex);
1933             if (g_errorHandler)
1934             {
1935                 g_errorHandler(endpoint, data, dataLen, result);
1936             }
1937             return -1;
1938         }
1939     }
1940     else
1941     {
1942         result = CALEAdapterClientSendData(NULL, data, dataLen);
1943         if (CA_STATUS_OK != result)
1944         {
1945             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data failed" );
1946             if (g_errorHandler)
1947             {
1948                 g_errorHandler(endpoint, data, dataLen, result);
1949             }
1950             ca_mutex_unlock(g_bleIsServerMutex);
1951             return -1;
1952         }
1953     }
1954     ca_mutex_unlock(g_bleIsServerMutex);
1955
1956     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1957     return dataLen;
1958 }
1959
1960 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1961 {
1962     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1963
1964     VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
1965
1966     char *local_address = NULL;
1967
1968     CAResult_t res = CAGetLEAddress(&local_address);
1969     if (CA_STATUS_OK != res)
1970     {
1971         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
1972         return res;
1973     }
1974
1975     if (NULL == local_address)
1976     {
1977         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
1978         return CA_STATUS_FAILED;
1979     }
1980
1981     *size = 0;
1982     (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
1983     if (NULL == (*info))
1984     {
1985         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
1986         OICFree(local_address);
1987         return CA_STATUS_FAILED;
1988     }
1989
1990     size_t local_address_len = strlen(local_address);
1991
1992     if(local_address_len >= sizeof(g_localBLEAddress) ||
1993             local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
1994     {
1995         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
1996         OICFree(*info);
1997         OICFree(local_address);
1998         return CA_STATUS_FAILED;
1999     }
2000
2001     OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
2002     ca_mutex_lock(g_bleLocalAddressMutex);
2003     OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
2004     ca_mutex_unlock(g_bleLocalAddressMutex);
2005
2006     (*info)->adapter = CA_ADAPTER_GATT_BTLE;
2007     *size = 1;
2008     OICFree(local_address);
2009
2010     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2011     return CA_STATUS_OK;
2012 }
2013
2014 static CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback)
2015 {
2016     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2017
2018     ca_mutex_lock(g_bleNetworkCbMutex);
2019     g_networkCallback = netCallback;
2020     ca_mutex_unlock(g_bleNetworkCbMutex);
2021     CAResult_t res = CA_STATUS_OK;
2022     if (netCallback)
2023     {
2024         res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
2025         if (CA_STATUS_OK != res)
2026         {
2027             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
2028         }
2029     }
2030     else
2031     {
2032         res = CAUnSetLEAdapterStateChangedCb();
2033         if (CA_STATUS_OK != res)
2034         {
2035             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
2036         }
2037     }
2038
2039     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2040     return res;
2041 }
2042
2043 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
2044 {
2045     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2046
2047     VERIFY_NON_NULL_VOID(g_localBLEAddress, CALEADAPTER_TAG, "g_localBLEAddress is null");
2048     CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE };
2049
2050     ca_mutex_lock(g_bleLocalAddressMutex);
2051     OICStrcpy(localEndpoint.addr,
2052               sizeof(localEndpoint.addr),
2053               g_localBLEAddress);
2054     ca_mutex_unlock(g_bleLocalAddressMutex);
2055
2056     g_bleAdapterState = adapter_state;
2057     // Start a GattServer/Client if gLeServerStatus is SET
2058     if (CA_LISTENING_SERVER == gLeServerStatus)
2059     {
2060         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartLEGattServer");
2061         CAStartLEGattServer();
2062     }
2063     else if (CA_DISCOVERY_SERVER == gLeServerStatus)
2064     {
2065         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartBleGattClient");
2066         CAStartLEGattClient();
2067     }
2068     gLeServerStatus = CA_SERVER_NOTSTARTED;
2069
2070     ca_mutex_lock(g_bleNetworkCbMutex);
2071     if (NULL != g_networkCallback)
2072     {
2073         g_networkCallback(&localEndpoint, adapter_state);
2074     }
2075     else
2076     {
2077         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
2078     }
2079     ca_mutex_unlock(g_bleNetworkCbMutex);
2080
2081     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2082 }
2083
2084 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
2085                                             const uint8_t *data,
2086                                             uint32_t dataLen)
2087 {
2088     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2089
2090     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
2091 #ifndef SINGLE_THREAD
2092     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
2093                         "g_bleClientSendQueueHandle is  NULL",
2094                         CA_STATUS_FAILED);
2095     VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
2096                         "g_bleClientSendDataMutex is NULL",
2097                         CA_STATUS_FAILED);
2098
2099     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG, "g_bleClientSendQueueHandle",
2100                         CA_STATUS_FAILED);
2101
2102     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%u]", dataLen);
2103
2104     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen);
2105     if (!bleData)
2106     {
2107         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2108         return CA_MEMORY_ALLOC_FAILED;
2109     }
2110     // Add message to send queue
2111     ca_mutex_lock(g_bleClientSendDataMutex);
2112     CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData, sizeof(CALEData_t));
2113     ca_mutex_unlock(g_bleClientSendDataMutex);
2114 #endif
2115     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2116     return CA_STATUS_OK;
2117 }
2118
2119 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
2120                                             const uint8_t *data,
2121                                             uint32_t dataLen)
2122 {
2123     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2124
2125     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
2126
2127 #ifdef SINGLE_THREAD
2128     uint8_t header[CA_HEADER_LENGTH] = { 0 };
2129
2130     CAResult_t result =
2131         CAGenerateHeader(header, CA_HEADER_LENGTH, dataLen);
2132
2133     if (CA_STATUS_OK != result)
2134     {
2135         OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
2136         return CA_STATUS_FAILED;
2137     }
2138
2139     if (!CAIsLEConnected())
2140     {
2141         OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
2142         return CA_STATUS_FAILED;
2143     }
2144
2145     result = CAUpdateCharacteristicsToAllGattClients(header, CA_HEADER_LENGTH);
2146     if (CA_STATUS_OK != result)
2147     {
2148         OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2149         return CA_STATUS_FAILED;
2150     }
2151
2152     const uint32_t dataLimit = dataLen / CA_SUPPORTED_BLE_MTU_SIZE;
2153     for (uint32_t iter = 0; iter < dataLimit; iter++)
2154     {
2155         result =
2156             CAUpdateCharacteristicsToAllGattClients(
2157                 data + (iter * CA_SUPPORTED_BLE_MTU_SIZE),
2158                 CA_SUPPORTED_BLE_MTU_SIZE);
2159
2160         if (CA_STATUS_OK != result)
2161         {
2162             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2163             return CA_STATUS_FAILED;
2164         }
2165
2166         CALEDoEvents();
2167     }
2168
2169     const uint32_t remainingLen = dataLen % CA_SUPPORTED_BLE_MTU_SIZE;
2170     if (remainingLen)
2171     {
2172         result =
2173             CAUpdateCharacteristicsToAllGattClients(
2174                 data + (dataLimit * CA_SUPPORTED_BLE_MTU_SIZE),
2175                 remainingLen);
2176         if (CA_STATUS_OK != result)
2177         {
2178             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2179             return CA_STATUS_FAILED;
2180         }
2181         CALEDoEvents();
2182     }
2183 #else
2184     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
2185                         "BleClientReceiverQueue is NULL",
2186                         CA_STATUS_FAILED);
2187     VERIFY_NON_NULL_RET(g_bleServerSendDataMutex, CALEADAPTER_TAG,
2188                         "BleClientSendDataMutex is NULL",
2189                         CA_STATUS_FAILED);
2190
2191     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG, "sendQueueHandle",
2192                         CA_STATUS_FAILED);
2193
2194     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
2195
2196     CALEData_t * const bleData =
2197         CACreateLEData(remoteEndpoint, data, dataLen);
2198
2199     if (!bleData)
2200     {
2201         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2202         return CA_MEMORY_ALLOC_FAILED;
2203     }
2204
2205     // Add message to send queue
2206     ca_mutex_lock(g_bleServerSendDataMutex);
2207     CAQueueingThreadAddData(g_bleServerSendQueueHandle,
2208                             bleData,
2209                             sizeof(CALEData_t));
2210     ca_mutex_unlock(g_bleServerSendDataMutex);
2211 #endif
2212     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2213     return CA_STATUS_OK;
2214 }
2215
2216 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
2217                                                 const uint8_t *data,
2218                                                 uint32_t dataLength,
2219                                                 uint32_t *sentLength)
2220 {
2221     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2222
2223     //Input validation
2224     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
2225     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
2226
2227 #ifdef SINGLE_THREAD
2228     if(g_networkPacketReceivedCallback)
2229     {
2230         // will be filled by upper layer
2231         const CASecureEndpoint_t endpoint =
2232             { .endpoint = { .adapter = CA_ADAPTER_GATT_BTLE } };
2233
2234
2235         g_networkPacketReceivedCallback(&endpoint, data, dataLength);
2236     }
2237 #else
2238     VERIFY_NON_NULL_RET(g_bleReceiverQueue,
2239                         CALEADAPTER_TAG,
2240                         "g_bleReceiverQueue",
2241                         CA_STATUS_FAILED);
2242
2243     //Add message to data queue
2244     CAEndpoint_t * const remoteEndpoint =
2245         CACreateEndpointObject(CA_DEFAULT_FLAGS,
2246                                CA_ADAPTER_GATT_BTLE,
2247                                remoteAddress,
2248                                0);
2249
2250     if (NULL == remoteEndpoint)
2251     {
2252         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
2253         return CA_STATUS_FAILED;
2254     }
2255
2256     // Create bleData to add to queue
2257     OIC_LOG_V(DEBUG,
2258               CALEADAPTER_TAG,
2259               "Data received from LE layer [%d]",
2260               dataLength);
2261
2262     CALEData_t * const bleData =
2263         CACreateLEData(remoteEndpoint, data, dataLength);
2264
2265     if (!bleData)
2266     {
2267         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2268         CAFreeEndpoint(remoteEndpoint);
2269         return CA_MEMORY_ALLOC_FAILED;
2270     }
2271
2272     CAFreeEndpoint(remoteEndpoint);
2273     // Add message to receiver queue
2274     CAQueueingThreadAddData(g_bleReceiverQueue, bleData, sizeof(CALEData_t));
2275
2276     *sentLength = dataLength;
2277 #endif
2278     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2279     return CA_STATUS_OK;
2280 }
2281
2282 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
2283                                                 const uint8_t *data,
2284                                                 uint32_t dataLength,
2285                                                 uint32_t *sentLength)
2286 {
2287     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2288
2289     //Input validation
2290     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
2291     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
2292 #ifndef SINGLE_THREAD
2293     VERIFY_NON_NULL_RET(g_bleReceiverQueue, CALEADAPTER_TAG, "g_bleReceiverQueue",
2294                         CA_STATUS_FAILED);
2295
2296     //Add message to data queue
2297     CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
2298                                                           CA_ADAPTER_GATT_BTLE,
2299                                                           remoteAddress, 0);
2300     if (NULL == remoteEndpoint)
2301     {
2302         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
2303         return CA_STATUS_FAILED;
2304     }
2305
2306     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%u]", dataLength);
2307
2308     // Create bleData to add to queue
2309     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLength);
2310     if (!bleData)
2311     {
2312         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2313         CAFreeEndpoint(remoteEndpoint);
2314         return CA_MEMORY_ALLOC_FAILED;
2315     }
2316
2317     CAFreeEndpoint(remoteEndpoint);
2318     // Add message to receiver queue
2319     CAQueueingThreadAddData(g_bleReceiverQueue, bleData, sizeof(CALEData_t));
2320
2321     *sentLength = dataLength;
2322 #endif
2323     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2324     return CA_STATUS_OK;
2325 }
2326
2327 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
2328 {
2329     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2330
2331     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
2332     g_bleAdapterThreadPool = handle;
2333     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
2334
2335     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2336 }
2337
2338 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
2339 {
2340     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2341
2342     ca_mutex_lock(g_bleAdapterReqRespCbMutex);
2343
2344     g_networkPacketReceivedCallback = callback;
2345
2346     ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
2347
2348     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2349 }
2350
2351 static void CALEErrorHandler(const char *remoteAddress,
2352                              const uint8_t *data,
2353                              uint32_t dataLen,
2354                              CAResult_t result)
2355 {
2356     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler IN");
2357
2358     VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
2359
2360     CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS,
2361                                                CA_ADAPTER_GATT_BTLE,
2362                                                remoteAddress,
2363                                                0);
2364
2365     // if required, will be used to build remote endpoint
2366     g_errorHandler(rep, data, dataLen, result);
2367
2368     CAFreeEndpoint(rep);
2369
2370     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler OUT");
2371 }