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