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