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