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