1 /* ****************************************************************
3 * Copyright 2014 Samsung Electronics All Rights Reserved.
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 ******************************************************************/
20 #include "caleadapter.h"
25 #include "cafragmentation.h"
27 #include "caleinterface.h"
30 #include "caadapterutils.h"
32 #include "ca_adapter_net_ssl.h"
35 #include "caqueueingthread.h"
37 #if defined(__TIZEN__) || defined(__ANDROID__)
38 #include "caleserver.h"
39 #include "caleclient.h"
41 #include "oic_malloc.h"
42 #include "oic_string.h"
43 #include "caremotehandler.h"
47 * Logging tag for module name.
49 #define CALEADAPTER_TAG "OIC_CA_LE_ADAP"
52 * Stores information of all the senders.
54 * This structure will be used to track and defragment all incoming data packet.
59 uint32_t totalDataLen;
61 CAEndpoint_t *remoteEndpoint;
67 ADAPTER_BOTH_CLIENT_SERVER,
73 * mtu size to use in fragmentation logic.
74 * default value is 20 byte.
76 static uint16_t g_mtuSize = CA_DEFAULT_BLE_MTU_SIZE;
78 * Callback to provide the status of the network change to CA layer.
80 static CAAdapterChangeCallback g_networkCallback = NULL;
83 * Callback to provide the status of the connection change to CA layer.
85 static CAConnectionChangeCallback g_connectionCallback = NULL;
88 * Own port value to identify packet owner. Default port value is 1.
90 static uint8_t g_localBLESourcePort = 1;
93 * bleAddress of the local adapter. Value will be initialized to zero,
94 * and will be updated later.
96 static char g_localBLEAddress[18] = { 0 };
99 * Variable to differentiate btw GattServer and GattClient.
101 static CABLEAdapter_t g_adapterType = ADAPTER_EMPTY;
104 static CADataType_t g_dataType = CA_REQUEST_DATA;
108 * Mutex to synchronize the task to be executed on the GattServer
111 static oc_mutex g_bleIsServerMutex = NULL;
114 * Mutex to synchronize the callback to be called for the network
117 static oc_mutex g_bleNetworkCbMutex = NULL;
120 * Mutex to synchronize the updates of the local LE address of the
123 static oc_mutex g_bleLocalAddressMutex = NULL;
126 * Reference to thread pool.
128 static ca_thread_pool_t g_bleAdapterThreadPool = NULL;
131 * Mutex to synchronize the task to be pushed to thread pool.
133 static oc_mutex g_bleAdapterThreadPoolMutex = NULL;
136 * Mutex to synchronize the queing of the data from SenderQueue.
138 static oc_mutex g_bleClientSendDataMutex = NULL;
141 * Mutex to synchronize the queing of the data from ReceiverQueue.
143 static oc_mutex g_bleClientReceiveDataMutex = NULL;
146 * Mutex to synchronize the queing of the data from SenderQueue.
148 static oc_mutex g_bleServerSendDataMutex = NULL;
151 * Mutex to synchronize the queing of the data from ReceiverQueue.
153 static oc_mutex g_bleServerReceiveDataMutex = NULL;
156 * Mutex to synchronize the callback to be called for the
157 * adapterReqResponse.
159 static oc_mutex g_bleAdapterReqRespCbMutex = NULL;
162 * Callback to be called when network packet received from either
163 * GattServer or GattClient.
165 static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
168 * Callback to notify error from the BLE adapter.
170 static CAErrorHandleCallback g_errorHandler = NULL;
173 static void CALESecureReceiveDataCB(const CASecureEndpoint_t *endpoint,
174 const void *data, size_t dataLength);
176 static ssize_t CALESecureSendDataCB(CAEndpoint_t *endpoint,
177 const void *data, size_t dataLength);
182 * Pointer to defragment received data from single threaded routine.
184 static CABLESenderInfo_t *g_singleThreadReceiveData = NULL;
187 * This function will be associated with the receive for single thread.
189 * This function will defragment the received data from sender
190 * respectively and will send it up to CA layer. Respective sender's
191 * header will provide the length of the data sent.
193 * @param[in] data Actual data received from the remote
195 * @param[in] dataLen Length of the data received from the
198 static void CALEDataReceiverHandlerSingleThread(const uint8_t *data,
202 * This function will be associated with the send for single threaded
205 * This function will fragment the data to the MTU of the transport
206 * and send the data in fragments to the adapters. The function will
207 * be blocked until all data is sent out from the adapter.
209 * @param[in] data Data to be transmitted from LE.
210 * @param[in] dataLen Length of the Data being transmitted.
212 static CAResult_t CALEServerSendDataSingleThread(const uint8_t *data,
217 * Register network change notification callback.
219 * @param[in] netCallback CAAdapterChangeCallback callback which will
220 * be set for the change in adapter.
221 * @param[in] connCallback CAConnectionChangeCallback callback which will
222 * be set for the change in connection.
224 * @return 0 on success otherwise a positive error value.
225 * @retval ::CA_STATUS_OK Successful.
226 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
227 * @retval ::CA_STATUS_FAILED Operation failed.
230 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
231 CAConnectionChangeCallback connCallback);
234 * Set the thread pool handle which is required for spawning new
237 * @param[in] handle Thread pool handle which is given by above layer
238 * for using thread creation task.
241 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle);
244 * Call the callback to the upper layer when the adapter state gets
247 * @param[in] adapter_state New state of the adapter to be notified to
250 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state);
253 * Call the callback to the upper layer when the device connection state gets
256 * @param[in] address LE address of the device to be notified to the upper layer.
257 * @param[in] isConnected whether connection state is connected or not.
259 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
263 * Used to initialize all required mutex variable for LE Adapter
266 * @return 0 on success otherwise a positive error value.
267 * @retval ::CA_STATUS_OK Successful.
268 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
269 * @retval ::CA_STATUS_FAILED Operation failed.
272 static CAResult_t CAInitLEAdapterMutex();
275 * Terminate all required mutex variables for LE adapter
278 static void CATerminateLEAdapterMutex();
281 * Prepares and notify error through error callback.
283 static void CALEErrorHandler(const char *remoteAddress,
288 #ifndef SINGLE_THREAD
290 * Stop condition of Server recvhandler.
292 static bool g_dataBleServerReceiverHandlerState = false;
295 * Stop condition of Client recvhandler.
297 static bool g_dataBleClientReceiverHandlerState = false;
300 * Sender information of Server.
302 static u_arraylist_t *g_bleServerSenderInfo = NULL;
305 * Sender information of Client.
307 static u_arraylist_t *g_bleClientSenderInfo = NULL;
310 * Queue to process the outgoing packets from GATTServer.
312 static CAQueueingThread_t *g_bleServerSendQueueHandle = NULL;
315 * Queue to process the outgoing packets from GATTClient.
317 static CAQueueingThread_t *g_bleClientSendQueueHandle = NULL;
320 * Queue to process the incoming packets from GATTServer.
322 static CAQueueingThread_t *g_bleServerReceiverQueue = NULL;
325 * Queue to process the incoming packets from GATTClient.
327 static CAQueueingThread_t *g_bleClientReceiverQueue = NULL;
330 * This function will be associated with the sender queue for
333 * This function will fragment the data to the MTU of the transport
334 * and send the data in fragments to the adapters. The function will
335 * be blocked until all data is sent out from the adapter.
337 * @param[in] threadData Data pushed to the queue which contains the
338 * info about RemoteEndpoint and Data.
340 static void CALEServerSendDataThread(void *threadData);
343 * This function will be associated with the sender queue for
346 * This function will fragment the data to the MTU of the transport
347 * and send the data in fragments to the adapters. The function will
348 * be blocked until all data is sent out from the adapter.
350 * @param[in] threadData Data pushed to the queue which contains the
351 * info about RemoteEndpoint and Data.
353 static void CALEClientSendDataThread(void *threadData);
356 * This function will defragment the received data from each sender
357 * respectively and will send it up to CA layer. Respective sender's
358 * header will provide the length of the data sent.
360 * @param[in] threadData Data pushed to the queue which contains the
361 * info about RemoteEndpoint and Data.
362 * @param[in] receiverType Whether receiver is server or client.
364 static void CALEDataReceiverHandler(void *threadData, CABLEAdapter_t receiverType);
367 * This function will be associated with the receiver queue for
370 * This function will call the function CALEDataReceiverHandler()
371 * with server type to defragment the received data.
373 * @param[in] threadData Data pushed to the queue which contains the
374 * info about RemoteEndpoint and Data.
376 static void CALEServerDataReceiverHandler(void *threadData);
379 * This function will be associated with the receiver queue for
382 * This function will call the function CALEDataReceiverHandler()
383 * with client type to defragment the received data.
385 * @param[in] threadData Data pushed to the queue which contains the
386 * info about RemoteEndpoint and Data.
388 static void CALEClientDataReceiverHandler(void *threadData);
391 * This function will stop all queues created for GattServer and
392 * GattClient. All four queues will be be stopped with this function
395 static void CAStopLEQueues();
398 * This function will terminate all queues created for GattServer and
399 * GattClient. All four queues will be be terminated with this
400 * function invocations.
402 static void CATerminateLEQueues();
405 * This function will initalize the Receiver and Sender queues for
406 * GattServer. This function will in turn call the functions
407 * CAInitBleServerReceiverQueue() and CAInitBleServerSenderQueue() to
408 * initialize the queues.
410 * @return ::CA_STATUS_OK or Appropriate error code.
411 * @retval ::CA_STATUS_OK Successful.
412 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
413 * @retval ::CA_STATUS_FAILED Operation failed.
415 static CAResult_t CAInitLEServerQueues();
418 * This function will initalize the Receiver and Sender queues for
419 * GattClient. This function will inturn call the functions
420 * CAInitBleClientReceiverQueue() and CAInitBleClientSenderQueue() to
421 * initialize the queues.
423 * @return ::CA_STATUS_OK or Appropriate error code.
424 * @retval ::CA_STATUS_OK Successful.
425 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
426 * @retval ::CA_STATUS_FAILED Operation failed.
429 static CAResult_t CAInitLEClientQueues();
432 * This function will initalize the Receiver queue for
433 * GattServer. This will initialize the queue to process the function
434 * CABLEServerSendDataThread() when ever the task is added to this
437 * @return ::CA_STATUS_OK or Appropriate error code.
438 * @retval ::CA_STATUS_OK Successful.
439 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
440 * @retval ::CA_STATUS_FAILED Operation failed.
442 static CAResult_t CAInitLEServerSenderQueue();
445 * This function will initalize the Receiver queue for
446 * GattClient. This will initialize the queue to process the function
447 * CABLEClientSendDataThread() when ever the task is added to this
450 * @return ::CA_STATUS_OK or Appropriate error code.
451 * @retval ::CA_STATUS_OK Successful.
452 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
453 * @retval ::CA_STATUS_FAILED Operation failed.
455 static CAResult_t CAInitLEClientSenderQueue();
458 * This function will initialize the Receiver queue for
459 * GattServer. This will initialize the queue to process the function
460 * CALEServerDataReceiverHandler() when ever the task is added to this
463 * @return ::CA_STATUS_OK or Appropriate error code
464 * @retval ::CA_STATUS_OK Successful
465 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments
466 * @retval ::CA_STATUS_FAILED Operation failed
469 static CAResult_t CAInitLEServerReceiverQueue();
472 * This function will initialize the Receiver queue for
473 * GattClient. This will initialize the queue to process the function
474 * CALEClientDataReceiverHandler() when ever the task is added to this
477 * @return ::CA_STATUS_OK or Appropriate error code
478 * @retval ::CA_STATUS_OK Successful
479 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments
480 * @retval ::CA_STATUS_FAILED Operation failed
483 static CAResult_t CAInitLEClientReceiverQueue();
486 * This function will create the Data required to send it in the
489 * @param[in] remoteEndpoint Remote endpoint information of the
491 * @param[in] data Data to be transmitted from LE.
492 * @param[in] dataLength Length of the Data being transmitted.
494 * @return ::CA_STATUS_OK or Appropriate error code.
495 * @retval ::CA_STATUS_OK Successful.
496 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
497 * @retval ::CA_STATUS_FAILED Operation failed.
499 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
502 u_arraylist_t *senderInfo);
505 * Used to free the BLE information stored in the sender/receiver
508 * @param[in] bleData Information for a particular data segment.
510 static void CAFreeLEData(CALEData_t *bleData);
515 static void CALEDataDestroyer(void *data, uint32_t size);
517 #ifndef SINGLE_THREAD
519 * remove request or response data of send queue.
521 * @param[in] queueHandle queue to process the outgoing packets.
522 * @param[in] mutex mutex related to sender for client / server.
523 * @param[in] address target address to remove data in queue.
525 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle,
527 const char* address);
530 * remove all received data of data list from receive queue.
532 * @param[in] dataInfoList received data list to remove for client / server.
533 * @param[in] address target address to remove data in queue.
535 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList,
536 const char* address);
539 * get received data info and positioned index from the received data list
540 * for client / server which is matched same leAddress and port.
542 * @param[in] leAddress target address to get serderInfo.
543 * @param[in] port target port to get serderInfo.
544 * @param[in] senderInfoList received data list for client / server.
545 * @param[out] senderInfo Pointer to contain matched(leAddress and port)
546 * received data info.
547 * @param[out] senderIndex Pointer to contain matched(leAddress and port)
548 * received data info index.
550 static CAResult_t CALEGetSenderInfo(const char *leAddress,
552 u_arraylist_t *senderInfoList,
553 CABLESenderInfo_t **senderInfo,
554 uint32_t *senderIndex);
557 * get ports related to remote address. It is need because multi application
558 * can have more than 2 senderInfo using same BLE address. So before remove
559 * receive queue data, should get port list from sender Info.
561 * @param[in] leAddress target address to get port in serderInfo.
562 * @param[in] senderInfoList received data list to remove for client / server.
563 * @param[out] portList target port list related to leAddress.
565 static CAResult_t CALEGetPortsFromSenderInfo(const char *leAddress,
566 u_arraylist_t *senderInfoList,
567 u_arraylist_t *portList);
570 static CAResult_t CAInitLEServerQueues()
572 oc_mutex_lock(g_bleAdapterThreadPoolMutex);
574 CAResult_t result = CAInitLEServerSenderQueue();
575 if (CA_STATUS_OK != result)
577 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerSenderQueue failed");
578 oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
579 return CA_STATUS_FAILED;
582 g_bleServerSenderInfo = u_arraylist_create();
583 if (!g_bleServerSenderInfo)
585 OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
586 oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
587 return CA_MEMORY_ALLOC_FAILED;
590 result = CAInitLEServerReceiverQueue();
591 if (CA_STATUS_OK != result)
593 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerReceiverQueue failed");
594 u_arraylist_free(&g_bleServerSenderInfo);
595 oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
596 return CA_STATUS_FAILED;
599 g_dataBleServerReceiverHandlerState = true;
601 oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
605 static CAResult_t CAInitLEClientQueues()
607 oc_mutex_lock(g_bleAdapterThreadPoolMutex);
609 CAResult_t result = CAInitLEClientSenderQueue();
610 if (CA_STATUS_OK != result)
612 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientSenderQueue failed");
613 oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
614 return CA_STATUS_FAILED;
617 g_bleClientSenderInfo = u_arraylist_create();
618 if (!g_bleClientSenderInfo)
620 OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
621 oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
622 return CA_MEMORY_ALLOC_FAILED;
625 result = CAInitLEClientReceiverQueue();
626 if (CA_STATUS_OK != result)
628 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientReceiverQueue failed");
629 u_arraylist_free(&g_bleClientSenderInfo);
630 oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
631 return CA_STATUS_FAILED;
634 g_dataBleClientReceiverHandlerState = true;
636 oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
640 static CAResult_t CAInitLEServerReceiverQueue()
642 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
643 // Check if the message queue is already initialized
644 if (g_bleServerReceiverQueue)
646 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
650 // Create recv message queue
651 g_bleServerReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
652 if (!g_bleServerReceiverQueue)
654 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
655 return CA_MEMORY_ALLOC_FAILED;
658 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerReceiverQueue,
659 g_bleAdapterThreadPool,
660 CALEServerDataReceiverHandler,
663 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize server receiver queue thread");
664 OICFree(g_bleServerReceiverQueue);
665 g_bleServerReceiverQueue = NULL;
666 return CA_STATUS_FAILED;
669 if (CA_STATUS_OK != CAQueueingThreadStart(g_bleServerReceiverQueue))
671 OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
672 OICFree(g_bleServerReceiverQueue);
673 g_bleServerReceiverQueue = NULL;
674 return CA_STATUS_FAILED;
680 static CAResult_t CAInitLEClientReceiverQueue()
682 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
683 // Check if the message queue is already initialized
684 if (g_bleClientReceiverQueue)
686 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
690 // Create recv message queue
691 g_bleClientReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
692 if (!g_bleClientReceiverQueue)
694 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
695 return CA_MEMORY_ALLOC_FAILED;
698 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientReceiverQueue,
699 g_bleAdapterThreadPool,
700 CALEClientDataReceiverHandler,
703 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize client receiver queue thread");
704 OICFree(g_bleClientReceiverQueue);
705 g_bleClientReceiverQueue = NULL;
706 return CA_STATUS_FAILED;
709 if (CA_STATUS_OK != CAQueueingThreadStart(g_bleClientReceiverQueue))
711 OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
712 OICFree(g_bleClientReceiverQueue);
713 g_bleClientReceiverQueue = NULL;
714 return CA_STATUS_FAILED;
720 static CAResult_t CAInitLEServerSenderQueue()
722 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
723 // Check if the message queue is already initialized
724 if (g_bleServerSendQueueHandle)
726 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Queue is already initialized!");
730 // Create send message queue
731 g_bleServerSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
732 if (!g_bleServerSendQueueHandle)
734 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
735 return CA_MEMORY_ALLOC_FAILED;
738 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerSendQueueHandle,
739 g_bleAdapterThreadPool,
740 CALEServerSendDataThread,
743 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
744 OICFree(g_bleServerSendQueueHandle);
745 g_bleServerSendQueueHandle = NULL;
746 return CA_STATUS_FAILED;
752 static void CALEClearSenderInfoImpl(u_arraylist_t ** list)
754 const size_t length = u_arraylist_length(*list);
755 for (size_t i = 0; i < length; ++i)
757 CABLESenderInfo_t * const info =
758 (CABLESenderInfo_t *) u_arraylist_get(*list, i);
761 OICFree(info->defragData);
762 CAFreeEndpoint(info->remoteEndpoint);
766 u_arraylist_free(list);
769 static void CALEClearSenderInfo()
771 CALEClearSenderInfoImpl(&g_bleServerSenderInfo);
772 CALEClearSenderInfoImpl(&g_bleClientSenderInfo);
775 static CAResult_t CAInitLEClientSenderQueue()
777 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
779 if (g_bleClientSendQueueHandle)
781 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
785 // Create send message queue
786 g_bleClientSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
787 if (!g_bleClientSendQueueHandle)
789 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
790 return CA_MEMORY_ALLOC_FAILED;
793 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientSendQueueHandle,
794 g_bleAdapterThreadPool,
795 CALEClientSendDataThread, CALEDataDestroyer))
797 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
798 OICFree(g_bleClientSendQueueHandle);
799 g_bleClientSendQueueHandle = NULL;
800 return CA_STATUS_FAILED;
805 static void CAStopLEQueues()
807 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
809 oc_mutex_lock(g_bleServerReceiveDataMutex);
810 if (NULL != g_bleServerReceiverQueue)
812 CAQueueingThreadStop(g_bleServerReceiverQueue);
814 oc_mutex_unlock(g_bleServerReceiveDataMutex);
816 oc_mutex_lock(g_bleClientReceiveDataMutex);
817 if (NULL != g_bleClientReceiverQueue)
819 CAQueueingThreadStop(g_bleClientReceiverQueue);
821 oc_mutex_unlock(g_bleClientReceiveDataMutex);
823 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
826 static void CATerminateLEQueues()
828 CAQueueingThreadDestroy(g_bleClientSendQueueHandle);
829 OICFree(g_bleClientSendQueueHandle);
830 g_bleClientSendQueueHandle = NULL;
832 CAQueueingThreadDestroy(g_bleServerSendQueueHandle);
833 OICFree(g_bleServerSendQueueHandle);
834 g_bleServerSendQueueHandle = NULL;
836 CAQueueingThreadDestroy(g_bleServerReceiverQueue);
837 OICFree(g_bleServerReceiverQueue);
838 g_bleServerReceiverQueue = NULL;
840 CAQueueingThreadDestroy(g_bleClientReceiverQueue);
841 OICFree(g_bleClientReceiverQueue);
842 g_bleClientReceiverQueue = NULL;
844 CALEClearSenderInfo();
847 static CAResult_t CALEGetSenderInfo(const char *leAddress,
849 u_arraylist_t *senderInfoList,
850 CABLESenderInfo_t **senderInfo,
851 uint32_t *senderIndex)
853 VERIFY_NON_NULL_RET(leAddress,
855 "NULL BLE address argument",
856 CA_STATUS_INVALID_PARAM);
857 VERIFY_NON_NULL_RET(senderIndex,
859 "NULL index argument",
860 CA_STATUS_INVALID_PARAM);
862 const uint32_t listLength = u_arraylist_length(senderInfoList);
863 const uint32_t addrLength = strlen(leAddress);
864 for (uint32_t index = 0; index < listLength; index++)
866 CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
867 if (!info || !(info->remoteEndpoint))
872 if (!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
874 if (info->remoteEndpoint->port == port)
876 *senderIndex = index;
886 return CA_STATUS_FAILED;
889 static void CALEDataReceiverHandler(void *threadData, CABLEAdapter_t receiverType)
891 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
893 oc_mutex bleReceiveDataMutex = NULL;
894 bool dataBleReceiverHandlerState = false;
896 switch (receiverType)
899 bleReceiveDataMutex = g_bleClientReceiveDataMutex;
900 dataBleReceiverHandlerState = g_dataBleClientReceiverHandlerState;
903 bleReceiveDataMutex = g_bleServerReceiveDataMutex;
904 dataBleReceiverHandlerState = g_dataBleServerReceiverHandlerState;
907 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Unsupported receiver type : %d", receiverType);
911 oc_mutex_lock(bleReceiveDataMutex);
913 if (dataBleReceiverHandlerState)
915 CALEData_t *bleData = (CALEData_t *) threadData;
918 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bleData!");
919 oc_mutex_unlock(bleReceiveDataMutex);
923 if (!(bleData->senderInfo))
925 OIC_LOG(ERROR, CALEADAPTER_TAG, "sender info is not available");
926 oc_mutex_unlock(bleReceiveDataMutex);
930 if (!(bleData->remoteEndpoint))
932 OIC_LOG(ERROR, CALEADAPTER_TAG, "RemoteEndPoint NULL!!");
933 oc_mutex_unlock(bleReceiveDataMutex);
937 CABLESenderInfo_t *senderInfo = NULL;
938 uint32_t senderIndex = 0;
941 CABLEPacketStart_t startFlag = CA_BLE_PACKET_NOT_START;
942 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
943 uint16_t sourcePort = 0;
944 uint16_t destPort = 0;
946 CAParseHeader(bleData->data, &startFlag, &sourcePort, &secureFlag, &destPort);
947 OIC_LOG_V(INFO, CALEADAPTER_TAG,
948 "header info: startFlag[%X] sourcePort[%d] secureFlag[%X] destPort[%d]",
949 startFlag, sourcePort, secureFlag, destPort);
951 if (destPort != g_localBLESourcePort && destPort != CA_BLE_MULTICAST_PORT)
953 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
954 "this packet is not valid for this app(port mismatch[mine:%d, packet:%d])",
955 g_localBLESourcePort, destPort);
956 oc_mutex_unlock(bleReceiveDataMutex);
960 bleData->remoteEndpoint->port = sourcePort;
962 if (CA_STATUS_OK != CALEGetSenderInfo(bleData->remoteEndpoint->addr,
963 bleData->remoteEndpoint->port,
965 &senderInfo, &senderIndex))
967 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This is a new client [%s:%X]",
968 bleData->remoteEndpoint->addr, bleData->remoteEndpoint->port);
974 OIC_LOG(ERROR, CALEADAPTER_TAG,
975 "This packet is start packet but exist senderInfo. Remove senderInfo");
976 u_arraylist_remove(bleData->senderInfo, senderIndex);
977 OICFree(senderInfo->defragData);
986 uint32_t totalLength = 0;
989 CAParseHeaderPayloadLength(bleData->data, CA_BLE_LENGTH_HEADER_SIZE, &totalLength);
993 OIC_LOG(ERROR, CALEADAPTER_TAG, "This packet is wrong packet! ignore.");
994 oc_mutex_unlock(bleReceiveDataMutex);
998 CABLESenderInfo_t *newSender = OICMalloc(sizeof(CABLESenderInfo_t));
1001 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
1002 oc_mutex_unlock(bleReceiveDataMutex);
1005 newSender->recvDataLen = 0;
1006 newSender->totalDataLen = 0;
1007 newSender->defragData = NULL;
1008 newSender->remoteEndpoint = NULL;
1010 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
1012 newSender->totalDataLen = totalLength;
1014 if (!(newSender->totalDataLen))
1016 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
1018 oc_mutex_unlock(bleReceiveDataMutex);
1022 size_t dataOnlyLen =
1023 bleData->dataLen - (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE);
1024 OIC_LOG_V(INFO, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
1025 newSender->totalDataLen);
1026 OIC_LOG_V(INFO, CALEADAPTER_TAG, "data received in the first packet [%zu] bytes",
1029 newSender->defragData = OICCalloc(newSender->totalDataLen + 1,
1030 sizeof(*newSender->defragData));
1032 if (NULL == newSender->defragData)
1034 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
1036 oc_mutex_unlock(bleReceiveDataMutex);
1039 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
1040 #ifdef __WITH_DTLS__
1041 if (CA_BLE_PACKET_SECURE == secureFlag)
1047 const char *remoteAddress = bleData->remoteEndpoint->addr;
1048 newSender->remoteEndpoint = CACreateEndpointObject(flags,
1049 CA_ADAPTER_GATT_BTLE,
1051 bleData->remoteEndpoint->port);
1053 if (NULL == newSender->remoteEndpoint)
1055 OIC_LOG(ERROR, CALEADAPTER_TAG, "remoteEndpoint is NULL!");
1056 OICFree(newSender->defragData);
1058 oc_mutex_unlock(bleReceiveDataMutex);
1062 if (newSender->recvDataLen + dataOnlyLen > newSender->totalDataLen)
1064 OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
1065 OICFree(newSender->defragData);
1066 CAFreeEndpoint(newSender->remoteEndpoint);
1068 oc_mutex_unlock(bleReceiveDataMutex);
1071 memcpy(newSender->defragData,
1072 bleData->data + (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE),
1074 newSender->recvDataLen += dataOnlyLen;
1076 u_arraylist_add(bleData->senderInfo,(void *)newSender);
1078 //Getting newSender index position in bleSenderInfo array list
1080 CALEGetSenderInfo(newSender->remoteEndpoint->addr,
1081 newSender->remoteEndpoint->port,
1082 bleData->senderInfo,
1083 NULL, &senderIndex))
1085 OIC_LOG(ERROR, CALEADAPTER_TAG, "Existing sender index not found!!");
1086 OICFree(newSender->defragData);
1087 CAFreeEndpoint(newSender->remoteEndpoint);
1089 oc_mutex_unlock(bleReceiveDataMutex);
1092 senderInfo = newSender;
1096 size_t dataOnlyLen = bleData->dataLen - CA_BLE_HEADER_SIZE;
1097 if (senderInfo->recvDataLen + dataOnlyLen > senderInfo->totalDataLen)
1099 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1100 "Data Length exceeding error!! Receiving [%zu] total length [%u]",
1101 senderInfo->recvDataLen + dataOnlyLen, senderInfo->totalDataLen);
1102 u_arraylist_remove(bleData->senderInfo, senderIndex);
1103 OICFree(senderInfo->defragData);
1104 OICFree(senderInfo);
1105 oc_mutex_unlock(bleReceiveDataMutex);
1108 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%zu]",
1110 memcpy(senderInfo->defragData + senderInfo->recvDataLen,
1111 bleData->data + CA_BLE_HEADER_SIZE,
1113 senderInfo->recvDataLen += dataOnlyLen;
1114 OIC_LOG_V(INFO, CALEADAPTER_TAG, "totalDatalength [%d] received Datalen [%d]",
1115 senderInfo->totalDataLen, senderInfo->recvDataLen);
1118 if (senderInfo->totalDataLen == senderInfo->recvDataLen)
1120 oc_mutex_lock(g_bleAdapterReqRespCbMutex);
1121 if (NULL == g_networkPacketReceivedCallback)
1123 OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
1125 u_arraylist_remove(bleData->senderInfo, senderIndex);
1126 OICFree(senderInfo->defragData);
1127 OICFree(senderInfo);
1128 oc_mutex_unlock(g_bleAdapterReqRespCbMutex);
1129 oc_mutex_unlock(bleReceiveDataMutex);
1133 OIC_LOG(DEBUG, CALEADAPTER_TAG, "[CALEDataReceiverHandler] Received data up !");
1135 const CASecureEndpoint_t tmp =
1137 .endpoint = *senderInfo->remoteEndpoint
1140 OIC_LOG_V(INFO, CALEADAPTER_TAG, "endpoint flags : %d", tmp.endpoint.flags);
1141 #ifdef __WITH_DTLS__
1142 if (CA_SECURE & tmp.endpoint.flags)
1144 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Secure data received");
1145 switch (receiverType)
1147 case ADAPTER_CLIENT:
1148 g_dataType = CA_REQUEST_DATA;
1150 case ADAPTER_SERVER:
1151 g_dataType = CA_RESPONSE_DATA;
1154 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Unsupported rcvr type:%d",receiverType);
1155 oc_mutex_unlock(g_bleAdapterReqRespCbMutex);
1156 u_arraylist_remove(bleData->senderInfo, senderIndex);
1157 senderInfo->remoteEndpoint = NULL;
1158 senderInfo->defragData = NULL;
1159 OICFree(senderInfo);
1160 oc_mutex_unlock(bleReceiveDataMutex);
1164 if (CA_STATUS_FAILED == CAdecryptSsl(&tmp,
1165 senderInfo->defragData,
1166 senderInfo->recvDataLen))
1168 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAdecryptSsl failed");
1172 OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAdecryptSsl successed");
1174 OICFree(senderInfo->defragData);
1179 OIC_LOG(INFO, CALEADAPTER_TAG, "Non-Secure data received");
1180 g_networkPacketReceivedCallback(&tmp,
1181 senderInfo->defragData,
1182 senderInfo->recvDataLen);
1183 #ifdef __WITH_DTLS__
1187 oc_mutex_unlock(g_bleAdapterReqRespCbMutex);
1188 u_arraylist_remove(bleData->senderInfo, senderIndex);
1189 senderInfo->remoteEndpoint = NULL;
1190 senderInfo->defragData = NULL;
1191 OICFree(senderInfo);
1194 oc_mutex_unlock(bleReceiveDataMutex);
1198 static void CALEServerDataReceiverHandler(void *threadData)
1200 CALEDataReceiverHandler(threadData, ADAPTER_SERVER);
1203 static void CALEClientDataReceiverHandler(void *threadData)
1205 CALEDataReceiverHandler(threadData, ADAPTER_CLIENT);
1208 static void CALEServerSendDataThread(void *threadData)
1210 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1212 CALEData_t * const bleData = (CALEData_t *) threadData;
1215 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid bledata!");
1219 if (!bleData->remoteEndpoint)
1221 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid endpoint of bledata!");
1225 #if defined(__TIZEN__) || defined(__ANDROID__)
1227 g_mtuSize = CALEServerGetMtuSize(bleData->remoteEndpoint->addr);
1229 OIC_LOG_V(INFO, CALEADAPTER_TAG, "MTU size [%d]", g_mtuSize);
1231 uint32_t midPacketCount = 0;
1232 size_t remainingLen = 0;
1233 size_t totalLength = 0;
1234 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1236 CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
1242 if (CA_STATUS_OK != result)
1244 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1245 "CAGenerateVariableForFragmentation failed, result [%d]", result);
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 void CALESecureReceiveDataCB(const CASecureEndpoint_t *sep, const void *data,
2659 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2661 VERIFY_NON_NULL_VOID(sep, CALEADAPTER_TAG, "sep is NULL");
2662 VERIFY_NON_NULL_VOID(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 !");
2673 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2675 if (g_networkPacketReceivedCallback)
2677 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2678 "[CALESecureReceiveDataCB] Secure flags = %d, %x",
2679 sep->endpoint.flags, sep->endpoint.flags);
2680 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2681 "[CALESecureReceiveDataCB] Received data up !");
2682 g_networkPacketReceivedCallback(sep, data, dataLen);
2687 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
2688 CANetworkPacketReceivedCallback reqRespCallback,
2689 CAAdapterChangeCallback netCallback,
2690 CAConnectionChangeCallback connCallback,
2691 CAErrorHandleCallback errorCallback,
2692 ca_thread_pool_t handle)
2694 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2697 VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null");
2698 VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null");
2699 VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null");
2700 VERIFY_NON_NULL(connCallback, CALEADAPTER_TAG, "ConnectionChange Callback is null");
2702 CAResult_t result = CA_STATUS_OK;
2703 result = CAInitLEAdapterMutex();
2704 if (CA_STATUS_OK != result)
2706 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
2707 return CA_STATUS_FAILED;
2710 result = CAInitializeLENetworkMonitor();
2711 if (CA_STATUS_OK != result)
2713 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
2714 return CA_STATUS_FAILED;
2716 CAInitializeLEAdapter();
2718 result = CAInitializeLEGattClient();
2719 if (CA_STATUS_OK != result)
2721 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattClient() failed");
2722 return CA_STATUS_FAILED;
2725 CASetLEClientThreadPoolHandle(handle);
2727 CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
2728 CASetLEServerThreadPoolHandle(handle);
2729 result = CAInitializeLEGattServer();
2730 if (CA_STATUS_OK != result)
2732 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattServer() failed");
2733 return CA_STATUS_FAILED;
2736 CASetLEAdapterThreadPoolHandle(handle);
2737 CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
2738 CASetLEReqRespAdapterCallback(reqRespCallback);
2740 CASetBLEClientErrorHandleCallback(CALEErrorHandler);
2741 CASetBLEServerErrorHandleCallback(CALEErrorHandler);
2742 CALERegisterNetworkNotifications(netCallback, connCallback);
2744 g_errorHandler = errorCallback;
2746 #ifdef __WITH_DTLS__
2747 if (CA_STATUS_OK != CAinitSslAdapter())
2749 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to init SSL adapter");
2753 CAsetSslAdapterCallbacks(CALESecureReceiveDataCB, CALESecureSendDataCB,
2754 CA_ADAPTER_GATT_BTLE);
2758 static const CAConnectivityHandler_t connHandler =
2760 .startAdapter = CAStartLE,
2761 .stopAdapter = CAStopLE,
2762 .startListenServer = CAStartLEListeningServer,
2763 .stopListenServer = CAStopLEListeningServer,
2764 .startDiscoveryServer = CAStartLEDiscoveryServer,
2765 .sendData = CASendLEUnicastData,
2766 .sendDataToAll = CASendLEMulticastData,
2767 .GetnetInfo = CAGetLEInterfaceInformation,
2768 .readData = CAReadLEData,
2769 .terminate = CATerminateLE,
2770 .cType = CA_ADAPTER_GATT_BTLE
2773 registerCallback(connHandler);
2774 return CA_STATUS_OK;
2777 static CAResult_t CAStartLE()
2779 return CAStartLEAdapter();
2782 static CAResult_t CAStopLE()
2784 #ifdef __WITH_DTLS__
2785 CAdeinitSslAdapter();
2788 #ifndef SINGLE_THREAD
2792 oc_mutex_lock(g_bleIsServerMutex);
2793 switch (g_adapterType)
2795 case ADAPTER_SERVER:
2796 CALEAdapterGattServerStop();
2798 case ADAPTER_CLIENT:
2799 CALEAdapterGattClientStop();
2801 case ADAPTER_BOTH_CLIENT_SERVER:
2802 CALEAdapterGattServerStop();
2803 CALEAdapterGattClientStop();
2808 oc_mutex_unlock(g_bleIsServerMutex);
2809 return CAStopLEAdapter();
2812 static void CATerminateLE()
2814 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2816 CASetLEReqRespServerCallback(NULL);
2817 CASetLEReqRespClientCallback(NULL);
2818 CALERegisterNetworkNotifications(NULL, NULL);
2819 CASetLEReqRespAdapterCallback(NULL);
2820 CATerminateLENetworkMonitor();
2822 oc_mutex_lock(g_bleIsServerMutex);
2823 switch (g_adapterType)
2825 case ADAPTER_SERVER:
2826 CATerminateLEGattServer();
2828 case ADAPTER_CLIENT:
2829 CATerminateLEGattClient();
2831 case ADAPTER_BOTH_CLIENT_SERVER:
2832 CATerminateLEGattServer();
2833 CATerminateLEGattClient();
2838 g_adapterType = ADAPTER_EMPTY;
2839 oc_mutex_unlock(g_bleIsServerMutex);
2841 #ifndef SINGLE_THREAD
2842 CATerminateLEQueues();
2845 #ifdef __WITH_DTLS__
2846 CAsetSslAdapterCallbacks(NULL, NULL, CA_ADAPTER_GATT_BTLE);
2849 CATerminateLEAdapterMutex();
2852 static CAResult_t CAStartLEListeningServer()
2854 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2856 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2858 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2859 caglobals.bleFlags);
2860 return CA_STATUS_OK;
2863 #ifndef ROUTING_GATEWAY
2864 CAResult_t result = CA_STATUS_OK;
2865 #ifndef SINGLE_THREAD
2866 result = CAInitLEServerQueues();
2867 if (CA_STATUS_OK != result)
2869 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
2874 oc_mutex_lock(g_bleIsServerMutex);
2875 switch (g_adapterType)
2877 case ADAPTER_CLIENT:
2878 g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2880 case ADAPTER_BOTH_CLIENT_SERVER:
2883 g_adapterType = ADAPTER_SERVER;
2885 oc_mutex_unlock(g_bleIsServerMutex);
2887 result = CAGetLEAdapterState();
2888 if (CA_STATUS_OK != result)
2890 if (CA_ADAPTER_NOT_ENABLED == result)
2894 "Listen Server will be started once BT Adapter is enabled");
2895 result = CA_STATUS_OK;
2900 result = CALEAdapterGattServerStart();
2903 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2906 // Routing Gateway only supports BLE client mode.
2907 OIC_LOG(ERROR, CALEADAPTER_TAG, "LE server not supported in Routing Gateway");
2908 return CA_NOT_SUPPORTED;
2912 static CAResult_t CAStopLEListeningServer()
2914 OIC_LOG(ERROR, CALEADAPTER_TAG, "Listen server stop not supported.");
2915 return CA_NOT_SUPPORTED;
2918 static CAResult_t CAStartLEDiscoveryServer()
2920 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2921 CAResult_t result = CA_STATUS_OK;
2922 #ifndef SINGLE_THREAD
2923 result = CAInitLEClientQueues();
2924 if (CA_STATUS_OK != result)
2926 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
2931 oc_mutex_lock(g_bleIsServerMutex);
2932 switch (g_adapterType)
2934 case ADAPTER_SERVER:
2935 g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2937 case ADAPTER_BOTH_CLIENT_SERVER:
2940 g_adapterType = ADAPTER_CLIENT;
2942 oc_mutex_unlock(g_bleIsServerMutex);
2944 result = CAGetLEAdapterState();
2945 if (CA_STATUS_OK != result)
2947 if (CA_ADAPTER_NOT_ENABLED == result)
2951 "Discovery Server will be started once BT Adapter is enabled");
2952 result = CA_STATUS_OK;
2957 result = CALEAdapterGattClientStart();
2960 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2964 static CAResult_t CAReadLEData()
2966 #ifdef SINGLE_THREAD
2969 return CA_STATUS_OK;
2972 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2975 CADataType_t dataType)
2977 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2978 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "type(%d)", dataType);
2981 VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
2982 VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2984 CAResult_t result = CA_STATUS_FAILED;
2986 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2987 if (ADAPTER_EMPTY == g_adapterType)
2989 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2992 oc_mutex_lock(g_bleIsServerMutex);
2993 if (ADAPTER_SERVER == g_adapterType ||
2994 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2996 #ifdef __WITH_DTLS__
2997 if (endpoint && endpoint->flags & CA_SECURE)
2999 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3000 "Response Data or server - secured data send(caadapternetdtlsencrypt) call");
3001 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
3002 g_dataType = dataType;
3003 oc_mutex_unlock(g_bleIsServerMutex);
3005 result = CAencryptSsl(endpoint, data, dataLen);
3006 if (CA_STATUS_OK != result)
3008 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
3015 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3016 "server or both - none secured data send(CALEAdapterServerSendData) call");
3017 result = CALEAdapterServerSendData(endpoint, data, dataLen);
3020 result = CALEAdapterServerSendData(endpoint, data, dataLen);
3022 if (CA_STATUS_OK != result)
3024 oc_mutex_unlock(g_bleIsServerMutex);
3025 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed");
3028 g_errorHandler(endpoint, data, dataLen, result);
3034 else if (ADAPTER_CLIENT == g_adapterType ||
3035 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
3036 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
3038 #ifdef __WITH_DTLS__
3039 if (endpoint && endpoint->flags & CA_SECURE)
3041 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3042 "Request Data or client - secured data send(caadapternetdtlsencrypt) call");
3043 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
3044 g_dataType = dataType;
3045 oc_mutex_unlock(g_bleIsServerMutex);
3047 result = CAencryptSsl(endpoint, data, dataLen);
3048 if (CA_STATUS_OK != result)
3050 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
3057 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3058 "client or both - none secured data send(CALEAdapterClientSendData) call");
3059 result = CALEAdapterClientSendData(endpoint, data, dataLen);
3062 result = CALEAdapterClientSendData(endpoint, data, dataLen);
3064 if (CA_STATUS_OK != result)
3066 oc_mutex_unlock(g_bleIsServerMutex);
3067 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
3071 g_errorHandler(endpoint, data, dataLen, result);
3076 oc_mutex_unlock(g_bleIsServerMutex);
3078 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3082 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
3085 CADataType_t dataType)
3087 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3090 VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
3094 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
3098 CAResult_t result = CA_STATUS_FAILED;
3100 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
3101 if (ADAPTER_EMPTY == g_adapterType)
3103 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
3106 oc_mutex_lock(g_bleIsServerMutex);
3107 if (ADAPTER_SERVER == g_adapterType ||
3108 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
3110 result = CALEAdapterServerSendData(NULL, data, dataLen);
3111 if (CA_STATUS_OK != result)
3113 oc_mutex_unlock(g_bleIsServerMutex);
3115 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data for server failed" );
3119 g_errorHandler(endpoint, data, dataLen, result);
3125 if (ADAPTER_CLIENT == g_adapterType ||
3126 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
3127 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
3129 result = CALEAdapterClientSendData(NULL, data, dataLen);
3130 if (CA_STATUS_OK != result)
3132 oc_mutex_unlock(g_bleIsServerMutex);
3134 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data for client failed" );
3138 g_errorHandler(endpoint, data, dataLen, result);
3143 oc_mutex_unlock(g_bleIsServerMutex);
3145 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3149 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
3151 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3153 VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
3155 char *local_address = NULL;
3157 CAResult_t res = CAGetLEAddress(&local_address);
3158 if (CA_STATUS_OK != res)
3160 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
3164 if (NULL == local_address)
3166 OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
3167 return CA_STATUS_FAILED;
3171 (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
3172 if (NULL == (*info))
3174 OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
3175 OICFree(local_address);
3176 return CA_STATUS_FAILED;
3179 size_t local_address_len = strlen(local_address);
3181 if(local_address_len >= sizeof(g_localBLEAddress) ||
3182 local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
3184 OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
3186 OICFree(local_address);
3187 return CA_STATUS_FAILED;
3190 OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
3191 oc_mutex_lock(g_bleLocalAddressMutex);
3192 OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
3193 oc_mutex_unlock(g_bleLocalAddressMutex);
3195 (*info)->adapter = CA_ADAPTER_GATT_BTLE;
3197 OICFree(local_address);
3199 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3200 return CA_STATUS_OK;
3203 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
3204 CAConnectionChangeCallback connCallback)
3206 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3208 oc_mutex_lock(g_bleNetworkCbMutex);
3209 g_networkCallback = netCallback;
3210 g_connectionCallback = connCallback;
3211 oc_mutex_unlock(g_bleNetworkCbMutex);
3212 CAResult_t res = CA_STATUS_OK;
3215 res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
3216 if (CA_STATUS_OK != res)
3218 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
3223 res = CAUnSetLEAdapterStateChangedCb();
3224 if (CA_STATUS_OK != res)
3226 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
3230 if (g_connectionCallback)
3232 res = CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCb);
3233 if (CA_STATUS_OK != res)
3235 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLENWConnectionStateChangedCb failed!");
3240 res = CAUnSetLENWConnectionStateChangedCb();
3241 if (CA_STATUS_OK != res)
3243 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUnSetLENWConnectionStateChangedCb failed!");
3247 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3251 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
3254 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3256 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3259 CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE };
3260 OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), address);
3263 oc_mutex_lock(g_bleIsServerMutex);
3264 switch (g_adapterType)
3266 case ADAPTER_SERVER:
3267 CALEGattServerConnectionStateChanged(isConnected, address);
3269 case ADAPTER_CLIENT:
3270 CALEGattConnectionStateChanged(isConnected, address);
3272 case ADAPTER_BOTH_CLIENT_SERVER:
3273 CALEGattConnectionStateChanged(isConnected, address);
3274 CALEGattServerConnectionStateChanged(isConnected, address);
3279 oc_mutex_unlock(g_bleIsServerMutex);
3284 #ifndef SINGLE_THREAD
3285 if(g_bleClientSenderInfo)
3287 CALERemoveReceiveQueueData(g_bleClientSenderInfo, address);
3290 if(g_bleServerSenderInfo)
3292 CALERemoveReceiveQueueData(g_bleServerSenderInfo, address);
3295 // remove data of send queue.
3296 if (g_bleClientSendQueueHandle)
3298 CALERemoveSendQueueData(g_bleClientSendQueueHandle,
3299 g_bleClientSendDataMutex,
3303 if (g_bleServerSendQueueHandle)
3305 CALERemoveSendQueueData(g_bleServerSendQueueHandle,
3306 g_bleServerSendDataMutex,
3311 #ifdef __WITH_DTLS__
3312 CAcloseSslConnection(&localEndpoint);
3316 if (g_connectionCallback)
3318 g_connectionCallback(&localEndpoint, isConnected);
3321 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3324 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
3326 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3328 if (CA_ADAPTER_ENABLED == adapter_state)
3330 oc_mutex_lock(g_bleIsServerMutex);
3331 switch (g_adapterType)
3333 case ADAPTER_SERVER:
3334 CALEAdapterGattServerStart();
3336 case ADAPTER_CLIENT:
3337 CALEAdapterGattClientStart();
3339 case ADAPTER_BOTH_CLIENT_SERVER:
3340 CALEAdapterGattServerStart();
3341 CALEAdapterGattClientStart();
3346 oc_mutex_unlock(g_bleIsServerMutex);
3350 oc_mutex_lock(g_bleIsServerMutex);
3351 switch (g_adapterType)
3353 case ADAPTER_SERVER:
3354 CALEAdapterGattServerStop();
3356 case ADAPTER_CLIENT:
3357 CALEAdapterGattClientStop();
3359 case ADAPTER_BOTH_CLIENT_SERVER:
3360 CALEAdapterGattServerStop();
3361 CALEAdapterGattClientStop();
3366 oc_mutex_unlock(g_bleIsServerMutex);
3369 if (NULL != g_networkCallback)
3371 g_networkCallback(CA_ADAPTER_GATT_BTLE, adapter_state);
3375 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
3378 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3381 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
3382 const uint8_t *data,
3385 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3386 #ifndef SINGLE_THREAD
3387 VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
3388 "g_bleClientSendQueueHandle is NULL",
3390 VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
3391 "g_bleClientSendDataMutex is NULL",
3394 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%u]", dataLen);
3396 CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3399 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3400 return CA_MEMORY_ALLOC_FAILED;
3402 // Add message to send queue
3403 oc_mutex_lock(g_bleClientSendDataMutex);
3404 CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData, sizeof(CALEData_t));
3405 oc_mutex_unlock(g_bleClientSendDataMutex);
3407 return CA_STATUS_OK;
3410 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
3411 const uint8_t *data,
3414 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3416 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3418 #ifdef SINGLE_THREAD
3419 if (!CAIsLEConnected())
3421 OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
3422 return CA_STATUS_FAILED;
3425 CAResult_t result = CALEServerSendDataSingleThread(data, dataLen);
3426 if (CA_STATUS_OK != result)
3428 OIC_LOG(ERROR, CALEADAPTER_TAG, "CALEServerSendDataSingleThread failed");
3429 return CA_STATUS_FAILED;
3432 VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
3433 "BleClientReceiverQueue is NULL",
3435 VERIFY_NON_NULL_RET(g_bleServerSendDataMutex, CALEADAPTER_TAG,
3436 "BleClientSendDataMutex is NULL",
3439 VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG, "sendQueueHandle",
3442 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
3444 CALEData_t * const bleData =
3445 CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3449 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3450 return CA_MEMORY_ALLOC_FAILED;
3453 // Add message to send queue
3454 oc_mutex_lock(g_bleServerSendDataMutex);
3455 CAQueueingThreadAddData(g_bleServerSendQueueHandle,
3457 sizeof(CALEData_t));
3458 oc_mutex_unlock(g_bleServerSendDataMutex);
3460 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3461 return CA_STATUS_OK;
3464 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
3465 const uint8_t *data,
3466 uint32_t dataLength,
3467 uint32_t *sentLength)
3469 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3472 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3473 VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3475 #ifdef SINGLE_THREAD
3476 CALEDataReceiverHandlerSingleThread(data, dataLength);
3478 if (g_singleThreadReceiveData->totalDataLen == g_singleThreadReceiveData->recvDataLen)
3480 if(g_networkPacketReceivedCallback)
3482 // will be filled by upper layer
3483 const CASecureEndpoint_t endpoint =
3484 { .endpoint = { .adapter = CA_ADAPTER_GATT_BTLE } };
3486 g_networkPacketReceivedCallback(&endpoint,
3487 g_singleThreadReceiveData->defragData,
3488 g_singleThreadReceiveData->recvDataLen);
3490 g_singleThreadReceiveData->remoteEndpoint = NULL;
3491 OICFree(g_singleThreadReceiveData->defragData);
3492 g_singleThreadReceiveData->defragData = NULL;
3493 OICFree(g_singleThreadReceiveData);
3494 g_singleThreadReceiveData = NULL;
3497 VERIFY_NON_NULL_RET(g_bleServerReceiverQueue,
3499 "g_bleServerReceiverQueue",
3502 //Add message to data queue
3503 CAEndpoint_t * const remoteEndpoint =
3504 CACreateEndpointObject(CA_DEFAULT_FLAGS,
3505 CA_ADAPTER_GATT_BTLE,
3509 if (NULL == remoteEndpoint)
3511 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3512 return CA_STATUS_FAILED;
3515 // Create bleData to add to queue
3518 "Data received from LE Server layer [%d]",
3521 CALEData_t * const bleData =
3522 CACreateLEData(remoteEndpoint, data, dataLength, g_bleServerSenderInfo);
3526 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3527 CAFreeEndpoint(remoteEndpoint);
3528 return CA_MEMORY_ALLOC_FAILED;
3531 CAFreeEndpoint(remoteEndpoint);
3532 // Add message to receiver queue
3533 CAQueueingThreadAddData(g_bleServerReceiverQueue, bleData, sizeof(CALEData_t));
3535 *sentLength = dataLength;
3537 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3538 return CA_STATUS_OK;
3541 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
3542 const uint8_t *data,
3543 uint32_t dataLength,
3544 uint32_t *sentLength)
3547 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3548 VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3549 #ifndef SINGLE_THREAD
3550 VERIFY_NON_NULL_RET(g_bleClientReceiverQueue, CALEADAPTER_TAG,
3551 "g_bleClientReceiverQueue",
3554 //Add message to data queue
3555 CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
3556 CA_ADAPTER_GATT_BTLE,
3558 if (NULL == remoteEndpoint)
3560 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3561 return CA_STATUS_FAILED;
3564 // Create bleData to add to queue
3567 "Data received from LE Client layer [%zu]",
3570 CALEData_t * const bleData =
3571 CACreateLEData(remoteEndpoint, data, dataLength, g_bleClientSenderInfo);
3575 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3576 CAFreeEndpoint(remoteEndpoint);
3577 return CA_MEMORY_ALLOC_FAILED;
3580 CAFreeEndpoint(remoteEndpoint);
3581 // Add message to receiver queue
3582 CAQueueingThreadAddData(g_bleClientReceiverQueue, bleData, sizeof(CALEData_t));
3584 *sentLength = dataLength;
3586 return CA_STATUS_OK;
3589 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
3591 oc_mutex_lock(g_bleAdapterThreadPoolMutex);
3592 g_bleAdapterThreadPool = handle;
3593 oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
3596 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
3598 oc_mutex_lock(g_bleAdapterReqRespCbMutex);
3600 g_networkPacketReceivedCallback = callback;
3602 oc_mutex_unlock(g_bleAdapterReqRespCbMutex);
3605 static void CALEErrorHandler(const char *remoteAddress,
3606 const uint8_t *data,
3610 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3612 VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
3614 CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS,
3615 CA_ADAPTER_GATT_BTLE,
3619 // if required, will be used to build remote endpoint
3620 g_errorHandler(rep, data, dataLen, result);
3622 CAFreeEndpoint(rep);
3624 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3627 #ifndef SINGLE_THREAD
3628 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle, oc_mutex mutex,
3629 const char* address)
3631 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
3633 VERIFY_NON_NULL_VOID(queueHandle, CALEADAPTER_TAG, "queueHandle");
3634 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3636 oc_mutex_lock(mutex);
3637 while (u_queue_get_size(queueHandle->dataQueue) > 0)
3639 OIC_LOG(DEBUG, CALEADAPTER_TAG, "get data from queue");
3640 u_queue_message_t *message = u_queue_get_element(queueHandle->dataQueue);
3641 if (NULL != message)
3643 CALEData_t *bleData = (CALEData_t *) message->msg;
3644 if (bleData && bleData->remoteEndpoint)
3646 if (!strcasecmp(bleData->remoteEndpoint->addr, address))
3648 OIC_LOG(DEBUG, CALEADAPTER_TAG, "found the message of disconnected device");
3649 if (NULL != queueHandle->destroy)
3651 queueHandle->destroy(message->msg, message->size);
3655 OICFree(message->msg);
3663 oc_mutex_unlock(mutex);
3666 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList, const char* address)
3668 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
3670 VERIFY_NON_NULL_VOID(dataInfoList, CALEADAPTER_TAG, "dataInfoList");
3671 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3673 CABLESenderInfo_t *senderInfo = NULL;
3674 uint32_t senderIndex = 0;
3676 u_arraylist_t *portList = u_arraylist_create();
3677 if (CA_STATUS_OK == CALEGetPortsFromSenderInfo(address, dataInfoList, portList))
3679 uint32_t arrayLength = u_arraylist_length(portList);
3680 for (uint32_t i = 0; i < arrayLength; i++)
3682 uint16_t *port = (uint16_t *)u_arraylist_get(portList, i);
3685 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to get port from sender info !");
3686 u_arraylist_destroy(portList);
3690 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "port : %X", *port);
3692 if (CA_STATUS_OK == CALEGetSenderInfo(address, *port,
3693 dataInfoList, &senderInfo,
3696 u_arraylist_remove(dataInfoList, senderIndex);
3697 OICFree(senderInfo->defragData);
3698 OICFree(senderInfo->remoteEndpoint);
3699 OICFree(senderInfo);
3701 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3702 "SenderInfo is removed for disconnection");
3706 OIC_LOG(DEBUG, CALEADAPTER_TAG, "SenderInfo doesn't exist");
3710 u_arraylist_destroy(portList);
3713 static CAResult_t CALEGetPortsFromSenderInfo(const char *leAddress,
3714 u_arraylist_t *senderInfoList,
3715 u_arraylist_t *portList)
3717 VERIFY_NON_NULL(leAddress,
3719 "NULL BLE address argument");
3721 const uint32_t listLength = u_arraylist_length(senderInfoList);
3722 const uint32_t addrLength = strlen(leAddress);
3724 for (uint32_t index = 0; index < listLength; index++)
3726 CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
3727 if (!info || !(info->remoteEndpoint))
3732 if (!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
3734 uint16_t *port = (uint16_t *)OICMalloc(sizeof(uint16_t));
3737 OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
3738 return CA_MEMORY_ALLOC_FAILED;
3740 *port = info->remoteEndpoint->port;
3741 u_arraylist_add(portList, (void *)port);
3745 if (u_arraylist_length(portList) != 0)
3747 return CA_STATUS_OK;
3751 return CA_STATUS_FAILED;
3756 void CALEStartGattServer()
3758 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3760 oc_mutex_lock(g_bleIsServerMutex);
3761 switch (g_adapterType)
3763 case ADAPTER_SERVER:
3764 CALEAdapterGattServerStart();
3766 case ADAPTER_CLIENT:
3767 CALEAdapterGattClientStart();
3769 case ADAPTER_BOTH_CLIENT_SERVER:
3770 CALEAdapterGattServerStart();
3771 CALEAdapterGattClientStart();
3776 oc_mutex_unlock(g_bleIsServerMutex);
3777 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3780 void CALEStopGattServer()
3782 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3784 oc_mutex_lock(g_bleIsServerMutex);
3785 switch (g_adapterType)
3787 case ADAPTER_SERVER:
3788 CALEAdapterGattServerStop();
3790 case ADAPTER_CLIENT:
3791 CALEAdapterGattClientStop();
3793 case ADAPTER_BOTH_CLIENT_SERVER:
3794 CALEAdapterGattServerStop();
3795 CALEAdapterGattClientStop();
3800 oc_mutex_unlock(g_bleIsServerMutex);
3801 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);