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