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 CAResult_t 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);
1248 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1253 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1254 "Packet info: data size[%d] midPacketCount[%u] remainingLen[%zu] totalLength[%zu]",
1255 bleData->dataLen, midPacketCount, remainingLen, totalLength);
1259 "Server total Data length with header is [%zu]",
1262 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1263 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1265 if (NULL != bleData->remoteEndpoint) //Unicast Data
1267 secureFlag = (bleData->remoteEndpoint->flags & CA_SECURE) ?
1268 CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
1270 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This Packet is secure? %d", secureFlag);
1271 result = CAGenerateHeader(dataHeader,
1272 CA_BLE_PACKET_START,
1273 g_localBLESourcePort,
1275 bleData->remoteEndpoint->port);
1277 else //Multicast Data
1279 result = CAGenerateHeader(dataHeader,
1280 CA_BLE_PACKET_START,
1281 g_localBLESourcePort,
1283 CA_BLE_MULTICAST_PORT);
1285 OIC_LOG_V(INFO, CALEADAPTER_TAG, "header info: secureFlag[%X]", secureFlag);
1287 if (CA_STATUS_OK != result)
1289 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1290 "CAGenerateHeader failed, result [%d]", result);
1293 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1298 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1299 result = CAGenerateHeaderPayloadLength(lengthHeader,
1300 CA_BLE_LENGTH_HEADER_SIZE,
1303 if (CA_STATUS_OK != result)
1305 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1306 "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1309 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1314 uint32_t length = 0;
1315 uint32_t dataLen = 0;
1316 if (g_mtuSize > totalLength)
1318 length = totalLength;
1319 dataLen = bleData->dataLen;
1324 dataLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1327 result = CAMakeFirstDataSegment(dataSegment,
1328 bleData->data, dataLen,
1329 dataHeader, lengthHeader);
1331 if (CA_STATUS_OK != result)
1333 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1334 "Making data segment failed, result [%d]", result);
1337 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1342 const uint32_t iter = midPacketCount;
1345 // Send the first segment with the header.
1346 if (NULL != bleData->remoteEndpoint) // Sending Unicast Data
1348 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Unicast Data");
1350 result = CAUpdateCharacteristicsToGattClient(
1351 bleData->remoteEndpoint->addr, dataSegment, length);
1353 if (CA_STATUS_OK != result)
1357 "Update characteristics failed, result [%d]",
1361 g_errorHandler(bleData->remoteEndpoint,
1371 "Server Sent Unicast First Data - data length [%zu]",
1374 result = CAGenerateHeader(dataHeader,
1375 CA_BLE_PACKET_NOT_START,
1376 g_localBLESourcePort,
1378 bleData->remoteEndpoint->port);
1380 if (CA_STATUS_OK != result)
1382 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1383 "CAGenerateHeader failed, result [%d]", result);
1386 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1391 for (index = 0; index < iter; index++)
1393 // Send the remaining header.
1394 result = CAMakeRemainDataSegment(dataSegment,
1395 g_mtuSize - CA_BLE_HEADER_SIZE,
1402 if (CA_STATUS_OK != result)
1404 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1405 "Making data segment failed, result [%d]", result);
1408 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1414 CAUpdateCharacteristicsToGattClient(
1415 bleData->remoteEndpoint->addr,
1419 if (CA_STATUS_OK != result)
1421 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1422 "Update characteristics failed, result [%d]", result);
1425 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1429 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]",
1433 if (remainingLen && (totalLength > g_mtuSize))
1435 // send the last segment of the data (Ex: 22 bytes of 622
1436 // bytes of data when MTU is 200)
1437 result = CAMakeRemainDataSegment(dataSegment,
1445 if (CA_STATUS_OK != result)
1447 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1448 "Making data segment failed, result [%d]", result);
1451 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1456 result = CAUpdateCharacteristicsToGattClient(
1457 bleData->remoteEndpoint->addr,
1459 remainingLen + CA_BLE_HEADER_SIZE);
1461 if (CA_STATUS_OK != result)
1465 "Update characteristics failed, result [%d]",
1469 g_errorHandler(bleData->remoteEndpoint,
1478 "Server Sent Unicast Last Data - data length [%zu]",
1479 remainingLen + CA_BLE_HEADER_SIZE);
1484 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
1485 OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
1488 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1491 static void CALEClientSendDataThread(void *threadData)
1493 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1495 CALEData_t *bleData = (CALEData_t *) threadData;
1498 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid bledata!");
1502 if (!bleData->remoteEndpoint)
1504 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid endpoint of bledata!");
1508 #if defined(__TIZEN__) || defined(__ANDROID__)
1510 if (false == CALEClientIsConnected(bleData->remoteEndpoint->addr))
1512 // triggering to gatt connect and MTU negotiation
1513 CAResult_t res = CALEClientSendNegotiationMessage(
1514 bleData->remoteEndpoint->addr);
1516 if (CA_STATUS_OK != res)
1520 "CALEClientSendNegotiationMessage has failed, result [%d]",
1524 g_errorHandler(bleData->remoteEndpoint,
1532 g_mtuSize = CALEClientGetMtuSize(bleData->remoteEndpoint->addr);
1534 OIC_LOG_V(INFO, CALEADAPTER_TAG, "MTU size [%d]", g_mtuSize);
1536 uint32_t midPacketCount = 0;
1537 size_t remainingLen = 0;
1538 size_t totalLength = 0;
1539 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1541 CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
1547 if (CA_STATUS_OK != result)
1549 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1550 "CAGenerateVariableForFragmentation failed, result [%d]", result);
1553 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1558 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1559 "Packet info: data size[%d] midPacketCount[%u] remainingLen[%zu] totalLength[%zu]",
1560 bleData->dataLen, midPacketCount, remainingLen, totalLength);
1562 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1563 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1565 if (NULL != bleData->remoteEndpoint) //Unicast Data
1567 secureFlag = (bleData->remoteEndpoint->flags & CA_SECURE) ?
1568 CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
1570 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This Packet is secure? %d", secureFlag);
1571 result = CAGenerateHeader(dataHeader,
1572 CA_BLE_PACKET_START,
1573 g_localBLESourcePort,
1575 bleData->remoteEndpoint->port);
1577 else //Multicast Data
1579 result = CAGenerateHeader(dataHeader,
1580 CA_BLE_PACKET_START,
1581 g_localBLESourcePort,
1583 CA_BLE_MULTICAST_PORT);
1586 OIC_LOG_V(INFO, CALEADAPTER_TAG, "header info: secureFlag[%X]", secureFlag);
1588 if (CA_STATUS_OK != result)
1590 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1591 "CAGenerateHeader failed, result [%d]", result);
1594 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1599 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1600 result = CAGenerateHeaderPayloadLength(lengthHeader,
1601 CA_BLE_LENGTH_HEADER_SIZE,
1604 if (CA_STATUS_OK != result)
1606 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1607 "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1610 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1615 uint32_t length = 0;
1616 uint32_t dataLen = 0;
1617 if (g_mtuSize > totalLength)
1619 length = totalLength;
1620 dataLen = bleData->dataLen;
1625 dataLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1628 result = CAMakeFirstDataSegment(dataSegment,
1629 bleData->data, dataLen,
1630 dataHeader, lengthHeader);
1632 if (CA_STATUS_OK != result)
1634 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1635 "Making data segment failed, result [%d]", result);
1638 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1643 const uint32_t iter = midPacketCount;
1645 if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
1647 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
1648 // Send the first segment with the header.
1650 CAUpdateCharacteristicsToGattServer(
1651 bleData->remoteEndpoint->addr,
1657 if (CA_STATUS_OK != result)
1661 "Update characteristics failed, result [%d]",
1665 g_errorHandler(bleData->remoteEndpoint,
1674 "Client Sent Unicast First Data - data length [%zu]",
1677 result = CAGenerateHeader(dataHeader,
1678 CA_BLE_PACKET_NOT_START,
1679 g_localBLESourcePort,
1681 bleData->remoteEndpoint->port);
1683 if (CA_STATUS_OK != result)
1685 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1686 "CAGenerateHeader failed, result [%d]", result);
1689 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1694 for (index = 0; index < iter; index++)
1696 result = CAMakeRemainDataSegment(dataSegment,
1697 g_mtuSize - CA_BLE_HEADER_SIZE,
1704 if (CA_STATUS_OK != result)
1706 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1707 "Making data segment failed, result [%d]", result);
1710 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1715 // Send the remaining header.
1716 result = CAUpdateCharacteristicsToGattServer(
1717 bleData->remoteEndpoint->addr,
1722 if (CA_STATUS_OK != result)
1726 "Update characteristics failed, result [%d]",
1730 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1736 "Client Sent Unicast %d Data - data(mtu) length [%zu]",
1741 if (remainingLen && (totalLength > g_mtuSize))
1743 // send the last segment of the data (Ex: 22 bytes of 622
1744 // bytes of data when MTU is 200)
1745 result = CAMakeRemainDataSegment(dataSegment,
1753 if (CA_STATUS_OK != result)
1755 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1756 "Making data segment failed, result [%d]", result);
1759 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1764 result = CAUpdateCharacteristicsToGattServer(
1765 bleData->remoteEndpoint->addr,
1767 remainingLen + CA_BLE_HEADER_SIZE,
1770 if (CA_STATUS_OK != result)
1772 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1776 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1782 "Client Sent Unicast Last Data - data length [%zu]",
1783 remainingLen + CA_BLE_HEADER_SIZE);
1788 //Sending Mulitcast Data
1789 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Client Sending Multicast Data");
1790 OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
1793 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1796 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
1797 const uint8_t *data,
1798 uint32_t dataLength,
1799 u_arraylist_t *senderInfo)
1801 CALEData_t * const bleData = OICMalloc(sizeof(CALEData_t));
1805 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1809 bleData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
1810 bleData->data = OICCalloc(dataLength + 1, 1);
1812 if (NULL == bleData->data)
1814 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1815 CAFreeLEData(bleData);
1819 memcpy(bleData->data, data, dataLength);
1820 bleData->dataLen = dataLength;
1823 bleData->senderInfo = senderInfo;
1829 static void CAFreeLEData(CALEData_t *bleData)
1831 VERIFY_NON_NULL_VOID(bleData, CALEADAPTER_TAG, "Param bleData is NULL");
1833 CAFreeEndpoint(bleData->remoteEndpoint);
1834 OICFree(bleData->data);
1838 static void CALEDataDestroyer(void *data, uint32_t size)
1840 if ((size_t)size < sizeof(CALEData_t *))
1842 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1843 "Destroy data too small %p %d", data, size);
1845 CALEData_t *ledata = (CALEData_t *) data;
1847 CAFreeLEData(ledata);
1851 #ifdef SINGLE_THREAD
1852 static void CALEDataReceiverHandlerSingleThread(const uint8_t *data,
1855 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1857 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1860 CABLEPacketStart_t startFlag = CA_BLE_PACKET_NOT_START;
1861 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1862 uint16_t sourcePort = 0;
1863 uint16_t destPort = 0;
1865 CAParseHeader(data, &startFlag, &sourcePort, &secureFlag, &destPort);
1866 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1867 "header info: startFlag[%X] sourcePort[%d] secureFlag[%X] destPort[%d]",
1868 startFlag, sourcePort, secureFlag, destPort);
1870 if (destPort != g_localBLESourcePort && destPort != CA_BLE_MULTICAST_PORT)
1872 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1873 "this packet is not valid for this app(port mismatch[mine:%d, packet:%d])",
1874 g_localBLESourcePort, destPort);
1880 if (g_singleThreadReceiveData)
1882 OIC_LOG(ERROR, CALEADAPTER_TAG,
1883 "This packet is start packet but exist senderInfo. Remove senderInfo");
1884 OICFree(g_singleThreadReceiveData->defragData);
1885 OICFree(g_singleThreadReceiveData);
1886 g_singleThreadReceiveData = NULL;
1889 uint32_t totalLength = 0;
1890 CAParseHeaderPayloadLength(data, CA_BLE_LENGTH_HEADER_SIZE, &totalLength);
1892 g_singleThreadReceiveData = OICMalloc(sizeof(CABLESenderInfo_t));
1894 if (!g_singleThreadReceiveData)
1896 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
1899 g_singleThreadReceiveData->recvDataLen = 0;
1900 g_singleThreadReceiveData->totalDataLen = 0;
1901 g_singleThreadReceiveData->defragData = NULL;
1902 g_singleThreadReceiveData->remoteEndpoint = NULL;
1904 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
1906 g_singleThreadReceiveData->totalDataLen = totalLength;
1908 if (!(g_singleThreadReceiveData->totalDataLen))
1910 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
1911 OICFree(g_singleThreadReceiveData);
1915 size_t dataOnlyLen = dataLen - (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE);
1916 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
1917 g_singleThreadReceiveData->totalDataLen);
1918 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%u] bytes",
1921 g_singleThreadReceiveData->defragData =
1922 OICCalloc(g_singleThreadReceiveData->totalDataLen + 1,
1923 sizeof(*g_singleThreadReceiveData->defragData));
1925 if (NULL == g_singleThreadReceiveData->defragData)
1927 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
1928 OICFree(g_singleThreadReceiveData);
1932 if (g_singleThreadReceiveData->recvDataLen + dataOnlyLen
1933 > g_singleThreadReceiveData->totalDataLen)
1935 OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
1936 OICFree(g_singleThreadReceiveData->defragData);
1937 OICFree(g_singleThreadReceiveData);
1940 memcpy(g_singleThreadReceiveData->defragData,
1941 data + (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE),
1943 g_singleThreadReceiveData->recvDataLen += dataOnlyLen;
1947 size_t dataOnlyLen = dataLen - CA_BLE_HEADER_SIZE;
1948 if (g_singleThreadReceiveData->recvDataLen + dataOnlyLen
1949 > g_singleThreadReceiveData->totalDataLen)
1951 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1952 "Data Length exceeding error!! Receiving [%d] total length [%d]",
1953 g_singleThreadReceiveData->recvDataLen + dataOnlyLen,
1954 g_singleThreadReceiveData->totalDataLen);
1955 OICFree(g_singleThreadReceiveData->defragData);
1956 OICFree(g_singleThreadReceiveData);
1959 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]",
1961 memcpy(g_singleThreadReceiveData->defragData + g_singleThreadReceiveData->recvDataLen,
1962 data + CA_BLE_HEADER_SIZE,
1964 g_singleThreadReceiveData->recvDataLen += dataOnlyLen;
1965 OIC_LOG_V(INFO, CALEADAPTER_TAG, "totalDatalength [%d] received Datalen [%d]",
1966 g_singleThreadReceiveData->totalDataLen, g_singleThreadReceiveData->recvDataLen);
1968 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1971 static CAResult_t CALEServerSendDataSingleThread(const uint8_t *data,
1974 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__););
1976 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1978 uint32_t midPacketCount = 0;
1979 size_t remainingLen = 0;
1980 size_t totalLength = 0;
1981 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1983 CAResult_t result = CAGenerateVariableForFragmentation(dataLen,
1989 if (CA_STATUS_OK != result)
1991 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1992 "CAGenerateVariableForFragmentation failed, result [%d]", result);
1996 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1997 "Packet info: data size[%d] midPacketCount[%d] remainingLen[%d] totalLength[%d]",
1998 dataLen, midPacketCount, remainingLen, totalLength);
2002 "Server total Data length with header is [%u]",
2005 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
2006 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
2008 result = CAGenerateHeader(dataHeader,
2009 CA_BLE_PACKET_START,
2010 g_localBLESourcePort,
2011 CA_BLE_PACKET_NON_SECURE,
2012 CA_BLE_MULTICAST_PORT);
2014 if (CA_STATUS_OK != result)
2016 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2017 "CAGenerateHeader failed, result [%d]", result);
2021 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
2022 result = CAGenerateHeaderPayloadLength(lengthHeader,
2023 CA_BLE_LENGTH_HEADER_SIZE,
2026 if (CA_STATUS_OK != result)
2028 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2029 "CAGenerateHeaderPayloadLength failed, result [%d]", result);
2033 uint32_t length = 0;
2034 uint32_t dataOnlyLen = 0;
2035 if (g_mtuSize > totalLength)
2037 length = totalLength;
2038 dataOnlyLen = dataLen;
2043 dataOnlyLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
2046 result = CAMakeFirstDataSegment(dataSegment,
2048 dataHeader, lengthHeader);
2050 if (CA_STATUS_OK != result)
2052 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2053 "Making data segment failed, result [%d]", result);
2057 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
2058 result = CAUpdateCharacteristicsToAllGattClients(dataSegment, length);
2059 if (CA_STATUS_OK != result)
2061 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
2068 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
2070 result = CAGenerateHeader(dataHeader,
2071 CA_BLE_PACKET_NOT_START,
2072 g_localBLESourcePort,
2073 CA_BLE_PACKET_NON_SECURE,
2074 CA_BLE_MULTICAST_PORT);
2076 if (CA_STATUS_OK != result)
2078 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2079 "CAGenerateHeader failed, result [%d]", result);
2083 const uint32_t dataLimit = midPacketCount;
2084 for (uint32_t iter = 0; iter < dataLimit; iter++)
2086 result = CAMakeRemainDataSegment(dataSegment,
2087 g_mtuSize - CA_BLE_HEADER_SIZE,
2094 if (CA_STATUS_OK != result)
2096 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2097 "Making data segment failed, result [%d]", result);
2101 result = CAUpdateCharacteristicsToAllGattClients(
2105 if (CA_STATUS_OK != result)
2107 OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2114 if (remainingLen && (totalLength > g_mtuSize))
2116 // send the last segment of the data
2117 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
2119 result = CAMakeRemainDataSegment(dataSegment,
2127 if (CA_STATUS_OK != result)
2129 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2130 "Making data segment failed, result [%d]", result);
2134 result = CAUpdateCharacteristicsToAllGattClients(
2136 remainingLen + CA_BLE_HEADER_SIZE);
2138 if (CA_STATUS_OK != result)
2140 OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2150 static CAResult_t CAInitLEAdapterMutex()
2152 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2154 if (NULL == g_bleIsServerMutex)
2156 g_bleIsServerMutex = oc_mutex_new();
2157 if (NULL == g_bleIsServerMutex)
2159 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2160 return CA_STATUS_FAILED;
2164 if (NULL == g_bleNetworkCbMutex)
2166 g_bleNetworkCbMutex = oc_mutex_new();
2167 if (NULL == g_bleNetworkCbMutex)
2169 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2170 CATerminateLEAdapterMutex();
2171 return CA_STATUS_FAILED;
2175 if (NULL == g_bleLocalAddressMutex)
2177 g_bleLocalAddressMutex = oc_mutex_new();
2178 if (NULL == g_bleLocalAddressMutex)
2180 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2181 CATerminateLEAdapterMutex();
2182 return CA_STATUS_FAILED;
2186 if (NULL == g_bleAdapterThreadPoolMutex)
2188 g_bleAdapterThreadPoolMutex = oc_mutex_new();
2189 if (NULL == g_bleAdapterThreadPoolMutex)
2191 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2192 CATerminateLEAdapterMutex();
2193 return CA_STATUS_FAILED;
2197 if (NULL == g_bleClientSendDataMutex)
2199 g_bleClientSendDataMutex = oc_mutex_new();
2200 if (NULL == g_bleClientSendDataMutex)
2202 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2203 CATerminateLEAdapterMutex();
2204 return CA_STATUS_FAILED;
2208 if (NULL == g_bleServerSendDataMutex)
2210 g_bleServerSendDataMutex = oc_mutex_new();
2211 if (NULL == g_bleServerSendDataMutex)
2213 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2214 CATerminateLEAdapterMutex();
2215 return CA_STATUS_FAILED;
2219 if (NULL == g_bleAdapterReqRespCbMutex)
2221 g_bleAdapterReqRespCbMutex = oc_mutex_new();
2222 if (NULL == g_bleAdapterReqRespCbMutex)
2224 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2225 CATerminateLEAdapterMutex();
2226 return CA_STATUS_FAILED;
2230 if (NULL == g_bleServerReceiveDataMutex)
2232 g_bleServerReceiveDataMutex = oc_mutex_new();
2233 if (NULL == g_bleServerReceiveDataMutex)
2235 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2236 return CA_STATUS_FAILED;
2240 if (NULL == g_bleClientReceiveDataMutex)
2242 g_bleClientReceiveDataMutex = oc_mutex_new();
2243 if (NULL == g_bleClientReceiveDataMutex)
2245 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2246 return CA_STATUS_FAILED;
2250 return CA_STATUS_OK;
2253 static void CATerminateLEAdapterMutex()
2255 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2257 oc_mutex_free(g_bleIsServerMutex);
2258 g_bleIsServerMutex = NULL;
2260 oc_mutex_free(g_bleNetworkCbMutex);
2261 g_bleNetworkCbMutex = NULL;
2263 oc_mutex_free(g_bleLocalAddressMutex);
2264 g_bleLocalAddressMutex = NULL;
2266 oc_mutex_free(g_bleAdapterThreadPoolMutex);
2267 g_bleAdapterThreadPoolMutex = NULL;
2269 oc_mutex_free(g_bleClientSendDataMutex);
2270 g_bleClientSendDataMutex = NULL;
2272 oc_mutex_free(g_bleServerSendDataMutex);
2273 g_bleServerSendDataMutex = NULL;
2275 oc_mutex_free(g_bleAdapterReqRespCbMutex);
2276 g_bleAdapterReqRespCbMutex = NULL;
2278 oc_mutex_free(g_bleServerReceiveDataMutex);
2279 g_bleServerReceiveDataMutex = NULL;
2281 oc_mutex_free(g_bleClientReceiveDataMutex);
2282 g_bleClientReceiveDataMutex = NULL;
2286 * Starting LE connectivity adapters.
2288 * As its peer to peer it does not require to start any servers.
2290 * @return ::CA_STATUS_OK or Appropriate error code.
2292 static CAResult_t CAStartLE();
2295 * Start listening server for receiving multicast search requests.
2297 * Transport Specific Behavior:
2298 * LE Starts GATT Server with prefixed UUID and Characteristics
2299 * per OIC Specification.
2300 * @return ::CA_STATUS_OK or Appropriate error code.
2302 static CAResult_t CAStartLEListeningServer();
2305 * Stops listening server from receiving multicast search requests.
2307 * Transport Specific Behavior:
2308 * LE Starts GATT Server with prefixed UUID and Characteristics
2309 * per OIC Specification.
2310 * @return ::CA_STATUS_OK or Appropriate error code.
2312 static CAResult_t CAStopLEListeningServer();
2315 * Sarting discovery of servers for receiving multicast
2318 * Transport Specific Behavior:
2319 * LE Starts GATT Server with prefixed UUID and Characteristics
2320 * per OIC Specification.
2322 * @return ::CA_STATUS_OK or Appropriate error code
2324 static CAResult_t CAStartLEDiscoveryServer();
2327 * Send data to the endpoint using the adapter connectivity.
2329 * @param[in] endpoint Remote Endpoint information (like MAC address,
2330 * reference URI and connectivity type) to which
2331 * the unicast data has to be sent.
2332 * @param[in] data Data which required to be sent.
2333 * @param[in] dataLen Size of data to be sent.
2335 * @note dataLen must be > 0.
2337 * @return The number of bytes sent on the network, or -1 on error.
2339 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2342 CADataType_t dataType);
2345 * Send multicast data to the endpoint using the LE connectivity.
2347 * @param[in] endpoint Remote Endpoint information to which the
2348 * multicast data has to be sent.
2349 * @param[in] data Data which required to be sent.
2350 * @param[in] dataLen Size of data to be sent.
2352 * @note dataLen must be > 0.
2354 * @return The number of bytes sent on the network, or -1 on error.
2356 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
2359 CADataType_t dataType);
2362 * Get LE Connectivity network information.
2364 * @param[out] info Local connectivity information structures.
2365 * @param[out] size Number of local connectivity structures.
2367 * @return ::CA_STATUS_OK or Appropriate error code.
2369 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info,
2373 * Read Synchronous API callback.
2375 * @return ::CA_STATUS_OK or Appropriate error code.
2377 static CAResult_t CAReadLEData();
2380 * Stopping the adapters and close socket connections.
2382 * LE Stops all GATT servers and GATT Clients.
2384 * @return ::CA_STATUS_OK or Appropriate error code.
2386 static CAResult_t CAStopLE();
2389 * Terminate the LE connectivity adapter.
2391 * Configuration information will be deleted from further use.
2393 static void CATerminateLE();
2396 * This function will receive the data from the GattServer and add the
2397 * data to the Server receiver queue.
2399 * @param[in] remoteAddress Remote address of the device from where
2401 * @param[in] data Actual data received from the remote
2403 * @param[in] dataLength Length of the data received from the
2405 * @param[in] sentLength Length of the data sent from the remote
2408 * @return ::CA_STATUS_OK or Appropriate error code.
2409 * @retval ::CA_STATUS_OK Successful.
2410 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2411 * @retval ::CA_STATUS_FAILED Operation failed.
2414 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
2415 const uint8_t *data,
2416 uint32_t dataLength,
2417 uint32_t *sentLength);
2420 * This function will receive the data from the GattClient and add the
2421 * data into the Client receiver queue.
2423 * @param[in] remoteAddress Remote address of the device from where
2425 * @param[in] data Actual data recevied from the remote
2427 * @param[in] dataLength Length of the data received from the
2429 * @param[in] sentLength Length of the data sent from the remote
2432 * @return ::CA_STATUS_OK or Appropriate error code.
2433 * @retval ::CA_STATUS_OK Successful.
2434 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2435 * @retval ::CA_STATUS_FAILED Operation failed.
2437 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
2438 const uint8_t *data,
2439 uint32_t dataLength,
2440 uint32_t *sentLength);
2443 * Set the NetworkPacket received callback to CA layer from adapter
2446 * @param[in] callback Callback handle sent from the upper layer.
2448 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
2451 * Push the data from CA layer to the Sender processor queue.
2453 * @param[in] remoteEndpoint Remote endpoint information of the
2455 * @param[in] data Data to be transmitted from LE.
2456 * @param[in] dataLen Length of the Data being transmitted.
2458 * @return ::CA_STATUS_OK or Appropriate error code.
2459 * @retval ::CA_STATUS_OK Successful.
2460 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2461 * @retval ::CA_STATUS_FAILED Operation failed.
2463 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
2464 const uint8_t *data,
2468 * Push the data from CA layer to the Sender processor queue.
2470 * @param[in] remoteEndpoint Remote endpoint information of the
2472 * @param[in] data Data to be transmitted from LE.
2473 * @param[in] dataLen Length of the Data being transmitted.
2475 * @return ::CA_STATUS_OK or Appropriate error code.
2476 * @retval ::CA_STATUS_OK Successful.
2477 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2478 * @retval ::CA_STATUS_FAILED Operation failed.
2480 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
2481 const uint8_t *data,
2484 static CAResult_t CALEAdapterGattServerStart()
2486 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2488 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2490 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2491 caglobals.bleFlags);
2492 return CA_STATUS_OK;
2495 CAResult_t result = CAStartLEGattServer();
2497 #ifndef SINGLE_THREAD
2499 Don't start the server side sending queue thread until the
2500 server itself has actually started.
2502 if (CA_STATUS_OK == result)
2504 oc_mutex_lock(g_bleServerSendDataMutex);
2505 result = CAQueueingThreadStart(g_bleServerSendQueueHandle);
2506 oc_mutex_unlock(g_bleServerSendDataMutex);
2508 if (CA_STATUS_OK != result)
2512 "Unable to start server queuing thread (%d)",
2521 static CAResult_t CALEAdapterGattServerStop()
2523 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2525 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2527 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2528 caglobals.bleFlags);
2529 return CA_STATUS_OK;
2532 #ifndef SINGLE_THREAD
2534 oc_mutex_lock(g_bleServerSendDataMutex);
2535 CAResult_t res = CAQueueingThreadStop(g_bleServerSendQueueHandle);
2536 if (CA_STATUS_OK != res)
2538 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAQueueingThreadStop has failed");
2540 oc_mutex_unlock(g_bleServerSendDataMutex);
2542 res = CAStopLEGattServer();
2543 if (CA_STATUS_OK != res)
2545 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAStopLEGattServer has failed");
2550 return CAStopLEGattServer();
2554 static CAResult_t CALEAdapterGattClientStart()
2556 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2558 CAResult_t result = CAStartLEGattClient();
2560 #ifndef SINGLE_THREAD
2562 Don't start the client side sending queue thread until the
2563 client itself has actually started.
2565 if (CA_STATUS_OK == result)
2567 oc_mutex_lock(g_bleClientSendDataMutex);
2568 result = CAQueueingThreadStart(g_bleClientSendQueueHandle);
2569 oc_mutex_unlock(g_bleClientSendDataMutex);
2571 if (CA_STATUS_OK != result)
2575 "Unable to start client queuing thread");
2583 static CAResult_t CALEAdapterGattClientStop()
2585 #ifndef SINGLE_THREAD
2586 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2587 CAStopLEGattClient();
2589 oc_mutex_lock(g_bleClientSendDataMutex);
2590 CAResult_t result = CAQueueingThreadStop(g_bleClientSendQueueHandle);
2591 oc_mutex_unlock(g_bleClientSendDataMutex);
2595 CAStopLEGattClient();
2597 return CA_STATUS_OK;
2601 #ifdef __WITH_DTLS__
2602 static ssize_t CALESecureSendDataCB(CAEndpoint_t *endpoint, const void *data, size_t dataLen)
2604 VERIFY_NON_NULL(endpoint, CALEADAPTER_TAG, "endpoint is NULL");
2605 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "data is NULL");
2606 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2607 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "encrypted datalen = %d", dataLen);
2610 CADataType_t dataType = g_dataType;
2613 if (ADAPTER_SERVER == g_adapterType ||
2614 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2616 result = CALEAdapterServerSendData(endpoint, data, dataLen);
2617 if (CA_STATUS_OK != result)
2619 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed" );
2623 g_errorHandler(endpoint, data, dataLen, result);
2627 ret = (ssize_t)dataLen;
2629 else if (ADAPTER_CLIENT == g_adapterType ||
2630 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
2631 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
2633 result = CALEAdapterClientSendData(endpoint, data, dataLen);
2634 if (CA_STATUS_OK != result)
2636 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
2640 g_errorHandler(endpoint, data, dataLen, result);
2644 ret = (ssize_t)dataLen;
2648 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2649 "Can't Send Message adapterType = %d, dataType = %d", g_adapterType, dataType);
2652 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2656 CAResult_t CALESecureReceiveDataCB(const CASecureEndpoint_t *sep, const void *data,
2659 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2661 VERIFY_NON_NULL(sep, CALEADAPTER_TAG, "sep is NULL");
2662 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "data is NULL");
2664 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2665 "Secure Data Receive - decrypted datalen = %d", dataLen);
2669 OIC_LOG(ERROR, CALEADAPTER_TAG, "incorrect dataLen, derecypt fail !");
2670 return CA_STATUS_INVALID_PARAM;
2673 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2675 CAResult_t res = CA_STATUS_OK;
2676 if (g_networkPacketReceivedCallback)
2678 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2679 "[CALESecureReceiveDataCB] Secure flags = %d, %x",
2680 sep->endpoint.flags, sep->endpoint.flags);
2681 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2682 "[CALESecureReceiveDataCB] Received data up !");
2683 res = g_networkPacketReceivedCallback(sep, data, dataLen);
2684 if (CA_STATUS_OK != res)
2686 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Error parsing CoAP data, res = %d", res);
2693 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
2694 CANetworkPacketReceivedCallback reqRespCallback,
2695 CAAdapterChangeCallback netCallback,
2696 CAConnectionChangeCallback connCallback,
2697 CAErrorHandleCallback errorCallback,
2698 ca_thread_pool_t handle)
2700 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2703 VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null");
2704 VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null");
2705 VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null");
2706 VERIFY_NON_NULL(connCallback, CALEADAPTER_TAG, "ConnectionChange Callback is null");
2708 CAResult_t result = CA_STATUS_OK;
2709 result = CAInitLEAdapterMutex();
2710 if (CA_STATUS_OK != result)
2712 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
2713 return CA_STATUS_FAILED;
2716 result = CAInitializeLENetworkMonitor();
2717 if (CA_STATUS_OK != result)
2719 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
2720 return CA_STATUS_FAILED;
2722 CAInitializeLEAdapter();
2724 result = CAInitializeLEGattClient();
2725 if (CA_STATUS_OK != result)
2727 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattClient() failed");
2728 return CA_STATUS_FAILED;
2731 CASetLEClientThreadPoolHandle(handle);
2733 CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
2734 CASetLEServerThreadPoolHandle(handle);
2735 result = CAInitializeLEGattServer();
2736 if (CA_STATUS_OK != result)
2738 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattServer() failed");
2739 return CA_STATUS_FAILED;
2742 CASetLEAdapterThreadPoolHandle(handle);
2743 CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
2744 CASetLEReqRespAdapterCallback(reqRespCallback);
2746 CASetBLEClientErrorHandleCallback(CALEErrorHandler);
2747 CASetBLEServerErrorHandleCallback(CALEErrorHandler);
2748 CALERegisterNetworkNotifications(netCallback, connCallback);
2750 g_errorHandler = errorCallback;
2752 #ifdef __WITH_DTLS__
2753 if (CA_STATUS_OK != CAinitSslAdapter())
2755 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to init SSL adapter");
2759 CAsetSslAdapterCallbacks(CALESecureReceiveDataCB, CALESecureSendDataCB,
2760 CA_ADAPTER_GATT_BTLE);
2764 static const CAConnectivityHandler_t connHandler =
2766 .startAdapter = CAStartLE,
2767 .stopAdapter = CAStopLE,
2768 .startListenServer = CAStartLEListeningServer,
2769 .stopListenServer = CAStopLEListeningServer,
2770 .startDiscoveryServer = CAStartLEDiscoveryServer,
2771 .sendData = CASendLEUnicastData,
2772 .sendDataToAll = CASendLEMulticastData,
2773 .GetnetInfo = CAGetLEInterfaceInformation,
2774 .readData = CAReadLEData,
2775 .terminate = CATerminateLE,
2776 .cType = CA_ADAPTER_GATT_BTLE
2779 registerCallback(connHandler);
2780 return CA_STATUS_OK;
2783 static CAResult_t CAStartLE()
2785 return CAStartLEAdapter();
2788 static CAResult_t CAStopLE()
2790 #ifdef __WITH_DTLS__
2791 CAdeinitSslAdapter();
2794 #ifndef SINGLE_THREAD
2798 oc_mutex_lock(g_bleIsServerMutex);
2799 switch (g_adapterType)
2801 case ADAPTER_SERVER:
2802 CALEAdapterGattServerStop();
2804 case ADAPTER_CLIENT:
2805 CALEAdapterGattClientStop();
2807 case ADAPTER_BOTH_CLIENT_SERVER:
2808 CALEAdapterGattServerStop();
2809 CALEAdapterGattClientStop();
2814 oc_mutex_unlock(g_bleIsServerMutex);
2815 return CAStopLEAdapter();
2818 static void CATerminateLE()
2820 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2822 CASetLEReqRespServerCallback(NULL);
2823 CASetLEReqRespClientCallback(NULL);
2824 CALERegisterNetworkNotifications(NULL, NULL);
2825 CASetLEReqRespAdapterCallback(NULL);
2826 CATerminateLENetworkMonitor();
2828 oc_mutex_lock(g_bleIsServerMutex);
2829 switch (g_adapterType)
2831 case ADAPTER_SERVER:
2832 CATerminateLEGattServer();
2834 case ADAPTER_CLIENT:
2835 CATerminateLEGattClient();
2837 case ADAPTER_BOTH_CLIENT_SERVER:
2838 CATerminateLEGattServer();
2839 CATerminateLEGattClient();
2844 g_adapterType = ADAPTER_EMPTY;
2845 oc_mutex_unlock(g_bleIsServerMutex);
2847 #ifndef SINGLE_THREAD
2848 CATerminateLEQueues();
2851 #ifdef __WITH_DTLS__
2852 CAsetSslAdapterCallbacks(NULL, NULL, CA_ADAPTER_GATT_BTLE);
2855 CATerminateLEAdapterMutex();
2858 static CAResult_t CAStartLEListeningServer()
2860 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2862 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2864 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2865 caglobals.bleFlags);
2866 return CA_STATUS_OK;
2869 #ifndef ROUTING_GATEWAY
2870 CAResult_t result = CA_STATUS_OK;
2871 #ifndef SINGLE_THREAD
2872 result = CAInitLEServerQueues();
2873 if (CA_STATUS_OK != result)
2875 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
2880 oc_mutex_lock(g_bleIsServerMutex);
2881 switch (g_adapterType)
2883 case ADAPTER_CLIENT:
2884 g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2886 case ADAPTER_BOTH_CLIENT_SERVER:
2889 g_adapterType = ADAPTER_SERVER;
2891 oc_mutex_unlock(g_bleIsServerMutex);
2893 result = CAGetLEAdapterState();
2894 if (CA_STATUS_OK != result)
2896 if (CA_ADAPTER_NOT_ENABLED == result)
2900 "Listen Server will be started once BT Adapter is enabled");
2901 result = CA_STATUS_OK;
2906 result = CALEAdapterGattServerStart();
2909 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2912 // Routing Gateway only supports BLE client mode.
2913 OIC_LOG(ERROR, CALEADAPTER_TAG, "LE server not supported in Routing Gateway");
2914 return CA_NOT_SUPPORTED;
2918 static CAResult_t CAStopLEListeningServer()
2920 OIC_LOG(ERROR, CALEADAPTER_TAG, "Listen server stop not supported.");
2921 return CA_NOT_SUPPORTED;
2924 static CAResult_t CAStartLEDiscoveryServer()
2926 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2927 CAResult_t result = CA_STATUS_OK;
2928 #ifndef SINGLE_THREAD
2929 result = CAInitLEClientQueues();
2930 if (CA_STATUS_OK != result)
2932 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
2937 oc_mutex_lock(g_bleIsServerMutex);
2938 switch (g_adapterType)
2940 case ADAPTER_SERVER:
2941 g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2943 case ADAPTER_BOTH_CLIENT_SERVER:
2946 g_adapterType = ADAPTER_CLIENT;
2948 oc_mutex_unlock(g_bleIsServerMutex);
2950 result = CAGetLEAdapterState();
2951 if (CA_STATUS_OK != result)
2953 if (CA_ADAPTER_NOT_ENABLED == result)
2957 "Discovery Server will be started once BT Adapter is enabled");
2958 result = CA_STATUS_OK;
2963 result = CALEAdapterGattClientStart();
2966 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2970 static CAResult_t CAReadLEData()
2972 #ifdef SINGLE_THREAD
2975 return CA_STATUS_OK;
2978 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2981 CADataType_t dataType)
2983 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2984 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "type(%d)", dataType);
2987 VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
2988 VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2990 CAResult_t result = CA_STATUS_FAILED;
2992 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2993 if (ADAPTER_EMPTY == g_adapterType)
2995 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2998 oc_mutex_lock(g_bleIsServerMutex);
2999 if (ADAPTER_SERVER == g_adapterType ||
3000 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
3002 #ifdef __WITH_DTLS__
3003 if (endpoint && endpoint->flags & CA_SECURE)
3005 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3006 "Response Data or server - secured data send(caadapternetdtlsencrypt) call");
3007 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
3008 g_dataType = dataType;
3009 oc_mutex_unlock(g_bleIsServerMutex);
3011 result = CAencryptSsl(endpoint, (void *)data, dataLen);
3012 if (CA_STATUS_OK != result)
3014 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
3021 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3022 "server or both - none secured data send(CALEAdapterServerSendData) call");
3023 result = CALEAdapterServerSendData(endpoint, data, dataLen);
3026 result = CALEAdapterServerSendData(endpoint, data, dataLen);
3028 if (CA_STATUS_OK != result)
3030 oc_mutex_unlock(g_bleIsServerMutex);
3031 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed");
3034 g_errorHandler(endpoint, data, dataLen, result);
3040 else if (ADAPTER_CLIENT == g_adapterType ||
3041 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
3042 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
3044 #ifdef __WITH_DTLS__
3045 if (endpoint && endpoint->flags & CA_SECURE)
3047 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3048 "Request Data or client - secured data send(caadapternetdtlsencrypt) call");
3049 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
3050 g_dataType = dataType;
3051 oc_mutex_unlock(g_bleIsServerMutex);
3053 result = CAencryptSsl(endpoint, (void *)data, dataLen);
3054 if (CA_STATUS_OK != result)
3056 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
3063 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3064 "client or both - none secured data send(CALEAdapterClientSendData) call");
3065 result = CALEAdapterClientSendData(endpoint, data, dataLen);
3068 result = CALEAdapterClientSendData(endpoint, data, dataLen);
3070 if (CA_STATUS_OK != result)
3072 oc_mutex_unlock(g_bleIsServerMutex);
3073 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast 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 int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
3091 CADataType_t dataType)
3093 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3096 VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
3100 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
3104 CAResult_t result = CA_STATUS_FAILED;
3106 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
3107 if (ADAPTER_EMPTY == g_adapterType)
3109 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
3112 oc_mutex_lock(g_bleIsServerMutex);
3113 if (ADAPTER_SERVER == g_adapterType ||
3114 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
3116 result = CALEAdapterServerSendData(NULL, data, dataLen);
3117 if (CA_STATUS_OK != result)
3119 oc_mutex_unlock(g_bleIsServerMutex);
3121 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data for server failed" );
3125 g_errorHandler(endpoint, data, dataLen, result);
3131 if (ADAPTER_CLIENT == g_adapterType ||
3132 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
3133 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
3135 result = CALEAdapterClientSendData(NULL, data, dataLen);
3136 if (CA_STATUS_OK != result)
3138 oc_mutex_unlock(g_bleIsServerMutex);
3140 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data for client failed" );
3144 g_errorHandler(endpoint, data, dataLen, result);
3149 oc_mutex_unlock(g_bleIsServerMutex);
3151 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3155 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
3157 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3159 VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
3161 char *local_address = NULL;
3163 CAResult_t res = CAGetLEAddress(&local_address);
3164 if (CA_STATUS_OK != res)
3166 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
3170 if (NULL == local_address)
3172 OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
3173 return CA_STATUS_FAILED;
3177 (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
3178 if (NULL == (*info))
3180 OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
3181 OICFree(local_address);
3182 return CA_STATUS_FAILED;
3185 size_t local_address_len = strlen(local_address);
3187 if(local_address_len >= sizeof(g_localBLEAddress) ||
3188 local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
3190 OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
3192 OICFree(local_address);
3193 return CA_STATUS_FAILED;
3196 OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
3197 oc_mutex_lock(g_bleLocalAddressMutex);
3198 OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
3199 oc_mutex_unlock(g_bleLocalAddressMutex);
3201 (*info)->adapter = CA_ADAPTER_GATT_BTLE;
3203 OICFree(local_address);
3205 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3206 return CA_STATUS_OK;
3209 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
3210 CAConnectionChangeCallback connCallback)
3212 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3214 oc_mutex_lock(g_bleNetworkCbMutex);
3215 g_networkCallback = netCallback;
3216 g_connectionCallback = connCallback;
3217 oc_mutex_unlock(g_bleNetworkCbMutex);
3218 CAResult_t res = CA_STATUS_OK;
3221 res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
3222 if (CA_STATUS_OK != res)
3224 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
3229 res = CAUnSetLEAdapterStateChangedCb();
3230 if (CA_STATUS_OK != res)
3232 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
3236 if (g_connectionCallback)
3238 res = CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCb);
3239 if (CA_STATUS_OK != res)
3241 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLENWConnectionStateChangedCb failed!");
3246 res = CAUnSetLENWConnectionStateChangedCb();
3247 if (CA_STATUS_OK != res)
3249 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUnSetLENWConnectionStateChangedCb failed!");
3253 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3257 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
3260 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3262 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3265 CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE };
3266 OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), address);
3269 oc_mutex_lock(g_bleIsServerMutex);
3270 switch (g_adapterType)
3272 case ADAPTER_SERVER:
3273 CALEGattServerConnectionStateChanged(isConnected, address);
3275 case ADAPTER_CLIENT:
3276 CALEGattConnectionStateChanged(isConnected, address);
3278 case ADAPTER_BOTH_CLIENT_SERVER:
3279 CALEGattConnectionStateChanged(isConnected, address);
3280 CALEGattServerConnectionStateChanged(isConnected, address);
3285 oc_mutex_unlock(g_bleIsServerMutex);
3290 #ifndef SINGLE_THREAD
3291 if(g_bleClientSenderInfo)
3293 CALERemoveReceiveQueueData(g_bleClientSenderInfo, address);
3296 if(g_bleServerSenderInfo)
3298 CALERemoveReceiveQueueData(g_bleServerSenderInfo, address);
3301 // remove data of send queue.
3302 if (g_bleClientSendQueueHandle)
3304 CALERemoveSendQueueData(g_bleClientSendQueueHandle,
3305 g_bleClientSendDataMutex,
3309 if (g_bleServerSendQueueHandle)
3311 CALERemoveSendQueueData(g_bleServerSendQueueHandle,
3312 g_bleServerSendDataMutex,
3317 #ifdef __WITH_DTLS__
3318 CAcloseSslConnection(&localEndpoint);
3322 if (g_connectionCallback)
3324 g_connectionCallback(&localEndpoint, isConnected);
3327 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3330 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
3332 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3334 if (CA_ADAPTER_ENABLED == adapter_state)
3336 oc_mutex_lock(g_bleIsServerMutex);
3337 switch (g_adapterType)
3339 case ADAPTER_SERVER:
3340 CALEAdapterGattServerStart();
3342 case ADAPTER_CLIENT:
3343 CALEAdapterGattClientStart();
3345 case ADAPTER_BOTH_CLIENT_SERVER:
3346 CALEAdapterGattServerStart();
3347 CALEAdapterGattClientStart();
3352 oc_mutex_unlock(g_bleIsServerMutex);
3356 oc_mutex_lock(g_bleIsServerMutex);
3357 switch (g_adapterType)
3359 case ADAPTER_SERVER:
3360 CALEAdapterGattServerStop();
3362 case ADAPTER_CLIENT:
3363 CALEAdapterGattClientStop();
3365 case ADAPTER_BOTH_CLIENT_SERVER:
3366 CALEAdapterGattServerStop();
3367 CALEAdapterGattClientStop();
3372 oc_mutex_unlock(g_bleIsServerMutex);
3375 if (NULL != g_networkCallback)
3377 g_networkCallback(CA_ADAPTER_GATT_BTLE, adapter_state);
3381 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
3384 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3387 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
3388 const uint8_t *data,
3391 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3392 #ifndef SINGLE_THREAD
3393 VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
3394 "g_bleClientSendQueueHandle is NULL",
3396 VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
3397 "g_bleClientSendDataMutex is NULL",
3400 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%u]", dataLen);
3402 CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3405 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3406 return CA_MEMORY_ALLOC_FAILED;
3408 // Add message to send queue
3409 oc_mutex_lock(g_bleClientSendDataMutex);
3410 CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData, sizeof(CALEData_t));
3411 oc_mutex_unlock(g_bleClientSendDataMutex);
3413 return CA_STATUS_OK;
3416 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
3417 const uint8_t *data,
3420 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3422 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3424 #ifdef SINGLE_THREAD
3425 if (!CAIsLEConnected())
3427 OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
3428 return CA_STATUS_FAILED;
3431 CAResult_t result = CALEServerSendDataSingleThread(data, dataLen);
3432 if (CA_STATUS_OK != result)
3434 OIC_LOG(ERROR, CALEADAPTER_TAG, "CALEServerSendDataSingleThread failed");
3435 return CA_STATUS_FAILED;
3438 VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
3439 "BleClientReceiverQueue is NULL",
3441 VERIFY_NON_NULL_RET(g_bleServerSendDataMutex, CALEADAPTER_TAG,
3442 "BleClientSendDataMutex is NULL",
3445 VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG, "sendQueueHandle",
3448 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
3450 CALEData_t * const bleData =
3451 CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3455 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3456 return CA_MEMORY_ALLOC_FAILED;
3459 // Add message to send queue
3460 oc_mutex_lock(g_bleServerSendDataMutex);
3461 CAQueueingThreadAddData(g_bleServerSendQueueHandle,
3463 sizeof(CALEData_t));
3464 oc_mutex_unlock(g_bleServerSendDataMutex);
3466 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3467 return CA_STATUS_OK;
3470 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
3471 const uint8_t *data,
3472 uint32_t dataLength,
3473 uint32_t *sentLength)
3475 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3478 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3479 VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3481 #ifdef SINGLE_THREAD
3482 CALEDataReceiverHandlerSingleThread(data, dataLength);
3484 if (g_singleThreadReceiveData->totalDataLen == g_singleThreadReceiveData->recvDataLen)
3486 if(g_networkPacketReceivedCallback)
3488 // will be filled by upper layer
3489 const CASecureEndpoint_t endpoint =
3490 { .endpoint = { .adapter = CA_ADAPTER_GATT_BTLE } };
3492 g_networkPacketReceivedCallback(&endpoint,
3493 g_singleThreadReceiveData->defragData,
3494 g_singleThreadReceiveData->recvDataLen);
3496 g_singleThreadReceiveData->remoteEndpoint = NULL;
3497 OICFree(g_singleThreadReceiveData->defragData);
3498 g_singleThreadReceiveData->defragData = NULL;
3499 OICFree(g_singleThreadReceiveData);
3500 g_singleThreadReceiveData = NULL;
3503 VERIFY_NON_NULL_RET(g_bleServerReceiverQueue,
3505 "g_bleServerReceiverQueue",
3508 //Add message to data queue
3509 CAEndpoint_t * const remoteEndpoint =
3510 CACreateEndpointObject(CA_DEFAULT_FLAGS,
3511 CA_ADAPTER_GATT_BTLE,
3515 if (NULL == remoteEndpoint)
3517 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3518 return CA_STATUS_FAILED;
3521 // Create bleData to add to queue
3524 "Data received from LE Server layer [%d]",
3527 CALEData_t * const bleData =
3528 CACreateLEData(remoteEndpoint, data, dataLength, g_bleServerSenderInfo);
3532 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3533 CAFreeEndpoint(remoteEndpoint);
3534 return CA_MEMORY_ALLOC_FAILED;
3537 CAFreeEndpoint(remoteEndpoint);
3538 // Add message to receiver queue
3539 CAQueueingThreadAddData(g_bleServerReceiverQueue, bleData, sizeof(CALEData_t));
3541 *sentLength = dataLength;
3543 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3544 return CA_STATUS_OK;
3547 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
3548 const uint8_t *data,
3549 uint32_t dataLength,
3550 uint32_t *sentLength)
3553 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3554 VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3555 #ifndef SINGLE_THREAD
3556 VERIFY_NON_NULL_RET(g_bleClientReceiverQueue, CALEADAPTER_TAG,
3557 "g_bleClientReceiverQueue",
3560 //Add message to data queue
3561 CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
3562 CA_ADAPTER_GATT_BTLE,
3564 if (NULL == remoteEndpoint)
3566 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3567 return CA_STATUS_FAILED;
3570 // Create bleData to add to queue
3573 "Data received from LE Client layer [%zu]",
3576 CALEData_t * const bleData =
3577 CACreateLEData(remoteEndpoint, data, dataLength, g_bleClientSenderInfo);
3581 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3582 CAFreeEndpoint(remoteEndpoint);
3583 return CA_MEMORY_ALLOC_FAILED;
3586 CAFreeEndpoint(remoteEndpoint);
3587 // Add message to receiver queue
3588 CAQueueingThreadAddData(g_bleClientReceiverQueue, bleData, sizeof(CALEData_t));
3590 *sentLength = dataLength;
3592 return CA_STATUS_OK;
3595 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
3597 oc_mutex_lock(g_bleAdapterThreadPoolMutex);
3598 g_bleAdapterThreadPool = handle;
3599 oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
3602 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
3604 oc_mutex_lock(g_bleAdapterReqRespCbMutex);
3606 g_networkPacketReceivedCallback = callback;
3608 oc_mutex_unlock(g_bleAdapterReqRespCbMutex);
3611 static void CALEErrorHandler(const char *remoteAddress,
3612 const uint8_t *data,
3616 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3618 VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
3620 CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS,
3621 CA_ADAPTER_GATT_BTLE,
3625 // if required, will be used to build remote endpoint
3626 g_errorHandler(rep, data, dataLen, result);
3628 CAFreeEndpoint(rep);
3630 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3633 #ifndef SINGLE_THREAD
3634 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle, oc_mutex mutex,
3635 const char* address)
3637 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
3639 VERIFY_NON_NULL_VOID(queueHandle, CALEADAPTER_TAG, "queueHandle");
3640 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3642 oc_mutex_lock(mutex);
3643 oc_mutex_lock(queueHandle->threadMutex);
3644 while (u_queue_get_size(queueHandle->dataQueue) > 0)
3646 OIC_LOG(DEBUG, CALEADAPTER_TAG, "get data from queue");
3647 u_queue_message_t *message = u_queue_get_element(queueHandle->dataQueue);
3648 if (NULL != message)
3650 CALEData_t *bleData = (CALEData_t *) message->msg;
3651 if (bleData && bleData->remoteEndpoint)
3653 if (!strcasecmp(bleData->remoteEndpoint->addr, address))
3655 OIC_LOG(DEBUG, CALEADAPTER_TAG, "found the message of disconnected device");
3656 if (NULL != queueHandle->destroy)
3658 queueHandle->destroy(message->msg, message->size);
3662 OICFree(message->msg);
3670 oc_mutex_unlock(queueHandle->threadMutex);
3671 oc_mutex_unlock(mutex);
3674 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList, const char* address)
3676 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
3678 VERIFY_NON_NULL_VOID(dataInfoList, CALEADAPTER_TAG, "dataInfoList");
3679 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3681 CABLESenderInfo_t *senderInfo = NULL;
3682 uint32_t senderIndex = 0;
3684 u_arraylist_t *portList = u_arraylist_create();
3685 if (CA_STATUS_OK == CALEGetPortsFromSenderInfo(address, dataInfoList, portList))
3687 uint32_t arrayLength = u_arraylist_length(portList);
3688 for (uint32_t i = 0; i < arrayLength; i++)
3690 uint16_t *port = (uint16_t *)u_arraylist_get(portList, i);
3693 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to get port from sender info !");
3694 u_arraylist_destroy(portList);
3698 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "port : %X", *port);
3700 if (CA_STATUS_OK == CALEGetSenderInfo(address, *port,
3701 dataInfoList, &senderInfo,
3704 u_arraylist_remove(dataInfoList, senderIndex);
3705 OICFree(senderInfo->defragData);
3706 OICFree(senderInfo->remoteEndpoint);
3707 OICFree(senderInfo);
3709 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3710 "SenderInfo is removed for disconnection");
3714 OIC_LOG(DEBUG, CALEADAPTER_TAG, "SenderInfo doesn't exist");
3718 u_arraylist_destroy(portList);
3721 static CAResult_t CALEGetPortsFromSenderInfo(const char *leAddress,
3722 u_arraylist_t *senderInfoList,
3723 u_arraylist_t *portList)
3725 VERIFY_NON_NULL(leAddress,
3727 "NULL BLE address argument");
3729 const uint32_t listLength = u_arraylist_length(senderInfoList);
3730 const uint32_t addrLength = strlen(leAddress);
3732 for (uint32_t index = 0; index < listLength; index++)
3734 CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
3735 if (!info || !(info->remoteEndpoint))
3740 if (!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
3742 uint16_t *port = (uint16_t *)OICMalloc(sizeof(uint16_t));
3745 OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
3746 return CA_MEMORY_ALLOC_FAILED;
3748 *port = info->remoteEndpoint->port;
3749 u_arraylist_add(portList, (void *)port);
3753 if (u_arraylist_length(portList) != 0)
3755 return CA_STATUS_OK;
3759 return CA_STATUS_FAILED;
3764 void CALEStartGattServer()
3766 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3768 oc_mutex_lock(g_bleIsServerMutex);
3769 switch (g_adapterType)
3771 case ADAPTER_SERVER:
3772 CALEAdapterGattServerStart();
3774 case ADAPTER_CLIENT:
3775 CALEAdapterGattClientStart();
3777 case ADAPTER_BOTH_CLIENT_SERVER:
3778 CALEAdapterGattServerStart();
3779 CALEAdapterGattClientStart();
3784 oc_mutex_unlock(g_bleIsServerMutex);
3785 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3788 void CALEStopGattServer()
3790 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3792 oc_mutex_lock(g_bleIsServerMutex);
3793 switch (g_adapterType)
3795 case ADAPTER_SERVER:
3796 CALEAdapterGattServerStop();
3798 case ADAPTER_CLIENT:
3799 CALEAdapterGattClientStop();
3801 case ADAPTER_BOTH_CLIENT_SERVER:
3802 CALEAdapterGattServerStop();
3803 CALEAdapterGattClientStop();
3808 oc_mutex_unlock(g_bleIsServerMutex);
3809 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);