Imported Upstream version 1.0.0
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / bt_edr_adapter / caedradapter.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
21 /**
22  * @file
23  *
24  * This file contains the APIs for EDR adapter.
25  */
26
27 #include "caedradapter.h"
28
29 #include "caedrinterface.h"
30 #include "caadapterutils.h"
31 #include "logger.h"
32 #include "cafragmentation.h"
33 #include "caqueueingthread.h"
34 #include "oic_malloc.h"
35 #include "caremotehandler.h"
36
37 /**
38  * @var EDR_ADAPTER_TAG
39  * @brief Logging tag for module name.
40  */
41 #define EDR_ADAPTER_TAG "CA_EDR_ADAPTER"
42
43 /**
44  * @var g_edrThreadPool
45  * @brief Reference to threadpool.
46  */
47 static ca_thread_pool_t g_edrThreadPool = NULL;
48
49 /**
50  * @var g_sendQueueHandle
51  * @brief Queue handle for Send Data
52  */
53 static CAQueueingThread_t *g_sendQueueHandle = NULL;
54
55 /**
56  * @var g_recvQueueHandle
57  * @brief Queue handle for Receive Data
58  */
59 static CAQueueingThread_t *g_recvQueueHandle = NULL;
60
61 /**
62  * @var g_adapterState
63  * @brief Storing Adapter state information
64  */
65 static bool g_adapterState = true;
66
67 /**
68  * @var g_networkPacketReceivedCallback
69  * @brief Maintains the callback to be notified on receival of network packets from other
70  *          Bluetooth devices.
71  */
72 static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
73
74 /**
75  * @var g_networkChangeCallback
76  * @brief Maintains the callback to be notified on local bluetooth adapter status change.
77  */
78 static CANetworkChangeCallback g_networkChangeCallback = NULL;
79
80 /**
81  * @var g_errorCallback
82  * @brief error Callback to CA adapter
83  */
84 static CAErrorHandleCallback g_errorCallback = NULL;
85
86 /**
87  * @var g_localConnectivity
88  * @brief Information of local Bluetooth adapter.
89  */
90 static CAEndpoint_t *g_localConnectivity = NULL;
91
92 /**
93  * @var g_serverState
94  * @brief Storing Rfcommserver state information
95  */
96 static bool g_serverState = false;
97
98 /**
99  * Stores information of all the senders.
100  *
101  * This structure will be used to track and defragment all incoming
102  * data packet.
103  */
104 typedef struct
105 {
106     uint32_t recvDataLen;
107     uint32_t totalDataLen;
108     uint8_t *defragData;
109     CAEndpoint_t *remoteEndpoint;
110 } CAEDRSenderInfo_t;
111
112 /**
113  * Sender information.
114  */
115 static u_arraylist_t *g_senderInfo = NULL;
116
117 static CAResult_t CAStartServer();
118 static CAResult_t CAEDRInitializeQueueHandlers();
119 CAResult_t CAEDRInitializeSendHandler();
120 CAResult_t CAEDRInitializeReceiveHandler();
121 void CAAdapterTerminateQueues();
122 void CAAdapterDataSendHandler(void *context);
123 void CAAdapterDataReceiverHandler(void *context);
124 CAResult_t CAAdapterStopQueue();
125 void CAAdapterRecvData(const char *remoteAddress, const uint8_t *data, uint32_t dataLength,
126                        uint32_t *sentLength);
127 void CAEDRNotifyNetworkStatus(CANetworkStatus_t status);
128 void CAEDROnNetworkStatusChanged(void *context);
129 CAResult_t CAAdapterSendData(const char *remoteAddress, const char *serviceUUID, const uint8_t *data,
130                              uint32_t dataLength, uint32_t *sentLength);
131 CAEDRNetworkEvent *CAEDRCreateNetworkEvent(CAEndpoint_t *connectivity,
132                                            CANetworkStatus_t status);
133
134 CAResult_t CAEDRClientSendData(const char *remoteAddress,
135                                const uint8_t *data,
136                                uint32_t dataLength);
137
138 /**
139  * @fn CACreateEDRData
140  * @brief Helper function to create CAEDRData
141  */
142 static CAEDRData *CACreateEDRData(const CAEndpoint_t *remoteEndpoint, const uint8_t *data,
143                                   uint32_t dataLength);
144
145 /**
146  * @fn CAFreeEDRData
147  * @brief Free the Created EDR data
148  */
149 static void CAFreeEDRData(CAEDRData *edrData);
150
151 /**
152  * @fn CAEDRFreeNetworkEvent
153  * @brief Free the memory associated with @event.
154  */
155 void CAEDRFreeNetworkEvent(CAEDRNetworkEvent *event);
156
157 static void CAEDRDataDestroyer(void *data, uint32_t size);
158
159 static void CAEDRErrorHandler(const char *remoteAddress, const uint8_t *data,
160                               uint32_t dataLength, CAResult_t result);
161
162 static void CAEDRClearSenderInfo();
163
164 CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback,
165                            CANetworkPacketReceivedCallback packetReceivedCallback,
166                            CANetworkChangeCallback networkStateChangeCallback,
167                            CAErrorHandleCallback errorCallback, ca_thread_pool_t handle)
168 {
169     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
170
171     // Input validation
172     VERIFY_NON_NULL(registerCallback, EDR_ADAPTER_TAG, "register callback is NULL");
173     VERIFY_NON_NULL(packetReceivedCallback, EDR_ADAPTER_TAG, "data receive callback is NULL");
174     VERIFY_NON_NULL(networkStateChangeCallback, EDR_ADAPTER_TAG,
175                     "network state change callback is NULL");
176     VERIFY_NON_NULL(handle, EDR_ADAPTER_TAG, "Thread pool handle is NULL");
177
178     // Register the callbacks
179
180     g_edrThreadPool = handle;
181     g_networkPacketReceivedCallback = packetReceivedCallback;
182     g_networkChangeCallback = networkStateChangeCallback;
183     g_errorCallback = errorCallback;
184
185     // Initialize EDR Network Monitor
186     CAResult_t err = CAEDRInitializeNetworkMonitor(handle);
187     if (CA_STATUS_OK != err)
188     {
189         OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "EDR N/w Monitor Initialize failed!, error number [%d]",
190                   err);
191         return err;
192     }
193
194     CAEDRSetNetworkChangeCallback(CAEDRNotifyNetworkStatus);
195     CAEDRSetPacketReceivedCallback(CAAdapterRecvData);
196     CAEDRSetErrorHandler(CAEDRErrorHandler);
197     CAEDRInitializeClient(handle);
198
199     CAConnectivityHandler_t handler;
200     handler.startAdapter = CAStartEDR;
201     handler.startListenServer = CAStartEDRListeningServer;
202     handler.stopListenServer = CAStopEDRListeningServer;
203     handler.startDiscoveryServer = CAStartEDRDiscoveryServer;
204     handler.sendData = CASendEDRUnicastData;
205     handler.sendDataToAll = CASendEDRMulticastData;
206     handler.GetnetInfo = CAGetEDRInterfaceInformation;
207     handler.readData = CAReadEDRData;
208     handler.stopAdapter = CAStopEDR;
209     handler.terminate = CATerminateEDR;
210     registerCallback(handler, CA_ADAPTER_RFCOMM_BTEDR);
211
212     // Initialize Send/Receive data message queues
213     if (CA_STATUS_OK != CAEDRInitializeQueueHandlers())
214     {
215         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "CAAdapterInitializeQueues API failed");
216         CATerminateEDR();
217         return CA_STATUS_FAILED;
218     }
219
220     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
221     return CA_STATUS_OK;
222 }
223
224 CAResult_t CAStartEDR()
225 {
226     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
227
228     //Start Monitoring EDR Network
229     CAResult_t ret = CAEDRStartNetworkMonitor();
230     if (CA_STATUS_OK != ret)
231     {
232        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to Start n/w monitor");
233     }
234
235     // Get Bluetooth adapter state
236     bool adapterState = false;
237     if (CA_STATUS_OK != CAEDRGetAdapterEnableState(&adapterState))
238     {
239         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to get adapter enable state");
240         return CA_STATUS_FAILED;
241     }
242
243     if (false == adapterState)
244     {
245         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Bluetooth adapter is disabled!");
246         g_adapterState = false;
247         return CA_ADAPTER_NOT_ENABLED;
248     }
249
250     if (CA_STATUS_OK != (ret = CAEDRClientSetCallbacks()))
251     {
252         OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Start Network Monitor failed!, error number [%d] ",
253                   ret);
254     }
255
256     if (CA_STATUS_OK != (ret = CAAdapterStartQueue()))
257     {
258         OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "CAAdapterStartQueue failed!, error number [%d] ", ret);
259     }
260
261     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
262     return ret;
263 }
264
265 CAResult_t CAStartEDRListeningServer()
266 {
267     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
268
269     return CAStartServer();
270 }
271
272 CAResult_t CAStopEDRListeningServer()
273 {
274     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
275
276     return CAEDRServerStop();
277 }
278
279 CAResult_t CAStartEDRDiscoveryServer()
280 {
281     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
282
283     return CAStartServer();
284 }
285
286 int32_t CASendEDRUnicastData(const CAEndpoint_t *remoteEndpoint, const void *data,
287                              uint32_t dataLength)
288 {
289     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
290
291     // Input validation
292     VERIFY_NON_NULL_RET(remoteEndpoint, EDR_ADAPTER_TAG, "Remote endpoint is null", -1);
293     VERIFY_NON_NULL_RET(data, EDR_ADAPTER_TAG, "Data is null", -1);
294
295     if (0 == dataLength)
296     {
297         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Invalid input: data length is zero!");
298         return -1;
299     }
300
301     if (0 == strlen(remoteEndpoint->addr))
302     {
303         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Invalid input: EDR Address is empty!");
304         return -1;
305     }
306
307     uint32_t sentLength = 0;
308     const char *serviceUUID = OIC_EDR_SERVICE_ID;
309     const char *address = remoteEndpoint->addr;
310     CAResult_t err = CAAdapterSendData(address, serviceUUID, data, dataLength, &sentLength);
311     if (CA_STATUS_OK != err)
312     {
313         OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Send unicast data failed!, error num [%d]", err);
314         g_errorCallback(remoteEndpoint, data, dataLength, err);
315         return -1;
316     }
317
318     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
319     return sentLength;
320 }
321
322 int32_t CASendEDRMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLength)
323 {
324     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN - CASendEDRMulticastData");
325
326     // Input validation
327     VERIFY_NON_NULL_RET(data, EDR_ADAPTER_TAG, "Data is null", -1);
328
329     if (0 == dataLength)
330     {
331         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Invalid input: data length is zero!");
332         return -1;
333     }
334
335     uint32_t sentLen = 0;
336     const char *serviceUUID = OIC_EDR_SERVICE_ID;
337     CAResult_t err = CAAdapterSendData(NULL, serviceUUID, data, dataLength, &sentLen);
338     if (CA_STATUS_OK != err)
339     {
340         OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Send multicast data failed!, error num [%d]", err);
341         g_errorCallback(endpoint, data, dataLength, err);
342         return -1;
343     }
344
345     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT - CASendEDRMulticastData");
346     return sentLen;
347 }
348
349 CAResult_t CAGetEDRInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
350 {
351     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
352
353     VERIFY_NON_NULL(info, EDR_ADAPTER_TAG, "LocalConnectivity info is null");
354
355     CAResult_t err = CA_STATUS_OK;
356     *size = 0;
357     if (CA_STATUS_OK != (err = CAEDRGetInterfaceInformation(info)))
358     {
359         OIC_LOG_V(ERROR, EDR_ADAPTER_TAG,
360                   "Failed to get local interface information!, error num [%d]", err);
361         return err;
362     }
363
364     *size = 1;
365     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
366     return err;
367 }
368
369 CAResult_t CAReadEDRData()
370 {
371     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
372
373     return CAEDRManagerReadData();
374 }
375
376 CAResult_t CAStopEDR()
377 {
378     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
379
380     // Stop RFComm server if it is running
381     CAEDRServerStop();
382
383     // Stop network monitor
384     CAEDRStopNetworkMonitor();
385
386     // Stop the adapter
387     CAEDRClientUnsetCallbacks();
388
389     // Disconnect all the client connections
390     CAEDRClientDisconnectAll();
391
392     // Stop Send and receive Queue
393     CAAdapterStopQueue();
394
395     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
396     return CA_STATUS_OK;
397 }
398
399 void CATerminateEDR()
400 {
401     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
402
403     // Terminate EDR Network Monitor
404     CAEDRTerminateNetworkMonitor();
405
406     // Terminate Send/Receive data messages queues
407     CAAdapterTerminateQueues();
408
409     g_networkPacketReceivedCallback = NULL;
410     g_networkChangeCallback = NULL;
411
412     // Terminate thread pool
413     g_edrThreadPool = NULL;
414
415     // Terminate EDR Client
416     CAEDRClientTerminate();
417
418     // Terminate EDR Server
419     CAEDRServerTerminate();
420
421     // Free LocalConnectivity information
422     CAFreeEndpoint(g_localConnectivity);
423     g_localConnectivity = NULL;
424
425     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
426 }
427
428 CAResult_t CAStartServer()
429 {
430     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
431
432     CAResult_t err = CA_STATUS_OK;
433
434     if (false == g_adapterState)
435     {
436         OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Bluetooth adapter is disabled!");
437         // Setting g_serverState for starting Rfcommserver when adapter starts
438         g_serverState = true;
439         return CA_STATUS_OK;
440     }
441
442     if (CA_STATUS_OK != (err = CAEDRServerStart(g_edrThreadPool)))
443     {
444         OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to start RFCOMM server!, error num [%d]",
445                   err);
446         return err;
447     }
448
449     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
450     return err;
451 }
452
453 CAResult_t CAEDRInitializeQueueHandlers()
454 {
455     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
456
457     if (CA_STATUS_OK == CAEDRInitializeSendHandler()
458         && CA_STATUS_OK == CAEDRInitializeReceiveHandler())
459     {
460         OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Queue is initialized!");
461         return CA_STATUS_OK;
462     }
463
464     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
465     return CA_STATUS_FAILED;
466 }
467
468 CAResult_t CAEDRInitializeSendHandler()
469 {
470     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
471     // Check if the message queue is already initialized
472     if (g_sendQueueHandle)
473     {
474         OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Already queue is initialized!");
475         return CA_STATUS_OK;
476     }
477
478     g_sendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
479     if (!g_sendQueueHandle)
480     {
481         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Memory allocation failed!");
482         return CA_MEMORY_ALLOC_FAILED;
483     }
484
485     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_sendQueueHandle, g_edrThreadPool,
486                                                    CAAdapterDataSendHandler, CAEDRDataDestroyer))
487     {
488         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to Initialize send queue thread");
489         return CA_STATUS_FAILED;
490     }
491     return CA_STATUS_OK;
492 }
493
494 CAResult_t CAEDRInitializeReceiveHandler()
495 {
496     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
497     // Check if the message queue is already initialized
498     if (g_recvQueueHandle)
499     {
500         OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Already queue is initialized!");
501         return CA_STATUS_OK;
502     }
503
504     g_recvQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
505     if (!g_recvQueueHandle)
506     {
507         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Memory allocation failed!");
508         return CA_MEMORY_ALLOC_FAILED;
509     }
510
511     g_senderInfo = u_arraylist_create();
512     if (!g_senderInfo)
513     {
514         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "ClientInfo memory allcation failed!");
515         OICFree(g_recvQueueHandle);
516         g_recvQueueHandle = NULL;
517         return CA_MEMORY_ALLOC_FAILED;
518     }
519
520     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_recvQueueHandle, g_edrThreadPool,
521                                                    CAAdapterDataReceiverHandler,
522                                                    CAEDRDataDestroyer))
523     {
524         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to Initialize send queue thread");
525         u_arraylist_free(&g_senderInfo);
526         OICFree(g_recvQueueHandle);
527         g_recvQueueHandle = NULL;
528         return CA_STATUS_FAILED;
529     }
530
531     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
532     return CA_STATUS_OK;
533 }
534
535 void CAAdapterTerminateQueues()
536 {
537     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
538
539     if (g_sendQueueHandle)
540     {
541         CAQueueingThreadDestroy(g_sendQueueHandle);
542         g_sendQueueHandle = NULL;
543     }
544     if (g_recvQueueHandle)
545     {
546         CAQueueingThreadDestroy(g_recvQueueHandle);
547         g_recvQueueHandle = NULL;
548     }
549
550     CAEDRClearSenderInfo();
551
552     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
553 }
554
555 void CAAdapterDataSendHandler(void *context)
556 {
557     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN - CAAdapterDataSendHandler");
558
559     CAEDRData *message = (CAEDRData *) context;
560     if (NULL == message)
561     {
562         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to get message!");
563         return;
564     }
565
566     const char *remoteAddress = NULL;
567
568     if (NULL == message->remoteEndpoint)
569     {
570         OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "remoteEndpoint is not available");
571         return;
572     }
573     else
574     {
575         remoteAddress = message->remoteEndpoint->addr;
576     }
577
578     if(!remoteAddress)
579     {
580         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "EDR Send Message error");
581         //Error cannot be sent if remote address is NULL
582         return;
583     }
584
585     uint32_t dataSegmentLength = message->dataLen + CA_HEADER_LENGTH;
586
587     uint8_t *header = (uint8_t *) OICCalloc(CA_HEADER_LENGTH, sizeof(uint8_t));
588     VERIFY_NON_NULL_VOID(header, EDR_ADAPTER_TAG, "Memory allocation failed");
589
590     uint8_t* dataSegment = (uint8_t *) OICCalloc(dataSegmentLength, sizeof(uint8_t));
591     if (NULL == dataSegment)
592     {
593         CAEDRErrorHandler(remoteAddress, message->data, message->dataLen, CA_SEND_FAILED);
594         OICFree(header);
595         return;
596     }
597
598     CAResult_t result = CAGenerateHeader(header, CA_HEADER_LENGTH, message->dataLen);
599     if (CA_STATUS_OK != result)
600     {
601         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Generate header failed");
602         OICFree(header);
603         OICFree(dataSegment);
604         CAEDRErrorHandler(remoteAddress, message->data, message->dataLen, result);
605         return;
606     }
607
608     memcpy(dataSegment, header, CA_HEADER_LENGTH);
609     OICFree(header);
610
611     memcpy(dataSegment + CA_HEADER_LENGTH, message->data, message->dataLen);
612
613     result = CAEDRClientSendData(remoteAddress, dataSegment, dataSegmentLength);
614     OICFree(dataSegment);
615
616     if (CA_STATUS_OK != result)
617     {
618         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "CAEDRClientSendData API failed");
619         CAEDRErrorHandler(remoteAddress, message->data, message->dataLen, result);
620         return;
621     }
622
623     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
624 }
625
626 CAResult_t CAEDRClientSendData(const char *remoteAddress,
627                                const uint8_t *data,
628                                uint32_t dataLength)
629 {
630
631     CAResult_t result = CA_SEND_FAILED;
632
633     // Send the first segment with the header.
634     if ((NULL != remoteAddress) && (0 < strlen(remoteAddress))) //Unicast data
635     {
636         result = CAEDRClientSendUnicastData(remoteAddress, data, dataLength);
637         if (CA_STATUS_OK != result)
638         {
639             OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to send unicast data !");
640             return result;
641         }
642     }
643     else
644     {
645         OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "sending multicast data : %s", data);
646         result = CAEDRClientSendMulticastData(data, dataLength);
647
648         if (CA_STATUS_OK != result)
649         {
650             OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to send multicast data !");
651             return result;
652         }
653     }
654     return result;
655 }
656
657 static void CAEDRClearSenderInfo()
658 {
659     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
660
661     uint32_t listIndex = 0;
662     uint32_t listLength = u_arraylist_length(g_senderInfo);
663     for (listIndex = 0; listIndex < listLength; listIndex++)
664     {
665         CAEDRSenderInfo_t *info = (CAEDRSenderInfo_t *) u_arraylist_get(g_senderInfo, listIndex);
666         if (!info)
667         {
668             continue;
669         }
670
671         OICFree(info->defragData);
672         CAFreeEndpoint(info->remoteEndpoint);
673         OICFree(info);
674     }
675     u_arraylist_free(&g_senderInfo);
676     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
677 }
678
679 static CAResult_t CAEDRGetSenderInfo(const char *edrAddress,
680                                      CAEDRSenderInfo_t **senderInfo,
681                                      uint32_t *senderIndex)
682 {
683     VERIFY_NON_NULL_RET(edrAddress,
684                         EDR_ADAPTER_TAG,
685                         "NULL edr address argument",
686                         CA_STATUS_INVALID_PARAM);
687     VERIFY_NON_NULL_RET(senderIndex,
688                         EDR_ADAPTER_TAG,
689                         "NULL index argument",
690                         CA_STATUS_INVALID_PARAM);
691
692     const uint32_t listLength = u_arraylist_length(g_senderInfo);
693     const uint32_t addrLength = strlen(edrAddress);
694     for (uint32_t index = 0; index < listLength; index++)
695     {
696         CAEDRSenderInfo_t *info = (CAEDRSenderInfo_t *) u_arraylist_get(g_senderInfo, index);
697         if (!info || !(info->remoteEndpoint))
698         {
699             continue;
700         }
701
702         if (!strncmp(info->remoteEndpoint->addr, edrAddress, addrLength))
703         {
704             *senderIndex = index;
705             if (senderInfo)
706             {
707                 *senderInfo = info;
708             }
709             return CA_STATUS_OK;
710         }
711     }
712
713     return CA_STATUS_FAILED;
714 }
715
716 void CAAdapterDataReceiverHandler(void *context)
717 {
718     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN_CAAdapterDataReceiverHandler");
719
720     if (NULL == g_networkPacketReceivedCallback)
721     {
722         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "g_networkPacketReceivedCallback is NULL");
723         return;
724     }
725
726     CAEDRData *message = (CAEDRData *) context;
727     if (NULL == message || NULL == message->remoteEndpoint)
728     {
729         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to get message!");
730         return;
731     }
732     uint32_t dataLen = 0;
733
734     CAEDRSenderInfo_t *senderInfo = NULL;
735     uint32_t senderIndex = 0;
736
737     while (dataLen < message->dataLen)
738     {
739         if(CA_STATUS_OK != CAEDRGetSenderInfo(message->remoteEndpoint->addr,
740                                               &senderInfo, &senderIndex))
741         {
742             OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "This is a new client [%s]",
743                                                 message->remoteEndpoint->addr);
744         }
745
746         if (!senderInfo)
747         {
748             CAEDRSenderInfo_t *newSender = OICMalloc(sizeof(CAEDRSenderInfo_t));
749             if (!newSender)
750             {
751                 return;
752             }
753             newSender->recvDataLen = 0;
754             newSender->totalDataLen = 0;
755             newSender->defragData = NULL;
756             newSender->remoteEndpoint = NULL;
757
758             OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Parsing the header");
759             newSender->totalDataLen = CAParseHeader(message->data + dataLen,
760                                                     message->dataLen - dataLen);
761             if(!(newSender->totalDataLen))
762             {
763                 OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Total Data Length is parsed as 0!!!");
764                 OICFree(newSender);
765                 return;
766             }
767
768             OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "Total data to be accumulated [%u] bytes",
769                                                 newSender->totalDataLen);
770             OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "data received in the first packet [%u] bytes",
771                                                 message->dataLen);
772
773             newSender->defragData = OICCalloc(newSender->totalDataLen,
774                                               sizeof(*newSender->defragData));
775
776             if (NULL == newSender->defragData)
777             {
778                 OICFree(newSender);
779                 return;
780             }
781
782             newSender->remoteEndpoint = CACloneEndpoint(message->remoteEndpoint);
783             if (NULL == newSender->remoteEndpoint)
784             {
785                 OIC_LOG(ERROR, EDR_ADAPTER_TAG, "remoteEndpoint is NULL!");
786                 OICFree(newSender->defragData);
787                 OICFree(newSender);
788                 return;
789             }
790
791             if (message->dataLen - CA_HEADER_LENGTH - dataLen <= newSender->totalDataLen)
792             {
793                 memcpy(newSender->defragData, message->data + dataLen + CA_HEADER_LENGTH,
794                        message->dataLen - dataLen - CA_HEADER_LENGTH);
795                 newSender->recvDataLen += message->dataLen - dataLen - CA_HEADER_LENGTH;
796                 u_arraylist_add(g_senderInfo,(void *)newSender);
797                 dataLen = message->dataLen;
798             }
799             else
800             {
801                 memcpy(newSender->defragData, message->data + dataLen + CA_HEADER_LENGTH,
802                        newSender->totalDataLen);
803                 newSender->recvDataLen = newSender->totalDataLen;
804                 u_arraylist_add(g_senderInfo,(void *)newSender);
805                 dataLen += newSender->totalDataLen + CA_HEADER_LENGTH;
806             }
807             //Getting newSender index position in g_senderInfo array list
808             if (CA_STATUS_OK !=
809                 CAEDRGetSenderInfo(newSender->remoteEndpoint->addr, NULL, &senderIndex))
810             {
811                 OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Existing sender index not found!!");
812                 OICFree(newSender->defragData);
813                 CAFreeEndpoint(newSender->remoteEndpoint);
814                 OICFree(newSender);
815                 return;
816             }
817             senderInfo = newSender;
818         }
819         else
820         {
821             if (senderInfo->recvDataLen + message->dataLen - dataLen <= senderInfo->totalDataLen)
822             {
823                 OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "Copying the data of length [%d]",
824                           message->dataLen - dataLen);
825                 memcpy(senderInfo->defragData + senderInfo->recvDataLen, message->data + dataLen,
826                        message->dataLen - dataLen);
827                 senderInfo->recvDataLen += message->dataLen - dataLen;
828                 OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "totalDatalength  [%d] recveived Datalen [%d]",
829                           senderInfo->totalDataLen, senderInfo->recvDataLen);
830                 dataLen = message->dataLen;
831             }
832             else
833             {
834                 OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "Copying the data of length [%d]",
835                           senderInfo->totalDataLen - senderInfo->recvDataLen);
836                 memcpy(senderInfo->defragData + senderInfo->recvDataLen, message->data + dataLen,
837                        senderInfo->totalDataLen - senderInfo->recvDataLen);
838                 dataLen += senderInfo->totalDataLen - senderInfo->recvDataLen;
839                 senderInfo->recvDataLen = senderInfo->totalDataLen;
840                 OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "totalDatalength  [%d] recveived Datalen [%d]",
841                           senderInfo->totalDataLen, senderInfo->recvDataLen);
842             }
843         }
844
845         if (senderInfo->totalDataLen == senderInfo->recvDataLen)
846         {
847             OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Sending data up !");
848
849             CASecureEndpoint_t sep = {.endpoint = *(senderInfo->remoteEndpoint)};
850             g_networkPacketReceivedCallback(&sep, senderInfo->defragData, senderInfo->recvDataLen);
851             u_arraylist_remove(g_senderInfo, senderIndex);
852             senderInfo->remoteEndpoint = NULL;
853             senderInfo->defragData = NULL;
854             OICFree(senderInfo);
855             senderInfo = NULL;
856         }
857     }
858     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT_CAAdapterDataReceiverHandler");
859 }
860
861 CAResult_t CAAdapterStartQueue()
862 {
863     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
864     // Start send queue thread
865     if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle))
866     {
867         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to Start Send Data Thread");
868         CAEDRClientUnsetCallbacks();
869         //Disconnect all the client connections
870         CAEDRClientDisconnectAll();
871         return CA_STATUS_FAILED;
872     }
873
874     // Start receive queue thread
875     if (CA_STATUS_OK != CAQueueingThreadStart(g_recvQueueHandle))
876     {
877         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to Start Receive Data Thread");
878         CAEDRClientUnsetCallbacks();
879         //Disconnect all the client connections
880         CAEDRClientDisconnectAll();
881         return CA_STATUS_FAILED;
882     }
883     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
884     return CA_STATUS_OK;
885 }
886
887 CAResult_t CAAdapterStopQueue()
888 {
889     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
890     //Stop send queue thread
891     CAQueueingThreadStop(g_sendQueueHandle);
892
893     //Stop receive queue thread
894     CAQueueingThreadStop(g_recvQueueHandle);
895     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
896     return CA_STATUS_OK;
897 }
898
899 void CAAdapterRecvData(const char *remoteAddress, const uint8_t *data, uint32_t dataLength,
900                        uint32_t *sentLength)
901 {
902     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
903
904     if (false == g_adapterState)
905     {
906         OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Bluetooth adapter is disabled!");
907         *sentLength = 0;
908         return;
909     }
910
911     // Input validation
912     VERIFY_NON_NULL_VOID(data, EDR_ADAPTER_TAG, "Data is null");
913     VERIFY_NON_NULL_VOID(sentLength, EDR_ADAPTER_TAG, "Sent data length holder is null");
914
915     // Create remote endpoint
916     CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
917                                                           CA_ADAPTER_RFCOMM_BTEDR,
918                                                           remoteAddress, 0);
919     if (NULL == remoteEndpoint)
920     {
921         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to create remote endpoint !");
922         return;
923     }
924
925     // Add message to data queue
926     CAEDRData *edrData =  CACreateEDRData(remoteEndpoint, data, dataLength);
927     CAQueueingThreadAddData(g_recvQueueHandle, edrData, sizeof(CAEDRData));
928     *sentLength = dataLength;
929
930     // Free remote endpoint
931     CAFreeEndpoint(remoteEndpoint);
932
933     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
934 }
935
936 void CAEDRErrorHandler(const char *remoteAddress, const uint8_t *data,
937                        uint32_t dataLength, CAResult_t result)
938 {
939     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
940
941     // Input validation
942     VERIFY_NON_NULL_VOID(data, EDR_ADAPTER_TAG, "Data is null");
943
944     // Create remote endpoint
945     CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(0, CA_ADAPTER_RFCOMM_BTEDR,
946                                                            remoteAddress, 0);
947     if (!remoteEndpoint)
948     {
949         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to create remote endpoint !");
950         return;
951     }
952
953     g_errorCallback(remoteEndpoint, data, dataLength, result);
954
955     // Free remote endpoint
956     CAFreeEndpoint(remoteEndpoint);
957
958     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
959 }
960
961 CAResult_t CAAdapterSendData(const char *remoteAddress, const char *serviceUUID, const uint8_t *data,
962                              uint32_t dataLength, uint32_t *sentLength)
963 {
964     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN - CAAdapterSendData");
965
966     if (false == g_adapterState)
967     {
968         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Bluetooth adapter is disabled!");
969         *sentLength = 0;
970         return CA_ADAPTER_NOT_ENABLED;
971     }
972     // Input validation
973     VERIFY_NON_NULL(serviceUUID, EDR_ADAPTER_TAG, "service UUID is null");
974     VERIFY_NON_NULL(data, EDR_ADAPTER_TAG, "Data is null");
975     VERIFY_NON_NULL(sentLength, EDR_ADAPTER_TAG, "Sent data length holder is null");
976
977     // Create remote endpoint
978     CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
979                                                           CA_ADAPTER_RFCOMM_BTEDR,
980                                                           remoteAddress, 0);
981     if (NULL == remoteEndpoint)
982     {
983         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to create remote endpoint !");
984         return CA_MEMORY_ALLOC_FAILED;
985     }
986
987     // Add message to data queue
988     CAEDRData *edrData =  CACreateEDRData(remoteEndpoint, data, dataLength);
989     CAQueueingThreadAddData(g_sendQueueHandle, edrData, sizeof (CAEDRData));
990     *sentLength = dataLength;
991
992     // Free remote endpoint
993     CAFreeEndpoint(remoteEndpoint);
994
995     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT - CAAdapterSendData");
996     return CA_STATUS_OK;
997 }
998
999 void CAEDRNotifyNetworkStatus(CANetworkStatus_t status)
1000 {
1001     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
1002
1003     // Create localconnectivity
1004     if (NULL == g_localConnectivity)
1005     {
1006         CAEDRGetInterfaceInformation(&g_localConnectivity);
1007     }
1008
1009     if (CA_INTERFACE_UP == status)
1010     {
1011         if (false == g_adapterState)
1012         {
1013             // Get Bluetooth adapter state
1014             bool adapterState = false;
1015             if (CA_STATUS_OK != CAEDRGetAdapterEnableState(&adapterState))
1016             {
1017                 OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to get adapter enable state");
1018                 return;
1019             }
1020
1021             if (false== adapterState)
1022             {
1023                 OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Bluetooth adapter is disabled!");
1024                 g_adapterState = false;
1025                 return;
1026             }
1027             CAEDRClientSetCallbacks();
1028             g_adapterState = true;
1029             CAAdapterStartQueue();
1030             // starting RFCommServer
1031             if (true == g_serverState)
1032             {
1033                 CAStartServer();
1034                 g_serverState = false;
1035             }
1036         }
1037     }
1038     else
1039     {
1040         g_adapterState = false;
1041     }
1042
1043     // Notify to upper layer
1044     if (g_networkChangeCallback && g_localConnectivity && g_edrThreadPool)
1045     {
1046         // Add notification task to thread pool
1047         CAEDRNetworkEvent *event = CAEDRCreateNetworkEvent(g_localConnectivity, status);
1048         if (NULL != event)
1049         {
1050             if (CA_STATUS_OK != ca_thread_pool_add_task(g_edrThreadPool,
1051                                                         CAEDROnNetworkStatusChanged,event))
1052             {
1053                 OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to create threadpool!");
1054                 return;
1055             }
1056         }
1057     }
1058
1059     OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
1060 }
1061
1062 void CAEDROnNetworkStatusChanged(void *context)
1063 {
1064     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
1065
1066     if (NULL == context)
1067     {
1068         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "context is NULL!");
1069         return;
1070     }
1071
1072     CAEDRNetworkEvent *networkEvent = (CAEDRNetworkEvent *) context;
1073
1074     // Notify to upper layer
1075     if (g_networkChangeCallback)
1076     {
1077         g_networkChangeCallback(networkEvent->info, networkEvent->status);
1078     }
1079
1080     // Free the created Network event
1081     CAEDRFreeNetworkEvent(networkEvent);
1082
1083     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
1084 }
1085
1086 CAEDRNetworkEvent *CAEDRCreateNetworkEvent(CAEndpoint_t *connectivity,
1087                                            CANetworkStatus_t status)
1088 {
1089     VERIFY_NON_NULL_RET(connectivity, EDR_ADAPTER_TAG, "connectivity is NULL", NULL);
1090
1091     // Create CAEDRNetworkEvent
1092     CAEDRNetworkEvent *event = (CAEDRNetworkEvent *) OICMalloc(sizeof(CAEDRNetworkEvent));
1093     if (NULL == event)
1094     {
1095         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to allocate memory to network event!");
1096         return NULL;
1097     }
1098
1099     // Create duplicate of Local connectivity
1100     event->info = CACloneEndpoint(connectivity);
1101     event->status = status;
1102     return event;
1103 }
1104
1105 void CAEDRFreeNetworkEvent(CAEDRNetworkEvent *event)
1106 {
1107     if (event)
1108     {
1109         CAFreeEndpoint(event->info);
1110         OICFree(event);
1111     }
1112 }
1113
1114 CAEDRData *CACreateEDRData(const CAEndpoint_t *remoteEndpoint,
1115                                         const uint8_t *data, uint32_t dataLength)
1116 {
1117     CAEDRData *edrData = (CAEDRData *)OICMalloc(sizeof (CAEDRData));
1118     if (!edrData)
1119     {
1120         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Memory allocation failed!");
1121         return NULL;
1122     }
1123
1124     edrData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
1125
1126     edrData->data = OICMalloc(dataLength);
1127     if (NULL == edrData->data)
1128     {
1129         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Memory allocation failed!");
1130         CAFreeEDRData(edrData);
1131         return NULL;
1132     }
1133     memcpy(edrData->data, data, dataLength);
1134     edrData->dataLen = dataLength;
1135
1136     return edrData;
1137 }
1138
1139 void CAFreeEDRData(CAEDRData *edrData)
1140 {
1141     VERIFY_NON_NULL_VOID(edrData, EDR_ADAPTER_TAG, "edrData is NULL");
1142
1143     CAFreeEndpoint(edrData->remoteEndpoint);
1144     OICFree(edrData->data);
1145     OICFree(edrData);
1146 }
1147
1148 void CAEDRDataDestroyer(void *data, uint32_t size)
1149 {
1150     if ((size_t)size < sizeof(CAEDRData))
1151     {
1152         OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Destroy data too small %p %d",
1153                   data, size);
1154     }
1155     CAEDRData *edrdata = (CAEDRData *) data;
1156
1157     CAFreeEDRData(edrdata);
1158 }