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