Merge Single/Multi thread for camessagehandler
[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  * @var CALEADAPTER_TAG
39  * @brief Logging tag for module name.
40  */
41 #define CALEADAPTER_TAG "LAD"
42
43 /**
44  * @var g_networkCallback
45  * @brief Callback to provide the status of the network change to CA layer.
46  */
47 static CANetworkChangeCallback g_networkCallback = NULL;
48
49 /**
50  * @var g_localBLEAddress
51  * @brief bleAddress of the local adapter. Value will be initialized to zero, and will
52  *        be updated later.
53  */
54 static char g_localBLEAddress[18] = {0};
55
56 /**
57  * @var g_isServer
58  * @brief Variable to differentiate btw GattServer and GattClient.
59  */
60 static bool g_isServer = false;
61
62 /**
63  * @var g_bleIsServerMutex
64  * @brief Mutex to synchronize the task to be executed on the GattServer function calls.
65  */
66 static ca_mutex g_bleIsServerMutex = NULL;
67
68 /**
69  * @var g_bleNetworkCbMutex
70  * @brief Mutex to synchronize the callback to be called for the network changes.
71  */
72 static ca_mutex g_bleNetworkCbMutex = NULL;
73
74 /**
75  * @var g_bleLocalAddressMutex
76  * @brief Mutex to synchronize the updation of the local LE address of the adapter.
77  */
78 static ca_mutex g_bleLocalAddressMutex = NULL;
79
80 /**
81  * @var g_bleAdapterThreadPool
82  * @brief reference to threadpool
83  */
84 static ca_thread_pool_t g_bleAdapterThreadPool = NULL;
85
86 /**
87  * @var g_bleAdapterThreadPoolMutex
88  * @brief Mutex to synchronize the task to be pushed to thread pool.
89  */
90 static ca_mutex g_bleAdapterThreadPoolMutex = NULL;
91
92 /**
93  * @var g_bleClientSendDataMutex
94  * @brief Mutex to synchronize the queing of the data from SenderQueue.
95  */
96 static ca_mutex g_bleClientSendDataMutex = NULL;
97
98 /**
99  * @var g_bleClientReceiveDataMutex
100  * @brief Mutex to synchronize the queing of the data from ReceiverQueue.
101  */
102 static ca_mutex g_bleClientReceiveDataMutex = NULL;
103
104
105 /**
106  * @var g_bleServerSendDataMutex
107  * @brief Mutex to synchronize the queing of the data from SenderQueue.
108  */
109 static ca_mutex g_bleServerSendDataMutex = NULL;
110
111 /**
112  * @var g_bleServerReceiveDataMutex
113  * @brief Mutex to synchronize the queing of the data from ReceiverQueue.
114  */
115 static ca_mutex g_bleServerReceiveDataMutex = NULL;
116
117 /**
118  * @var g_bleAdapterReqRespCbMutex
119  * @brief Mutex to synchronize the callback to be called for the adapterReqResponse.
120  */
121 static ca_mutex g_bleAdapterReqRespCbMutex = NULL;
122
123 /**
124  * @var g_networkPacketReceivedCallback
125  * @brief Callback to be called when network packet recieved from either GattServer or GattClient.
126  */
127 static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
128
129 /**
130  * @var g_errorHandler
131  * @brief Callback to notify error from the BLE adapter
132  */
133 static CAErrorHandleCallback g_errorHandler = NULL;
134
135 /**
136  * @var g_bleAdapterState
137  * @brief Storing Adapter state information
138  */
139 static CAAdapterState_t g_bleAdapterState = CA_ADAPTER_DISABLED;
140
141 /**
142  * @ENUM CALeServerStatus
143  * @brief status of BLE Server Status
144  *  This ENUM provides information of LE Adapter Server status
145  */
146 typedef enum
147 {
148     CA_SERVER_NOTSTARTED = 0,
149     CA_LISTENING_SERVER,
150     CA_DISCOVERY_SERVER
151 } CALeServerStatus;
152
153 /**
154  * @var gLeServerStatus
155  * @brief structure to maintain the status of the server.
156  */
157 static CALeServerStatus gLeServerStatus = CA_SERVER_NOTSTARTED;
158
159 /**
160 * @fn  CALERegisterNetworkNotifications
161 * @brief  This function is used to register network change notification callback.
162 *
163 * @param[in]  netCallback CANetworkChangeCallback callback which will be set for the change in nwk.
164 *
165 * @return  0 on success otherwise a positive error value.
166 * @retval  CA_STATUS_OK  Successful
167 * @retval  CA_STATUS_INVALID_PARAM  Invalid input argumets
168 * @retval  CA_STATUS_FAILED Operation failed
169 *
170 */
171 CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback);
172
173 /**
174 * @fn  CASetBleAdapterThreadPoolHandle
175 * @brief  Used to Set the gThreadPool handle which is required for spawning new thread.
176 *
177 * @param[in] handle - Thread pool handle which is given by above layer for using thread
178 *                     creation task.
179 *
180 * @return  void
181 *
182 */
183 void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle);
184
185 /**
186 * @fn  CALEDeviceStateChangedCb
187 * @brief  This function is used to call the callback to the upper layer when the device state gets
188 *         changed.
189 *
190 * @param[in]  adapter_state New state of the adapter to be notified to the upper layer.
191 *
192 * @return  None.
193 *
194 */
195 void CALEDeviceStateChangedCb( CAAdapterState_t adapter_state);
196
197 /**
198 * @fn  CAInitBleAdapterMutex
199 * @brief  Used to initialize all required mutex variable for LE Adapter implementation.
200 *
201 * @return  0 on success otherwise a positive error value.
202 * @retval  CA_STATUS_OK  Successful
203 * @retval  CA_STATUS_INVALID_PARAM  Invalid input argumets
204 * @retval  CA_STATUS_FAILED Operation failed
205 *
206 */
207 CAResult_t CAInitLEAdapterMutex();
208
209 /**
210 * @fn  CATerminateBleAdapterMutex
211 * @brief  Used to terminate all required mutex variable for LE adapter implementation.
212 *
213 * @return  void
214 */
215 void CATerminateLEAdapterMutex();
216
217 /**
218 * @fn  CALEErrorHandler
219 * @brief  prepares and notify error through error callback
220 *
221 * @return  void
222 */
223 static void CALEErrorHandler(const char *remoteAddress, const void *data, uint32_t dataLen,
224                              CAResult_t result);
225
226 #ifndef SINGLE_THREAD
227 /**
228  * @var g_dataReceiverHandlerState
229  * @brief Stop condition of recvhandler.
230  */
231 static bool g_dataReceiverHandlerState = false;
232
233 /**
234  * @var g_bleClientSendQueueHandle
235  * @brief Queue to process the outgoing packets from GATTClient.
236  */
237 static CAQueueingThread_t *g_bleClientSendQueueHandle = NULL;
238
239 /**
240  * @var g_bleClientReceiverQueue
241  * @brief Queue to process the incoming packets to GATT Client.
242  */
243 static CAQueueingThread_t *g_bleClientReceiverQueue = NULL;
244
245 /**
246  * @var g_bleServerSendQueueHandle
247  * @brief Queue to process the outgoing packets from GATTServer.
248  */
249 static CAQueueingThread_t *g_bleServerSendQueueHandle = NULL;
250
251 /**
252  * @var g_bleServerReceiverQueue
253  * @brief Queue to process the incoming packets to GATTServer
254  */
255 static CAQueueingThread_t *g_bleServerReceiverQueue = NULL;
256
257 /**
258 * @fn  CALEDataDestroyer
259 * @brief  Used to free data
260 *
261 * @return  void
262 */
263 static void CALEDataDestroyer(void *data, uint32_t size);
264
265 void CAInitLEQueues()
266 {
267     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
268
269     CAResult_t result = CAInitLEServerQueues();
270     if (CA_STATUS_OK != result)
271     {
272         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerQueues failed");
273         return;
274     }
275
276     result = CAInitLEClientQueues();
277     if (CA_STATUS_OK != result)
278     {
279         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientQueues failed");
280         return;
281     }
282
283     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
284 }
285
286 CAResult_t CAInitLEServerQueues()
287 {
288     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
289
290     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
291
292     CAResult_t result = CAInitLEServerSenderQueue();
293     if (CA_STATUS_OK != result)
294     {
295         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerSenderQueue failed");
296         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
297         return CA_STATUS_FAILED;
298     }
299
300     result = CAInitLEServerReceiverQueue();
301     if (CA_STATUS_OK != result)
302     {
303         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerReceiverQueue failed");
304         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
305         return CA_STATUS_FAILED;
306     }
307
308     g_dataReceiverHandlerState = true;
309
310     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
311
312     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
313     return CA_STATUS_OK;
314 }
315
316 CAResult_t CAInitLEClientQueues()
317 {
318     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
319
320     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
321
322     CAResult_t result = CAInitLEClientSenderQueue();
323     if (CA_STATUS_OK != result)
324     {
325         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientSenderQueue failed");
326         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
327         return CA_STATUS_FAILED;
328     }
329
330     result = CAInitLEClientReceiverQueue();
331     if (CA_STATUS_OK != result)
332     {
333         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientReceiverQueue failed");
334         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
335         return CA_STATUS_FAILED;
336     }
337
338     g_dataReceiverHandlerState = true;
339
340     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
341
342     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
343     return CA_STATUS_OK;
344 }
345
346 CAResult_t CAInitLEServerSenderQueue()
347 {
348     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
349     // Check if the message queue is already initialized
350     if (g_bleServerSendQueueHandle)
351     {
352         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Queue is already initialized!");
353         return CA_STATUS_OK;
354     }
355
356     // Create send message queue
357     g_bleServerSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
358     if (!g_bleServerSendQueueHandle)
359     {
360         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
361         return CA_MEMORY_ALLOC_FAILED;
362     }
363
364     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerSendQueueHandle,
365                                                    g_bleAdapterThreadPool,
366                                                    CALEServerSendDataThread, CALEDataDestroyer))
367     {
368         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
369         OICFree(g_bleServerSendQueueHandle);
370         g_bleServerSendQueueHandle = NULL;
371         return CA_STATUS_FAILED;
372     }
373
374     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleServerSendQueueHandle))
375     {
376         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
377         OICFree(g_bleServerSendQueueHandle);
378         g_bleServerSendQueueHandle = NULL;
379         return CA_STATUS_FAILED;
380     }
381
382     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
383     return CA_STATUS_OK;
384 }
385
386 CAResult_t CAInitLEClientSenderQueue()
387 {
388     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
389
390     if (g_bleClientSendQueueHandle)
391     {
392         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
393         return CA_STATUS_OK;
394     }
395
396     // Create send message queue
397     g_bleClientSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
398     if (!g_bleClientSendQueueHandle)
399     {
400         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
401         return CA_MEMORY_ALLOC_FAILED;
402     }
403
404     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientSendQueueHandle,
405                                                    g_bleAdapterThreadPool,
406                                                    CALEClientSendDataThread, CALEDataDestroyer))
407     {
408         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
409         OICFree(g_bleClientSendQueueHandle);
410         g_bleClientSendQueueHandle = NULL;
411         return CA_STATUS_FAILED;
412     }
413
414     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleClientSendQueueHandle))
415     {
416         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
417         OICFree(g_bleClientSendQueueHandle);
418         g_bleClientSendQueueHandle = NULL;
419         return CA_STATUS_FAILED;
420     }
421
422     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
423     return CA_STATUS_OK;
424 }
425
426 CAResult_t CAInitLEServerReceiverQueue()
427 {
428     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
429     // Check if the message queue is already initialized
430     if (g_bleServerReceiverQueue)
431     {
432         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
433         return CA_STATUS_OK;
434     }
435
436     // Create send message queue
437     g_bleServerReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
438     if (!g_bleServerReceiverQueue)
439     {
440         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
441         OICFree(g_bleServerSendQueueHandle);
442         return CA_MEMORY_ALLOC_FAILED;
443     }
444
445     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerReceiverQueue, g_bleAdapterThreadPool,
446             CALEServerDataReceiverHandler, CALEDataDestroyer))
447     {
448         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
449         OICFree(g_bleServerReceiverQueue);
450         g_bleServerReceiverQueue = NULL;
451         return CA_STATUS_FAILED;
452     }
453
454     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleServerReceiverQueue))
455     {
456         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
457         OICFree(g_bleServerReceiverQueue);
458         g_bleServerReceiverQueue = NULL;
459         return CA_STATUS_FAILED;
460     }
461
462     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
463     return CA_STATUS_OK;
464 }
465
466 CAResult_t CAInitLEClientReceiverQueue()
467 {
468     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
469
470     // Check if the message queue is already initialized
471     if (g_bleClientReceiverQueue)
472     {
473         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
474     }
475     else
476     {
477         // Create send message queue
478         g_bleClientReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
479         if (!g_bleClientReceiverQueue)
480         {
481             OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
482             OICFree(g_bleClientSendQueueHandle);
483             return CA_MEMORY_ALLOC_FAILED;
484         }
485
486         if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientReceiverQueue,
487                                                        g_bleAdapterThreadPool,
488                                                        CALEClientDataReceiverHandler, NULL))
489         {
490             OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
491             OICFree(g_bleClientSendQueueHandle);
492             OICFree(g_bleClientReceiverQueue);
493             g_bleClientReceiverQueue = NULL;
494             return CA_STATUS_FAILED;
495         }
496     }
497     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleClientReceiverQueue))
498     {
499         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
500         OICFree(g_bleClientReceiverQueue);
501         g_bleClientReceiverQueue = NULL;
502         return CA_STATUS_FAILED;
503     }
504
505     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
506     return CA_STATUS_OK;
507 }
508
509 void CAStopLEQueues()
510 {
511     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
512
513     ca_mutex_lock(g_bleClientSendDataMutex);
514     if (NULL != g_bleClientSendQueueHandle)
515     {
516         CAQueueingThreadStop(g_bleClientSendQueueHandle);
517     }
518     ca_mutex_unlock(g_bleClientSendDataMutex);
519
520     ca_mutex_lock(g_bleClientReceiveDataMutex);
521     if (NULL != g_bleClientReceiverQueue)
522     {
523         CAQueueingThreadStop(g_bleClientReceiverQueue);
524     }
525     ca_mutex_unlock(g_bleClientReceiveDataMutex);
526
527     ca_mutex_lock(g_bleServerSendDataMutex);
528     if (NULL != g_bleServerSendQueueHandle)
529     {
530         CAQueueingThreadStop(g_bleServerSendQueueHandle);
531     }
532     ca_mutex_unlock(g_bleServerSendDataMutex);
533
534     ca_mutex_lock(g_bleServerReceiveDataMutex);
535     if (NULL != g_bleServerReceiverQueue)
536     {
537         CAQueueingThreadStop(g_bleServerReceiverQueue);
538     }
539     ca_mutex_unlock(g_bleServerReceiveDataMutex);
540
541     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
542 }
543
544 void CATerminateLEQueues()
545 {
546     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
547
548     CAQueueingThreadDestroy(g_bleClientSendQueueHandle);
549     OICFree(g_bleClientSendQueueHandle);
550     g_bleClientSendQueueHandle = NULL;
551
552
553     CAQueueingThreadDestroy(g_bleClientReceiverQueue);
554     OICFree(g_bleClientReceiverQueue);
555     g_bleClientReceiverQueue = NULL;
556
557
558     CAQueueingThreadDestroy(g_bleServerSendQueueHandle);
559     OICFree(g_bleServerSendQueueHandle);
560     g_bleServerSendQueueHandle = NULL;
561
562
563     CAQueueingThreadDestroy(g_bleServerReceiverQueue);
564     OICFree(g_bleServerReceiverQueue);
565     g_bleServerReceiverQueue = NULL;
566
567     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
568 }
569
570 void CALEServerDataReceiverHandler(void *threadData)
571 {
572     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
573
574     static uint32_t recvDataLen = 0;
575     static uint32_t totalDataLen = 0;
576     static char *defragData = NULL;
577     static bool isHeaderAvailable = false;
578     static CAEndpoint_t *remoteEndpoint = NULL;
579
580     ca_mutex_lock(g_bleServerReceiveDataMutex);
581
582     if (g_dataReceiverHandlerState)
583     {
584         OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
585
586         CALEData_t *bleData = (CALEData_t *) threadData;
587         if (!bleData)
588         {
589             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bleData!");
590             ca_mutex_unlock(g_bleServerReceiveDataMutex);
591             return;
592         }
593
594         OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
595
596         if (!isHeaderAvailable)
597         {
598             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
599             totalDataLen = CAParseHeader((char*)bleData->data);
600
601             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%d] bytes", totalDataLen);
602             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%d] bytes", bleData->dataLen);
603
604             defragData = (char *) OICCalloc(totalDataLen + 1, sizeof(char));
605             if (NULL == defragData)
606             {
607                 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
608                 ca_mutex_unlock(g_bleServerReceiveDataMutex);
609                 return;
610             }
611
612             const char *remoteAddress = bleData->remoteEndpoint->addr;
613
614             remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS, CA_ADAPTER_GATT_BTLE,
615                                                     remoteAddress, 0);
616
617             memcpy(defragData + recvDataLen, bleData->data + CA_HEADER_LENGTH,
618                    bleData->dataLen - CA_HEADER_LENGTH);
619             recvDataLen += bleData->dataLen - CA_HEADER_LENGTH;
620             isHeaderAvailable = true;
621         }
622         else
623         {
624             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]", bleData->dataLen);
625             memcpy(defragData + recvDataLen, bleData->data, bleData->dataLen);
626             recvDataLen += bleData->dataLen ;
627             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "totalDatalength  [%d] recveived Datalen [%d]",
628                       totalDataLen, recvDataLen);
629         }
630         if (totalDataLen == recvDataLen)
631         {
632             ca_mutex_lock(g_bleAdapterReqRespCbMutex);
633             if (NULL == g_networkPacketReceivedCallback)
634             {
635                 OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
636                 OICFree(defragData);
637                 CAFreeEndpoint(remoteEndpoint);
638                 remoteEndpoint = NULL;
639                 defragData = NULL;
640                 ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
641                 ca_mutex_unlock(g_bleServerReceiveDataMutex);
642                 return;
643             }
644             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending data up !");
645             g_networkPacketReceivedCallback(remoteEndpoint, defragData, recvDataLen);
646
647             OICFree(defragData);
648             CAFreeEndpoint(remoteEndpoint);
649
650             recvDataLen = 0;
651             totalDataLen = 0;
652             isHeaderAvailable = false;
653             remoteEndpoint = NULL;
654             defragData = NULL;
655             ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
656         }
657
658         if (false == g_dataReceiverHandlerState)
659         {
660             OIC_LOG(DEBUG, CALEADAPTER_TAG, "GATTClient is terminating. Cleaning up");
661             recvDataLen = 0;
662             totalDataLen = 0;
663             isHeaderAvailable = false;
664             OICFree(defragData);
665             CAFreeEndpoint(remoteEndpoint);
666             remoteEndpoint = NULL;
667             defragData = NULL;
668             ca_mutex_unlock(g_bleServerReceiveDataMutex);
669             return;
670         }
671     }
672     ca_mutex_unlock(g_bleServerReceiveDataMutex);
673     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
674 }
675
676 void CALEClientDataReceiverHandler(void *threadData)
677 {
678     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
679
680     static const char *remoteAddress = NULL;
681     static uint32_t recvDataLen = 0;
682     static uint32_t totalDataLen = 0;
683     static char *defragData = NULL;
684     static bool isHeaderAvailable = false;
685     static CAEndpoint_t *remoteEndpoint = NULL;
686
687     ca_mutex_lock(g_bleClientReceiveDataMutex);
688
689     if (g_dataReceiverHandlerState)
690     {
691         OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
692
693         CALEData_t *bleData = (CALEData_t *) threadData;
694         if (!bleData)
695         {
696             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid wifidata!");
697             ca_mutex_unlock(g_bleClientReceiveDataMutex);
698             return;
699         }
700
701         OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
702
703         if (!isHeaderAvailable)
704         {
705             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
706
707             totalDataLen = CAParseHeader(bleData->data);
708             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%d] bytes",
709                       totalDataLen);
710             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received in the first packet [%d] bytes",
711                       bleData->dataLen);
712
713             defragData = (char *) OICMalloc(sizeof(char) * totalDataLen);
714             if (NULL == defragData)
715             {
716                 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
717                 ca_mutex_unlock(g_bleClientReceiveDataMutex);
718                 return;
719             }
720
721             remoteAddress = bleData->remoteEndpoint->addr;
722
723             remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS, CA_ADAPTER_GATT_BTLE,
724                                                     remoteAddress, 0);
725
726             memcpy(defragData, bleData->data + CA_HEADER_LENGTH,
727                    bleData->dataLen - CA_HEADER_LENGTH);
728             recvDataLen += bleData->dataLen - CA_HEADER_LENGTH;
729             isHeaderAvailable = true;
730         }
731         else
732         {
733             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]", bleData->dataLen);
734             memcpy(defragData + recvDataLen, bleData->data, bleData->dataLen);
735             recvDataLen += bleData->dataLen ;
736             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "totalDatalength  [%d] recveived Datalen [%d]",
737                       totalDataLen, recvDataLen);
738         }
739         if (totalDataLen == recvDataLen)
740         {
741             ca_mutex_lock(g_bleAdapterReqRespCbMutex);
742             if (NULL == g_networkPacketReceivedCallback)
743             {
744                 OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
745                 OICFree(defragData);
746                 CAFreeEndpoint(remoteEndpoint);
747                 remoteEndpoint = NULL;
748                 defragData = NULL;
749                 ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
750                 ca_mutex_unlock(g_bleClientReceiveDataMutex);
751                 return;
752             }
753             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending data up !");
754             g_networkPacketReceivedCallback(remoteEndpoint, defragData, recvDataLen);
755             recvDataLen = 0;
756             totalDataLen = 0;
757             isHeaderAvailable = false;
758             OICFree(defragData);
759             CAFreeEndpoint(remoteEndpoint);
760             remoteEndpoint = NULL;
761             defragData = NULL;
762             ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
763         }
764
765         if (false == g_dataReceiverHandlerState)
766         {
767             OIC_LOG(DEBUG, CALEADAPTER_TAG, "GATTClient is terminating. Cleaning up");
768             OICFree(defragData);
769             CAFreeEndpoint(remoteEndpoint);
770             remoteEndpoint = NULL;
771             defragData = NULL;
772             ca_mutex_unlock(g_bleClientReceiveDataMutex);
773             return;
774         }
775     }
776     ca_mutex_unlock(g_bleClientReceiveDataMutex);
777     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
778 }
779
780 void CALEServerSendDataThread(void *threadData)
781 {
782     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
783
784     CALEData_t *bleData = (CALEData_t *) threadData;
785     if (!bleData)
786     {
787         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
788         return;
789     }
790
791     char *header = (char *) OICCalloc(CA_HEADER_LENGTH, sizeof(char));
792     VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "Malloc failed");
793
794     int32_t totalLength = bleData->dataLen + CA_HEADER_LENGTH;
795
796     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server total Data length with header is [%d]", totalLength);
797     char *dataSegment = (char *) OICCalloc(totalLength + 1, sizeof(char));
798     if (NULL == dataSegment)
799     {
800         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
801         OICFree(header);
802         return;
803     }
804
805     CAResult_t result = CAGenerateHeader(header, bleData->dataLen);
806     if (CA_STATUS_OK != result )
807     {
808         OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
809         OICFree(header);
810         OICFree(dataSegment);
811         return ;
812     }
813
814     memcpy(dataSegment, header, CA_HEADER_LENGTH);
815     OICFree(header);
816
817     int32_t length = 0;
818     if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
819     {
820         length = totalLength;
821         memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data, bleData->dataLen);
822     }
823     else
824     {
825         length =  CA_SUPPORTED_BLE_MTU_SIZE;
826         memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data,
827                CA_SUPPORTED_BLE_MTU_SIZE - CA_HEADER_LENGTH);
828     }
829
830     int32_t iter = totalLength / CA_SUPPORTED_BLE_MTU_SIZE;
831     int32_t index = 0;
832     // Send the first segment with the header.
833      if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
834     {
835         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Unicast Data");
836         result = CAUpdateCharacteristicsToGattClient(
837                     bleData->remoteEndpoint->addr, dataSegment, length);
838         if (CA_STATUS_OK != result)
839         {
840             OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
841             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
842             OICFree(dataSegment);
843             return;
844         }
845
846         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
847         for (index = 1; index < iter; index++)
848         {
849             // Send the remaining header.
850             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Sending the chunk number [%d]", index);
851             result = CAUpdateCharacteristicsToGattClient(
852                          bleData->remoteEndpoint->addr,
853                          bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH),
854                          CA_SUPPORTED_BLE_MTU_SIZE);
855             if (CA_STATUS_OK != result)
856             {
857                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
858                             "Update characteristics failed, result [%d]", result);
859                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
860                 OICFree(dataSegment);
861                 return;
862             }
863             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]",
864                                                CA_SUPPORTED_BLE_MTU_SIZE);
865         }
866
867         int32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
868         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
869         {
870             // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
871             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
872             result = CAUpdateCharacteristicsToGattClient(
873                          bleData->remoteEndpoint->addr,
874                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
875                          remainingLen);
876             if (CA_STATUS_OK != result)
877             {
878                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
879                                                    result);
880                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
881                 OICFree(dataSegment);
882                 return;
883             }
884             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", remainingLen);
885         }
886      }
887     else
888     {
889         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
890         result = CAUpdateCharacteristicsToAllGattClients(dataSegment, length);
891         if (CA_STATUS_OK != result)
892         {
893             OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
894                       result);
895             CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
896             OICFree(dataSegment);
897             return;
898         }
899         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
900         for (index = 1; index < iter; index++)
901         {
902             // Send the remaining header.
903             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Sending the chunk number [%d]", index);
904             result = CAUpdateCharacteristicsToAllGattClients(
905                          bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH),
906                          CA_SUPPORTED_BLE_MTU_SIZE);
907             if (CA_STATUS_OK != result)
908             {
909                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
910                           result);
911                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
912                 OICFree(dataSegment);
913                 return;
914             }
915             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", CA_SUPPORTED_BLE_MTU_SIZE);
916         }
917
918         int32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
919         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
920         {
921             // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
922             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
923             result = CAUpdateCharacteristicsToAllGattClients(
924                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
925                          remainingLen);
926             if (CA_STATUS_OK != result)
927             {
928                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
929                           result);
930                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
931                 OICFree(dataSegment);
932                 return;
933             }
934             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", remainingLen);
935         }
936     }
937     OICFree(dataSegment);
938
939     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
940 }
941
942 void CALEClientSendDataThread(void *threadData)
943 {
944     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
945
946     CALEData_t *bleData = (CALEData_t *) threadData;
947     if (!bleData)
948     {
949         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
950         return;
951     }
952
953     char *header = (char *) OICCalloc(CA_HEADER_LENGTH, sizeof(char));
954     VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "Malloc failed");
955
956     uint32_t totalLength = bleData->dataLen + CA_HEADER_LENGTH;
957     char *dataSegment = (char *) OICCalloc(totalLength + 1, sizeof(char));
958     if (NULL == dataSegment)
959     {
960         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
961         OICFree(header);
962         return;
963     }
964
965     CAResult_t result = CAGenerateHeader(header, bleData->dataLen);
966     if (CA_STATUS_OK != result )
967     {
968         OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
969         OICFree(header);
970         OICFree(dataSegment);
971         return ;
972     }
973     memcpy(dataSegment, header, CA_HEADER_LENGTH);
974     OICFree(header);
975
976     uint32_t length = 0;
977     if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
978     {
979         length = totalLength;
980         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "length [%d]", length);
981         memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data, bleData->dataLen);
982     }
983     else
984     {
985         length = CA_SUPPORTED_BLE_MTU_SIZE;
986         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "length  [%d]", length);
987         memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data,
988                CA_SUPPORTED_BLE_MTU_SIZE - CA_HEADER_LENGTH);
989     }
990
991     uint32_t iter = totalLength / CA_SUPPORTED_BLE_MTU_SIZE;
992     uint32_t index = 0;
993     if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
994     {
995         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
996         // Send the first segment with the header.
997         result = CAUpdateCharacteristicsToGattServer(bleData->remoteEndpoint->addr,
998                  dataSegment,
999                  length,
1000                  LE_UNICAST, 0);
1001
1002         if (CA_STATUS_OK != result)
1003         {
1004             OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
1005             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1006             OICFree(dataSegment);
1007             return ;
1008         }
1009
1010         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", length);
1011         for (index = 1; index < iter; index++)
1012         {
1013             // Send the remaining header.
1014             result = CAUpdateCharacteristicsToGattServer(
1015                      bleData->remoteEndpoint->addr,
1016                      bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
1017                      CA_SUPPORTED_BLE_MTU_SIZE,
1018                      LE_UNICAST, 0);
1019             if (CA_STATUS_OK != result)
1020             {
1021                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1022                                                    result);
1023                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1024                 OICFree(dataSegment);
1025                 return;
1026             }
1027             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]",
1028                                                CA_SUPPORTED_BLE_MTU_SIZE);
1029         }
1030
1031         uint32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
1032         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1033         {
1034             // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
1035             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1036             result = CAUpdateCharacteristicsToGattServer(
1037                      bleData->remoteEndpoint->addr,
1038                      bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
1039                      remainingLen,
1040                      LE_UNICAST, 0);
1041
1042             if (CA_STATUS_OK != result)
1043             {
1044                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1045                                                    result);
1046                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1047                 OICFree(dataSegment);
1048                 return;
1049             }
1050             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", remainingLen);
1051         }
1052     }
1053     else
1054     {
1055         //Sending Mulitcast Data
1056         // Send the first segment with the header.
1057         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Multicast Data");
1058         result = CAUpdateCharacteristicsToAllGattServers(dataSegment, length);
1059         if (CA_STATUS_OK != result)
1060         {
1061             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1062                       "Update characteristics (all) failed, result [%d]", result);
1063             CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1064             OICFree(dataSegment);
1065             return ;
1066         }
1067         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", length);
1068         // Send the remaining header.
1069         for (index = 1; index < iter; index++)
1070         {
1071             result = CAUpdateCharacteristicsToAllGattServers(
1072                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
1073                          CA_SUPPORTED_BLE_MTU_SIZE);
1074             if (CA_STATUS_OK != result)
1075             {
1076                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics (all) failed, result [%d]",
1077                           result);
1078                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1079                 OICFree(dataSegment);
1080                 return;
1081             }
1082             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]",
1083                       CA_SUPPORTED_BLE_MTU_SIZE);
1084         }
1085
1086         uint32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
1087         if ( remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1088         {
1089             // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
1090             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1091             result = CAUpdateCharacteristicsToAllGattServers(
1092                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
1093                           remainingLen);
1094             if (CA_STATUS_OK != result)
1095             {
1096                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1097                           "Update characteristics (all) failed, result [%d]", result);
1098                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1099                 OICFree(dataSegment);
1100                 return;
1101             }
1102             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", remainingLen);
1103         }
1104
1105     }
1106
1107     OICFree(dataSegment);
1108
1109     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CABLEClientSendDataThread");
1110 }
1111
1112 CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint, const void *data,
1113                            uint32_t dataLength)
1114 {
1115     CALEData_t *bleData = (CALEData_t *) OICMalloc(sizeof(CALEData_t));
1116     if (!bleData)
1117     {
1118         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1119         return NULL;
1120     }
1121
1122     bleData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
1123     bleData->data = (void *)OICCalloc(dataLength + 1, 1);
1124     if (NULL == bleData->data)
1125     {
1126         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1127         CAFreeLEData(bleData);
1128         return NULL;
1129     }
1130     memcpy(bleData->data, data, dataLength);
1131     bleData->dataLen = dataLength;
1132
1133     return bleData;
1134 }
1135
1136 void CAFreeLEData(CALEData_t *bleData)
1137 {
1138     VERIFY_NON_NULL_VOID(bleData, CALEADAPTER_TAG, "Param bleData is NULL");
1139
1140     CAFreeEndpoint(bleData->remoteEndpoint);
1141     OICFree(bleData->data);
1142     OICFree(bleData);
1143 }
1144
1145 void CALEDataDestroyer(void *data, uint32_t size)
1146 {
1147     CALEData_t *ledata = (CALEData_t *) data;
1148
1149     CAFreeLEData(ledata);
1150 }
1151 #endif
1152
1153 CAResult_t CAInitLEAdapterMutex()
1154 {
1155     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1156
1157     if (NULL == g_bleIsServerMutex)
1158     {
1159         g_bleIsServerMutex = ca_mutex_new();
1160         if (NULL == g_bleIsServerMutex)
1161         {
1162             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1163             return CA_STATUS_FAILED;
1164         }
1165     }
1166
1167     if (NULL == g_bleNetworkCbMutex)
1168     {
1169         g_bleNetworkCbMutex = ca_mutex_new();
1170         if (NULL == g_bleNetworkCbMutex)
1171         {
1172             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1173             CATerminateLEAdapterMutex();
1174             return CA_STATUS_FAILED;
1175         }
1176     }
1177
1178     if (NULL == g_bleLocalAddressMutex)
1179     {
1180         g_bleLocalAddressMutex = ca_mutex_new();
1181         if (NULL == g_bleLocalAddressMutex)
1182         {
1183             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1184             CATerminateLEAdapterMutex();
1185             return CA_STATUS_FAILED;
1186         }
1187     }
1188
1189     if (NULL == g_bleAdapterThreadPoolMutex)
1190     {
1191         g_bleAdapterThreadPoolMutex = ca_mutex_new();
1192         if (NULL == g_bleAdapterThreadPoolMutex)
1193         {
1194             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1195             CATerminateLEAdapterMutex();
1196             return CA_STATUS_FAILED;
1197         }
1198     }
1199
1200     if (NULL == g_bleClientSendDataMutex)
1201     {
1202         g_bleClientSendDataMutex = ca_mutex_new();
1203         if (NULL == g_bleClientSendDataMutex)
1204         {
1205             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1206             CATerminateLEAdapterMutex();
1207             return CA_STATUS_FAILED;
1208         }
1209     }
1210
1211     if (NULL == g_bleClientReceiveDataMutex)
1212     {
1213         g_bleClientReceiveDataMutex = ca_mutex_new();
1214         if (NULL == g_bleClientReceiveDataMutex)
1215         {
1216             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1217             CATerminateLEAdapterMutex();
1218             return CA_STATUS_FAILED;
1219         }
1220     }
1221
1222     if (NULL == g_bleServerSendDataMutex)
1223     {
1224         g_bleServerSendDataMutex = ca_mutex_new();
1225         if (NULL == g_bleServerSendDataMutex)
1226         {
1227             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1228             CATerminateLEAdapterMutex();
1229             return CA_STATUS_FAILED;
1230         }
1231     }
1232
1233     if (NULL == g_bleServerReceiveDataMutex)
1234     {
1235         g_bleServerReceiveDataMutex = ca_mutex_new();
1236         if (NULL == g_bleServerReceiveDataMutex)
1237         {
1238             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1239             CATerminateLEAdapterMutex();
1240             return CA_STATUS_FAILED;
1241         }
1242     }
1243
1244     if (NULL == g_bleAdapterReqRespCbMutex)
1245     {
1246         g_bleAdapterReqRespCbMutex = ca_mutex_new();
1247         if (NULL == g_bleAdapterReqRespCbMutex)
1248         {
1249             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1250             CATerminateLEAdapterMutex();
1251             return CA_STATUS_FAILED;
1252         }
1253     }
1254
1255     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1256     return CA_STATUS_OK;
1257 }
1258
1259 void CATerminateLEAdapterMutex()
1260 {
1261     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1262
1263     ca_mutex_free(g_bleIsServerMutex);
1264     g_bleIsServerMutex = NULL;
1265
1266     ca_mutex_free(g_bleNetworkCbMutex);
1267     g_bleNetworkCbMutex = NULL;
1268
1269     ca_mutex_free(g_bleLocalAddressMutex);
1270     g_bleLocalAddressMutex = NULL;
1271
1272     ca_mutex_free(g_bleAdapterThreadPoolMutex);
1273     g_bleAdapterThreadPoolMutex = NULL;
1274
1275     ca_mutex_free(g_bleClientSendDataMutex);
1276     g_bleClientSendDataMutex = NULL;
1277
1278     ca_mutex_free(g_bleClientReceiveDataMutex);
1279     g_bleClientReceiveDataMutex = NULL;
1280
1281     ca_mutex_free(g_bleServerSendDataMutex);
1282     g_bleServerSendDataMutex = NULL;
1283
1284     ca_mutex_free(g_bleServerReceiveDataMutex);
1285     g_bleServerReceiveDataMutex = NULL;
1286
1287     ca_mutex_free(g_bleAdapterReqRespCbMutex);
1288     g_bleAdapterReqRespCbMutex = NULL;
1289
1290     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1291 }
1292
1293 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
1294                           CANetworkPacketReceivedCallback reqRespCallback,
1295                           CANetworkChangeCallback netCallback,
1296                           CAErrorHandleCallback errorCallback, ca_thread_pool_t handle)
1297 {
1298     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1299
1300     //Input validation
1301     VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null");
1302     VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null");
1303     VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null");
1304
1305     CAResult_t result = CA_STATUS_OK;
1306     result = CAInitLEAdapterMutex();
1307     if (CA_STATUS_OK != result)
1308     {
1309         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
1310         return CA_STATUS_FAILED;
1311     }
1312     result = CAInitializeLENetworkMonitor();
1313     if (CA_STATUS_OK != result)
1314     {
1315         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
1316         return CA_STATUS_FAILED;
1317     }
1318
1319     CAInitializeLEAdapter();
1320
1321     CASetLEClientThreadPoolHandle(handle);
1322     CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
1323     CASetLEServerThreadPoolHandle(handle);
1324     CASetLEAdapterThreadPoolHandle(handle);
1325     CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
1326     CASetLEReqRespAdapterCallback(reqRespCallback);
1327
1328     CASetBLEClientErrorHandleCallback(CALEErrorHandler);
1329     CASetBLEServerErrorHandleCallback(CALEErrorHandler);
1330     CALERegisterNetworkNotifications(netCallback);
1331
1332     g_errorHandler = errorCallback;
1333
1334     CAConnectivityHandler_t connHandler;
1335     connHandler.startAdapter = CAStartLE;
1336     connHandler.stopAdapter = CAStopLE;
1337     connHandler.startListenServer = CAStartLEListeningServer;
1338     connHandler.startDiscoveryServer = CAStartLEDiscoveryServer;
1339     connHandler.sendData = CASendLEUnicastData;
1340     connHandler.sendDataToAll = CASendLEMulticastData;
1341     connHandler.GetnetInfo = CAGetLEInterfaceInformation;
1342     connHandler.readData = CAReadLEData;
1343     connHandler.terminate = CATerminateLE;
1344     registerCallback(connHandler, CA_ADAPTER_GATT_BTLE);
1345
1346     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1347
1348     return CA_STATUS_OK;
1349 }
1350
1351 CAResult_t CAStartLE()
1352 {
1353     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1354     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAStartLE, not implemented");
1355     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1356     return CA_STATUS_OK;
1357 }
1358
1359 CAResult_t CAStopLE()
1360 {
1361     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1362 #ifndef SINGLE_THREAD
1363     CAStopLEQueues();
1364 #endif
1365
1366     ca_mutex_lock(g_bleIsServerMutex);
1367     if (true == g_isServer)
1368     {
1369         CAStopLEGattServer();
1370     }
1371     else
1372     {
1373         CAStopLEGattClient();
1374     }
1375     ca_mutex_unlock(g_bleIsServerMutex);
1376
1377     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1378
1379     return CA_STATUS_OK;
1380 }
1381
1382 void CATerminateLE()
1383 {
1384     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1385
1386     CASetLEReqRespServerCallback(NULL);
1387     CASetLEReqRespClientCallback(NULL);
1388     CALERegisterNetworkNotifications(NULL);
1389     CASetLEReqRespAdapterCallback(NULL);
1390     CATerminateLENetworkMonitor();
1391
1392     ca_mutex_lock(g_bleIsServerMutex);
1393     if (true == g_isServer)
1394     {
1395         CATerminateLEGattServer();
1396     }
1397     else
1398     {
1399         CATerminateLEGattClient();
1400     }
1401     ca_mutex_unlock(g_bleIsServerMutex);
1402
1403 #ifndef SINGLE_THREAD
1404     CATerminateLEQueues();
1405 #endif
1406     CATerminateLEAdapterMutex();
1407
1408     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1409 }
1410
1411 CAResult_t CAStartLEListeningServer()
1412 {
1413     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1414     CAResult_t result = CA_STATUS_OK;
1415 #ifndef SINGLE_THREAD
1416     result = CAInitLEServerQueues();
1417     if (CA_STATUS_OK != result)
1418     {
1419         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
1420         return CA_STATUS_FAILED;
1421     }
1422 #endif
1423
1424     result = CAGetLEAdapterState();
1425     if (CA_ADAPTER_NOT_ENABLED == result)
1426     {
1427         gLeServerStatus = CA_LISTENING_SERVER;
1428         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
1429         return CA_STATUS_OK;
1430     }
1431
1432     if (CA_STATUS_FAILED == result)
1433     {
1434         OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
1435         return CA_STATUS_FAILED;
1436     }
1437
1438     CAStartLEGattServer();
1439
1440     ca_mutex_lock(g_bleIsServerMutex);
1441     g_isServer = true;
1442     ca_mutex_unlock(g_bleIsServerMutex);
1443
1444     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1445     return CA_STATUS_OK;
1446 }
1447
1448 CAResult_t CAStartLEDiscoveryServer()
1449 {
1450     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1451     CAResult_t result = CA_STATUS_OK;
1452 #ifndef SINGLE_THREAD
1453     result = CAInitLEClientQueues();
1454     if (CA_STATUS_OK != result)
1455     {
1456         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
1457         return CA_STATUS_FAILED;
1458     }
1459 #endif
1460     result = CAGetLEAdapterState();
1461     if (CA_ADAPTER_NOT_ENABLED == result)
1462     {
1463         gLeServerStatus = CA_DISCOVERY_SERVER;
1464         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
1465         return CA_STATUS_OK;
1466     }
1467
1468     if (CA_STATUS_FAILED == result)
1469     {
1470         OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
1471         return CA_STATUS_FAILED;
1472     }
1473
1474     CAStartLEGattClient();
1475
1476     ca_mutex_lock(g_bleIsServerMutex);
1477     g_isServer = false;
1478     ca_mutex_unlock(g_bleIsServerMutex);
1479
1480     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1481     return CA_STATUS_OK;
1482 }
1483
1484 CAResult_t CAStartLENotifyServer()
1485 {
1486     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1487
1488     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1489     return CA_STATUS_OK;
1490 }
1491
1492 uint32_t CASendLENotification(const CAEndpoint_t *endpoint, const void *data,
1493                               uint32_t dataLen)
1494 {
1495     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1496
1497     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1498     return 0;
1499 }
1500
1501 CAResult_t CAReadLEData()
1502 {
1503     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1504 #ifdef SINGLE_THREAD
1505     CACheckLEData();
1506 #endif
1507     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1508     return CA_STATUS_OK;
1509 }
1510
1511 int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen)
1512 {
1513     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1514
1515     //Input validation
1516     VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
1517     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
1518
1519     CAResult_t result = CA_STATUS_FAILED;
1520
1521     ca_mutex_lock(g_bleIsServerMutex);
1522     if (true  == g_isServer)
1523     {
1524         result = CALEAdapterServerSendData(endpoint, data, dataLen);
1525         if (CA_STATUS_OK != result)
1526         {
1527             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data failed\n");
1528             if (g_errorHandler)
1529             {
1530                 g_errorHandler((void *) endpoint, (void *) data, dataLen, result);
1531             }
1532             ca_mutex_unlock(g_bleIsServerMutex);
1533             return -1;
1534         }
1535     }
1536     else
1537     {
1538         result = CALEAdapterClientSendData(endpoint, data, dataLen);
1539         if (CA_STATUS_OK != result)
1540         {
1541             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data failed \n");
1542             if (g_errorHandler)
1543             {
1544                 g_errorHandler(endpoint, data, dataLen, result);
1545             }
1546             ca_mutex_unlock(g_bleIsServerMutex);
1547             return -1;
1548         }
1549     }
1550     ca_mutex_unlock(g_bleIsServerMutex);
1551
1552     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1553     return dataLen;
1554 }
1555
1556 int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen)
1557 {
1558     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1559
1560     //Input validation
1561     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
1562
1563     if (0 >= dataLen)
1564     {
1565         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
1566         return -1;
1567     }
1568
1569     CAResult_t result = CA_STATUS_FAILED;
1570
1571     ca_mutex_lock(g_bleIsServerMutex);
1572     if (true  == g_isServer)
1573     {
1574         result = CALEAdapterServerSendData(NULL, data, dataLen);
1575         if (CA_STATUS_OK != result)
1576         {
1577             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data failed" );
1578
1579             ca_mutex_unlock(g_bleIsServerMutex);
1580             if (g_errorHandler)
1581             {
1582                 g_errorHandler(endpoint, data, dataLen, result);
1583             }
1584             return -1;
1585         }
1586     }
1587     else
1588     {
1589         result = CALEAdapterClientSendData(NULL, data, dataLen);
1590         if (CA_STATUS_OK != result)
1591         {
1592             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data failed" );
1593             if (g_errorHandler)
1594             {
1595                 g_errorHandler(endpoint, data, dataLen, result);
1596             }
1597             ca_mutex_unlock(g_bleIsServerMutex);
1598             return -1;
1599         }
1600     }
1601     ca_mutex_unlock(g_bleIsServerMutex);
1602
1603     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1604     return dataLen;
1605 }
1606
1607 CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1608 {
1609     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1610
1611     VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
1612
1613     char *local_address = NULL;
1614
1615     CAResult_t res = CAGetLEAddress(&local_address);
1616     if (CA_STATUS_OK != res)
1617     {
1618         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
1619         return res;
1620     }
1621
1622     if (NULL == local_address)
1623     {
1624         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
1625         return CA_STATUS_FAILED;
1626     }
1627
1628     *size = 0;
1629     (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
1630     if (NULL == (*info))
1631     {
1632         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
1633         OICFree(local_address);
1634         return CA_STATUS_FAILED;
1635     }
1636
1637     size_t local_address_len = strlen(local_address);
1638
1639     if(local_address_len >= sizeof(g_localBLEAddress) ||
1640             local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
1641     {
1642         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
1643         OICFree(*info);
1644         OICFree(local_address);
1645         return CA_STATUS_FAILED;
1646     }
1647
1648     OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
1649     ca_mutex_lock(g_bleLocalAddressMutex);
1650     OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
1651     ca_mutex_unlock(g_bleLocalAddressMutex);
1652
1653     (*info)->adapter = CA_ADAPTER_GATT_BTLE;
1654     *size = 1;
1655     OICFree(local_address);
1656
1657     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1658     return CA_STATUS_OK;
1659 }
1660
1661 CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback)
1662 {
1663     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1664
1665     ca_mutex_lock(g_bleNetworkCbMutex);
1666     g_networkCallback = netCallback;
1667     ca_mutex_unlock(g_bleNetworkCbMutex);
1668     CAResult_t res = CA_STATUS_OK;
1669     if (netCallback)
1670     {
1671         res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
1672         if (CA_STATUS_OK != res)
1673         {
1674             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
1675         }
1676     }
1677     else
1678     {
1679         res = CAUnSetLEAdapterStateChangedCb();
1680         if (CA_STATUS_OK != res)
1681         {
1682             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
1683         }
1684     }
1685
1686     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1687     return res;
1688 }
1689
1690 void CALEDeviceStateChangedCb( CAAdapterState_t adapter_state)
1691 {
1692     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1693
1694     VERIFY_NON_NULL_VOID(g_localBLEAddress, CALEADAPTER_TAG, "g_localBLEAddress is null");
1695     CAEndpoint_t localEndpoint = {};
1696
1697     ca_mutex_lock(g_bleLocalAddressMutex);
1698     OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), g_localBLEAddress);
1699     ca_mutex_unlock(g_bleLocalAddressMutex);
1700
1701     g_bleAdapterState = adapter_state;
1702     // Start a GattServer/Client if gLeServerStatus is SET
1703     if (CA_LISTENING_SERVER == gLeServerStatus)
1704     {
1705         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartLEGattServer");
1706         CAStartLEGattServer();
1707     }
1708     else if (CA_DISCOVERY_SERVER == gLeServerStatus)
1709     {
1710         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartBleGattClient");
1711         CAStartLEGattClient();
1712     }
1713     gLeServerStatus = CA_SERVER_NOTSTARTED;
1714
1715     ca_mutex_lock(g_bleNetworkCbMutex);
1716     if (NULL != g_networkCallback)
1717     {
1718         g_networkCallback(&localEndpoint, adapter_state);
1719     }
1720     else
1721     {
1722         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
1723     }
1724     ca_mutex_unlock(g_bleNetworkCbMutex);
1725
1726     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1727 }
1728
1729 CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
1730                                      const void *data,
1731                                      uint32_t dataLen)
1732 {
1733     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1734
1735     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1736 #ifndef SINGLE_THREAD
1737     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
1738                         "g_bleClientSendQueueHandle is  NULL",
1739                         CA_STATUS_FAILED);
1740     VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
1741                         "g_bleClientSendDataMutex is NULL",
1742                         CA_STATUS_FAILED);
1743
1744     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG, "g_bleClientSendQueueHandle",
1745                         CA_STATUS_FAILED);
1746
1747     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
1748
1749     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen);
1750     if (!bleData)
1751     {
1752         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
1753         return CA_MEMORY_ALLOC_FAILED;
1754     }
1755     // Add message to send queue
1756     ca_mutex_lock(g_bleClientSendDataMutex);
1757     CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData, sizeof(CALEData_t));
1758     ca_mutex_unlock(g_bleClientSendDataMutex);
1759 #endif
1760     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1761     return CA_STATUS_OK;
1762 }
1763
1764
1765 CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
1766                                      const void *data,
1767                                      uint32_t dataLen)
1768 {
1769     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1770
1771     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1772
1773 #ifdef SINGLE_THREAD
1774     char header[CA_HEADER_LENGTH] = {0};
1775
1776     CAResult_t result = CAGenerateHeader(header, dataLen);
1777
1778     if (CA_STATUS_OK != result)
1779     {
1780         OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
1781         return -1;
1782     }
1783
1784     if (!CAIsLEConnected())
1785     {
1786         OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
1787         return -1;
1788     }
1789
1790     result = CAUpdateCharacteristicsToAllGattClients(header, CA_HEADER_LENGTH);
1791     if (CA_STATUS_OK != result)
1792     {
1793         OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
1794         return -1;
1795     }
1796
1797     int32_t dataLimit = dataLen / CA_SUPPORTED_BLE_MTU_SIZE;
1798     for (int32_t iter = 0; iter < dataLimit; iter++)
1799     {
1800         result = CAUpdateCharacteristicsToAllGattClients((data +
1801                                                          (iter * CA_SUPPORTED_BLE_MTU_SIZE)),
1802                                                          CA_SUPPORTED_BLE_MTU_SIZE);
1803         if (CA_STATUS_OK != result)
1804         {
1805             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
1806             return -1;
1807         }
1808         CALEDoEvents();
1809     }
1810
1811     uint8_t remainingLen = dataLen % CA_SUPPORTED_BLE_MTU_SIZE;
1812     if(remainingLen)
1813     {
1814         result = CAUpdateCharacteristicsToAllGattClients((data +
1815                                                          (dataLimit * CA_SUPPORTED_BLE_MTU_SIZE)),
1816                                                          remainingLen);
1817         if (CA_STATUS_OK != result)
1818         {
1819             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
1820             return -1;
1821         }
1822         CALEDoEvents();
1823     }
1824 #else
1825     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
1826                         "BleClientReceiverQueue is NULL",
1827                         CA_STATUS_FAILED);
1828     VERIFY_NON_NULL_RET(g_bleServerSendDataMutex, CALEADAPTER_TAG,
1829                         "BleClientSendDataMutex is NULL",
1830                         CA_STATUS_FAILED);
1831
1832     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG, "sendQueueHandle",
1833                         CA_STATUS_FAILED);
1834
1835     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
1836
1837     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen);
1838     if (!bleData)
1839     {
1840         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
1841         return CA_MEMORY_ALLOC_FAILED;
1842     }
1843     // Add message to send queue
1844     ca_mutex_lock(g_bleServerSendDataMutex);
1845     CAQueueingThreadAddData(g_bleServerSendQueueHandle, bleData, sizeof(CALEData_t));
1846     ca_mutex_unlock(g_bleServerSendDataMutex);
1847 #endif
1848     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1849     return CA_STATUS_OK;
1850 }
1851
1852 CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress, const char *serviceUUID,
1853                                          const void *data, uint32_t dataLength,
1854                                          uint32_t *sentLength)
1855 {
1856     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1857
1858     //Input validation
1859     VERIFY_NON_NULL(serviceUUID, CALEADAPTER_TAG, "service UUID is null");
1860     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
1861     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
1862
1863 #ifdef SINGLE_THREAD
1864     if(g_networkPacketReceivedCallback)
1865     {
1866         CAEndpoint_t endPoint = { 0 };   // will be filled by upper layer
1867         endPoint.adapter = CA_ADAPTER_GATT_BTLE;
1868         g_networkPacketReceivedCallback(&endPoint, data, dataLength);
1869     }
1870 #else
1871     VERIFY_NON_NULL_RET(g_bleServerReceiverQueue, CALEADAPTER_TAG, "g_bleServerReceiverQueue",
1872                         CA_STATUS_FAILED);
1873
1874     //Add message to data queue
1875     CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
1876                                                           CA_ADAPTER_GATT_BTLE,
1877                                                           remoteAddress, 0);
1878     if (NULL == remoteEndpoint)
1879     {
1880         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
1881         return CA_STATUS_FAILED;
1882     }
1883
1884     // Create bleData to add to queue
1885     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%d]", dataLength);
1886
1887     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLength);
1888     if (!bleData)
1889     {
1890         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
1891         CAFreeEndpoint(remoteEndpoint);
1892         return CA_MEMORY_ALLOC_FAILED;
1893     }
1894
1895     CAFreeEndpoint(remoteEndpoint);
1896     // Add message to send queue
1897     CAQueueingThreadAddData(g_bleServerReceiverQueue, bleData, sizeof(CALEData_t));
1898
1899     *sentLength = dataLength;
1900 #endif
1901     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1902     return CA_STATUS_OK;
1903 }
1904
1905 CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress, const char *serviceUUID,
1906                                          const void *data, uint32_t dataLength,
1907                                          uint32_t *sentLength)
1908 {
1909     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1910
1911     //Input validation
1912     VERIFY_NON_NULL(serviceUUID, CALEADAPTER_TAG, "service UUID is null");
1913     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
1914     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
1915 #ifndef SINGLE_THREAD
1916     VERIFY_NON_NULL_RET(g_bleClientReceiverQueue, CALEADAPTER_TAG, "g_bleClientReceiverQueue",
1917                         CA_STATUS_FAILED);
1918
1919     //Add message to data queue
1920     CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
1921                                                           CA_ADAPTER_GATT_BTLE,
1922                                                           remoteAddress, 0);
1923     if (NULL == remoteEndpoint)
1924     {
1925         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
1926         return CA_STATUS_FAILED;
1927     }
1928
1929     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%d]", dataLength);
1930
1931     // Create bleData to add to queue
1932     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLength);
1933     if (!bleData)
1934     {
1935         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
1936         CAFreeEndpoint(remoteEndpoint);
1937         return CA_MEMORY_ALLOC_FAILED;
1938     }
1939
1940     CAFreeEndpoint(remoteEndpoint);
1941     // Add message to send queue
1942     CAQueueingThreadAddData(g_bleClientReceiverQueue, bleData, sizeof(CALEData_t));
1943
1944     *sentLength = dataLength;
1945 #endif
1946     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1947     return CA_STATUS_OK;
1948 }
1949
1950 void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
1951 {
1952     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1953
1954     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
1955     g_bleAdapterThreadPool = handle;
1956     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
1957
1958     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1959 }
1960
1961 void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
1962 {
1963     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1964
1965     ca_mutex_lock(g_bleAdapterReqRespCbMutex);
1966
1967     g_networkPacketReceivedCallback = callback;
1968
1969     ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
1970
1971     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1972 }
1973
1974 void CALEErrorHandler(const char *remoteAddress, const void *data, uint32_t dataLen,
1975                       CAResult_t result)
1976 {
1977     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler IN");
1978
1979     VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
1980     CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS, CA_ADAPTER_GATT_BTLE,
1981                                                remoteAddress, 0);
1982     //if required, will be used to build remote end point
1983     g_errorHandler(rep, data, dataLen, result);
1984
1985     CAFreeEndpoint(rep);
1986     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler OUT");
1987 }