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