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;
68 ADAPTER_BOTH_CLIENT_SERVER,
74 * mtu size to use in fragmentation logic.
75 * default value is 20 byte.
77 static uint16_t g_mtuSize = CA_DEFAULT_BLE_MTU_SIZE;
80 * Callback to provide the status of the network change to CA layer.
82 static CAAdapterChangeCallback g_networkCallback = NULL;
85 * Callback to provide the status of the connection change to CA layer.
87 static CAConnectionChangeCallback g_connectionCallback = NULL;
90 * Own port value to identify packet owner. Default port value is 1.
92 static uint8_t g_localBLESourcePort = 1;
95 * bleAddress of the local adapter. Value will be initialized to zero,
96 * and will be updated later.
98 static char g_localBLEAddress[18] = { 0 };
101 * Variable to differentiate btw GattServer and GattClient.
103 static CABLEAdapter_t g_adapterType = ADAPTER_EMPTY;
106 static CADataType_t g_dataType = CA_REQUEST_DATA;
110 * Mutex to synchronize the task to be executed on the GattServer
113 static oc_mutex g_bleIsServerMutex = NULL;
116 * Mutex to synchronize the updates of the local LE address of the
119 static oc_mutex g_bleLocalAddressMutex = NULL;
122 * Reference to thread pool.
124 static ca_thread_pool_t g_bleAdapterThreadPool = NULL;
127 * Mutex to synchronize the queing of the data from ReceiverQueue.
129 static oc_mutex g_bleClientReceiveDataMutex = NULL;
132 * Mutex to synchronize the queing of the data from ReceiverQueue.
134 static oc_mutex g_bleServerReceiveDataMutex = NULL;
137 * Callback to be called when network packet received from either
138 * GattServer or GattClient.
140 static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
143 * Callback to notify error from the BLE adapter.
145 static CAErrorHandleCallback g_errorHandler = NULL;
148 static CAResult_t CALESecureReceiveDataCB(const CASecureEndpoint_t *endpoint,
149 const void *data, size_t dataLength);
151 static ssize_t CALESecureSendDataCB(CAEndpoint_t *endpoint,
152 const void *data, size_t dataLength);
157 * Pointer to defragment received data from single threaded routine.
159 static CABLESenderInfo_t *g_singleThreadReceiveData = NULL;
162 * This function will be associated with the receive for single thread.
164 * This function will defragment the received data from sender
165 * respectively and will send it up to CA layer. Respective sender's
166 * header will provide the length of the data sent.
168 * @param[in] data Actual data received from the remote
170 * @param[in] dataLen Length of the data received from the
173 static void CALEDataReceiverHandlerSingleThread(const uint8_t *data,
177 * This function will be associated with the send for single threaded
180 * This function will fragment the data to the MTU of the transport
181 * and send the data in fragments to the adapters. The function will
182 * be blocked until all data is sent out from the adapter.
184 * @param[in] data Data to be transmitted from LE.
185 * @param[in] dataLen Length of the Data being transmitted.
187 static CAResult_t CALEServerSendDataSingleThread(const uint8_t *data,
192 * Register network change notification callback.
194 * @param[in] netCallback CAAdapterChangeCallback callback which will
195 * be set for the change in adapter.
196 * @param[in] connCallback CAConnectionChangeCallback callback which will
197 * be set for the change in connection.
199 * @return 0 on success otherwise a positive error value.
200 * @retval ::CA_STATUS_OK Successful.
201 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
202 * @retval ::CA_STATUS_FAILED Operation failed.
205 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
206 CAConnectionChangeCallback connCallback);
209 * Set the thread pool handle which is required for spawning new
212 * @param[in] handle Thread pool handle which is given by above layer
213 * for using thread creation task.
216 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle);
219 * Call the callback to the upper layer when the adapter state gets
222 * @param[in] adapter_state New state of the adapter to be notified to
225 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state);
228 * Call the callback to the upper layer when the device connection state gets
231 * @param[in] address LE address of the device to be notified to the upper layer.
232 * @param[in] isConnected whether connection state is connected or not.
234 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
238 * Used to initialize all required mutex variable for LE Adapter
241 * @return 0 on success otherwise a positive error value.
242 * @retval ::CA_STATUS_OK Successful.
243 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
244 * @retval ::CA_STATUS_FAILED Operation failed.
247 static CAResult_t CAInitLEAdapterMutex();
250 * Terminate all required mutex variables for LE adapter
253 static void CATerminateLEAdapterMutex();
256 * Prepares and notify error through error callback.
258 static void CALEErrorHandler(const char *remoteAddress,
263 #ifndef SINGLE_THREAD
265 * Stop condition of Server recvhandler.
267 static bool g_dataBleServerReceiverHandlerState = false;
270 * Stop condition of Client recvhandler.
272 static bool g_dataBleClientReceiverHandlerState = false;
275 * Sender information of Server.
277 static u_arraylist_t *g_bleServerSenderInfo = NULL;
280 * Sender information of Client.
282 static u_arraylist_t *g_bleClientSenderInfo = NULL;
285 * Mutex to synchronize access to all senderInfos
287 static oc_mutex g_senderInfoMutex = NULL;
290 * Queue to process the outgoing packets from GATTServer.
292 static CAQueueingThread_t *g_bleServerSendQueueHandle = NULL;
295 * Queue to process the outgoing packets from GATTClient.
297 static CAQueueingThread_t *g_bleClientSendQueueHandle = NULL;
300 * Queue to process the incoming packets from GATTServer.
302 static CAQueueingThread_t *g_bleServerReceiverQueue = NULL;
305 * Queue to process the incoming packets from GATTClient.
307 static CAQueueingThread_t *g_bleClientReceiverQueue = NULL;
310 * This function will be associated with the sender queue for
313 * This function will fragment the data to the MTU of the transport
314 * and send the data in fragments to the adapters. The function will
315 * be blocked until all data is sent out from the adapter.
317 * @param[in] threadData Data pushed to the queue which contains the
318 * info about RemoteEndpoint and Data.
320 static void CALEServerSendDataThread(void *threadData);
323 * This function will be associated with the sender queue for
326 * This function will fragment the data to the MTU of the transport
327 * and send the data in fragments to the adapters. The function will
328 * be blocked until all data is sent out from the adapter.
330 * @param[in] threadData Data pushed to the queue which contains the
331 * info about RemoteEndpoint and Data.
333 static void CALEClientSendDataThread(void *threadData);
336 * This function will defragment the received data from each sender
337 * respectively and will send it up to CA layer. Respective sender's
338 * header will provide the length of the data sent.
340 * @param[in] threadData Data pushed to the queue which contains the
341 * info about RemoteEndpoint and Data.
342 * @param[in] receiverType Whether receiver is server or client.
344 static void CALEDataReceiverHandler(void *threadData, CABLEAdapter_t receiverType);
347 * This function will be associated with the receiver queue for
350 * This function will call the function CALEDataReceiverHandler()
351 * with server type to defragment the received data.
353 * @param[in] threadData Data pushed to the queue which contains the
354 * info about RemoteEndpoint and Data.
356 static void CALEServerDataReceiverHandler(void *threadData);
359 * This function will be associated with the receiver queue for
362 * This function will call the function CALEDataReceiverHandler()
363 * with client type to defragment the received data.
365 * @param[in] threadData Data pushed to the queue which contains the
366 * info about RemoteEndpoint and Data.
368 static void CALEClientDataReceiverHandler(void *threadData);
371 * This function will stop all queues created for GattServer and
372 * GattClient. All four queues will be be stopped with this function
375 static void CAStopLEQueues();
378 * This function will terminate all queues created for GattServer and
379 * GattClient. All four queues will be be terminated with this
380 * function invocations.
382 static void CATerminateLEQueues();
385 * This function will initalize the Receiver and Sender queues for
386 * GattServer. This function will in turn call the functions
387 * CAInitBleServerReceiverQueue() and CAInitBleServerSenderQueue() to
388 * initialize the queues.
390 * @return ::CA_STATUS_OK or Appropriate error code.
391 * @retval ::CA_STATUS_OK Successful.
392 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
393 * @retval ::CA_STATUS_FAILED Operation failed.
395 static CAResult_t CAInitLEServerQueues();
398 * This function will initalize the Receiver and Sender queues for
399 * GattClient. This function will inturn call the functions
400 * CAInitBleClientReceiverQueue() and CAInitBleClientSenderQueue() to
401 * initialize the queues.
403 * @return ::CA_STATUS_OK or Appropriate error code.
404 * @retval ::CA_STATUS_OK Successful.
405 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
406 * @retval ::CA_STATUS_FAILED Operation failed.
409 static CAResult_t CAInitLEClientQueues();
412 * This function will initalize the Receiver queue for
413 * GattServer. This will initialize the queue to process the function
414 * CABLEServerSendDataThread() when ever the task is added to this
417 * @return ::CA_STATUS_OK or Appropriate error code.
418 * @retval ::CA_STATUS_OK Successful.
419 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
420 * @retval ::CA_STATUS_FAILED Operation failed.
422 static CAResult_t CAInitLEServerSenderQueue();
425 * This function will initalize the Receiver queue for
426 * GattClient. This will initialize the queue to process the function
427 * CABLEClientSendDataThread() when ever the task is added to this
430 * @return ::CA_STATUS_OK or Appropriate error code.
431 * @retval ::CA_STATUS_OK Successful.
432 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
433 * @retval ::CA_STATUS_FAILED Operation failed.
435 static CAResult_t CAInitLEClientSenderQueue();
438 * This function will initialize the Receiver queue for
439 * GattServer. This will initialize the queue to process the function
440 * CALEServerDataReceiverHandler() when ever the task is added to this
443 * @return ::CA_STATUS_OK or Appropriate error code
444 * @retval ::CA_STATUS_OK Successful
445 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments
446 * @retval ::CA_STATUS_FAILED Operation failed
449 static CAResult_t CAInitLEServerReceiverQueue();
452 * This function will initialize the Receiver queue for
453 * GattClient. This will initialize the queue to process the function
454 * CALEClientDataReceiverHandler() when ever the task is added to this
457 * @return ::CA_STATUS_OK or Appropriate error code
458 * @retval ::CA_STATUS_OK Successful
459 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments
460 * @retval ::CA_STATUS_FAILED Operation failed
463 static CAResult_t CAInitLEClientReceiverQueue();
466 * This function will create the Data required to send it in the
469 * @param[in] remoteEndpoint Remote endpoint information of the
471 * @param[in] data Data to be transmitted from LE.
472 * @param[in] dataLength Length of the Data being transmitted.
474 * @return ::CA_STATUS_OK or Appropriate error code.
475 * @retval ::CA_STATUS_OK Successful.
476 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
477 * @retval ::CA_STATUS_FAILED Operation failed.
479 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
482 u_arraylist_t *senderInfo);
485 * Used to free the BLE information stored in the sender/receiver
488 * @param[in] bleData Information for a particular data segment.
490 static void CAFreeLEData(CALEData_t *bleData);
495 static void CALEDataDestroyer(void *data, uint32_t size);
497 #ifndef SINGLE_THREAD
499 * remove request or response data of send queue.
501 * @param[in] queueHandle queue to process the outgoing packets.
502 * @param[in] mutex mutex related to sender for client / server.
503 * @param[in] address target address to remove data in queue.
505 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle,
506 const char* address);
509 * remove all received data of data list from receive queue.
511 * @param[in] dataInfoList received data list to remove for client / server.
512 * @param[in] address target address to remove data in queue.
514 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList,
515 const char* address);
518 * get received data info and positioned index from the received data list
519 * for client / server which is matched same leAddress and port.
520 * CABLESenderInfo_t is reference counted structure, you must call
521 * CALEFreeSenderInfo on senderInfo to release reference.
523 * @param[in] leAddress target address to get serderInfo.
524 * @param[in] port target port to get senderInfo.
525 * @param[in] senderInfoList received data list for client / server.
526 * @param[out] senderInfo Pointer to contain matched(leAddress and port)
527 * received data info.
528 * @param[out] senderIndex Pointer to contain matched(leAddress and port)
529 * received data info index.
531 static CAResult_t CALEGetSenderInfo(const char *leAddress,
533 u_arraylist_t *senderInfoList,
534 CABLESenderInfo_t **senderInfo,
535 uint32_t *senderIndex);
538 * Add sender info to list.
540 * @param[in] u_arraylist_t Array list to add sender info to.
541 * @param[in] senderInfo Sender info to be added to list.
543 * @return true on success, otherwise false.
545 static bool CALEAddSenderInfoToList(u_arraylist_t *senderInfoList,
546 CABLESenderInfo_t *senderInfo);
549 * Remove desired sender info from list.
551 * @param[in] u_arraylist_t Array list to remove sender info from.
552 * @param[in] senderInfo Sender info to be removed from list.
555 static void CALERemoveSenderInfoFromList(u_arraylist_t *senderInfoList,
556 CABLESenderInfo_t *senderInfo);
559 * Free sender info. CABLESenderInfo_t is reference counted structure
560 * and info will be freed only when reference count reaches 0 or negative.
562 * @param[in] senderInfo Sender info to be freed.
565 static CAResult_t CALEFreeSenderInfo(CABLESenderInfo_t *senderInfo);
568 * get ports related to remote address. It is need because multi application
569 * can have more than 2 senderInfo using same BLE address. So before remove
570 * receive queue data, should get port list from sender Info.
572 * @param[in] leAddress target address to get port in serderInfo.
573 * @param[in] senderInfoList received data list to remove for client / server.
574 * @param[out] portList target port list related to leAddress.
576 static CAResult_t CALEGetPortsFromSenderInfo(const char *leAddress,
577 u_arraylist_t *senderInfoList,
578 u_arraylist_t *portList);
581 static CAResult_t CAInitLEServerQueues()
583 CAResult_t result = CAInitLEServerSenderQueue();
584 if (CA_STATUS_OK != result)
586 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerSenderQueue failed");
588 return CA_STATUS_FAILED;
591 g_bleServerSenderInfo = u_arraylist_create();
592 if (!g_bleServerSenderInfo)
594 OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
595 return CA_MEMORY_ALLOC_FAILED;
598 result = CAInitLEServerReceiverQueue();
599 if (CA_STATUS_OK != result)
601 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerReceiverQueue failed");
602 u_arraylist_free(&g_bleServerSenderInfo);
603 return CA_STATUS_FAILED;
606 g_dataBleServerReceiverHandlerState = true;
610 static CAResult_t CAInitLEClientQueues()
612 CAResult_t result = CAInitLEClientSenderQueue();
613 if (CA_STATUS_OK != result)
615 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientSenderQueue failed");
616 return CA_STATUS_FAILED;
619 g_bleClientSenderInfo = u_arraylist_create();
620 if (!g_bleClientSenderInfo)
622 OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
623 return CA_MEMORY_ALLOC_FAILED;
626 result = CAInitLEClientReceiverQueue();
627 if (CA_STATUS_OK != result)
629 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientReceiverQueue failed");
630 u_arraylist_free(&g_bleClientSenderInfo);
631 return CA_STATUS_FAILED;
634 g_dataBleClientReceiverHandlerState = true;
639 static CAResult_t CAInitLEServerReceiverQueue()
641 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
642 // Check if the message queue is already initialized
643 if (g_bleServerReceiverQueue)
645 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
649 // Create recv message queue
650 g_bleServerReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
651 if (!g_bleServerReceiverQueue)
653 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
654 return CA_MEMORY_ALLOC_FAILED;
657 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerReceiverQueue,
658 g_bleAdapterThreadPool,
659 CALEServerDataReceiverHandler,
662 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize server receiver queue thread");
663 OICFree(g_bleServerReceiverQueue);
664 g_bleServerReceiverQueue = NULL;
665 return CA_STATUS_FAILED;
668 if (CA_STATUS_OK != CAQueueingThreadStart(g_bleServerReceiverQueue))
670 OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
671 OICFree(g_bleServerReceiverQueue);
672 g_bleServerReceiverQueue = NULL;
673 return CA_STATUS_FAILED;
679 static CAResult_t CAInitLEClientReceiverQueue()
681 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
682 // Check if the message queue is already initialized
683 if (g_bleClientReceiverQueue)
685 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
689 // Create recv message queue
690 g_bleClientReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
691 if (!g_bleClientReceiverQueue)
693 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
694 return CA_MEMORY_ALLOC_FAILED;
697 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientReceiverQueue,
698 g_bleAdapterThreadPool,
699 CALEClientDataReceiverHandler,
702 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize client receiver queue thread");
703 OICFree(g_bleClientReceiverQueue);
704 g_bleClientReceiverQueue = NULL;
705 return CA_STATUS_FAILED;
708 if (CA_STATUS_OK != CAQueueingThreadStart(g_bleClientReceiverQueue))
710 OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
711 OICFree(g_bleClientReceiverQueue);
712 g_bleClientReceiverQueue = NULL;
713 return CA_STATUS_FAILED;
719 static CAResult_t CAInitLEServerSenderQueue()
721 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
722 // Check if the message queue is already initialized
723 if (g_bleServerSendQueueHandle)
725 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Queue is already initialized!");
729 // Create send message queue
730 g_bleServerSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
731 if (!g_bleServerSendQueueHandle)
733 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
734 return CA_MEMORY_ALLOC_FAILED;
737 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerSendQueueHandle,
738 g_bleAdapterThreadPool,
739 CALEServerSendDataThread,
742 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
743 OICFree(g_bleServerSendQueueHandle);
744 g_bleServerSendQueueHandle = NULL;
745 return CA_STATUS_FAILED;
751 static void CALEClearSenderInfoImpl(u_arraylist_t **list)
753 oc_mutex_lock(g_senderInfoMutex);
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);
767 oc_mutex_unlock(g_senderInfoMutex);
770 static void CALEClearSenderInfo()
772 CALEClearSenderInfoImpl(&g_bleServerSenderInfo);
773 CALEClearSenderInfoImpl(&g_bleClientSenderInfo);
776 static CAResult_t CAInitLEClientSenderQueue()
778 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
780 if (g_bleClientSendQueueHandle)
782 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
786 // Create send message queue
787 g_bleClientSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
788 if (!g_bleClientSendQueueHandle)
790 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
791 return CA_MEMORY_ALLOC_FAILED;
794 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientSendQueueHandle,
795 g_bleAdapterThreadPool,
796 CALEClientSendDataThread, CALEDataDestroyer))
798 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
799 OICFree(g_bleClientSendQueueHandle);
800 g_bleClientSendQueueHandle = NULL;
801 return CA_STATUS_FAILED;
806 static void CAStopLEQueues()
808 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
810 oc_mutex_lock(g_bleServerReceiveDataMutex);
811 if (NULL != g_bleServerReceiverQueue)
813 CAQueueingThreadStop(g_bleServerReceiverQueue);
815 oc_mutex_unlock(g_bleServerReceiveDataMutex);
817 oc_mutex_lock(g_bleClientReceiveDataMutex);
818 if (NULL != g_bleClientReceiverQueue)
820 CAQueueingThreadStop(g_bleClientReceiverQueue);
822 oc_mutex_unlock(g_bleClientReceiveDataMutex);
824 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
827 static void CATerminateLEQueues()
829 CAQueueingThreadDestroy(g_bleClientSendQueueHandle);
830 OICFree(g_bleClientSendQueueHandle);
831 g_bleClientSendQueueHandle = NULL;
833 CAQueueingThreadDestroy(g_bleServerSendQueueHandle);
834 OICFree(g_bleServerSendQueueHandle);
835 g_bleServerSendQueueHandle = NULL;
837 CAQueueingThreadDestroy(g_bleServerReceiverQueue);
838 OICFree(g_bleServerReceiverQueue);
839 g_bleServerReceiverQueue = NULL;
841 CAQueueingThreadDestroy(g_bleClientReceiverQueue);
842 OICFree(g_bleClientReceiverQueue);
843 g_bleClientReceiverQueue = NULL;
845 CALEClearSenderInfo();
848 static CAResult_t CALEGetSenderInfo(const char *leAddress,
850 u_arraylist_t *senderInfoList,
851 CABLESenderInfo_t **senderInfo,
852 uint32_t *senderIndex)
854 VERIFY_NON_NULL_RET(leAddress,
856 "NULL BLE address argument",
857 CA_STATUS_INVALID_PARAM);
858 VERIFY_NON_NULL_RET(senderIndex,
860 "NULL index argument",
861 CA_STATUS_INVALID_PARAM);
863 oc_mutex_lock(g_senderInfoMutex);
864 const uint32_t listLength = u_arraylist_length(senderInfoList);
865 const uint32_t addrLength = strlen(leAddress);
866 for (uint32_t index = 0; index < listLength; index++)
868 CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
869 if (!info || !(info->remoteEndpoint))
874 if (!strncmp(info->remoteEndpoint->addr, leAddress, addrLength)
875 && info->remoteEndpoint->port == port)
877 *senderIndex = index;
881 (*senderInfo)->refCount++;
883 oc_mutex_unlock(g_senderInfoMutex);
888 oc_mutex_unlock(g_senderInfoMutex);
889 return CA_STATUS_FAILED;
892 static bool CALEAddSenderInfoToList(u_arraylist_t *senderInfoList, CABLESenderInfo_t *senderInfo)
894 oc_mutex_lock(g_senderInfoMutex);
895 senderInfo->refCount++;
896 if (!u_arraylist_add(senderInfoList,(void *)senderInfo))
898 senderInfo->refCount--;
899 oc_mutex_unlock(g_senderInfoMutex);
902 oc_mutex_unlock(g_senderInfoMutex);
906 static void CALERemoveSenderInfoFromList(u_arraylist_t *senderInfoList, CABLESenderInfo_t *senderInfo)
908 oc_mutex_lock(g_senderInfoMutex);
910 bool elemFound = u_arraylist_get_index(senderInfoList, (const void*)senderInfo, &idx);
913 void *info = u_arraylist_remove(senderInfoList, idx);
916 senderInfo->refCount--;
919 oc_mutex_unlock(g_senderInfoMutex);
922 static CAResult_t CALEFreeSenderInfo(CABLESenderInfo_t *senderInfo)
924 VERIFY_NON_NULL_RET(senderInfo,
926 "NULL senderInfo to remove argument",
927 CA_STATUS_INVALID_PARAM);
929 oc_mutex_lock(g_senderInfoMutex);
930 senderInfo->refCount--;
931 if(senderInfo->refCount <= 0)
933 OICFree(senderInfo->defragData);
934 OICFree(senderInfo->remoteEndpoint);
937 oc_mutex_unlock(g_senderInfoMutex);
941 static void CALEDataReceiverHandler(void *threadData, CABLEAdapter_t receiverType)
943 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
945 oc_mutex bleReceiveDataMutex = NULL;
946 bool dataBleReceiverHandlerState = false;
948 switch (receiverType)
951 bleReceiveDataMutex = g_bleClientReceiveDataMutex;
952 dataBleReceiverHandlerState = g_dataBleClientReceiverHandlerState;
955 bleReceiveDataMutex = g_bleServerReceiveDataMutex;
956 dataBleReceiverHandlerState = g_dataBleServerReceiverHandlerState;
959 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Unsupported receiver type : %d", receiverType);
963 oc_mutex_lock(bleReceiveDataMutex);
965 if (dataBleReceiverHandlerState)
967 CALEData_t *bleData = (CALEData_t *) threadData;
970 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bleData!");
971 oc_mutex_unlock(bleReceiveDataMutex);
975 if (!(bleData->senderInfo))
977 OIC_LOG(ERROR, CALEADAPTER_TAG, "sender info is not available");
978 oc_mutex_unlock(bleReceiveDataMutex);
982 if (!(bleData->remoteEndpoint))
984 OIC_LOG(ERROR, CALEADAPTER_TAG, "RemoteEndPoint NULL!!");
985 oc_mutex_unlock(bleReceiveDataMutex);
989 CABLESenderInfo_t *senderInfo = NULL;
990 uint32_t senderIndex = 0;
993 CABLEPacketStart_t startFlag = CA_BLE_PACKET_NOT_START;
994 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
995 uint16_t sourcePort = 0;
996 uint16_t destPort = 0;
998 CAParseHeader(bleData->data, &startFlag, &sourcePort, &secureFlag, &destPort);
999 OIC_LOG_V(INFO, CALEADAPTER_TAG,
1000 "header info: startFlag[%X] sourcePort[%d] secureFlag[%X] destPort[%d]",
1001 startFlag, sourcePort, secureFlag, destPort);
1003 if (destPort != g_localBLESourcePort && destPort != CA_BLE_MULTICAST_PORT)
1005 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1006 "this packet is not valid for this app(port mismatch[mine:%d, packet:%d])",
1007 g_localBLESourcePort, destPort);
1008 oc_mutex_unlock(bleReceiveDataMutex);
1012 bleData->remoteEndpoint->port = sourcePort;
1014 if (CA_STATUS_OK != CALEGetSenderInfo(bleData->remoteEndpoint->addr,
1015 bleData->remoteEndpoint->port,
1016 bleData->senderInfo,
1017 &senderInfo, &senderIndex))
1019 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This is a new client [%s:%X]",
1020 bleData->remoteEndpoint->addr, bleData->remoteEndpoint->port);
1026 OIC_LOG(ERROR, CALEADAPTER_TAG,
1027 "This packet is start packet but exist senderInfo. Remove senderInfo");
1028 CALERemoveSenderInfoFromList(bleData->senderInfo, senderInfo);
1029 CALEFreeSenderInfo(senderInfo);
1037 uint32_t totalLength = 0;
1040 CAParseHeaderPayloadLength(bleData->data, CA_BLE_LENGTH_HEADER_SIZE, &totalLength);
1044 OIC_LOG(ERROR, CALEADAPTER_TAG, "This packet is wrong packet! ignore.");
1045 oc_mutex_unlock(bleReceiveDataMutex);
1049 CABLESenderInfo_t *newSender = OICCalloc(1, sizeof(CABLESenderInfo_t));
1052 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
1053 oc_mutex_unlock(bleReceiveDataMutex);
1057 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
1059 newSender->totalDataLen = totalLength;
1060 if (!(newSender->totalDataLen))
1062 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
1063 CALEFreeSenderInfo(newSender);
1064 oc_mutex_unlock(bleReceiveDataMutex);
1068 size_t dataOnlyLen =
1069 bleData->dataLen - (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE);
1070 OIC_LOG_V(INFO, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
1071 newSender->totalDataLen);
1072 OIC_LOG_V(INFO, CALEADAPTER_TAG, "data received in the first packet [%zu] bytes",
1075 newSender->defragData = OICCalloc(newSender->totalDataLen + 1,
1076 sizeof(*newSender->defragData));
1078 if (NULL == newSender->defragData)
1080 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
1081 CALEFreeSenderInfo(newSender);
1082 oc_mutex_unlock(bleReceiveDataMutex);
1085 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
1086 #ifdef __WITH_DTLS__
1087 if (CA_BLE_PACKET_SECURE == secureFlag)
1093 const char *remoteAddress = bleData->remoteEndpoint->addr;
1094 newSender->remoteEndpoint = CACreateEndpointObject(flags,
1095 CA_ADAPTER_GATT_BTLE,
1097 bleData->remoteEndpoint->port);
1099 if (NULL == newSender->remoteEndpoint)
1101 OIC_LOG(ERROR, CALEADAPTER_TAG, "remoteEndpoint is NULL!");
1102 CALEFreeSenderInfo(newSender);
1103 oc_mutex_unlock(bleReceiveDataMutex);
1107 if (newSender->recvDataLen + dataOnlyLen > newSender->totalDataLen)
1109 OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
1110 CALEFreeSenderInfo(newSender);
1111 oc_mutex_unlock(bleReceiveDataMutex);
1114 memcpy(newSender->defragData,
1115 bleData->data + (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE),
1117 newSender->recvDataLen += dataOnlyLen;
1119 newSender->refCount = 1;
1121 if (!CALEAddSenderInfoToList(bleData->senderInfo, newSender))
1123 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to add sender info!");
1124 CALEFreeSenderInfo(newSender);
1125 oc_mutex_unlock(bleReceiveDataMutex);
1129 senderInfo = newSender;
1133 size_t dataOnlyLen = bleData->dataLen - CA_BLE_HEADER_SIZE;
1134 if (senderInfo->recvDataLen + dataOnlyLen > senderInfo->totalDataLen)
1136 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1137 "Data Length exceeding error!! Receiving [%zu] total length [%u]",
1138 senderInfo->recvDataLen + dataOnlyLen, senderInfo->totalDataLen);
1139 CALERemoveSenderInfoFromList(bleData->senderInfo, senderInfo);
1140 CALEFreeSenderInfo(senderInfo);
1141 oc_mutex_unlock(bleReceiveDataMutex);
1144 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%zu]",
1146 memcpy(senderInfo->defragData + senderInfo->recvDataLen,
1147 bleData->data + CA_BLE_HEADER_SIZE,
1149 senderInfo->recvDataLen += dataOnlyLen;
1150 OIC_LOG_V(INFO, CALEADAPTER_TAG, "totalDatalength [%d] received Datalen [%d]",
1151 senderInfo->totalDataLen, senderInfo->recvDataLen);
1154 if (senderInfo->totalDataLen == senderInfo->recvDataLen)
1156 if (NULL == g_networkPacketReceivedCallback)
1158 OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
1159 CALERemoveSenderInfoFromList(bleData->senderInfo, senderInfo);
1160 CALEFreeSenderInfo(senderInfo);
1161 oc_mutex_unlock(bleReceiveDataMutex);
1165 OIC_LOG(DEBUG, CALEADAPTER_TAG, "[CALEDataReceiverHandler] Received data up !");
1167 const CASecureEndpoint_t tmp =
1169 .endpoint = *senderInfo->remoteEndpoint
1172 OIC_LOG_V(INFO, CALEADAPTER_TAG, "endpoint flags : %d", tmp.endpoint.flags);
1173 #ifdef __WITH_DTLS__
1174 if (CA_SECURE & tmp.endpoint.flags)
1176 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Secure data received");
1177 switch (receiverType)
1179 case ADAPTER_CLIENT:
1180 g_dataType = CA_REQUEST_DATA;
1182 case ADAPTER_SERVER:
1183 g_dataType = CA_RESPONSE_DATA;
1186 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Unsupported rcvr type:%d",receiverType);
1187 CALERemoveSenderInfoFromList(bleData->senderInfo, senderInfo);
1188 senderInfo->remoteEndpoint = NULL;
1189 senderInfo->defragData = NULL;
1190 CALEFreeSenderInfo(senderInfo);
1191 oc_mutex_unlock(bleReceiveDataMutex);
1195 if (CA_STATUS_FAILED == CAdecryptSsl(&tmp,
1196 senderInfo->defragData,
1197 senderInfo->recvDataLen))
1199 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAdecryptSsl failed");
1203 OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAdecryptSsl successed");
1205 OICFree(senderInfo->defragData);
1210 OIC_LOG(INFO, CALEADAPTER_TAG, "Non-Secure data received");
1211 g_networkPacketReceivedCallback(&tmp,
1212 senderInfo->defragData,
1213 senderInfo->recvDataLen);
1214 #ifdef __WITH_DTLS__
1218 CALERemoveSenderInfoFromList(bleData->senderInfo, senderInfo);
1219 senderInfo->remoteEndpoint = NULL;
1220 senderInfo->defragData = NULL;
1221 CALEFreeSenderInfo(senderInfo);
1222 oc_mutex_unlock(bleReceiveDataMutex);
1225 CALEFreeSenderInfo(senderInfo);
1227 oc_mutex_unlock(bleReceiveDataMutex);
1231 static void CALEServerDataReceiverHandler(void *threadData)
1233 CALEDataReceiverHandler(threadData, ADAPTER_SERVER);
1236 static void CALEClientDataReceiverHandler(void *threadData)
1238 CALEDataReceiverHandler(threadData, ADAPTER_CLIENT);
1241 static void CALEServerSendDataThread(void *threadData)
1243 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1245 CALEData_t * const bleData = (CALEData_t *) threadData;
1248 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid bledata!");
1252 if (!bleData->remoteEndpoint)
1254 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid endpoint of bledata!");
1258 #if defined(__TIZEN__) || defined(__ANDROID__)
1260 g_mtuSize = CALEServerGetMtuSize(bleData->remoteEndpoint->addr);
1262 OIC_LOG_V(INFO, CALEADAPTER_TAG, "MTU size [%d]", g_mtuSize);
1264 uint32_t midPacketCount = 0;
1265 size_t remainingLen = 0;
1266 size_t totalLength = 0;
1267 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1269 CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
1275 if (CA_STATUS_OK != result)
1277 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1278 "CAGenerateVariableForFragmentation failed, result [%d]", result);
1281 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1286 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1287 "Packet info: data size[%d] midPacketCount[%u] remainingLen[%zu] totalLength[%zu]",
1288 bleData->dataLen, midPacketCount, remainingLen, totalLength);
1292 "Server total Data length with header is [%zu]",
1295 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1296 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1298 if (NULL != bleData->remoteEndpoint) //Unicast Data
1300 secureFlag = (bleData->remoteEndpoint->flags & CA_SECURE) ?
1301 CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
1303 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This Packet is secure? %d", secureFlag);
1304 result = CAGenerateHeader(dataHeader,
1305 CA_BLE_PACKET_START,
1306 g_localBLESourcePort,
1308 bleData->remoteEndpoint->port);
1310 else //Multicast Data
1312 result = CAGenerateHeader(dataHeader,
1313 CA_BLE_PACKET_START,
1314 g_localBLESourcePort,
1316 CA_BLE_MULTICAST_PORT);
1318 OIC_LOG_V(INFO, CALEADAPTER_TAG, "header info: secureFlag[%X]", secureFlag);
1320 if (CA_STATUS_OK != result)
1322 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1323 "CAGenerateHeader failed, result [%d]", result);
1326 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1331 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1332 result = CAGenerateHeaderPayloadLength(lengthHeader,
1333 CA_BLE_LENGTH_HEADER_SIZE,
1336 if (CA_STATUS_OK != result)
1338 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1339 "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1342 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1347 uint32_t length = 0;
1348 uint32_t dataLen = 0;
1349 if (g_mtuSize > totalLength)
1351 length = (uint32_t)totalLength;
1352 dataLen = bleData->dataLen;
1357 dataLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1360 result = CAMakeFirstDataSegment(dataSegment,
1361 bleData->data, dataLen,
1362 dataHeader, lengthHeader);
1364 if (CA_STATUS_OK != result)
1366 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1367 "Making data segment failed, result [%d]", result);
1370 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1375 const uint32_t iter = midPacketCount;
1378 // Send the first segment with the header.
1379 if (NULL != bleData->remoteEndpoint) // Sending Unicast Data
1381 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Unicast Data");
1383 result = CAUpdateCharacteristicsToGattClient(
1384 bleData->remoteEndpoint->addr, dataSegment, length);
1386 if (CA_STATUS_OK != result)
1390 "Update characteristics failed, result [%d]",
1394 g_errorHandler(bleData->remoteEndpoint,
1404 "Server Sent Unicast First Data - data length [%u]",
1407 result = CAGenerateHeader(dataHeader,
1408 CA_BLE_PACKET_NOT_START,
1409 g_localBLESourcePort,
1411 bleData->remoteEndpoint->port);
1413 if (CA_STATUS_OK != result)
1415 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1416 "CAGenerateHeader failed, result [%d]", result);
1419 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1424 for (index = 0; index < iter; index++)
1426 // Send the remaining header.
1427 result = CAMakeRemainDataSegment(dataSegment,
1428 g_mtuSize - CA_BLE_HEADER_SIZE,
1435 if (CA_STATUS_OK != result)
1437 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1438 "Making data segment failed, result [%d]", result);
1441 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1447 CAUpdateCharacteristicsToGattClient(
1448 bleData->remoteEndpoint->addr,
1452 if (CA_STATUS_OK != result)
1454 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1455 "Update characteristics failed, result [%d]", result);
1458 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1462 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]",
1466 if (remainingLen && (totalLength > g_mtuSize))
1468 // send the last segment of the data (Ex: 22 bytes of 622
1469 // bytes of data when MTU is 200)
1470 result = CAMakeRemainDataSegment(dataSegment,
1478 if (CA_STATUS_OK != result)
1480 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1481 "Making data segment failed, result [%d]", result);
1484 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1489 result = CAUpdateCharacteristicsToGattClient(
1490 bleData->remoteEndpoint->addr,
1492 remainingLen + CA_BLE_HEADER_SIZE);
1494 if (CA_STATUS_OK != result)
1498 "Update characteristics failed, result [%d]",
1502 g_errorHandler(bleData->remoteEndpoint,
1511 "Server Sent Unicast Last Data - data length [%zu]",
1512 remainingLen + CA_BLE_HEADER_SIZE);
1517 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
1518 OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
1521 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1524 static void CALEClientSendDataThread(void *threadData)
1526 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1528 CALEData_t *bleData = (CALEData_t *) threadData;
1531 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid bledata!");
1535 if (!bleData->remoteEndpoint)
1537 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid endpoint of bledata!");
1541 #if defined(__ANDROID__)
1543 if (false == CALEClientIsConnected(bleData->remoteEndpoint->addr))
1545 // triggering to gatt connect and MTU negotiation
1546 CAResult_t res = CALEClientSendNegotiationMessage(
1547 bleData->remoteEndpoint->addr);
1549 if (CA_STATUS_OK != res)
1553 "CALEClientSendNegotiationMessage has failed, result [%d]",
1557 g_errorHandler(bleData->remoteEndpoint,
1566 #if defined(__TIZEN__) || defined(__ANDROID__)
1567 g_mtuSize = CALEClientGetMtuSize(bleData->remoteEndpoint->addr);
1569 OIC_LOG_V(INFO, CALEADAPTER_TAG, "MTU size [%d]", g_mtuSize);
1571 uint32_t midPacketCount = 0;
1572 size_t remainingLen = 0;
1573 size_t totalLength = 0;
1574 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1576 CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
1582 if (CA_STATUS_OK != result)
1584 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1585 "CAGenerateVariableForFragmentation failed, result [%d]", result);
1588 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1593 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1594 "Packet info: data size[%d] midPacketCount[%u] remainingLen[%zu] totalLength[%zu]",
1595 bleData->dataLen, midPacketCount, remainingLen, totalLength);
1597 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1598 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1600 if (NULL != bleData->remoteEndpoint) //Unicast Data
1602 secureFlag = (bleData->remoteEndpoint->flags & CA_SECURE) ?
1603 CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
1605 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This Packet is secure? %d", secureFlag);
1606 result = CAGenerateHeader(dataHeader,
1607 CA_BLE_PACKET_START,
1608 g_localBLESourcePort,
1610 bleData->remoteEndpoint->port);
1612 else //Multicast Data
1614 result = CAGenerateHeader(dataHeader,
1615 CA_BLE_PACKET_START,
1616 g_localBLESourcePort,
1618 CA_BLE_MULTICAST_PORT);
1621 OIC_LOG_V(INFO, CALEADAPTER_TAG, "header info: secureFlag[%X]", secureFlag);
1623 if (CA_STATUS_OK != result)
1625 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1626 "CAGenerateHeader failed, result [%d]", result);
1629 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1634 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1635 result = CAGenerateHeaderPayloadLength(lengthHeader,
1636 CA_BLE_LENGTH_HEADER_SIZE,
1639 if (CA_STATUS_OK != result)
1641 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1642 "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1645 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1650 uint32_t length = 0;
1651 uint32_t dataLen = 0;
1652 if (g_mtuSize > totalLength)
1654 length = (uint32_t)totalLength;
1655 dataLen = bleData->dataLen;
1660 dataLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1663 result = CAMakeFirstDataSegment(dataSegment,
1664 bleData->data, dataLen,
1665 dataHeader, lengthHeader);
1667 if (CA_STATUS_OK != result)
1669 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1670 "Making data segment failed, result [%d]", result);
1673 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1678 const uint32_t iter = midPacketCount;
1680 if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
1682 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
1683 // Send the first segment with the header.
1685 CAUpdateCharacteristicsToGattServer(
1686 bleData->remoteEndpoint->addr,
1692 if (CA_STATUS_OK != result)
1696 "Update characteristics failed, result [%d]",
1700 g_errorHandler(bleData->remoteEndpoint,
1709 "Client Sent Unicast First Data - data length [%u]",
1712 result = CAGenerateHeader(dataHeader,
1713 CA_BLE_PACKET_NOT_START,
1714 g_localBLESourcePort,
1716 bleData->remoteEndpoint->port);
1718 if (CA_STATUS_OK != result)
1720 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1721 "CAGenerateHeader failed, result [%d]", result);
1724 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1729 for (index = 0; index < iter; index++)
1731 result = CAMakeRemainDataSegment(dataSegment,
1732 g_mtuSize - CA_BLE_HEADER_SIZE,
1739 if (CA_STATUS_OK != result)
1741 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1742 "Making data segment failed, result [%d]", result);
1745 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1750 // Send the remaining header.
1751 result = CAUpdateCharacteristicsToGattServer(
1752 bleData->remoteEndpoint->addr,
1757 if (CA_STATUS_OK != result)
1761 "Update characteristics failed, result [%d]",
1765 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1771 "Client Sent Unicast %d Data - data(mtu) length [%hu]",
1776 if (remainingLen && (totalLength > g_mtuSize))
1778 // send the last segment of the data (Ex: 22 bytes of 622
1779 // bytes of data when MTU is 200)
1780 result = CAMakeRemainDataSegment(dataSegment,
1788 if (CA_STATUS_OK != result)
1790 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1791 "Making data segment failed, result [%d]", result);
1794 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1799 result = CAUpdateCharacteristicsToGattServer(
1800 bleData->remoteEndpoint->addr,
1802 remainingLen + CA_BLE_HEADER_SIZE,
1805 if (CA_STATUS_OK != result)
1807 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1811 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1817 "Client Sent Unicast Last Data - data length [%zu]",
1818 remainingLen + CA_BLE_HEADER_SIZE);
1823 //Sending Mulitcast Data
1824 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Client Sending Multicast Data");
1825 OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
1828 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1831 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
1832 const uint8_t *data,
1833 uint32_t dataLength,
1834 u_arraylist_t *senderInfo)
1836 CALEData_t * const bleData = OICMalloc(sizeof(CALEData_t));
1840 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1844 bleData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
1845 bleData->data = OICCalloc(dataLength + 1, 1);
1847 if (NULL == bleData->data)
1849 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1850 CAFreeLEData(bleData);
1854 memcpy(bleData->data, data, dataLength);
1855 bleData->dataLen = dataLength;
1858 bleData->senderInfo = senderInfo;
1864 static void CAFreeLEData(CALEData_t *bleData)
1866 VERIFY_NON_NULL_VOID(bleData, CALEADAPTER_TAG, "Param bleData is NULL");
1868 CAFreeEndpoint(bleData->remoteEndpoint);
1869 OICFree(bleData->data);
1873 static void CALEDataDestroyer(void *data, uint32_t size)
1875 if ((size_t)size < sizeof(CALEData_t *))
1877 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1878 "Destroy data too small %p %d", data, size);
1880 CALEData_t *ledata = (CALEData_t *) data;
1882 CAFreeLEData(ledata);
1886 #ifdef SINGLE_THREAD
1887 static void CALEDataReceiverHandlerSingleThread(const uint8_t *data,
1890 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1892 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1895 CABLEPacketStart_t startFlag = CA_BLE_PACKET_NOT_START;
1896 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1897 uint16_t sourcePort = 0;
1898 uint16_t destPort = 0;
1900 CAParseHeader(data, &startFlag, &sourcePort, &secureFlag, &destPort);
1901 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1902 "header info: startFlag[%X] sourcePort[%d] secureFlag[%X] destPort[%d]",
1903 startFlag, sourcePort, secureFlag, destPort);
1905 if (destPort != g_localBLESourcePort && destPort != CA_BLE_MULTICAST_PORT)
1907 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1908 "this packet is not valid for this app(port mismatch[mine:%d, packet:%d])",
1909 g_localBLESourcePort, destPort);
1915 if (g_singleThreadReceiveData)
1917 OIC_LOG(ERROR, CALEADAPTER_TAG,
1918 "This packet is start packet but exist senderInfo. Remove senderInfo");
1919 OICFree(g_singleThreadReceiveData->defragData);
1920 OICFree(g_singleThreadReceiveData);
1921 g_singleThreadReceiveData = NULL;
1924 uint32_t totalLength = 0;
1925 CAParseHeaderPayloadLength(data, CA_BLE_LENGTH_HEADER_SIZE, &totalLength);
1927 g_singleThreadReceiveData = OICMalloc(sizeof(CABLESenderInfo_t));
1929 if (!g_singleThreadReceiveData)
1931 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
1934 g_singleThreadReceiveData->recvDataLen = 0;
1935 g_singleThreadReceiveData->totalDataLen = 0;
1936 g_singleThreadReceiveData->defragData = NULL;
1937 g_singleThreadReceiveData->remoteEndpoint = NULL;
1939 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
1941 g_singleThreadReceiveData->totalDataLen = totalLength;
1943 if (!(g_singleThreadReceiveData->totalDataLen))
1945 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
1946 OICFree(g_singleThreadReceiveData);
1950 size_t dataOnlyLen = dataLen - (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE);
1951 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
1952 g_singleThreadReceiveData->totalDataLen);
1953 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%u] bytes",
1956 g_singleThreadReceiveData->defragData =
1957 OICCalloc(g_singleThreadReceiveData->totalDataLen + 1,
1958 sizeof(*g_singleThreadReceiveData->defragData));
1960 if (NULL == g_singleThreadReceiveData->defragData)
1962 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
1963 OICFree(g_singleThreadReceiveData);
1967 if (g_singleThreadReceiveData->recvDataLen + dataOnlyLen
1968 > g_singleThreadReceiveData->totalDataLen)
1970 OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
1971 OICFree(g_singleThreadReceiveData->defragData);
1972 OICFree(g_singleThreadReceiveData);
1975 memcpy(g_singleThreadReceiveData->defragData,
1976 data + (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE),
1978 g_singleThreadReceiveData->recvDataLen += dataOnlyLen;
1982 size_t dataOnlyLen = dataLen - CA_BLE_HEADER_SIZE;
1983 if (g_singleThreadReceiveData->recvDataLen + dataOnlyLen
1984 > g_singleThreadReceiveData->totalDataLen)
1986 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1987 "Data Length exceeding error!! Receiving [%d] total length [%d]",
1988 g_singleThreadReceiveData->recvDataLen + dataOnlyLen,
1989 g_singleThreadReceiveData->totalDataLen);
1990 OICFree(g_singleThreadReceiveData->defragData);
1991 OICFree(g_singleThreadReceiveData);
1994 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]",
1996 memcpy(g_singleThreadReceiveData->defragData + g_singleThreadReceiveData->recvDataLen,
1997 data + CA_BLE_HEADER_SIZE,
1999 g_singleThreadReceiveData->recvDataLen += dataOnlyLen;
2000 OIC_LOG_V(INFO, CALEADAPTER_TAG, "totalDatalength [%d] received Datalen [%d]",
2001 g_singleThreadReceiveData->totalDataLen, g_singleThreadReceiveData->recvDataLen);
2003 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2006 static CAResult_t CALEServerSendDataSingleThread(const uint8_t *data,
2009 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__););
2011 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
2013 uint32_t midPacketCount = 0;
2014 size_t remainingLen = 0;
2015 size_t totalLength = 0;
2016 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
2018 CAResult_t result = CAGenerateVariableForFragmentation(dataLen,
2024 if (CA_STATUS_OK != result)
2026 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2027 "CAGenerateVariableForFragmentation failed, result [%d]", result);
2031 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2032 "Packet info: data size[%d] midPacketCount[%d] remainingLen[%d] totalLength[%d]",
2033 dataLen, midPacketCount, remainingLen, totalLength);
2037 "Server total Data length with header is [%u]",
2040 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
2041 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
2043 result = CAGenerateHeader(dataHeader,
2044 CA_BLE_PACKET_START,
2045 g_localBLESourcePort,
2046 CA_BLE_PACKET_NON_SECURE,
2047 CA_BLE_MULTICAST_PORT);
2049 if (CA_STATUS_OK != result)
2051 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2052 "CAGenerateHeader failed, result [%d]", result);
2056 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
2057 result = CAGenerateHeaderPayloadLength(lengthHeader,
2058 CA_BLE_LENGTH_HEADER_SIZE,
2061 if (CA_STATUS_OK != result)
2063 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2064 "CAGenerateHeaderPayloadLength failed, result [%d]", result);
2068 uint32_t length = 0;
2069 uint32_t dataOnlyLen = 0;
2070 if (g_mtuSize > totalLength)
2072 length = totalLength;
2073 dataOnlyLen = dataLen;
2078 dataOnlyLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
2081 result = CAMakeFirstDataSegment(dataSegment,
2083 dataHeader, lengthHeader);
2085 if (CA_STATUS_OK != result)
2087 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2088 "Making data segment failed, result [%d]", result);
2092 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
2093 result = CAUpdateCharacteristicsToAllGattClients(dataSegment, length);
2094 if (CA_STATUS_OK != result)
2096 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
2103 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
2105 result = CAGenerateHeader(dataHeader,
2106 CA_BLE_PACKET_NOT_START,
2107 g_localBLESourcePort,
2108 CA_BLE_PACKET_NON_SECURE,
2109 CA_BLE_MULTICAST_PORT);
2111 if (CA_STATUS_OK != result)
2113 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2114 "CAGenerateHeader failed, result [%d]", result);
2118 const uint32_t dataLimit = midPacketCount;
2119 for (uint32_t iter = 0; iter < dataLimit; iter++)
2121 result = CAMakeRemainDataSegment(dataSegment,
2122 g_mtuSize - CA_BLE_HEADER_SIZE,
2129 if (CA_STATUS_OK != result)
2131 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2132 "Making data segment failed, result [%d]", result);
2136 result = CAUpdateCharacteristicsToAllGattClients(
2140 if (CA_STATUS_OK != result)
2142 OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2149 if (remainingLen && (totalLength > g_mtuSize))
2151 // send the last segment of the data
2152 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
2154 result = CAMakeRemainDataSegment(dataSegment,
2162 if (CA_STATUS_OK != result)
2164 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2165 "Making data segment failed, result [%d]", result);
2169 result = CAUpdateCharacteristicsToAllGattClients(
2171 remainingLen + CA_BLE_HEADER_SIZE);
2173 if (CA_STATUS_OK != result)
2175 OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2185 static CAResult_t CAInitLEAdapterMutex()
2187 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2189 if (NULL == g_bleIsServerMutex)
2191 g_bleIsServerMutex = oc_mutex_new();
2192 if (NULL == g_bleIsServerMutex)
2194 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2195 return CA_STATUS_FAILED;
2199 if (NULL == g_bleLocalAddressMutex)
2201 g_bleLocalAddressMutex = oc_mutex_new();
2202 if (NULL == g_bleLocalAddressMutex)
2204 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2205 CATerminateLEAdapterMutex();
2206 return CA_STATUS_FAILED;
2212 if (NULL == g_bleServerReceiveDataMutex)
2214 g_bleServerReceiveDataMutex = oc_mutex_new();
2215 if (NULL == g_bleServerReceiveDataMutex)
2217 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2218 return CA_STATUS_FAILED;
2222 if (NULL == g_bleClientReceiveDataMutex)
2224 g_bleClientReceiveDataMutex = oc_mutex_new();
2225 if (NULL == g_bleClientReceiveDataMutex)
2227 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2228 return CA_STATUS_FAILED;
2232 if (NULL == g_senderInfoMutex)
2234 g_senderInfoMutex = oc_mutex_new();
2235 if (NULL == g_senderInfoMutex)
2237 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2238 return CA_STATUS_FAILED;
2242 return CA_STATUS_OK;
2245 static void CATerminateLEAdapterMutex()
2247 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2249 oc_mutex_free(g_bleIsServerMutex);
2250 g_bleIsServerMutex = NULL;
2253 oc_mutex_free(g_bleLocalAddressMutex);
2254 g_bleLocalAddressMutex = NULL;
2256 oc_mutex_free(g_bleServerReceiveDataMutex);
2257 g_bleServerReceiveDataMutex = NULL;
2259 oc_mutex_free(g_bleClientReceiveDataMutex);
2260 g_bleClientReceiveDataMutex = NULL;
2262 oc_mutex_free(g_senderInfoMutex);
2263 g_senderInfoMutex = NULL;
2267 * Starting LE connectivity adapters.
2269 * As its peer to peer it does not require to start any servers.
2271 * @return ::CA_STATUS_OK or Appropriate error code.
2273 static CAResult_t CAStartLE();
2276 * Start listening server for receiving multicast search requests.
2278 * Transport Specific Behavior:
2279 * LE Starts GATT Server with prefixed UUID and Characteristics
2280 * per OIC Specification.
2281 * @return ::CA_STATUS_OK or Appropriate error code.
2283 static CAResult_t CAStartLEListeningServer();
2286 * Stops listening server from receiving multicast search requests.
2288 * Transport Specific Behavior:
2289 * LE Starts GATT Server with prefixed UUID and Characteristics
2290 * per OIC Specification.
2291 * @return ::CA_STATUS_OK or Appropriate error code.
2293 static CAResult_t CAStopLEListeningServer();
2296 * Sarting discovery of servers for receiving multicast
2299 * Transport Specific Behavior:
2300 * LE Starts GATT Server with prefixed UUID and Characteristics
2301 * per OIC Specification.
2303 * @return ::CA_STATUS_OK or Appropriate error code
2305 static CAResult_t CAStartLEDiscoveryServer();
2308 * Send data to the endpoint using the adapter connectivity.
2310 * @param[in] endpoint Remote Endpoint information (like MAC address,
2311 * reference URI and connectivity type) to which
2312 * the unicast data has to be sent.
2313 * @param[in] data Data which required to be sent.
2314 * @param[in] dataLen Size of data to be sent.
2316 * @note dataLen must be > 0.
2318 * @return The number of bytes sent on the network, or -1 on error.
2320 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2323 CADataType_t dataType);
2326 * Send multicast data to the endpoint using the LE connectivity.
2328 * @param[in] endpoint Remote Endpoint information to which the
2329 * multicast data has to be sent.
2330 * @param[in] data Data which required to be sent.
2331 * @param[in] dataLen Size of data to be sent.
2333 * @note dataLen must be > 0.
2335 * @return The number of bytes sent on the network, or -1 on error.
2337 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
2340 CADataType_t dataType);
2343 * Get LE Connectivity network information.
2345 * @param[out] info Local connectivity information structures.
2346 * @param[out] size Number of local connectivity structures.
2348 * @return ::CA_STATUS_OK or Appropriate error code.
2350 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info,
2354 * Read Synchronous API callback.
2356 * @return ::CA_STATUS_OK or Appropriate error code.
2358 static CAResult_t CAReadLEData();
2361 * Stopping the adapters and close socket connections.
2363 * LE Stops all GATT servers and GATT Clients.
2365 * @return ::CA_STATUS_OK or Appropriate error code.
2367 static CAResult_t CAStopLE();
2370 * Terminate the LE connectivity adapter.
2372 * Configuration information will be deleted from further use.
2374 static void CATerminateLE();
2377 * This function will receive the data from the GattServer and add the
2378 * data to the Server receiver queue.
2380 * @param[in] remoteAddress Remote address of the device from where
2382 * @param[in] data Actual data received from the remote
2384 * @param[in] dataLength Length of the data received from the
2386 * @param[in] sentLength Length of the data sent from the remote
2389 * @return ::CA_STATUS_OK or Appropriate error code.
2390 * @retval ::CA_STATUS_OK Successful.
2391 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2392 * @retval ::CA_STATUS_FAILED Operation failed.
2395 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
2396 const uint8_t *data,
2397 uint32_t dataLength,
2398 uint32_t *sentLength);
2401 * This function will receive the data from the GattClient and add the
2402 * data into the Client receiver queue.
2404 * @param[in] remoteAddress Remote address of the device from where
2406 * @param[in] data Actual data recevied from the remote
2408 * @param[in] dataLength Length of the data received from the
2410 * @param[in] sentLength Length of the data sent from the remote
2413 * @return ::CA_STATUS_OK or Appropriate error code.
2414 * @retval ::CA_STATUS_OK Successful.
2415 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2416 * @retval ::CA_STATUS_FAILED Operation failed.
2418 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
2419 const uint8_t *data,
2420 uint32_t dataLength,
2421 uint32_t *sentLength);
2424 * Set the NetworkPacket received callback to CA layer from adapter
2427 * @param[in] callback Callback handle sent from the upper layer.
2429 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
2432 * Push the data from CA layer to the Sender processor queue.
2434 * @param[in] remoteEndpoint Remote endpoint information of the
2436 * @param[in] data Data to be transmitted from LE.
2437 * @param[in] dataLen Length of the Data being transmitted.
2439 * @return ::CA_STATUS_OK or Appropriate error code.
2440 * @retval ::CA_STATUS_OK Successful.
2441 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2442 * @retval ::CA_STATUS_FAILED Operation failed.
2444 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
2445 const uint8_t *data,
2449 * Push the data from CA layer to the Sender processor queue.
2451 * @param[in] remoteEndpoint Remote endpoint information of the
2453 * @param[in] data Data to be transmitted from LE.
2454 * @param[in] dataLen Length of the Data being transmitted.
2456 * @return ::CA_STATUS_OK or Appropriate error code.
2457 * @retval ::CA_STATUS_OK Successful.
2458 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2459 * @retval ::CA_STATUS_FAILED Operation failed.
2461 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
2462 const uint8_t *data,
2465 static CAResult_t CALEAdapterGattServerStart()
2467 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2468 CAResult_t result = CA_STATUS_FAILED;
2470 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2472 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2473 caglobals.bleFlags);
2474 return CA_STATUS_OK;
2477 #ifndef DISABLE_BLE_SERVER
2478 OIC_LOG_V(INFO, CALEADAPTER_TAG, "Starting LE GATT Server");
2479 result = CAStartLEGattServer();
2482 #ifndef SINGLE_THREAD
2484 Don't start the server side sending queue thread until the
2485 server itself has actually started.
2487 if (CA_STATUS_OK == result)
2489 result = CAQueueingThreadStart(g_bleServerSendQueueHandle);
2490 if (CA_STATUS_OK != result)
2494 "Unable to start server queuing thread (%d)",
2503 static CAResult_t CALEAdapterGattServerStop()
2505 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2507 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2509 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2510 caglobals.bleFlags);
2511 return CA_STATUS_OK;
2514 #ifndef SINGLE_THREAD
2516 CAResult_t res = CAQueueingThreadStop(g_bleServerSendQueueHandle);
2517 if (CA_STATUS_OK != res)
2519 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAQueueingThreadStop has failed");
2521 res = CAStopLEGattServer();
2522 if (CA_STATUS_OK != res)
2524 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAStopLEGattServer has failed");
2529 return CAStopLEGattServer();
2533 static CAResult_t CALEAdapterGattClientStart()
2535 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2537 CAResult_t result = CAStartLEGattClient();
2539 #ifndef SINGLE_THREAD
2541 Don't start the client side sending queue thread until the
2542 client itself has actually started.
2544 if (CA_STATUS_OK == result)
2546 result = CAQueueingThreadStart(g_bleClientSendQueueHandle);
2547 if (CA_STATUS_OK != result)
2551 "Unable to start client queuing thread");
2559 static CAResult_t CALEAdapterGattClientStop()
2561 #ifndef SINGLE_THREAD
2562 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2563 CAStopLEGattClient();
2565 CAResult_t result = CAQueueingThreadStop(g_bleClientSendQueueHandle);
2569 CAStopLEGattClient();
2571 return CA_STATUS_OK;
2575 #ifdef __WITH_DTLS__
2576 static ssize_t CALESecureSendDataCB(CAEndpoint_t *endpoint, const void *data, size_t dataLen)
2578 VERIFY_NON_NULL(endpoint, CALEADAPTER_TAG, "endpoint is NULL");
2579 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "data is NULL");
2580 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2581 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "encrypted datalen = %zd", dataLen);
2584 CADataType_t dataType = g_dataType;
2587 if (ADAPTER_SERVER == g_adapterType ||
2588 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2590 result = CALEAdapterServerSendData(endpoint, data, dataLen);
2591 if (CA_STATUS_OK != result)
2593 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed" );
2597 g_errorHandler(endpoint, data, dataLen, result);
2601 ret = (ssize_t)dataLen;
2603 else if (ADAPTER_CLIENT == g_adapterType ||
2604 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
2605 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
2607 result = CALEAdapterClientSendData(endpoint, data, dataLen);
2608 if (CA_STATUS_OK != result)
2610 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
2614 g_errorHandler(endpoint, data, dataLen, result);
2618 ret = (ssize_t)dataLen;
2622 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2623 "Can't Send Message adapterType = %d, dataType = %d", g_adapterType, dataType);
2626 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2630 CAResult_t CALESecureReceiveDataCB(const CASecureEndpoint_t *sep, const void *data,
2633 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2635 VERIFY_NON_NULL(sep, CALEADAPTER_TAG, "sep is NULL");
2636 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "data is NULL");
2638 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2639 "Secure Data Receive - decrypted datalen = %zd", dataLen);
2643 OIC_LOG(ERROR, CALEADAPTER_TAG, "incorrect dataLen, derecypt fail !");
2644 return CA_STATUS_INVALID_PARAM;
2647 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2649 CAResult_t res = CA_STATUS_OK;
2650 if (g_networkPacketReceivedCallback)
2652 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2653 "[CALESecureReceiveDataCB] Secure flags = %d, %x",
2654 sep->endpoint.flags, sep->endpoint.flags);
2655 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2656 "[CALESecureReceiveDataCB] Received data up !");
2657 res = g_networkPacketReceivedCallback(sep, data, dataLen);
2658 if (CA_STATUS_OK != res)
2660 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Error parsing CoAP data, res = %d", res);
2667 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
2668 CANetworkPacketReceivedCallback reqRespCallback,
2669 CAAdapterChangeCallback netCallback,
2670 CAConnectionChangeCallback connCallback,
2671 CAErrorHandleCallback errorCallback,
2672 ca_thread_pool_t handle)
2674 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2677 VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null");
2678 VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null");
2679 VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null");
2680 VERIFY_NON_NULL(connCallback, CALEADAPTER_TAG, "ConnectionChange Callback is null");
2682 CAResult_t result = CA_STATUS_OK;
2683 result = CAInitLEAdapterMutex();
2684 if (CA_STATUS_OK != result)
2686 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
2687 return CA_STATUS_FAILED;
2690 result = CAInitializeLENetworkMonitor();
2691 if (CA_STATUS_OK != result)
2693 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
2694 return CA_STATUS_FAILED;
2696 CAInitializeLEAdapter();
2698 result = CAInitializeLEGattClient();
2699 if (CA_STATUS_OK != result)
2701 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattClient() failed");
2702 return CA_STATUS_FAILED;
2705 CASetLEClientThreadPoolHandle(handle);
2707 CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
2708 CASetLEServerThreadPoolHandle(handle);
2709 result = CAInitializeLEGattServer();
2710 if (CA_STATUS_OK != result)
2712 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattServer() failed");
2713 return CA_STATUS_FAILED;
2716 CASetLEAdapterThreadPoolHandle(handle);
2717 CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
2718 CASetLEReqRespAdapterCallback(reqRespCallback);
2720 CASetBLEClientErrorHandleCallback(CALEErrorHandler);
2721 CASetBLEServerErrorHandleCallback(CALEErrorHandler);
2722 CALERegisterNetworkNotifications(netCallback, connCallback);
2724 g_errorHandler = errorCallback;
2726 #ifdef __WITH_DTLS__
2727 if (CA_STATUS_OK != CAinitSslAdapter())
2729 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to init SSL adapter");
2733 CAsetSslAdapterCallbacks(CALESecureReceiveDataCB, CALESecureSendDataCB,
2734 CA_ADAPTER_GATT_BTLE);
2738 static const CAConnectivityHandler_t connHandler =
2740 .startAdapter = CAStartLE,
2741 .stopAdapter = CAStopLE,
2742 .startListenServer = CAStartLEListeningServer,
2743 .stopListenServer = CAStopLEListeningServer,
2744 .startDiscoveryServer = CAStartLEDiscoveryServer,
2745 .sendData = CASendLEUnicastData,
2746 .sendDataToAll = CASendLEMulticastData,
2747 .GetnetInfo = CAGetLEInterfaceInformation,
2748 .readData = CAReadLEData,
2749 .terminate = CATerminateLE,
2750 .cType = CA_ADAPTER_GATT_BTLE
2753 registerCallback(connHandler);
2754 return CA_STATUS_OK;
2757 static CAResult_t CAStartLE()
2759 return CAStartLEAdapter();
2762 static CAResult_t CAStopLE()
2765 #ifndef SINGLE_THREAD
2769 oc_mutex_lock(g_bleIsServerMutex);
2770 switch (g_adapterType)
2772 case ADAPTER_SERVER:
2773 CALEAdapterGattServerStop();
2775 case ADAPTER_CLIENT:
2776 CALEAdapterGattClientStop();
2778 case ADAPTER_BOTH_CLIENT_SERVER:
2779 CALEAdapterGattServerStop();
2780 CALEAdapterGattClientStop();
2785 oc_mutex_unlock(g_bleIsServerMutex);
2786 return CAStopLEAdapter();
2789 static void CATerminateLE()
2791 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2793 CASetLEReqRespServerCallback(NULL);
2794 CASetLEReqRespClientCallback(NULL);
2795 CALERegisterNetworkNotifications(NULL, NULL);
2796 CASetLEReqRespAdapterCallback(NULL);
2797 CATerminateLENetworkMonitor();
2799 oc_mutex_lock(g_bleIsServerMutex);
2800 switch (g_adapterType)
2802 case ADAPTER_SERVER:
2803 CATerminateLEGattServer();
2805 case ADAPTER_CLIENT:
2806 CATerminateLEGattClient();
2808 case ADAPTER_BOTH_CLIENT_SERVER:
2809 CATerminateLEGattServer();
2810 CATerminateLEGattClient();
2815 g_adapterType = ADAPTER_EMPTY;
2816 oc_mutex_unlock(g_bleIsServerMutex);
2818 #ifndef SINGLE_THREAD
2819 CATerminateLEQueues();
2822 #ifdef __WITH_DTLS__
2823 CAsetSslAdapterCallbacks(NULL, NULL, CA_ADAPTER_GATT_BTLE);
2826 CATerminateLEAdapterMutex();
2829 static CAResult_t CAStartLEListeningServer()
2831 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2833 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2835 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2836 caglobals.bleFlags);
2837 return CA_STATUS_OK;
2840 #ifndef ROUTING_GATEWAY
2841 CAResult_t result = CA_STATUS_OK;
2842 #ifndef SINGLE_THREAD
2843 result = CAInitLEServerQueues();
2844 if (CA_STATUS_OK != result)
2846 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
2851 oc_mutex_lock(g_bleIsServerMutex);
2852 switch (g_adapterType)
2854 case ADAPTER_CLIENT:
2855 g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2857 case ADAPTER_BOTH_CLIENT_SERVER:
2860 g_adapterType = ADAPTER_SERVER;
2862 oc_mutex_unlock(g_bleIsServerMutex);
2864 result = CAGetLEAdapterState();
2865 if (CA_STATUS_OK != result)
2867 if (CA_ADAPTER_NOT_ENABLED == result)
2871 "Listen Server will be started once BT Adapter is enabled");
2872 result = CA_STATUS_OK;
2877 result = CALEAdapterGattServerStart();
2880 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2883 // Routing Gateway only supports BLE client mode.
2884 OIC_LOG(ERROR, CALEADAPTER_TAG, "LE server not supported in Routing Gateway");
2885 return CA_NOT_SUPPORTED;
2889 static CAResult_t CAStopLEListeningServer()
2891 OIC_LOG(ERROR, CALEADAPTER_TAG, "Listen server stop not supported.");
2892 return CA_NOT_SUPPORTED;
2895 static CAResult_t CAStartLEDiscoveryServer()
2897 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2898 CAResult_t result = CA_STATUS_OK;
2899 #ifndef SINGLE_THREAD
2900 result = CAInitLEClientQueues();
2901 if (CA_STATUS_OK != result)
2903 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
2908 oc_mutex_lock(g_bleIsServerMutex);
2909 switch (g_adapterType)
2911 case ADAPTER_SERVER:
2912 g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2914 case ADAPTER_BOTH_CLIENT_SERVER:
2917 g_adapterType = ADAPTER_CLIENT;
2919 oc_mutex_unlock(g_bleIsServerMutex);
2921 result = CAGetLEAdapterState();
2922 if (CA_STATUS_OK != result)
2924 if (CA_ADAPTER_NOT_ENABLED == result)
2928 "Discovery Server will be started once BT Adapter is enabled");
2929 result = CA_STATUS_OK;
2934 result = CALEAdapterGattClientStart();
2937 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2941 static CAResult_t CAReadLEData()
2943 #ifdef SINGLE_THREAD
2946 return CA_STATUS_OK;
2949 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2952 CADataType_t dataType)
2954 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2955 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "type(%d)", dataType);
2958 VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
2959 VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2961 CAResult_t result = CA_STATUS_FAILED;
2963 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2964 if (ADAPTER_EMPTY == g_adapterType)
2966 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2969 oc_mutex_lock(g_bleIsServerMutex);
2970 if (ADAPTER_SERVER == g_adapterType ||
2971 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2973 #ifdef __WITH_DTLS__
2974 if (endpoint && endpoint->flags & CA_SECURE)
2976 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2977 "Response Data or server - secured data send(caadapternetdtlsencrypt) call");
2978 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2979 g_dataType = dataType;
2980 oc_mutex_unlock(g_bleIsServerMutex);
2982 result = CAencryptSsl(endpoint, (void *)data, dataLen);
2983 if (CA_STATUS_OK != result)
2985 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
2992 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2993 "server or both - none secured data send(CALEAdapterServerSendData) call");
2994 result = CALEAdapterServerSendData(endpoint, data, dataLen);
2997 result = CALEAdapterServerSendData(endpoint, data, dataLen);
2999 if (CA_STATUS_OK != result)
3001 oc_mutex_unlock(g_bleIsServerMutex);
3002 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed");
3005 g_errorHandler(endpoint, data, dataLen, result);
3011 else if (ADAPTER_CLIENT == g_adapterType ||
3012 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
3013 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
3015 #ifdef __WITH_DTLS__
3016 if (endpoint && endpoint->flags & CA_SECURE)
3018 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3019 "Request Data or client - secured data send(caadapternetdtlsencrypt) call");
3020 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
3021 g_dataType = dataType;
3022 oc_mutex_unlock(g_bleIsServerMutex);
3024 result = CAencryptSsl(endpoint, (void *)data, dataLen);
3025 if (CA_STATUS_OK != result)
3027 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
3034 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3035 "client or both - none secured data send(CALEAdapterClientSendData) call");
3036 result = CALEAdapterClientSendData(endpoint, data, dataLen);
3039 result = CALEAdapterClientSendData(endpoint, data, dataLen);
3041 if (CA_STATUS_OK != result)
3043 oc_mutex_unlock(g_bleIsServerMutex);
3044 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
3048 g_errorHandler(endpoint, data, dataLen, result);
3053 oc_mutex_unlock(g_bleIsServerMutex);
3055 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3059 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
3062 CADataType_t dataType)
3064 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3067 VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
3071 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
3075 CAResult_t result = CA_STATUS_FAILED;
3077 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
3078 if (ADAPTER_EMPTY == g_adapterType)
3080 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
3083 oc_mutex_lock(g_bleIsServerMutex);
3084 if (ADAPTER_SERVER == g_adapterType ||
3085 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
3087 result = CALEAdapterServerSendData(NULL, data, dataLen);
3088 if (CA_STATUS_OK != result)
3090 oc_mutex_unlock(g_bleIsServerMutex);
3092 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data for server failed" );
3096 g_errorHandler(endpoint, data, dataLen, result);
3102 if (ADAPTER_CLIENT == g_adapterType ||
3103 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
3104 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
3106 result = CALEAdapterClientSendData(NULL, data, dataLen);
3107 if (CA_STATUS_OK != result)
3109 oc_mutex_unlock(g_bleIsServerMutex);
3111 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data for client failed" );
3115 g_errorHandler(endpoint, data, dataLen, result);
3120 oc_mutex_unlock(g_bleIsServerMutex);
3122 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3126 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
3128 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3130 VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
3132 char *local_address = NULL;
3134 CAResult_t res = CAGetLEAddress(&local_address);
3135 if (CA_STATUS_OK != res)
3137 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
3141 if (NULL == local_address)
3143 OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
3144 return CA_STATUS_FAILED;
3148 (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
3149 if (NULL == (*info))
3151 OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
3152 OICFree(local_address);
3153 return CA_STATUS_FAILED;
3156 size_t local_address_len = strlen(local_address);
3158 if(local_address_len >= sizeof(g_localBLEAddress) ||
3159 local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
3161 OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
3163 OICFree(local_address);
3164 return CA_STATUS_FAILED;
3167 OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
3168 oc_mutex_lock(g_bleLocalAddressMutex);
3169 OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
3170 oc_mutex_unlock(g_bleLocalAddressMutex);
3172 (*info)->adapter = CA_ADAPTER_GATT_BTLE;
3174 OICFree(local_address);
3176 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3177 return CA_STATUS_OK;
3180 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
3181 CAConnectionChangeCallback connCallback)
3183 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3185 g_networkCallback = netCallback;
3186 g_connectionCallback = connCallback;
3187 CAResult_t res = CA_STATUS_OK;
3190 res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
3191 if (CA_STATUS_OK != res)
3193 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
3198 res = CAUnSetLEAdapterStateChangedCb();
3199 if (CA_STATUS_OK != res)
3201 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
3205 if (g_connectionCallback)
3207 res = CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCb);
3208 if (CA_STATUS_OK != res)
3210 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLENWConnectionStateChangedCb failed!");
3215 res = CAUnSetLENWConnectionStateChangedCb();
3216 if (CA_STATUS_OK != res)
3218 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUnSetLENWConnectionStateChangedCb failed!");
3222 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3226 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
3229 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3231 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3234 CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE };
3235 OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), address);
3238 oc_mutex_lock(g_bleIsServerMutex);
3239 switch (g_adapterType)
3241 case ADAPTER_SERVER:
3242 CALEGattServerConnectionStateChanged(isConnected, address);
3244 case ADAPTER_CLIENT:
3245 CALEGattConnectionStateChanged(isConnected, address);
3247 case ADAPTER_BOTH_CLIENT_SERVER:
3248 CALEGattConnectionStateChanged(isConnected, address);
3249 CALEGattServerConnectionStateChanged(isConnected, address);
3254 oc_mutex_unlock(g_bleIsServerMutex);
3259 #ifndef SINGLE_THREAD
3260 if(g_bleClientSenderInfo)
3262 CALERemoveReceiveQueueData(g_bleClientSenderInfo, address);
3265 if(g_bleServerSenderInfo)
3267 CALERemoveReceiveQueueData(g_bleServerSenderInfo, address);
3270 // remove data of send queue.
3271 if (g_bleClientSendQueueHandle)
3273 CALERemoveSendQueueData(g_bleClientSendQueueHandle, address);
3276 if (g_bleServerSendQueueHandle)
3278 CALERemoveSendQueueData(g_bleServerSendQueueHandle, address);
3282 #ifdef __WITH_DTLS__
3283 #if defined(__TIZEN__) && !defined(SINGLE_THREAD)
3284 // CAcloseSslConnection returns CAResult_t instead of void*, but the size is the same and crash shouldn't occur
3286 pthread_attr_t attr;
3287 int initAttrRes = -1;
3288 int pthreadCreateRes = -1;
3289 int detachStatusRes = -1;
3290 int memoryAllocationRes = -1;
3294 initAttrRes = pthread_attr_init(&attr);
3295 if (initAttrRes != 0)
3299 CAEndpoint_t *localEndpointCpyPtr = OICMalloc(sizeof(CAEndpoint_t));
3301 if(NULL == localEndpointCpyPtr)
3303 memoryAllocationRes = -1;
3308 memoryAllocationRes = 0;
3311 (*localEndpointCpyPtr) = localEndpoint;
3312 // this piece of code is reached on the main thread
3313 // CAcloseSslConnection might wait for too long (network + mutexes) and watchdog might kill it
3314 // Asynchronous call protects this function from watchdog
3315 pthreadCreateRes = pthread_create(&ccThread, &attr, (void *(*)(void*))&CAcloseSslConnectionFreeEndpoint, (void*)localEndpointCpyPtr);
3317 if (pthreadCreateRes != 0)
3321 detachStatusRes = pthread_detach(ccThread);
3324 // regardless of CAcloseSslConnection result, the function will continue and g_connectionCallback will be called
3325 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "CAcloseSslConnection pthread_init [%d], mem_alloc [%d] pthread_create [%d], pthread_detach [%d]",
3326 initAttrRes, memoryAllocationRes, pthreadCreateRes, detachStatusRes);
3328 CAcloseSslConnection(&localEndpoint);
3333 if (g_connectionCallback)
3335 g_connectionCallback(&localEndpoint, isConnected);
3338 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3341 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
3343 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3345 if (CA_ADAPTER_ENABLED == adapter_state)
3347 oc_mutex_lock(g_bleIsServerMutex);
3348 switch (g_adapterType)
3350 case ADAPTER_SERVER:
3351 CALEAdapterGattServerStart();
3353 case ADAPTER_CLIENT:
3354 CALEAdapterGattClientStart();
3356 case ADAPTER_BOTH_CLIENT_SERVER:
3357 CALEAdapterGattServerStart();
3358 CALEAdapterGattClientStart();
3363 oc_mutex_unlock(g_bleIsServerMutex);
3367 oc_mutex_lock(g_bleIsServerMutex);
3368 switch (g_adapterType)
3370 case ADAPTER_SERVER:
3371 CALEAdapterGattServerStop();
3373 case ADAPTER_CLIENT:
3374 CALEAdapterGattClientStop();
3376 case ADAPTER_BOTH_CLIENT_SERVER:
3377 CALEAdapterGattServerStop();
3378 CALEAdapterGattClientStop();
3383 oc_mutex_unlock(g_bleIsServerMutex);
3386 if (NULL != g_networkCallback)
3388 g_networkCallback(CA_ADAPTER_GATT_BTLE, adapter_state);
3392 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
3395 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3398 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
3399 const uint8_t *data,
3402 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3403 #ifndef SINGLE_THREAD
3404 VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
3405 "g_bleClientSendQueueHandle is NULL",
3408 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%u]", dataLen);
3410 CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3413 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3414 return CA_MEMORY_ALLOC_FAILED;
3416 // Add message to send queue
3418 CAResult_t res = CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData,
3419 sizeof(CALEData_t));
3420 if (CA_STATUS_OK != res)
3422 CALEDataDestroyer(bleData, sizeof(CALEData_t));
3425 return CA_STATUS_OK;
3428 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
3429 const uint8_t *data,
3432 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3434 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3436 #ifdef SINGLE_THREAD
3437 if (!CAIsLEConnected())
3439 OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
3440 return CA_STATUS_FAILED;
3443 CAResult_t result = CALEServerSendDataSingleThread(data, dataLen);
3444 if (CA_STATUS_OK != result)
3446 OIC_LOG(ERROR, CALEADAPTER_TAG, "CALEServerSendDataSingleThread failed");
3447 return CA_STATUS_FAILED;
3450 VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
3451 "g_bleServerSendQueueHandle is NULL",
3454 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
3456 CALEData_t * const bleData =
3457 CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3461 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3462 return CA_MEMORY_ALLOC_FAILED;
3465 // Add message to send queue
3467 CAResult_t res = CAQueueingThreadAddData(g_bleServerSendQueueHandle,
3469 sizeof(CALEData_t));
3470 if (CA_STATUS_OK != res)
3472 CALEDataDestroyer(bleData, sizeof(CALEData_t));
3475 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3476 return CA_STATUS_OK;
3479 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
3480 const uint8_t *data,
3481 uint32_t dataLength,
3482 uint32_t *sentLength)
3484 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3487 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3488 VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3490 #ifdef SINGLE_THREAD
3491 CALEDataReceiverHandlerSingleThread(data, dataLength);
3493 if (g_singleThreadReceiveData->totalDataLen == g_singleThreadReceiveData->recvDataLen)
3495 if(g_networkPacketReceivedCallback)
3497 // will be filled by upper layer
3498 const CASecureEndpoint_t endpoint =
3499 { .endpoint = { .adapter = CA_ADAPTER_GATT_BTLE } };
3501 g_networkPacketReceivedCallback(&endpoint,
3502 g_singleThreadReceiveData->defragData,
3503 g_singleThreadReceiveData->recvDataLen);
3505 g_singleThreadReceiveData->remoteEndpoint = NULL;
3506 OICFree(g_singleThreadReceiveData->defragData);
3507 g_singleThreadReceiveData->defragData = NULL;
3508 OICFree(g_singleThreadReceiveData);
3509 g_singleThreadReceiveData = NULL;
3512 VERIFY_NON_NULL_RET(g_bleServerReceiverQueue,
3514 "g_bleServerReceiverQueue",
3517 //Add message to data queue
3518 CAEndpoint_t * const remoteEndpoint =
3519 CACreateEndpointObject(CA_DEFAULT_FLAGS,
3520 CA_ADAPTER_GATT_BTLE,
3524 if (NULL == remoteEndpoint)
3526 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3527 return CA_STATUS_FAILED;
3530 // Create bleData to add to queue
3533 "Data received from LE Server layer [%d]",
3536 CALEData_t * const bleData =
3537 CACreateLEData(remoteEndpoint, data, dataLength, g_bleServerSenderInfo);
3541 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3542 CAFreeEndpoint(remoteEndpoint);
3543 return CA_MEMORY_ALLOC_FAILED;
3546 CAFreeEndpoint(remoteEndpoint);
3547 // Add message to receiver queue
3548 CAQueueingThreadAddData(g_bleServerReceiverQueue, bleData, sizeof(CALEData_t));
3550 *sentLength = dataLength;
3552 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3553 return CA_STATUS_OK;
3556 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
3557 const uint8_t *data,
3558 uint32_t dataLength,
3559 uint32_t *sentLength)
3562 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3563 VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3564 #ifndef SINGLE_THREAD
3565 VERIFY_NON_NULL_RET(g_bleClientReceiverQueue, CALEADAPTER_TAG,
3566 "g_bleClientReceiverQueue",
3569 //Add message to data queue
3570 CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
3571 CA_ADAPTER_GATT_BTLE,
3573 if (NULL == remoteEndpoint)
3575 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3576 return CA_STATUS_FAILED;
3579 // Create bleData to add to queue
3582 "Data received from LE Client layer [%u]",
3585 CALEData_t * const bleData =
3586 CACreateLEData(remoteEndpoint, data, dataLength, g_bleClientSenderInfo);
3590 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3591 CAFreeEndpoint(remoteEndpoint);
3592 return CA_MEMORY_ALLOC_FAILED;
3595 CAFreeEndpoint(remoteEndpoint);
3596 // Add message to receiver queue
3597 CAQueueingThreadAddData(g_bleClientReceiverQueue, bleData, sizeof(CALEData_t));
3599 *sentLength = dataLength;
3601 return CA_STATUS_OK;
3604 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
3606 g_bleAdapterThreadPool = handle;
3610 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
3612 g_networkPacketReceivedCallback = callback;
3616 static void CALEErrorHandler(const char *remoteAddress,
3617 const uint8_t *data,
3621 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3623 VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
3625 CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS,
3626 CA_ADAPTER_GATT_BTLE,
3630 // if required, will be used to build remote endpoint
3631 g_errorHandler(rep, data, dataLen, result);
3633 CAFreeEndpoint(rep);
3635 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3638 #ifndef SINGLE_THREAD
3639 static bool CALEClearQueueAddressDataContext(void *data, uint32_t size, void *ctx)
3641 if (NULL == data || NULL == ctx)
3646 CALEData_t *caLeData = (CALEData_t *)data;
3647 const char *address = (const char *)ctx;
3649 if (NULL != caLeData && NULL != caLeData->remoteEndpoint)
3651 if (!strcasecmp(caLeData->remoteEndpoint->addr, address))
3659 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle, const char* address)
3661 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
3663 VERIFY_NON_NULL_VOID(queueHandle, CALEADAPTER_TAG, "queueHandle");
3664 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3666 CAResult_t res = CAQueueingThreadClearContextData(queueHandle,
3667 CALEClearQueueAddressDataContext,
3669 if (CA_STATUS_OK != res)
3672 OIC_LOG(ERROR, CALEADAPTER_TAG, "Could not clear the send queue");
3677 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList, const char* address)
3679 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
3681 VERIFY_NON_NULL_VOID(dataInfoList, CALEADAPTER_TAG, "dataInfoList");
3682 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3684 CABLESenderInfo_t *senderInfo = NULL;
3685 uint32_t senderIndex = 0;
3687 u_arraylist_t *portList = u_arraylist_create();
3688 if (CA_STATUS_OK == CALEGetPortsFromSenderInfo(address, dataInfoList, portList))
3690 uint32_t arrayLength = u_arraylist_length(portList);
3691 for (uint32_t i = 0; i < arrayLength; i++)
3693 uint16_t *port = (uint16_t *)u_arraylist_get(portList, i);
3696 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to get port from sender info !");
3697 u_arraylist_destroy(portList);
3701 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "port : %X", *port);
3703 if (CA_STATUS_OK == CALEGetSenderInfo(address, *port,
3704 dataInfoList, &senderInfo,
3707 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3708 "SenderInfo is removed for disconnection");
3709 CALERemoveSenderInfoFromList(dataInfoList, senderInfo);
3710 CALEFreeSenderInfo(senderInfo);
3714 OIC_LOG(DEBUG, CALEADAPTER_TAG, "SenderInfo doesn't exist");
3718 u_arraylist_destroy(portList);
3721 static CAResult_t CALEGetPortsFromSenderInfo(const char *leAddress,
3722 u_arraylist_t *senderInfoList,
3723 u_arraylist_t *portList)
3725 VERIFY_NON_NULL(leAddress,
3727 "NULL BLE address argument");
3729 const uint32_t listLength = u_arraylist_length(senderInfoList);
3730 const uint32_t addrLength = strlen(leAddress);
3732 for (uint32_t index = 0; index < listLength; index++)
3734 CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
3735 if (!info || !(info->remoteEndpoint))
3740 if (!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
3742 uint16_t *port = (uint16_t *)OICMalloc(sizeof(uint16_t));
3745 OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
3746 return CA_MEMORY_ALLOC_FAILED;
3748 *port = info->remoteEndpoint->port;
3749 u_arraylist_add(portList, (void *)port);
3753 if (u_arraylist_length(portList) != 0)
3755 return CA_STATUS_OK;
3759 return CA_STATUS_FAILED;
3764 void CALEStartGattServer()
3766 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3768 oc_mutex_lock(g_bleIsServerMutex);
3769 switch (g_adapterType)
3771 case ADAPTER_SERVER:
3772 CALEAdapterGattServerStart();
3774 case ADAPTER_CLIENT:
3775 CALEAdapterGattClientStart();
3777 case ADAPTER_BOTH_CLIENT_SERVER:
3778 CALEAdapterGattServerStart();
3779 CALEAdapterGattClientStart();
3784 oc_mutex_unlock(g_bleIsServerMutex);
3785 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3788 void CALEStopGattServer()
3790 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3792 oc_mutex_lock(g_bleIsServerMutex);
3793 switch (g_adapterType)
3795 case ADAPTER_SERVER:
3796 CALEAdapterGattServerStop();
3798 case ADAPTER_CLIENT:
3799 CALEAdapterGattClientStop();
3801 case ADAPTER_BOTH_CLIENT_SERVER:
3802 CALEAdapterGattServerStop();
3803 CALEAdapterGattClientStop();
3808 oc_mutex_unlock(g_bleIsServerMutex);
3809 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);