Merge "Merge branch 'master' into easysetup" into easysetup
[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 #include "pdu.h"
37
38 /**
39  * Logging tag for module name.
40  */
41 #define CALEADAPTER_TAG "OIC_LE_ADAP"
42
43 /**
44  * Stores information of all the senders.
45  *
46  * This structure will be used to track and defragment all incoming
47  * data packet.
48  */
49 typedef struct
50 {
51     uint32_t recvDataLen;
52     uint32_t totalDataLen;
53     uint8_t *defragData;
54     CAEndpoint_t *remoteEndpoint;
55  } CABLESenderInfo_t;
56
57 typedef enum
58 {
59     ADAPTER_EMPTY = 1,
60     ADAPTER_BOTH_CLIENT_SERVER,
61     ADAPTER_CLIENT,
62     ADAPTER_SERVER
63 } CABLEAdapter_t;
64
65 /**
66  * Callback to provide the status of the network change to CA layer.
67  */
68 static CANetworkChangeCallback g_networkCallback = NULL;
69
70 /**
71  * bleAddress of the local adapter. Value will be initialized to zero,
72  * and will be updated later.
73  */
74 static char g_localBLEAddress[18] = { 0 };
75
76 /**
77  * Variable to differentiate btw GattServer and GattClient.
78  */
79 static CABLEAdapter_t g_adapterType = ADAPTER_EMPTY;
80
81 /**
82  * Mutex to synchronize the task to be executed on the GattServer
83  * function calls.
84  */
85 static ca_mutex g_bleIsServerMutex = NULL;
86
87 /**
88  * Mutex to synchronize the callback to be called for the network
89  * changes.
90  */
91 static ca_mutex g_bleNetworkCbMutex = NULL;
92
93 /**
94  * Mutex to synchronize the updates of the local LE address of the
95  * adapter.
96  */
97 static ca_mutex g_bleLocalAddressMutex = NULL;
98
99 /**
100  * Reference to thread pool.
101  */
102 static ca_thread_pool_t g_bleAdapterThreadPool = NULL;
103
104 /**
105  * Mutex to synchronize the task to be pushed to thread pool.
106  */
107 static ca_mutex g_bleAdapterThreadPoolMutex = NULL;
108
109 /**
110  * Mutex to synchronize the queing of the data from SenderQueue.
111  */
112 static ca_mutex g_bleClientSendDataMutex = NULL;
113
114 /**
115  * Mutex to synchronize the queing of the data from ReceiverQueue.
116  */
117 static ca_mutex g_bleReceiveDataMutex = NULL;
118
119 /**
120  * Mutex to synchronize the queing of the data from SenderQueue.
121  */
122 static ca_mutex g_bleServerSendDataMutex = NULL;
123
124 /**
125  * Mutex to synchronize the callback to be called for the
126  * adapterReqResponse.
127  */
128 static ca_mutex g_bleAdapterReqRespCbMutex = NULL;
129
130 /**
131  * Callback to be called when network packet received from either
132  * GattServer or GattClient.
133  */
134 static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
135
136 /**
137  * Callback to notify error from the BLE adapter.
138  */
139 static CAErrorHandleCallback g_errorHandler = NULL;
140
141 /**
142  * Register network change notification callback.
143  *
144  * @param[in]  netCallback CANetworkChangeCallback callback which will
145  *                         be set for the change in network.
146  *
147  * @return  0 on success otherwise a positive error value.
148  * @retval  ::CA_STATUS_OK  Successful.
149  * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
150  * @retval  ::CA_STATUS_FAILED Operation failed.
151  *
152  */
153 static CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback);
154
155 /**
156  * Set the thread pool handle which is required for spawning new
157  * thread.
158  *
159  * @param[in] handle Thread pool handle which is given by above layer
160  *                   for using thread creation task.
161  *
162  */
163 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle);
164
165 /**
166  * Call the callback to the upper layer when the device state gets
167  * changed.
168  *
169  * @param[in] adapter_state New state of the adapter to be notified to
170  *                          the upper layer.
171  */
172 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state);
173
174 /**
175  * Used to initialize all required mutex variable for LE Adapter
176  * implementation.
177  *
178  * @return  0 on success otherwise a positive error value.
179  * @retval  ::CA_STATUS_OK  Successful.
180  * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
181  * @retval  ::CA_STATUS_FAILED Operation failed.
182  *
183  */
184 static CAResult_t CAInitLEAdapterMutex();
185
186 /**
187  * Terminate all required mutex variables for LE adapter
188  * implementation.
189  */
190 static void CATerminateLEAdapterMutex();
191
192 /**
193  * Prepares and notify error through error callback.
194  */
195 static void CALEErrorHandler(const char *remoteAddress,
196                              const uint8_t *data,
197                              uint32_t dataLen,
198                              CAResult_t result);
199
200 #ifndef SINGLE_THREAD
201 /**
202  * Stop condition of recvhandler.
203  */
204 static bool g_dataBleReceiverHandlerState = false;
205
206 /**
207  * Sender information.
208  */
209 static u_arraylist_t *g_bleServerSenderInfo = NULL;
210
211 static u_arraylist_t *g_bleClientSenderInfo = NULL;
212
213 /**
214  * Queue to process the outgoing packets from GATTClient.
215  */
216 static CAQueueingThread_t *g_bleClientSendQueueHandle = NULL;
217
218 /**
219  * Queue to process the incoming packets.
220  */
221 static CAQueueingThread_t *g_bleReceiverQueue = NULL;
222
223 /**
224  * Queue to process the outgoing packets from GATTServer.
225  */
226 static CAQueueingThread_t *g_bleServerSendQueueHandle = NULL;
227
228 /**
229  * This function will be associated with the sender queue for
230  * GattServer.
231  *
232  * This function will fragment the data to the MTU of the transport
233  * and send the data in fragments to the adapters. The function will
234  * be blocked until all data is sent out from the adapter.
235  *
236  * @param[in] threadData Data pushed to the queue which contains the
237  *                       info about RemoteEndpoint and Data.
238  */
239 static void CALEServerSendDataThread(void *threadData);
240
241 /**
242  * This function will be associated with the sender queue for
243  * GattClient.
244  *
245  * This function will fragment the data to the MTU of the transport
246  * and send the data in fragments to the adapters. The function will
247  * be blocked until all data is sent out from the adapter.
248  *
249  * @param[in] threadData Data pushed to the queue which contains the
250  *                       info about RemoteEndpoint and Data.
251  */
252 static void CALEClientSendDataThread(void *threadData);
253
254 /**
255  * This function will be associated with the receiver queue.
256  *
257  * This function will defragment the received data from each sender
258  * respectively and will send it up to CA layer.  Respective sender's
259  * header will provide the length of the data sent.
260  *
261  * @param[in] threadData Data pushed to the queue which contains the
262  *                       info about RemoteEndpoint and Data.
263  */
264 static void CALEDataReceiverHandler(void *threadData);
265
266 /**
267  * This function will stop all queues created for GattServer and
268  * GattClient. All four queues will be be stopped with this function
269  * invocations.
270  */
271 static void CAStopLEQueues();
272
273 /**
274  * This function will terminate all queues created for GattServer and
275  * GattClient. All four queues will be be terminated with this
276  * function invocations.
277  */
278 static void CATerminateLEQueues();
279
280 /**
281  * This function will initalize the Receiver and Sender queues for
282  * GattServer. This function will in turn call the functions
283  * CAInitBleServerReceiverQueue() and CAInitBleServerSenderQueue() to
284  * initialize the queues.
285  *
286  * @return ::CA_STATUS_OK or Appropriate error code.
287  * @retval ::CA_STATUS_OK  Successful.
288  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
289  * @retval ::CA_STATUS_FAILED Operation failed.
290  */
291 static CAResult_t CAInitLEServerQueues();
292
293 /**
294  * This function will initalize the Receiver and Sender queues for
295  * GattClient. This function will inturn call the functions
296  * CAInitBleClientReceiverQueue() and CAInitBleClientSenderQueue() to
297  * initialize the queues.
298  *
299  * @return ::CA_STATUS_OK or Appropriate error code.
300  * @retval ::CA_STATUS_OK  Successful.
301  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
302  * @retval ::CA_STATUS_FAILED Operation failed.
303  *
304  */
305 static CAResult_t CAInitLEClientQueues();
306
307 /**
308  * This function will initalize the Receiver queue for
309  * GattServer. This will initialize the queue to process the function
310  * CABLEServerSendDataThread() when ever the task is added to this
311  * queue.
312  *
313  * @return ::CA_STATUS_OK or Appropriate error code.
314  * @retval ::CA_STATUS_OK  Successful.
315  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
316  * @retval ::CA_STATUS_FAILED Operation failed.
317  */
318 static CAResult_t CAInitLEServerSenderQueue();
319
320 /**
321  * This function will initalize the Receiver queue for
322  * GattClient. This will initialize the queue to process the function
323  * CABLEClientSendDataThread() when ever the task is added to this
324  * queue.
325  *
326  * @return ::CA_STATUS_OK or Appropriate error code.
327  * @retval ::CA_STATUS_OK  Successful.
328  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
329  * @retval ::CA_STATUS_FAILED Operation failed.
330  */
331 static CAResult_t CAInitLEClientSenderQueue();
332
333 /**
334  * This function will initialize the Receiver queue for
335  * LEAdapter. This will initialize the queue to process the function
336  * CABLEDataReceiverHandler() when ever the task is added to this
337  * queue.
338  *
339  * @return ::CA_STATUS_OK or Appropriate error code
340  * @retval ::CA_STATUS_OK  Successful
341  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments
342  * @retval ::CA_STATUS_FAILED Operation failed
343  *
344  */
345 static CAResult_t CAInitLEReceiverQueue();
346
347 /**
348  * This function will create the Data required to send it in the
349  * queue.
350  *
351  * @param[in] remoteEndpoint Remote endpoint information of the
352  *                           server.
353  * @param[in] data           Data to be transmitted from LE.
354  * @param[in] dataLength     Length of the Data being transmitted.
355  *
356  * @return ::CA_STATUS_OK or Appropriate error code.
357  * @retval ::CA_STATUS_OK  Successful.
358  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
359  * @retval ::CA_STATUS_FAILED Operation failed.
360  */
361 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
362                                   const uint8_t *data,
363                                   uint32_t dataLength,
364                                   u_arraylist_t *senderInfo);
365
366 /**
367  * Used to free the BLE information stored in the sender/receiver
368  * queues.
369  *
370  * @param[in] bleData Information for a particular data segment.
371  */
372 static void CAFreeLEData(CALEData_t *bleData);
373
374 /**
375  * Free data.
376  */
377 static void CALEDataDestroyer(void *data, uint32_t size);
378
379 static CAResult_t CAInitLEServerQueues()
380 {
381     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
382
383     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
384
385     CAResult_t result = CAInitLEServerSenderQueue();
386     if (CA_STATUS_OK != result)
387     {
388         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerSenderQueue failed");
389         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
390         return CA_STATUS_FAILED;
391     }
392
393     g_bleServerSenderInfo = u_arraylist_create();
394     if (!g_bleServerSenderInfo)
395     {
396         OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
397         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
398         return CA_MEMORY_ALLOC_FAILED;
399     }
400
401     result = CAInitLEReceiverQueue();
402     if (CA_STATUS_OK != result)
403     {
404         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEReceiverQueue failed");
405         u_arraylist_free(&g_bleServerSenderInfo);
406         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
407         return CA_STATUS_FAILED;
408     }
409
410     g_dataBleReceiverHandlerState = true;
411
412     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
413
414     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
415     return CA_STATUS_OK;
416 }
417
418 static CAResult_t CAInitLEClientQueues()
419 {
420     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
421
422     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
423
424     CAResult_t result = CAInitLEClientSenderQueue();
425     if (CA_STATUS_OK != result)
426     {
427         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientSenderQueue failed");
428         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
429         return CA_STATUS_FAILED;
430     }
431
432     g_bleClientSenderInfo = u_arraylist_create();
433     if (!g_bleClientSenderInfo)
434     {
435         OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
436         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
437         return CA_MEMORY_ALLOC_FAILED;
438     }
439
440     result = CAInitLEReceiverQueue();
441     if (CA_STATUS_OK != result)
442     {
443         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEReceiverQueue failed");
444         u_arraylist_free(&g_bleClientSenderInfo);
445         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
446         return CA_STATUS_FAILED;
447     }
448
449     g_dataBleReceiverHandlerState = true;
450
451     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
452
453     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
454     return CA_STATUS_OK;
455 }
456
457 static CAResult_t CAInitLEReceiverQueue()
458 {
459     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAInitLEReceiverQueue");
460     // Check if the message queue is already initialized
461     if (g_bleReceiverQueue)
462     {
463         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
464         return CA_STATUS_OK;
465     }
466
467     // Create recv message queue
468     g_bleReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
469     if (!g_bleReceiverQueue)
470     {
471         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
472         return CA_MEMORY_ALLOC_FAILED;
473     }
474
475     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleReceiverQueue,
476                                                    g_bleAdapterThreadPool,
477                                                    CALEDataReceiverHandler,
478                                                    CALEDataDestroyer))
479     {
480         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
481         OICFree(g_bleReceiverQueue);
482         g_bleReceiverQueue = NULL;
483         return CA_STATUS_FAILED;
484     }
485
486     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleReceiverQueue))
487     {
488         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
489         OICFree(g_bleReceiverQueue);
490         g_bleReceiverQueue = NULL;
491         return CA_STATUS_FAILED;
492     }
493
494     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
495     return CA_STATUS_OK;
496 }
497
498 static CAResult_t CAInitLEServerSenderQueue()
499 {
500     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAInitLEServerSenderQueue");
501     // Check if the message queue is already initialized
502     if (g_bleServerSendQueueHandle)
503     {
504         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Queue is already initialized!");
505         return CA_STATUS_OK;
506     }
507
508     // Create send message queue
509     g_bleServerSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
510     if (!g_bleServerSendQueueHandle)
511     {
512         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
513         return CA_MEMORY_ALLOC_FAILED;
514     }
515
516     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerSendQueueHandle,
517                                                    g_bleAdapterThreadPool,
518                                                    CALEServerSendDataThread,
519                                                    CALEDataDestroyer))
520     {
521         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
522         OICFree(g_bleServerSendQueueHandle);
523         g_bleServerSendQueueHandle = NULL;
524         return CA_STATUS_FAILED;
525     }
526
527     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
528     return CA_STATUS_OK;
529 }
530
531 static void CALEClearSenderInfoImpl(u_arraylist_t ** list)
532 {
533     const size_t length = u_arraylist_length(*list);
534     for (size_t i = 0; i < length; ++i)
535     {
536         CABLESenderInfo_t * const info =
537                 (CABLESenderInfo_t *) u_arraylist_get(*list, i);
538         if (info)
539          {
540              OICFree(info->defragData);
541              CAFreeEndpoint(info->remoteEndpoint);
542              OICFree(info);
543          }
544     }
545     u_arraylist_free(list);
546 }
547
548 static void CALEClearSenderInfo()
549 {
550     CALEClearSenderInfoImpl(&g_bleServerSenderInfo);
551     CALEClearSenderInfoImpl(&g_bleClientSenderInfo);
552 }
553
554 static size_t CAGetMessageLengthFromData(const unsigned char *recvBuffer)
555 {
556     coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
557             ((unsigned char *)recvBuffer)[0] >> 4);
558     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
559                                                         transport);
560     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
561
562     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "option/paylaod length [%d]", optPaylaodLen);
563     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "header length [%d]", headerLen);
564     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "total data length [%d]", headerLen + optPaylaodLen);
565
566     return headerLen + optPaylaodLen;
567 }
568
569 static CAResult_t CAInitLEClientSenderQueue()
570 {
571     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAInitLEClientSenderQueue");
572
573     if (g_bleClientSendQueueHandle)
574     {
575         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
576         return CA_STATUS_OK;
577     }
578
579     // Create send message queue
580     g_bleClientSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
581     if (!g_bleClientSendQueueHandle)
582     {
583         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
584         return CA_MEMORY_ALLOC_FAILED;
585     }
586
587     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientSendQueueHandle,
588                                                    g_bleAdapterThreadPool,
589                                                    CALEClientSendDataThread, CALEDataDestroyer))
590     {
591         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
592         OICFree(g_bleClientSendQueueHandle);
593         g_bleClientSendQueueHandle = NULL;
594         return CA_STATUS_FAILED;
595     }
596
597     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CAInitLEClientSenderQueue");
598     return CA_STATUS_OK;
599 }
600
601 static void CAStopLEQueues()
602 {
603     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAStopLEQueues");
604
605     ca_mutex_lock(g_bleReceiveDataMutex);
606     if (NULL != g_bleReceiverQueue)
607     {
608         CAQueueingThreadStop(g_bleReceiverQueue);
609     }
610     ca_mutex_unlock(g_bleReceiveDataMutex);
611
612     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CAStopLEQueues");
613 }
614
615 static void CATerminateLEQueues()
616 {
617     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
618
619     CAQueueingThreadDestroy(g_bleClientSendQueueHandle);
620     OICFree(g_bleClientSendQueueHandle);
621     g_bleClientSendQueueHandle = NULL;
622
623     CAQueueingThreadDestroy(g_bleServerSendQueueHandle);
624     OICFree(g_bleServerSendQueueHandle);
625     g_bleServerSendQueueHandle = NULL;
626
627     CAQueueingThreadDestroy(g_bleReceiverQueue);
628     OICFree(g_bleReceiverQueue);
629     g_bleReceiverQueue = NULL;
630
631     CALEClearSenderInfo();
632
633     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
634 }
635
636 static CAResult_t CALEGetSenderInfo(const char *leAddress,
637                                     u_arraylist_t *senderInfoList,
638                                     CABLESenderInfo_t **senderInfo,
639                                     uint32_t *senderIndex)
640 {
641     VERIFY_NON_NULL_RET(leAddress,
642                         CALEADAPTER_TAG,
643                         "NULL BLE address argument",
644                         CA_STATUS_INVALID_PARAM);
645     VERIFY_NON_NULL_RET(senderIndex,
646                         CALEADAPTER_TAG,
647                         "NULL index argument",
648                         CA_STATUS_INVALID_PARAM);
649
650     const uint32_t listLength = u_arraylist_length(senderInfoList);
651     const uint32_t addrLength = strlen(leAddress);
652     for (uint32_t index = 0; index < listLength; index++)
653     {
654         CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
655         if(!info || !(info->remoteEndpoint))
656         {
657             continue;
658         }
659
660         if(!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
661         {
662             *senderIndex = index;
663             if(senderInfo)
664             {
665                 *senderInfo = info;
666             }
667             return CA_STATUS_OK;
668         }
669     }
670
671     return CA_STATUS_FAILED;
672 }
673
674 static void CALEDataReceiverHandler(void *threadData)
675 {
676     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEDataReceiverHandler");
677
678     ca_mutex_lock(g_bleReceiveDataMutex);
679
680     if (g_dataBleReceiverHandlerState)
681     {
682         OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
683
684         CALEData_t *bleData = (CALEData_t *) threadData;
685         if (!bleData)
686         {
687             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bleData!");
688             ca_mutex_unlock(g_bleReceiveDataMutex);
689             return;
690         }
691
692         if (!(bleData->senderInfo))
693         {
694             OIC_LOG(ERROR, CALEADAPTER_TAG, "sender info is not available");
695             ca_mutex_unlock(g_bleReceiveDataMutex);
696             return;
697         }
698
699         if (!(bleData->remoteEndpoint))
700         {
701             OIC_LOG(ERROR, CALEADAPTER_TAG, "Client RemoteEndPoint NULL!!");
702             ca_mutex_unlock(g_bleReceiveDataMutex);
703             return;
704         }
705
706         CABLESenderInfo_t *senderInfo = NULL;
707         uint32_t senderIndex = 0;
708
709         if(CA_STATUS_OK != CALEGetSenderInfo(bleData->remoteEndpoint->addr,
710                                              bleData->senderInfo,
711                                              &senderInfo, &senderIndex))
712         {
713             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This is a new client [%s]",
714                       bleData->remoteEndpoint->addr);
715         }
716
717         if(!senderInfo)
718         {
719             CABLESenderInfo_t *newSender = OICMalloc(sizeof(CABLESenderInfo_t));
720             if(!newSender)
721             {
722                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
723                 ca_mutex_unlock(g_bleReceiveDataMutex);
724                 return;
725             }
726             newSender->recvDataLen = 0;
727             newSender->totalDataLen = 0;
728             newSender->defragData = NULL;
729             newSender->remoteEndpoint = NULL;
730
731             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
732
733             newSender->totalDataLen = CAGetMessageLengthFromData(bleData->data);
734
735             if(!(newSender->totalDataLen))
736             {
737                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
738                 OICFree(newSender);
739                 ca_mutex_unlock(g_bleReceiveDataMutex);
740                 return;
741             }
742
743             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
744                       newSender->totalDataLen);
745             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%u] bytes",
746                       bleData->dataLen);
747
748             newSender->defragData = OICCalloc(newSender->totalDataLen + 1,
749                                               sizeof(*newSender->defragData));
750
751             if (NULL == newSender->defragData)
752             {
753                 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
754                 OICFree(newSender);
755                 ca_mutex_unlock(g_bleReceiveDataMutex);
756                 return;
757             }
758
759             const char *remoteAddress = bleData->remoteEndpoint->addr;
760             newSender->remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
761                                                                CA_ADAPTER_GATT_BTLE,
762                                                                remoteAddress,
763                                                                0);
764             if (NULL == newSender->remoteEndpoint)
765             {
766                 OIC_LOG(ERROR, CALEADAPTER_TAG, "remoteEndpoint is NULL!");
767                 OICFree(newSender->defragData);
768                 OICFree(newSender);
769                 ca_mutex_unlock(g_bleReceiveDataMutex);
770                 return;
771             }
772
773             if (newSender->recvDataLen + bleData->dataLen > newSender->totalDataLen)
774             {
775                 OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
776                 OICFree(newSender->defragData);
777                 CAFreeEndpoint(newSender->remoteEndpoint);
778                 OICFree(newSender);
779                 ca_mutex_unlock(g_bleReceiveDataMutex);
780                 return;
781             }
782             memcpy(newSender->defragData, bleData->data, bleData->dataLen);
783             newSender->recvDataLen += bleData->dataLen;
784
785             u_arraylist_add(bleData->senderInfo,(void *)newSender);
786
787             //Getting newSender index position in bleSenderInfo array list
788             if(CA_STATUS_OK !=
789                 CALEGetSenderInfo(newSender->remoteEndpoint->addr, bleData->senderInfo,
790                                   NULL, &senderIndex))
791             {
792                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Existing sender index not found!!");
793                 OICFree(newSender->defragData);
794                 CAFreeEndpoint(newSender->remoteEndpoint);
795                 OICFree(newSender);
796                 ca_mutex_unlock(g_bleReceiveDataMutex);
797                 return;
798             }
799             senderInfo = newSender;
800         }
801         else
802         {
803             if(senderInfo->recvDataLen + bleData->dataLen > senderInfo->totalDataLen)
804             {
805                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
806                           "Data Length exceeding error!! Receiving [%d] total length [%d]",
807                           senderInfo->recvDataLen + bleData->dataLen, senderInfo->totalDataLen);
808                 u_arraylist_remove(bleData->senderInfo, senderIndex);
809                 OICFree(senderInfo->defragData);
810                 OICFree(senderInfo);
811                 ca_mutex_unlock(g_bleReceiveDataMutex);
812                 return;
813             }
814             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]",
815                       bleData->dataLen);
816             memcpy(senderInfo->defragData + senderInfo->recvDataLen, bleData->data,
817                    bleData->dataLen);
818             senderInfo->recvDataLen += bleData->dataLen ;
819             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "totalDatalength  [%d] received Datalen [%d]",
820                                                 senderInfo->totalDataLen, senderInfo->recvDataLen);
821         }
822
823         if (senderInfo->totalDataLen == senderInfo->recvDataLen)
824         {
825             ca_mutex_lock(g_bleAdapterReqRespCbMutex);
826             if (NULL == g_networkPacketReceivedCallback)
827             {
828                 OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
829
830                 u_arraylist_remove(bleData->senderInfo, senderIndex);
831                 OICFree(senderInfo->defragData);
832                 OICFree(senderInfo);
833                 ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
834                 ca_mutex_unlock(g_bleReceiveDataMutex);
835                 return;
836             }
837
838             OIC_LOG(DEBUG, CALEADAPTER_TAG, "[CALEDataReceiverHandler] Sending data up !");
839
840             const CASecureEndpoint_t tmp =
841                 {
842                     .endpoint = *senderInfo->remoteEndpoint
843                 };
844
845             g_networkPacketReceivedCallback(&tmp,
846                                             senderInfo->defragData,
847                                             senderInfo->recvDataLen);
848             ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
849             u_arraylist_remove(bleData->senderInfo, senderIndex);
850             senderInfo->remoteEndpoint = NULL;
851             senderInfo->defragData = NULL;
852             OICFree(senderInfo);
853         }
854     }
855     ca_mutex_unlock(g_bleReceiveDataMutex);
856     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
857 }
858
859 static void CALEServerSendDataThread(void *threadData)
860 {
861     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEServerSendDataThread");
862
863     CALEData_t * const bleData = (CALEData_t *) threadData;
864     if (!bleData)
865     {
866         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
867         return;
868     }
869
870     const uint32_t totalLength = bleData->dataLen;
871
872     OIC_LOG_V(DEBUG,
873               CALEADAPTER_TAG,
874               "Server total Data length with header is [%u]",
875               totalLength);
876
877     uint8_t * const dataSegment = OICCalloc(totalLength, 1);
878
879     if (NULL == dataSegment)
880     {
881         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
882         return;
883     }
884
885     uint32_t length = 0;
886     if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
887     {
888         length = totalLength;
889         memcpy(dataSegment, bleData->data, bleData->dataLen);
890     }
891     else
892     {
893         length =  CA_SUPPORTED_BLE_MTU_SIZE;
894         memcpy(dataSegment, bleData->data, CA_SUPPORTED_BLE_MTU_SIZE);
895     }
896
897     uint32_t iter = totalLength / CA_SUPPORTED_BLE_MTU_SIZE;
898     uint32_t index = 0;
899     CAResult_t result = CA_STATUS_FAILED;
900
901     // Send the first segment with the header.
902     if (NULL != bleData->remoteEndpoint) // Sending Unicast Data
903     {
904         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Unicast Data");
905
906         result = CAUpdateCharacteristicsToGattClient(
907                     bleData->remoteEndpoint->addr, dataSegment, length);
908
909         if (CA_STATUS_OK != result)
910         {
911             OIC_LOG_V(ERROR,
912                       CALEADAPTER_TAG,
913                       "Update characteristics failed, result [%d]",
914                       result);
915
916             g_errorHandler(bleData->remoteEndpoint,
917                            bleData->data,
918                            bleData->dataLen,
919                            result);
920             OICFree(dataSegment);
921             return;
922         }
923
924         OIC_LOG_V(DEBUG,
925                   CALEADAPTER_TAG,
926                   "Server Sent data length [%u]",
927                   length);
928         for (index = 1; index < iter; index++)
929         {
930             // Send the remaining header.
931             OIC_LOG_V(DEBUG,
932                       CALEADAPTER_TAG,
933                       "Sending the chunk number [%u]",
934                       index);
935
936             result =
937                 CAUpdateCharacteristicsToGattClient(
938                     bleData->remoteEndpoint->addr,
939                     bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE)),
940                     CA_SUPPORTED_BLE_MTU_SIZE);
941
942             if (CA_STATUS_OK != result)
943             {
944                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
945                             "Update characteristics failed, result [%d]", result);
946                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
947                 OICFree(dataSegment);
948                 return;
949             }
950             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]",
951                                                CA_SUPPORTED_BLE_MTU_SIZE);
952         }
953
954         const uint32_t remainingLen =
955             totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
956
957         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
958         {
959             // send the last segment of the data (Ex: 22 bytes of 622
960             // bytes of data when MTU is 200)
961             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
962
963             result = CAUpdateCharacteristicsToGattClient(
964                          bleData->remoteEndpoint->addr,
965                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE),
966                          remainingLen);
967
968             if (CA_STATUS_OK != result)
969             {
970                 OIC_LOG_V(ERROR,
971                           CALEADAPTER_TAG,
972                           "Update characteristics failed, result [%d]",
973                           result);
974                 g_errorHandler(bleData->remoteEndpoint,
975                                bleData->data,
976                                bleData->dataLen,
977                                result);
978                 OICFree(dataSegment);
979                 return;
980             }
981             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", remainingLen);
982         }
983      }
984     else
985     {
986         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
987         result = CAUpdateCharacteristicsToAllGattClients(dataSegment, length);
988         if (CA_STATUS_OK != result)
989         {
990             OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
991                       result);
992             CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
993             OICFree(dataSegment);
994             return;
995         }
996         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
997         for (index = 1; index < iter; index++)
998         {
999             // Send the remaining header.
1000             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Sending the chunk number [%d]", index);
1001
1002             result = CAUpdateCharacteristicsToAllGattClients(
1003                          bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE)),
1004                          CA_SUPPORTED_BLE_MTU_SIZE);
1005
1006             if (CA_STATUS_OK != result)
1007             {
1008                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1009                           result);
1010                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1011                 OICFree(dataSegment);
1012                 return;
1013             }
1014             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%u]",
1015                       CA_SUPPORTED_BLE_MTU_SIZE);
1016         }
1017
1018         const uint32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
1019         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1020         {
1021             // send the last segment of the data
1022             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1023
1024             result = CAUpdateCharacteristicsToAllGattClients(
1025                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE),
1026                          remainingLen);
1027
1028             if (CA_STATUS_OK != result)
1029             {
1030                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1031                           result);
1032                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1033                 OICFree(dataSegment);
1034                 return;
1035             }
1036             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", remainingLen);
1037         }
1038     }
1039     OICFree(dataSegment);
1040
1041     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CALEServerSendDataThread");
1042 }
1043
1044 static void CALEClientSendDataThread(void *threadData)
1045 {
1046     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEClientSendDataThread");
1047
1048     CALEData_t *bleData = (CALEData_t *) threadData;
1049     if (!bleData)
1050     {
1051         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
1052         return;
1053     }
1054
1055     const uint32_t totalLength = bleData->dataLen;
1056
1057     uint8_t *dataSegment = OICCalloc(totalLength, 1);
1058     if (NULL == dataSegment)
1059     {
1060         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
1061         return;
1062     }
1063
1064     uint32_t length = 0;
1065     if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
1066     {
1067         length = totalLength;
1068         memcpy(dataSegment,
1069                bleData->data,
1070                bleData->dataLen);
1071     }
1072     else
1073     {
1074         length = CA_SUPPORTED_BLE_MTU_SIZE;
1075         memcpy(dataSegment,
1076                bleData->data,
1077                CA_SUPPORTED_BLE_MTU_SIZE);
1078     }
1079
1080     CAResult_t result = CA_STATUS_FAILED;
1081     const uint32_t iter = totalLength / CA_SUPPORTED_BLE_MTU_SIZE;
1082     uint32_t index = 0;
1083     if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
1084     {
1085         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
1086         // Send the first segment with the header.
1087         result =
1088             CAUpdateCharacteristicsToGattServer(
1089                 bleData->remoteEndpoint->addr,
1090                 dataSegment,
1091                 length,
1092                 LE_UNICAST,
1093                 0);
1094
1095         if (CA_STATUS_OK != result)
1096         {
1097             OIC_LOG_V(ERROR,
1098                       CALEADAPTER_TAG,
1099                       "Update characteristics failed, result [%d]",
1100                       result);
1101             g_errorHandler(bleData->remoteEndpoint,
1102                            bleData->data,
1103                            bleData->dataLen,
1104                            result);
1105             OICFree(dataSegment);
1106             return;
1107         }
1108
1109         OIC_LOG_V(DEBUG,
1110                   CALEADAPTER_TAG,
1111                   "Client Sent Data length  is [%u]",
1112                   length);
1113
1114         for (index = 1; index < iter; index++)
1115         {
1116             // Send the remaining header.
1117             result = CAUpdateCharacteristicsToGattServer(
1118                      bleData->remoteEndpoint->addr,
1119                      bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE),
1120                      CA_SUPPORTED_BLE_MTU_SIZE,
1121                      LE_UNICAST, 0);
1122
1123             if (CA_STATUS_OK != result)
1124             {
1125                 OIC_LOG_V(ERROR,
1126                           CALEADAPTER_TAG,
1127                           "Update characteristics failed, result [%d]",
1128                           result);
1129                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1130                 OICFree(dataSegment);
1131                 return;
1132             }
1133             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]",
1134                                                CA_SUPPORTED_BLE_MTU_SIZE);
1135         }
1136
1137         const uint32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
1138         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1139         {
1140             // send the last segment of the data (Ex: 22 bytes of 622
1141             // bytes of data when MTU is 200)
1142             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1143
1144             result = CAUpdateCharacteristicsToGattServer(
1145                      bleData->remoteEndpoint->addr,
1146                      bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE),
1147                      remainingLen,
1148                      LE_UNICAST, 0);
1149
1150             if (CA_STATUS_OK != result)
1151             {
1152                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1153                                                    result);
1154                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1155                 OICFree(dataSegment);
1156                 return;
1157             }
1158             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", remainingLen);
1159         }
1160     }
1161     else
1162     {
1163         //Sending Mulitcast Data
1164         // Send the first segment with the header.
1165         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Multicast Data");
1166         result = CAUpdateCharacteristicsToAllGattServers(dataSegment, length);
1167         if (CA_STATUS_OK != result)
1168         {
1169             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1170                       "Update characteristics (all) failed, result [%d]", result);
1171             CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1172             OICFree(dataSegment);
1173             return ;
1174         }
1175         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", length);
1176         // Send the remaining header.
1177         for (index = 1; index < iter; index++)
1178         {
1179             result = CAUpdateCharacteristicsToAllGattServers(
1180                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE),
1181                          CA_SUPPORTED_BLE_MTU_SIZE);
1182
1183             if (CA_STATUS_OK != result)
1184             {
1185                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1186                           result);
1187                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1188                 OICFree(dataSegment);
1189                 return;
1190             }
1191             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]",
1192                       CA_SUPPORTED_BLE_MTU_SIZE);
1193         }
1194
1195         uint32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
1196         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1197         {
1198             // send the last segment of the data (Ex: 22 bytes of 622
1199             // bytes of data when MTU is 200)
1200             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1201             result =
1202                 CAUpdateCharacteristicsToAllGattServers(
1203                     bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE),
1204                     remainingLen);
1205
1206             if (CA_STATUS_OK != result)
1207             {
1208                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1209                           "Update characteristics (all) failed, result [%d]", result);
1210                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1211                 OICFree(dataSegment);
1212                 return;
1213             }
1214             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", remainingLen);
1215         }
1216
1217     }
1218
1219     OICFree(dataSegment);
1220
1221     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CABLEClientSendDataThread");
1222 }
1223
1224 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
1225                                   const uint8_t *data,
1226                                   uint32_t dataLength,
1227                                   u_arraylist_t *senderInfo)
1228 {
1229     CALEData_t * const bleData = OICMalloc(sizeof(CALEData_t));
1230
1231     if (!bleData)
1232     {
1233         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1234         return NULL;
1235     }
1236
1237     bleData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
1238     bleData->data = OICCalloc(dataLength + 1, 1);
1239
1240     if (NULL == bleData->data)
1241     {
1242         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1243         CAFreeLEData(bleData);
1244         return NULL;
1245     }
1246
1247     memcpy(bleData->data, data, dataLength);
1248     bleData->dataLen = dataLength;
1249     if (senderInfo)
1250     {
1251         bleData->senderInfo = senderInfo;
1252     }
1253
1254     return bleData;
1255 }
1256
1257 static void CAFreeLEData(CALEData_t *bleData)
1258 {
1259     VERIFY_NON_NULL_VOID(bleData, CALEADAPTER_TAG, "Param bleData is NULL");
1260
1261     CAFreeEndpoint(bleData->remoteEndpoint);
1262     OICFree(bleData->data);
1263     OICFree(bleData);
1264 }
1265
1266 static void CALEDataDestroyer(void *data, uint32_t size)
1267 {
1268     if ((size_t)size < sizeof(CALEData_t *))
1269     {
1270         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1271                   "Destroy data too small %p %d", data, size);
1272     }
1273     CALEData_t *ledata = (CALEData_t *) data;
1274
1275     CAFreeLEData(ledata);
1276 }
1277 #endif
1278
1279 static CAResult_t CAInitLEAdapterMutex()
1280 {
1281     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAInitLEAdapterMutex");
1282
1283     if (NULL == g_bleIsServerMutex)
1284     {
1285         g_bleIsServerMutex = ca_mutex_new();
1286         if (NULL == g_bleIsServerMutex)
1287         {
1288             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1289             return CA_STATUS_FAILED;
1290         }
1291     }
1292
1293     if (NULL == g_bleNetworkCbMutex)
1294     {
1295         g_bleNetworkCbMutex = ca_mutex_new();
1296         if (NULL == g_bleNetworkCbMutex)
1297         {
1298             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1299             CATerminateLEAdapterMutex();
1300             return CA_STATUS_FAILED;
1301         }
1302     }
1303
1304     if (NULL == g_bleLocalAddressMutex)
1305     {
1306         g_bleLocalAddressMutex = ca_mutex_new();
1307         if (NULL == g_bleLocalAddressMutex)
1308         {
1309             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1310             CATerminateLEAdapterMutex();
1311             return CA_STATUS_FAILED;
1312         }
1313     }
1314
1315     if (NULL == g_bleAdapterThreadPoolMutex)
1316     {
1317         g_bleAdapterThreadPoolMutex = ca_mutex_new();
1318         if (NULL == g_bleAdapterThreadPoolMutex)
1319         {
1320             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1321             CATerminateLEAdapterMutex();
1322             return CA_STATUS_FAILED;
1323         }
1324     }
1325
1326     if (NULL == g_bleClientSendDataMutex)
1327     {
1328         g_bleClientSendDataMutex = ca_mutex_new();
1329         if (NULL == g_bleClientSendDataMutex)
1330         {
1331             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1332             CATerminateLEAdapterMutex();
1333             return CA_STATUS_FAILED;
1334         }
1335     }
1336
1337     if (NULL == g_bleServerSendDataMutex)
1338     {
1339         g_bleServerSendDataMutex = ca_mutex_new();
1340         if (NULL == g_bleServerSendDataMutex)
1341         {
1342             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1343             CATerminateLEAdapterMutex();
1344             return CA_STATUS_FAILED;
1345         }
1346     }
1347
1348     if (NULL == g_bleAdapterReqRespCbMutex)
1349     {
1350         g_bleAdapterReqRespCbMutex = ca_mutex_new();
1351         if (NULL == g_bleAdapterReqRespCbMutex)
1352         {
1353             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1354             CATerminateLEAdapterMutex();
1355             return CA_STATUS_FAILED;
1356         }
1357     }
1358
1359     if (NULL == g_bleReceiveDataMutex)
1360     {
1361         g_bleReceiveDataMutex = ca_mutex_new();
1362         if (NULL == g_bleReceiveDataMutex)
1363         {
1364             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1365             return CA_STATUS_FAILED;
1366         }
1367     }
1368
1369     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1370     return CA_STATUS_OK;
1371 }
1372
1373 static void CATerminateLEAdapterMutex()
1374 {
1375     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CATerminateLEAdapterMutex");
1376
1377     ca_mutex_free(g_bleIsServerMutex);
1378     g_bleIsServerMutex = NULL;
1379
1380     ca_mutex_free(g_bleNetworkCbMutex);
1381     g_bleNetworkCbMutex = NULL;
1382
1383     ca_mutex_free(g_bleLocalAddressMutex);
1384     g_bleLocalAddressMutex = NULL;
1385
1386     ca_mutex_free(g_bleAdapterThreadPoolMutex);
1387     g_bleAdapterThreadPoolMutex = NULL;
1388
1389     ca_mutex_free(g_bleClientSendDataMutex);
1390     g_bleClientSendDataMutex = NULL;
1391
1392     ca_mutex_free(g_bleServerSendDataMutex);
1393     g_bleServerSendDataMutex = NULL;
1394
1395     ca_mutex_free(g_bleAdapterReqRespCbMutex);
1396     g_bleAdapterReqRespCbMutex = NULL;
1397
1398     ca_mutex_free(g_bleReceiveDataMutex);
1399     g_bleReceiveDataMutex = NULL;
1400
1401     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1402 }
1403
1404 /**
1405  * Starting LE connectivity adapters.
1406  *
1407  * As its peer to peer it does not require to start any servers.
1408  *
1409  * @return ::CA_STATUS_OK or Appropriate error code.
1410  */
1411 static CAResult_t CAStartLE();
1412
1413 /**
1414  * Start listening server for receiving multicast search requests.
1415  *
1416  * Transport Specific Behavior:
1417  *   LE  Starts GATT Server with prefixed UUID and Characteristics
1418  *   per OIC Specification.
1419  * @return  ::CA_STATUS_OK or Appropriate error code.
1420  */
1421 static CAResult_t CAStartLEListeningServer();
1422
1423 /**
1424  * Stops listening server from receiving multicast search requests.
1425  *
1426  * Transport Specific Behavior:
1427  *   LE  Starts GATT Server with prefixed UUID and Characteristics
1428  *   per OIC Specification.
1429  * @return  ::CA_STATUS_OK or Appropriate error code.
1430  */
1431 static CAResult_t CAStopLEListeningServer();
1432
1433 /**
1434  * Sarting discovery of servers for receiving multicast
1435  * advertisements.
1436  *
1437  * Transport Specific Behavior:
1438  *   LE  Starts GATT Server with prefixed UUID and Characteristics
1439  *   per OIC Specification.
1440  *
1441  * @return ::CA_STATUS_OK or Appropriate error code
1442  */
1443 static CAResult_t CAStartLEDiscoveryServer();
1444
1445 /**
1446  * Send data to the endpoint using the adapter connectivity.
1447  *
1448  * @param[in] endpoint Remote Endpoint information (like MAC address,
1449  *                     reference URI and connectivity type) to which
1450  *                     the unicast data has to be sent.
1451  * @param[in] data     Data which required to be sent.
1452  * @param[in] dataLen  Size of data to be sent.
1453  *
1454  * @note  dataLen must be > 0.
1455  *
1456  * @return The number of bytes sent on the network, or -1 on error.
1457  */
1458 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
1459                                    const void *data,
1460                                    uint32_t dataLen);
1461
1462 /**
1463  * Send multicast data to the endpoint using the LE connectivity.
1464  *
1465  * @param[in] endpoint Remote Endpoint information to which the
1466  *                     multicast data has to be sent.
1467  * @param[in] data     Data which required to be sent.
1468  * @param[in] dataLen  Size of data to be sent.
1469  *
1470  * @note  dataLen must be > 0.
1471  *
1472  * @return The number of bytes sent on the network, or -1 on error.
1473  */
1474 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
1475                                      const void *data,
1476                                      uint32_t dataLen);
1477
1478 /**
1479  * Get LE Connectivity network information.
1480  *
1481  * @param[out] info Local connectivity information structures.
1482  * @param[out] size Number of local connectivity structures.
1483  *
1484  * @return ::CA_STATUS_OK or Appropriate error code.
1485  */
1486 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info,
1487                                               uint32_t *size);
1488
1489 /**
1490  * Read Synchronous API callback.
1491  *
1492  * @return  ::CA_STATUS_OK or Appropriate error code.
1493  */
1494 static CAResult_t CAReadLEData();
1495
1496 /**
1497  * Stopping the adapters and close socket connections.
1498  *
1499  * LE Stops all GATT servers and GATT Clients.
1500  *
1501  * @return ::CA_STATUS_OK or Appropriate error code.
1502  */
1503 static CAResult_t CAStopLE();
1504
1505 /**
1506  * Terminate the LE connectivity adapter.
1507  *
1508  * Configuration information will be deleted from further use.
1509  */
1510 static void CATerminateLE();
1511
1512 /**
1513  * This function will receive the data from the GattServer and add the
1514  * data to the Server receiver queue.
1515  *
1516  * @param[in] remoteAddress Remote address of the device from where
1517  *                          data is received.
1518  * @param[in] data          Actual data recevied from the remote
1519  *                          device.
1520  * @param[in] dataLength    Length of the data received from the
1521  *                          remote device.
1522  * @param[in] sentLength    Length of the data sent from the remote
1523  *                          device.
1524  *
1525  * @return ::CA_STATUS_OK or Appropriate error code.
1526  * @retval ::CA_STATUS_OK  Successful.
1527  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
1528  * @retval ::CA_STATUS_FAILED Operation failed.
1529  *
1530  */
1531 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
1532                                                 const uint8_t *data,
1533                                                 uint32_t dataLength,
1534                                                 uint32_t *sentLength);
1535
1536 /**
1537  * This function will receive the data from the GattClient and add the
1538  * data into the Client receiver queue.
1539  *
1540  * @param[in] remoteAddress Remote address of the device from where
1541  *                          data is received.
1542  * @param[in] data          Actual data recevied from the remote
1543  *                          device.
1544  * @param[in] dataLength    Length of the data received from the
1545  *                          remote device.
1546  * @param[in] sentLength    Length of the data sent from the remote
1547  *                          device.
1548  *
1549  * @return ::CA_STATUS_OK or Appropriate error code.
1550  * @retval ::CA_STATUS_OK  Successful.
1551  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
1552  * @retval ::CA_STATUS_FAILED Operation failed.
1553  */
1554 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
1555                                                 const uint8_t *data,
1556                                                 uint32_t dataLength,
1557                                                 uint32_t *sentLength);
1558
1559 /**
1560  * Set the NetworkPacket received callback to CA layer from adapter
1561  * layer.
1562  *
1563  * @param[in] callback Callback handle sent from the upper layer.
1564  */
1565 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
1566
1567 /**
1568  * Push the data from CA layer to the Sender processor queue.
1569  *
1570  * @param[in] remoteEndpoint Remote endpoint information of the
1571  *                           server.
1572  * @param[in] data           Data to be transmitted from LE.
1573  * @param[in] dataLen        Length of the Data being transmitted.
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 CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
1581                                             const uint8_t *data,
1582                                             uint32_t dataLen);
1583
1584 /**
1585  * Push the data from CA layer to the Sender processor queue.
1586  *
1587  * @param[in] remoteEndpoint Remote endpoint information of the
1588  *                           server.
1589  * @param[in] data           Data to be transmitted from LE.
1590  * @param[in] dataLen        Length of the Data being transmitted.
1591  *
1592  * @return ::CA_STATUS_OK or Appropriate error code.
1593  * @retval ::CA_STATUS_OK  Successful.
1594  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
1595  * @retval ::CA_STATUS_FAILED Operation failed.
1596  */
1597 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
1598                                             const uint8_t *data,
1599                                             uint32_t dataLen);
1600
1601 static CAResult_t CALEAdapterGattServerStart()
1602 {
1603     OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartLEGattServer");
1604
1605     CAResult_t result = CAStartLEGattServer();
1606
1607 #ifndef SINGLE_THREAD
1608     /*
1609       Don't start the server side sending queue thread until the
1610       server itself has actually started.
1611     */
1612     if (CA_STATUS_OK == result)
1613     {
1614         ca_mutex_lock(g_bleServerSendDataMutex);
1615         result = CAQueueingThreadStart(g_bleServerSendQueueHandle);
1616         ca_mutex_unlock(g_bleServerSendDataMutex);
1617
1618         if (CA_STATUS_OK != result)
1619         {
1620             OIC_LOG_V(ERROR,
1621                       CALEADAPTER_TAG,
1622                       "Unable to start server queuing thread (%d)",
1623                       result);
1624         }
1625     }
1626 #endif
1627
1628     return result;
1629 }
1630
1631 static CAResult_t CALEAdapterGattServerStop()
1632 {
1633 #ifndef SINGLE_THREAD
1634     ca_mutex_lock(g_bleServerSendDataMutex);
1635     CAResult_t result = CAQueueingThreadStop(g_bleServerSendQueueHandle);
1636     ca_mutex_unlock(g_bleServerSendDataMutex);
1637     if (CA_STATUS_OK == result)
1638     {
1639         result = CAStopLEGattServer();
1640     }
1641
1642     return result;
1643 #else
1644     return CAStopLEGattServer();
1645 #endif
1646 }
1647
1648 static CAResult_t CALEAdapterGattClientStart()
1649 {
1650     OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartLEGattClient");
1651
1652     CAResult_t result = CAStartLEGattClient();
1653
1654 #ifndef SINGLE_THREAD
1655     /*
1656       Don't start the client side sending queue thread until the
1657       client itself has actually started.
1658     */
1659     if (CA_STATUS_OK == result)
1660     {
1661         ca_mutex_lock(g_bleClientSendDataMutex);
1662         result = CAQueueingThreadStart(g_bleClientSendQueueHandle);
1663         ca_mutex_unlock(g_bleClientSendDataMutex);
1664
1665         if (CA_STATUS_OK != result)
1666         {
1667             OIC_LOG(ERROR,
1668                     CALEADAPTER_TAG,
1669                     "Unable to start client queuing thread");
1670         }
1671     }
1672 #endif
1673
1674     return result;
1675 }
1676
1677 static CAResult_t CALEAdapterGattClientStop()
1678 {
1679 #ifndef SINGLE_THREAD
1680     ca_mutex_lock(g_bleClientSendDataMutex);
1681     CAResult_t result = CAQueueingThreadStop(g_bleClientSendQueueHandle);
1682     ca_mutex_unlock(g_bleClientSendDataMutex);
1683     if (CA_STATUS_OK == result)
1684     {
1685         CAStopLEGattClient();
1686     }
1687
1688     return result;
1689 #else
1690     CAStopLEGattClient();
1691
1692     return CA_STATUS_OK;
1693 #endif
1694 }
1695
1696 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
1697                           CANetworkPacketReceivedCallback reqRespCallback,
1698                           CANetworkChangeCallback netCallback,
1699                           CAErrorHandleCallback errorCallback,
1700                           ca_thread_pool_t handle)
1701 {
1702     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1703
1704     //Input validation
1705     VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null");
1706     VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null");
1707     VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null");
1708
1709     CAResult_t result = CA_STATUS_OK;
1710     result = CAInitLEAdapterMutex();
1711     if (CA_STATUS_OK != result)
1712     {
1713         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
1714         return CA_STATUS_FAILED;
1715     }
1716
1717     result = CAInitializeLENetworkMonitor();
1718     if (CA_STATUS_OK != result)
1719     {
1720         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
1721         return CA_STATUS_FAILED;
1722     }
1723     CAInitializeLEAdapter(handle);
1724
1725     CASetLEClientThreadPoolHandle(handle);
1726
1727     result = CAInitializeLEGattClient();
1728     if (CA_STATUS_OK != result)
1729     {
1730         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattClient() failed");
1731         return CA_STATUS_FAILED;
1732     }
1733
1734     CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
1735     CASetLEServerThreadPoolHandle(handle);
1736     result = CAInitializeLEGattServer();
1737     if (CA_STATUS_OK != result)
1738     {
1739         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattServer() failed");
1740         return CA_STATUS_FAILED;
1741     }
1742
1743     CASetLEAdapterThreadPoolHandle(handle);
1744     CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
1745     CASetLEReqRespAdapterCallback(reqRespCallback);
1746
1747     CASetBLEClientErrorHandleCallback(CALEErrorHandler);
1748     CASetBLEServerErrorHandleCallback(CALEErrorHandler);
1749     CALERegisterNetworkNotifications(netCallback);
1750
1751     g_errorHandler = errorCallback;
1752
1753     static const CAConnectivityHandler_t connHandler =
1754         {
1755             .startAdapter = CAStartLE,
1756             .stopAdapter = CAStopLE,
1757             .startListenServer = CAStartLEListeningServer,
1758             .stopListenServer = CAStopLEListeningServer,
1759             .startDiscoveryServer = CAStartLEDiscoveryServer,
1760             .sendData = CASendLEUnicastData,
1761             .sendDataToAll = CASendLEMulticastData,
1762             .GetnetInfo = CAGetLEInterfaceInformation,
1763             .readData = CAReadLEData,
1764             .terminate = CATerminateLE,
1765             .cType = CA_ADAPTER_GATT_BTLE
1766         };
1767
1768     registerCallback(connHandler);
1769
1770     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1771
1772     return CA_STATUS_OK;
1773 }
1774
1775 static CAResult_t CAStartLE()
1776 {
1777     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAStartLE");
1778
1779     return CAStartLEAdapter();
1780 }
1781
1782 static CAResult_t CAStopLE()
1783 {
1784     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1785 #ifndef SINGLE_THREAD
1786     CAStopLEQueues();
1787 #endif
1788
1789     ca_mutex_lock(g_bleIsServerMutex);
1790     switch (g_adapterType)
1791     {
1792         case ADAPTER_SERVER:
1793             CALEAdapterGattServerStop();
1794             break;
1795         case ADAPTER_CLIENT:
1796             CALEAdapterGattClientStop();
1797             break;
1798         case ADAPTER_BOTH_CLIENT_SERVER:
1799             CALEAdapterGattServerStop();
1800             CALEAdapterGattClientStop();
1801             break;
1802         default:
1803             break;
1804     }
1805     ca_mutex_unlock(g_bleIsServerMutex);
1806
1807     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1808
1809     return CAStopLEAdapter();
1810 }
1811
1812 static void CATerminateLE()
1813 {
1814     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1815
1816     CASetLEReqRespServerCallback(NULL);
1817     CASetLEReqRespClientCallback(NULL);
1818     CALERegisterNetworkNotifications(NULL);
1819     CASetLEReqRespAdapterCallback(NULL);
1820     CATerminateLENetworkMonitor();
1821
1822     ca_mutex_lock(g_bleIsServerMutex);
1823     switch (g_adapterType)
1824     {
1825         case ADAPTER_SERVER:
1826             CATerminateLEGattServer();
1827             break;
1828         case ADAPTER_CLIENT:
1829             CATerminateLEGattClient();
1830             break;
1831         case ADAPTER_BOTH_CLIENT_SERVER:
1832             CATerminateLEGattServer();
1833             CATerminateLEGattClient();
1834             break;
1835         default:
1836             break;
1837     }
1838     g_adapterType = ADAPTER_EMPTY;
1839     ca_mutex_unlock(g_bleIsServerMutex);
1840
1841 #ifndef SINGLE_THREAD
1842     CATerminateLEQueues();
1843 #endif
1844     CATerminateLEAdapterMutex();
1845
1846     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1847 }
1848
1849 static CAResult_t CAStartLEListeningServer()
1850 {
1851     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAStartLEListeningServer");
1852 #ifndef ROUTING_GATEWAY
1853     CAResult_t result = CA_STATUS_OK;
1854 #ifndef SINGLE_THREAD
1855     result = CAInitLEServerQueues();
1856     if (CA_STATUS_OK != result)
1857     {
1858         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
1859         return result;
1860     }
1861 #endif
1862
1863     ca_mutex_lock(g_bleIsServerMutex);
1864     switch (g_adapterType)
1865     {
1866         case ADAPTER_CLIENT:
1867             g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
1868             break;
1869         case ADAPTER_BOTH_CLIENT_SERVER:
1870             break;
1871         default:
1872             g_adapterType = ADAPTER_SERVER;
1873     }
1874     ca_mutex_unlock(g_bleIsServerMutex);
1875
1876     result = CAGetLEAdapterState();
1877     if (CA_STATUS_OK != result)
1878     {
1879         if (CA_ADAPTER_NOT_ENABLED == result)
1880         {
1881             OIC_LOG(DEBUG,
1882                     CALEADAPTER_TAG,
1883                     "Listen Server will be started once BT Adapter is enabled");
1884         }
1885     }
1886     else
1887     {
1888         result = CALEAdapterGattServerStart();
1889     }
1890
1891     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1892     return result;
1893 #else
1894     // Routing Gateway only supports BLE client mode.
1895     OIC_LOG(ERROR, CALEADAPTER_TAG, "LE server not supported in Routing Gateway");
1896     return CA_NOT_SUPPORTED;
1897 #endif
1898 }
1899
1900 static CAResult_t CAStopLEListeningServer()
1901 {
1902     OIC_LOG(ERROR, CALEADAPTER_TAG, "Listen server stop not supported.");
1903     return CA_NOT_SUPPORTED;
1904 }
1905
1906 static CAResult_t CAStartLEDiscoveryServer()
1907 {
1908     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAStartLEDiscoveryServer");
1909     CAResult_t result = CA_STATUS_OK;
1910 #ifndef SINGLE_THREAD
1911     result = CAInitLEClientQueues();
1912     if (CA_STATUS_OK != result)
1913     {
1914         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
1915         return result;
1916     }
1917 #endif
1918
1919     ca_mutex_lock(g_bleIsServerMutex);
1920     switch (g_adapterType)
1921     {
1922         case ADAPTER_SERVER:
1923             g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
1924             break;
1925         case ADAPTER_BOTH_CLIENT_SERVER:
1926             break;
1927         default:
1928             g_adapterType = ADAPTER_CLIENT;
1929     }
1930     ca_mutex_unlock(g_bleIsServerMutex);
1931
1932     result = CAGetLEAdapterState();
1933     if (CA_STATUS_OK != result)
1934     {
1935         if (CA_ADAPTER_NOT_ENABLED == result)
1936         {
1937             OIC_LOG(DEBUG,
1938                     CALEADAPTER_TAG,
1939                     "Discovery Server will be started once BT Adapter is enabled");
1940         }
1941     }
1942     else
1943     {
1944         result = CALEAdapterGattClientStart();
1945     }
1946
1947     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1948     return result;
1949 }
1950
1951 static CAResult_t CAReadLEData()
1952 {
1953     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1954 #ifdef SINGLE_THREAD
1955     CACheckLEData();
1956 #endif
1957     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1958     return CA_STATUS_OK;
1959 }
1960
1961 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
1962                                    const void *data,
1963                                    uint32_t dataLen)
1964 {
1965     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CASendLEUnicastData");
1966
1967     //Input validation
1968     VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
1969     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
1970
1971     CAResult_t result = CA_STATUS_FAILED;
1972
1973     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
1974     if (ADAPTER_EMPTY == g_adapterType)
1975     {
1976         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
1977     }
1978
1979     ca_mutex_lock(g_bleIsServerMutex);
1980     if (ADAPTER_SERVER == g_adapterType || ADAPTER_BOTH_CLIENT_SERVER == g_adapterType)
1981     {
1982         result = CALEAdapterServerSendData(endpoint, data, dataLen);
1983         if (CA_STATUS_OK != result)
1984         {
1985             ca_mutex_unlock(g_bleIsServerMutex);
1986             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed");
1987             if (g_errorHandler)
1988             {
1989                 g_errorHandler(endpoint, data, dataLen, result);
1990             }
1991
1992             return -1;
1993         }
1994     }
1995
1996     if (ADAPTER_CLIENT == g_adapterType || ADAPTER_BOTH_CLIENT_SERVER == g_adapterType)
1997     {
1998         result = CALEAdapterClientSendData(endpoint, data, dataLen);
1999         if (CA_STATUS_OK != result)
2000         {
2001             ca_mutex_unlock(g_bleIsServerMutex);
2002             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
2003
2004              if (g_errorHandler)
2005              {
2006                  g_errorHandler(endpoint, data, dataLen, result);
2007              }
2008             return -1;
2009         }
2010     }
2011     ca_mutex_unlock(g_bleIsServerMutex);
2012
2013     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2014     return dataLen;
2015 }
2016
2017 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
2018                                      const void *data,
2019                                      uint32_t dataLen)
2020 {
2021     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CASendLEMulticastData");
2022
2023     //Input validation
2024     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2025
2026     if (0 >= dataLen)
2027     {
2028         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
2029         return -1;
2030     }
2031
2032     CAResult_t result = CA_STATUS_FAILED;
2033
2034     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2035     if (ADAPTER_EMPTY == g_adapterType)
2036     {
2037         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2038     }
2039
2040     ca_mutex_lock(g_bleIsServerMutex);
2041     if (ADAPTER_SERVER == g_adapterType || ADAPTER_BOTH_CLIENT_SERVER == g_adapterType)
2042     {
2043         result = CALEAdapterServerSendData(NULL, data, dataLen);
2044         if (CA_STATUS_OK != result)
2045         {
2046             ca_mutex_unlock(g_bleIsServerMutex);
2047
2048             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data for server failed" );
2049
2050             if (g_errorHandler)
2051             {
2052                 g_errorHandler(endpoint, data, dataLen, result);
2053             }
2054             return -1;
2055         }
2056     }
2057
2058     if (ADAPTER_CLIENT == g_adapterType || ADAPTER_BOTH_CLIENT_SERVER == g_adapterType)
2059     {
2060         result = CALEAdapterClientSendData(NULL, data, dataLen);
2061         if (CA_STATUS_OK != result)
2062         {
2063             ca_mutex_unlock(g_bleIsServerMutex);
2064
2065             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data for client failed" );
2066
2067             if (g_errorHandler)
2068             {
2069                 g_errorHandler(endpoint, data, dataLen, result);
2070             }
2071             return -1;
2072         }
2073     }
2074     ca_mutex_unlock(g_bleIsServerMutex);
2075
2076     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CASendLEMulticastData");
2077     return dataLen;
2078 }
2079
2080 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
2081 {
2082     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2083
2084     VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
2085
2086     char *local_address = NULL;
2087
2088     CAResult_t res = CAGetLEAddress(&local_address);
2089     if (CA_STATUS_OK != res)
2090     {
2091         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
2092         return res;
2093     }
2094
2095     if (NULL == local_address)
2096     {
2097         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
2098         return CA_STATUS_FAILED;
2099     }
2100
2101     *size = 0;
2102     (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
2103     if (NULL == (*info))
2104     {
2105         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
2106         OICFree(local_address);
2107         return CA_STATUS_FAILED;
2108     }
2109
2110     size_t local_address_len = strlen(local_address);
2111
2112     if(local_address_len >= sizeof(g_localBLEAddress) ||
2113             local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
2114     {
2115         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
2116         OICFree(*info);
2117         OICFree(local_address);
2118         return CA_STATUS_FAILED;
2119     }
2120
2121     OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
2122     ca_mutex_lock(g_bleLocalAddressMutex);
2123     OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
2124     ca_mutex_unlock(g_bleLocalAddressMutex);
2125
2126     (*info)->adapter = CA_ADAPTER_GATT_BTLE;
2127     *size = 1;
2128     OICFree(local_address);
2129
2130     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2131     return CA_STATUS_OK;
2132 }
2133
2134 static CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback)
2135 {
2136     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2137
2138     ca_mutex_lock(g_bleNetworkCbMutex);
2139     g_networkCallback = netCallback;
2140     ca_mutex_unlock(g_bleNetworkCbMutex);
2141     CAResult_t res = CA_STATUS_OK;
2142     if (netCallback)
2143     {
2144         res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
2145         if (CA_STATUS_OK != res)
2146         {
2147             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
2148         }
2149     }
2150     else
2151     {
2152         res = CAUnSetLEAdapterStateChangedCb();
2153         if (CA_STATUS_OK != res)
2154         {
2155             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
2156         }
2157     }
2158
2159     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2160     return res;
2161 }
2162
2163 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
2164 {
2165     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEDeviceStateChangedCb");
2166
2167     VERIFY_NON_NULL_VOID(g_localBLEAddress, CALEADAPTER_TAG, "g_localBLEAddress is null");
2168     CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE };
2169
2170     ca_mutex_lock(g_bleLocalAddressMutex);
2171     OICStrcpy(localEndpoint.addr,
2172               sizeof(localEndpoint.addr),
2173               g_localBLEAddress);
2174     ca_mutex_unlock(g_bleLocalAddressMutex);
2175
2176     if (CA_ADAPTER_ENABLED == adapter_state)
2177     {
2178         ca_mutex_lock(g_bleIsServerMutex);
2179         switch (g_adapterType)
2180         {
2181             case ADAPTER_SERVER:
2182                 CALEAdapterGattServerStart();
2183                 break;
2184             case ADAPTER_CLIENT:
2185                 CALEAdapterGattClientStart();
2186                 break;
2187             case ADAPTER_BOTH_CLIENT_SERVER:
2188                 CALEAdapterGattServerStart();
2189                 CALEAdapterGattClientStart();
2190                 break;
2191             default:
2192                 break;
2193         }
2194         ca_mutex_unlock(g_bleIsServerMutex);
2195     }
2196     else
2197     {
2198         ca_mutex_lock(g_bleIsServerMutex);
2199         switch (g_adapterType)
2200         {
2201             case ADAPTER_SERVER:
2202                 CALEAdapterGattServerStop();
2203                 break;
2204             case ADAPTER_CLIENT:
2205                 CALEAdapterGattClientStop();
2206                 break;
2207             case ADAPTER_BOTH_CLIENT_SERVER:
2208                 CALEAdapterGattServerStop();
2209                 CALEAdapterGattClientStop();
2210                 break;
2211             default:
2212                 break;
2213         }
2214         ca_mutex_unlock(g_bleIsServerMutex);
2215     }
2216
2217     ca_mutex_lock(g_bleNetworkCbMutex);
2218     if (NULL != g_networkCallback)
2219     {
2220         g_networkCallback(&localEndpoint, adapter_state);
2221     }
2222     else
2223     {
2224         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
2225     }
2226     ca_mutex_unlock(g_bleNetworkCbMutex);
2227
2228     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2229 }
2230
2231 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
2232                                             const uint8_t *data,
2233                                             uint32_t dataLen)
2234 {
2235     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2236
2237     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
2238 #ifndef SINGLE_THREAD
2239     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
2240                         "g_bleClientSendQueueHandle is  NULL",
2241                         CA_STATUS_FAILED);
2242     VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
2243                         "g_bleClientSendDataMutex is NULL",
2244                         CA_STATUS_FAILED);
2245
2246     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
2247                         "g_bleClientSendQueueHandle",
2248                         CA_STATUS_FAILED);
2249
2250     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%u]", dataLen);
2251
2252     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen, NULL);
2253     if (!bleData)
2254     {
2255         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2256         return CA_MEMORY_ALLOC_FAILED;
2257     }
2258     // Add message to send queue
2259     ca_mutex_lock(g_bleClientSendDataMutex);
2260     CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData, sizeof(CALEData_t));
2261     ca_mutex_unlock(g_bleClientSendDataMutex);
2262 #endif
2263     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2264     return CA_STATUS_OK;
2265 }
2266
2267 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
2268                                             const uint8_t *data,
2269                                             uint32_t dataLen)
2270 {
2271     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2272
2273     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
2274
2275 #ifdef SINGLE_THREAD
2276     uint8_t header[CA_HEADER_LENGTH] = { 0 };
2277
2278     CAResult_t result =
2279         CAGenerateHeader(header, CA_HEADER_LENGTH, dataLen);
2280
2281     if (CA_STATUS_OK != result)
2282     {
2283         OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
2284         return CA_STATUS_FAILED;
2285     }
2286
2287     if (!CAIsLEConnected())
2288     {
2289         OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
2290         return CA_STATUS_FAILED;
2291     }
2292
2293     result = CAUpdateCharacteristicsToAllGattClients(header, CA_HEADER_LENGTH);
2294     if (CA_STATUS_OK != result)
2295     {
2296         OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2297         return CA_STATUS_FAILED;
2298     }
2299
2300     const uint32_t dataLimit = dataLen / CA_SUPPORTED_BLE_MTU_SIZE;
2301     for (uint32_t iter = 0; iter < dataLimit; iter++)
2302     {
2303         result =
2304             CAUpdateCharacteristicsToAllGattClients(
2305                 data + (iter * CA_SUPPORTED_BLE_MTU_SIZE),
2306                 CA_SUPPORTED_BLE_MTU_SIZE);
2307
2308         if (CA_STATUS_OK != result)
2309         {
2310             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2311             return CA_STATUS_FAILED;
2312         }
2313
2314         CALEDoEvents();
2315     }
2316
2317     const uint32_t remainingLen = dataLen % CA_SUPPORTED_BLE_MTU_SIZE;
2318     if (remainingLen)
2319     {
2320         result =
2321             CAUpdateCharacteristicsToAllGattClients(
2322                 data + (dataLimit * CA_SUPPORTED_BLE_MTU_SIZE),
2323                 remainingLen);
2324         if (CA_STATUS_OK != result)
2325         {
2326             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2327             return CA_STATUS_FAILED;
2328         }
2329         CALEDoEvents();
2330     }
2331 #else
2332     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
2333                         "BleClientReceiverQueue is NULL",
2334                         CA_STATUS_FAILED);
2335     VERIFY_NON_NULL_RET(g_bleServerSendDataMutex, CALEADAPTER_TAG,
2336                         "BleClientSendDataMutex is NULL",
2337                         CA_STATUS_FAILED);
2338
2339     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG, "sendQueueHandle",
2340                         CA_STATUS_FAILED);
2341
2342     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
2343
2344     CALEData_t * const bleData =
2345         CACreateLEData(remoteEndpoint, data, dataLen, NULL);
2346
2347     if (!bleData)
2348     {
2349         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2350         return CA_MEMORY_ALLOC_FAILED;
2351     }
2352
2353     // Add message to send queue
2354     ca_mutex_lock(g_bleServerSendDataMutex);
2355     CAQueueingThreadAddData(g_bleServerSendQueueHandle,
2356                             bleData,
2357                             sizeof(CALEData_t));
2358     ca_mutex_unlock(g_bleServerSendDataMutex);
2359 #endif
2360     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2361     return CA_STATUS_OK;
2362 }
2363
2364 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
2365                                                 const uint8_t *data,
2366                                                 uint32_t dataLength,
2367                                                 uint32_t *sentLength)
2368 {
2369     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2370
2371     //Input validation
2372     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
2373     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
2374
2375 #ifdef SINGLE_THREAD
2376     if(g_networkPacketReceivedCallback)
2377     {
2378         // will be filled by upper layer
2379         const CASecureEndpoint_t endpoint =
2380             { .endpoint = { .adapter = CA_ADAPTER_GATT_BTLE } };
2381
2382
2383         g_networkPacketReceivedCallback(&endpoint, data, dataLength);
2384     }
2385 #else
2386     VERIFY_NON_NULL_RET(g_bleReceiverQueue,
2387                         CALEADAPTER_TAG,
2388                         "g_bleReceiverQueue",
2389                         CA_STATUS_FAILED);
2390
2391     //Add message to data queue
2392     CAEndpoint_t * const remoteEndpoint =
2393         CACreateEndpointObject(CA_DEFAULT_FLAGS,
2394                                CA_ADAPTER_GATT_BTLE,
2395                                remoteAddress,
2396                                0);
2397
2398     if (NULL == remoteEndpoint)
2399     {
2400         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
2401         return CA_STATUS_FAILED;
2402     }
2403
2404     // Create bleData to add to queue
2405     OIC_LOG_V(DEBUG,
2406               CALEADAPTER_TAG,
2407               "Data received from LE layer [%d]",
2408               dataLength);
2409
2410     CALEData_t * const bleData =
2411         CACreateLEData(remoteEndpoint, data, dataLength, g_bleServerSenderInfo);
2412
2413     if (!bleData)
2414     {
2415         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2416         CAFreeEndpoint(remoteEndpoint);
2417         return CA_MEMORY_ALLOC_FAILED;
2418     }
2419
2420     CAFreeEndpoint(remoteEndpoint);
2421     // Add message to receiver queue
2422     CAQueueingThreadAddData(g_bleReceiverQueue, bleData, sizeof(CALEData_t));
2423
2424     *sentLength = dataLength;
2425 #endif
2426     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2427     return CA_STATUS_OK;
2428 }
2429
2430 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
2431                                                 const uint8_t *data,
2432                                                 uint32_t dataLength,
2433                                                 uint32_t *sentLength)
2434 {
2435     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2436
2437     //Input validation
2438     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
2439     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
2440 #ifndef SINGLE_THREAD
2441     VERIFY_NON_NULL_RET(g_bleReceiverQueue, CALEADAPTER_TAG,
2442                         "g_bleReceiverQueue",
2443                         CA_STATUS_FAILED);
2444
2445     //Add message to data queue
2446     CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
2447                                                           CA_ADAPTER_GATT_BTLE,
2448                                                           remoteAddress, 0);
2449     if (NULL == remoteEndpoint)
2450     {
2451         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
2452         return CA_STATUS_FAILED;
2453     }
2454
2455     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%u]", dataLength);
2456
2457     // Create bleData to add to queue
2458     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data,
2459                                          dataLength, g_bleClientSenderInfo);
2460     if (!bleData)
2461     {
2462         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2463         CAFreeEndpoint(remoteEndpoint);
2464         return CA_MEMORY_ALLOC_FAILED;
2465     }
2466
2467     CAFreeEndpoint(remoteEndpoint);
2468     // Add message to receiver queue
2469     CAQueueingThreadAddData(g_bleReceiverQueue, bleData, sizeof(CALEData_t));
2470
2471     *sentLength = dataLength;
2472 #endif
2473     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2474     return CA_STATUS_OK;
2475 }
2476
2477 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
2478 {
2479     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2480
2481     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
2482     g_bleAdapterThreadPool = handle;
2483     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
2484
2485     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2486 }
2487
2488 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
2489 {
2490     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2491
2492     ca_mutex_lock(g_bleAdapterReqRespCbMutex);
2493
2494     g_networkPacketReceivedCallback = callback;
2495
2496     ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
2497
2498     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2499 }
2500
2501 static void CALEErrorHandler(const char *remoteAddress,
2502                              const uint8_t *data,
2503                              uint32_t dataLen,
2504                              CAResult_t result)
2505 {
2506     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler IN");
2507
2508     VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
2509
2510     CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS,
2511                                                CA_ADAPTER_GATT_BTLE,
2512                                                remoteAddress,
2513                                                0);
2514
2515     // if required, will be used to build remote endpoint
2516     g_errorHandler(rep, data, dataLen, result);
2517
2518     CAFreeEndpoint(rep);
2519
2520     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler OUT");
2521 }