Merge branch 'master' into simulator
[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     result = CAInitializeLENetworkMonitor();
1648     if (CA_STATUS_OK != result)
1649     {
1650         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
1651         return CA_STATUS_FAILED;
1652     }
1653
1654     CAInitializeLEAdapter();
1655
1656     CASetLEClientThreadPoolHandle(handle);
1657     CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
1658     CASetLEServerThreadPoolHandle(handle);
1659     CASetLEAdapterThreadPoolHandle(handle);
1660     CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
1661     CASetLEReqRespAdapterCallback(reqRespCallback);
1662
1663     CASetBLEClientErrorHandleCallback(CALEErrorHandler);
1664     CASetBLEServerErrorHandleCallback(CALEErrorHandler);
1665     CALERegisterNetworkNotifications(netCallback);
1666
1667     g_errorHandler = errorCallback;
1668
1669     static const CAConnectivityHandler_t connHandler =
1670         {
1671             .startAdapter = CAStartLE,
1672             .stopAdapter = CAStopLE,
1673             .startListenServer = CAStartLEListeningServer,
1674             .stopListenServer = CAStopLEListeningServer,
1675             .startDiscoveryServer = CAStartLEDiscoveryServer,
1676             .sendData = CASendLEUnicastData,
1677             .sendDataToAll = CASendLEMulticastData,
1678             .GetnetInfo = CAGetLEInterfaceInformation,
1679             .readData = CAReadLEData,
1680             .terminate = CATerminateLE
1681         };
1682
1683     registerCallback(connHandler, CA_ADAPTER_GATT_BTLE);
1684
1685     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1686
1687     return CA_STATUS_OK;
1688 }
1689
1690 static CAResult_t CAStartLE()
1691 {
1692     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAStartLE");
1693
1694     return CAStartLEAdapter();
1695 }
1696
1697 static CAResult_t CAStopLE()
1698 {
1699     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1700 #ifndef SINGLE_THREAD
1701     CAStopLEQueues();
1702 #endif
1703
1704     ca_mutex_lock(g_bleIsServerMutex);
1705     if (true == g_isServer)
1706     {
1707         CAStopLEGattServer();
1708     }
1709     else
1710     {
1711         CAStopLEGattClient();
1712     }
1713     ca_mutex_unlock(g_bleIsServerMutex);
1714
1715     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1716
1717     return CA_STATUS_OK;
1718 }
1719
1720 static void CATerminateLE()
1721 {
1722     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1723
1724     CASetLEReqRespServerCallback(NULL);
1725     CASetLEReqRespClientCallback(NULL);
1726     CALERegisterNetworkNotifications(NULL);
1727     CASetLEReqRespAdapterCallback(NULL);
1728     CATerminateLENetworkMonitor();
1729
1730     ca_mutex_lock(g_bleIsServerMutex);
1731     if (true == g_isServer)
1732     {
1733         CATerminateLEGattServer();
1734     }
1735     else
1736     {
1737         CATerminateLEGattClient();
1738     }
1739     ca_mutex_unlock(g_bleIsServerMutex);
1740
1741 #ifndef SINGLE_THREAD
1742     CATerminateLEQueues();
1743 #endif
1744     CATerminateLEAdapterMutex();
1745
1746     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1747 }
1748
1749 static CAResult_t CAStartLEListeningServer()
1750 {
1751     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1752 #ifndef ROUTING_GATEWAY
1753     CAResult_t result = CA_STATUS_OK;
1754 #ifndef SINGLE_THREAD
1755     result = CAInitLEServerQueues();
1756     if (CA_STATUS_OK != result)
1757     {
1758         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
1759         return CA_STATUS_FAILED;
1760     }
1761 #endif
1762
1763     result = CAGetLEAdapterState();
1764     if (CA_ADAPTER_NOT_ENABLED == result)
1765     {
1766         gLeServerStatus = CA_LISTENING_SERVER;
1767         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
1768         return CA_STATUS_OK;
1769     }
1770
1771     if (CA_STATUS_FAILED == result)
1772     {
1773         OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
1774         return CA_STATUS_FAILED;
1775     }
1776
1777     CAStartLEGattServer();
1778
1779     ca_mutex_lock(g_bleIsServerMutex);
1780     g_isServer = true;
1781     ca_mutex_unlock(g_bleIsServerMutex);
1782
1783     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1784     return CA_STATUS_OK;
1785 #else
1786     // Routing Gateway only supports BLE client mode.
1787     OIC_LOG(ERROR, CALEADAPTER_TAG, "LE server not supported in Routing Gateway");
1788     return CA_NOT_SUPPORTED;
1789 #endif
1790 }
1791
1792 static CAResult_t CAStopLEListeningServer()
1793 {
1794     OIC_LOG(ERROR, CALEADAPTER_TAG, "Listen server stop not supported.");
1795     return CA_NOT_SUPPORTED;
1796 }
1797
1798 static CAResult_t CAStartLEDiscoveryServer()
1799 {
1800     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1801     CAResult_t result = CA_STATUS_OK;
1802 #ifndef SINGLE_THREAD
1803     result = CAInitLEClientQueues();
1804     if (CA_STATUS_OK != result)
1805     {
1806         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
1807         return CA_STATUS_FAILED;
1808     }
1809 #endif
1810     result = CAGetLEAdapterState();
1811     if (CA_ADAPTER_NOT_ENABLED == result)
1812     {
1813         gLeServerStatus = CA_DISCOVERY_SERVER;
1814         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
1815         return CA_STATUS_OK;
1816     }
1817
1818     if (CA_STATUS_FAILED == result)
1819     {
1820         OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
1821         return CA_STATUS_FAILED;
1822     }
1823
1824     CAStartLEGattClient();
1825
1826     ca_mutex_lock(g_bleIsServerMutex);
1827     g_isServer = false;
1828     ca_mutex_unlock(g_bleIsServerMutex);
1829
1830     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1831     return CA_STATUS_OK;
1832 }
1833
1834 static CAResult_t CAReadLEData()
1835 {
1836     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1837 #ifdef SINGLE_THREAD
1838     CACheckLEData();
1839 #endif
1840     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1841     return CA_STATUS_OK;
1842 }
1843
1844 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
1845                                    const void *data,
1846                                    uint32_t dataLen)
1847 {
1848     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1849
1850     //Input validation
1851     VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
1852     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
1853
1854     CAResult_t result = CA_STATUS_FAILED;
1855
1856     ca_mutex_lock(g_bleIsServerMutex);
1857     if (true  == g_isServer)
1858     {
1859         result = CALEAdapterServerSendData(endpoint, data, dataLen);
1860         if (CA_STATUS_OK != result)
1861         {
1862             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data failed\n");
1863             if (g_errorHandler)
1864             {
1865                 g_errorHandler(endpoint, data, dataLen, result);
1866             }
1867             ca_mutex_unlock(g_bleIsServerMutex);
1868             return -1;
1869         }
1870     }
1871     else
1872     {
1873         result = CALEAdapterClientSendData(endpoint, data, dataLen);
1874         if (CA_STATUS_OK != result)
1875         {
1876             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data failed \n");
1877             if (g_errorHandler)
1878             {
1879                 g_errorHandler(endpoint, data, dataLen, result);
1880             }
1881             ca_mutex_unlock(g_bleIsServerMutex);
1882             return -1;
1883         }
1884     }
1885     ca_mutex_unlock(g_bleIsServerMutex);
1886
1887     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1888     return dataLen;
1889 }
1890
1891 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
1892                                      const void *data,
1893                                      uint32_t dataLen)
1894 {
1895     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1896
1897     //Input validation
1898     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
1899
1900     if (0 >= dataLen)
1901     {
1902         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
1903         return -1;
1904     }
1905
1906     CAResult_t result = CA_STATUS_FAILED;
1907
1908     ca_mutex_lock(g_bleIsServerMutex);
1909     if (true  == g_isServer)
1910     {
1911         result = CALEAdapterServerSendData(NULL, data, dataLen);
1912         if (CA_STATUS_OK != result)
1913         {
1914             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data failed" );
1915
1916             ca_mutex_unlock(g_bleIsServerMutex);
1917             if (g_errorHandler)
1918             {
1919                 g_errorHandler(endpoint, data, dataLen, result);
1920             }
1921             return -1;
1922         }
1923     }
1924     else
1925     {
1926         result = CALEAdapterClientSendData(NULL, data, dataLen);
1927         if (CA_STATUS_OK != result)
1928         {
1929             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data failed" );
1930             if (g_errorHandler)
1931             {
1932                 g_errorHandler(endpoint, data, dataLen, result);
1933             }
1934             ca_mutex_unlock(g_bleIsServerMutex);
1935             return -1;
1936         }
1937     }
1938     ca_mutex_unlock(g_bleIsServerMutex);
1939
1940     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1941     return dataLen;
1942 }
1943
1944 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1945 {
1946     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1947
1948     VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
1949
1950     char *local_address = NULL;
1951
1952     CAResult_t res = CAGetLEAddress(&local_address);
1953     if (CA_STATUS_OK != res)
1954     {
1955         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
1956         return res;
1957     }
1958
1959     if (NULL == local_address)
1960     {
1961         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
1962         return CA_STATUS_FAILED;
1963     }
1964
1965     *size = 0;
1966     (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
1967     if (NULL == (*info))
1968     {
1969         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
1970         OICFree(local_address);
1971         return CA_STATUS_FAILED;
1972     }
1973
1974     size_t local_address_len = strlen(local_address);
1975
1976     if(local_address_len >= sizeof(g_localBLEAddress) ||
1977             local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
1978     {
1979         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
1980         OICFree(*info);
1981         OICFree(local_address);
1982         return CA_STATUS_FAILED;
1983     }
1984
1985     OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
1986     ca_mutex_lock(g_bleLocalAddressMutex);
1987     OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
1988     ca_mutex_unlock(g_bleLocalAddressMutex);
1989
1990     (*info)->adapter = CA_ADAPTER_GATT_BTLE;
1991     *size = 1;
1992     OICFree(local_address);
1993
1994     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1995     return CA_STATUS_OK;
1996 }
1997
1998 static CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback)
1999 {
2000     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2001
2002     ca_mutex_lock(g_bleNetworkCbMutex);
2003     g_networkCallback = netCallback;
2004     ca_mutex_unlock(g_bleNetworkCbMutex);
2005     CAResult_t res = CA_STATUS_OK;
2006     if (netCallback)
2007     {
2008         res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
2009         if (CA_STATUS_OK != res)
2010         {
2011             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
2012         }
2013     }
2014     else
2015     {
2016         res = CAUnSetLEAdapterStateChangedCb();
2017         if (CA_STATUS_OK != res)
2018         {
2019             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
2020         }
2021     }
2022
2023     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2024     return res;
2025 }
2026
2027 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
2028 {
2029     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2030
2031     VERIFY_NON_NULL_VOID(g_localBLEAddress, CALEADAPTER_TAG, "g_localBLEAddress is null");
2032     CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE };
2033
2034     ca_mutex_lock(g_bleLocalAddressMutex);
2035     OICStrcpy(localEndpoint.addr,
2036               sizeof(localEndpoint.addr),
2037               g_localBLEAddress);
2038     ca_mutex_unlock(g_bleLocalAddressMutex);
2039
2040     g_bleAdapterState = adapter_state;
2041     // Start a GattServer/Client if gLeServerStatus is SET
2042     if (CA_LISTENING_SERVER == gLeServerStatus)
2043     {
2044         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartLEGattServer");
2045         CAStartLEGattServer();
2046     }
2047     else if (CA_DISCOVERY_SERVER == gLeServerStatus)
2048     {
2049         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartBleGattClient");
2050         CAStartLEGattClient();
2051     }
2052     gLeServerStatus = CA_SERVER_NOTSTARTED;
2053
2054     ca_mutex_lock(g_bleNetworkCbMutex);
2055     if (NULL != g_networkCallback)
2056     {
2057         g_networkCallback(&localEndpoint, adapter_state);
2058     }
2059     else
2060     {
2061         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
2062     }
2063     ca_mutex_unlock(g_bleNetworkCbMutex);
2064
2065     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2066 }
2067
2068 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
2069                                             const uint8_t *data,
2070                                             uint32_t dataLen)
2071 {
2072     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2073
2074     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
2075 #ifndef SINGLE_THREAD
2076     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
2077                         "g_bleClientSendQueueHandle is  NULL",
2078                         CA_STATUS_FAILED);
2079     VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
2080                         "g_bleClientSendDataMutex is NULL",
2081                         CA_STATUS_FAILED);
2082
2083     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG, "g_bleClientSendQueueHandle",
2084                         CA_STATUS_FAILED);
2085
2086     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%u]", dataLen);
2087
2088     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen);
2089     if (!bleData)
2090     {
2091         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2092         return CA_MEMORY_ALLOC_FAILED;
2093     }
2094     // Add message to send queue
2095     ca_mutex_lock(g_bleClientSendDataMutex);
2096     CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData, sizeof(CALEData_t));
2097     ca_mutex_unlock(g_bleClientSendDataMutex);
2098 #endif
2099     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2100     return CA_STATUS_OK;
2101 }
2102
2103 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
2104                                             const uint8_t *data,
2105                                             uint32_t dataLen)
2106 {
2107     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2108
2109     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
2110
2111 #ifdef SINGLE_THREAD
2112     uint8_t header[CA_HEADER_LENGTH] = { 0 };
2113
2114     CAResult_t result =
2115         CAGenerateHeader(header, CA_HEADER_LENGTH, dataLen);
2116
2117     if (CA_STATUS_OK != result)
2118     {
2119         OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
2120         return CA_STATUS_FAILED;
2121     }
2122
2123     if (!CAIsLEConnected())
2124     {
2125         OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
2126         return CA_STATUS_FAILED;
2127     }
2128
2129     result = CAUpdateCharacteristicsToAllGattClients(header, CA_HEADER_LENGTH);
2130     if (CA_STATUS_OK != result)
2131     {
2132         OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2133         return CA_STATUS_FAILED;
2134     }
2135
2136     const uint32_t dataLimit = dataLen / CA_SUPPORTED_BLE_MTU_SIZE;
2137     for (uint32_t iter = 0; iter < dataLimit; iter++)
2138     {
2139         result =
2140             CAUpdateCharacteristicsToAllGattClients(
2141                 data + (iter * CA_SUPPORTED_BLE_MTU_SIZE),
2142                 CA_SUPPORTED_BLE_MTU_SIZE);
2143
2144         if (CA_STATUS_OK != result)
2145         {
2146             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2147             return CA_STATUS_FAILED;
2148         }
2149
2150         CALEDoEvents();
2151     }
2152
2153     const uint32_t remainingLen = dataLen % CA_SUPPORTED_BLE_MTU_SIZE;
2154     if (remainingLen)
2155     {
2156         result =
2157             CAUpdateCharacteristicsToAllGattClients(
2158                 data + (dataLimit * CA_SUPPORTED_BLE_MTU_SIZE),
2159                 remainingLen);
2160         if (CA_STATUS_OK != result)
2161         {
2162             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2163             return CA_STATUS_FAILED;
2164         }
2165         CALEDoEvents();
2166     }
2167 #else
2168     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
2169                         "BleClientReceiverQueue is NULL",
2170                         CA_STATUS_FAILED);
2171     VERIFY_NON_NULL_RET(g_bleServerSendDataMutex, CALEADAPTER_TAG,
2172                         "BleClientSendDataMutex is NULL",
2173                         CA_STATUS_FAILED);
2174
2175     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG, "sendQueueHandle",
2176                         CA_STATUS_FAILED);
2177
2178     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
2179
2180     CALEData_t * const bleData =
2181         CACreateLEData(remoteEndpoint, data, dataLen);
2182
2183     if (!bleData)
2184     {
2185         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2186         return CA_MEMORY_ALLOC_FAILED;
2187     }
2188
2189     // Add message to send queue
2190     ca_mutex_lock(g_bleServerSendDataMutex);
2191     CAQueueingThreadAddData(g_bleServerSendQueueHandle,
2192                             bleData,
2193                             sizeof(CALEData_t));
2194     ca_mutex_unlock(g_bleServerSendDataMutex);
2195 #endif
2196     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2197     return CA_STATUS_OK;
2198 }
2199
2200 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
2201                                                 const uint8_t *data,
2202                                                 uint32_t dataLength,
2203                                                 uint32_t *sentLength)
2204 {
2205     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2206
2207     //Input validation
2208     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
2209     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
2210
2211 #ifdef SINGLE_THREAD
2212     if(g_networkPacketReceivedCallback)
2213     {
2214         // will be filled by upper layer
2215         const CASecureEndpoint_t endpoint =
2216             { .endpoint = { .adapter = CA_ADAPTER_GATT_BTLE } };
2217
2218
2219         g_networkPacketReceivedCallback(&endpoint, data, dataLength);
2220     }
2221 #else
2222     VERIFY_NON_NULL_RET(g_bleReceiverQueue,
2223                         CALEADAPTER_TAG,
2224                         "g_bleReceiverQueue",
2225                         CA_STATUS_FAILED);
2226
2227     //Add message to data queue
2228     CAEndpoint_t * const remoteEndpoint =
2229         CACreateEndpointObject(CA_DEFAULT_FLAGS,
2230                                CA_ADAPTER_GATT_BTLE,
2231                                remoteAddress,
2232                                0);
2233
2234     if (NULL == remoteEndpoint)
2235     {
2236         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
2237         return CA_STATUS_FAILED;
2238     }
2239
2240     // Create bleData to add to queue
2241     OIC_LOG_V(DEBUG,
2242               CALEADAPTER_TAG,
2243               "Data received from LE layer [%d]",
2244               dataLength);
2245
2246     CALEData_t * const bleData =
2247         CACreateLEData(remoteEndpoint, data, dataLength);
2248
2249     if (!bleData)
2250     {
2251         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2252         CAFreeEndpoint(remoteEndpoint);
2253         return CA_MEMORY_ALLOC_FAILED;
2254     }
2255
2256     CAFreeEndpoint(remoteEndpoint);
2257     // Add message to receiver queue
2258     CAQueueingThreadAddData(g_bleReceiverQueue, bleData, sizeof(CALEData_t));
2259
2260     *sentLength = dataLength;
2261 #endif
2262     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2263     return CA_STATUS_OK;
2264 }
2265
2266 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
2267                                                 const uint8_t *data,
2268                                                 uint32_t dataLength,
2269                                                 uint32_t *sentLength)
2270 {
2271     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2272
2273     //Input validation
2274     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
2275     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
2276 #ifndef SINGLE_THREAD
2277     VERIFY_NON_NULL_RET(g_bleReceiverQueue, CALEADAPTER_TAG, "g_bleReceiverQueue",
2278                         CA_STATUS_FAILED);
2279
2280     //Add message to data queue
2281     CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
2282                                                           CA_ADAPTER_GATT_BTLE,
2283                                                           remoteAddress, 0);
2284     if (NULL == remoteEndpoint)
2285     {
2286         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
2287         return CA_STATUS_FAILED;
2288     }
2289
2290     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%u]", dataLength);
2291
2292     // Create bleData to add to queue
2293     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLength);
2294     if (!bleData)
2295     {
2296         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2297         CAFreeEndpoint(remoteEndpoint);
2298         return CA_MEMORY_ALLOC_FAILED;
2299     }
2300
2301     CAFreeEndpoint(remoteEndpoint);
2302     // Add message to receiver queue
2303     CAQueueingThreadAddData(g_bleReceiverQueue, bleData, sizeof(CALEData_t));
2304
2305     *sentLength = dataLength;
2306 #endif
2307     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2308     return CA_STATUS_OK;
2309 }
2310
2311 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
2312 {
2313     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2314
2315     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
2316     g_bleAdapterThreadPool = handle;
2317     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
2318
2319     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2320 }
2321
2322 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
2323 {
2324     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2325
2326     ca_mutex_lock(g_bleAdapterReqRespCbMutex);
2327
2328     g_networkPacketReceivedCallback = callback;
2329
2330     ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
2331
2332     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2333 }
2334
2335 static void CALEErrorHandler(const char *remoteAddress,
2336                              const uint8_t *data,
2337                              uint32_t dataLen,
2338                              CAResult_t result)
2339 {
2340     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler IN");
2341
2342     VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
2343
2344     CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS,
2345                                                CA_ADAPTER_GATT_BTLE,
2346                                                remoteAddress,
2347                                                0);
2348
2349     // if required, will be used to build remote endpoint
2350     g_errorHandler(rep, data, dataLen, result);
2351
2352     CAFreeEndpoint(rep);
2353
2354     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler OUT");
2355 }