1 /* ****************************************************************
3 * Copyright 2014 Samsung Electronics All Rights Reserved.
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 ******************************************************************/
20 #include "caleadapter.h"
25 #include "cafragmentation.h"
27 #include "caleinterface.h"
30 #include "caadapterutils.h"
32 #include "ca_adapter_net_ssl.h"
35 #include "caqueueingthread.h"
37 #if defined(__TIZEN__) || defined(__ANDROID__)
38 #include "caleserver.h"
39 #include "caleclient.h"
41 #include "oic_malloc.h"
42 #include "oic_string.h"
43 #include "caremotehandler.h"
47 * Logging tag for module name.
49 #define CALEADAPTER_TAG "OIC_CA_LE_ADAP"
52 * Stores information of all the senders.
54 * This structure will be used to track and defragment all incoming data packet.
59 uint32_t totalDataLen;
61 CAEndpoint_t *remoteEndpoint;
67 ADAPTER_BOTH_CLIENT_SERVER,
73 * mtu size to use in fragmentation logic.
74 * default value is 20 byte.
76 static uint16_t g_mtuSize = CA_DEFAULT_BLE_MTU_SIZE;
78 * Callback to provide the status of the network change to CA layer.
80 static CAAdapterChangeCallback g_networkCallback = NULL;
83 * Callback to provide the status of the connection change to CA layer.
85 static CAConnectionChangeCallback g_connectionCallback = NULL;
88 * Own port value to identify packet owner. Default port value is 1.
90 static uint8_t g_localBLESourcePort = 1;
93 * bleAddress of the local adapter. Value will be initialized to zero,
94 * and will be updated later.
96 static char g_localBLEAddress[18] = { 0 };
99 * Variable to differentiate btw GattServer and GattClient.
101 static CABLEAdapter_t g_adapterType = ADAPTER_EMPTY;
104 static CADataType_t g_dataType = CA_REQUEST_DATA;
108 * Mutex to synchronize the task to be executed on the GattServer
111 static oc_mutex g_bleIsServerMutex = NULL;
114 * Mutex to synchronize the callback to be called for the network
117 static oc_mutex g_bleNetworkCbMutex = NULL;
120 * Mutex to synchronize the updates of the local LE address of the
123 static oc_mutex g_bleLocalAddressMutex = NULL;
126 * Reference to thread pool.
128 static ca_thread_pool_t g_bleAdapterThreadPool = NULL;
131 * Mutex to synchronize the task to be pushed to thread pool.
133 static oc_mutex g_bleAdapterThreadPoolMutex = NULL;
136 * Mutex to synchronize the queing of the data from SenderQueue.
138 static oc_mutex g_bleClientSendDataMutex = NULL;
141 * Mutex to synchronize the queing of the data from ReceiverQueue.
143 static oc_mutex g_bleClientReceiveDataMutex = NULL;
146 * Mutex to synchronize the queing of the data from SenderQueue.
148 static oc_mutex g_bleServerSendDataMutex = NULL;
151 * Mutex to synchronize the queing of the data from ReceiverQueue.
153 static oc_mutex g_bleServerReceiveDataMutex = NULL;
156 * Mutex to synchronize the callback to be called for the
157 * adapterReqResponse.
159 static oc_mutex g_bleAdapterReqRespCbMutex = NULL;
162 * Callback to be called when network packet received from either
163 * GattServer or GattClient.
165 static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
168 * Callback to notify error from the BLE adapter.
170 static CAErrorHandleCallback g_errorHandler = NULL;
173 static void CALESecureReceiveDataCB(const CASecureEndpoint_t *endpoint,
174 const void *data, size_t dataLength);
176 static ssize_t CALESecureSendDataCB(CAEndpoint_t *endpoint,
177 const void *data, size_t dataLength);
182 * Pointer to defragment received data from single threaded routine.
184 static CABLESenderInfo_t *g_singleThreadReceiveData = NULL;
187 * This function will be associated with the receive for single thread.
189 * This function will defragment the received data from sender
190 * respectively and will send it up to CA layer. Respective sender's
191 * header will provide the length of the data sent.
193 * @param[in] data Actual data received from the remote
195 * @param[in] dataLen Length of the data received from the
198 static void CALEDataReceiverHandlerSingleThread(const uint8_t *data,
202 * This function will be associated with the send for single threaded
205 * This function will fragment the data to the MTU of the transport
206 * and send the data in fragments to the adapters. The function will
207 * be blocked until all data is sent out from the adapter.
209 * @param[in] data Data to be transmitted from LE.
210 * @param[in] dataLen Length of the Data being transmitted.
212 static CAResult_t CALEServerSendDataSingleThread(const uint8_t *data,
217 * Register network change notification callback.
219 * @param[in] netCallback CAAdapterChangeCallback callback which will
220 * be set for the change in adapter.
221 * @param[in] connCallback CAConnectionChangeCallback callback which will
222 * be set for the change in connection.
224 * @return 0 on success otherwise a positive error value.
225 * @retval ::CA_STATUS_OK Successful.
226 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
227 * @retval ::CA_STATUS_FAILED Operation failed.
230 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
231 CAConnectionChangeCallback connCallback);
234 * Set the thread pool handle which is required for spawning new
237 * @param[in] handle Thread pool handle which is given by above layer
238 * for using thread creation task.
241 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle);
244 * Call the callback to the upper layer when the adapter state gets
247 * @param[in] adapter_state New state of the adapter to be notified to
250 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state);
253 * Call the callback to the upper layer when the device connection state gets
256 * @param[in] address LE address of the device to be notified to the upper layer.
257 * @param[in] isConnected whether connection state is connected or not.
259 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
263 * Used to initialize all required mutex variable for LE Adapter
266 * @return 0 on success otherwise a positive error value.
267 * @retval ::CA_STATUS_OK Successful.
268 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
269 * @retval ::CA_STATUS_FAILED Operation failed.
272 static CAResult_t CAInitLEAdapterMutex();
275 * Terminate all required mutex variables for LE adapter
278 static void CATerminateLEAdapterMutex();
281 * Prepares and notify error through error callback.
283 static void CALEErrorHandler(const char *remoteAddress,
288 #ifndef SINGLE_THREAD
290 * Stop condition of Server recvhandler.
292 static bool g_dataBleServerReceiverHandlerState = false;
295 * Stop condition of Client recvhandler.
297 static bool g_dataBleClientReceiverHandlerState = false;
300 * Sender information of Server.
302 static u_arraylist_t *g_bleServerSenderInfo = NULL;
305 * Sender information of Client.
307 static u_arraylist_t *g_bleClientSenderInfo = NULL;
310 * Queue to process the outgoing packets from GATTServer.
312 static CAQueueingThread_t *g_bleServerSendQueueHandle = NULL;
315 * Queue to process the outgoing packets from GATTClient.
317 static CAQueueingThread_t *g_bleClientSendQueueHandle = NULL;
320 * Queue to process the incoming packets from GATTServer.
322 static CAQueueingThread_t *g_bleServerReceiverQueue = NULL;
325 * Queue to process the incoming packets from GATTClient.
327 static CAQueueingThread_t *g_bleClientReceiverQueue = NULL;
330 * This function will be associated with the sender queue for
333 * This function will fragment the data to the MTU of the transport
334 * and send the data in fragments to the adapters. The function will
335 * be blocked until all data is sent out from the adapter.
337 * @param[in] threadData Data pushed to the queue which contains the
338 * info about RemoteEndpoint and Data.
340 static void CALEServerSendDataThread(void *threadData);
343 * This function will be associated with the sender queue for
346 * This function will fragment the data to the MTU of the transport
347 * and send the data in fragments to the adapters. The function will
348 * be blocked until all data is sent out from the adapter.
350 * @param[in] threadData Data pushed to the queue which contains the
351 * info about RemoteEndpoint and Data.
353 static void CALEClientSendDataThread(void *threadData);
356 * This function will defragment the received data from each sender
357 * respectively and will send it up to CA layer. Respective sender's
358 * header will provide the length of the data sent.
360 * @param[in] threadData Data pushed to the queue which contains the
361 * info about RemoteEndpoint and Data.
362 * @param[in] receiverType Whether receiver is server or client.
364 static void CALEDataReceiverHandler(void *threadData, CABLEAdapter_t receiverType);
367 * This function will be associated with the receiver queue for
370 * This function will call the function CALEDataReceiverHandler()
371 * with server type to defragment the received data.
373 * @param[in] threadData Data pushed to the queue which contains the
374 * info about RemoteEndpoint and Data.
376 static void CALEServerDataReceiverHandler(void *threadData);
379 * This function will be associated with the receiver queue for
382 * This function will call the function CALEDataReceiverHandler()
383 * with client type to defragment the received data.
385 * @param[in] threadData Data pushed to the queue which contains the
386 * info about RemoteEndpoint and Data.
388 static void CALEClientDataReceiverHandler(void *threadData);
391 * This function will stop all queues created for GattServer and
392 * GattClient. All four queues will be be stopped with this function
395 static void CAStopLEQueues();
398 * This function will terminate all queues created for GattServer and
399 * GattClient. All four queues will be be terminated with this
400 * function invocations.
402 static void CATerminateLEQueues();
405 * This function will initalize the Receiver and Sender queues for
406 * GattServer. This function will in turn call the functions
407 * CAInitBleServerReceiverQueue() and CAInitBleServerSenderQueue() to
408 * initialize the queues.
410 * @return ::CA_STATUS_OK or Appropriate error code.
411 * @retval ::CA_STATUS_OK Successful.
412 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
413 * @retval ::CA_STATUS_FAILED Operation failed.
415 static CAResult_t CAInitLEServerQueues();
418 * This function will initalize the Receiver and Sender queues for
419 * GattClient. This function will inturn call the functions
420 * CAInitBleClientReceiverQueue() and CAInitBleClientSenderQueue() to
421 * initialize the queues.
423 * @return ::CA_STATUS_OK or Appropriate error code.
424 * @retval ::CA_STATUS_OK Successful.
425 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
426 * @retval ::CA_STATUS_FAILED Operation failed.
429 static CAResult_t CAInitLEClientQueues();
432 * This function will initalize the Receiver queue for
433 * GattServer. This will initialize the queue to process the function
434 * CABLEServerSendDataThread() when ever the task is added to this
437 * @return ::CA_STATUS_OK or Appropriate error code.
438 * @retval ::CA_STATUS_OK Successful.
439 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
440 * @retval ::CA_STATUS_FAILED Operation failed.
442 static CAResult_t CAInitLEServerSenderQueue();
445 * This function will initalize the Receiver queue for
446 * GattClient. This will initialize the queue to process the function
447 * CABLEClientSendDataThread() when ever the task is added to this
450 * @return ::CA_STATUS_OK or Appropriate error code.
451 * @retval ::CA_STATUS_OK Successful.
452 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
453 * @retval ::CA_STATUS_FAILED Operation failed.
455 static CAResult_t CAInitLEClientSenderQueue();
458 * This function will initialize the Receiver queue for
459 * GattServer. This will initialize the queue to process the function
460 * CALEServerDataReceiverHandler() when ever the task is added to this
463 * @return ::CA_STATUS_OK or Appropriate error code
464 * @retval ::CA_STATUS_OK Successful
465 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments
466 * @retval ::CA_STATUS_FAILED Operation failed
469 static CAResult_t CAInitLEServerReceiverQueue();
472 * This function will initialize the Receiver queue for
473 * GattClient. This will initialize the queue to process the function
474 * CALEClientDataReceiverHandler() when ever the task is added to this
477 * @return ::CA_STATUS_OK or Appropriate error code
478 * @retval ::CA_STATUS_OK Successful
479 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments
480 * @retval ::CA_STATUS_FAILED Operation failed
483 static CAResult_t CAInitLEClientReceiverQueue();
486 * This function will create the Data required to send it in the
489 * @param[in] remoteEndpoint Remote endpoint information of the
491 * @param[in] data Data to be transmitted from LE.
492 * @param[in] dataLength Length of the Data being transmitted.
494 * @return ::CA_STATUS_OK or Appropriate error code.
495 * @retval ::CA_STATUS_OK Successful.
496 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
497 * @retval ::CA_STATUS_FAILED Operation failed.
499 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
502 u_arraylist_t *senderInfo);
505 * Used to free the BLE information stored in the sender/receiver
508 * @param[in] bleData Information for a particular data segment.
510 static void CAFreeLEData(CALEData_t *bleData);
515 static void CALEDataDestroyer(void *data, uint32_t size);
517 #ifndef SINGLE_THREAD
519 * remove request or response data of send queue.
521 * @param[in] queueHandle queue to process the outgoing packets.
522 * @param[in] mutex mutex related to sender for client / server.
523 * @param[in] address target address to remove data in queue.
525 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle,
527 const char* address);
530 * remove all received data of data list from receive queue.
532 * @param[in] dataInfoList received data list to remove for client / server.
533 * @param[in] address target address to remove data in queue.
535 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList,
536 const char* address);
539 * get received data info and positioned index from the received data list
540 * for client / server which is matched same leAddress and port.
542 * @param[in] leAddress target address to get serderInfo.
543 * @param[in] port target port to get serderInfo.
544 * @param[in] senderInfoList received data list for client / server.
545 * @param[out] senderInfo Pointer to contain matched(leAddress and port)
546 * received data info.
547 * @param[out] senderIndex Pointer to contain matched(leAddress and port)
548 * received data info index.
550 static CAResult_t CALEGetSenderInfo(const char *leAddress,
552 u_arraylist_t *senderInfoList,
553 CABLESenderInfo_t **senderInfo,
554 uint32_t *senderIndex);
557 * get ports related to remote address. It is need because multi application
558 * can have more than 2 senderInfo using same BLE address. So before remove
559 * receive queue data, should get port list from sender Info.
561 * @param[in] leAddress target address to get port in serderInfo.
562 * @param[in] senderInfoList received data list to remove for client / server.
563 * @param[out] portList target port list related to leAddress.
565 static CAResult_t CALEGetPortsFromSenderInfo(const char *leAddress,
566 u_arraylist_t *senderInfoList,
567 u_arraylist_t *portList);
570 static CAResult_t CAInitLEServerQueues()
572 oc_mutex_lock(g_bleAdapterThreadPoolMutex);
574 CAResult_t result = CAInitLEServerSenderQueue();
575 if (CA_STATUS_OK != result)
577 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerSenderQueue failed");
578 oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
579 return CA_STATUS_FAILED;
582 g_bleServerSenderInfo = u_arraylist_create();
583 if (!g_bleServerSenderInfo)
585 OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
586 oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
587 return CA_MEMORY_ALLOC_FAILED;
590 result = CAInitLEServerReceiverQueue();
591 if (CA_STATUS_OK != result)
593 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerReceiverQueue failed");
594 u_arraylist_free(&g_bleServerSenderInfo);
595 oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
596 return CA_STATUS_FAILED;
599 g_dataBleServerReceiverHandlerState = true;
601 oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
605 static CAResult_t CAInitLEClientQueues()
607 oc_mutex_lock(g_bleAdapterThreadPoolMutex);
609 CAResult_t result = CAInitLEClientSenderQueue();
610 if (CA_STATUS_OK != result)
612 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientSenderQueue failed");
613 oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
614 return CA_STATUS_FAILED;
617 g_bleClientSenderInfo = u_arraylist_create();
618 if (!g_bleClientSenderInfo)
620 OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
621 oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
622 return CA_MEMORY_ALLOC_FAILED;
625 result = CAInitLEClientReceiverQueue();
626 if (CA_STATUS_OK != result)
628 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientReceiverQueue failed");
629 u_arraylist_free(&g_bleClientSenderInfo);
630 oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
631 return CA_STATUS_FAILED;
634 g_dataBleClientReceiverHandlerState = true;
636 oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
640 static CAResult_t CAInitLEServerReceiverQueue()
642 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
643 // Check if the message queue is already initialized
644 if (g_bleServerReceiverQueue)
646 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
650 // Create recv message queue
651 g_bleServerReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
652 if (!g_bleServerReceiverQueue)
654 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
655 return CA_MEMORY_ALLOC_FAILED;
658 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerReceiverQueue,
659 g_bleAdapterThreadPool,
660 CALEServerDataReceiverHandler,
663 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize server receiver queue thread");
664 OICFree(g_bleServerReceiverQueue);
665 g_bleServerReceiverQueue = NULL;
666 return CA_STATUS_FAILED;
669 if (CA_STATUS_OK != CAQueueingThreadStart(g_bleServerReceiverQueue))
671 OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
672 OICFree(g_bleServerReceiverQueue);
673 g_bleServerReceiverQueue = NULL;
674 return CA_STATUS_FAILED;
680 static CAResult_t CAInitLEClientReceiverQueue()
682 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
683 // Check if the message queue is already initialized
684 if (g_bleClientReceiverQueue)
686 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
690 // Create recv message queue
691 g_bleClientReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
692 if (!g_bleClientReceiverQueue)
694 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
695 return CA_MEMORY_ALLOC_FAILED;
698 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientReceiverQueue,
699 g_bleAdapterThreadPool,
700 CALEClientDataReceiverHandler,
703 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize client receiver queue thread");
704 OICFree(g_bleClientReceiverQueue);
705 g_bleClientReceiverQueue = NULL;
706 return CA_STATUS_FAILED;
709 if (CA_STATUS_OK != CAQueueingThreadStart(g_bleClientReceiverQueue))
711 OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
712 OICFree(g_bleClientReceiverQueue);
713 g_bleClientReceiverQueue = NULL;
714 return CA_STATUS_FAILED;
720 static CAResult_t CAInitLEServerSenderQueue()
722 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
723 // Check if the message queue is already initialized
724 if (g_bleServerSendQueueHandle)
726 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Queue is already initialized!");
730 // Create send message queue
731 g_bleServerSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
732 if (!g_bleServerSendQueueHandle)
734 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
735 return CA_MEMORY_ALLOC_FAILED;
738 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerSendQueueHandle,
739 g_bleAdapterThreadPool,
740 CALEServerSendDataThread,
743 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
744 OICFree(g_bleServerSendQueueHandle);
745 g_bleServerSendQueueHandle = NULL;
746 return CA_STATUS_FAILED;
752 static void CALEClearSenderInfoImpl(u_arraylist_t ** list)
754 const size_t length = u_arraylist_length(*list);
755 for (size_t i = 0; i < length; ++i)
757 CABLESenderInfo_t * const info =
758 (CABLESenderInfo_t *) u_arraylist_get(*list, i);
761 OICFree(info->defragData);
762 CAFreeEndpoint(info->remoteEndpoint);
766 u_arraylist_free(list);
769 static void CALEClearSenderInfo()
771 CALEClearSenderInfoImpl(&g_bleServerSenderInfo);
772 CALEClearSenderInfoImpl(&g_bleClientSenderInfo);
775 static CAResult_t CAInitLEClientSenderQueue()
777 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
779 if (g_bleClientSendQueueHandle)
781 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
785 // Create send message queue
786 g_bleClientSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
787 if (!g_bleClientSendQueueHandle)
789 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
790 return CA_MEMORY_ALLOC_FAILED;
793 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientSendQueueHandle,
794 g_bleAdapterThreadPool,
795 CALEClientSendDataThread, CALEDataDestroyer))
797 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
798 OICFree(g_bleClientSendQueueHandle);
799 g_bleClientSendQueueHandle = NULL;
800 return CA_STATUS_FAILED;
805 static void CAStopLEQueues()
807 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
809 oc_mutex_lock(g_bleServerReceiveDataMutex);
810 if (NULL != g_bleServerReceiverQueue)
812 CAQueueingThreadStop(g_bleServerReceiverQueue);
814 oc_mutex_unlock(g_bleServerReceiveDataMutex);
816 oc_mutex_lock(g_bleClientReceiveDataMutex);
817 if (NULL != g_bleClientReceiverQueue)
819 CAQueueingThreadStop(g_bleClientReceiverQueue);
821 oc_mutex_unlock(g_bleClientReceiveDataMutex);
823 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
826 static void CATerminateLEQueues()
828 CAQueueingThreadDestroy(g_bleClientSendQueueHandle);
829 OICFree(g_bleClientSendQueueHandle);
830 g_bleClientSendQueueHandle = NULL;
832 CAQueueingThreadDestroy(g_bleServerSendQueueHandle);
833 OICFree(g_bleServerSendQueueHandle);
834 g_bleServerSendQueueHandle = NULL;
836 CAQueueingThreadDestroy(g_bleServerReceiverQueue);
837 OICFree(g_bleServerReceiverQueue);
838 g_bleServerReceiverQueue = NULL;
840 CAQueueingThreadDestroy(g_bleClientReceiverQueue);
841 OICFree(g_bleClientReceiverQueue);
842 g_bleClientReceiverQueue = NULL;
844 CALEClearSenderInfo();
847 static CAResult_t CALEGetSenderInfo(const char *leAddress,
849 u_arraylist_t *senderInfoList,
850 CABLESenderInfo_t **senderInfo,
851 uint32_t *senderIndex)
853 VERIFY_NON_NULL_RET(leAddress,
855 "NULL BLE address argument",
856 CA_STATUS_INVALID_PARAM);
857 VERIFY_NON_NULL_RET(senderIndex,
859 "NULL index argument",
860 CA_STATUS_INVALID_PARAM);
862 const uint32_t listLength = u_arraylist_length(senderInfoList);
863 const uint32_t addrLength = strlen(leAddress);
864 for (uint32_t index = 0; index < listLength; index++)
866 CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
867 if (!info || !(info->remoteEndpoint))
872 if (!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
874 if (info->remoteEndpoint->port == port)
876 *senderIndex = index;
886 return CA_STATUS_FAILED;
889 static void CALEDataReceiverHandler(void *threadData, CABLEAdapter_t receiverType)
891 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
893 oc_mutex bleReceiveDataMutex = NULL;
894 bool dataBleReceiverHandlerState = false;
896 switch (receiverType)
899 bleReceiveDataMutex = g_bleClientReceiveDataMutex;
900 dataBleReceiverHandlerState = g_dataBleClientReceiverHandlerState;
903 bleReceiveDataMutex = g_bleServerReceiveDataMutex;
904 dataBleReceiverHandlerState = g_dataBleServerReceiverHandlerState;
907 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Unsupported receiver type : %d", receiverType);
911 oc_mutex_lock(bleReceiveDataMutex);
913 if (dataBleReceiverHandlerState)
915 CALEData_t *bleData = (CALEData_t *) threadData;
918 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bleData!");
919 oc_mutex_unlock(bleReceiveDataMutex);
923 if (!(bleData->senderInfo))
925 OIC_LOG(ERROR, CALEADAPTER_TAG, "sender info is not available");
926 oc_mutex_unlock(bleReceiveDataMutex);
930 if (!(bleData->remoteEndpoint))
932 OIC_LOG(ERROR, CALEADAPTER_TAG, "RemoteEndPoint NULL!!");
933 oc_mutex_unlock(bleReceiveDataMutex);
937 CABLESenderInfo_t *senderInfo = NULL;
938 uint32_t senderIndex = 0;
941 CABLEPacketStart_t startFlag = CA_BLE_PACKET_NOT_START;
942 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
943 uint16_t sourcePort = 0;
944 uint16_t destPort = 0;
946 CAParseHeader(bleData->data, &startFlag, &sourcePort, &secureFlag, &destPort);
947 OIC_LOG_V(INFO, CALEADAPTER_TAG,
948 "header info: startFlag[%X] sourcePort[%d] secureFlag[%X] destPort[%d]",
949 startFlag, sourcePort, secureFlag, destPort);
951 if (destPort != g_localBLESourcePort && destPort != CA_BLE_MULTICAST_PORT)
953 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
954 "this packet is not valid for this app(port mismatch[mine:%d, packet:%d])",
955 g_localBLESourcePort, destPort);
956 oc_mutex_unlock(bleReceiveDataMutex);
960 bleData->remoteEndpoint->port = sourcePort;
962 if (CA_STATUS_OK != CALEGetSenderInfo(bleData->remoteEndpoint->addr,
963 bleData->remoteEndpoint->port,
965 &senderInfo, &senderIndex))
967 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This is a new client [%s:%X]",
968 bleData->remoteEndpoint->addr, bleData->remoteEndpoint->port);
974 OIC_LOG(ERROR, CALEADAPTER_TAG,
975 "This packet is start packet but exist senderInfo. Remove senderInfo");
976 u_arraylist_remove(bleData->senderInfo, senderIndex);
977 OICFree(senderInfo->defragData);
986 uint32_t totalLength = 0;
989 CAParseHeaderPayloadLength(bleData->data, CA_BLE_LENGTH_HEADER_SIZE, &totalLength);
993 OIC_LOG(ERROR, CALEADAPTER_TAG, "This packet is wrong packet! ignore.");
994 oc_mutex_unlock(bleReceiveDataMutex);
998 CABLESenderInfo_t *newSender = OICMalloc(sizeof(CABLESenderInfo_t));
1001 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
1002 oc_mutex_unlock(bleReceiveDataMutex);
1005 newSender->recvDataLen = 0;
1006 newSender->totalDataLen = 0;
1007 newSender->defragData = NULL;
1008 newSender->remoteEndpoint = NULL;
1010 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
1012 newSender->totalDataLen = totalLength;
1014 if (!(newSender->totalDataLen))
1016 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
1018 oc_mutex_unlock(bleReceiveDataMutex);
1022 size_t dataOnlyLen =
1023 bleData->dataLen - (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE);
1024 OIC_LOG_V(INFO, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
1025 newSender->totalDataLen);
1026 OIC_LOG_V(INFO, CALEADAPTER_TAG, "data received in the first packet [%zu] bytes",
1029 newSender->defragData = OICCalloc(newSender->totalDataLen + 1,
1030 sizeof(*newSender->defragData));
1032 if (NULL == newSender->defragData)
1034 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
1036 oc_mutex_unlock(bleReceiveDataMutex);
1039 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
1040 #ifdef __WITH_DTLS__
1041 if (CA_BLE_PACKET_SECURE == secureFlag)
1047 const char *remoteAddress = bleData->remoteEndpoint->addr;
1048 newSender->remoteEndpoint = CACreateEndpointObject(flags,
1049 CA_ADAPTER_GATT_BTLE,
1051 bleData->remoteEndpoint->port);
1053 if (NULL == newSender->remoteEndpoint)
1055 OIC_LOG(ERROR, CALEADAPTER_TAG, "remoteEndpoint is NULL!");
1056 OICFree(newSender->defragData);
1058 oc_mutex_unlock(bleReceiveDataMutex);
1062 if (newSender->recvDataLen + dataOnlyLen > newSender->totalDataLen)
1064 OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
1065 OICFree(newSender->defragData);
1066 CAFreeEndpoint(newSender->remoteEndpoint);
1068 oc_mutex_unlock(bleReceiveDataMutex);
1071 memcpy(newSender->defragData,
1072 bleData->data + (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE),
1074 newSender->recvDataLen += dataOnlyLen;
1076 u_arraylist_add(bleData->senderInfo,(void *)newSender);
1078 //Getting newSender index position in bleSenderInfo array list
1080 CALEGetSenderInfo(newSender->remoteEndpoint->addr,
1081 newSender->remoteEndpoint->port,
1082 bleData->senderInfo,
1083 NULL, &senderIndex))
1085 OIC_LOG(ERROR, CALEADAPTER_TAG, "Existing sender index not found!!");
1086 OICFree(newSender->defragData);
1087 CAFreeEndpoint(newSender->remoteEndpoint);
1089 oc_mutex_unlock(bleReceiveDataMutex);
1092 senderInfo = newSender;
1096 size_t dataOnlyLen = bleData->dataLen - CA_BLE_HEADER_SIZE;
1097 if (senderInfo->recvDataLen + dataOnlyLen > senderInfo->totalDataLen)
1099 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1100 "Data Length exceeding error!! Receiving [%zu] total length [%u]",
1101 senderInfo->recvDataLen + dataOnlyLen, senderInfo->totalDataLen);
1102 u_arraylist_remove(bleData->senderInfo, senderIndex);
1103 OICFree(senderInfo->defragData);
1104 OICFree(senderInfo);
1105 oc_mutex_unlock(bleReceiveDataMutex);
1108 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%zu]",
1110 memcpy(senderInfo->defragData + senderInfo->recvDataLen,
1111 bleData->data + CA_BLE_HEADER_SIZE,
1113 senderInfo->recvDataLen += dataOnlyLen;
1114 OIC_LOG_V(INFO, CALEADAPTER_TAG, "totalDatalength [%d] received Datalen [%d]",
1115 senderInfo->totalDataLen, senderInfo->recvDataLen);
1118 if (senderInfo->totalDataLen == senderInfo->recvDataLen)
1120 oc_mutex_lock(g_bleAdapterReqRespCbMutex);
1121 if (NULL == g_networkPacketReceivedCallback)
1123 OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
1125 u_arraylist_remove(bleData->senderInfo, senderIndex);
1126 OICFree(senderInfo->defragData);
1127 OICFree(senderInfo);
1128 oc_mutex_unlock(g_bleAdapterReqRespCbMutex);
1129 oc_mutex_unlock(bleReceiveDataMutex);
1133 OIC_LOG(DEBUG, CALEADAPTER_TAG, "[CALEDataReceiverHandler] Received data up !");
1135 const CASecureEndpoint_t tmp =
1137 .endpoint = *senderInfo->remoteEndpoint
1140 OIC_LOG_V(INFO, CALEADAPTER_TAG, "endpoint flags : %d", tmp.endpoint.flags);
1141 #ifdef __WITH_DTLS__
1142 if (CA_SECURE & tmp.endpoint.flags)
1144 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Secure data received");
1145 switch (receiverType)
1147 case ADAPTER_CLIENT:
1148 g_dataType = CA_REQUEST_DATA;
1150 case ADAPTER_SERVER:
1151 g_dataType = CA_RESPONSE_DATA;
1154 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Unsupported rcvr type:%d",receiverType);
1155 oc_mutex_unlock(g_bleAdapterReqRespCbMutex);
1156 u_arraylist_remove(bleData->senderInfo, senderIndex);
1157 senderInfo->remoteEndpoint = NULL;
1158 senderInfo->defragData = NULL;
1159 OICFree(senderInfo);
1160 oc_mutex_unlock(bleReceiveDataMutex);
1164 if (CA_STATUS_FAILED == CAdecryptSsl(&tmp,
1165 senderInfo->defragData,
1166 senderInfo->recvDataLen))
1168 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAdecryptSsl failed");
1172 OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAdecryptSsl successed");
1174 OICFree(senderInfo->defragData);
1179 OIC_LOG(INFO, CALEADAPTER_TAG, "Non-Secure data received");
1180 g_networkPacketReceivedCallback(&tmp,
1181 senderInfo->defragData,
1182 senderInfo->recvDataLen);
1183 #ifdef __WITH_DTLS__
1187 oc_mutex_unlock(g_bleAdapterReqRespCbMutex);
1188 u_arraylist_remove(bleData->senderInfo, senderIndex);
1189 senderInfo->remoteEndpoint = NULL;
1190 senderInfo->defragData = NULL;
1191 OICFree(senderInfo);
1194 oc_mutex_unlock(bleReceiveDataMutex);
1198 static void CALEServerDataReceiverHandler(void *threadData)
1200 CALEDataReceiverHandler(threadData, ADAPTER_SERVER);
1203 static void CALEClientDataReceiverHandler(void *threadData)
1205 CALEDataReceiverHandler(threadData, ADAPTER_CLIENT);
1208 static void CALEServerSendDataThread(void *threadData)
1210 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1212 CALEData_t * const bleData = (CALEData_t *) threadData;
1215 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid bledata!");
1219 if (!bleData->remoteEndpoint)
1221 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid endpoint of bledata!");
1225 #if defined(__TIZEN__) || defined(__ANDROID__)
1227 g_mtuSize = CALEServerGetMtuSize(bleData->remoteEndpoint->addr);
1229 OIC_LOG_V(INFO, CALEADAPTER_TAG, "MTU size [%d]", g_mtuSize);
1231 uint32_t midPacketCount = 0;
1232 size_t remainingLen = 0;
1233 size_t totalLength = 0;
1234 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1236 CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
1242 if (CA_STATUS_OK != result)
1244 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1245 "CAGenerateVariableForFragmentation failed, result [%d]", result);
1246 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1250 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1251 "Packet info: data size[%d] midPacketCount[%u] remainingLen[%zu] totalLength[%zu]",
1252 bleData->dataLen, midPacketCount, remainingLen, totalLength);
1256 "Server total Data length with header is [%zu]",
1259 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1260 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1262 if (NULL != bleData->remoteEndpoint) //Unicast Data
1264 secureFlag = (bleData->remoteEndpoint->flags & CA_SECURE) ?
1265 CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
1267 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This Packet is secure? %d", secureFlag);
1268 result = CAGenerateHeader(dataHeader,
1269 CA_BLE_PACKET_START,
1270 g_localBLESourcePort,
1272 bleData->remoteEndpoint->port);
1274 else //Multicast Data
1276 result = CAGenerateHeader(dataHeader,
1277 CA_BLE_PACKET_START,
1278 g_localBLESourcePort,
1280 CA_BLE_MULTICAST_PORT);
1282 OIC_LOG_V(INFO, CALEADAPTER_TAG, "header info: secureFlag[%X]", secureFlag);
1284 if (CA_STATUS_OK != result)
1286 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1287 "CAGenerateHeader failed, result [%d]", result);
1288 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1292 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1293 result = CAGenerateHeaderPayloadLength(lengthHeader,
1294 CA_BLE_LENGTH_HEADER_SIZE,
1297 if (CA_STATUS_OK != result)
1299 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1300 "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1301 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1305 uint32_t length = 0;
1306 uint32_t dataLen = 0;
1307 if (g_mtuSize > totalLength)
1309 length = totalLength;
1310 dataLen = bleData->dataLen;
1315 dataLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1318 result = CAMakeFirstDataSegment(dataSegment,
1319 bleData->data, dataLen,
1320 dataHeader, lengthHeader);
1322 if (CA_STATUS_OK != result)
1324 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1325 "Making data segment failed, result [%d]", result);
1326 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1330 const uint32_t iter = midPacketCount;
1333 // Send the first segment with the header.
1334 if (NULL != bleData->remoteEndpoint) // Sending Unicast Data
1336 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Unicast Data");
1338 result = CAUpdateCharacteristicsToGattClient(
1339 bleData->remoteEndpoint->addr, dataSegment, length);
1341 if (CA_STATUS_OK != result)
1345 "Update characteristics failed, result [%d]",
1348 g_errorHandler(bleData->remoteEndpoint,
1357 "Server Sent Unicast First Data - data length [%zu]",
1360 result = CAGenerateHeader(dataHeader,
1361 CA_BLE_PACKET_NOT_START,
1362 g_localBLESourcePort,
1364 bleData->remoteEndpoint->port);
1366 if (CA_STATUS_OK != result)
1368 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1369 "CAGenerateHeader failed, result [%d]", result);
1370 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1374 for (index = 0; index < iter; index++)
1376 // Send the remaining header.
1377 result = CAMakeRemainDataSegment(dataSegment,
1378 g_mtuSize - CA_BLE_HEADER_SIZE,
1385 if (CA_STATUS_OK != result)
1387 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1388 "Making data segment failed, result [%d]", result);
1389 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1394 CAUpdateCharacteristicsToGattClient(
1395 bleData->remoteEndpoint->addr,
1399 if (CA_STATUS_OK != result)
1401 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1402 "Update characteristics failed, result [%d]", result);
1403 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1406 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]",
1410 if (remainingLen && (totalLength > g_mtuSize))
1412 // send the last segment of the data (Ex: 22 bytes of 622
1413 // bytes of data when MTU is 200)
1414 result = CAMakeRemainDataSegment(dataSegment,
1422 if (CA_STATUS_OK != result)
1424 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1425 "Making data segment failed, result [%d]", result);
1426 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1430 result = CAUpdateCharacteristicsToGattClient(
1431 bleData->remoteEndpoint->addr,
1433 remainingLen + CA_BLE_HEADER_SIZE);
1435 if (CA_STATUS_OK != result)
1439 "Update characteristics failed, result [%d]",
1441 g_errorHandler(bleData->remoteEndpoint,
1449 "Server Sent Unicast Last Data - data length [%zu]",
1450 remainingLen + CA_BLE_HEADER_SIZE);
1455 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
1456 OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
1459 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1462 static void CALEClientSendDataThread(void *threadData)
1464 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1466 CALEData_t *bleData = (CALEData_t *) threadData;
1469 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid bledata!");
1473 if (!bleData->remoteEndpoint)
1475 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid endpoint of bledata!");
1479 #if defined(__TIZEN__) || defined(__ANDROID__)
1481 if (false == CALEClientIsConnected(bleData->remoteEndpoint->addr))
1483 // triggering to gatt connect and MTU negotiation
1484 CAResult_t res = CALEClientSendNegotiationMessage(
1485 bleData->remoteEndpoint->addr);
1487 if (CA_STATUS_OK != res)
1491 "CALEClientSendNegotiationMessage has failed, result [%d]",
1494 g_errorHandler(bleData->remoteEndpoint,
1501 g_mtuSize = CALEClientGetMtuSize(bleData->remoteEndpoint->addr);
1503 OIC_LOG_V(INFO, CALEADAPTER_TAG, "MTU size [%d]", g_mtuSize);
1505 uint32_t midPacketCount = 0;
1506 size_t remainingLen = 0;
1507 size_t totalLength = 0;
1508 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1510 CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
1516 if (CA_STATUS_OK != result)
1518 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1519 "CAGenerateVariableForFragmentation failed, result [%d]", result);
1520 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1524 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1525 "Packet info: data size[%d] midPacketCount[%u] remainingLen[%zu] totalLength[%zu]",
1526 bleData->dataLen, midPacketCount, remainingLen, totalLength);
1528 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1529 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1531 if (NULL != bleData->remoteEndpoint) //Unicast Data
1533 secureFlag = (bleData->remoteEndpoint->flags & CA_SECURE) ?
1534 CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
1536 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This Packet is secure? %d", secureFlag);
1537 result = CAGenerateHeader(dataHeader,
1538 CA_BLE_PACKET_START,
1539 g_localBLESourcePort,
1541 bleData->remoteEndpoint->port);
1543 else //Multicast Data
1545 result = CAGenerateHeader(dataHeader,
1546 CA_BLE_PACKET_START,
1547 g_localBLESourcePort,
1549 CA_BLE_MULTICAST_PORT);
1552 OIC_LOG_V(INFO, CALEADAPTER_TAG, "header info: secureFlag[%X]", secureFlag);
1554 if (CA_STATUS_OK != result)
1556 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1557 "CAGenerateHeader failed, result [%d]", result);
1558 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1562 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1563 result = CAGenerateHeaderPayloadLength(lengthHeader,
1564 CA_BLE_LENGTH_HEADER_SIZE,
1567 if (CA_STATUS_OK != result)
1569 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1570 "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1571 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1575 uint32_t length = 0;
1576 uint32_t dataLen = 0;
1577 if (g_mtuSize > totalLength)
1579 length = totalLength;
1580 dataLen = bleData->dataLen;
1585 dataLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1588 result = CAMakeFirstDataSegment(dataSegment,
1589 bleData->data, dataLen,
1590 dataHeader, lengthHeader);
1592 if (CA_STATUS_OK != result)
1594 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1595 "Making data segment failed, result [%d]", result);
1596 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1600 const uint32_t iter = midPacketCount;
1602 if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
1604 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
1605 // Send the first segment with the header.
1607 CAUpdateCharacteristicsToGattServer(
1608 bleData->remoteEndpoint->addr,
1614 if (CA_STATUS_OK != result)
1618 "Update characteristics failed, result [%d]",
1620 g_errorHandler(bleData->remoteEndpoint,
1628 "Client Sent Unicast First Data - data length [%zu]",
1631 result = CAGenerateHeader(dataHeader,
1632 CA_BLE_PACKET_NOT_START,
1633 g_localBLESourcePort,
1635 bleData->remoteEndpoint->port);
1637 if (CA_STATUS_OK != result)
1639 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1640 "CAGenerateHeader failed, result [%d]", result);
1641 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1645 for (index = 0; index < iter; index++)
1647 result = CAMakeRemainDataSegment(dataSegment,
1648 g_mtuSize - CA_BLE_HEADER_SIZE,
1655 if (CA_STATUS_OK != result)
1657 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1658 "Making data segment failed, result [%d]", result);
1659 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1663 // Send the remaining header.
1664 result = CAUpdateCharacteristicsToGattServer(
1665 bleData->remoteEndpoint->addr,
1670 if (CA_STATUS_OK != result)
1674 "Update characteristics failed, result [%d]",
1676 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1681 "Client Sent Unicast %d Data - data(mtu) length [%zu]",
1686 if (remainingLen && (totalLength > g_mtuSize))
1688 // send the last segment of the data (Ex: 22 bytes of 622
1689 // bytes of data when MTU is 200)
1690 result = CAMakeRemainDataSegment(dataSegment,
1698 if (CA_STATUS_OK != result)
1700 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1701 "Making data segment failed, result [%d]", result);
1702 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1706 result = CAUpdateCharacteristicsToGattServer(
1707 bleData->remoteEndpoint->addr,
1709 remainingLen + CA_BLE_HEADER_SIZE,
1712 if (CA_STATUS_OK != result)
1714 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1716 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1721 "Client Sent Unicast Last Data - data length [%zu]",
1722 remainingLen + CA_BLE_HEADER_SIZE);
1727 //Sending Mulitcast Data
1728 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Client Sending Multicast Data");
1729 OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
1732 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1735 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
1736 const uint8_t *data,
1737 uint32_t dataLength,
1738 u_arraylist_t *senderInfo)
1740 CALEData_t * const bleData = OICMalloc(sizeof(CALEData_t));
1744 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1748 bleData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
1749 bleData->data = OICCalloc(dataLength + 1, 1);
1751 if (NULL == bleData->data)
1753 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1754 CAFreeLEData(bleData);
1758 memcpy(bleData->data, data, dataLength);
1759 bleData->dataLen = dataLength;
1762 bleData->senderInfo = senderInfo;
1768 static void CAFreeLEData(CALEData_t *bleData)
1770 VERIFY_NON_NULL_VOID(bleData, CALEADAPTER_TAG, "Param bleData is NULL");
1772 CAFreeEndpoint(bleData->remoteEndpoint);
1773 OICFree(bleData->data);
1777 static void CALEDataDestroyer(void *data, uint32_t size)
1779 if ((size_t)size < sizeof(CALEData_t *))
1781 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1782 "Destroy data too small %p %d", data, size);
1784 CALEData_t *ledata = (CALEData_t *) data;
1786 CAFreeLEData(ledata);
1790 #ifdef SINGLE_THREAD
1791 static void CALEDataReceiverHandlerSingleThread(const uint8_t *data,
1794 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1796 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1799 CABLEPacketStart_t startFlag = CA_BLE_PACKET_NOT_START;
1800 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1801 uint16_t sourcePort = 0;
1802 uint16_t destPort = 0;
1804 CAParseHeader(data, &startFlag, &sourcePort, &secureFlag, &destPort);
1805 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1806 "header info: startFlag[%X] sourcePort[%d] secureFlag[%X] destPort[%d]",
1807 startFlag, sourcePort, secureFlag, destPort);
1809 if (destPort != g_localBLESourcePort && destPort != CA_BLE_MULTICAST_PORT)
1811 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1812 "this packet is not valid for this app(port mismatch[mine:%d, packet:%d])",
1813 g_localBLESourcePort, destPort);
1819 if (g_singleThreadReceiveData)
1821 OIC_LOG(ERROR, CALEADAPTER_TAG,
1822 "This packet is start packet but exist senderInfo. Remove senderInfo");
1823 OICFree(g_singleThreadReceiveData->defragData);
1824 OICFree(g_singleThreadReceiveData);
1825 g_singleThreadReceiveData = NULL;
1828 uint32_t totalLength = 0;
1829 CAParseHeaderPayloadLength(data, CA_BLE_LENGTH_HEADER_SIZE, &totalLength);
1831 g_singleThreadReceiveData = OICMalloc(sizeof(CABLESenderInfo_t));
1833 if (!g_singleThreadReceiveData)
1835 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
1838 g_singleThreadReceiveData->recvDataLen = 0;
1839 g_singleThreadReceiveData->totalDataLen = 0;
1840 g_singleThreadReceiveData->defragData = NULL;
1841 g_singleThreadReceiveData->remoteEndpoint = NULL;
1843 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
1845 g_singleThreadReceiveData->totalDataLen = totalLength;
1847 if (!(g_singleThreadReceiveData->totalDataLen))
1849 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
1850 OICFree(g_singleThreadReceiveData);
1854 size_t dataOnlyLen = dataLen - (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE);
1855 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
1856 g_singleThreadReceiveData->totalDataLen);
1857 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%u] bytes",
1860 g_singleThreadReceiveData->defragData =
1861 OICCalloc(g_singleThreadReceiveData->totalDataLen + 1,
1862 sizeof(*g_singleThreadReceiveData->defragData));
1864 if (NULL == g_singleThreadReceiveData->defragData)
1866 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
1867 OICFree(g_singleThreadReceiveData);
1871 if (g_singleThreadReceiveData->recvDataLen + dataOnlyLen
1872 > g_singleThreadReceiveData->totalDataLen)
1874 OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
1875 OICFree(g_singleThreadReceiveData->defragData);
1876 OICFree(g_singleThreadReceiveData);
1879 memcpy(g_singleThreadReceiveData->defragData,
1880 data + (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE),
1882 g_singleThreadReceiveData->recvDataLen += dataOnlyLen;
1886 size_t dataOnlyLen = dataLen - CA_BLE_HEADER_SIZE;
1887 if (g_singleThreadReceiveData->recvDataLen + dataOnlyLen
1888 > g_singleThreadReceiveData->totalDataLen)
1890 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1891 "Data Length exceeding error!! Receiving [%d] total length [%d]",
1892 g_singleThreadReceiveData->recvDataLen + dataOnlyLen,
1893 g_singleThreadReceiveData->totalDataLen);
1894 OICFree(g_singleThreadReceiveData->defragData);
1895 OICFree(g_singleThreadReceiveData);
1898 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]",
1900 memcpy(g_singleThreadReceiveData->defragData + g_singleThreadReceiveData->recvDataLen,
1901 data + CA_BLE_HEADER_SIZE,
1903 g_singleThreadReceiveData->recvDataLen += dataOnlyLen;
1904 OIC_LOG_V(INFO, CALEADAPTER_TAG, "totalDatalength [%d] received Datalen [%d]",
1905 g_singleThreadReceiveData->totalDataLen, g_singleThreadReceiveData->recvDataLen);
1907 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1910 static CAResult_t CALEServerSendDataSingleThread(const uint8_t *data,
1913 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__););
1915 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1917 uint32_t midPacketCount = 0;
1918 size_t remainingLen = 0;
1919 size_t totalLength = 0;
1920 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1922 CAResult_t result = CAGenerateVariableForFragmentation(dataLen,
1928 if (CA_STATUS_OK != result)
1930 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1931 "CAGenerateVariableForFragmentation failed, result [%d]", result);
1935 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1936 "Packet info: data size[%d] midPacketCount[%d] remainingLen[%d] totalLength[%d]",
1937 dataLen, midPacketCount, remainingLen, totalLength);
1941 "Server total Data length with header is [%u]",
1944 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1945 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1947 result = CAGenerateHeader(dataHeader,
1948 CA_BLE_PACKET_START,
1949 g_localBLESourcePort,
1950 CA_BLE_PACKET_NON_SECURE,
1951 CA_BLE_MULTICAST_PORT);
1953 if (CA_STATUS_OK != result)
1955 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1956 "CAGenerateHeader failed, result [%d]", result);
1960 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1961 result = CAGenerateHeaderPayloadLength(lengthHeader,
1962 CA_BLE_LENGTH_HEADER_SIZE,
1965 if (CA_STATUS_OK != result)
1967 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1968 "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1972 uint32_t length = 0;
1973 uint32_t dataOnlyLen = 0;
1974 if (g_mtuSize > totalLength)
1976 length = totalLength;
1977 dataOnlyLen = dataLen;
1982 dataOnlyLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1985 result = CAMakeFirstDataSegment(dataSegment,
1987 dataHeader, lengthHeader);
1989 if (CA_STATUS_OK != result)
1991 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1992 "Making data segment failed, result [%d]", result);
1996 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
1997 result = CAUpdateCharacteristicsToAllGattClients(dataSegment, length);
1998 if (CA_STATUS_OK != result)
2000 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
2007 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
2009 result = CAGenerateHeader(dataHeader,
2010 CA_BLE_PACKET_NOT_START,
2011 g_localBLESourcePort,
2012 CA_BLE_PACKET_NON_SECURE,
2013 CA_BLE_MULTICAST_PORT);
2015 if (CA_STATUS_OK != result)
2017 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2018 "CAGenerateHeader failed, result [%d]", result);
2022 const uint32_t dataLimit = midPacketCount;
2023 for (uint32_t iter = 0; iter < dataLimit; iter++)
2025 result = CAMakeRemainDataSegment(dataSegment,
2026 g_mtuSize - CA_BLE_HEADER_SIZE,
2033 if (CA_STATUS_OK != result)
2035 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2036 "Making data segment failed, result [%d]", result);
2040 result = CAUpdateCharacteristicsToAllGattClients(
2044 if (CA_STATUS_OK != result)
2046 OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2053 if (remainingLen && (totalLength > g_mtuSize))
2055 // send the last segment of the data
2056 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
2058 result = CAMakeRemainDataSegment(dataSegment,
2066 if (CA_STATUS_OK != result)
2068 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2069 "Making data segment failed, result [%d]", result);
2073 result = CAUpdateCharacteristicsToAllGattClients(
2075 remainingLen + CA_BLE_HEADER_SIZE);
2077 if (CA_STATUS_OK != result)
2079 OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2089 static CAResult_t CAInitLEAdapterMutex()
2091 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2093 if (NULL == g_bleIsServerMutex)
2095 g_bleIsServerMutex = oc_mutex_new();
2096 if (NULL == g_bleIsServerMutex)
2098 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2099 return CA_STATUS_FAILED;
2103 if (NULL == g_bleNetworkCbMutex)
2105 g_bleNetworkCbMutex = oc_mutex_new();
2106 if (NULL == g_bleNetworkCbMutex)
2108 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2109 CATerminateLEAdapterMutex();
2110 return CA_STATUS_FAILED;
2114 if (NULL == g_bleLocalAddressMutex)
2116 g_bleLocalAddressMutex = oc_mutex_new();
2117 if (NULL == g_bleLocalAddressMutex)
2119 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2120 CATerminateLEAdapterMutex();
2121 return CA_STATUS_FAILED;
2125 if (NULL == g_bleAdapterThreadPoolMutex)
2127 g_bleAdapterThreadPoolMutex = oc_mutex_new();
2128 if (NULL == g_bleAdapterThreadPoolMutex)
2130 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2131 CATerminateLEAdapterMutex();
2132 return CA_STATUS_FAILED;
2136 if (NULL == g_bleClientSendDataMutex)
2138 g_bleClientSendDataMutex = oc_mutex_new();
2139 if (NULL == g_bleClientSendDataMutex)
2141 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2142 CATerminateLEAdapterMutex();
2143 return CA_STATUS_FAILED;
2147 if (NULL == g_bleServerSendDataMutex)
2149 g_bleServerSendDataMutex = oc_mutex_new();
2150 if (NULL == g_bleServerSendDataMutex)
2152 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2153 CATerminateLEAdapterMutex();
2154 return CA_STATUS_FAILED;
2158 if (NULL == g_bleAdapterReqRespCbMutex)
2160 g_bleAdapterReqRespCbMutex = oc_mutex_new();
2161 if (NULL == g_bleAdapterReqRespCbMutex)
2163 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2164 CATerminateLEAdapterMutex();
2165 return CA_STATUS_FAILED;
2169 if (NULL == g_bleServerReceiveDataMutex)
2171 g_bleServerReceiveDataMutex = oc_mutex_new();
2172 if (NULL == g_bleServerReceiveDataMutex)
2174 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2175 return CA_STATUS_FAILED;
2179 if (NULL == g_bleClientReceiveDataMutex)
2181 g_bleClientReceiveDataMutex = oc_mutex_new();
2182 if (NULL == g_bleClientReceiveDataMutex)
2184 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2185 return CA_STATUS_FAILED;
2189 return CA_STATUS_OK;
2192 static void CATerminateLEAdapterMutex()
2194 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2196 oc_mutex_free(g_bleIsServerMutex);
2197 g_bleIsServerMutex = NULL;
2199 oc_mutex_free(g_bleNetworkCbMutex);
2200 g_bleNetworkCbMutex = NULL;
2202 oc_mutex_free(g_bleLocalAddressMutex);
2203 g_bleLocalAddressMutex = NULL;
2205 oc_mutex_free(g_bleAdapterThreadPoolMutex);
2206 g_bleAdapterThreadPoolMutex = NULL;
2208 oc_mutex_free(g_bleClientSendDataMutex);
2209 g_bleClientSendDataMutex = NULL;
2211 oc_mutex_free(g_bleServerSendDataMutex);
2212 g_bleServerSendDataMutex = NULL;
2214 oc_mutex_free(g_bleAdapterReqRespCbMutex);
2215 g_bleAdapterReqRespCbMutex = NULL;
2217 oc_mutex_free(g_bleServerReceiveDataMutex);
2218 g_bleServerReceiveDataMutex = NULL;
2220 oc_mutex_free(g_bleClientReceiveDataMutex);
2221 g_bleClientReceiveDataMutex = NULL;
2225 * Starting LE connectivity adapters.
2227 * As its peer to peer it does not require to start any servers.
2229 * @return ::CA_STATUS_OK or Appropriate error code.
2231 static CAResult_t CAStartLE();
2234 * Start listening server for receiving multicast search requests.
2236 * Transport Specific Behavior:
2237 * LE Starts GATT Server with prefixed UUID and Characteristics
2238 * per OIC Specification.
2239 * @return ::CA_STATUS_OK or Appropriate error code.
2241 static CAResult_t CAStartLEListeningServer();
2244 * Stops listening server from receiving multicast search requests.
2246 * Transport Specific Behavior:
2247 * LE Starts GATT Server with prefixed UUID and Characteristics
2248 * per OIC Specification.
2249 * @return ::CA_STATUS_OK or Appropriate error code.
2251 static CAResult_t CAStopLEListeningServer();
2254 * Sarting discovery of servers for receiving multicast
2257 * Transport Specific Behavior:
2258 * LE Starts GATT Server with prefixed UUID and Characteristics
2259 * per OIC Specification.
2261 * @return ::CA_STATUS_OK or Appropriate error code
2263 static CAResult_t CAStartLEDiscoveryServer();
2266 * Send data to the endpoint using the adapter connectivity.
2268 * @param[in] endpoint Remote Endpoint information (like MAC address,
2269 * reference URI and connectivity type) to which
2270 * the unicast data has to be sent.
2271 * @param[in] data Data which required to be sent.
2272 * @param[in] dataLen Size of data to be sent.
2274 * @note dataLen must be > 0.
2276 * @return The number of bytes sent on the network, or -1 on error.
2278 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2281 CADataType_t dataType);
2284 * Send multicast data to the endpoint using the LE connectivity.
2286 * @param[in] endpoint Remote Endpoint information to which the
2287 * multicast data has to be sent.
2288 * @param[in] data Data which required to be sent.
2289 * @param[in] dataLen Size of data to be sent.
2291 * @note dataLen must be > 0.
2293 * @return The number of bytes sent on the network, or -1 on error.
2295 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
2298 CADataType_t dataType);
2301 * Get LE Connectivity network information.
2303 * @param[out] info Local connectivity information structures.
2304 * @param[out] size Number of local connectivity structures.
2306 * @return ::CA_STATUS_OK or Appropriate error code.
2308 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info,
2312 * Read Synchronous API callback.
2314 * @return ::CA_STATUS_OK or Appropriate error code.
2316 static CAResult_t CAReadLEData();
2319 * Stopping the adapters and close socket connections.
2321 * LE Stops all GATT servers and GATT Clients.
2323 * @return ::CA_STATUS_OK or Appropriate error code.
2325 static CAResult_t CAStopLE();
2328 * Terminate the LE connectivity adapter.
2330 * Configuration information will be deleted from further use.
2332 static void CATerminateLE();
2335 * This function will receive the data from the GattServer and add the
2336 * data to the Server receiver queue.
2338 * @param[in] remoteAddress Remote address of the device from where
2340 * @param[in] data Actual data received from the remote
2342 * @param[in] dataLength Length of the data received from the
2344 * @param[in] sentLength Length of the data sent from the remote
2347 * @return ::CA_STATUS_OK or Appropriate error code.
2348 * @retval ::CA_STATUS_OK Successful.
2349 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2350 * @retval ::CA_STATUS_FAILED Operation failed.
2353 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
2354 const uint8_t *data,
2355 uint32_t dataLength,
2356 uint32_t *sentLength);
2359 * This function will receive the data from the GattClient and add the
2360 * data into the Client receiver queue.
2362 * @param[in] remoteAddress Remote address of the device from where
2364 * @param[in] data Actual data recevied from the remote
2366 * @param[in] dataLength Length of the data received from the
2368 * @param[in] sentLength Length of the data sent from the remote
2371 * @return ::CA_STATUS_OK or Appropriate error code.
2372 * @retval ::CA_STATUS_OK Successful.
2373 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2374 * @retval ::CA_STATUS_FAILED Operation failed.
2376 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
2377 const uint8_t *data,
2378 uint32_t dataLength,
2379 uint32_t *sentLength);
2382 * Set the NetworkPacket received callback to CA layer from adapter
2385 * @param[in] callback Callback handle sent from the upper layer.
2387 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
2390 * Push the data from CA layer to the Sender processor queue.
2392 * @param[in] remoteEndpoint Remote endpoint information of the
2394 * @param[in] data Data to be transmitted from LE.
2395 * @param[in] dataLen Length of the Data being transmitted.
2397 * @return ::CA_STATUS_OK or Appropriate error code.
2398 * @retval ::CA_STATUS_OK Successful.
2399 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2400 * @retval ::CA_STATUS_FAILED Operation failed.
2402 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
2403 const uint8_t *data,
2407 * Push the data from CA layer to the Sender processor queue.
2409 * @param[in] remoteEndpoint Remote endpoint information of the
2411 * @param[in] data Data to be transmitted from LE.
2412 * @param[in] dataLen Length of the Data being transmitted.
2414 * @return ::CA_STATUS_OK or Appropriate error code.
2415 * @retval ::CA_STATUS_OK Successful.
2416 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2417 * @retval ::CA_STATUS_FAILED Operation failed.
2419 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
2420 const uint8_t *data,
2423 static CAResult_t CALEAdapterGattServerStart()
2425 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2427 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2429 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2430 caglobals.bleFlags);
2431 return CA_STATUS_OK;
2434 CAResult_t result = CAStartLEGattServer();
2436 #ifndef SINGLE_THREAD
2438 Don't start the server side sending queue thread until the
2439 server itself has actually started.
2441 if (CA_STATUS_OK == result)
2443 oc_mutex_lock(g_bleServerSendDataMutex);
2444 result = CAQueueingThreadStart(g_bleServerSendQueueHandle);
2445 oc_mutex_unlock(g_bleServerSendDataMutex);
2447 if (CA_STATUS_OK != result)
2451 "Unable to start server queuing thread (%d)",
2460 static CAResult_t CALEAdapterGattServerStop()
2462 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2464 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2466 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2467 caglobals.bleFlags);
2468 return CA_STATUS_OK;
2471 #ifndef SINGLE_THREAD
2473 oc_mutex_lock(g_bleServerSendDataMutex);
2474 CAResult_t res = CAQueueingThreadStop(g_bleServerSendQueueHandle);
2475 if (CA_STATUS_OK != res)
2477 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAQueueingThreadStop has failed");
2479 oc_mutex_unlock(g_bleServerSendDataMutex);
2481 res = CAStopLEGattServer();
2482 if (CA_STATUS_OK != res)
2484 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAStopLEGattServer has failed");
2489 return CAStopLEGattServer();
2493 static CAResult_t CALEAdapterGattClientStart()
2495 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2497 CAResult_t result = CAStartLEGattClient();
2499 #ifndef SINGLE_THREAD
2501 Don't start the client side sending queue thread until the
2502 client itself has actually started.
2504 if (CA_STATUS_OK == result)
2506 oc_mutex_lock(g_bleClientSendDataMutex);
2507 result = CAQueueingThreadStart(g_bleClientSendQueueHandle);
2508 oc_mutex_unlock(g_bleClientSendDataMutex);
2510 if (CA_STATUS_OK != result)
2514 "Unable to start client queuing thread");
2522 static CAResult_t CALEAdapterGattClientStop()
2524 #ifndef SINGLE_THREAD
2525 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2526 CAStopLEGattClient();
2528 oc_mutex_lock(g_bleClientSendDataMutex);
2529 CAResult_t result = CAQueueingThreadStop(g_bleClientSendQueueHandle);
2530 oc_mutex_unlock(g_bleClientSendDataMutex);
2534 CAStopLEGattClient();
2536 return CA_STATUS_OK;
2540 #ifdef __WITH_DTLS__
2541 static ssize_t CALESecureSendDataCB(CAEndpoint_t *endpoint, const void *data, size_t dataLen)
2543 VERIFY_NON_NULL(endpoint, CALEADAPTER_TAG, "endpoint is NULL");
2544 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "data is NULL");
2545 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2546 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "encrypted datalen = %d", dataLen);
2549 CADataType_t dataType = g_dataType;
2552 if (ADAPTER_SERVER == g_adapterType ||
2553 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2555 result = CALEAdapterServerSendData(endpoint, data, dataLen);
2556 if (CA_STATUS_OK != result)
2558 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed" );
2562 g_errorHandler(endpoint, data, dataLen, result);
2566 ret = (ssize_t)dataLen;
2568 else if (ADAPTER_CLIENT == g_adapterType ||
2569 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
2570 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
2572 result = CALEAdapterClientSendData(endpoint, data, dataLen);
2573 if (CA_STATUS_OK != result)
2575 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
2579 g_errorHandler(endpoint, data, dataLen, result);
2583 ret = (ssize_t)dataLen;
2587 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2588 "Can't Send Message adapterType = %d, dataType = %d", g_adapterType, dataType);
2591 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2595 void CALESecureReceiveDataCB(const CASecureEndpoint_t *sep, const void *data,
2598 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2600 VERIFY_NON_NULL_VOID(sep, CALEADAPTER_TAG, "sep is NULL");
2601 VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "data is NULL");
2603 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2604 "Secure Data Receive - decrypted datalen = %d", dataLen);
2608 OIC_LOG(ERROR, CALEADAPTER_TAG, "incorrect dataLen, derecypt fail !");
2612 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2614 if (g_networkPacketReceivedCallback)
2616 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2617 "[CALESecureReceiveDataCB] Secure flags = %d, %x",
2618 sep->endpoint.flags, sep->endpoint.flags);
2619 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2620 "[CALESecureReceiveDataCB] Received data up !");
2621 g_networkPacketReceivedCallback(sep, data, dataLen);
2626 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
2627 CANetworkPacketReceivedCallback reqRespCallback,
2628 CAAdapterChangeCallback netCallback,
2629 CAConnectionChangeCallback connCallback,
2630 CAErrorHandleCallback errorCallback,
2631 ca_thread_pool_t handle)
2633 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2636 VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null");
2637 VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null");
2638 VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null");
2639 VERIFY_NON_NULL(connCallback, CALEADAPTER_TAG, "ConnectionChange Callback is null");
2641 CAResult_t result = CA_STATUS_OK;
2642 result = CAInitLEAdapterMutex();
2643 if (CA_STATUS_OK != result)
2645 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
2646 return CA_STATUS_FAILED;
2649 result = CAInitializeLENetworkMonitor();
2650 if (CA_STATUS_OK != result)
2652 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
2653 return CA_STATUS_FAILED;
2655 CAInitializeLEAdapter();
2657 result = CAInitializeLEGattClient();
2658 if (CA_STATUS_OK != result)
2660 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattClient() failed");
2661 return CA_STATUS_FAILED;
2664 CASetLEClientThreadPoolHandle(handle);
2666 CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
2667 CASetLEServerThreadPoolHandle(handle);
2668 result = CAInitializeLEGattServer();
2669 if (CA_STATUS_OK != result)
2671 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattServer() failed");
2672 return CA_STATUS_FAILED;
2675 CASetLEAdapterThreadPoolHandle(handle);
2676 CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
2677 CASetLEReqRespAdapterCallback(reqRespCallback);
2679 CASetBLEClientErrorHandleCallback(CALEErrorHandler);
2680 CASetBLEServerErrorHandleCallback(CALEErrorHandler);
2681 CALERegisterNetworkNotifications(netCallback, connCallback);
2683 g_errorHandler = errorCallback;
2685 #ifdef __WITH_DTLS__
2686 if (CA_STATUS_OK != CAinitSslAdapter())
2688 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to init SSL adapter");
2692 CAsetSslAdapterCallbacks(CALESecureReceiveDataCB, CALESecureSendDataCB,
2693 CA_ADAPTER_GATT_BTLE);
2697 static const CAConnectivityHandler_t connHandler =
2699 .startAdapter = CAStartLE,
2700 .stopAdapter = CAStopLE,
2701 .startListenServer = CAStartLEListeningServer,
2702 .stopListenServer = CAStopLEListeningServer,
2703 .startDiscoveryServer = CAStartLEDiscoveryServer,
2704 .sendData = CASendLEUnicastData,
2705 .sendDataToAll = CASendLEMulticastData,
2706 .GetnetInfo = CAGetLEInterfaceInformation,
2707 .readData = CAReadLEData,
2708 .terminate = CATerminateLE,
2709 .cType = CA_ADAPTER_GATT_BTLE
2712 registerCallback(connHandler);
2713 return CA_STATUS_OK;
2716 static CAResult_t CAStartLE()
2718 return CAStartLEAdapter();
2721 static CAResult_t CAStopLE()
2723 #ifdef __WITH_DTLS__
2724 CAdeinitSslAdapter();
2727 #ifndef SINGLE_THREAD
2731 oc_mutex_lock(g_bleIsServerMutex);
2732 switch (g_adapterType)
2734 case ADAPTER_SERVER:
2735 CALEAdapterGattServerStop();
2737 case ADAPTER_CLIENT:
2738 CALEAdapterGattClientStop();
2740 case ADAPTER_BOTH_CLIENT_SERVER:
2741 CALEAdapterGattServerStop();
2742 CALEAdapterGattClientStop();
2747 oc_mutex_unlock(g_bleIsServerMutex);
2748 return CAStopLEAdapter();
2751 static void CATerminateLE()
2753 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2755 CASetLEReqRespServerCallback(NULL);
2756 CASetLEReqRespClientCallback(NULL);
2757 CALERegisterNetworkNotifications(NULL, NULL);
2758 CASetLEReqRespAdapterCallback(NULL);
2759 CATerminateLENetworkMonitor();
2761 oc_mutex_lock(g_bleIsServerMutex);
2762 switch (g_adapterType)
2764 case ADAPTER_SERVER:
2765 CATerminateLEGattServer();
2767 case ADAPTER_CLIENT:
2768 CATerminateLEGattClient();
2770 case ADAPTER_BOTH_CLIENT_SERVER:
2771 CATerminateLEGattServer();
2772 CATerminateLEGattClient();
2777 g_adapterType = ADAPTER_EMPTY;
2778 oc_mutex_unlock(g_bleIsServerMutex);
2780 #ifndef SINGLE_THREAD
2781 CATerminateLEQueues();
2784 #ifdef __WITH_DTLS__
2785 CAsetSslAdapterCallbacks(NULL, NULL, CA_ADAPTER_GATT_BTLE);
2788 CATerminateLEAdapterMutex();
2791 static CAResult_t CAStartLEListeningServer()
2793 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2795 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2797 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2798 caglobals.bleFlags);
2799 return CA_STATUS_OK;
2802 #ifndef ROUTING_GATEWAY
2803 CAResult_t result = CA_STATUS_OK;
2804 #ifndef SINGLE_THREAD
2805 result = CAInitLEServerQueues();
2806 if (CA_STATUS_OK != result)
2808 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
2813 oc_mutex_lock(g_bleIsServerMutex);
2814 switch (g_adapterType)
2816 case ADAPTER_CLIENT:
2817 g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2819 case ADAPTER_BOTH_CLIENT_SERVER:
2822 g_adapterType = ADAPTER_SERVER;
2824 oc_mutex_unlock(g_bleIsServerMutex);
2826 result = CAGetLEAdapterState();
2827 if (CA_STATUS_OK != result)
2829 if (CA_ADAPTER_NOT_ENABLED == result)
2833 "Listen Server will be started once BT Adapter is enabled");
2834 result = CA_STATUS_OK;
2839 result = CALEAdapterGattServerStart();
2842 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2845 // Routing Gateway only supports BLE client mode.
2846 OIC_LOG(ERROR, CALEADAPTER_TAG, "LE server not supported in Routing Gateway");
2847 return CA_NOT_SUPPORTED;
2851 static CAResult_t CAStopLEListeningServer()
2853 OIC_LOG(ERROR, CALEADAPTER_TAG, "Listen server stop not supported.");
2854 return CA_NOT_SUPPORTED;
2857 static CAResult_t CAStartLEDiscoveryServer()
2859 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2860 CAResult_t result = CA_STATUS_OK;
2861 #ifndef SINGLE_THREAD
2862 result = CAInitLEClientQueues();
2863 if (CA_STATUS_OK != result)
2865 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
2870 oc_mutex_lock(g_bleIsServerMutex);
2871 switch (g_adapterType)
2873 case ADAPTER_SERVER:
2874 g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2876 case ADAPTER_BOTH_CLIENT_SERVER:
2879 g_adapterType = ADAPTER_CLIENT;
2881 oc_mutex_unlock(g_bleIsServerMutex);
2883 result = CAGetLEAdapterState();
2884 if (CA_STATUS_OK != result)
2886 if (CA_ADAPTER_NOT_ENABLED == result)
2890 "Discovery Server will be started once BT Adapter is enabled");
2891 result = CA_STATUS_OK;
2896 result = CALEAdapterGattClientStart();
2899 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2903 static CAResult_t CAReadLEData()
2905 #ifdef SINGLE_THREAD
2908 return CA_STATUS_OK;
2911 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2914 CADataType_t dataType)
2916 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2917 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "type(%d)", dataType);
2920 VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
2921 VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2923 CAResult_t result = CA_STATUS_FAILED;
2925 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2926 if (ADAPTER_EMPTY == g_adapterType)
2928 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2931 oc_mutex_lock(g_bleIsServerMutex);
2932 if (ADAPTER_SERVER == g_adapterType ||
2933 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2935 #ifdef __WITH_DTLS__
2936 if (endpoint && endpoint->flags & CA_SECURE)
2938 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2939 "Response Data or server - secured data send(caadapternetdtlsencrypt) call");
2940 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2941 g_dataType = dataType;
2942 oc_mutex_unlock(g_bleIsServerMutex);
2944 result = CAencryptSsl(endpoint, data, dataLen);
2945 if (CA_STATUS_OK != result)
2947 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
2954 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2955 "server or both - none secured data send(CALEAdapterServerSendData) call");
2956 result = CALEAdapterServerSendData(endpoint, data, dataLen);
2959 result = CALEAdapterServerSendData(endpoint, data, dataLen);
2961 if (CA_STATUS_OK != result)
2963 oc_mutex_unlock(g_bleIsServerMutex);
2964 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed");
2967 g_errorHandler(endpoint, data, dataLen, result);
2973 else if (ADAPTER_CLIENT == g_adapterType ||
2974 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
2975 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
2977 #ifdef __WITH_DTLS__
2978 if (endpoint && endpoint->flags & CA_SECURE)
2980 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2981 "Request Data or client - secured data send(caadapternetdtlsencrypt) call");
2982 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2983 g_dataType = dataType;
2984 oc_mutex_unlock(g_bleIsServerMutex);
2986 result = CAencryptSsl(endpoint, data, dataLen);
2987 if (CA_STATUS_OK != result)
2989 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
2996 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2997 "client or both - none secured data send(CALEAdapterClientSendData) call");
2998 result = CALEAdapterClientSendData(endpoint, data, dataLen);
3001 result = CALEAdapterClientSendData(endpoint, data, dataLen);
3003 if (CA_STATUS_OK != result)
3005 oc_mutex_unlock(g_bleIsServerMutex);
3006 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
3010 g_errorHandler(endpoint, data, dataLen, result);
3015 oc_mutex_unlock(g_bleIsServerMutex);
3017 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3021 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
3024 CADataType_t dataType)
3026 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3029 VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
3033 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
3037 CAResult_t result = CA_STATUS_FAILED;
3039 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
3040 if (ADAPTER_EMPTY == g_adapterType)
3042 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
3045 oc_mutex_lock(g_bleIsServerMutex);
3046 if (ADAPTER_SERVER == g_adapterType ||
3047 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
3049 result = CALEAdapterServerSendData(NULL, data, dataLen);
3050 if (CA_STATUS_OK != result)
3052 oc_mutex_unlock(g_bleIsServerMutex);
3054 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data for server failed" );
3058 g_errorHandler(endpoint, data, dataLen, result);
3064 if (ADAPTER_CLIENT == g_adapterType ||
3065 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
3066 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
3068 result = CALEAdapterClientSendData(NULL, data, dataLen);
3069 if (CA_STATUS_OK != result)
3071 oc_mutex_unlock(g_bleIsServerMutex);
3073 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data for client failed" );
3077 g_errorHandler(endpoint, data, dataLen, result);
3082 oc_mutex_unlock(g_bleIsServerMutex);
3084 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3088 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
3090 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3092 VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
3094 char *local_address = NULL;
3096 CAResult_t res = CAGetLEAddress(&local_address);
3097 if (CA_STATUS_OK != res)
3099 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
3103 if (NULL == local_address)
3105 OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
3106 return CA_STATUS_FAILED;
3110 (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
3111 if (NULL == (*info))
3113 OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
3114 OICFree(local_address);
3115 return CA_STATUS_FAILED;
3118 size_t local_address_len = strlen(local_address);
3120 if(local_address_len >= sizeof(g_localBLEAddress) ||
3121 local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
3123 OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
3125 OICFree(local_address);
3126 return CA_STATUS_FAILED;
3129 OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
3130 oc_mutex_lock(g_bleLocalAddressMutex);
3131 OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
3132 oc_mutex_unlock(g_bleLocalAddressMutex);
3134 (*info)->adapter = CA_ADAPTER_GATT_BTLE;
3136 OICFree(local_address);
3138 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3139 return CA_STATUS_OK;
3142 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
3143 CAConnectionChangeCallback connCallback)
3145 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3147 oc_mutex_lock(g_bleNetworkCbMutex);
3148 g_networkCallback = netCallback;
3149 g_connectionCallback = connCallback;
3150 oc_mutex_unlock(g_bleNetworkCbMutex);
3151 CAResult_t res = CA_STATUS_OK;
3154 res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
3155 if (CA_STATUS_OK != res)
3157 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
3162 res = CAUnSetLEAdapterStateChangedCb();
3163 if (CA_STATUS_OK != res)
3165 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
3169 if (g_connectionCallback)
3171 res = CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCb);
3172 if (CA_STATUS_OK != res)
3174 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLENWConnectionStateChangedCb failed!");
3179 res = CAUnSetLENWConnectionStateChangedCb();
3180 if (CA_STATUS_OK != res)
3182 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUnSetLENWConnectionStateChangedCb failed!");
3186 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3190 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
3193 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3195 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3198 CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE };
3199 OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), address);
3202 oc_mutex_lock(g_bleIsServerMutex);
3203 switch (g_adapterType)
3205 case ADAPTER_SERVER:
3206 CALEGattServerConnectionStateChanged(isConnected, address);
3208 case ADAPTER_CLIENT:
3209 CALEGattConnectionStateChanged(isConnected, address);
3211 case ADAPTER_BOTH_CLIENT_SERVER:
3212 CALEGattConnectionStateChanged(isConnected, address);
3213 CALEGattServerConnectionStateChanged(isConnected, address);
3218 oc_mutex_unlock(g_bleIsServerMutex);
3223 #ifndef SINGLE_THREAD
3224 if(g_bleClientSenderInfo)
3226 CALERemoveReceiveQueueData(g_bleClientSenderInfo, address);
3229 if(g_bleServerSenderInfo)
3231 CALERemoveReceiveQueueData(g_bleServerSenderInfo, address);
3234 // remove data of send queue.
3235 if (g_bleClientSendQueueHandle)
3237 CALERemoveSendQueueData(g_bleClientSendQueueHandle,
3238 g_bleClientSendDataMutex,
3242 if (g_bleServerSendQueueHandle)
3244 CALERemoveSendQueueData(g_bleServerSendQueueHandle,
3245 g_bleServerSendDataMutex,
3250 #ifdef __WITH_DTLS__
3251 CAcloseSslConnection(&localEndpoint);
3255 if (g_connectionCallback)
3257 g_connectionCallback(&localEndpoint, isConnected);
3260 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3263 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
3265 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3267 if (CA_ADAPTER_ENABLED == adapter_state)
3269 oc_mutex_lock(g_bleIsServerMutex);
3270 switch (g_adapterType)
3272 case ADAPTER_SERVER:
3273 CALEAdapterGattServerStart();
3275 case ADAPTER_CLIENT:
3276 CALEAdapterGattClientStart();
3278 case ADAPTER_BOTH_CLIENT_SERVER:
3279 CALEAdapterGattServerStart();
3280 CALEAdapterGattClientStart();
3285 oc_mutex_unlock(g_bleIsServerMutex);
3289 oc_mutex_lock(g_bleIsServerMutex);
3290 switch (g_adapterType)
3292 case ADAPTER_SERVER:
3293 CALEAdapterGattServerStop();
3295 case ADAPTER_CLIENT:
3296 CALEAdapterGattClientStop();
3298 case ADAPTER_BOTH_CLIENT_SERVER:
3299 CALEAdapterGattServerStop();
3300 CALEAdapterGattClientStop();
3305 oc_mutex_unlock(g_bleIsServerMutex);
3308 if (NULL != g_networkCallback)
3310 g_networkCallback(CA_ADAPTER_GATT_BTLE, adapter_state);
3314 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
3317 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3320 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
3321 const uint8_t *data,
3324 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3325 #ifndef SINGLE_THREAD
3326 VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
3327 "g_bleClientSendQueueHandle is NULL",
3329 VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
3330 "g_bleClientSendDataMutex is NULL",
3333 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%u]", dataLen);
3335 CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3338 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3339 return CA_MEMORY_ALLOC_FAILED;
3341 // Add message to send queue
3342 oc_mutex_lock(g_bleClientSendDataMutex);
3343 CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData, sizeof(CALEData_t));
3344 oc_mutex_unlock(g_bleClientSendDataMutex);
3346 return CA_STATUS_OK;
3349 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
3350 const uint8_t *data,
3353 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3355 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3357 #ifdef SINGLE_THREAD
3358 if (!CAIsLEConnected())
3360 OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
3361 return CA_STATUS_FAILED;
3364 CAResult_t result = CALEServerSendDataSingleThread(data, dataLen);
3365 if (CA_STATUS_OK != result)
3367 OIC_LOG(ERROR, CALEADAPTER_TAG, "CALEServerSendDataSingleThread failed");
3368 return CA_STATUS_FAILED;
3371 VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
3372 "BleClientReceiverQueue is NULL",
3374 VERIFY_NON_NULL_RET(g_bleServerSendDataMutex, CALEADAPTER_TAG,
3375 "BleClientSendDataMutex is NULL",
3378 VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG, "sendQueueHandle",
3381 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
3383 CALEData_t * const bleData =
3384 CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3388 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3389 return CA_MEMORY_ALLOC_FAILED;
3392 // Add message to send queue
3393 oc_mutex_lock(g_bleServerSendDataMutex);
3394 CAQueueingThreadAddData(g_bleServerSendQueueHandle,
3396 sizeof(CALEData_t));
3397 oc_mutex_unlock(g_bleServerSendDataMutex);
3399 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3400 return CA_STATUS_OK;
3403 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
3404 const uint8_t *data,
3405 uint32_t dataLength,
3406 uint32_t *sentLength)
3408 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3411 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3412 VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3414 #ifdef SINGLE_THREAD
3415 CALEDataReceiverHandlerSingleThread(data, dataLength);
3417 if (g_singleThreadReceiveData->totalDataLen == g_singleThreadReceiveData->recvDataLen)
3419 if(g_networkPacketReceivedCallback)
3421 // will be filled by upper layer
3422 const CASecureEndpoint_t endpoint =
3423 { .endpoint = { .adapter = CA_ADAPTER_GATT_BTLE } };
3425 g_networkPacketReceivedCallback(&endpoint,
3426 g_singleThreadReceiveData->defragData,
3427 g_singleThreadReceiveData->recvDataLen);
3429 g_singleThreadReceiveData->remoteEndpoint = NULL;
3430 OICFree(g_singleThreadReceiveData->defragData);
3431 g_singleThreadReceiveData->defragData = NULL;
3432 OICFree(g_singleThreadReceiveData);
3433 g_singleThreadReceiveData = NULL;
3436 VERIFY_NON_NULL_RET(g_bleServerReceiverQueue,
3438 "g_bleServerReceiverQueue",
3441 //Add message to data queue
3442 CAEndpoint_t * const remoteEndpoint =
3443 CACreateEndpointObject(CA_DEFAULT_FLAGS,
3444 CA_ADAPTER_GATT_BTLE,
3448 if (NULL == remoteEndpoint)
3450 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3451 return CA_STATUS_FAILED;
3454 // Create bleData to add to queue
3457 "Data received from LE Server layer [%d]",
3460 CALEData_t * const bleData =
3461 CACreateLEData(remoteEndpoint, data, dataLength, g_bleServerSenderInfo);
3465 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3466 CAFreeEndpoint(remoteEndpoint);
3467 return CA_MEMORY_ALLOC_FAILED;
3470 CAFreeEndpoint(remoteEndpoint);
3471 // Add message to receiver queue
3472 CAQueueingThreadAddData(g_bleServerReceiverQueue, bleData, sizeof(CALEData_t));
3474 *sentLength = dataLength;
3476 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3477 return CA_STATUS_OK;
3480 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
3481 const uint8_t *data,
3482 uint32_t dataLength,
3483 uint32_t *sentLength)
3486 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3487 VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3488 #ifndef SINGLE_THREAD
3489 VERIFY_NON_NULL_RET(g_bleClientReceiverQueue, CALEADAPTER_TAG,
3490 "g_bleClientReceiverQueue",
3493 //Add message to data queue
3494 CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
3495 CA_ADAPTER_GATT_BTLE,
3497 if (NULL == remoteEndpoint)
3499 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3500 return CA_STATUS_FAILED;
3503 // Create bleData to add to queue
3506 "Data received from LE Client layer [%zu]",
3509 CALEData_t * const bleData =
3510 CACreateLEData(remoteEndpoint, data, dataLength, g_bleClientSenderInfo);
3514 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3515 CAFreeEndpoint(remoteEndpoint);
3516 return CA_MEMORY_ALLOC_FAILED;
3519 CAFreeEndpoint(remoteEndpoint);
3520 // Add message to receiver queue
3521 CAQueueingThreadAddData(g_bleClientReceiverQueue, bleData, sizeof(CALEData_t));
3523 *sentLength = dataLength;
3525 return CA_STATUS_OK;
3528 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
3530 oc_mutex_lock(g_bleAdapterThreadPoolMutex);
3531 g_bleAdapterThreadPool = handle;
3532 oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
3535 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
3537 oc_mutex_lock(g_bleAdapterReqRespCbMutex);
3539 g_networkPacketReceivedCallback = callback;
3541 oc_mutex_unlock(g_bleAdapterReqRespCbMutex);
3544 static void CALEErrorHandler(const char *remoteAddress,
3545 const uint8_t *data,
3549 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3551 VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
3553 CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS,
3554 CA_ADAPTER_GATT_BTLE,
3558 // if required, will be used to build remote endpoint
3559 g_errorHandler(rep, data, dataLen, result);
3561 CAFreeEndpoint(rep);
3563 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3566 #ifndef SINGLE_THREAD
3567 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle, oc_mutex mutex,
3568 const char* address)
3570 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
3572 VERIFY_NON_NULL_VOID(queueHandle, CALEADAPTER_TAG, "queueHandle");
3573 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3575 oc_mutex_lock(mutex);
3576 while (u_queue_get_size(queueHandle->dataQueue) > 0)
3578 OIC_LOG(DEBUG, CALEADAPTER_TAG, "get data from queue");
3579 u_queue_message_t *message = u_queue_get_element(queueHandle->dataQueue);
3580 if (NULL != message)
3582 CALEData_t *bleData = (CALEData_t *) message->msg;
3583 if (bleData && bleData->remoteEndpoint)
3585 if (!strcasecmp(bleData->remoteEndpoint->addr, address))
3587 OIC_LOG(DEBUG, CALEADAPTER_TAG, "found the message of disconnected device");
3588 if (NULL != queueHandle->destroy)
3590 queueHandle->destroy(message->msg, message->size);
3594 OICFree(message->msg);
3602 oc_mutex_unlock(mutex);
3605 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList, const char* address)
3607 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
3609 VERIFY_NON_NULL_VOID(dataInfoList, CALEADAPTER_TAG, "dataInfoList");
3610 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3612 CABLESenderInfo_t *senderInfo = NULL;
3613 uint32_t senderIndex = 0;
3615 u_arraylist_t *portList = u_arraylist_create();
3616 if (CA_STATUS_OK == CALEGetPortsFromSenderInfo(address, dataInfoList, portList))
3618 uint32_t arrayLength = u_arraylist_length(portList);
3619 for (uint32_t i = 0; i < arrayLength; i++)
3621 uint16_t *port = (uint16_t *)u_arraylist_get(portList, i);
3624 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to get port from sender info !");
3625 u_arraylist_destroy(portList);
3629 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "port : %X", *port);
3631 if (CA_STATUS_OK == CALEGetSenderInfo(address, *port,
3632 dataInfoList, &senderInfo,
3635 u_arraylist_remove(dataInfoList, senderIndex);
3636 OICFree(senderInfo->defragData);
3637 OICFree(senderInfo->remoteEndpoint);
3638 OICFree(senderInfo);
3640 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3641 "SenderInfo is removed for disconnection");
3645 OIC_LOG(DEBUG, CALEADAPTER_TAG, "SenderInfo doesn't exist");
3649 u_arraylist_destroy(portList);
3652 static CAResult_t CALEGetPortsFromSenderInfo(const char *leAddress,
3653 u_arraylist_t *senderInfoList,
3654 u_arraylist_t *portList)
3656 VERIFY_NON_NULL(leAddress,
3658 "NULL BLE address argument");
3660 const uint32_t listLength = u_arraylist_length(senderInfoList);
3661 const uint32_t addrLength = strlen(leAddress);
3663 for (uint32_t index = 0; index < listLength; index++)
3665 CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
3666 if (!info || !(info->remoteEndpoint))
3671 if (!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
3673 uint16_t *port = (uint16_t *)OICMalloc(sizeof(uint16_t));
3676 OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
3677 return CA_MEMORY_ALLOC_FAILED;
3679 *port = info->remoteEndpoint->port;
3680 u_arraylist_add(portList, (void *)port);
3684 if (u_arraylist_length(portList) != 0)
3686 return CA_STATUS_OK;
3690 return CA_STATUS_FAILED;
3695 void CALEStartGattServer()
3697 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3699 oc_mutex_lock(g_bleIsServerMutex);
3700 switch (g_adapterType)
3702 case ADAPTER_SERVER:
3703 CALEAdapterGattServerStart();
3705 case ADAPTER_CLIENT:
3706 CALEAdapterGattClientStart();
3708 case ADAPTER_BOTH_CLIENT_SERVER:
3709 CALEAdapterGattServerStart();
3710 CALEAdapterGattClientStart();
3715 oc_mutex_unlock(g_bleIsServerMutex);
3716 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3719 void CALEStopGattServer()
3721 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3723 oc_mutex_lock(g_bleIsServerMutex);
3724 switch (g_adapterType)
3726 case ADAPTER_SERVER:
3727 CALEAdapterGattServerStop();
3729 case ADAPTER_CLIENT:
3730 CALEAdapterGattClientStop();
3732 case ADAPTER_BOTH_CLIENT_SERVER:
3733 CALEAdapterGattServerStop();
3734 CALEAdapterGattClientStop();
3739 oc_mutex_unlock(g_bleIsServerMutex);
3740 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);