9b26415729ae7b3ecae1bf0fec35cc7e0fe5b6b7
[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 "cafragmentation.h"
26
27 #include "caleinterface.h"
28 #include "cacommon.h"
29 #include "octhread.h"
30 #include "caadapterutils.h"
31 #ifdef __WITH_DTLS__
32 #include "ca_adapter_net_ssl.h"
33 #endif
34 #ifndef SINGLE_THREAD
35 #include "caqueueingthread.h"
36 #endif
37 #if defined(__TIZEN__) || defined(__ANDROID__)
38 #include "caleserver.h"
39 #include "caleclient.h"
40 #endif
41 #include "oic_malloc.h"
42 #include "oic_string.h"
43 #include "caremotehandler.h"
44 #include <coap/pdu.h>
45
46 /**
47  * Logging tag for module name.
48  */
49 #define CALEADAPTER_TAG "OIC_CA_LE_ADAP"
50
51 /**
52  * Stores information of all the senders.
53  *
54  * This structure will be used to track and defragment all incoming data packet.
55  */
56 typedef struct
57 {
58     uint32_t recvDataLen;
59     uint32_t totalDataLen;
60     uint8_t *defragData;
61     CAEndpoint_t *remoteEndpoint;
62  } CABLESenderInfo_t;
63
64 typedef enum
65 {
66     ADAPTER_EMPTY = 1,
67     ADAPTER_BOTH_CLIENT_SERVER,
68     ADAPTER_CLIENT,
69     ADAPTER_SERVER
70 } CABLEAdapter_t;
71
72 /**
73  * mtu size to use in fragmentation logic.
74  * default value is 20 byte.
75  */
76 static uint16_t g_mtuSize = CA_DEFAULT_BLE_MTU_SIZE;
77 /**
78  * Callback to provide the status of the network change to CA layer.
79  */
80 static CAAdapterChangeCallback g_networkCallback = NULL;
81
82 /**
83  * Callback to provide the status of the connection change to CA layer.
84  */
85 static CAConnectionChangeCallback g_connectionCallback = NULL;
86
87 /**
88  * Own port value to identify packet owner. Default port value is 1.
89  */
90 static uint8_t g_localBLESourcePort = 1;
91
92 /**
93  * bleAddress of the local adapter. Value will be initialized to zero,
94  * and will be updated later.
95  */
96 static char g_localBLEAddress[18] = { 0 };
97
98 /**
99  * Variable to differentiate btw GattServer and GattClient.
100  */
101 static CABLEAdapter_t g_adapterType = ADAPTER_EMPTY;
102
103 #ifdef __WITH_DTLS__
104 /**
105  * Variable for storing data type during dtls encryption.
106  */
107 static CADataType_t g_dataType = CA_REQUEST_DATA;
108 #endif
109
110 /**
111  * Mutex to synchronize the task to be executed on the GattServer
112  * function calls.
113  */
114 static oc_mutex g_bleIsServerMutex = NULL;
115
116 /**
117  * Mutex to synchronize the callback to be called for the network
118  * changes.
119  */
120 static oc_mutex g_bleNetworkCbMutex = NULL;
121
122 /**
123  * Mutex to synchronize the updates of the local LE address of the
124  * adapter.
125  */
126 static oc_mutex g_bleLocalAddressMutex = NULL;
127
128 /**
129  * Reference to thread pool.
130  */
131 static ca_thread_pool_t g_bleAdapterThreadPool = NULL;
132
133 /**
134  * Mutex to synchronize the task to be pushed to thread pool.
135  */
136 static oc_mutex g_bleAdapterThreadPoolMutex = NULL;
137
138 /**
139  * Mutex to synchronize the queing of the data from SenderQueue.
140  */
141 static oc_mutex g_bleClientSendDataMutex = NULL;
142
143 /**
144  * Mutex to synchronize the queing of the data from ReceiverQueue.
145  */
146 static oc_mutex g_bleClientReceiveDataMutex = NULL;
147
148 /**
149  * Mutex to synchronize the queing of the data from SenderQueue.
150  */
151 static oc_mutex g_bleServerSendDataMutex = NULL;
152
153 /**
154  * Mutex to synchronize the queing of the data from ReceiverQueue.
155  */
156 static oc_mutex g_bleServerReceiveDataMutex = NULL;
157
158 /**
159  * Mutex to synchronize the callback to be called for the
160  * adapterReqResponse.
161  */
162 static oc_mutex g_bleAdapterReqRespCbMutex = NULL;
163
164 /**
165  * Callback to be called when network packet received from either
166  * GattServer or GattClient.
167  */
168 static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
169
170 /**
171  * Callback to notify error from the BLE adapter.
172  */
173 static CAErrorHandleCallback g_errorHandler = NULL;
174
175 #ifdef __WITH_DTLS__
176 /**
177  * Callback to receive decrypted data from the ssl adapter.
178  */
179 static void CALESecureReceiveDataCB(const CASecureEndpoint_t *sep,
180                                  const void *data, size_t dataLen);
181
182 /**
183  * Callback to receive encrypted data from the ssl adapter.
184  */
185 static ssize_t CALESecureSendDataCB(CAEndpoint_t *endpoint,
186                              const void *data, size_t dataLen);
187 #endif
188
189 #ifdef SINGLE_THREAD
190 /**
191  * Pointer to defragment received data from single threaded routine.
192  */
193 static CABLESenderInfo_t *g_singleThreadReceiveData = NULL;
194
195 /**
196  * This function will be associated with the receive for single thread.
197  *
198  * This function will defragment the received data from sender
199  * respectively and will send it up to CA layer. Respective sender's
200  * header will provide the length of the data sent.
201  *
202  * @param[in] data       Actual data received from the remote
203  *                       device.
204  * @param[in] dataLen    Length of the data received from the
205  *                       remote device.
206  */
207 static void CALEDataReceiverHandlerSingleThread(const uint8_t *data,
208                                                 uint32_t dataLen);
209
210 /**
211  * This function will be associated with the send for single threaded
212  * GattServer.
213  *
214  * This function will fragment the data to the MTU of the transport
215  * and send the data in fragments to the adapters. The function will
216  * be blocked until all data is sent out from the adapter.
217  *
218  * @param[in] data       Data to be transmitted from LE.
219  * @param[in] dataLen    Length of the Data being transmitted.
220  */
221 static CAResult_t CALEServerSendDataSingleThread(const uint8_t *data,
222                                                  uint32_t dataLen);
223 #endif
224
225 /**
226  * Register network change notification callback.
227  *
228  * @param[in]  netCallback  CAAdapterChangeCallback callback which will
229  *                          be set for the change in adapter.
230  * @param[in]  connCallback CAConnectionChangeCallback callback which will
231  *                          be set for the change in connection.
232  *
233  * @return  0 on success otherwise a positive error value.
234  * @retval  ::CA_STATUS_OK  Successful.
235  * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
236  * @retval  ::CA_STATUS_FAILED Operation failed.
237  *
238  */
239 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
240                                                    CAConnectionChangeCallback connCallback);
241
242 /**
243  * Set the thread pool handle which is required for spawning new
244  * thread.
245  *
246  * @param[in] handle Thread pool handle which is given by above layer
247  *                   for using thread creation task.
248  *
249  */
250 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle);
251
252 /**
253  * Call the callback to the upper layer when the adapter state gets
254  * changed.
255  *
256  * @param[in] adapter_state New state of the adapter to be notified to
257  *                          the upper layer.
258  */
259 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state);
260
261 /**
262  * Call the callback to the upper layer when the device connection state gets
263  * changed.
264  *
265  * @param[in] address      LE address of the device to be notified to the upper layer.
266  * @param[in] isConnected  whether connection state is connected or not.
267  */
268 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
269                                          bool isConnected);
270
271 /**
272  * Used to initialize all required mutex variable for LE Adapter
273  * implementation.
274  *
275  * @return  0 on success otherwise a positive error value.
276  * @retval  ::CA_STATUS_OK  Successful.
277  * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
278  * @retval  ::CA_STATUS_FAILED Operation failed.
279  *
280  */
281 static CAResult_t CAInitLEAdapterMutex();
282
283 /**
284  * Terminate all required mutex variables for LE adapter
285  * implementation.
286  */
287 static void CATerminateLEAdapterMutex();
288
289 /**
290  * Prepares and notify error through error callback.
291  */
292 static void CALEErrorHandler(const char *remoteAddress,
293                              const uint8_t *data,
294                              uint32_t dataLen,
295                              CAResult_t result);
296
297 #ifndef SINGLE_THREAD
298 /**
299  * Stop condition of Server recvhandler.
300  */
301 static bool g_dataBleServerReceiverHandlerState = false;
302
303 /**
304  * Stop condition of Client recvhandler.
305  */
306 static bool g_dataBleClientReceiverHandlerState = false;
307
308 /**
309  * Sender information of Server.
310  */
311 static u_arraylist_t *g_bleServerSenderInfo = NULL;
312
313 /**
314  * Sender information of Client.
315  */
316 static u_arraylist_t *g_bleClientSenderInfo = NULL;
317
318 /**
319  * Queue to process the outgoing packets from GATTServer.
320  */
321 static CAQueueingThread_t *g_bleServerSendQueueHandle = NULL;
322
323 /**
324  * Queue to process the outgoing packets from GATTClient.
325  */
326 static CAQueueingThread_t *g_bleClientSendQueueHandle = NULL;
327
328 /**
329  * Queue to process the incoming packets from GATTServer.
330  */
331 static CAQueueingThread_t *g_bleServerReceiverQueue = NULL;
332
333 /**
334  * Queue to process the incoming packets from GATTClient.
335  */
336 static CAQueueingThread_t *g_bleClientReceiverQueue = NULL;
337
338 /**
339  * This function will be associated with the sender queue for
340  * GattServer.
341  *
342  * This function will fragment the data to the MTU of the transport
343  * and send the data in fragments to the adapters. The function will
344  * be blocked until all data is sent out from the adapter.
345  *
346  * @param[in] threadData Data pushed to the queue which contains the
347  *                       info about RemoteEndpoint and Data.
348  */
349 static void CALEServerSendDataThread(void *threadData);
350
351 /**
352  * This function will be associated with the sender queue for
353  * GattClient.
354  *
355  * This function will fragment the data to the MTU of the transport
356  * and send the data in fragments to the adapters. The function will
357  * be blocked until all data is sent out from the adapter.
358  *
359  * @param[in] threadData Data pushed to the queue which contains the
360  *                       info about RemoteEndpoint and Data.
361  */
362 static void CALEClientSendDataThread(void *threadData);
363
364 /**
365  * This function will defragment the received data from each sender
366  * respectively and will send it up to CA layer.  Respective sender's
367  * header will provide the length of the data sent.
368  *
369  * @param[in] threadData   Data pushed to the queue which contains the
370  *                         info about RemoteEndpoint and Data.
371  * @param[in] receiverType Whether receiver is server or client.
372  */
373 static void CALEDataReceiverHandler(void *threadData, CABLEAdapter_t receiverType);
374
375 /**
376  * This function will be associated with the receiver queue for
377  * GattServer.
378  *
379  * This function will call the function CALEDataReceiverHandler()
380  * with server type to defragment the received data.
381  *
382  * @param[in] threadData Data pushed to the queue which contains the
383  *                       info about RemoteEndpoint and Data.
384  */
385 static void CALEServerDataReceiverHandler(void *threadData);
386
387 /**
388  * This function will be associated with the receiver queue for
389  * GattClient.
390  *
391  * This function will call the function CALEDataReceiverHandler()
392  * with client type to defragment the received data.
393  *
394  * @param[in] threadData Data pushed to the queue which contains the
395  *                       info about RemoteEndpoint and Data.
396  */
397 static void CALEClientDataReceiverHandler(void *threadData);
398
399 /**
400  * This function will stop all queues created for GattServer and
401  * GattClient. All four queues will be be stopped with this function
402  * invocations.
403  */
404 static void CAStopLEQueues();
405
406 /**
407  * This function will terminate all queues created for GattServer and
408  * GattClient. All four queues will be be terminated with this
409  * function invocations.
410  */
411 static void CATerminateLEQueues();
412
413 /**
414  * This function will initalize the Receiver and Sender queues for
415  * GattServer. This function will in turn call the functions
416  * CAInitBleServerReceiverQueue() and CAInitBleServerSenderQueue() to
417  * initialize the queues.
418  *
419  * @return ::CA_STATUS_OK or Appropriate error code.
420  * @retval ::CA_STATUS_OK  Successful.
421  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
422  * @retval ::CA_STATUS_FAILED Operation failed.
423  */
424 static CAResult_t CAInitLEServerQueues();
425
426 /**
427  * This function will initalize the Receiver and Sender queues for
428  * GattClient. This function will inturn call the functions
429  * CAInitBleClientReceiverQueue() and CAInitBleClientSenderQueue() to
430  * initialize the queues.
431  *
432  * @return ::CA_STATUS_OK or Appropriate error code.
433  * @retval ::CA_STATUS_OK  Successful.
434  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
435  * @retval ::CA_STATUS_FAILED Operation failed.
436  *
437  */
438 static CAResult_t CAInitLEClientQueues();
439
440 /**
441  * This function will initalize the Receiver queue for
442  * GattServer. This will initialize the queue to process the function
443  * CABLEServerSendDataThread() when ever the task is added to this
444  * queue.
445  *
446  * @return ::CA_STATUS_OK or Appropriate error code.
447  * @retval ::CA_STATUS_OK  Successful.
448  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
449  * @retval ::CA_STATUS_FAILED Operation failed.
450  */
451 static CAResult_t CAInitLEServerSenderQueue();
452
453 /**
454  * This function will initalize the Receiver queue for
455  * GattClient. This will initialize the queue to process the function
456  * CABLEClientSendDataThread() when ever the task is added to this
457  * queue.
458  *
459  * @return ::CA_STATUS_OK or Appropriate error code.
460  * @retval ::CA_STATUS_OK  Successful.
461  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
462  * @retval ::CA_STATUS_FAILED Operation failed.
463  */
464 static CAResult_t CAInitLEClientSenderQueue();
465
466 /**
467  * This function will initialize the Receiver queue for
468  * GattServer. This will initialize the queue to process the function
469  * CALEServerDataReceiverHandler() when ever the task is added to this
470  * queue.
471  *
472  * @return ::CA_STATUS_OK or Appropriate error code
473  * @retval ::CA_STATUS_OK  Successful
474  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments
475  * @retval ::CA_STATUS_FAILED Operation failed
476  *
477  */
478 static CAResult_t CAInitLEServerReceiverQueue();
479
480 /**
481  * This function will initialize the Receiver queue for
482  * GattClient. This will initialize the queue to process the function
483  * CALEClientDataReceiverHandler() when ever the task is added to this
484  * queue.
485  *
486  * @return ::CA_STATUS_OK or Appropriate error code
487  * @retval ::CA_STATUS_OK  Successful
488  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments
489  * @retval ::CA_STATUS_FAILED Operation failed
490  *
491  */
492 static CAResult_t CAInitLEClientReceiverQueue();
493
494 /**
495  * This function will create the Data required to send it in the
496  * queue.
497  *
498  * @param[in] remoteEndpoint Remote endpoint information of the
499  *                           server.
500  * @param[in] data           Data to be transmitted from LE.
501  * @param[in] dataLength     Length of the Data being transmitted.
502  *
503  * @return ::CA_STATUS_OK or Appropriate error code.
504  * @retval ::CA_STATUS_OK  Successful.
505  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
506  * @retval ::CA_STATUS_FAILED Operation failed.
507  */
508 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
509                                   const uint8_t *data,
510                                   uint32_t dataLength,
511                                   u_arraylist_t *senderInfo);
512
513 /**
514  * Used to free the BLE information stored in the sender/receiver
515  * queues.
516  *
517  * @param[in] bleData Information for a particular data segment.
518  */
519 static void CAFreeLEData(CALEData_t *bleData);
520
521 /**
522  * Free data.
523  */
524 static void CALEDataDestroyer(void *data, uint32_t size);
525
526 #ifndef SINGLE_THREAD
527 /**
528  * remove request or response data of send queue.
529  *
530  * @param[in] queueHandle    queue to process the outgoing packets.
531  * @param[in] mutex          mutex related to sender for client / server.
532  * @param[in] address        target address to remove data in queue.
533  */
534 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle,
535                                     oc_mutex mutex,
536                                     const char* address);
537
538 /**
539  * remove all received data of data list from receive queue.
540  *
541  * @param[in] dataInfoList   received data list to remove for client / server.
542  * @param[in] address        target address to remove data in queue.
543  */
544 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList,
545                                        const char* address);
546
547 /**
548  * get received data info and positioned index from the received data list
549  * for client / server which is matched same leAddress and port.
550  *
551  * @param[in]  leAddress       target address to get serderInfo.
552  * @param[in]  port            target port to get serderInfo.
553  * @param[in]  senderInfoList  received data list for client / server.
554  * @param[out] senderInfo      Pointer to contain matched(leAddress and port)
555  *                             received data info.
556  * @param[out] senderIndex     Pointer to contain matched(leAddress and port)
557  *                             received data info index.
558  */
559 static CAResult_t CALEGetSenderInfo(const char *leAddress,
560                                     const uint16_t port,
561                                     u_arraylist_t *senderInfoList,
562                                     CABLESenderInfo_t **senderInfo,
563                                     size_t *senderIndex);
564
565 /**
566  * get ports related to remote address. It is need because multi application
567  * can have more than 2 senderInfo using same BLE address. So before remove
568  * receive queue data, should get port list from sender Info.
569  *
570  * @param[in]  leAddress       target address to get port in serderInfo.
571  * @param[in]  senderInfoList  received data list to remove for client / server.
572  * @param[out] portList        target port list related to leAddress.
573  */
574 static CAResult_t CALEGetPortsFromSenderInfo(const char *leAddress,
575                                             u_arraylist_t *senderInfoList,
576                                             u_arraylist_t *portList);
577 #endif
578
579 static CAResult_t CAInitLEServerQueues()
580 {
581     oc_mutex_lock(g_bleAdapterThreadPoolMutex);
582
583     CAResult_t result = CAInitLEServerSenderQueue();
584     if (CA_STATUS_OK != result)
585     {
586         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerSenderQueue failed");
587         oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
588         return CA_STATUS_FAILED;
589     }
590
591     g_bleServerSenderInfo = u_arraylist_create();
592     if (!g_bleServerSenderInfo)
593     {
594         OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
595         oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
596         return CA_MEMORY_ALLOC_FAILED;
597     }
598
599     result = CAInitLEServerReceiverQueue();
600     if (CA_STATUS_OK != result)
601     {
602         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerReceiverQueue failed");
603         u_arraylist_free(&g_bleServerSenderInfo);
604         oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
605         return CA_STATUS_FAILED;
606     }
607
608     g_dataBleServerReceiverHandlerState = true;
609
610     oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
611     return CA_STATUS_OK;
612 }
613
614 static CAResult_t CAInitLEClientQueues()
615 {
616     oc_mutex_lock(g_bleAdapterThreadPoolMutex);
617
618     CAResult_t result = CAInitLEClientSenderQueue();
619     if (CA_STATUS_OK != result)
620     {
621         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientSenderQueue failed");
622         oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
623         return CA_STATUS_FAILED;
624     }
625
626     g_bleClientSenderInfo = u_arraylist_create();
627     if (!g_bleClientSenderInfo)
628     {
629         OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
630         oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
631         return CA_MEMORY_ALLOC_FAILED;
632     }
633
634     result = CAInitLEClientReceiverQueue();
635     if (CA_STATUS_OK != result)
636     {
637         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientReceiverQueue failed");
638         u_arraylist_free(&g_bleClientSenderInfo);
639         oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
640         return CA_STATUS_FAILED;
641     }
642
643     g_dataBleClientReceiverHandlerState = true;
644
645     oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
646     return CA_STATUS_OK;
647 }
648
649 static CAResult_t CAInitLEServerReceiverQueue()
650 {
651     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAInitLEServerReceiverQueue");
652     // Check if the message queue is already initialized
653     if (g_bleServerReceiverQueue)
654     {
655         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
656         return CA_STATUS_OK;
657     }
658
659     // Create recv message queue
660     g_bleServerReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
661     if (!g_bleServerReceiverQueue)
662     {
663         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
664         return CA_MEMORY_ALLOC_FAILED;
665     }
666
667     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerReceiverQueue,
668                                                    g_bleAdapterThreadPool,
669                                                    CALEServerDataReceiverHandler,
670                                                    CALEDataDestroyer))
671     {
672         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize server receiver queue thread");
673         OICFree(g_bleServerReceiverQueue);
674         g_bleServerReceiverQueue = NULL;
675         return CA_STATUS_FAILED;
676     }
677
678     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleServerReceiverQueue))
679     {
680         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
681         OICFree(g_bleServerReceiverQueue);
682         g_bleServerReceiverQueue = NULL;
683         return CA_STATUS_FAILED;
684     }
685
686     return CA_STATUS_OK;
687 }
688
689 static CAResult_t CAInitLEClientReceiverQueue()
690 {
691     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAInitLEClientReceiverQueue");
692     // Check if the message queue is already initialized
693     if (g_bleClientReceiverQueue)
694     {
695         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
696         return CA_STATUS_OK;
697     }
698
699     // Create recv message queue
700     g_bleClientReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
701     if (!g_bleClientReceiverQueue)
702     {
703         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
704         return CA_MEMORY_ALLOC_FAILED;
705     }
706
707     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientReceiverQueue,
708                                                    g_bleAdapterThreadPool,
709                                                    CALEClientDataReceiverHandler,
710                                                    CALEDataDestroyer))
711     {
712         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize client receiver queue thread");
713         OICFree(g_bleClientReceiverQueue);
714         g_bleClientReceiverQueue = NULL;
715         return CA_STATUS_FAILED;
716     }
717
718     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleClientReceiverQueue))
719     {
720         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
721         OICFree(g_bleClientReceiverQueue);
722         g_bleClientReceiverQueue = NULL;
723         return CA_STATUS_FAILED;
724     }
725
726     return CA_STATUS_OK;
727 }
728
729 static CAResult_t CAInitLEServerSenderQueue()
730 {
731     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAInitLEServerSenderQueue");
732     // Check if the message queue is already initialized
733     if (g_bleServerSendQueueHandle)
734     {
735         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Queue is already initialized!");
736         return CA_STATUS_OK;
737     }
738
739     // Create send message queue
740     g_bleServerSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
741     if (!g_bleServerSendQueueHandle)
742     {
743         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
744         return CA_MEMORY_ALLOC_FAILED;
745     }
746
747     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerSendQueueHandle,
748                                                    g_bleAdapterThreadPool,
749                                                    CALEServerSendDataThread,
750                                                    CALEDataDestroyer))
751     {
752         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
753         OICFree(g_bleServerSendQueueHandle);
754         g_bleServerSendQueueHandle = NULL;
755         return CA_STATUS_FAILED;
756     }
757
758     return CA_STATUS_OK;
759 }
760
761 static void CALEClearSenderInfoImpl(u_arraylist_t ** list)
762 {
763     const size_t length = u_arraylist_length(*list);
764     for (size_t i = 0; i < length; ++i)
765     {
766         CABLESenderInfo_t * const info =
767                 (CABLESenderInfo_t *) u_arraylist_get(*list, i);
768         if (info)
769          {
770              OICFree(info->defragData);
771              CAFreeEndpoint(info->remoteEndpoint);
772              OICFree(info);
773          }
774     }
775     u_arraylist_free(list);
776 }
777
778 static void CALEClearSenderInfo()
779 {
780     CALEClearSenderInfoImpl(&g_bleServerSenderInfo);
781     CALEClearSenderInfoImpl(&g_bleClientSenderInfo);
782 }
783
784 static CAResult_t CAInitLEClientSenderQueue()
785 {
786     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAInitLEClientSenderQueue");
787
788     if (g_bleClientSendQueueHandle)
789     {
790         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
791         return CA_STATUS_OK;
792     }
793
794     // Create send message queue
795     g_bleClientSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
796     if (!g_bleClientSendQueueHandle)
797     {
798         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
799         return CA_MEMORY_ALLOC_FAILED;
800     }
801
802     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientSendQueueHandle,
803                                                    g_bleAdapterThreadPool,
804                                                    CALEClientSendDataThread, CALEDataDestroyer))
805     {
806         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
807         OICFree(g_bleClientSendQueueHandle);
808         g_bleClientSendQueueHandle = NULL;
809         return CA_STATUS_FAILED;
810     }
811     return CA_STATUS_OK;
812 }
813
814 static void CAStopLEQueues()
815 {
816     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAStopLEQueues");
817
818     oc_mutex_lock(g_bleServerReceiveDataMutex);
819     if (NULL != g_bleServerReceiverQueue)
820     {
821         CAQueueingThreadStop(g_bleServerReceiverQueue);
822     }
823     oc_mutex_unlock(g_bleServerReceiveDataMutex);
824
825     oc_mutex_lock(g_bleClientReceiveDataMutex);
826     if (NULL != g_bleClientReceiverQueue)
827     {
828         CAQueueingThreadStop(g_bleClientReceiverQueue);
829     }
830     oc_mutex_unlock(g_bleClientReceiveDataMutex);
831
832     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CAStopLEQueues");
833 }
834
835 static void CATerminateLEQueues()
836 {
837     CAQueueingThreadDestroy(g_bleClientSendQueueHandle);
838     OICFree(g_bleClientSendQueueHandle);
839     g_bleClientSendQueueHandle = NULL;
840
841     CAQueueingThreadDestroy(g_bleServerSendQueueHandle);
842     OICFree(g_bleServerSendQueueHandle);
843     g_bleServerSendQueueHandle = NULL;
844
845     CAQueueingThreadDestroy(g_bleServerReceiverQueue);
846     OICFree(g_bleServerReceiverQueue);
847     g_bleServerReceiverQueue = NULL;
848
849     CAQueueingThreadDestroy(g_bleClientReceiverQueue);
850     OICFree(g_bleClientReceiverQueue);
851     g_bleClientReceiverQueue = NULL;
852
853     CALEClearSenderInfo();
854 }
855
856 static CAResult_t CALEGetSenderInfo(const char *leAddress,
857                                     const uint16_t port,
858                                     u_arraylist_t *senderInfoList,
859                                     CABLESenderInfo_t **senderInfo,
860                                     size_t *senderIndex)
861 {
862     VERIFY_NON_NULL_RET(leAddress,
863                         CALEADAPTER_TAG,
864                         "NULL BLE address argument",
865                         CA_STATUS_INVALID_PARAM);
866     VERIFY_NON_NULL_RET(senderIndex,
867                         CALEADAPTER_TAG,
868                         "NULL index argument",
869                         CA_STATUS_INVALID_PARAM);
870
871     const size_t listLength = u_arraylist_length(senderInfoList);
872     const size_t addrLength = strlen(leAddress);
873     for (size_t index = 0; index < listLength; index++)
874     {
875         CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
876         if (!info || !(info->remoteEndpoint))
877         {
878             continue;
879         }
880
881         if (!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
882         {
883             if (info->remoteEndpoint->port == port)
884             {
885                 *senderIndex = index;
886                 if (senderInfo)
887                 {
888                     *senderInfo = info;
889                 }
890                 return CA_STATUS_OK;
891             }
892         }
893     }
894
895     return CA_STATUS_FAILED;
896 }
897
898 static void CALEDataReceiverHandler(void *threadData, CABLEAdapter_t receiverType)
899 {
900     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEDataReceiverHandler");
901
902     oc_mutex bleReceiveDataMutex = NULL;
903     bool dataBleReceiverHandlerState = false;
904 #ifdef __WITH_DTLS__
905     CADataType_t dataType = CA_REQUEST_DATA;
906 #endif
907
908     switch (receiverType)
909     {
910         case ADAPTER_CLIENT:
911             bleReceiveDataMutex = g_bleClientReceiveDataMutex;
912             dataBleReceiverHandlerState = g_dataBleClientReceiverHandlerState;
913 #ifdef __WITH_DTLS__
914             dataType = CA_REQUEST_DATA;
915 #endif
916             break;
917         case ADAPTER_SERVER:
918             bleReceiveDataMutex = g_bleServerReceiveDataMutex;
919             dataBleReceiverHandlerState = g_dataBleServerReceiverHandlerState;
920 #ifdef __WITH_DTLS__
921             dataType = CA_RESPONSE_DATA;
922 #endif
923             break;
924         default:
925             OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Unsupported receiver type : %d", receiverType);
926             return;
927     }
928
929     oc_mutex_lock(bleReceiveDataMutex);
930
931     if (dataBleReceiverHandlerState)
932     {
933         CALEData_t *bleData = (CALEData_t *) threadData;
934         if (!bleData)
935         {
936             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bleData!");
937             oc_mutex_unlock(bleReceiveDataMutex);
938             return;
939         }
940
941         if (!(bleData->senderInfo))
942         {
943             OIC_LOG(ERROR, CALEADAPTER_TAG, "sender info is not available");
944             oc_mutex_unlock(bleReceiveDataMutex);
945             return;
946         }
947
948         if (!(bleData->remoteEndpoint))
949         {
950             OIC_LOG(ERROR, CALEADAPTER_TAG, "RemoteEndPoint NULL!!");
951             oc_mutex_unlock(bleReceiveDataMutex);
952             return;
953         }
954
955         CABLESenderInfo_t *senderInfo = NULL;
956         size_t senderIndex = 0;
957
958         //packet parsing
959         CABLEPacketStart_t startFlag = CA_BLE_PACKET_NOT_START;
960         CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
961         uint16_t sourcePort = 0;
962         uint16_t destPort = 0;
963
964         CAParseHeader(bleData->data, &startFlag, &sourcePort, &secureFlag, &destPort);
965         OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
966                   "header info: startFlag[%X] sourcePort[%d] secureFlag[%X] destPort[%d]",
967                   startFlag, sourcePort, secureFlag, destPort);
968
969         if (destPort != g_localBLESourcePort && destPort != CA_BLE_MULTICAST_PORT)
970         {
971             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
972                       "this packet is not valid for this app(port mismatch[mine:%d, packet:%d])",
973                       g_localBLESourcePort, destPort);
974             oc_mutex_unlock(bleReceiveDataMutex);
975             return;
976         }
977
978         bleData->remoteEndpoint->port = sourcePort;
979
980         if (CA_STATUS_OK != CALEGetSenderInfo(bleData->remoteEndpoint->addr,
981                                               bleData->remoteEndpoint->port,
982                                               bleData->senderInfo,
983                                               &senderInfo, &senderIndex))
984         {
985             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This is a new client [%s:%X]",
986                       bleData->remoteEndpoint->addr, bleData->remoteEndpoint->port);
987         }
988         else
989         {
990             if (startFlag)
991             {
992                 OIC_LOG(ERROR, CALEADAPTER_TAG,
993                         "This packet is start packet but exist senderInfo. Remove senderInfo");
994                 u_arraylist_remove(bleData->senderInfo, senderIndex);
995                 OICFree(senderInfo->defragData);
996                 OICFree(senderInfo);
997                 senderInfo = NULL;
998                 senderIndex = 0;
999             }
1000         }
1001
1002         if (!senderInfo)
1003         {
1004             uint32_t totalLength = 0;
1005             if (startFlag)
1006             {
1007                 CAParseHeaderPayloadLength(bleData->data, CA_BLE_LENGTH_HEADER_SIZE, &totalLength);
1008             }
1009             else
1010             {
1011                 OIC_LOG(ERROR, CALEADAPTER_TAG, "This packet is wrong packet! ignore.");
1012                 oc_mutex_unlock(bleReceiveDataMutex);
1013                 return;
1014             }
1015
1016             CABLESenderInfo_t *newSender = OICMalloc(sizeof(CABLESenderInfo_t));
1017             if (!newSender)
1018             {
1019                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
1020                 oc_mutex_unlock(bleReceiveDataMutex);
1021                 return;
1022             }
1023             newSender->recvDataLen = 0;
1024             newSender->totalDataLen = 0;
1025             newSender->defragData = NULL;
1026             newSender->remoteEndpoint = NULL;
1027
1028             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
1029
1030             newSender->totalDataLen = totalLength;
1031
1032             if (!(newSender->totalDataLen))
1033             {
1034                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
1035                 OICFree(newSender);
1036                 oc_mutex_unlock(bleReceiveDataMutex);
1037                 return;
1038             }
1039
1040             size_t dataOnlyLen =
1041                 bleData->dataLen - (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE);
1042             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
1043                       newSender->totalDataLen);
1044             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%" PRIuPTR "] bytes",
1045                       dataOnlyLen);
1046
1047             newSender->defragData = OICCalloc(newSender->totalDataLen + 1,
1048                                               sizeof(*newSender->defragData));
1049
1050             if (NULL == newSender->defragData)
1051             {
1052                 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
1053                 OICFree(newSender);
1054                 oc_mutex_unlock(bleReceiveDataMutex);
1055                 return;
1056             }
1057             CATransportFlags_t flags = CA_DEFAULT_FLAGS;
1058 #ifdef __WITH_DTLS__
1059             if (CA_BLE_PACKET_SECURE ==  secureFlag)
1060             {
1061                 flags |= CA_SECURE;
1062             }
1063 #endif
1064
1065             const char *remoteAddress = bleData->remoteEndpoint->addr;
1066             newSender->remoteEndpoint = CACreateEndpointObject(flags,
1067                                                                CA_ADAPTER_GATT_BTLE,
1068                                                                remoteAddress,
1069                                                                bleData->remoteEndpoint->port);
1070
1071             if (NULL == newSender->remoteEndpoint)
1072             {
1073                 OIC_LOG(ERROR, CALEADAPTER_TAG, "remoteEndpoint is NULL!");
1074                 OICFree(newSender->defragData);
1075                 OICFree(newSender);
1076                 oc_mutex_unlock(bleReceiveDataMutex);
1077                 return;
1078             }
1079
1080             if (newSender->recvDataLen + dataOnlyLen > newSender->totalDataLen)
1081             {
1082                 OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
1083                 OICFree(newSender->defragData);
1084                 CAFreeEndpoint(newSender->remoteEndpoint);
1085                 OICFree(newSender);
1086                 oc_mutex_unlock(bleReceiveDataMutex);
1087                 return;
1088             }
1089             memcpy(newSender->defragData,
1090                    bleData->data + (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE),
1091                    dataOnlyLen);
1092             newSender->recvDataLen += dataOnlyLen;
1093
1094             u_arraylist_add(bleData->senderInfo,(void *)newSender);
1095
1096             //Getting newSender index position in bleSenderInfo array list
1097             if (CA_STATUS_OK !=
1098                     CALEGetSenderInfo(newSender->remoteEndpoint->addr,
1099                                       newSender->remoteEndpoint->port,
1100                                       bleData->senderInfo,
1101                                       NULL, &senderIndex))
1102             {
1103                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Existing sender index not found!!");
1104                 OICFree(newSender->defragData);
1105                 CAFreeEndpoint(newSender->remoteEndpoint);
1106                 OICFree(newSender);
1107                 oc_mutex_unlock(bleReceiveDataMutex);
1108                 return;
1109             }
1110             senderInfo = newSender;
1111         }
1112         else
1113         {
1114             size_t dataOnlyLen = bleData->dataLen - CA_BLE_HEADER_SIZE;
1115             if (senderInfo->recvDataLen + dataOnlyLen > senderInfo->totalDataLen)
1116             {
1117                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1118                           "Data Length exceeding error!! Receiving [%" PRIuPTR "] total length [%u]",
1119                           senderInfo->recvDataLen + dataOnlyLen, senderInfo->totalDataLen);
1120                 u_arraylist_remove(bleData->senderInfo, senderIndex);
1121                 OICFree(senderInfo->defragData);
1122                 OICFree(senderInfo);
1123                 oc_mutex_unlock(bleReceiveDataMutex);
1124                 return;
1125             }
1126             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%" PRIuPTR "]",
1127                       dataOnlyLen);
1128             memcpy(senderInfo->defragData + senderInfo->recvDataLen,
1129                    bleData->data + CA_BLE_HEADER_SIZE,
1130                    dataOnlyLen);
1131             senderInfo->recvDataLen += dataOnlyLen;
1132             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "totalDatalength  [%d] received Datalen [%d]",
1133                                                 senderInfo->totalDataLen, senderInfo->recvDataLen);
1134         }
1135
1136         if (senderInfo->totalDataLen == senderInfo->recvDataLen)
1137         {
1138             oc_mutex_lock(g_bleAdapterReqRespCbMutex);
1139             if (NULL == g_networkPacketReceivedCallback)
1140             {
1141                 OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
1142
1143                 u_arraylist_remove(bleData->senderInfo, senderIndex);
1144                 OICFree(senderInfo->defragData);
1145                 OICFree(senderInfo);
1146                 oc_mutex_unlock(g_bleAdapterReqRespCbMutex);
1147                 oc_mutex_unlock(bleReceiveDataMutex);
1148                 return;
1149             }
1150
1151             OIC_LOG(DEBUG, CALEADAPTER_TAG, "[CALEDataReceiverHandler] Received data up !");
1152
1153             const CASecureEndpoint_t tmp =
1154                 {
1155                     .endpoint = *senderInfo->remoteEndpoint
1156                 };
1157
1158 #ifdef __WITH_DTLS__
1159             if (CA_SECURE & tmp.endpoint.flags)
1160             {
1161                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Secure data received");
1162                 g_dataType = dataType;
1163
1164                 if (CA_STATUS_FAILED == CAdecryptSsl(&tmp,
1165                                                 senderInfo->defragData,
1166                                                 senderInfo->recvDataLen))
1167                 {
1168                     OIC_LOG(ERROR, CALEADAPTER_TAG, "CAdecryptSsl failed");
1169                 }
1170                 else
1171                 {
1172                     OIC_LOG(ERROR, CALEADAPTER_TAG, "CAdecryptSsl successed");
1173                 }
1174                 OICFree(senderInfo->defragData);
1175             }
1176             else
1177             {
1178 #endif
1179                 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Non-Secure data received");
1180                 g_networkPacketReceivedCallback(&tmp,
1181                                                 senderInfo->defragData,
1182                                                 senderInfo->recvDataLen);
1183 #ifdef __WITH_DTLS__
1184             }
1185 #endif
1186
1187             oc_mutex_unlock(g_bleAdapterReqRespCbMutex);
1188             u_arraylist_remove(bleData->senderInfo, senderIndex);
1189             senderInfo->remoteEndpoint = NULL;
1190             senderInfo->defragData = NULL;
1191             OICFree(senderInfo);
1192         }
1193     }
1194     oc_mutex_unlock(bleReceiveDataMutex);
1195 }
1196
1197
1198 static void CALEServerDataReceiverHandler(void *threadData)
1199 {
1200     CALEDataReceiverHandler(threadData, ADAPTER_SERVER);
1201 }
1202
1203 static void CALEClientDataReceiverHandler(void *threadData)
1204 {
1205     CALEDataReceiverHandler(threadData, ADAPTER_CLIENT);
1206 }
1207
1208 static void CALEServerSendDataThread(void *threadData)
1209 {
1210     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEServerSendDataThread");
1211
1212     CALEData_t * const bleData = (CALEData_t *) threadData;
1213     if (!bleData)
1214     {
1215         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
1216         return;
1217     }
1218
1219     if (!bleData->remoteEndpoint)
1220     {
1221         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid endpoint of bledata!");
1222         return;
1223     }
1224
1225 #if defined(__ANDROID__)
1226     // get MTU size
1227     g_mtuSize = CALEServerGetMtuSize(bleData->remoteEndpoint->addr);
1228 #endif
1229     OIC_LOG_V(INFO, CALEADAPTER_TAG, "MTU size [%d]", g_mtuSize);
1230
1231     uint32_t midPacketCount = 0;
1232     size_t remainingLen = 0;
1233     size_t totalLength = 0;
1234     CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1235
1236     CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
1237                                                            &midPacketCount,
1238                                                            &remainingLen,
1239                                                            &totalLength,
1240                                                            g_mtuSize);
1241
1242     if (CA_STATUS_OK != result)
1243     {
1244         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1245                   "CAGenerateVariableForFragmentation failed, result [%d]", result);
1246         if (g_errorHandler)
1247         {
1248             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1249         }
1250         return;
1251     }
1252
1253     OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1254               "Packet info: data size[%d] midPacketCount[%u] remainingLen[%" PRIuPTR "] totalLength[%" PRIuPTR "]",
1255               bleData->dataLen, midPacketCount, remainingLen, totalLength);
1256
1257     OIC_LOG_V(DEBUG,
1258               CALEADAPTER_TAG,
1259               "Server total Data length with header is [%" PRIuPTR "]",
1260               totalLength);
1261
1262     uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1263     uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1264
1265     if (NULL != bleData->remoteEndpoint) //Unicast Data
1266     {
1267         secureFlag = (bleData->remoteEndpoint->flags & CA_SECURE) ?
1268             CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
1269
1270         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This Packet is secure? %d", secureFlag);
1271         result = CAGenerateHeader(dataHeader,
1272                                   CA_BLE_PACKET_START,
1273                                   g_localBLESourcePort,
1274                                   secureFlag,
1275                                   bleData->remoteEndpoint->port);
1276     }
1277     else                                //Multicast Data
1278     {
1279         result = CAGenerateHeader(dataHeader,
1280                                   CA_BLE_PACKET_START,
1281                                   g_localBLESourcePort,
1282                                   secureFlag,
1283                                   CA_BLE_MULTICAST_PORT);
1284     }
1285
1286     if (CA_STATUS_OK != result)
1287     {
1288         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1289                   "CAGenerateHeader failed, result [%d]", result);
1290         if (g_errorHandler)
1291         {
1292             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1293         }
1294         return;
1295     }
1296
1297     uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1298     result = CAGenerateHeaderPayloadLength(lengthHeader,
1299                                            CA_BLE_LENGTH_HEADER_SIZE,
1300                                            bleData->dataLen);
1301
1302     if (CA_STATUS_OK != result)
1303     {
1304         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1305                   "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1306         if (g_errorHandler)
1307         {
1308             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1309         }
1310         return;
1311     }
1312
1313     uint32_t length = 0;
1314     uint32_t dataLen = 0;
1315     if (g_mtuSize > totalLength)
1316     {
1317         length = totalLength;
1318         dataLen = bleData->dataLen;
1319     }
1320     else
1321     {
1322         length = g_mtuSize;
1323         dataLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1324     }
1325
1326     result = CAMakeFirstDataSegment(dataSegment,
1327                                     bleData->data, dataLen,
1328                                     dataHeader, lengthHeader);
1329
1330     if (CA_STATUS_OK != result)
1331     {
1332         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1333                   "Making data segment failed, result [%d]", result);
1334         if (g_errorHandler)
1335         {
1336             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1337         }
1338         return;
1339     }
1340
1341     const uint32_t iter = midPacketCount;
1342     uint32_t index = 0;
1343
1344     // Send the first segment with the header.
1345     if (NULL != bleData->remoteEndpoint) // Sending Unicast Data
1346     {
1347         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Unicast Data");
1348
1349         result = CAUpdateCharacteristicsToGattClient(
1350                     bleData->remoteEndpoint->addr, dataSegment, length);
1351
1352         if (CA_STATUS_OK != result)
1353         {
1354             OIC_LOG_V(ERROR,
1355                       CALEADAPTER_TAG,
1356                       "Update characteristics failed, result [%d]",
1357                       result);
1358             if (g_errorHandler)
1359             {
1360                 g_errorHandler(bleData->remoteEndpoint,
1361                                bleData->data,
1362                                bleData->dataLen,
1363                                result);
1364             }
1365             return;
1366         }
1367
1368         OIC_LOG_V(DEBUG,
1369                   CALEADAPTER_TAG,
1370                   "Server Sent Unicast First Data - data length [%zu]",
1371                   length);
1372
1373         result = CAGenerateHeader(dataHeader,
1374                                   CA_BLE_PACKET_NOT_START,
1375                                   g_localBLESourcePort,
1376                                   secureFlag,
1377                                   bleData->remoteEndpoint->port);
1378
1379         if (CA_STATUS_OK != result)
1380         {
1381             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1382                       "CAGenerateHeader failed, result [%d]", result);
1383             if (g_errorHandler)
1384             {
1385                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1386             }
1387             return;
1388         }
1389
1390         for (index = 0; index < iter; index++)
1391         {
1392             // Send the remaining header.
1393             result = CAMakeRemainDataSegment(dataSegment,
1394                                              g_mtuSize - CA_BLE_HEADER_SIZE,
1395                                              bleData->data,
1396                                              bleData->dataLen,
1397                                              index,
1398                                              dataHeader,
1399                                              g_mtuSize);
1400
1401             if (CA_STATUS_OK != result)
1402             {
1403                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1404                             "Making data segment failed, result [%d]", result);
1405                 if (g_errorHandler)
1406                 {
1407                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1408                 }
1409                 return;
1410             }
1411
1412             result =
1413                 CAUpdateCharacteristicsToGattClient(
1414                     bleData->remoteEndpoint->addr,
1415                     dataSegment,
1416                     g_mtuSize);
1417
1418             if (CA_STATUS_OK != result)
1419             {
1420                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1421                             "Update characteristics failed, result [%d]", result);
1422                 if (g_errorHandler)
1423                 {
1424                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1425                 }
1426                 return;
1427             }
1428             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]",
1429                                                g_mtuSize);
1430         }
1431
1432         if (remainingLen && (totalLength > g_mtuSize))
1433         {
1434             // send the last segment of the data (Ex: 22 bytes of 622
1435             // bytes of data when MTU is 200)
1436             result = CAMakeRemainDataSegment(dataSegment,
1437                                              remainingLen,
1438                                              bleData->data,
1439                                              bleData->dataLen,
1440                                              index,
1441                                              dataHeader,
1442                                              g_mtuSize);
1443
1444             if (CA_STATUS_OK != result)
1445             {
1446                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1447                             "Making data segment failed, result [%d]", result);
1448                 if (g_errorHandler)
1449                 {
1450                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1451                 }
1452                 return;
1453             }
1454
1455             result = CAUpdateCharacteristicsToGattClient(
1456                          bleData->remoteEndpoint->addr,
1457                          dataSegment,
1458                          remainingLen + CA_BLE_HEADER_SIZE);
1459
1460             if (CA_STATUS_OK != result)
1461             {
1462                 OIC_LOG_V(ERROR,
1463                           CALEADAPTER_TAG,
1464                           "Update characteristics failed, result [%d]",
1465                           result);
1466                 if (g_errorHandler)
1467                 {
1468                     g_errorHandler(bleData->remoteEndpoint,
1469                                    bleData->data,
1470                                    bleData->dataLen,
1471                                    result);
1472                 }
1473                 return;
1474             }
1475             OIC_LOG_V(DEBUG,
1476                       CALEADAPTER_TAG,
1477                       "Server Sent Unicast Last Data - data length [%" PRIuPTR "]",
1478                       remainingLen + CA_BLE_HEADER_SIZE);
1479         }
1480      }
1481     else
1482     {
1483         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast Data");
1484         OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
1485     }
1486
1487     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CALEServerSendDataThread");
1488 }
1489
1490 static void CALEClientSendDataThread(void *threadData)
1491 {
1492     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEClientSendDataThread");
1493
1494     CALEData_t *bleData = (CALEData_t *) threadData;
1495     if (!bleData)
1496     {
1497         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
1498         return;
1499     }
1500
1501     if (!bleData->remoteEndpoint)
1502     {
1503         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid endpoint of bledata!");
1504         return;
1505     }
1506
1507 #if defined(__ANDROID__)
1508     // get MTU size
1509     if (false == CALEClientIsConnected(bleData->remoteEndpoint->addr))
1510     {
1511         // triggering to gatt connect and MTU negotiation
1512         CAResult_t res = CALEClientSendNegotiationMessage(
1513                 bleData->remoteEndpoint->addr);
1514
1515         if (CA_STATUS_OK != res)
1516         {
1517             OIC_LOG_V(ERROR,
1518                       CALEADAPTER_TAG,
1519                       "CALEClientSendNegotiationMessage has failed, result [%d]",
1520                       res);
1521             if (g_errorHandler)
1522             {
1523                 g_errorHandler(bleData->remoteEndpoint,
1524                                bleData->data,
1525                                bleData->dataLen,
1526                                res);
1527             }
1528             return;
1529         }
1530     }
1531     g_mtuSize = CALEClientGetMtuSize(bleData->remoteEndpoint->addr);
1532 #endif
1533     OIC_LOG_V(INFO, CALEADAPTER_TAG, "MTU size [%d]", g_mtuSize);
1534
1535     uint32_t midPacketCount = 0;
1536     size_t remainingLen = 0;
1537     size_t totalLength = 0;
1538     CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1539
1540     CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
1541                                                            &midPacketCount,
1542                                                            &remainingLen,
1543                                                            &totalLength,
1544                                                            g_mtuSize);
1545
1546     if (CA_STATUS_OK != result)
1547     {
1548         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1549                   "CAGenerateVariableForFragmentation failed, result [%d]", result);
1550         if (g_errorHandler)
1551         {
1552             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1553         }
1554         return;
1555     }
1556
1557     OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1558               "Packet info: data size[%d] midPacketCount[%u] remainingLen[%" PRIuPTR "] totalLength[%" PRIuPTR "]",
1559               bleData->dataLen, midPacketCount, remainingLen, totalLength);
1560
1561     uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1562     uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1563
1564     if (NULL != bleData->remoteEndpoint) //Unicast Data
1565     {
1566         secureFlag = (bleData->remoteEndpoint->flags & CA_SECURE) ?
1567             CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
1568
1569         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This Packet is secure? %d", secureFlag);
1570         result = CAGenerateHeader(dataHeader,
1571                                   CA_BLE_PACKET_START,
1572                                   g_localBLESourcePort,
1573                                   secureFlag,
1574                                   bleData->remoteEndpoint->port);
1575     }
1576     else                                //Multicast Data
1577     {
1578         result = CAGenerateHeader(dataHeader,
1579                                   CA_BLE_PACKET_START,
1580                                   g_localBLESourcePort,
1581                                   secureFlag,
1582                                   CA_BLE_MULTICAST_PORT);
1583     }
1584
1585     if (CA_STATUS_OK != result)
1586     {
1587         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1588                   "CAGenerateHeader failed, result [%d]", result);
1589         if (g_errorHandler)
1590         {
1591             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1592         }
1593         return;
1594     }
1595
1596     uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1597     result = CAGenerateHeaderPayloadLength(lengthHeader,
1598                                            CA_BLE_LENGTH_HEADER_SIZE,
1599                                            bleData->dataLen);
1600
1601     if (CA_STATUS_OK != result)
1602     {
1603         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1604                   "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1605         if (g_errorHandler)
1606         {
1607             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1608         }
1609         return;
1610     }
1611
1612     uint32_t length = 0;
1613     uint32_t dataLen = 0;
1614     if (g_mtuSize > totalLength)
1615     {
1616         length = totalLength;
1617         dataLen = bleData->dataLen;
1618     }
1619     else
1620     {
1621         length = g_mtuSize;
1622         dataLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1623     }
1624
1625     result = CAMakeFirstDataSegment(dataSegment,
1626                                     bleData->data, dataLen,
1627                                     dataHeader, lengthHeader);
1628
1629     if (CA_STATUS_OK != result)
1630     {
1631         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1632                   "Making data segment failed, result [%d]", result);
1633         if (g_errorHandler)
1634         {
1635             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1636         }
1637         return;
1638     }
1639
1640     const uint32_t iter = midPacketCount;
1641     uint32_t index = 0;
1642     if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
1643     {
1644         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
1645         // Send the first segment with the header.
1646         result =
1647             CAUpdateCharacteristicsToGattServer(
1648                 bleData->remoteEndpoint->addr,
1649                 dataSegment,
1650                 length,
1651                 LE_UNICAST,
1652                 0);
1653
1654         if (CA_STATUS_OK != result)
1655         {
1656             OIC_LOG_V(ERROR,
1657                       CALEADAPTER_TAG,
1658                       "Update characteristics failed, result [%d]",
1659                       result);
1660             if (g_errorHandler)
1661             {
1662                 g_errorHandler(bleData->remoteEndpoint,
1663                                bleData->data,
1664                                bleData->dataLen,
1665                                result);
1666             }
1667             return;
1668         }
1669         OIC_LOG_V(DEBUG,
1670                   CALEADAPTER_TAG,
1671                   "Client Sent Unicast First Data - data length [%zu]",
1672                   length);
1673
1674         result = CAGenerateHeader(dataHeader,
1675                                   CA_BLE_PACKET_NOT_START,
1676                                   g_localBLESourcePort,
1677                                   secureFlag,
1678                                   bleData->remoteEndpoint->port);
1679
1680         if (CA_STATUS_OK != result)
1681         {
1682             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1683                       "CAGenerateHeader failed, result [%d]", result);
1684             if (g_errorHandler)
1685             {
1686                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1687             }
1688             return;
1689         }
1690
1691         for (index = 0; index < iter; index++)
1692         {
1693             result = CAMakeRemainDataSegment(dataSegment,
1694                                              g_mtuSize - CA_BLE_HEADER_SIZE,
1695                                              bleData->data,
1696                                              bleData->dataLen,
1697                                              index,
1698                                              dataHeader,
1699                                              g_mtuSize);
1700
1701             if (CA_STATUS_OK != result)
1702             {
1703                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1704                             "Making data segment failed, result [%d]", result);
1705                 if (g_errorHandler)
1706                 {
1707                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1708                 }
1709                 return;
1710             }
1711
1712             // Send the remaining header.
1713             result = CAUpdateCharacteristicsToGattServer(
1714                      bleData->remoteEndpoint->addr,
1715                      dataSegment,
1716                      g_mtuSize,
1717                      LE_UNICAST, 0);
1718
1719             if (CA_STATUS_OK != result)
1720             {
1721                 OIC_LOG_V(ERROR,
1722                           CALEADAPTER_TAG,
1723                           "Update characteristics failed, result [%d]",
1724                           result);
1725                 if (g_errorHandler)
1726                 {
1727                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1728                 }
1729                 return;
1730             }
1731             OIC_LOG_V(DEBUG,
1732                       CALEADAPTER_TAG,
1733                       "Client Sent Unicast %d Data - data(mtu) length [%zu]",
1734                       index + 1,
1735                       g_mtuSize);
1736         }
1737
1738         if (remainingLen && (totalLength > g_mtuSize))
1739         {
1740             // send the last segment of the data (Ex: 22 bytes of 622
1741             // bytes of data when MTU is 200)
1742             result = CAMakeRemainDataSegment(dataSegment,
1743                                              remainingLen,
1744                                              bleData->data,
1745                                              bleData->dataLen,
1746                                              index,
1747                                              dataHeader,
1748                                              g_mtuSize);
1749
1750             if (CA_STATUS_OK != result)
1751             {
1752                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1753                             "Making data segment failed, result [%d]", result);
1754                 if (g_errorHandler)
1755                 {
1756                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1757                 }
1758                 return;
1759             }
1760
1761             result = CAUpdateCharacteristicsToGattServer(
1762                      bleData->remoteEndpoint->addr,
1763                      dataSegment,
1764                      remainingLen + CA_BLE_HEADER_SIZE,
1765                      LE_UNICAST, 0);
1766
1767             if (CA_STATUS_OK != result)
1768             {
1769                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1770                                                    result);
1771                 if (g_errorHandler)
1772                 {
1773                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1774                 }
1775                 return;
1776             }
1777             OIC_LOG_V(DEBUG,
1778                       CALEADAPTER_TAG,
1779                       "Client Sent Unicast Last Data - data length [%" PRIuPTR "]",
1780                       remainingLen + CA_BLE_HEADER_SIZE);
1781         }
1782     }
1783     else
1784     {
1785         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Client Sending Multicast data");
1786         OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
1787     }
1788
1789     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CABLEClientSendDataThread");
1790 }
1791
1792 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
1793                                   const uint8_t *data,
1794                                   uint32_t dataLength,
1795                                   u_arraylist_t *senderInfo)
1796 {
1797     CALEData_t * const bleData = OICMalloc(sizeof(CALEData_t));
1798
1799     if (!bleData)
1800     {
1801         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1802         return NULL;
1803     }
1804
1805     bleData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
1806     bleData->data = OICCalloc(dataLength + 1, 1);
1807
1808     if (NULL == bleData->data)
1809     {
1810         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1811         CAFreeLEData(bleData);
1812         return NULL;
1813     }
1814
1815     memcpy(bleData->data, data, dataLength);
1816     bleData->dataLen = dataLength;
1817     if (senderInfo)
1818     {
1819         bleData->senderInfo = senderInfo;
1820     }
1821
1822     return bleData;
1823 }
1824
1825 static void CAFreeLEData(CALEData_t *bleData)
1826 {
1827     VERIFY_NON_NULL_VOID(bleData, CALEADAPTER_TAG, "Param bleData is NULL");
1828
1829     CAFreeEndpoint(bleData->remoteEndpoint);
1830     OICFree(bleData->data);
1831     OICFree(bleData);
1832 }
1833
1834 static void CALEDataDestroyer(void *data, uint32_t size)
1835 {
1836     if ((size_t)size < sizeof(CALEData_t *))
1837     {
1838         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1839                   "Destroy data too small %p %d", data, size);
1840     }
1841     CALEData_t *ledata = (CALEData_t *) data;
1842
1843     CAFreeLEData(ledata);
1844 }
1845 #endif
1846
1847 #ifdef SINGLE_THREAD
1848 static void CALEDataReceiverHandlerSingleThread(const uint8_t *data,
1849                                                 uint32_t dataLen)
1850 {
1851     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1852
1853     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1854
1855     //packet parsing
1856     CABLEPacketStart_t startFlag = CA_BLE_PACKET_NOT_START;
1857     CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1858     uint16_t sourcePort = 0;
1859     uint16_t destPort = 0;
1860
1861     CAParseHeader(data, &startFlag, &sourcePort, &secureFlag, &destPort);
1862     OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1863               "header info: startFlag[%X] sourcePort[%d] secureFlag[%X] destPort[%d]",
1864               startFlag, sourcePort, secureFlag, destPort);
1865
1866     if (destPort != g_localBLESourcePort && destPort != CA_BLE_MULTICAST_PORT)
1867     {
1868         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1869                   "this packet is not valid for this app(port mismatch[mine:%d, packet:%d])",
1870                   g_localBLESourcePort, destPort);
1871         return;
1872     }
1873
1874     if (startFlag)
1875     {
1876         if (g_singleThreadReceiveData)
1877         {
1878             OIC_LOG(ERROR, CALEADAPTER_TAG,
1879                     "This packet is start packet but exist senderInfo. Remove senderInfo");
1880             OICFree(g_singleThreadReceiveData->defragData);
1881             OICFree(g_singleThreadReceiveData);
1882             g_singleThreadReceiveData = NULL;
1883         }
1884
1885         uint32_t totalLength = 0;
1886         CAParseHeaderPayloadLength(data, CA_BLE_LENGTH_HEADER_SIZE, &totalLength);
1887
1888         g_singleThreadReceiveData = OICMalloc(sizeof(CABLESenderInfo_t));
1889
1890         if (!g_singleThreadReceiveData)
1891         {
1892             OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
1893             return;
1894         }
1895         g_singleThreadReceiveData->recvDataLen = 0;
1896         g_singleThreadReceiveData->totalDataLen = 0;
1897         g_singleThreadReceiveData->defragData = NULL;
1898         g_singleThreadReceiveData->remoteEndpoint = NULL;
1899
1900         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
1901
1902         g_singleThreadReceiveData->totalDataLen = totalLength;
1903
1904         if (!(g_singleThreadReceiveData->totalDataLen))
1905         {
1906             OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
1907             OICFree(g_singleThreadReceiveData);
1908             return;
1909         }
1910
1911         size_t dataOnlyLen = dataLen - (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE);
1912         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
1913                   g_singleThreadReceiveData->totalDataLen);
1914         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%u] bytes",
1915                   dataOnlyLen);
1916
1917         g_singleThreadReceiveData->defragData =
1918             OICCalloc(g_singleThreadReceiveData->totalDataLen + 1,
1919                     sizeof(*g_singleThreadReceiveData->defragData));
1920
1921         if (NULL == g_singleThreadReceiveData->defragData)
1922         {
1923             OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
1924             OICFree(g_singleThreadReceiveData);
1925             return;
1926         }
1927
1928         if (g_singleThreadReceiveData->recvDataLen + dataOnlyLen
1929                 > g_singleThreadReceiveData->totalDataLen)
1930         {
1931             OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
1932             OICFree(g_singleThreadReceiveData->defragData);
1933             OICFree(g_singleThreadReceiveData);
1934             return;
1935         }
1936         memcpy(g_singleThreadReceiveData->defragData,
1937                data + (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE),
1938                dataOnlyLen);
1939         g_singleThreadReceiveData->recvDataLen += dataOnlyLen;
1940     }
1941     else
1942     {
1943         size_t dataOnlyLen = dataLen - CA_BLE_HEADER_SIZE;
1944         if (g_singleThreadReceiveData->recvDataLen + dataOnlyLen
1945                 > g_singleThreadReceiveData->totalDataLen)
1946         {
1947             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1948                       "Data Length exceeding error!! Receiving [%d] total length [%d]",
1949                       g_singleThreadReceiveData->recvDataLen + dataOnlyLen,
1950                       g_singleThreadReceiveData->totalDataLen);
1951             OICFree(g_singleThreadReceiveData->defragData);
1952             OICFree(g_singleThreadReceiveData);
1953             return;
1954         }
1955         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]",
1956                   dataOnlyLen);
1957         memcpy(g_singleThreadReceiveData->defragData + g_singleThreadReceiveData->recvDataLen,
1958                data + CA_BLE_HEADER_SIZE,
1959                dataOnlyLen);
1960         g_singleThreadReceiveData->recvDataLen += dataOnlyLen;
1961         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "totalDatalength  [%d] received Datalen [%d]",
1962                 g_singleThreadReceiveData->totalDataLen, g_singleThreadReceiveData->recvDataLen);
1963     }
1964 }
1965
1966 static CAResult_t CALEServerSendDataSingleThread(const uint8_t *data,
1967                                                  uint32_t dataLen)
1968 {
1969     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1970
1971     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1972
1973     uint32_t midPacketCount = 0;
1974     size_t remainingLen = 0;
1975     size_t totalLength = 0;
1976     CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1977
1978     CAResult_t result = CAGenerateVariableForFragmentation(dataLen,
1979                                                            &midPacketCount,
1980                                                            &remainingLen,
1981                                                            &totalLength,
1982                                                            g_mtuSize);
1983
1984     if (CA_STATUS_OK != result)
1985     {
1986         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1987                   "CAGenerateVariableForFragmentation failed, result [%d]", result);
1988         return result;
1989     }
1990
1991     OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1992               "Packet info: data size[%d] midPacketCount[%d] remainingLen[%d] totalLength[%d]",
1993               dataLen, midPacketCount, remainingLen, totalLength);
1994
1995     OIC_LOG_V(DEBUG,
1996               CALEADAPTER_TAG,
1997               "Server total Data length with header is [%u]",
1998               totalLength);
1999
2000     uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
2001     uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
2002
2003     result = CAGenerateHeader(dataHeader,
2004                               CA_BLE_PACKET_START,
2005                               g_localBLESourcePort,
2006                               CA_BLE_PACKET_NON_SECURE,
2007                               CA_BLE_MULTICAST_PORT);
2008
2009     if (CA_STATUS_OK != result)
2010     {
2011         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2012                   "CAGenerateHeader failed, result [%d]", result);
2013         return result;
2014     }
2015
2016     uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
2017     result = CAGenerateHeaderPayloadLength(lengthHeader,
2018                                            CA_BLE_LENGTH_HEADER_SIZE,
2019                                            dataLen);
2020
2021     if (CA_STATUS_OK != result)
2022     {
2023         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2024                   "CAGenerateHeaderPayloadLength failed, result [%d]", result);
2025         return result;
2026     }
2027
2028     uint32_t length = 0;
2029     uint32_t dataOnlyLen = 0;
2030     if (g_mtuSize > totalLength)
2031     {
2032         length = totalLength;
2033         dataOnlyLen = dataLen;
2034     }
2035     else
2036     {
2037         length = g_mtuSize;
2038         dataOnlyLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
2039     }
2040
2041     result = CAMakeFirstDataSegment(dataSegment,
2042                                     data, dataOnlyLen,
2043                                     dataHeader, lengthHeader);
2044
2045     if (CA_STATUS_OK != result)
2046     {
2047         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2048                   "Making data segment failed, result [%d]", result);
2049         return result;
2050     }
2051
2052     OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
2053     result = CAUpdateCharacteristicsToAllGattClients(dataSegment, length);
2054     if (CA_STATUS_OK != result)
2055     {
2056         OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
2057                 result);
2058         return result;
2059     }
2060
2061     CALEDoEvents();
2062
2063     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
2064
2065     result = CAGenerateHeader(dataHeader,
2066                               CA_BLE_PACKET_NOT_START,
2067                               g_localBLESourcePort,
2068                               CA_BLE_PACKET_NON_SECURE,
2069                               CA_BLE_MULTICAST_PORT);
2070
2071     if (CA_STATUS_OK != result)
2072     {
2073         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2074                   "CAGenerateHeader failed, result [%d]", result);
2075         return result;
2076     }
2077
2078     const uint32_t dataLimit = midPacketCount;
2079     for (uint32_t iter = 0; iter < dataLimit; iter++)
2080     {
2081         result = CAMakeRemainDataSegment(dataSegment,
2082                                          g_mtuSize - CA_BLE_HEADER_SIZE,
2083                                          data,
2084                                          dataLen,
2085                                          iter,
2086                                          dataHeader,
2087                                          g_mtuSize);
2088
2089         if (CA_STATUS_OK != result)
2090         {
2091             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2092                     "Making data segment failed, result [%d]", result);
2093             return result;
2094         }
2095
2096         result = CAUpdateCharacteristicsToAllGattClients(
2097                      dataSegment,
2098                      g_mtuSize);
2099
2100         if (CA_STATUS_OK != result)
2101         {
2102             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2103             return result;
2104         }
2105
2106         CALEDoEvents();
2107     }
2108
2109     if (remainingLen && (totalLength > g_mtuSize))
2110     {
2111         // send the last segment of the data
2112         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
2113
2114         result = CAMakeRemainDataSegment(dataSegment,
2115                                          remainingLen,
2116                                          data,
2117                                          dataLen,
2118                                          dataLimit,
2119                                          dataHeader,
2120                                          g_mtuSize);
2121
2122         if (CA_STATUS_OK != result)
2123         {
2124             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2125                     "Making data segment failed, result [%d]", result);
2126             return result;
2127         }
2128
2129         result = CAUpdateCharacteristicsToAllGattClients(
2130                      dataSegment,
2131                      remainingLen + CA_BLE_HEADER_SIZE);
2132
2133         if (CA_STATUS_OK != result)
2134         {
2135             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2136             return result;
2137         }
2138         CALEDoEvents();
2139     }
2140
2141     return result;
2142 }
2143 #endif
2144
2145 static CAResult_t CAInitLEAdapterMutex()
2146 {
2147     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAInitLEAdapterMutex");
2148
2149     if (NULL == g_bleIsServerMutex)
2150     {
2151         g_bleIsServerMutex = oc_mutex_new();
2152         if (NULL == g_bleIsServerMutex)
2153         {
2154             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2155             return CA_STATUS_FAILED;
2156         }
2157     }
2158
2159     if (NULL == g_bleNetworkCbMutex)
2160     {
2161         g_bleNetworkCbMutex = oc_mutex_new();
2162         if (NULL == g_bleNetworkCbMutex)
2163         {
2164             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2165             CATerminateLEAdapterMutex();
2166             return CA_STATUS_FAILED;
2167         }
2168     }
2169
2170     if (NULL == g_bleLocalAddressMutex)
2171     {
2172         g_bleLocalAddressMutex = oc_mutex_new();
2173         if (NULL == g_bleLocalAddressMutex)
2174         {
2175             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2176             CATerminateLEAdapterMutex();
2177             return CA_STATUS_FAILED;
2178         }
2179     }
2180
2181     if (NULL == g_bleAdapterThreadPoolMutex)
2182     {
2183         g_bleAdapterThreadPoolMutex = oc_mutex_new();
2184         if (NULL == g_bleAdapterThreadPoolMutex)
2185         {
2186             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2187             CATerminateLEAdapterMutex();
2188             return CA_STATUS_FAILED;
2189         }
2190     }
2191
2192     if (NULL == g_bleClientSendDataMutex)
2193     {
2194         g_bleClientSendDataMutex = oc_mutex_new();
2195         if (NULL == g_bleClientSendDataMutex)
2196         {
2197             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2198             CATerminateLEAdapterMutex();
2199             return CA_STATUS_FAILED;
2200         }
2201     }
2202
2203     if (NULL == g_bleServerSendDataMutex)
2204     {
2205         g_bleServerSendDataMutex = oc_mutex_new();
2206         if (NULL == g_bleServerSendDataMutex)
2207         {
2208             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2209             CATerminateLEAdapterMutex();
2210             return CA_STATUS_FAILED;
2211         }
2212     }
2213
2214     if (NULL == g_bleAdapterReqRespCbMutex)
2215     {
2216         g_bleAdapterReqRespCbMutex = oc_mutex_new();
2217         if (NULL == g_bleAdapterReqRespCbMutex)
2218         {
2219             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2220             CATerminateLEAdapterMutex();
2221             return CA_STATUS_FAILED;
2222         }
2223     }
2224
2225     if (NULL == g_bleServerReceiveDataMutex)
2226     {
2227         g_bleServerReceiveDataMutex = oc_mutex_new();
2228         if (NULL == g_bleServerReceiveDataMutex)
2229         {
2230             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2231             return CA_STATUS_FAILED;
2232         }
2233     }
2234
2235     if (NULL == g_bleClientReceiveDataMutex)
2236     {
2237         g_bleClientReceiveDataMutex = oc_mutex_new();
2238         if (NULL == g_bleClientReceiveDataMutex)
2239         {
2240             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2241             return CA_STATUS_FAILED;
2242         }
2243     }
2244
2245     return CA_STATUS_OK;
2246 }
2247
2248 static void CATerminateLEAdapterMutex()
2249 {
2250     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CATerminateLEAdapterMutex");
2251
2252     oc_mutex_free(g_bleIsServerMutex);
2253     g_bleIsServerMutex = NULL;
2254
2255     oc_mutex_free(g_bleNetworkCbMutex);
2256     g_bleNetworkCbMutex = NULL;
2257
2258     oc_mutex_free(g_bleLocalAddressMutex);
2259     g_bleLocalAddressMutex = NULL;
2260
2261     oc_mutex_free(g_bleAdapterThreadPoolMutex);
2262     g_bleAdapterThreadPoolMutex = NULL;
2263
2264     oc_mutex_free(g_bleClientSendDataMutex);
2265     g_bleClientSendDataMutex = NULL;
2266
2267     oc_mutex_free(g_bleServerSendDataMutex);
2268     g_bleServerSendDataMutex = NULL;
2269
2270     oc_mutex_free(g_bleAdapterReqRespCbMutex);
2271     g_bleAdapterReqRespCbMutex = NULL;
2272
2273     oc_mutex_free(g_bleServerReceiveDataMutex);
2274     g_bleServerReceiveDataMutex = NULL;
2275
2276     oc_mutex_free(g_bleClientReceiveDataMutex);
2277     g_bleClientReceiveDataMutex = NULL;
2278 }
2279
2280 /**
2281  * Starting LE connectivity adapters.
2282  *
2283  * As its peer to peer it does not require to start any servers.
2284  *
2285  * @return ::CA_STATUS_OK or Appropriate error code.
2286  */
2287 static CAResult_t CAStartLE();
2288
2289 /**
2290  * Start listening server for receiving multicast search requests.
2291  *
2292  * Transport Specific Behavior:
2293  *   LE  Starts GATT Server with prefixed UUID and Characteristics
2294  *   per OIC Specification.
2295  * @return  ::CA_STATUS_OK or Appropriate error code.
2296  */
2297 static CAResult_t CAStartLEListeningServer();
2298
2299 /**
2300  * Stops listening server from receiving multicast search requests.
2301  *
2302  * Transport Specific Behavior:
2303  *   LE  Starts GATT Server with prefixed UUID and Characteristics
2304  *   per OIC Specification.
2305  * @return  ::CA_STATUS_OK or Appropriate error code.
2306  */
2307 static CAResult_t CAStopLEListeningServer();
2308
2309 /**
2310  * Sarting discovery of servers for receiving multicast
2311  * advertisements.
2312  *
2313  * Transport Specific Behavior:
2314  *   LE  Starts GATT Server with prefixed UUID and Characteristics
2315  *   per OIC Specification.
2316  *
2317  * @return ::CA_STATUS_OK or Appropriate error code
2318  */
2319 static CAResult_t CAStartLEDiscoveryServer();
2320
2321 /**
2322  * Send data to the endpoint using the adapter connectivity.
2323  *
2324  * @param[in] endpoint Remote Endpoint information (like MAC address,
2325  *                     reference URI and connectivity type) to which
2326  *                     the unicast data has to be sent.
2327  * @param[in] data     Data which required to be sent.
2328  * @param[in] dataLen  Size of data to be sent.
2329  *
2330  * @note  dataLen must be > 0.
2331  *
2332  * @return The number of bytes sent on the network, or -1 on error.
2333  */
2334 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2335                                    const void *data,
2336                                    uint32_t dataLen,
2337                                    CADataType_t dataType);
2338
2339 /**
2340  * Send multicast data to the endpoint using the LE connectivity.
2341  *
2342  * @param[in] endpoint Remote Endpoint information to which the
2343  *                     multicast data has to be sent.
2344  * @param[in] data     Data which required to be sent.
2345  * @param[in] dataLen  Size of data to be sent.
2346  *
2347  * @note  dataLen must be > 0.
2348  *
2349  * @return The number of bytes sent on the network, or -1 on error.
2350  */
2351 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
2352                                      const void *data,
2353                                      uint32_t dataLen,
2354                                      CADataType_t dataType);
2355
2356 /**
2357  * Get LE Connectivity network information.
2358  *
2359  * @param[out] info Local connectivity information structures.
2360  * @param[out] size Number of local connectivity structures.
2361  *
2362  * @return ::CA_STATUS_OK or Appropriate error code.
2363  */
2364 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info,
2365                                               size_t *size);
2366
2367 /**
2368  * Read Synchronous API callback.
2369  *
2370  * @return  ::CA_STATUS_OK or Appropriate error code.
2371  */
2372 static CAResult_t CAReadLEData();
2373
2374 /**
2375  * Stopping the adapters and close socket connections.
2376  *
2377  * LE Stops all GATT servers and GATT Clients.
2378  *
2379  * @return ::CA_STATUS_OK or Appropriate error code.
2380  */
2381 static CAResult_t CAStopLE();
2382
2383 /**
2384  * Terminate the LE connectivity adapter.
2385  *
2386  * Configuration information will be deleted from further use.
2387  */
2388 static void CATerminateLE();
2389
2390 /**
2391  * This function will receive the data from the GattServer and add the
2392  * data to the Server receiver queue.
2393  *
2394  * @param[in] remoteAddress Remote address of the device from where
2395  *                          data is received.
2396  * @param[in] data          Actual data received from the remote
2397  *                          device.
2398  * @param[in] dataLength    Length of the data received from the
2399  *                          remote device.
2400  * @param[in] sentLength    Length of the data sent from the remote
2401  *                          device.
2402  *
2403  * @return ::CA_STATUS_OK or Appropriate error code.
2404  * @retval ::CA_STATUS_OK  Successful.
2405  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
2406  * @retval ::CA_STATUS_FAILED Operation failed.
2407  *
2408  */
2409 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
2410                                                 const uint8_t *data,
2411                                                 uint32_t dataLength,
2412                                                 uint32_t *sentLength);
2413
2414 /**
2415  * This function will receive the data from the GattClient and add the
2416  * data into the Client receiver queue.
2417  *
2418  * @param[in] remoteAddress Remote address of the device from where
2419  *                          data is received.
2420  * @param[in] data          Actual data recevied from the remote
2421  *                          device.
2422  * @param[in] dataLength    Length of the data received from the
2423  *                          remote device.
2424  * @param[in] sentLength    Length of the data sent from the remote
2425  *                          device.
2426  *
2427  * @return ::CA_STATUS_OK or Appropriate error code.
2428  * @retval ::CA_STATUS_OK  Successful.
2429  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
2430  * @retval ::CA_STATUS_FAILED Operation failed.
2431  */
2432 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
2433                                                 const uint8_t *data,
2434                                                 uint32_t dataLength,
2435                                                 uint32_t *sentLength);
2436
2437 /**
2438  * Set the NetworkPacket received callback to CA layer from adapter
2439  * layer.
2440  *
2441  * @param[in] callback Callback handle sent from the upper layer.
2442  */
2443 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
2444
2445 /**
2446  * Push the data from CA layer to the Sender processor queue.
2447  *
2448  * @param[in] remoteEndpoint Remote endpoint information of the
2449  *                           server.
2450  * @param[in] data           Data to be transmitted from LE.
2451  * @param[in] dataLen        Length of the Data being transmitted.
2452  *
2453  * @return ::CA_STATUS_OK or Appropriate error code.
2454  * @retval ::CA_STATUS_OK  Successful.
2455  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
2456  * @retval ::CA_STATUS_FAILED Operation failed.
2457  */
2458 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
2459                                             const uint8_t *data,
2460                                             uint32_t dataLen);
2461
2462 /**
2463  * Push the data from CA layer to the Sender processor queue.
2464  *
2465  * @param[in] remoteEndpoint Remote endpoint information of the
2466  *                           server.
2467  * @param[in] data           Data to be transmitted from LE.
2468  * @param[in] dataLen        Length of the Data being transmitted.
2469  *
2470  * @return ::CA_STATUS_OK or Appropriate error code.
2471  * @retval ::CA_STATUS_OK  Successful.
2472  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
2473  * @retval ::CA_STATUS_FAILED Operation failed.
2474  */
2475 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
2476                                             const uint8_t *data,
2477                                             uint32_t dataLen);
2478
2479 static CAResult_t CALEAdapterGattServerStart()
2480 {
2481     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEAdapterGattServerStart");
2482
2483     if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2484     {
2485         OIC_LOG_V(INFO, CALEADAPTER_TAG, "server's flag is disabled in configuration [%d]",
2486                   caglobals.bleFlags);
2487         return CA_STATUS_OK;
2488     }
2489
2490     CAResult_t result = CAStartLEGattServer();
2491
2492 #ifndef SINGLE_THREAD
2493     /*
2494       Don't start the server side sending queue thread until the
2495       server itself has actually started.
2496     */
2497     if (CA_STATUS_OK == result)
2498     {
2499         oc_mutex_lock(g_bleServerSendDataMutex);
2500         result = CAQueueingThreadStart(g_bleServerSendQueueHandle);
2501         oc_mutex_unlock(g_bleServerSendDataMutex);
2502
2503         if (CA_STATUS_OK != result)
2504         {
2505             OIC_LOG_V(ERROR,
2506                       CALEADAPTER_TAG,
2507                       "Unable to start server queuing thread (%d)",
2508                       result);
2509         }
2510     }
2511 #endif
2512
2513     return result;
2514 }
2515
2516 static CAResult_t CALEAdapterGattServerStop()
2517 {
2518     OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Stop");
2519
2520     if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2521     {
2522         OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2523                   caglobals.bleFlags);
2524         return CA_STATUS_OK;
2525     }
2526
2527 #ifndef SINGLE_THREAD
2528
2529     CAResult_t res = CAStopLEGattServer();
2530     if (CA_STATUS_OK != res)
2531     {
2532         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAStopLEGattServer has failed");
2533     }
2534
2535     oc_mutex_lock(g_bleServerSendDataMutex);
2536     res = CAQueueingThreadStop(g_bleServerSendQueueHandle);
2537     if (CA_STATUS_OK != res)
2538     {
2539         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAQueueingThreadStop has failed");
2540     }
2541     oc_mutex_unlock(g_bleServerSendDataMutex);
2542
2543     return res;
2544 #else
2545     return CAStopLEGattServer();
2546 #endif
2547 }
2548
2549 static CAResult_t CALEAdapterGattClientStart()
2550 {
2551     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEAdapterGattClientStart");
2552
2553     CAResult_t result = CAStartLEGattClient();
2554
2555 #ifndef SINGLE_THREAD
2556     /*
2557       Don't start the client side sending queue thread until the
2558       client itself has actually started.
2559     */
2560     if (CA_STATUS_OK == result)
2561     {
2562         oc_mutex_lock(g_bleClientSendDataMutex);
2563         result = CAQueueingThreadStart(g_bleClientSendQueueHandle);
2564         oc_mutex_unlock(g_bleClientSendDataMutex);
2565
2566         if (CA_STATUS_OK != result)
2567         {
2568             OIC_LOG(ERROR,
2569                     CALEADAPTER_TAG,
2570                     "Unable to start client queuing thread");
2571         }
2572     }
2573 #endif
2574
2575     return result;
2576 }
2577
2578 static CAResult_t CALEAdapterGattClientStop()
2579 {
2580 #ifndef SINGLE_THREAD
2581     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEAdapterGattClientStop");
2582     CAStopLEGattClient();
2583
2584     oc_mutex_lock(g_bleClientSendDataMutex);
2585     CAResult_t result = CAQueueingThreadStop(g_bleClientSendQueueHandle);
2586     oc_mutex_unlock(g_bleClientSendDataMutex);
2587
2588     return result;
2589 #else
2590     CAStopLEGattClient();
2591
2592     return CA_STATUS_OK;
2593 #endif
2594 }
2595
2596 #ifdef __WITH_DTLS__
2597 static ssize_t CALESecureSendDataCB(CAEndpoint_t *endpoint,
2598                              const void *data, size_t dataLen)
2599 {
2600     VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "endpoint is NULL", -1);
2601     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "data is NULL", -1);
2602
2603     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Secure Data Send - encrypted datalen = %d", dataLen);
2604
2605     CAResult_t result;
2606     CADataType_t dataType = g_dataType;
2607
2608     if (ADAPTER_SERVER == g_adapterType ||
2609             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2610     {
2611         result = CALEAdapterServerSendData(endpoint, data, dataLen);
2612         if (CA_STATUS_OK != result)
2613         {
2614             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed" );
2615
2616             if (g_errorHandler)
2617             {
2618                 g_errorHandler(endpoint, data, dataLen, result);
2619             }
2620             return -1;
2621         }
2622     }
2623     else if (ADAPTER_CLIENT == g_adapterType ||
2624             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
2625             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
2626     {
2627         result = CALEAdapterClientSendData(endpoint, data, dataLen);
2628         if (CA_STATUS_OK != result)
2629         {
2630             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
2631
2632             if (g_errorHandler)
2633             {
2634                 g_errorHandler(endpoint, data, dataLen, result);
2635             }
2636             return -1;
2637         }
2638     }
2639     else
2640     {
2641         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2642                   "Can't Send Message adapterType = %d, dataType = %d", g_adapterType, dataType);
2643         return -1;
2644     }
2645
2646     return (ssize_t)dataLen;
2647 }
2648
2649 static void CALESecureReceiveDataCB(const CASecureEndpoint_t *sep,
2650                                  const void *data, size_t dataLen)
2651 {
2652     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2653
2654     VERIFY_NON_NULL_VOID(sep, CALEADAPTER_TAG, "sep is NULL");
2655     VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "data is NULL");
2656
2657     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Secure Data Receive - decrypted datalen = %d", dataLen);
2658
2659     if (dataLen == 0)
2660     {
2661         OIC_LOG(ERROR, CALEADAPTER_TAG, "incorrect dataLen, derecypt fail !");
2662         return;
2663     }
2664
2665     OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2666
2667     if (g_networkPacketReceivedCallback)
2668     {
2669         OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2670                   "[CALESecureReceiveDataCB] Secure flags = %d, %x",
2671                   sep->endpoint.flags, sep->endpoint.flags);
2672         OIC_LOG(DEBUG, CALEADAPTER_TAG,
2673                   "[CALESecureReceiveDataCB] Received data up !");
2674         g_networkPacketReceivedCallback(sep, data, dataLen);
2675     }
2676 }
2677 #endif
2678
2679 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
2680                           CANetworkPacketReceivedCallback reqRespCallback,
2681                           CAAdapterChangeCallback netCallback,
2682                           CAConnectionChangeCallback connCallback,
2683                           CAErrorHandleCallback errorCallback,
2684                           ca_thread_pool_t handle)
2685 {
2686     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAInitializeLE");
2687
2688     //Input validation
2689     VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null");
2690     VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null");
2691     VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null");
2692     VERIFY_NON_NULL(connCallback, CALEADAPTER_TAG, "ConnectionChange Callback is null");
2693
2694     CAResult_t result = CA_STATUS_OK;
2695     result = CAInitLEAdapterMutex();
2696     if (CA_STATUS_OK != result)
2697     {
2698         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
2699         return CA_STATUS_FAILED;
2700     }
2701
2702     result = CAInitializeLENetworkMonitor();
2703     if (CA_STATUS_OK != result)
2704     {
2705         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
2706         return CA_STATUS_FAILED;
2707     }
2708     CAInitializeLEAdapter();
2709
2710     result = CAInitializeLEGattClient();
2711     if (CA_STATUS_OK != result)
2712     {
2713         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattClient() failed");
2714         return CA_STATUS_FAILED;
2715     }
2716
2717     CASetLEClientThreadPoolHandle(handle);
2718
2719     CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
2720     CASetLEServerThreadPoolHandle(handle);
2721     result = CAInitializeLEGattServer();
2722     if (CA_STATUS_OK != result)
2723     {
2724         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattServer() failed");
2725         return CA_STATUS_FAILED;
2726     }
2727
2728     CASetLEAdapterThreadPoolHandle(handle);
2729     CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
2730     CASetLEReqRespAdapterCallback(reqRespCallback);
2731
2732     CASetBLEClientErrorHandleCallback(CALEErrorHandler);
2733     CASetBLEServerErrorHandleCallback(CALEErrorHandler);
2734     CALERegisterNetworkNotifications(netCallback, connCallback);
2735
2736     g_errorHandler = errorCallback;
2737
2738 #ifdef __WITH_DTLS__
2739      if (CA_STATUS_OK != CAinitSslAdapter())
2740     {
2741         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to init SSL adapter");
2742     }
2743     else
2744     {
2745         CAsetSslAdapterCallbacks(CALESecureReceiveDataCB, CALESecureSendDataCB, CA_ADAPTER_GATT_BTLE);
2746     }
2747 #endif
2748
2749     static const CAConnectivityHandler_t connHandler =
2750         {
2751             .startAdapter = CAStartLE,
2752             .stopAdapter = CAStopLE,
2753             .startListenServer = CAStartLEListeningServer,
2754             .stopListenServer = CAStopLEListeningServer,
2755             .startDiscoveryServer = CAStartLEDiscoveryServer,
2756             .sendData = CASendLEUnicastData,
2757             .sendDataToAll = CASendLEMulticastData,
2758             .GetnetInfo = CAGetLEInterfaceInformation,
2759             .readData = CAReadLEData,
2760             .terminate = CATerminateLE,
2761             .cType = CA_ADAPTER_GATT_BTLE
2762         };
2763
2764     registerCallback(connHandler);
2765     return CA_STATUS_OK;
2766 }
2767
2768 static CAResult_t CAStartLE()
2769 {
2770     return CAStartLEAdapter();
2771 }
2772
2773 static CAResult_t CAStopLE()
2774 {
2775 #ifdef __WITH_DTLS__
2776     CAdeinitSslAdapter();
2777 #endif
2778
2779 #ifndef SINGLE_THREAD
2780     CAStopLEQueues();
2781 #endif
2782
2783     oc_mutex_lock(g_bleIsServerMutex);
2784     switch (g_adapterType)
2785     {
2786         case ADAPTER_SERVER:
2787             CALEAdapterGattServerStop();
2788             break;
2789         case ADAPTER_CLIENT:
2790             CALEAdapterGattClientStop();
2791             break;
2792         case ADAPTER_BOTH_CLIENT_SERVER:
2793             CALEAdapterGattServerStop();
2794             CALEAdapterGattClientStop();
2795             break;
2796         default:
2797             break;
2798     }
2799     oc_mutex_unlock(g_bleIsServerMutex);
2800     return CAStopLEAdapter();
2801 }
2802
2803 static void CATerminateLE()
2804 {
2805     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CATerminateLE");
2806
2807     CASetLEReqRespServerCallback(NULL);
2808     CASetLEReqRespClientCallback(NULL);
2809     CALERegisterNetworkNotifications(NULL, NULL);
2810     CASetLEReqRespAdapterCallback(NULL);
2811     CATerminateLENetworkMonitor();
2812
2813     oc_mutex_lock(g_bleIsServerMutex);
2814     switch (g_adapterType)
2815     {
2816         case ADAPTER_SERVER:
2817             CATerminateLEGattServer();
2818             break;
2819         case ADAPTER_CLIENT:
2820             CATerminateLEGattClient();
2821             break;
2822         case ADAPTER_BOTH_CLIENT_SERVER:
2823             CATerminateLEGattServer();
2824             CATerminateLEGattClient();
2825             break;
2826         default:
2827             break;
2828     }
2829     g_adapterType = ADAPTER_EMPTY;
2830     oc_mutex_unlock(g_bleIsServerMutex);
2831
2832 #ifndef SINGLE_THREAD
2833     CATerminateLEQueues();
2834 #endif
2835
2836 #ifdef __WITH_DTLS__
2837     CAsetSslAdapterCallbacks(NULL, NULL, CA_ADAPTER_GATT_BTLE);
2838 #endif
2839
2840     CATerminateLEAdapterMutex();
2841 }
2842
2843 static CAResult_t CAStartLEListeningServer()
2844 {
2845     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAStartLEListeningServer");
2846
2847     if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2848     {
2849         OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2850                   caglobals.bleFlags);
2851         return CA_STATUS_OK;
2852     }
2853
2854 #ifndef ROUTING_GATEWAY
2855     CAResult_t result = CA_STATUS_OK;
2856 #ifndef SINGLE_THREAD
2857     result = CAInitLEServerQueues();
2858     if (CA_STATUS_OK != result)
2859     {
2860         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
2861         return result;
2862     }
2863 #endif
2864
2865     oc_mutex_lock(g_bleIsServerMutex);
2866     switch (g_adapterType)
2867     {
2868         case ADAPTER_CLIENT:
2869             g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2870             break;
2871         case ADAPTER_BOTH_CLIENT_SERVER:
2872             break;
2873         default:
2874             g_adapterType = ADAPTER_SERVER;
2875     }
2876     oc_mutex_unlock(g_bleIsServerMutex);
2877
2878     result = CAGetLEAdapterState();
2879     if (CA_STATUS_OK != result)
2880     {
2881         if (CA_ADAPTER_NOT_ENABLED == result)
2882         {
2883             OIC_LOG(DEBUG,
2884                     CALEADAPTER_TAG,
2885                     "Listen Server will be started once BT Adapter is enabled");
2886             result = CA_STATUS_OK;
2887         }
2888     }
2889     else
2890     {
2891         result = CALEAdapterGattServerStart();
2892     }
2893
2894     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2895     return result;
2896 #else
2897     // Routing Gateway only supports BLE client mode.
2898     OIC_LOG(ERROR, CALEADAPTER_TAG, "LE server not supported in Routing Gateway");
2899     return CA_NOT_SUPPORTED;
2900 #endif
2901 }
2902
2903 static CAResult_t CAStopLEListeningServer()
2904 {
2905     OIC_LOG(ERROR, CALEADAPTER_TAG, "Listen server stop not supported.");
2906     return CA_NOT_SUPPORTED;
2907 }
2908
2909 static CAResult_t CAStartLEDiscoveryServer()
2910 {
2911     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAStartLEDiscoveryServer");
2912     CAResult_t result = CA_STATUS_OK;
2913 #ifndef SINGLE_THREAD
2914     result = CAInitLEClientQueues();
2915     if (CA_STATUS_OK != result)
2916     {
2917         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
2918         return result;
2919     }
2920 #endif
2921
2922     oc_mutex_lock(g_bleIsServerMutex);
2923     switch (g_adapterType)
2924     {
2925         case ADAPTER_SERVER:
2926             g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2927             break;
2928         case ADAPTER_BOTH_CLIENT_SERVER:
2929             break;
2930         default:
2931             g_adapterType = ADAPTER_CLIENT;
2932     }
2933     oc_mutex_unlock(g_bleIsServerMutex);
2934
2935     result = CAGetLEAdapterState();
2936     if (CA_STATUS_OK != result)
2937     {
2938         if (CA_ADAPTER_NOT_ENABLED == result)
2939         {
2940             OIC_LOG(DEBUG,
2941                     CALEADAPTER_TAG,
2942                     "Discovery Server will be started once BT Adapter is enabled");
2943             result = CA_STATUS_OK;
2944         }
2945     }
2946     else
2947     {
2948         result = CALEAdapterGattClientStart();
2949     }
2950
2951     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2952     return result;
2953 }
2954
2955 static CAResult_t CAReadLEData()
2956 {
2957 #ifdef SINGLE_THREAD
2958     CACheckLEData();
2959 #endif
2960     return CA_STATUS_OK;
2961 }
2962
2963 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2964                                    const void *data,
2965                                    uint32_t dataLen,
2966                                    CADataType_t dataType)
2967 {
2968     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN - CASendLEUnicastData : type(%d)", dataType);
2969
2970     //Input validation
2971     VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
2972     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2973
2974     CAResult_t result = CA_STATUS_FAILED;
2975
2976     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2977     if (ADAPTER_EMPTY == g_adapterType)
2978     {
2979         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2980     }
2981
2982     oc_mutex_lock(g_bleIsServerMutex);
2983     if (ADAPTER_SERVER == g_adapterType ||
2984             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2985     {
2986 #ifdef __WITH_DTLS__
2987         if (endpoint && endpoint->flags & CA_SECURE)
2988         {
2989             OIC_LOG(DEBUG, CALEADAPTER_TAG,
2990                     "Response Data or server - secured data send(caadapternetdtlsencrypt) call");
2991             g_dataType = dataType;
2992             oc_mutex_unlock(g_bleIsServerMutex);
2993
2994             result = CAencryptSsl(endpoint, data, dataLen);
2995             if (CA_STATUS_OK != result)
2996             {
2997                 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
2998                 return -1;
2999             }
3000             return dataLen;
3001         }
3002         else
3003         {
3004             OIC_LOG(DEBUG, CALEADAPTER_TAG,
3005                     "server or both - none secured data send(CALEAdapterServerSendData) call");
3006             result = CALEAdapterServerSendData(endpoint, data, dataLen);
3007         }
3008 #else
3009         result = CALEAdapterServerSendData(endpoint, data, dataLen);
3010 #endif
3011         if (CA_STATUS_OK != result)
3012         {
3013             oc_mutex_unlock(g_bleIsServerMutex);
3014             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed");
3015             if (g_errorHandler)
3016             {
3017                 g_errorHandler(endpoint, data, dataLen, result);
3018             }
3019
3020             return -1;
3021         }
3022     }
3023     else if (ADAPTER_CLIENT == g_adapterType ||
3024             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
3025             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
3026     {
3027 #ifdef __WITH_DTLS__
3028         if (endpoint && endpoint->flags & CA_SECURE)
3029         {
3030             OIC_LOG(DEBUG, CALEADAPTER_TAG,
3031                     "Request Data or client - secured data send(caadapternetdtlsencrypt) call");
3032             g_dataType = dataType;
3033             oc_mutex_unlock(g_bleIsServerMutex);
3034
3035             result = CAencryptSsl(endpoint, data, dataLen);
3036             if (CA_STATUS_OK != result)
3037             {
3038                 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
3039                 return -1;
3040             }
3041             return dataLen;
3042         }
3043         else
3044         {
3045             OIC_LOG(DEBUG, CALEADAPTER_TAG,
3046                     "client or both - none secured data send(CALEAdapterClientSendData) call");
3047             result = CALEAdapterClientSendData(endpoint, data, dataLen);
3048         }
3049 #else
3050         result = CALEAdapterClientSendData(endpoint, data, dataLen);
3051 #endif
3052         if (CA_STATUS_OK != result)
3053         {
3054             oc_mutex_unlock(g_bleIsServerMutex);
3055             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
3056
3057             if (g_errorHandler)
3058             {
3059                 g_errorHandler(endpoint, data, dataLen, result);
3060             }
3061             return -1;
3062         }
3063     }
3064     oc_mutex_unlock(g_bleIsServerMutex);
3065
3066     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
3067     return dataLen;
3068 }
3069
3070 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
3071                                      const void *data,
3072                                      uint32_t dataLen,
3073                                      CADataType_t dataType)
3074 {
3075     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CASendLEMulticastData");
3076
3077     //Input validation
3078     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
3079
3080     if (0 >= dataLen)
3081     {
3082         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
3083         return -1;
3084     }
3085
3086     CAResult_t result = CA_STATUS_FAILED;
3087
3088     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
3089     if (ADAPTER_EMPTY == g_adapterType)
3090     {
3091         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
3092     }
3093
3094     oc_mutex_lock(g_bleIsServerMutex);
3095     if (ADAPTER_SERVER == g_adapterType ||
3096             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
3097     {
3098         result = CALEAdapterServerSendData(NULL, data, dataLen);
3099         if (CA_STATUS_OK != result)
3100         {
3101             oc_mutex_unlock(g_bleIsServerMutex);
3102
3103             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data for server failed" );
3104
3105             if (g_errorHandler)
3106             {
3107                 g_errorHandler(endpoint, data, dataLen, result);
3108             }
3109             return -1;
3110         }
3111     }
3112
3113     if (ADAPTER_CLIENT == g_adapterType ||
3114             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
3115             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
3116     {
3117         result = CALEAdapterClientSendData(NULL, data, dataLen);
3118         if (CA_STATUS_OK != result)
3119         {
3120             oc_mutex_unlock(g_bleIsServerMutex);
3121
3122             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data for client failed" );
3123
3124             if (g_errorHandler)
3125             {
3126                 g_errorHandler(endpoint, data, dataLen, result);
3127             }
3128             return -1;
3129         }
3130     }
3131     oc_mutex_unlock(g_bleIsServerMutex);
3132
3133     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CASendLEMulticastData");
3134     return dataLen;
3135 }
3136
3137 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, size_t *size)
3138 {
3139     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
3140
3141     VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
3142
3143     char *local_address = NULL;
3144
3145     CAResult_t res = CAGetLEAddress(&local_address);
3146     if (CA_STATUS_OK != res)
3147     {
3148         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
3149         return res;
3150     }
3151
3152     if (NULL == local_address)
3153     {
3154         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
3155         return CA_STATUS_FAILED;
3156     }
3157
3158     *size = 0;
3159     (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
3160     if (NULL == (*info))
3161     {
3162         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
3163         OICFree(local_address);
3164         return CA_STATUS_FAILED;
3165     }
3166
3167     size_t local_address_len = strlen(local_address);
3168
3169     if(local_address_len >= sizeof(g_localBLEAddress) ||
3170             local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
3171     {
3172         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
3173         OICFree(*info);
3174         OICFree(local_address);
3175         return CA_STATUS_FAILED;
3176     }
3177
3178     OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
3179     oc_mutex_lock(g_bleLocalAddressMutex);
3180     OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
3181     oc_mutex_unlock(g_bleLocalAddressMutex);
3182
3183     (*info)->adapter = CA_ADAPTER_GATT_BTLE;
3184     *size = 1;
3185     OICFree(local_address);
3186
3187     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
3188     return CA_STATUS_OK;
3189 }
3190
3191 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
3192                                                    CAConnectionChangeCallback connCallback)
3193 {
3194     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
3195
3196     oc_mutex_lock(g_bleNetworkCbMutex);
3197     g_networkCallback = netCallback;
3198     g_connectionCallback = connCallback;
3199     oc_mutex_unlock(g_bleNetworkCbMutex);
3200     CAResult_t res = CA_STATUS_OK;
3201     if (netCallback)
3202     {
3203         res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
3204         if (CA_STATUS_OK != res)
3205         {
3206             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
3207         }
3208     }
3209     else
3210     {
3211         res = CAUnSetLEAdapterStateChangedCb();
3212         if (CA_STATUS_OK != res)
3213         {
3214             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
3215         }
3216     }
3217
3218     if (g_connectionCallback)
3219     {
3220         res = CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCb);
3221         if (CA_STATUS_OK != res)
3222         {
3223             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLENWConnectionStateChangedCb failed!");
3224         }
3225     }
3226
3227     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
3228     return res;
3229 }
3230
3231 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
3232                                          bool isConnected)
3233 {
3234     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEConnectionStateChangedCb");
3235
3236     VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3237     (void)adapter;
3238
3239     CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE };
3240     OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), address);
3241
3242 #ifdef __TIZEN__
3243     oc_mutex_lock(g_bleIsServerMutex);
3244     switch (g_adapterType)
3245     {
3246         case ADAPTER_SERVER:
3247             CALEGattServerConnectionStateChanged(isConnected, address);
3248             break;
3249         case ADAPTER_CLIENT:
3250             CALEGattConnectionStateChanged(isConnected, address);
3251             break;
3252         case ADAPTER_BOTH_CLIENT_SERVER:
3253             CALEGattConnectionStateChanged(isConnected, address);
3254             CALEGattServerConnectionStateChanged(isConnected, address);
3255             break;
3256         default:
3257             break;
3258     }
3259     oc_mutex_unlock(g_bleIsServerMutex);
3260 #endif
3261
3262     if(!isConnected)
3263     {
3264 #ifndef SINGLE_THREAD
3265         if(g_bleClientSenderInfo)
3266         {
3267             CALERemoveReceiveQueueData(g_bleClientSenderInfo, address);
3268         }
3269
3270         if(g_bleServerSenderInfo)
3271         {
3272             CALERemoveReceiveQueueData(g_bleServerSenderInfo, address);
3273         }
3274
3275         // remove data of send queue.
3276         if (g_bleClientSendQueueHandle)
3277         {
3278             CALERemoveSendQueueData(g_bleClientSendQueueHandle,
3279                                     g_bleClientSendDataMutex,
3280                                     address);
3281         }
3282
3283         if (g_bleServerSendQueueHandle)
3284         {
3285             CALERemoveSendQueueData(g_bleServerSendQueueHandle,
3286                                     g_bleServerSendDataMutex,
3287                                     address);
3288         }
3289 #endif
3290
3291 #ifdef __WITH_DTLS__
3292         CAcloseSslConnection(&localEndpoint);
3293 #endif
3294     }
3295
3296     oc_mutex_lock(g_bleNetworkCbMutex);
3297     if (g_connectionCallback)
3298     {
3299         g_connectionCallback(&localEndpoint, isConnected);
3300     }
3301     oc_mutex_unlock(g_bleNetworkCbMutex);
3302
3303     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
3304 }
3305
3306 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
3307 {
3308     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEDeviceStateChangedCb");
3309
3310     if (CA_ADAPTER_ENABLED == adapter_state)
3311     {
3312         oc_mutex_lock(g_bleIsServerMutex);
3313         switch (g_adapterType)
3314         {
3315             case ADAPTER_SERVER:
3316                 CALEAdapterGattServerStart();
3317                 break;
3318             case ADAPTER_CLIENT:
3319                 CALEAdapterGattClientStart();
3320                 break;
3321             case ADAPTER_BOTH_CLIENT_SERVER:
3322                 CALEAdapterGattServerStart();
3323                 CALEAdapterGattClientStart();
3324                 break;
3325             default:
3326                 break;
3327         }
3328         oc_mutex_unlock(g_bleIsServerMutex);
3329     }
3330     else
3331     {
3332         oc_mutex_lock(g_bleIsServerMutex);
3333         switch (g_adapterType)
3334         {
3335             case ADAPTER_SERVER:
3336                 CALEAdapterGattServerStop();
3337                 break;
3338             case ADAPTER_CLIENT:
3339                 CALEAdapterGattClientStop();
3340                 break;
3341             case ADAPTER_BOTH_CLIENT_SERVER:
3342                 CALEAdapterGattServerStop();
3343                 CALEAdapterGattClientStop();
3344                 break;
3345             default:
3346                 break;
3347         }
3348         oc_mutex_unlock(g_bleIsServerMutex);
3349     }
3350
3351     oc_mutex_lock(g_bleNetworkCbMutex);
3352     if (NULL != g_networkCallback)
3353     {
3354         g_networkCallback(CA_ADAPTER_GATT_BTLE, adapter_state);
3355     }
3356     else
3357     {
3358         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
3359     }
3360     oc_mutex_unlock(g_bleNetworkCbMutex);
3361
3362     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
3363 }
3364
3365 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
3366                                             const uint8_t *data,
3367                                             uint32_t dataLen)
3368 {
3369     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3370 #ifndef SINGLE_THREAD
3371     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
3372                         "g_bleClientSendQueueHandle is  NULL",
3373                         CA_STATUS_FAILED);
3374     VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
3375                         "g_bleClientSendDataMutex is NULL",
3376                         CA_STATUS_FAILED);
3377
3378     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%u]", dataLen);
3379
3380     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3381     if (!bleData)
3382     {
3383         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3384         return CA_MEMORY_ALLOC_FAILED;
3385     }
3386     // Add message to send queue
3387     oc_mutex_lock(g_bleClientSendDataMutex);
3388     CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData, sizeof(CALEData_t));
3389     oc_mutex_unlock(g_bleClientSendDataMutex);
3390 #endif
3391     return CA_STATUS_OK;
3392 }
3393
3394 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
3395                                             const uint8_t *data,
3396                                             uint32_t dataLen)
3397 {
3398     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
3399
3400     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3401
3402 #ifdef SINGLE_THREAD
3403     if (!CAIsLEConnected())
3404     {
3405         OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
3406         return CA_STATUS_FAILED;
3407     }
3408
3409     CAResult_t result = CALEServerSendDataSingleThread(data, dataLen);
3410     if (CA_STATUS_OK != result)
3411     {
3412         OIC_LOG(ERROR, CALEADAPTER_TAG, "CALEServerSendDataSingleThread failed");
3413         return CA_STATUS_FAILED;
3414     }
3415 #else
3416     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
3417                         "BleClientReceiverQueue is NULL",
3418                         CA_STATUS_FAILED);
3419     VERIFY_NON_NULL_RET(g_bleServerSendDataMutex, CALEADAPTER_TAG,
3420                         "BleClientSendDataMutex is NULL",
3421                         CA_STATUS_FAILED);
3422
3423     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG, "sendQueueHandle",
3424                         CA_STATUS_FAILED);
3425
3426     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
3427
3428     CALEData_t * const bleData =
3429         CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3430
3431     if (!bleData)
3432     {
3433         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3434         return CA_MEMORY_ALLOC_FAILED;
3435     }
3436
3437     // Add message to send queue
3438     oc_mutex_lock(g_bleServerSendDataMutex);
3439     CAQueueingThreadAddData(g_bleServerSendQueueHandle,
3440                             bleData,
3441                             sizeof(CALEData_t));
3442     oc_mutex_unlock(g_bleServerSendDataMutex);
3443 #endif
3444     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
3445     return CA_STATUS_OK;
3446 }
3447
3448 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
3449                                                 const uint8_t *data,
3450                                                 uint32_t dataLength,
3451                                                 uint32_t *sentLength)
3452 {
3453     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
3454
3455     //Input validation
3456     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3457     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3458
3459 #ifdef SINGLE_THREAD
3460     CALEDataReceiverHandlerSingleThread(data, dataLength);
3461
3462     if (g_singleThreadReceiveData->totalDataLen == g_singleThreadReceiveData->recvDataLen)
3463     {
3464         if(g_networkPacketReceivedCallback)
3465         {
3466             // will be filled by upper layer
3467             const CASecureEndpoint_t endpoint =
3468                 { .endpoint = { .adapter = CA_ADAPTER_GATT_BTLE } };
3469
3470             g_networkPacketReceivedCallback(&endpoint,
3471                                             g_singleThreadReceiveData->defragData,
3472                                             g_singleThreadReceiveData->recvDataLen);
3473         }
3474         g_singleThreadReceiveData->remoteEndpoint = NULL;
3475         OICFree(g_singleThreadReceiveData->defragData);
3476         g_singleThreadReceiveData->defragData = NULL;
3477         OICFree(g_singleThreadReceiveData);
3478         g_singleThreadReceiveData = NULL;
3479     }
3480 #else
3481     VERIFY_NON_NULL_RET(g_bleServerReceiverQueue,
3482                         CALEADAPTER_TAG,
3483                         "g_bleServerReceiverQueue",
3484                         CA_STATUS_FAILED);
3485
3486     //Add message to data queue
3487     CAEndpoint_t * const remoteEndpoint =
3488         CACreateEndpointObject(CA_DEFAULT_FLAGS,
3489                                CA_ADAPTER_GATT_BTLE,
3490                                remoteAddress,
3491                                0);
3492
3493     if (NULL == remoteEndpoint)
3494     {
3495         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3496         return CA_STATUS_FAILED;
3497     }
3498
3499     // Create bleData to add to queue
3500     OIC_LOG_V(DEBUG,
3501               CALEADAPTER_TAG,
3502               "Data received from LE Server layer [%d]",
3503               dataLength);
3504
3505     CALEData_t * const bleData =
3506         CACreateLEData(remoteEndpoint, data, dataLength, g_bleServerSenderInfo);
3507
3508     if (!bleData)
3509     {
3510         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3511         CAFreeEndpoint(remoteEndpoint);
3512         return CA_MEMORY_ALLOC_FAILED;
3513     }
3514
3515     CAFreeEndpoint(remoteEndpoint);
3516     // Add message to receiver queue
3517     CAQueueingThreadAddData(g_bleServerReceiverQueue, bleData, sizeof(CALEData_t));
3518
3519     *sentLength = dataLength;
3520 #endif
3521     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
3522     return CA_STATUS_OK;
3523 }
3524
3525 static&nbs