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