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