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