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__)
39 #include "caleserver.h"
40 #include "caleclient.h"
42 #include "oic_malloc.h"
43 #include "oic_string.h"
44 #include "caremotehandler.h"
48 * Logging tag for module name.
50 #define CALEADAPTER_TAG "OIC_CA_LE_ADAP"
53 * Stores information of all the senders.
55 * This structure will be used to track and defragment all incoming data packet.
60 uint32_t totalDataLen;
62 CAEndpoint_t *remoteEndpoint;
69 ADAPTER_BOTH_CLIENT_SERVER,
75 * mtu size to use in fragmentation logic.
76 * default value is 20 byte.
78 static uint16_t g_mtuSize = CA_DEFAULT_BLE_MTU_SIZE;
81 * Callback to provide the status of the network change to CA layer.
83 static CAAdapterChangeCallback g_networkCallback = NULL;
86 * Callback to provide the status of the connection change to CA layer.
88 static CAConnectionChangeCallback g_connectionCallback = NULL;
91 * Own port value to identify packet owner. Default port value is 1.
93 static uint8_t g_localBLESourcePort = 1;
96 * bleAddress of the local adapter. Value will be initialized to zero,
97 * and will be updated later.
99 static char g_localBLEAddress[18] = { 0 };
102 * Variable to differentiate btw GattServer and GattClient.
104 static CABLEAdapter_t g_adapterType = ADAPTER_EMPTY;
107 static CADataType_t g_dataType = CA_REQUEST_DATA;
111 * Mutex to synchronize the task to be executed on the GattServer
114 static oc_mutex g_bleIsServerMutex = NULL;
117 * Mutex to synchronize the updates of the local LE address of the
120 static oc_mutex g_bleLocalAddressMutex = NULL;
123 * Reference to thread pool.
125 static ca_thread_pool_t g_bleAdapterThreadPool = NULL;
128 * Mutex to synchronize the queing of the data from ReceiverQueue.
130 static oc_mutex g_bleClientReceiveDataMutex = NULL;
133 * Mutex to synchronize the queing of the data from ReceiverQueue.
135 static oc_mutex g_bleServerReceiveDataMutex = NULL;
138 * Callback to be called when network packet received from either
139 * GattServer or GattClient.
141 static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
144 * Callback to notify error from the BLE adapter.
146 static CAErrorHandleCallback g_errorHandler = NULL;
149 static CAResult_t CALESecureReceiveDataCB(const CASecureEndpoint_t *endpoint,
150 const void *data, size_t dataLength);
152 static ssize_t CALESecureSendDataCB(CAEndpoint_t *endpoint,
153 const void *data, size_t dataLength);
158 * Pointer to defragment received data from single threaded routine.
160 static CABLESenderInfo_t *g_singleThreadReceiveData = NULL;
163 * This function will be associated with the receive for single thread.
165 * This function will defragment the received data from sender
166 * respectively and will send it up to CA layer. Respective sender's
167 * header will provide the length of the data sent.
169 * @param[in] data Actual data received from the remote
171 * @param[in] dataLen Length of the data received from the
174 static void CALEDataReceiverHandlerSingleThread(const uint8_t *data,
178 * This function will be associated with the send for single threaded
181 * This function will fragment the data to the MTU of the transport
182 * and send the data in fragments to the adapters. The function will
183 * be blocked until all data is sent out from the adapter.
185 * @param[in] data Data to be transmitted from LE.
186 * @param[in] dataLen Length of the Data being transmitted.
188 static CAResult_t CALEServerSendDataSingleThread(const uint8_t *data,
193 * Register network change notification callback.
195 * @param[in] netCallback CAAdapterChangeCallback callback which will
196 * be set for the change in adapter.
197 * @param[in] connCallback CAConnectionChangeCallback callback which will
198 * be set for the change in connection.
200 * @return 0 on success otherwise a positive error value.
201 * @retval ::CA_STATUS_OK Successful.
202 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
203 * @retval ::CA_STATUS_FAILED Operation failed.
206 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
207 CAConnectionChangeCallback connCallback);
210 * Set the thread pool handle which is required for spawning new
213 * @param[in] handle Thread pool handle which is given by above layer
214 * for using thread creation task.
217 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle);
220 * Call the callback to the upper layer when the adapter state gets
223 * @param[in] adapter_state New state of the adapter to be notified to
226 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state);
229 * Call the callback to the upper layer when the device connection state gets
232 * @param[in] address LE address of the device to be notified to the upper layer.
233 * @param[in] isConnected whether connection state is connected or not.
235 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
239 * Used to initialize all required mutex variable for LE Adapter
242 * @return 0 on success otherwise a positive error value.
243 * @retval ::CA_STATUS_OK Successful.
244 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
245 * @retval ::CA_STATUS_FAILED Operation failed.
248 static CAResult_t CAInitLEAdapterMutex();
251 * Terminate all required mutex variables for LE adapter
254 static void CATerminateLEAdapterMutex();
257 * Prepares and notify error through error callback.
259 static void CALEErrorHandler(const char *remoteAddress,
264 #ifndef SINGLE_THREAD
266 * Stop condition of Server recvhandler.
268 static bool g_dataBleServerReceiverHandlerState = false;
271 * Stop condition of Client recvhandler.
273 static bool g_dataBleClientReceiverHandlerState = false;
276 * Sender information of Server.
278 static u_arraylist_t *g_bleServerSenderInfo = NULL;
281 * Sender information of Client.
283 static u_arraylist_t *g_bleClientSenderInfo = NULL;
286 * Mutex to synchronize access to all senderInfos
288 static oc_mutex g_senderInfoMutex = NULL;
291 * Queue to process the outgoing packets from GATTServer.
293 static CAQueueingThread_t *g_bleServerSendQueueHandle = NULL;
296 * Queue to process the outgoing packets from GATTClient.
298 static CAQueueingThread_t *g_bleClientSendQueueHandle = NULL;
301 * Queue to process the incoming packets from GATTServer.
303 static CAQueueingThread_t *g_bleServerReceiverQueue = NULL;
306 * Queue to process the incoming packets from GATTClient.
308 static CAQueueingThread_t *g_bleClientReceiverQueue = NULL;
311 * This function will be associated with the sender queue for
314 * This function will fragment the data to the MTU of the transport
315 * and send the data in fragments to the adapters. The function will
316 * be blocked until all data is sent out from the adapter.
318 * @param[in] threadData Data pushed to the queue which contains the
319 * info about RemoteEndpoint and Data.
321 static void CALEServerSendDataThread(void *threadData);
324 * This function will be associated with the sender queue for
327 * This function will fragment the data to the MTU of the transport
328 * and send the data in fragments to the adapters. The function will
329 * be blocked until all data is sent out from the adapter.
331 * @param[in] threadData Data pushed to the queue which contains the
332 * info about RemoteEndpoint and Data.
334 static void CALEClientSendDataThread(void *threadData);
337 * This function will defragment the received data from each sender
338 * respectively and will send it up to CA layer. Respective sender's
339 * header will provide the length of the data sent.
341 * @param[in] threadData Data pushed to the queue which contains the
342 * info about RemoteEndpoint and Data.
343 * @param[in] receiverType Whether receiver is server or client.
345 static void CALEDataReceiverHandler(void *threadData, CABLEAdapter_t receiverType);
348 * This function will be associated with the receiver queue for
351 * This function will call the function CALEDataReceiverHandler()
352 * with server type to defragment the received data.
354 * @param[in] threadData Data pushed to the queue which contains the
355 * info about RemoteEndpoint and Data.
357 static void CALEServerDataReceiverHandler(void *threadData);
360 * This function will be associated with the receiver queue for
363 * This function will call the function CALEDataReceiverHandler()
364 * with client type to defragment the received data.
366 * @param[in] threadData Data pushed to the queue which contains the
367 * info about RemoteEndpoint and Data.
369 static void CALEClientDataReceiverHandler(void *threadData);
372 * This function will stop all queues created for GattServer and
373 * GattClient. All four queues will be be stopped with this function
376 static void CAStopLEQueues();
379 * This function will terminate all queues created for GattServer and
380 * GattClient. All four queues will be be terminated with this
381 * function invocations.
383 static void CATerminateLEQueues();
386 * This function will initalize the Receiver and Sender queues for
387 * GattServer. This function will in turn call the functions
388 * CAInitBleServerReceiverQueue() and CAInitBleServerSenderQueue() to
389 * initialize the queues.
391 * @return ::CA_STATUS_OK or Appropriate error code.
392 * @retval ::CA_STATUS_OK Successful.
393 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
394 * @retval ::CA_STATUS_FAILED Operation failed.
396 static CAResult_t CAInitLEServerQueues();
399 * This function will initalize the Receiver and Sender queues for
400 * GattClient. This function will inturn call the functions
401 * CAInitBleClientReceiverQueue() and CAInitBleClientSenderQueue() to
402 * initialize the queues.
404 * @return ::CA_STATUS_OK or Appropriate error code.
405 * @retval ::CA_STATUS_OK Successful.
406 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
407 * @retval ::CA_STATUS_FAILED Operation failed.
410 static CAResult_t CAInitLEClientQueues();
413 * This function will initalize the Receiver queue for
414 * GattServer. This will initialize the queue to process the function
415 * CABLEServerSendDataThread() when ever the task is added to this
418 * @return ::CA_STATUS_OK or Appropriate error code.
419 * @retval ::CA_STATUS_OK Successful.
420 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
421 * @retval ::CA_STATUS_FAILED Operation failed.
423 static CAResult_t CAInitLEServerSenderQueue();
426 * This function will initalize the Receiver queue for
427 * GattClient. This will initialize the queue to process the function
428 * CABLEClientSendDataThread() when ever the task is added to this
431 * @return ::CA_STATUS_OK or Appropriate error code.
432 * @retval ::CA_STATUS_OK Successful.
433 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
434 * @retval ::CA_STATUS_FAILED Operation failed.
436 static CAResult_t CAInitLEClientSenderQueue();
439 * This function will initialize the Receiver queue for
440 * GattServer. This will initialize the queue to process the function
441 * CALEServerDataReceiverHandler() when ever the task is added to this
444 * @return ::CA_STATUS_OK or Appropriate error code
445 * @retval ::CA_STATUS_OK Successful
446 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments
447 * @retval ::CA_STATUS_FAILED Operation failed
450 static CAResult_t CAInitLEServerReceiverQueue();
453 * This function will initialize the Receiver queue for
454 * GattClient. This will initialize the queue to process the function
455 * CALEClientDataReceiverHandler() when ever the task is added to this
458 * @return ::CA_STATUS_OK or Appropriate error code
459 * @retval ::CA_STATUS_OK Successful
460 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments
461 * @retval ::CA_STATUS_FAILED Operation failed
464 static CAResult_t CAInitLEClientReceiverQueue();
467 * This function will create the Data required to send it in the
470 * @param[in] remoteEndpoint Remote endpoint information of the
472 * @param[in] data Data to be transmitted from LE.
473 * @param[in] dataLength Length of the Data being transmitted.
475 * @return ::CA_STATUS_OK or Appropriate error code.
476 * @retval ::CA_STATUS_OK Successful.
477 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
478 * @retval ::CA_STATUS_FAILED Operation failed.
480 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
483 u_arraylist_t *senderInfo);
486 * Used to free the BLE information stored in the sender/receiver
489 * @param[in] bleData Information for a particular data segment.
491 static void CAFreeLEData(CALEData_t *bleData);
496 static void CALEDataDestroyer(void *data, uint32_t size);
498 #ifndef SINGLE_THREAD
500 * remove request or response data of send queue.
502 * @param[in] queueHandle queue to process the outgoing packets.
503 * @param[in] mutex mutex related to sender for client / server.
504 * @param[in] address target address to remove data in queue.
506 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle,
507 const char* address);
510 * remove all received data of data list from receive queue.
512 * @param[in] dataInfoList received data list to remove for client / server.
513 * @param[in] address target address to remove data in queue.
515 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList,
516 const char* address);
519 * get received data info and positioned index from the received data list
520 * for client / server which is matched same leAddress and port.
521 * CABLESenderInfo_t is reference counted structure, you must call
522 * CALEFreeSenderInfo on senderInfo to release reference.
524 * @param[in] leAddress target address to get serderInfo.
525 * @param[in] port target port to get senderInfo.
526 * @param[in] senderInfoList received data list for client / server.
527 * @param[out] senderInfo Pointer to contain matched(leAddress and port)
528 * received data info.
529 * @param[out] senderIndex Pointer to contain matched(leAddress and port)
530 * received data info index.
532 static CAResult_t CALEGetSenderInfo(const char *leAddress,
534 u_arraylist_t *senderInfoList,
535 CABLESenderInfo_t **senderInfo,
536 uint32_t *senderIndex);
539 * Add sender info to list.
541 * @param[in] u_arraylist_t Array list to add sender info to.
542 * @param[in] senderInfo Sender info to be added to list.
544 * @return true on success, otherwise false.
546 static bool CALEAddSenderInfoToList(u_arraylist_t *senderInfoList,
547 CABLESenderInfo_t *senderInfo);
550 * Remove desired sender info from list.
552 * @param[in] u_arraylist_t Array list to remove sender info from.
553 * @param[in] senderInfo Sender info to be removed from list.
556 static void CALERemoveSenderInfoFromList(u_arraylist_t *senderInfoList,
557 CABLESenderInfo_t *senderInfo);
560 * Free sender info. CABLESenderInfo_t is reference counted structure
561 * and info will be freed only when reference count reaches 0 or negative.
563 * @param[in] senderInfo Sender info to be freed.
566 static CAResult_t CALEFreeSenderInfo(CABLESenderInfo_t *senderInfo);
569 * get ports related to remote address. It is need because multi application
570 * can have more than 2 senderInfo using same BLE address. So before remove
571 * receive queue data, should get port list from sender Info.
573 * @param[in] leAddress target address to get port in serderInfo.
574 * @param[in] senderInfoList received data list to remove for client / server.
575 * @param[out] portList target port list related to leAddress.
577 static CAResult_t CALEGetPortsFromSenderInfo(const char *leAddress,
578 u_arraylist_t *senderInfoList,
579 u_arraylist_t *portList);
582 static CAResult_t CAInitLEServerQueues()
584 CAResult_t result = CAInitLEServerSenderQueue();
585 if (CA_STATUS_OK != result)
587 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerSenderQueue failed");
589 return CA_STATUS_FAILED;
592 g_bleServerSenderInfo = u_arraylist_create();
593 if (!g_bleServerSenderInfo)
595 OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
596 return CA_MEMORY_ALLOC_FAILED;
599 result = CAInitLEServerReceiverQueue();
600 if (CA_STATUS_OK != result)
602 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerReceiverQueue failed");
603 u_arraylist_free(&g_bleServerSenderInfo);
604 return CA_STATUS_FAILED;
607 g_dataBleServerReceiverHandlerState = true;
611 static CAResult_t CAInitLEClientQueues()
613 CAResult_t result = CAInitLEClientSenderQueue();
614 if (CA_STATUS_OK != result)
616 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientSenderQueue failed");
617 return CA_STATUS_FAILED;
620 g_bleClientSenderInfo = u_arraylist_create();
621 if (!g_bleClientSenderInfo)
623 OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
624 return CA_MEMORY_ALLOC_FAILED;
627 result = CAInitLEClientReceiverQueue();
628 if (CA_STATUS_OK != result)
630 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientReceiverQueue failed");
631 u_arraylist_free(&g_bleClientSenderInfo);
632 return CA_STATUS_FAILED;
635 g_dataBleClientReceiverHandlerState = true;
640 static CAResult_t CAInitLEServerReceiverQueue()
642 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
643 // Check if the message queue is already initialized
644 if (g_bleServerReceiverQueue)
646 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
650 // Create recv message queue
651 g_bleServerReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
652 if (!g_bleServerReceiverQueue)
654 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
655 return CA_MEMORY_ALLOC_FAILED;
658 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerReceiverQueue,
659 g_bleAdapterThreadPool,
660 CALEServerDataReceiverHandler,
663 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize server receiver queue thread");
664 OICFree(g_bleServerReceiverQueue);
665 g_bleServerReceiverQueue = NULL;
666 return CA_STATUS_FAILED;
669 if (CA_STATUS_OK != CAQueueingThreadStart(g_bleServerReceiverQueue))
671 OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
672 OICFree(g_bleServerReceiverQueue);
673 g_bleServerReceiverQueue = NULL;
674 return CA_STATUS_FAILED;
680 static CAResult_t CAInitLEClientReceiverQueue()
682 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
683 // Check if the message queue is already initialized
684 if (g_bleClientReceiverQueue)
686 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
690 // Create recv message queue
691 g_bleClientReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
692 if (!g_bleClientReceiverQueue)
694 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
695 return CA_MEMORY_ALLOC_FAILED;
698 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientReceiverQueue,
699 g_bleAdapterThreadPool,
700 CALEClientDataReceiverHandler,
703 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize client receiver queue thread");
704 OICFree(g_bleClientReceiverQueue);
705 g_bleClientReceiverQueue = NULL;
706 return CA_STATUS_FAILED;
709 if (CA_STATUS_OK != CAQueueingThreadStart(g_bleClientReceiverQueue))
711 OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
712 OICFree(g_bleClientReceiverQueue);
713 g_bleClientReceiverQueue = NULL;
714 return CA_STATUS_FAILED;
720 static CAResult_t CAInitLEServerSenderQueue()
722 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
723 // Check if the message queue is already initialized
724 if (g_bleServerSendQueueHandle)
726 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Queue is already initialized!");
730 // Create send message queue
731 g_bleServerSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
732 if (!g_bleServerSendQueueHandle)
734 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
735 return CA_MEMORY_ALLOC_FAILED;
738 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerSendQueueHandle,
739 g_bleAdapterThreadPool,
740 CALEServerSendDataThread,
743 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
744 OICFree(g_bleServerSendQueueHandle);
745 g_bleServerSendQueueHandle = NULL;
746 return CA_STATUS_FAILED;
752 static void CALEClearSenderInfoImpl(u_arraylist_t **list)
754 oc_mutex_lock(g_senderInfoMutex);
755 const size_t length = u_arraylist_length(*list);
756 for (size_t i = 0; i < length; ++i)
758 CABLESenderInfo_t * const info =
759 (CABLESenderInfo_t *) u_arraylist_get(*list, i);
762 OICFree(info->defragData);
763 CAFreeEndpoint(info->remoteEndpoint);
767 u_arraylist_free(list);
768 oc_mutex_unlock(g_senderInfoMutex);
771 static void CALEClearSenderInfo()
773 CALEClearSenderInfoImpl(&g_bleServerSenderInfo);
774 CALEClearSenderInfoImpl(&g_bleClientSenderInfo);
777 static CAResult_t CAInitLEClientSenderQueue()
779 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
781 if (g_bleClientSendQueueHandle)
783 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
787 // Create send message queue
788 g_bleClientSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
789 if (!g_bleClientSendQueueHandle)
791 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
792 return CA_MEMORY_ALLOC_FAILED;
795 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientSendQueueHandle,
796 g_bleAdapterThreadPool,
797 CALEClientSendDataThread, CALEDataDestroyer))
799 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
800 OICFree(g_bleClientSendQueueHandle);
801 g_bleClientSendQueueHandle = NULL;
802 return CA_STATUS_FAILED;
807 static void CAStopLEQueues()
809 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
811 oc_mutex_lock(g_bleServerReceiveDataMutex);
812 if (NULL != g_bleServerReceiverQueue)
814 CAQueueingThreadStop(g_bleServerReceiverQueue);
816 oc_mutex_unlock(g_bleServerReceiveDataMutex);
818 oc_mutex_lock(g_bleClientReceiveDataMutex);
819 if (NULL != g_bleClientReceiverQueue)
821 CAQueueingThreadStop(g_bleClientReceiverQueue);
823 oc_mutex_unlock(g_bleClientReceiveDataMutex);
825 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
828 static void CATerminateLEQueues()
830 CAQueueingThreadDestroy(g_bleClientSendQueueHandle);
831 OICFree(g_bleClientSendQueueHandle);
832 g_bleClientSendQueueHandle = NULL;
834 CAQueueingThreadDestroy(g_bleServerSendQueueHandle);
835 OICFree(g_bleServerSendQueueHandle);
836 g_bleServerSendQueueHandle = NULL;
838 CAQueueingThreadDestroy(g_bleServerReceiverQueue);
839 OICFree(g_bleServerReceiverQueue);
840 g_bleServerReceiverQueue = NULL;
842 CAQueueingThreadDestroy(g_bleClientReceiverQueue);
843 OICFree(g_bleClientReceiverQueue);
844 g_bleClientReceiverQueue = NULL;
846 CALEClearSenderInfo();
849 static CAResult_t CALEGetSenderInfo(const char *leAddress,
851 u_arraylist_t *senderInfoList,
852 CABLESenderInfo_t **senderInfo,
853 uint32_t *senderIndex)
855 VERIFY_NON_NULL_RET(leAddress,
857 "NULL BLE address argument",
858 CA_STATUS_INVALID_PARAM);
859 VERIFY_NON_NULL_RET(senderIndex,
861 "NULL index argument",
862 CA_STATUS_INVALID_PARAM);
864 oc_mutex_lock(g_senderInfoMutex);
865 const uint32_t listLength = u_arraylist_length(senderInfoList);
866 const uint32_t addrLength = strlen(leAddress);
867 for (uint32_t index = 0; index < listLength; index++)
869 CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
870 if (!info || !(info->remoteEndpoint))
875 if (!strncmp(info->remoteEndpoint->addr, leAddress, addrLength)
876 && info->remoteEndpoint->port == port)
878 *senderIndex = index;
882 (*senderInfo)->refCount++;
884 oc_mutex_unlock(g_senderInfoMutex);
889 oc_mutex_unlock(g_senderInfoMutex);
890 return CA_STATUS_FAILED;
893 static bool CALEAddSenderInfoToList(u_arraylist_t *senderInfoList, CABLESenderInfo_t *senderInfo)
895 oc_mutex_lock(g_senderInfoMutex);
896 senderInfo->refCount++;
897 if (!u_arraylist_add(senderInfoList,(void *)senderInfo))
899 senderInfo->refCount--;
900 oc_mutex_unlock(g_senderInfoMutex);
903 oc_mutex_unlock(g_senderInfoMutex);
907 static void CALERemoveSenderInfoFromList(u_arraylist_t *senderInfoList, CABLESenderInfo_t *senderInfo)
909 oc_mutex_lock(g_senderInfoMutex);
911 bool elemFound = u_arraylist_get_index(senderInfoList, (const void*)senderInfo, &idx);
914 void *info = u_arraylist_remove(senderInfoList, idx);
917 senderInfo->refCount--;
920 oc_mutex_unlock(g_senderInfoMutex);
923 static CAResult_t CALEFreeSenderInfo(CABLESenderInfo_t *senderInfo)
925 VERIFY_NON_NULL_RET(senderInfo,
927 "NULL senderInfo to remove argument",
928 CA_STATUS_INVALID_PARAM);
930 oc_mutex_lock(g_senderInfoMutex);
931 senderInfo->refCount--;
932 if(senderInfo->refCount <= 0)
934 OICFree(senderInfo->defragData);
935 OICFree(senderInfo->remoteEndpoint);
938 oc_mutex_unlock(g_senderInfoMutex);
942 static void CALEDataReceiverHandler(void *threadData, CABLEAdapter_t receiverType)
944 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
946 oc_mutex bleReceiveDataMutex = NULL;
947 bool dataBleReceiverHandlerState = false;
949 switch (receiverType)
952 bleReceiveDataMutex = g_bleClientReceiveDataMutex;
953 dataBleReceiverHandlerState = g_dataBleClientReceiverHandlerState;
956 bleReceiveDataMutex = g_bleServerReceiveDataMutex;
957 dataBleReceiverHandlerState = g_dataBleServerReceiverHandlerState;
960 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Unsupported receiver type : %d", receiverType);
964 oc_mutex_lock(bleReceiveDataMutex);
966 if (dataBleReceiverHandlerState)
968 CALEData_t *bleData = (CALEData_t *) threadData;
971 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bleData!");
972 oc_mutex_unlock(bleReceiveDataMutex);
976 if (!(bleData->senderInfo))
978 OIC_LOG(ERROR, CALEADAPTER_TAG, "sender info is not available");
979 oc_mutex_unlock(bleReceiveDataMutex);
983 if (!(bleData->remoteEndpoint))
985 OIC_LOG(ERROR, CALEADAPTER_TAG, "RemoteEndPoint NULL!!");
986 oc_mutex_unlock(bleReceiveDataMutex);
990 CABLESenderInfo_t *senderInfo = NULL;
991 uint32_t senderIndex = 0;
994 CABLEPacketStart_t startFlag = CA_BLE_PACKET_NOT_START;
995 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
996 uint16_t sourcePort = 0;
997 uint16_t destPort = 0;
999 CAParseHeader(bleData->data, &startFlag, &sourcePort, &secureFlag, &destPort);
1000 OIC_LOG_V(INFO, CALEADAPTER_TAG,
1001 "header info: startFlag[%X] sourcePort[%d] secureFlag[%X] destPort[%d]",
1002 startFlag, sourcePort, secureFlag, destPort);
1004 if (destPort != g_localBLESourcePort && destPort != CA_BLE_MULTICAST_PORT)
1006 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1007 "this packet is not valid for this app(port mismatch[mine:%d, packet:%d])",
1008 g_localBLESourcePort, destPort);
1009 oc_mutex_unlock(bleReceiveDataMutex);
1013 bleData->remoteEndpoint->port = sourcePort;
1015 if (CA_STATUS_OK != CALEGetSenderInfo(bleData->remoteEndpoint->addr,
1016 bleData->remoteEndpoint->port,
1017 bleData->senderInfo,
1018 &senderInfo, &senderIndex))
1020 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This is a new client [%s:%X]",
1021 bleData->remoteEndpoint->addr, bleData->remoteEndpoint->port);
1027 OIC_LOG(ERROR, CALEADAPTER_TAG,
1028 "This packet is start packet but exist senderInfo. Remove senderInfo");
1029 CALERemoveSenderInfoFromList(bleData->senderInfo, senderInfo);
1030 CALEFreeSenderInfo(senderInfo);
1038 uint32_t totalLength = 0;
1041 CAParseHeaderPayloadLength(bleData->data, CA_BLE_LENGTH_HEADER_SIZE, &totalLength);
1045 OIC_LOG(ERROR, CALEADAPTER_TAG, "This packet is wrong packet! ignore.");
1046 oc_mutex_unlock(bleReceiveDataMutex);
1050 CABLESenderInfo_t *newSender = OICCalloc(1, sizeof(CABLESenderInfo_t));
1053 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
1054 oc_mutex_unlock(bleReceiveDataMutex);
1058 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
1060 newSender->totalDataLen = totalLength;
1061 if (!(newSender->totalDataLen))
1063 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
1064 CALEFreeSenderInfo(newSender);
1065 oc_mutex_unlock(bleReceiveDataMutex);
1069 size_t dataOnlyLen =
1070 bleData->dataLen - (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE);
1071 OIC_LOG_V(INFO, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
1072 newSender->totalDataLen);
1073 OIC_LOG_V(INFO, CALEADAPTER_TAG, "data received in the first packet [%zu] bytes",
1076 newSender->defragData = OICCalloc(newSender->totalDataLen + 1,
1077 sizeof(*newSender->defragData));
1079 if (NULL == newSender->defragData)
1081 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
1082 CALEFreeSenderInfo(newSender);
1083 oc_mutex_unlock(bleReceiveDataMutex);
1086 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
1087 #ifdef __WITH_DTLS__
1088 if (CA_BLE_PACKET_SECURE == secureFlag)
1094 const char *remoteAddress = bleData->remoteEndpoint->addr;
1095 newSender->remoteEndpoint = CACreateEndpointObject(flags,
1096 CA_ADAPTER_GATT_BTLE,
1098 bleData->remoteEndpoint->port);
1100 if (NULL == newSender->remoteEndpoint)
1102 OIC_LOG(ERROR, CALEADAPTER_TAG, "remoteEndpoint is NULL!");
1103 CALEFreeSenderInfo(newSender);
1104 oc_mutex_unlock(bleReceiveDataMutex);
1108 if (newSender->recvDataLen + dataOnlyLen > newSender->totalDataLen)
1110 OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
1111 CALEFreeSenderInfo(newSender);
1112 oc_mutex_unlock(bleReceiveDataMutex);
1115 memcpy(newSender->defragData,
1116 bleData->data + (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE),
1118 newSender->recvDataLen += dataOnlyLen;
1120 newSender->refCount = 1;
1122 if (!CALEAddSenderInfoToList(bleData->senderInfo, newSender))
1124 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to add sender info!");
1125 CALEFreeSenderInfo(newSender);
1126 oc_mutex_unlock(bleReceiveDataMutex);
1130 senderInfo = newSender;
1134 size_t dataOnlyLen = bleData->dataLen - CA_BLE_HEADER_SIZE;
1135 if (senderInfo->recvDataLen + dataOnlyLen > senderInfo->totalDataLen)
1137 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1138 "Data Length exceeding error!! Receiving [%zu] total length [%u]",
1139 senderInfo->recvDataLen + dataOnlyLen, senderInfo->totalDataLen);
1140 CALERemoveSenderInfoFromList(bleData->senderInfo, senderInfo);
1141 CALEFreeSenderInfo(senderInfo);
1142 oc_mutex_unlock(bleReceiveDataMutex);
1145 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%zu]",
1147 memcpy(senderInfo->defragData + senderInfo->recvDataLen,
1148 bleData->data + CA_BLE_HEADER_SIZE,
1150 senderInfo->recvDataLen += dataOnlyLen;
1151 OIC_LOG_V(INFO, CALEADAPTER_TAG, "totalDatalength [%d] received Datalen [%d]",
1152 senderInfo->totalDataLen, senderInfo->recvDataLen);
1155 if (senderInfo->totalDataLen == senderInfo->recvDataLen)
1157 if (NULL == g_networkPacketReceivedCallback)
1159 OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
1160 CALERemoveSenderInfoFromList(bleData->senderInfo, senderInfo);
1161 CALEFreeSenderInfo(senderInfo);
1162 oc_mutex_unlock(bleReceiveDataMutex);
1166 OIC_LOG(DEBUG, CALEADAPTER_TAG, "[CALEDataReceiverHandler] Received data up !");
1168 const CASecureEndpoint_t tmp =
1170 .endpoint = *senderInfo->remoteEndpoint
1173 OIC_LOG_V(INFO, CALEADAPTER_TAG, "endpoint flags : %d", tmp.endpoint.flags);
1174 #ifdef __WITH_DTLS__
1175 if (CA_SECURE & tmp.endpoint.flags)
1177 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Secure data received");
1178 switch (receiverType)
1180 case ADAPTER_CLIENT:
1181 g_dataType = CA_REQUEST_DATA;
1183 case ADAPTER_SERVER:
1184 g_dataType = CA_RESPONSE_DATA;
1187 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Unsupported rcvr type:%d",receiverType);
1188 CALERemoveSenderInfoFromList(bleData->senderInfo, senderInfo);
1189 senderInfo->remoteEndpoint = NULL;
1190 senderInfo->defragData = NULL;
1191 CALEFreeSenderInfo(senderInfo);
1192 oc_mutex_unlock(bleReceiveDataMutex);
1196 if (CA_STATUS_FAILED == CAdecryptSsl(&tmp,
1197 senderInfo->defragData,
1198 senderInfo->recvDataLen))
1200 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAdecryptSsl failed");
1204 OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAdecryptSsl successed");
1206 OICFree(senderInfo->defragData);
1211 OIC_LOG(INFO, CALEADAPTER_TAG, "Non-Secure data received");
1212 g_networkPacketReceivedCallback(&tmp,
1213 senderInfo->defragData,
1214 senderInfo->recvDataLen);
1215 #ifdef __WITH_DTLS__
1219 CALERemoveSenderInfoFromList(bleData->senderInfo, senderInfo);
1220 senderInfo->remoteEndpoint = NULL;
1221 senderInfo->defragData = NULL;
1222 CALEFreeSenderInfo(senderInfo);
1223 oc_mutex_unlock(bleReceiveDataMutex);
1226 CALEFreeSenderInfo(senderInfo);
1228 oc_mutex_unlock(bleReceiveDataMutex);
1232 static void CALEServerDataReceiverHandler(void *threadData)
1234 CALEDataReceiverHandler(threadData, ADAPTER_SERVER);
1237 static void CALEClientDataReceiverHandler(void *threadData)
1239 CALEDataReceiverHandler(threadData, ADAPTER_CLIENT);
1242 static void CALEServerSendDataThread(void *threadData)
1244 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1246 CALEData_t * const bleData = (CALEData_t *) threadData;
1249 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid bledata!");
1253 if (!bleData->remoteEndpoint)
1255 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid endpoint of bledata!");
1259 #if defined(__TIZEN__) || defined(__ANDROID__)
1261 g_mtuSize = CALEServerGetMtuSize(bleData->remoteEndpoint->addr);
1263 OIC_LOG_V(INFO, CALEADAPTER_TAG, "MTU size [%d]", g_mtuSize);
1265 uint32_t midPacketCount = 0;
1266 size_t remainingLen = 0;
1267 size_t totalLength = 0;
1268 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1270 CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
1276 if (CA_STATUS_OK != result)
1278 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1279 "CAGenerateVariableForFragmentation failed, result [%d]", result);
1282 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1287 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1288 "Packet info: data size[%d] midPacketCount[%u] remainingLen[%zu] totalLength[%zu]",
1289 bleData->dataLen, midPacketCount, remainingLen, totalLength);
1293 "Server total Data length with header is [%zu]",
1296 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1297 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1299 if (NULL != bleData->remoteEndpoint) //Unicast Data
1301 secureFlag = (bleData->remoteEndpoint->flags & CA_SECURE) ?
1302 CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
1304 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This Packet is secure? %d", secureFlag);
1305 result = CAGenerateHeader(dataHeader,
1306 CA_BLE_PACKET_START,
1307 g_localBLESourcePort,
1309 bleData->remoteEndpoint->port);
1311 else //Multicast Data
1313 result = CAGenerateHeader(dataHeader,
1314 CA_BLE_PACKET_START,
1315 g_localBLESourcePort,
1317 CA_BLE_MULTICAST_PORT);
1319 OIC_LOG_V(INFO, CALEADAPTER_TAG, "header info: secureFlag[%X]", secureFlag);
1321 if (CA_STATUS_OK != result)
1323 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1324 "CAGenerateHeader failed, result [%d]", result);
1327 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1332 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1333 result = CAGenerateHeaderPayloadLength(lengthHeader,
1334 CA_BLE_LENGTH_HEADER_SIZE,
1337 if (CA_STATUS_OK != result)
1339 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1340 "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1343 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1348 uint32_t length = 0;
1349 uint32_t dataLen = 0;
1350 if (g_mtuSize > totalLength)
1352 length = (uint32_t)totalLength;
1353 dataLen = bleData->dataLen;
1358 dataLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1361 result = CAMakeFirstDataSegment(dataSegment,
1362 bleData->data, dataLen,
1363 dataHeader, lengthHeader);
1365 if (CA_STATUS_OK != result)
1367 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1368 "Making data segment failed, result [%d]", result);
1371 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1376 const uint32_t iter = midPacketCount;
1379 // Send the first segment with the header.
1380 if (NULL != bleData->remoteEndpoint) // Sending Unicast Data
1382 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Unicast Data");
1384 result = CAUpdateCharacteristicsToGattClient(
1385 bleData->remoteEndpoint->addr, dataSegment, length);
1387 if (CA_STATUS_OK != result)
1391 "Update characteristics failed, result [%d]",
1395 g_errorHandler(bleData->remoteEndpoint,
1405 "Server Sent Unicast First Data - data length [%u]",
1408 result = CAGenerateHeader(dataHeader,
1409 CA_BLE_PACKET_NOT_START,
1410 g_localBLESourcePort,
1412 bleData->remoteEndpoint->port);
1414 if (CA_STATUS_OK != result)
1416 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1417 "CAGenerateHeader failed, result [%d]", result);
1420 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1425 for (index = 0; index < iter; index++)
1427 // Send the remaining header.
1428 result = CAMakeRemainDataSegment(dataSegment,
1429 g_mtuSize - CA_BLE_HEADER_SIZE,
1436 if (CA_STATUS_OK != result)
1438 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1439 "Making data segment failed, result [%d]", result);
1442 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1448 CAUpdateCharacteristicsToGattClient(
1449 bleData->remoteEndpoint->addr,
1453 if (CA_STATUS_OK != result)
1455 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1456 "Update characteristics failed, result [%d]", result);
1459 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1463 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]",
1467 if (remainingLen && (totalLength > g_mtuSize))
1469 // send the last segment of the data (Ex: 22 bytes of 622
1470 // bytes of data when MTU is 200)
1471 result = CAMakeRemainDataSegment(dataSegment,
1479 if (CA_STATUS_OK != result)
1481 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1482 "Making data segment failed, result [%d]", result);
1485 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1490 result = CAUpdateCharacteristicsToGattClient(
1491 bleData->remoteEndpoint->addr,
1493 remainingLen + CA_BLE_HEADER_SIZE);
1495 if (CA_STATUS_OK != result)
1499 "Update characteristics failed, result [%d]",
1503 g_errorHandler(bleData->remoteEndpoint,
1512 "Server Sent Unicast Last Data - data length [%zu]",
1513 remainingLen + CA_BLE_HEADER_SIZE);
1518 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
1519 OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
1522 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1525 static void CALEClientSendDataThread(void *threadData)
1527 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1529 CALEData_t *bleData = (CALEData_t *) threadData;
1532 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid bledata!");
1536 if (!bleData->remoteEndpoint)
1538 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid endpoint of bledata!");
1542 #if defined(__ANDROID__)
1544 if (false == CALEClientIsConnected(bleData->remoteEndpoint->addr))
1546 // triggering to gatt connect and MTU negotiation
1547 CAResult_t res = CALEClientSendNegotiationMessage(
1548 bleData->remoteEndpoint->addr);
1550 if (CA_STATUS_OK != res)
1554 "CALEClientSendNegotiationMessage has failed, result [%d]",
1558 g_errorHandler(bleData->remoteEndpoint,
1567 #if defined(__TIZEN__) || defined(__ANDROID__)
1568 g_mtuSize = CALEClientGetMtuSize(bleData->remoteEndpoint->addr);
1570 OIC_LOG_V(INFO, CALEADAPTER_TAG, "MTU size [%d]", g_mtuSize);
1572 uint32_t midPacketCount = 0;
1573 size_t remainingLen = 0;
1574 size_t totalLength = 0;
1575 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1577 CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
1583 if (CA_STATUS_OK != result)
1585 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1586 "CAGenerateVariableForFragmentation failed, result [%d]", result);
1589 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1594 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1595 "Packet info: data size[%d] midPacketCount[%u] remainingLen[%zu] totalLength[%zu]",
1596 bleData->dataLen, midPacketCount, remainingLen, totalLength);
1598 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1599 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1601 if (NULL != bleData->remoteEndpoint) //Unicast Data
1603 secureFlag = (bleData->remoteEndpoint->flags & CA_SECURE) ?
1604 CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
1606 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This Packet is secure? %d", secureFlag);
1607 result = CAGenerateHeader(dataHeader,
1608 CA_BLE_PACKET_START,
1609 g_localBLESourcePort,
1611 bleData->remoteEndpoint->port);
1613 else //Multicast Data
1615 result = CAGenerateHeader(dataHeader,
1616 CA_BLE_PACKET_START,
1617 g_localBLESourcePort,
1619 CA_BLE_MULTICAST_PORT);
1622 OIC_LOG_V(INFO, CALEADAPTER_TAG, "header info: secureFlag[%X]", secureFlag);
1624 if (CA_STATUS_OK != result)
1626 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1627 "CAGenerateHeader failed, result [%d]", result);
1630 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1635 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1636 result = CAGenerateHeaderPayloadLength(lengthHeader,
1637 CA_BLE_LENGTH_HEADER_SIZE,
1640 if (CA_STATUS_OK != result)
1642 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1643 "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1646 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1651 uint32_t length = 0;
1652 uint32_t dataLen = 0;
1653 if (g_mtuSize > totalLength)
1655 length = (uint32_t)totalLength;
1656 dataLen = bleData->dataLen;
1661 dataLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1664 result = CAMakeFirstDataSegment(dataSegment,
1665 bleData->data, dataLen,
1666 dataHeader, lengthHeader);
1668 if (CA_STATUS_OK != result)
1670 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1671 "Making data segment failed, result [%d]", result);
1674 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1679 const uint32_t iter = midPacketCount;
1681 if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
1683 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
1684 // Send the first segment with the header.
1686 CAUpdateCharacteristicsToGattServer(
1687 bleData->remoteEndpoint->addr,
1693 if (CA_STATUS_OK != result)
1697 "Update characteristics failed, result [%d]",
1701 g_errorHandler(bleData->remoteEndpoint,
1710 "Client Sent Unicast First Data - data length [%u]",
1713 result = CAGenerateHeader(dataHeader,
1714 CA_BLE_PACKET_NOT_START,
1715 g_localBLESourcePort,
1717 bleData->remoteEndpoint->port);
1719 if (CA_STATUS_OK != result)
1721 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1722 "CAGenerateHeader failed, result [%d]", result);
1725 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1730 for (index = 0; index < iter; index++)
1732 result = CAMakeRemainDataSegment(dataSegment,
1733 g_mtuSize - CA_BLE_HEADER_SIZE,
1740 if (CA_STATUS_OK != result)
1742 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1743 "Making data segment failed, result [%d]", result);
1746 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1751 // Send the remaining header.
1752 result = CAUpdateCharacteristicsToGattServer(
1753 bleData->remoteEndpoint->addr,
1758 if (CA_STATUS_OK != result)
1762 "Update characteristics failed, result [%d]",
1766 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1772 "Client Sent Unicast %d Data - data(mtu) length [%hu]",
1777 if (remainingLen && (totalLength > g_mtuSize))
1779 // send the last segment of the data (Ex: 22 bytes of 622
1780 // bytes of data when MTU is 200)
1781 result = CAMakeRemainDataSegment(dataSegment,
1789 if (CA_STATUS_OK != result)
1791 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1792 "Making data segment failed, result [%d]", result);
1795 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1800 result = CAUpdateCharacteristicsToGattServer(
1801 bleData->remoteEndpoint->addr,
1803 remainingLen + CA_BLE_HEADER_SIZE,
1806 if (CA_STATUS_OK != result)
1808 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1812 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1818 "Client Sent Unicast Last Data - data length [%zu]",
1819 remainingLen + CA_BLE_HEADER_SIZE);
1824 //Sending Mulitcast Data
1825 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Client Sending Multicast Data");
1826 OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
1829 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1832 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
1833 const uint8_t *data,
1834 uint32_t dataLength,
1835 u_arraylist_t *senderInfo)
1837 CALEData_t * const bleData = OICMalloc(sizeof(CALEData_t));
1841 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1845 bleData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
1846 bleData->data = OICCalloc(dataLength + 1, 1);
1848 if (NULL == bleData->data)
1850 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1851 CAFreeLEData(bleData);
1855 memcpy(bleData->data, data, dataLength);
1856 bleData->dataLen = dataLength;
1859 bleData->senderInfo = senderInfo;
1865 static void CAFreeLEData(CALEData_t *bleData)
1867 VERIFY_NON_NULL_VOID(bleData, CALEADAPTER_TAG, "Param bleData is NULL");
1869 CAFreeEndpoint(bleData->remoteEndpoint);
1870 OICFree(bleData->data);
1874 static void CALEDataDestroyer(void *data, uint32_t size)
1876 if ((size_t)size < sizeof(CALEData_t *))
1878 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1879 "Destroy data too small %p %d", data, size);
1881 CALEData_t *ledata = (CALEData_t *) data;
1883 CAFreeLEData(ledata);
1887 #ifdef SINGLE_THREAD
1888 static void CALEDataReceiverHandlerSingleThread(const uint8_t *data,
1891 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1893 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1896 CABLEPacketStart_t startFlag = CA_BLE_PACKET_NOT_START;
1897 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1898 uint16_t sourcePort = 0;
1899 uint16_t destPort = 0;
1901 CAParseHeader(data, &startFlag, &sourcePort, &secureFlag, &destPort);
1902 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1903 "header info: startFlag[%X] sourcePort[%d] secureFlag[%X] destPort[%d]",
1904 startFlag, sourcePort, secureFlag, destPort);
1906 if (destPort != g_localBLESourcePort && destPort != CA_BLE_MULTICAST_PORT)
1908 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1909 "this packet is not valid for this app(port mismatch[mine:%d, packet:%d])",
1910 g_localBLESourcePort, destPort);
1916 if (g_singleThreadReceiveData)
1918 OIC_LOG(ERROR, CALEADAPTER_TAG,
1919 "This packet is start packet but exist senderInfo. Remove senderInfo");
1920 OICFree(g_singleThreadReceiveData->defragData);
1921 OICFree(g_singleThreadReceiveData);
1922 g_singleThreadReceiveData = NULL;
1925 uint32_t totalLength = 0;
1926 CAParseHeaderPayloadLength(data, CA_BLE_LENGTH_HEADER_SIZE, &totalLength);
1928 g_singleThreadReceiveData = OICMalloc(sizeof(CABLESenderInfo_t));
1930 if (!g_singleThreadReceiveData)
1932 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
1935 g_singleThreadReceiveData->recvDataLen = 0;
1936 g_singleThreadReceiveData->totalDataLen = 0;
1937 g_singleThreadReceiveData->defragData = NULL;
1938 g_singleThreadReceiveData->remoteEndpoint = NULL;
1940 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
1942 g_singleThreadReceiveData->totalDataLen = totalLength;
1944 if (!(g_singleThreadReceiveData->totalDataLen))
1946 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
1947 OICFree(g_singleThreadReceiveData);
1951 size_t dataOnlyLen = dataLen - (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE);
1952 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
1953 g_singleThreadReceiveData->totalDataLen);
1954 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%u] bytes",
1957 g_singleThreadReceiveData->defragData =
1958 OICCalloc(g_singleThreadReceiveData->totalDataLen + 1,
1959 sizeof(*g_singleThreadReceiveData->defragData));
1961 if (NULL == g_singleThreadReceiveData->defragData)
1963 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
1964 OICFree(g_singleThreadReceiveData);
1968 if (g_singleThreadReceiveData->recvDataLen + dataOnlyLen
1969 > g_singleThreadReceiveData->totalDataLen)
1971 OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
1972 OICFree(g_singleThreadReceiveData->defragData);
1973 OICFree(g_singleThreadReceiveData);
1976 memcpy(g_singleThreadReceiveData->defragData,
1977 data + (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE),
1979 g_singleThreadReceiveData->recvDataLen += dataOnlyLen;
1983 size_t dataOnlyLen = dataLen - CA_BLE_HEADER_SIZE;
1984 if (g_singleThreadReceiveData->recvDataLen + dataOnlyLen
1985 > g_singleThreadReceiveData->totalDataLen)
1987 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1988 "Data Length exceeding error!! Receiving [%d] total length [%d]",
1989 g_singleThreadReceiveData->recvDataLen + dataOnlyLen,
1990 g_singleThreadReceiveData->totalDataLen);
1991 OICFree(g_singleThreadReceiveData->defragData);
1992 OICFree(g_singleThreadReceiveData);
1995 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]",
1997 memcpy(g_singleThreadReceiveData->defragData + g_singleThreadReceiveData->recvDataLen,
1998 data + CA_BLE_HEADER_SIZE,
2000 g_singleThreadReceiveData->recvDataLen += dataOnlyLen;
2001 OIC_LOG_V(INFO, CALEADAPTER_TAG, "totalDatalength [%d] received Datalen [%d]",
2002 g_singleThreadReceiveData->totalDataLen, g_singleThreadReceiveData->recvDataLen);
2004 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2007 static CAResult_t CALEServerSendDataSingleThread(const uint8_t *data,
2010 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2012 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
2014 uint32_t midPacketCount = 0;
2015 size_t remainingLen = 0;
2016 size_t totalLength = 0;
2017 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
2019 CAResult_t result = CAGenerateVariableForFragmentation(dataLen,
2025 if (CA_STATUS_OK != result)
2027 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2028 "CAGenerateVariableForFragmentation failed, result [%d]", result);
2032 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2033 "Packet info: data size[%d] midPacketCount[%d] remainingLen[%d] totalLength[%d]",
2034 dataLen, midPacketCount, remainingLen, totalLength);
2038 "Server total Data length with header is [%u]",
2041 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
2042 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
2044 result = CAGenerateHeader(dataHeader,
2045 CA_BLE_PACKET_START,
2046 g_localBLESourcePort,
2047 CA_BLE_PACKET_NON_SECURE,
2048 CA_BLE_MULTICAST_PORT);
2050 if (CA_STATUS_OK != result)
2052 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2053 "CAGenerateHeader failed, result [%d]", result);
2057 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
2058 result = CAGenerateHeaderPayloadLength(lengthHeader,
2059 CA_BLE_LENGTH_HEADER_SIZE,
2062 if (CA_STATUS_OK != result)
2064 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2065 "CAGenerateHeaderPayloadLength failed, result [%d]", result);
2069 uint32_t length = 0;
2070 uint32_t dataOnlyLen = 0;
2071 if (g_mtuSize > totalLength)
2073 length = totalLength;
2074 dataOnlyLen = dataLen;
2079 dataOnlyLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
2082 result = CAMakeFirstDataSegment(dataSegment,
2084 dataHeader, lengthHeader);
2086 if (CA_STATUS_OK != result)
2088 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2089 "Making data segment failed, result [%d]", result);
2093 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
2094 result = CAUpdateCharacteristicsToAllGattClients(dataSegment, length);
2095 if (CA_STATUS_OK != result)
2097 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
2104 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
2106 result = CAGenerateHeader(dataHeader,
2107 CA_BLE_PACKET_NOT_START,
2108 g_localBLESourcePort,
2109 CA_BLE_PACKET_NON_SECURE,
2110 CA_BLE_MULTICAST_PORT);
2112 if (CA_STATUS_OK != result)
2114 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2115 "CAGenerateHeader failed, result [%d]", result);
2119 const uint32_t dataLimit = midPacketCount;
2120 for (uint32_t iter = 0; iter < dataLimit; iter++)
2122 result = CAMakeRemainDataSegment(dataSegment,
2123 g_mtuSize - CA_BLE_HEADER_SIZE,
2130 if (CA_STATUS_OK != result)
2132 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2133 "Making data segment failed, result [%d]", result);
2137 result = CAUpdateCharacteristicsToAllGattClients(
2141 if (CA_STATUS_OK != result)
2143 OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2150 if (remainingLen && (totalLength > g_mtuSize))
2152 // send the last segment of the data
2153 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
2155 result = CAMakeRemainDataSegment(dataSegment,
2163 if (CA_STATUS_OK != result)
2165 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2166 "Making data segment failed, result [%d]", result);
2170 result = CAUpdateCharacteristicsToAllGattClients(
2172 remainingLen + CA_BLE_HEADER_SIZE);
2174 if (CA_STATUS_OK != result)
2176 OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2186 static CAResult_t CAInitLEAdapterMutex()
2188 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2190 if (NULL == g_bleIsServerMutex)
2192 g_bleIsServerMutex = oc_mutex_new();
2193 if (NULL == g_bleIsServerMutex)
2195 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2196 return CA_STATUS_FAILED;
2200 if (NULL == g_bleLocalAddressMutex)
2202 g_bleLocalAddressMutex = oc_mutex_new();
2203 if (NULL == g_bleLocalAddressMutex)
2205 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2206 CATerminateLEAdapterMutex();
2207 return CA_STATUS_FAILED;
2213 if (NULL == g_bleServerReceiveDataMutex)
2215 g_bleServerReceiveDataMutex = oc_mutex_new();
2216 if (NULL == g_bleServerReceiveDataMutex)
2218 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2219 return CA_STATUS_FAILED;
2223 if (NULL == g_bleClientReceiveDataMutex)
2225 g_bleClientReceiveDataMutex = oc_mutex_new();
2226 if (NULL == g_bleClientReceiveDataMutex)
2228 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2229 return CA_STATUS_FAILED;
2233 if (NULL == g_senderInfoMutex)
2235 g_senderInfoMutex = oc_mutex_new();
2236 if (NULL == g_senderInfoMutex)
2238 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2239 return CA_STATUS_FAILED;
2243 return CA_STATUS_OK;
2246 static void CATerminateLEAdapterMutex()
2248 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2250 oc_mutex_free(g_bleIsServerMutex);
2251 g_bleIsServerMutex = NULL;
2254 oc_mutex_free(g_bleLocalAddressMutex);
2255 g_bleLocalAddressMutex = NULL;
2257 oc_mutex_free(g_bleServerReceiveDataMutex);
2258 g_bleServerReceiveDataMutex = NULL;
2260 oc_mutex_free(g_bleClientReceiveDataMutex);
2261 g_bleClientReceiveDataMutex = NULL;
2263 oc_mutex_free(g_senderInfoMutex);
2264 g_senderInfoMutex = NULL;
2268 * Starting LE connectivity adapters.
2270 * As its peer to peer it does not require to start any servers.
2272 * @return ::CA_STATUS_OK or Appropriate error code.
2274 static CAResult_t CAStartLE();
2277 * Start listening server for receiving multicast search requests.
2279 * Transport Specific Behavior:
2280 * LE Starts GATT Server with prefixed UUID and Characteristics
2281 * per OIC Specification.
2282 * @return ::CA_STATUS_OK or Appropriate error code.
2284 static CAResult_t CAStartLEListeningServer();
2287 * Stops listening server from receiving multicast search requests.
2289 * Transport Specific Behavior:
2290 * LE Starts GATT Server with prefixed UUID and Characteristics
2291 * per OIC Specification.
2292 * @return ::CA_STATUS_OK or Appropriate error code.
2294 static CAResult_t CAStopLEListeningServer();
2297 * Sarting discovery of servers for receiving multicast
2300 * Transport Specific Behavior:
2301 * LE Starts GATT Server with prefixed UUID and Characteristics
2302 * per OIC Specification.
2304 * @return ::CA_STATUS_OK or Appropriate error code
2306 static CAResult_t CAStartLEDiscoveryServer();
2309 * Send data to the endpoint using the adapter connectivity.
2311 * @param[in] endpoint Remote Endpoint information (like MAC address,
2312 * reference URI and connectivity type) to which
2313 * the unicast data has to be sent.
2314 * @param[in] data Data which required to be sent.
2315 * @param[in] dataLen Size of data to be sent.
2317 * @note dataLen must be > 0.
2319 * @return The number of bytes sent on the network, or -1 on error.
2321 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2324 CADataType_t dataType);
2327 * Send multicast data to the endpoint using the LE connectivity.
2329 * @param[in] endpoint Remote Endpoint information to which the
2330 * multicast data has to be sent.
2331 * @param[in] data Data which required to be sent.
2332 * @param[in] dataLen Size of data to be sent.
2334 * @note dataLen must be > 0.
2336 * @return The number of bytes sent on the network, or -1 on error.
2338 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
2341 CADataType_t dataType);
2344 * Get LE Connectivity network information.
2346 * @param[out] info Local connectivity information structures.
2347 * @param[out] size Number of local connectivity structures.
2349 * @return ::CA_STATUS_OK or Appropriate error code.
2351 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info,
2355 * Read Synchronous API callback.
2357 * @return ::CA_STATUS_OK or Appropriate error code.
2359 static CAResult_t CAReadLEData();
2362 * Stopping the adapters and close socket connections.
2364 * LE Stops all GATT servers and GATT Clients.
2366 * @return ::CA_STATUS_OK or Appropriate error code.
2368 static CAResult_t CAStopLE();
2371 * Terminate the LE connectivity adapter.
2373 * Configuration information will be deleted from further use.
2375 static void CATerminateLE();
2378 * This function will receive the data from the GattServer and add the
2379 * data to the Server receiver queue.
2381 * @param[in] remoteAddress Remote address of the device from where
2383 * @param[in] data Actual data received from the remote
2385 * @param[in] dataLength Length of the data received from the
2387 * @param[in] sentLength Length of the data sent from the remote
2390 * @return ::CA_STATUS_OK or Appropriate error code.
2391 * @retval ::CA_STATUS_OK Successful.
2392 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2393 * @retval ::CA_STATUS_FAILED Operation failed.
2396 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
2397 const uint8_t *data,
2398 uint32_t dataLength,
2399 uint32_t *sentLength);
2402 * This function will receive the data from the GattClient and add the
2403 * data into the Client receiver queue.
2405 * @param[in] remoteAddress Remote address of the device from where
2407 * @param[in] data Actual data recevied from the remote
2409 * @param[in] dataLength Length of the data received from the
2411 * @param[in] sentLength Length of the data sent from the remote
2414 * @return ::CA_STATUS_OK or Appropriate error code.
2415 * @retval ::CA_STATUS_OK Successful.
2416 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2417 * @retval ::CA_STATUS_FAILED Operation failed.
2419 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
2420 const uint8_t *data,
2421 uint32_t dataLength,
2422 uint32_t *sentLength);
2425 * Set the NetworkPacket received callback to CA layer from adapter
2428 * @param[in] callback Callback handle sent from the upper layer.
2430 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
2433 * Push the data from CA layer to the Sender processor queue.
2435 * @param[in] remoteEndpoint Remote endpoint information of the
2437 * @param[in] data Data to be transmitted from LE.
2438 * @param[in] dataLen Length of the Data being transmitted.
2440 * @return ::CA_STATUS_OK or Appropriate error code.
2441 * @retval ::CA_STATUS_OK Successful.
2442 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2443 * @retval ::CA_STATUS_FAILED Operation failed.
2445 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
2446 const uint8_t *data,
2450 * Push the data from CA layer to the Sender processor queue.
2452 * @param[in] remoteEndpoint Remote endpoint information of the
2454 * @param[in] data Data to be transmitted from LE.
2455 * @param[in] dataLen Length of the Data being transmitted.
2457 * @return ::CA_STATUS_OK or Appropriate error code.
2458 * @retval ::CA_STATUS_OK Successful.
2459 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2460 * @retval ::CA_STATUS_FAILED Operation failed.
2462 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
2463 const uint8_t *data,
2466 static CAResult_t CALEAdapterGattServerStart()
2468 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2469 CAResult_t result = CA_STATUS_FAILED;
2471 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2473 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2474 caglobals.bleFlags);
2475 return CA_STATUS_OK;
2478 #ifndef DISABLE_BLE_SERVER
2479 OIC_LOG_V(INFO, CALEADAPTER_TAG, "Starting LE GATT Server");
2480 result = CAStartLEGattServer();
2483 #ifndef SINGLE_THREAD
2485 Don't start the server side sending queue thread until the
2486 server itself has actually started.
2488 if (CA_STATUS_OK == result)
2490 result = CAQueueingThreadStart(g_bleServerSendQueueHandle);
2491 if (CA_STATUS_OK != result)
2495 "Unable to start server queuing thread (%d)",
2504 static CAResult_t CALEAdapterGattServerStop()
2506 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2508 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2510 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2511 caglobals.bleFlags);
2512 return CA_STATUS_OK;
2515 #ifndef SINGLE_THREAD
2517 CAResult_t res = CAQueueingThreadStop(g_bleServerSendQueueHandle);
2518 if (CA_STATUS_OK != res)
2520 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAQueueingThreadStop has failed");
2522 res = CAStopLEGattServer();
2523 if (CA_STATUS_OK != res)
2525 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAStopLEGattServer has failed");
2530 return CAStopLEGattServer();
2534 static CAResult_t CALEAdapterGattClientStart()
2536 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2538 CAResult_t result = CAStartLEGattClient();
2540 #ifndef SINGLE_THREAD
2542 Don't start the client side sending queue thread until the
2543 client itself has actually started.
2545 if (CA_STATUS_OK == result)
2547 result = CAQueueingThreadStart(g_bleClientSendQueueHandle);
2548 if (CA_STATUS_OK != result)
2552 "Unable to start client queuing thread");
2560 static CAResult_t CALEAdapterGattClientStop()
2562 #ifndef SINGLE_THREAD
2563 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2564 CAStopLEGattClient();
2566 CAResult_t result = CAQueueingThreadStop(g_bleClientSendQueueHandle);
2570 CAStopLEGattClient();
2572 return CA_STATUS_OK;
2576 #ifdef __WITH_DTLS__
2577 static ssize_t CALESecureSendDataCB(CAEndpoint_t *endpoint, const void *data, size_t dataLen)
2579 VERIFY_NON_NULL(endpoint, CALEADAPTER_TAG, "endpoint is NULL");
2580 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "data is NULL");
2581 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2582 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "encrypted datalen = %zd", dataLen);
2585 CADataType_t dataType = g_dataType;
2588 if (ADAPTER_SERVER == g_adapterType ||
2589 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2591 result = CALEAdapterServerSendData(endpoint, data, dataLen);
2592 if (CA_STATUS_OK != result)
2594 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed" );
2598 g_errorHandler(endpoint, data, dataLen, result);
2602 ret = (ssize_t)dataLen;
2604 else if (ADAPTER_CLIENT == g_adapterType ||
2605 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
2606 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
2608 result = CALEAdapterClientSendData(endpoint, data, dataLen);
2609 if (CA_STATUS_OK != result)
2611 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
2615 g_errorHandler(endpoint, data, dataLen, result);
2619 ret = (ssize_t)dataLen;
2623 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2624 "Can't Send Message adapterType = %d, dataType = %d", g_adapterType, dataType);
2627 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2631 CAResult_t CALESecureReceiveDataCB(const CASecureEndpoint_t *sep, const void *data,
2634 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2636 VERIFY_NON_NULL(sep, CALEADAPTER_TAG, "sep is NULL");
2637 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "data is NULL");
2639 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2640 "Secure Data Receive - decrypted datalen = %zd", dataLen);
2644 OIC_LOG(ERROR, CALEADAPTER_TAG, "incorrect dataLen, derecypt fail !");
2645 return CA_STATUS_INVALID_PARAM;
2648 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2650 CAResult_t res = CA_STATUS_OK;
2651 if (g_networkPacketReceivedCallback)
2653 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2654 "[CALESecureReceiveDataCB] Secure flags = %d, %x",
2655 sep->endpoint.flags, sep->endpoint.flags);
2656 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2657 "[CALESecureReceiveDataCB] Received data up !");
2658 res = g_networkPacketReceivedCallback(sep, data, dataLen);
2659 if (CA_STATUS_OK != res)
2661 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Error parsing CoAP data, res = %d", res);
2668 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
2669 CANetworkPacketReceivedCallback reqRespCallback,
2670 CAAdapterChangeCallback netCallback,
2671 CAConnectionChangeCallback connCallback,
2672 CAErrorHandleCallback errorCallback,
2673 ca_thread_pool_t handle)
2675 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2678 VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null");
2679 VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null");
2680 VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null");
2681 VERIFY_NON_NULL(connCallback, CALEADAPTER_TAG, "ConnectionChange Callback is null");
2683 CAResult_t result = CA_STATUS_OK;
2684 result = CAInitLEAdapterMutex();
2685 if (CA_STATUS_OK != result)
2687 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
2688 return CA_STATUS_FAILED;
2691 result = CAInitializeLENetworkMonitor();
2692 if (CA_STATUS_OK != result)
2694 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
2695 return CA_STATUS_FAILED;
2697 CAInitializeLEAdapter();
2699 result = CAInitializeLEGattClient();
2700 if (CA_STATUS_OK != result)
2702 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattClient() failed");
2703 return CA_STATUS_FAILED;
2706 CASetLEClientThreadPoolHandle(handle);
2708 CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
2709 CASetLEServerThreadPoolHandle(handle);
2710 result = CAInitializeLEGattServer();
2711 if (CA_STATUS_OK != result)
2713 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattServer() failed");
2714 return CA_STATUS_FAILED;
2717 CASetLEAdapterThreadPoolHandle(handle);
2718 CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
2719 CASetLEReqRespAdapterCallback(reqRespCallback);
2721 CASetBLEClientErrorHandleCallback(CALEErrorHandler);
2722 CASetBLEServerErrorHandleCallback(CALEErrorHandler);
2723 CALERegisterNetworkNotifications(netCallback, connCallback);
2725 g_errorHandler = errorCallback;
2727 #ifdef __WITH_DTLS__
2728 if (CA_STATUS_OK != CAinitSslAdapter())
2730 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to init SSL adapter");
2734 CAsetSslAdapterCallbacks(CALESecureReceiveDataCB, CALESecureSendDataCB,
2735 CA_ADAPTER_GATT_BTLE);
2739 static const CAConnectivityHandler_t connHandler =
2741 .startAdapter = CAStartLE,
2742 .stopAdapter = CAStopLE,
2743 .startListenServer = CAStartLEListeningServer,
2744 .stopListenServer = CAStopLEListeningServer,
2745 .startDiscoveryServer = CAStartLEDiscoveryServer,
2746 .sendData = CASendLEUnicastData,
2747 .sendDataToAll = CASendLEMulticastData,
2748 .GetnetInfo = CAGetLEInterfaceInformation,
2749 .readData = CAReadLEData,
2750 .terminate = CATerminateLE,
2751 .cType = CA_ADAPTER_GATT_BTLE
2754 registerCallback(connHandler);
2755 return CA_STATUS_OK;
2758 static CAResult_t CAStartLE()
2760 return CAStartLEAdapter();
2763 static CAResult_t CAStopLE()
2766 #ifndef SINGLE_THREAD
2770 oc_mutex_lock(g_bleIsServerMutex);
2771 switch (g_adapterType)
2773 case ADAPTER_SERVER:
2774 CALEAdapterGattServerStop();
2776 case ADAPTER_CLIENT:
2777 CALEAdapterGattClientStop();
2779 case ADAPTER_BOTH_CLIENT_SERVER:
2780 CALEAdapterGattServerStop();
2781 CALEAdapterGattClientStop();
2786 oc_mutex_unlock(g_bleIsServerMutex);
2787 return CAStopLEAdapter();
2790 static void CATerminateLE()
2792 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2794 CASetLEReqRespServerCallback(NULL);
2795 CASetLEReqRespClientCallback(NULL);
2796 CALERegisterNetworkNotifications(NULL, NULL);
2797 CASetLEReqRespAdapterCallback(NULL);
2798 CATerminateLENetworkMonitor();
2800 oc_mutex_lock(g_bleIsServerMutex);
2801 switch (g_adapterType)
2803 case ADAPTER_SERVER:
2804 CATerminateLEGattServer();
2806 case ADAPTER_CLIENT:
2807 CATerminateLEGattClient();
2809 case ADAPTER_BOTH_CLIENT_SERVER:
2810 CATerminateLEGattServer();
2811 CATerminateLEGattClient();
2816 g_adapterType = ADAPTER_EMPTY;
2817 oc_mutex_unlock(g_bleIsServerMutex);
2819 #ifndef SINGLE_THREAD
2820 CATerminateLEQueues();
2823 #ifdef __WITH_DTLS__
2824 CAsetSslAdapterCallbacks(NULL, NULL, CA_ADAPTER_GATT_BTLE);
2827 CATerminateLEAdapterMutex();
2830 static CAResult_t CAStartLEListeningServer()
2832 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2834 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2836 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2837 caglobals.bleFlags);
2838 return CA_STATUS_OK;
2841 #ifndef ROUTING_GATEWAY
2842 CAResult_t result = CA_STATUS_OK;
2843 #ifndef SINGLE_THREAD
2844 result = CAInitLEServerQueues();
2845 if (CA_STATUS_OK != result)
2847 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
2852 oc_mutex_lock(g_bleIsServerMutex);
2853 switch (g_adapterType)
2855 case ADAPTER_CLIENT:
2856 g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2858 case ADAPTER_BOTH_CLIENT_SERVER:
2861 g_adapterType = ADAPTER_SERVER;
2863 oc_mutex_unlock(g_bleIsServerMutex);
2865 result = CAGetLEAdapterState();
2866 if (CA_STATUS_OK != result)
2868 if (CA_ADAPTER_NOT_ENABLED == result)
2872 "Listen Server will be started once BT Adapter is enabled");
2873 result = CA_STATUS_OK;
2878 result = CALEAdapterGattServerStart();
2881 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2884 // Routing Gateway only supports BLE client mode.
2885 OIC_LOG(ERROR, CALEADAPTER_TAG, "LE server not supported in Routing Gateway");
2886 return CA_NOT_SUPPORTED;
2890 static CAResult_t CAStopLEListeningServer()
2892 OIC_LOG(ERROR, CALEADAPTER_TAG, "Listen server stop not supported.");
2893 return CA_NOT_SUPPORTED;
2896 static CAResult_t CAStartLEDiscoveryServer()
2898 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2899 CAResult_t result = CA_STATUS_OK;
2900 #ifndef SINGLE_THREAD
2901 result = CAInitLEClientQueues();
2902 if (CA_STATUS_OK != result)
2904 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
2909 oc_mutex_lock(g_bleIsServerMutex);
2910 switch (g_adapterType)
2912 case ADAPTER_SERVER:
2913 g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2915 case ADAPTER_BOTH_CLIENT_SERVER:
2918 g_adapterType = ADAPTER_CLIENT;
2920 oc_mutex_unlock(g_bleIsServerMutex);
2922 result = CAGetLEAdapterState();
2923 if (CA_STATUS_OK != result)
2925 if (CA_ADAPTER_NOT_ENABLED == result)
2929 "Discovery Server will be started once BT Adapter is enabled");
2930 result = CA_STATUS_OK;
2935 result = CALEAdapterGattClientStart();
2938 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2942 static CAResult_t CAReadLEData()
2944 #ifdef SINGLE_THREAD
2947 return CA_STATUS_OK;
2950 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2953 CADataType_t dataType)
2955 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2956 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "type(%d)", dataType);
2959 VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
2960 VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2962 CAResult_t result = CA_STATUS_FAILED;
2964 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2965 if (ADAPTER_EMPTY == g_adapterType)
2967 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2970 oc_mutex_lock(g_bleIsServerMutex);
2971 if (ADAPTER_SERVER == g_adapterType ||
2972 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2974 #ifdef __WITH_DTLS__
2975 if (endpoint && endpoint->flags & CA_SECURE)
2977 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2978 "Response Data or server - secured data send(caadapternetdtlsencrypt) call");
2979 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2980 g_dataType = dataType;
2981 oc_mutex_unlock(g_bleIsServerMutex);
2983 result = CAencryptSsl(endpoint, (void *)data, dataLen);
2984 if (CA_STATUS_OK != result)
2986 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
2993 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2994 "server or both - none secured data send(CALEAdapterServerSendData) call");
2995 result = CALEAdapterServerSendData(endpoint, data, dataLen);
2998 result = CALEAdapterServerSendData(endpoint, data, dataLen);
3000 if (CA_STATUS_OK != result)
3002 oc_mutex_unlock(g_bleIsServerMutex);
3003 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed");
3006 g_errorHandler(endpoint, data, dataLen, result);
3012 else if (ADAPTER_CLIENT == g_adapterType ||
3013 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
3014 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
3016 #ifdef __WITH_DTLS__
3017 if (endpoint && endpoint->flags & CA_SECURE)
3019 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3020 "Request Data or client - secured data send(caadapternetdtlsencrypt) call");
3021 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
3022 g_dataType = dataType;
3023 oc_mutex_unlock(g_bleIsServerMutex);
3025 result = CAencryptSsl(endpoint, (void *)data, dataLen);
3026 if (CA_STATUS_OK != result)
3028 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
3035 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3036 "client or both - none secured data send(CALEAdapterClientSendData) call");
3037 result = CALEAdapterClientSendData(endpoint, data, dataLen);
3040 result = CALEAdapterClientSendData(endpoint, data, dataLen);
3042 if (CA_STATUS_OK != result)
3044 oc_mutex_unlock(g_bleIsServerMutex);
3045 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
3049 g_errorHandler(endpoint, data, dataLen, result);
3054 oc_mutex_unlock(g_bleIsServerMutex);
3056 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3060 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
3063 CADataType_t dataType)
3065 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3068 VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
3072 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
3076 CAResult_t result = CA_STATUS_FAILED;
3078 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
3079 if (ADAPTER_EMPTY == g_adapterType)
3081 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
3084 oc_mutex_lock(g_bleIsServerMutex);
3085 if (ADAPTER_SERVER == g_adapterType ||
3086 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
3088 result = CALEAdapterServerSendData(NULL, data, dataLen);
3089 if (CA_STATUS_OK != result)
3091 oc_mutex_unlock(g_bleIsServerMutex);
3093 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data for server failed" );
3097 g_errorHandler(endpoint, data, dataLen, result);
3103 if (ADAPTER_CLIENT == g_adapterType ||
3104 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
3105 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
3107 result = CALEAdapterClientSendData(NULL, data, dataLen);
3108 if (CA_STATUS_OK != result)
3110 oc_mutex_unlock(g_bleIsServerMutex);
3112 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data for client failed" );
3116 g_errorHandler(endpoint, data, dataLen, result);
3121 oc_mutex_unlock(g_bleIsServerMutex);
3123 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3127 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
3129 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3131 VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
3133 char *local_address = NULL;
3135 CAResult_t res = CAGetLEAddress(&local_address);
3136 if (CA_STATUS_OK != res)
3138 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
3142 if (NULL == local_address)
3144 OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
3145 return CA_STATUS_FAILED;
3149 (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
3150 if (NULL == (*info))
3152 OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
3153 OICFree(local_address);
3154 return CA_STATUS_FAILED;
3157 size_t local_address_len = strlen(local_address);
3159 if(local_address_len >= sizeof(g_localBLEAddress) ||
3160 local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
3162 OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
3164 OICFree(local_address);
3165 return CA_STATUS_FAILED;
3168 OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
3169 oc_mutex_lock(g_bleLocalAddressMutex);
3170 OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
3171 oc_mutex_unlock(g_bleLocalAddressMutex);
3173 (*info)->adapter = CA_ADAPTER_GATT_BTLE;
3175 OICFree(local_address);
3177 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3178 return CA_STATUS_OK;
3181 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
3182 CAConnectionChangeCallback connCallback)
3184 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3186 g_networkCallback = netCallback;
3187 g_connectionCallback = connCallback;
3188 CAResult_t res = CA_STATUS_OK;
3191 res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
3192 if (CA_STATUS_OK != res)
3194 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
3199 res = CAUnSetLEAdapterStateChangedCb();
3200 if (CA_STATUS_OK != res)
3202 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
3206 if (g_connectionCallback)
3208 res = CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCb);
3209 if (CA_STATUS_OK != res)
3211 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLENWConnectionStateChangedCb failed!");
3216 res = CAUnSetLENWConnectionStateChangedCb();
3217 if (CA_STATUS_OK != res)
3219 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUnSetLENWConnectionStateChangedCb failed!");
3223 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3227 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
3230 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3232 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3235 CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE };
3236 OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), address);
3239 oc_mutex_lock(g_bleIsServerMutex);
3240 switch (g_adapterType)
3242 case ADAPTER_SERVER:
3243 CALEGattServerConnectionStateChanged(isConnected, address);
3245 case ADAPTER_CLIENT:
3246 CALEGattConnectionStateChanged(isConnected, address);
3248 case ADAPTER_BOTH_CLIENT_SERVER:
3249 CALEGattConnectionStateChanged(isConnected, address);
3250 CALEGattServerConnectionStateChanged(isConnected, address);
3255 oc_mutex_unlock(g_bleIsServerMutex);
3260 #ifndef SINGLE_THREAD
3261 if(g_bleClientSenderInfo)
3263 CALERemoveReceiveQueueData(g_bleClientSenderInfo, address);
3266 if(g_bleServerSenderInfo)
3268 CALERemoveReceiveQueueData(g_bleServerSenderInfo, address);
3271 // remove data of send queue.
3272 if (g_bleClientSendQueueHandle)
3274 CALERemoveSendQueueData(g_bleClientSendQueueHandle, address);
3277 if (g_bleServerSendQueueHandle)
3279 CALERemoveSendQueueData(g_bleServerSendQueueHandle, address);
3283 #ifdef __WITH_DTLS__
3284 #if defined(__TIZEN__) && !defined(SINGLE_THREAD)
3285 // CAcloseSslConnection returns CAResult_t instead of void*, but the size is the same and crash shouldn't occur
3287 pthread_attr_t attr;
3288 int initAttrRes = -1;
3289 int pthreadCreateRes = -1;
3290 int detachStatusRes = -1;
3291 int memoryAllocationRes = -1;
3295 initAttrRes = pthread_attr_init(&attr);
3296 if (initAttrRes != 0)
3300 CAEndpoint_t *localEndpointCpyPtr = OICMalloc(sizeof(CAEndpoint_t));
3302 if(NULL == localEndpointCpyPtr)
3304 memoryAllocationRes = -1;
3309 memoryAllocationRes = 0;
3312 (*localEndpointCpyPtr) = localEndpoint;
3313 // this piece of code is reached on the main thread
3314 // CAcloseSslConnection might wait for too long (network + mutexes) and watchdog might kill it
3315 // Asynchronous call protects this function from watchdog
3316 pthreadCreateRes = pthread_create(&ccThread, &attr, (void *(*)(void*))&CAcloseSslConnectionFreeEndpoint, (void*)localEndpointCpyPtr);
3318 if (pthreadCreateRes != 0)
3322 detachStatusRes = pthread_detach(ccThread);
3325 // regardless of CAcloseSslConnection result, the function will continue and g_connectionCallback will be called
3326 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "CAcloseSslConnection pthread_init [%d], mem_alloc [%d] pthread_create [%d], pthread_detach [%d]",
3327 initAttrRes, memoryAllocationRes, pthreadCreateRes, detachStatusRes);
3329 CAcloseSslConnection(&localEndpoint);
3334 if (g_connectionCallback)
3336 g_connectionCallback(&localEndpoint, isConnected);
3339 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3342 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
3344 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3346 if (CA_ADAPTER_ENABLED == adapter_state)
3348 oc_mutex_lock(g_bleIsServerMutex);
3349 switch (g_adapterType)
3351 case ADAPTER_SERVER:
3352 CALEAdapterGattServerStart();
3354 case ADAPTER_CLIENT:
3355 CALEAdapterGattClientStart();
3357 case ADAPTER_BOTH_CLIENT_SERVER:
3358 CALEAdapterGattServerStart();
3359 CALEAdapterGattClientStart();
3364 oc_mutex_unlock(g_bleIsServerMutex);
3368 oc_mutex_lock(g_bleIsServerMutex);
3369 switch (g_adapterType)
3371 case ADAPTER_SERVER:
3372 CALEAdapterGattServerStop();
3374 case ADAPTER_CLIENT:
3375 CALEAdapterGattClientStop();
3377 case ADAPTER_BOTH_CLIENT_SERVER:
3378 CALEAdapterGattServerStop();
3379 CALEAdapterGattClientStop();
3384 oc_mutex_unlock(g_bleIsServerMutex);
3387 if (NULL != g_networkCallback)
3389 g_networkCallback(CA_ADAPTER_GATT_BTLE, adapter_state);
3393 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
3396 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3399 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
3400 const uint8_t *data,
3403 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3404 #ifndef SINGLE_THREAD
3405 VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
3406 "g_bleClientSendQueueHandle is NULL",
3409 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%u]", dataLen);
3411 CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3414 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3415 return CA_MEMORY_ALLOC_FAILED;
3417 // Add message to send queue
3419 CAResult_t res = CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData,
3420 sizeof(CALEData_t));
3421 if (CA_STATUS_OK != res)
3423 CALEDataDestroyer(bleData, sizeof(CALEData_t));
3426 return CA_STATUS_OK;
3429 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
3430 const uint8_t *data,
3433 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3435 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3437 #ifdef SINGLE_THREAD
3438 if (!CAIsLEConnected())
3440 OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
3441 return CA_STATUS_FAILED;
3444 CAResult_t result = CALEServerSendDataSingleThread(data, dataLen);
3445 if (CA_STATUS_OK != result)
3447 OIC_LOG(ERROR, CALEADAPTER_TAG, "CALEServerSendDataSingleThread failed");
3448 return CA_STATUS_FAILED;
3451 VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
3452 "g_bleServerSendQueueHandle is NULL",
3455 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
3457 CALEData_t * const bleData =
3458 CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3462 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3463 return CA_MEMORY_ALLOC_FAILED;
3466 // Add message to send queue
3468 CAResult_t res = CAQueueingThreadAddData(g_bleServerSendQueueHandle,
3470 sizeof(CALEData_t));
3471 if (CA_STATUS_OK != res)
3473 CALEDataDestroyer(bleData, sizeof(CALEData_t));
3476 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3477 return CA_STATUS_OK;
3480 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
3481 const uint8_t *data,
3482 uint32_t dataLength,
3483 uint32_t *sentLength)
3485 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3488 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3489 VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3491 #ifdef SINGLE_THREAD
3492 CALEDataReceiverHandlerSingleThread(data, dataLength);
3494 if (g_singleThreadReceiveData->totalDataLen == g_singleThreadReceiveData->recvDataLen)
3496 if(g_networkPacketReceivedCallback)
3498 // will be filled by upper layer
3499 const CASecureEndpoint_t endpoint =
3500 { .endpoint = { .adapter = CA_ADAPTER_GATT_BTLE } };
3502 g_networkPacketReceivedCallback(&endpoint,
3503 g_singleThreadReceiveData->defragData,
3504 g_singleThreadReceiveData->recvDataLen);
3506 g_singleThreadReceiveData->remoteEndpoint = NULL;
3507 OICFree(g_singleThreadReceiveData->defragData);
3508 g_singleThreadReceiveData->defragData = NULL;
3509 OICFree(g_singleThreadReceiveData);
3510 g_singleThreadReceiveData = NULL;
3513 VERIFY_NON_NULL_RET(g_bleServerReceiverQueue,
3515 "g_bleServerReceiverQueue",
3518 //Add message to data queue
3519 CAEndpoint_t * const remoteEndpoint =
3520 CACreateEndpointObject(CA_DEFAULT_FLAGS,
3521 CA_ADAPTER_GATT_BTLE,
3525 if (NULL == remoteEndpoint)
3527 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3528 return CA_STATUS_FAILED;
3531 // Create bleData to add to queue
3534 "Data received from LE Server layer [%d]",
3537 CALEData_t * const bleData =
3538 CACreateLEData(remoteEndpoint, data, dataLength, g_bleServerSenderInfo);
3542 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3543 CAFreeEndpoint(remoteEndpoint);
3544 return CA_MEMORY_ALLOC_FAILED;
3547 CAFreeEndpoint(remoteEndpoint);
3548 // Add message to receiver queue
3549 CAQueueingThreadAddData(g_bleServerReceiverQueue, bleData, sizeof(CALEData_t));
3551 *sentLength = dataLength;
3553 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3554 return CA_STATUS_OK;
3557 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
3558 const uint8_t *data,
3559 uint32_t dataLength,
3560 uint32_t *sentLength)
3563 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3564 VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3565 #ifndef SINGLE_THREAD
3566 VERIFY_NON_NULL_RET(g_bleClientReceiverQueue, CALEADAPTER_TAG,
3567 "g_bleClientReceiverQueue",
3570 //Add message to data queue
3571 CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
3572 CA_ADAPTER_GATT_BTLE,
3574 if (NULL == remoteEndpoint)
3576 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3577 return CA_STATUS_FAILED;
3580 // Create bleData to add to queue
3583 "Data received from LE Client layer [%u]",
3586 CALEData_t * const bleData =
3587 CACreateLEData(remoteEndpoint, data, dataLength, g_bleClientSenderInfo);
3591 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3592 CAFreeEndpoint(remoteEndpoint);
3593 return CA_MEMORY_ALLOC_FAILED;
3596 CAFreeEndpoint(remoteEndpoint);
3597 // Add message to receiver queue
3598 CAQueueingThreadAddData(g_bleClientReceiverQueue, bleData, sizeof(CALEData_t));
3600 *sentLength = dataLength;
3602 return CA_STATUS_OK;
3605 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
3607 g_bleAdapterThreadPool = handle;
3611 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
3613 g_networkPacketReceivedCallback = callback;
3617 static void CALEErrorHandler(const char *remoteAddress,
3618 const uint8_t *data,
3622 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3624 VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
3626 CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS,
3627 CA_ADAPTER_GATT_BTLE,
3631 // if required, will be used to build remote endpoint
3632 g_errorHandler(rep, data, dataLen, result);
3634 CAFreeEndpoint(rep);
3636 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3639 #ifndef SINGLE_THREAD
3640 static bool CALEClearQueueAddressDataContext(void *data, uint32_t size, void *ctx)
3642 if (NULL == data || NULL == ctx)
3647 CALEData_t *caLeData = (CALEData_t *)data;
3648 const char *address = (const char *)ctx;
3650 if (NULL != caLeData && NULL != caLeData->remoteEndpoint)
3652 if (!strcasecmp(caLeData->remoteEndpoint->addr, address))
3660 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle, const char* address)
3662 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
3664 VERIFY_NON_NULL_VOID(queueHandle, CALEADAPTER_TAG, "queueHandle");
3665 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3667 CAResult_t res = CAQueueingThreadClearContextData(queueHandle,
3668 CALEClearQueueAddressDataContext,
3670 if (CA_STATUS_OK != res)
3673 OIC_LOG(ERROR, CALEADAPTER_TAG, "Could not clear the send queue");
3678 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList, const char* address)
3680 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
3682 VERIFY_NON_NULL_VOID(dataInfoList, CALEADAPTER_TAG, "dataInfoList");
3683 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3685 CABLESenderInfo_t *senderInfo = NULL;
3686 uint32_t senderIndex = 0;
3688 u_arraylist_t *portList = u_arraylist_create();
3689 if (CA_STATUS_OK == CALEGetPortsFromSenderInfo(address, dataInfoList, portList))
3691 uint32_t arrayLength = u_arraylist_length(portList);
3692 for (uint32_t i = 0; i < arrayLength; i++)
3694 uint16_t *port = (uint16_t *)u_arraylist_get(portList, i);
3697 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to get port from sender info !");
3698 u_arraylist_destroy(portList);
3702 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "port : %X", *port);
3704 if (CA_STATUS_OK == CALEGetSenderInfo(address, *port,
3705 dataInfoList, &senderInfo,
3708 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3709 "SenderInfo is removed for disconnection");
3710 CALERemoveSenderInfoFromList(dataInfoList, senderInfo);
3711 CALEFreeSenderInfo(senderInfo);
3715 OIC_LOG(DEBUG, CALEADAPTER_TAG, "SenderInfo doesn't exist");
3719 u_arraylist_destroy(portList);
3722 static CAResult_t CALEGetPortsFromSenderInfo(const char *leAddress,
3723 u_arraylist_t *senderInfoList,
3724 u_arraylist_t *portList)
3726 VERIFY_NON_NULL(leAddress,
3728 "NULL BLE address argument");
3730 const uint32_t listLength = u_arraylist_length(senderInfoList);
3731 const uint32_t addrLength = strlen(leAddress);
3733 for (uint32_t index = 0; index < listLength; index++)
3735 CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
3736 if (!info || !(info->remoteEndpoint))
3741 if (!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
3743 uint16_t *port = (uint16_t *)OICMalloc(sizeof(uint16_t));
3746 OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
3747 return CA_MEMORY_ALLOC_FAILED;
3749 *port = info->remoteEndpoint->port;
3750 u_arraylist_add(portList, (void *)port);
3754 if (u_arraylist_length(portList) != 0)
3756 return CA_STATUS_OK;
3760 return CA_STATUS_FAILED;
3765 void CALEStartGattServer()
3767 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3769 oc_mutex_lock(g_bleIsServerMutex);
3770 switch (g_adapterType)
3772 case ADAPTER_SERVER:
3773 CALEAdapterGattServerStart();
3775 case ADAPTER_CLIENT:
3776 CALEAdapterGattClientStart();
3778 case ADAPTER_BOTH_CLIENT_SERVER:
3779 CALEAdapterGattServerStart();
3780 CALEAdapterGattClientStart();
3785 oc_mutex_unlock(g_bleIsServerMutex);
3786 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3789 void CALEStopGattServer()
3791 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3793 oc_mutex_lock(g_bleIsServerMutex);
3794 switch (g_adapterType)
3796 case ADAPTER_SERVER:
3797 CALEAdapterGattServerStop();
3799 case ADAPTER_CLIENT:
3800 CALEAdapterGattClientStop();
3802 case ADAPTER_BOTH_CLIENT_SERVER:
3803 CALEAdapterGattServerStop();
3804 CALEAdapterGattClientStop();
3809 oc_mutex_unlock(g_bleIsServerMutex);
3810 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);