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 * Macro for checking CAResult_t
55 #define VERIFY_CARESULT(res, func, arg1, arg2, arg3) \
56 if (CA_STATUS_OK != res) \
58 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "%s failed, result [%d]", #func, res); \
61 g_errorHandler(arg1, arg2, arg3, res); \
67 * Stores information of all the senders.
69 * This structure will be used to track and defragment all incoming data packet.
74 uint32_t totalDataLen;
76 CAEndpoint_t *remoteEndpoint;
83 ADAPTER_BOTH_CLIENT_SERVER,
89 * mtu size to use in fragmentation logic.
90 * default value is 20 byte.
92 static uint16_t g_mtuSize = CA_DEFAULT_BLE_MTU_SIZE;
95 * Callback to provide the status of the network change to CA layer.
97 static CAAdapterChangeCallback g_networkCallback = NULL;
100 * Callback to provide the status of the connection change to CA layer.
102 static CAConnectionChangeCallback g_connectionCallback = NULL;
105 * Own port value to identify packet owner. Default port value is 1.
107 static uint8_t g_localBLESourcePort = 1;
110 * bleAddress of the local adapter. Value will be initialized to zero,
111 * and will be updated later.
113 static char g_localBLEAddress[18] = { 0 };
116 * Variable to differentiate btw GattServer and GattClient.
118 static CABLEAdapter_t g_adapterType = ADAPTER_EMPTY;
121 static CADataType_t g_dataType = CA_REQUEST_DATA;
125 * Mutex to synchronize the task to be executed on the GattServer
128 static oc_mutex g_bleIsServerMutex = NULL;
131 * Mutex to synchronize the updates of the local LE address of the
134 static oc_mutex g_bleLocalAddressMutex = NULL;
137 * Reference to thread pool.
139 static ca_thread_pool_t g_bleAdapterThreadPool = NULL;
142 * Mutex to synchronize the queing of the data from ReceiverQueue.
144 static oc_mutex g_bleClientReceiveDataMutex = NULL;
147 * Mutex to synchronize the queing of the data from ReceiverQueue.
149 static oc_mutex g_bleServerReceiveDataMutex = NULL;
152 * Callback to be called when network packet received from either
153 * GattServer or GattClient.
155 static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
158 * Callback to notify error from the BLE adapter.
160 static CAErrorHandleCallback g_errorHandler = NULL;
163 static CAResult_t CALESecureReceiveDataCB(const CASecureEndpoint_t *endpoint,
164 const void *data, size_t dataLength);
166 static ssize_t CALESecureSendDataCB(CAEndpoint_t *endpoint,
167 const void *data, size_t dataLength);
172 * Pointer to defragment received data from single threaded routine.
174 static CABLESenderInfo_t *g_singleThreadReceiveData = NULL;
177 * This function will be associated with the receive for single thread.
179 * This function will defragment the received data from sender
180 * respectively and will send it up to CA layer. Respective sender's
181 * header will provide the length of the data sent.
183 * @param[in] data Actual data received from the remote
185 * @param[in] dataLen Length of the data received from the
188 static void CALEDataReceiverHandlerSingleThread(const uint8_t *data,
192 * This function will be associated with the send for single threaded
195 * This function will fragment the data to the MTU of the transport
196 * and send the data in fragments to the adapters. The function will
197 * be blocked until all data is sent out from the adapter.
199 * @param[in] data Data to be transmitted from LE.
200 * @param[in] dataLen Length of the Data being transmitted.
202 static CAResult_t CALEServerSendDataSingleThread(const uint8_t *data,
207 * Register network change notification callback.
209 * @param[in] netCallback CAAdapterChangeCallback callback which will
210 * be set for the change in adapter.
211 * @param[in] connCallback CAConnectionChangeCallback callback which will
212 * be set for the change in connection.
214 * @return 0 on success otherwise a positive error value.
215 * @retval ::CA_STATUS_OK Successful.
216 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
217 * @retval ::CA_STATUS_FAILED Operation failed.
220 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
221 CAConnectionChangeCallback connCallback);
224 * Set the thread pool handle which is required for spawning new
227 * @param[in] handle Thread pool handle which is given by above layer
228 * for using thread creation task.
231 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle);
234 * Call the callback to the upper layer when the adapter state gets
237 * @param[in] adapter_state New state of the adapter to be notified to
240 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state);
243 * Call the callback to the upper layer when the device connection state gets
246 * @param[in] address LE address of the device to be notified to the upper layer.
247 * @param[in] isConnected whether connection state is connected or not.
249 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
253 * Used to initialize all required mutex variable for LE Adapter
256 * @return 0 on success otherwise a positive error value.
257 * @retval ::CA_STATUS_OK Successful.
258 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
259 * @retval ::CA_STATUS_FAILED Operation failed.
262 static CAResult_t CAInitLEAdapterMutex();
265 * Terminate all required mutex variables for LE adapter
268 static void CATerminateLEAdapterMutex();
271 * Prepares and notify error through error callback.
273 static void CALEErrorHandler(const char *remoteAddress,
278 #ifndef SINGLE_THREAD
280 * Stop condition of Server recvhandler.
282 static bool g_dataBleServerReceiverHandlerState = false;
285 * Stop condition of Client recvhandler.
287 static bool g_dataBleClientReceiverHandlerState = false;
290 * Sender information of Server.
292 static u_arraylist_t *g_bleServerSenderInfo = NULL;
295 * Sender information of Client.
297 static u_arraylist_t *g_bleClientSenderInfo = NULL;
300 * Mutex to synchronize access to all senderInfos
302 static oc_mutex g_senderInfoMutex = NULL;
305 * Queue to process the outgoing packets from GATTServer.
307 static CAQueueingThread_t *g_bleServerSendQueueHandle = NULL;
310 * Queue to process the outgoing packets from GATTClient.
312 static CAQueueingThread_t *g_bleClientSendQueueHandle = NULL;
315 * Queue to process the incoming packets from GATTServer.
317 static CAQueueingThread_t *g_bleServerReceiverQueue = NULL;
320 * Queue to process the incoming packets from GATTClient.
322 static CAQueueingThread_t *g_bleClientReceiverQueue = NULL;
325 * This function will be associated with the sender queue for
328 * This function will fragment the data to the MTU of the transport
329 * and send the data in fragments to the adapters. The function will
330 * be blocked until all data is sent out from the adapter.
332 * @param[in] threadData Data pushed to the queue which contains the
333 * info about RemoteEndpoint and Data.
335 static void CALEServerSendDataThread(void *threadData);
338 * This function will be associated with the sender queue for
341 * This function will fragment the data to the MTU of the transport
342 * and send the data in fragments to the adapters. The function will
343 * be blocked until all data is sent out from the adapter.
345 * @param[in] threadData Data pushed to the queue which contains the
346 * info about RemoteEndpoint and Data.
348 static void CALEClientSendDataThread(void *threadData);
351 * This function will defragment the received data from each sender
352 * respectively and will send it up to CA layer. Respective sender's
353 * header will provide the length of the data sent.
355 * @param[in] threadData Data pushed to the queue which contains the
356 * info about RemoteEndpoint and Data.
357 * @param[in] receiverType Whether receiver is server or client.
359 static void CALEDataReceiverHandler(void *threadData, CABLEAdapter_t receiverType);
362 * This function will be associated with the receiver queue for
365 * This function will call the function CALEDataReceiverHandler()
366 * with server type to defragment the received data.
368 * @param[in] threadData Data pushed to the queue which contains the
369 * info about RemoteEndpoint and Data.
371 static void CALEServerDataReceiverHandler(void *threadData);
374 * This function will be associated with the receiver queue for
377 * This function will call the function CALEDataReceiverHandler()
378 * with client type to defragment the received data.
380 * @param[in] threadData Data pushed to the queue which contains the
381 * info about RemoteEndpoint and Data.
383 static void CALEClientDataReceiverHandler(void *threadData);
386 * This function will stop all queues created for GattServer and
387 * GattClient. All four queues will be be stopped with this function
390 static void CAStopLEQueues();
393 * This function will terminate all queues created for GattServer and
394 * GattClient. All four queues will be be terminated with this
395 * function invocations.
397 static void CATerminateLEQueues();
400 * This function will initalize the Receiver and Sender queues for
401 * GattServer. This function will in turn call the functions
402 * CAInitBleServerReceiverQueue() and CAInitBleServerSenderQueue() to
403 * initialize the queues.
405 * @return ::CA_STATUS_OK or Appropriate error code.
406 * @retval ::CA_STATUS_OK Successful.
407 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
408 * @retval ::CA_STATUS_FAILED Operation failed.
410 static CAResult_t CAInitLEServerQueues();
413 * This function will initalize the Receiver and Sender queues for
414 * GattClient. This function will inturn call the functions
415 * CAInitBleClientReceiverQueue() and CAInitBleClientSenderQueue() to
416 * initialize the queues.
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.
424 static CAResult_t CAInitLEClientQueues();
427 * This function will initalize the Receiver queue for
428 * GattServer. This will initialize the queue to process the function
429 * CABLEServerSendDataThread() when ever the task is added to this
432 * @return ::CA_STATUS_OK or Appropriate error code.
433 * @retval ::CA_STATUS_OK Successful.
434 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
435 * @retval ::CA_STATUS_FAILED Operation failed.
437 static CAResult_t CAInitLEServerSenderQueue();
440 * This function will initalize the Receiver queue for
441 * GattClient. This will initialize the queue to process the function
442 * CABLEClientSendDataThread() when ever the task is added to this
445 * @return ::CA_STATUS_OK or Appropriate error code.
446 * @retval ::CA_STATUS_OK Successful.
447 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
448 * @retval ::CA_STATUS_FAILED Operation failed.
450 static CAResult_t CAInitLEClientSenderQueue();
453 * This function will initialize the Receiver queue for
454 * GattServer. This will initialize the queue to process the function
455 * CALEServerDataReceiverHandler() 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 CAInitLEServerReceiverQueue();
467 * This function will initialize the Receiver queue for
468 * GattClient. This will initialize the queue to process the function
469 * CALEClientDataReceiverHandler() when ever the task is added to this
472 * @return ::CA_STATUS_OK or Appropriate error code
473 * @retval ::CA_STATUS_OK Successful
474 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments
475 * @retval ::CA_STATUS_FAILED Operation failed
478 static CAResult_t CAInitLEClientReceiverQueue();
481 * This function will create the Data required to send it in the
484 * @param[in] remoteEndpoint Remote endpoint information of the
486 * @param[in] data Data to be transmitted from LE.
487 * @param[in] dataLength Length of the Data being transmitted.
489 * @return ::CA_STATUS_OK or Appropriate error code.
490 * @retval ::CA_STATUS_OK Successful.
491 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
492 * @retval ::CA_STATUS_FAILED Operation failed.
494 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
497 u_arraylist_t *senderInfo);
500 * Used to free the BLE information stored in the sender/receiver
503 * @param[in] bleData Information for a particular data segment.
505 static void CAFreeLEData(CALEData_t *bleData);
510 static void CALEDataDestroyer(void *data, uint32_t size);
512 #ifndef SINGLE_THREAD
514 * remove request or response data of send queue.
516 * @param[in] queueHandle queue to process the outgoing packets.
517 * @param[in] mutex mutex related to sender for client / server.
518 * @param[in] address target address to remove data in queue.
520 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle,
521 const char* address);
524 * remove all received data of data list from receive queue.
526 * @param[in] dataInfoList received data list to remove for client / server.
527 * @param[in] address target address to remove data in queue.
529 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList,
530 const char* address);
533 * get received data info and positioned index from the received data list
534 * for client / server which is matched same leAddress and port.
535 * CABLESenderInfo_t is reference counted structure, you must call
536 * CALEFreeSenderInfo on senderInfo to release reference.
538 * @param[in] leAddress target address to get serderInfo.
539 * @param[in] port target port to get senderInfo.
540 * @param[in] senderInfoList received data list for client / server.
541 * @param[out] senderInfo Pointer to contain matched(leAddress and port)
542 * received data info.
543 * @param[out] senderIndex Pointer to contain matched(leAddress and port)
544 * received data info index.
546 static CAResult_t CALEGetSenderInfo(const char *leAddress,
548 u_arraylist_t *senderInfoList,
549 CABLESenderInfo_t **senderInfo,
550 uint32_t *senderIndex);
553 * Add sender info to list.
555 * @param[in] u_arraylist_t Array list to add sender info to.
556 * @param[in] senderInfo Sender info to be added to list.
558 * @return true on success, otherwise false.
560 static bool CALEAddSenderInfoToList(u_arraylist_t *senderInfoList,
561 CABLESenderInfo_t *senderInfo);
564 * Remove desired sender info from list.
566 * @param[in] u_arraylist_t Array list to remove sender info from.
567 * @param[in] senderInfo Sender info to be removed from list.
570 static void CALERemoveSenderInfoFromList(u_arraylist_t *senderInfoList,
571 CABLESenderInfo_t *senderInfo);
574 * Free sender info. CABLESenderInfo_t is reference counted structure
575 * and info will be freed only when reference count reaches 0 or negative.
577 * @param[in] senderInfo Sender info to be freed.
580 static CAResult_t CALEFreeSenderInfo(CABLESenderInfo_t *senderInfo);
583 * get ports related to remote address. It is need because multi application
584 * can have more than 2 senderInfo using same BLE address. So before remove
585 * receive queue data, should get port list from sender Info.
587 * @param[in] leAddress target address to get port in serderInfo.
588 * @param[in] senderInfoList received data list to remove for client / server.
589 * @param[out] portList target port list related to leAddress.
591 static CAResult_t CALEGetPortsFromSenderInfo(const char *leAddress,
592 u_arraylist_t *senderInfoList,
593 u_arraylist_t *portList);
596 static CAResult_t CAInitLEServerQueues()
598 CAResult_t result = CAInitLEServerSenderQueue();
599 if (CA_STATUS_OK != result)
601 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerSenderQueue failed");
603 return CA_STATUS_FAILED;
606 g_bleServerSenderInfo = u_arraylist_create();
607 if (!g_bleServerSenderInfo)
609 OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
610 return CA_MEMORY_ALLOC_FAILED;
613 result = CAInitLEServerReceiverQueue();
614 if (CA_STATUS_OK != result)
616 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerReceiverQueue failed");
617 u_arraylist_free(&g_bleServerSenderInfo);
618 return CA_STATUS_FAILED;
621 g_dataBleServerReceiverHandlerState = true;
625 static CAResult_t CAInitLEClientQueues()
627 CAResult_t result = CAInitLEClientSenderQueue();
628 if (CA_STATUS_OK != result)
630 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientSenderQueue failed");
631 return CA_STATUS_FAILED;
634 g_bleClientSenderInfo = u_arraylist_create();
635 if (!g_bleClientSenderInfo)
637 OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
638 return CA_MEMORY_ALLOC_FAILED;
641 result = CAInitLEClientReceiverQueue();
642 if (CA_STATUS_OK != result)
644 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientReceiverQueue failed");
645 u_arraylist_free(&g_bleClientSenderInfo);
646 return CA_STATUS_FAILED;
649 g_dataBleClientReceiverHandlerState = true;
654 static CAResult_t CAInitLEServerReceiverQueue()
656 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
657 // Check if the message queue is already initialized
658 if (g_bleServerReceiverQueue)
660 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
664 // Create recv message queue
665 g_bleServerReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
666 if (!g_bleServerReceiverQueue)
668 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
669 return CA_MEMORY_ALLOC_FAILED;
672 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerReceiverQueue,
673 g_bleAdapterThreadPool,
674 CALEServerDataReceiverHandler,
677 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize server receiver queue thread");
678 OICFree(g_bleServerReceiverQueue);
679 g_bleServerReceiverQueue = NULL;
680 return CA_STATUS_FAILED;
683 if (CA_STATUS_OK != CAQueueingThreadStart(g_bleServerReceiverQueue))
685 OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
686 OICFree(g_bleServerReceiverQueue);
687 g_bleServerReceiverQueue = NULL;
688 return CA_STATUS_FAILED;
694 static CAResult_t CAInitLEClientReceiverQueue()
696 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
697 // Check if the message queue is already initialized
698 if (g_bleClientReceiverQueue)
700 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
704 // Create recv message queue
705 g_bleClientReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
706 if (!g_bleClientReceiverQueue)
708 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
709 return CA_MEMORY_ALLOC_FAILED;
712 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientReceiverQueue,
713 g_bleAdapterThreadPool,
714 CALEClientDataReceiverHandler,
717 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize client receiver queue thread");
718 OICFree(g_bleClientReceiverQueue);
719 g_bleClientReceiverQueue = NULL;
720 return CA_STATUS_FAILED;
723 if (CA_STATUS_OK != CAQueueingThreadStart(g_bleClientReceiverQueue))
725 OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
726 OICFree(g_bleClientReceiverQueue);
727 g_bleClientReceiverQueue = NULL;
728 return CA_STATUS_FAILED;
734 static CAResult_t CAInitLEServerSenderQueue()
736 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
737 // Check if the message queue is already initialized
738 if (g_bleServerSendQueueHandle)
740 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Queue is already initialized!");
744 // Create send message queue
745 g_bleServerSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
746 if (!g_bleServerSendQueueHandle)
748 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
749 return CA_MEMORY_ALLOC_FAILED;
752 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerSendQueueHandle,
753 g_bleAdapterThreadPool,
754 CALEServerSendDataThread,
757 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
758 OICFree(g_bleServerSendQueueHandle);
759 g_bleServerSendQueueHandle = NULL;
760 return CA_STATUS_FAILED;
766 static void CALEClearSenderInfoImpl(u_arraylist_t **list)
768 oc_mutex_lock(g_senderInfoMutex);
769 const size_t length = u_arraylist_length(*list);
770 for (size_t i = 0; i < length; ++i)
772 CABLESenderInfo_t * const info =
773 (CABLESenderInfo_t *) u_arraylist_get(*list, i);
776 OICFree(info->defragData);
777 CAFreeEndpoint(info->remoteEndpoint);
781 u_arraylist_free(list);
782 oc_mutex_unlock(g_senderInfoMutex);
785 static void CALEClearSenderInfo()
787 CALEClearSenderInfoImpl(&g_bleServerSenderInfo);
788 CALEClearSenderInfoImpl(&g_bleClientSenderInfo);
791 static CAResult_t CAInitLEClientSenderQueue()
793 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
795 if (g_bleClientSendQueueHandle)
797 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
801 // Create send message queue
802 g_bleClientSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
803 if (!g_bleClientSendQueueHandle)
805 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
806 return CA_MEMORY_ALLOC_FAILED;
809 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientSendQueueHandle,
810 g_bleAdapterThreadPool,
811 CALEClientSendDataThread, CALEDataDestroyer))
813 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
814 OICFree(g_bleClientSendQueueHandle);
815 g_bleClientSendQueueHandle = NULL;
816 return CA_STATUS_FAILED;
821 static void CAStopLEQueues()
823 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
825 oc_mutex_lock(g_bleServerReceiveDataMutex);
826 if (NULL != g_bleServerReceiverQueue)
828 CAQueueingThreadStop(g_bleServerReceiverQueue);
830 oc_mutex_unlock(g_bleServerReceiveDataMutex);
832 oc_mutex_lock(g_bleClientReceiveDataMutex);
833 if (NULL != g_bleClientReceiverQueue)
835 CAQueueingThreadStop(g_bleClientReceiverQueue);
837 oc_mutex_unlock(g_bleClientReceiveDataMutex);
839 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
842 static void CATerminateLEQueues()
844 CAQueueingThreadDestroy(g_bleClientSendQueueHandle);
845 OICFree(g_bleClientSendQueueHandle);
846 g_bleClientSendQueueHandle = NULL;
848 CAQueueingThreadDestroy(g_bleServerSendQueueHandle);
849 OICFree(g_bleServerSendQueueHandle);
850 g_bleServerSendQueueHandle = NULL;
852 CAQueueingThreadDestroy(g_bleServerReceiverQueue);
853 OICFree(g_bleServerReceiverQueue);
854 g_bleServerReceiverQueue = NULL;
856 CAQueueingThreadDestroy(g_bleClientReceiverQueue);
857 OICFree(g_bleClientReceiverQueue);
858 g_bleClientReceiverQueue = NULL;
860 CALEClearSenderInfo();
863 static CAResult_t CALEGetSenderInfo(const char *leAddress,
865 u_arraylist_t *senderInfoList,
866 CABLESenderInfo_t **senderInfo,
867 uint32_t *senderIndex)
869 VERIFY_NON_NULL_RET(leAddress,
871 "NULL BLE address argument",
872 CA_STATUS_INVALID_PARAM);
873 VERIFY_NON_NULL_RET(senderIndex,
875 "NULL index argument",
876 CA_STATUS_INVALID_PARAM);
878 oc_mutex_lock(g_senderInfoMutex);
879 const uint32_t listLength = u_arraylist_length(senderInfoList);
880 const uint32_t addrLength = strlen(leAddress);
881 for (uint32_t index = 0; index < listLength; index++)
883 CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
884 if (!info || !(info->remoteEndpoint))
889 if (!strncmp(info->remoteEndpoint->addr, leAddress, addrLength)
890 && info->remoteEndpoint->port == port)
892 *senderIndex = index;
896 (*senderInfo)->refCount++;
898 oc_mutex_unlock(g_senderInfoMutex);
903 oc_mutex_unlock(g_senderInfoMutex);
904 return CA_STATUS_FAILED;
907 static bool CALEAddSenderInfoToList(u_arraylist_t *senderInfoList, CABLESenderInfo_t *senderInfo)
909 oc_mutex_lock(g_senderInfoMutex);
910 senderInfo->refCount++;
911 if (!u_arraylist_add(senderInfoList,(void *)senderInfo))
913 senderInfo->refCount--;
914 oc_mutex_unlock(g_senderInfoMutex);
917 oc_mutex_unlock(g_senderInfoMutex);
921 static void CALERemoveSenderInfoFromList(u_arraylist_t *senderInfoList, CABLESenderInfo_t *senderInfo)
923 oc_mutex_lock(g_senderInfoMutex);
925 bool elemFound = u_arraylist_get_index(senderInfoList, (const void*)senderInfo, &idx);
928 void *info = u_arraylist_remove(senderInfoList, idx);
931 senderInfo->refCount--;
934 oc_mutex_unlock(g_senderInfoMutex);
937 static CAResult_t CALEFreeSenderInfo(CABLESenderInfo_t *senderInfo)
939 VERIFY_NON_NULL_RET(senderInfo,
941 "NULL senderInfo to remove argument",
942 CA_STATUS_INVALID_PARAM);
944 oc_mutex_lock(g_senderInfoMutex);
945 senderInfo->refCount--;
946 if(senderInfo->refCount == 0)
948 OICFree(senderInfo->defragData);
949 OICFree(senderInfo->remoteEndpoint);
952 oc_mutex_unlock(g_senderInfoMutex);
956 static void CALEDataReceiverHandler(void *threadData, CABLEAdapter_t receiverType)
958 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
960 oc_mutex bleReceiveDataMutex = NULL;
961 bool dataBleReceiverHandlerState = false;
963 switch (receiverType)
966 bleReceiveDataMutex = g_bleClientReceiveDataMutex;
967 dataBleReceiverHandlerState = g_dataBleClientReceiverHandlerState;
970 bleReceiveDataMutex = g_bleServerReceiveDataMutex;
971 dataBleReceiverHandlerState = g_dataBleServerReceiverHandlerState;
974 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Unsupported receiver type : %d", receiverType);
978 oc_mutex_lock(bleReceiveDataMutex);
980 if (dataBleReceiverHandlerState)
982 CALEData_t *bleData = (CALEData_t *) threadData;
985 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bleData!");
986 oc_mutex_unlock(bleReceiveDataMutex);
990 if (!(bleData->senderInfo))
992 OIC_LOG(ERROR, CALEADAPTER_TAG, "sender info is not available");
993 oc_mutex_unlock(bleReceiveDataMutex);
997 if (!(bleData->remoteEndpoint))
999 OIC_LOG(ERROR, CALEADAPTER_TAG, "RemoteEndPoint NULL!!");
1000 oc_mutex_unlock(bleReceiveDataMutex);
1004 CABLESenderInfo_t *senderInfo = NULL;
1005 uint32_t senderIndex = 0;
1008 CABLEPacketStart_t startFlag = CA_BLE_PACKET_NOT_START;
1009 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1010 uint16_t sourcePort = 0;
1011 uint16_t destPort = 0;
1013 CAParseHeader(bleData->data, &startFlag, &sourcePort, &secureFlag, &destPort);
1014 OIC_LOG_V(INFO, CALEADAPTER_TAG,
1015 "header info: startFlag[%X] sourcePort[%d] secureFlag[%X] destPort[%d]",
1016 startFlag, sourcePort, secureFlag, destPort);
1018 if (destPort != g_localBLESourcePort && destPort != CA_BLE_MULTICAST_PORT)
1020 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1021 "this packet is not valid for this app(port mismatch[mine:%d, packet:%d])",
1022 g_localBLESourcePort, destPort);
1023 oc_mutex_unlock(bleReceiveDataMutex);
1027 bleData->remoteEndpoint->port = sourcePort;
1029 if (CA_STATUS_OK != CALEGetSenderInfo(bleData->remoteEndpoint->addr,
1030 bleData->remoteEndpoint->port,
1031 bleData->senderInfo,
1032 &senderInfo, &senderIndex))
1034 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This is a new client [%s:%X]",
1035 bleData->remoteEndpoint->addr, bleData->remoteEndpoint->port);
1041 OIC_LOG(ERROR, CALEADAPTER_TAG,
1042 "This packet is start packet but exist senderInfo. Remove senderInfo");
1043 CALERemoveSenderInfoFromList(bleData->senderInfo, senderInfo);
1044 CALEFreeSenderInfo(senderInfo);
1052 uint32_t totalLength = 0;
1055 CAParseHeaderPayloadLength(bleData->data, CA_BLE_LENGTH_HEADER_SIZE, &totalLength);
1059 OIC_LOG(ERROR, CALEADAPTER_TAG, "This packet is wrong packet! ignore.");
1060 oc_mutex_unlock(bleReceiveDataMutex);
1064 CABLESenderInfo_t *newSender = OICCalloc(1, sizeof(CABLESenderInfo_t));
1067 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
1068 oc_mutex_unlock(bleReceiveDataMutex);
1072 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
1074 newSender->totalDataLen = totalLength;
1075 if (!(newSender->totalDataLen))
1077 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
1078 CALEFreeSenderInfo(newSender);
1079 oc_mutex_unlock(bleReceiveDataMutex);
1083 size_t dataOnlyLen =
1084 bleData->dataLen - (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE);
1085 OIC_LOG_V(INFO, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
1086 newSender->totalDataLen);
1087 OIC_LOG_V(INFO, CALEADAPTER_TAG, "data received in the first packet [%zu] bytes",
1090 newSender->defragData = OICCalloc(newSender->totalDataLen + 1,
1091 sizeof(*newSender->defragData));
1093 if (NULL == newSender->defragData)
1095 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
1096 CALEFreeSenderInfo(newSender);
1097 oc_mutex_unlock(bleReceiveDataMutex);
1100 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
1101 #ifdef __WITH_DTLS__
1102 if (CA_BLE_PACKET_SECURE == secureFlag)
1108 const char *remoteAddress = bleData->remoteEndpoint->addr;
1109 newSender->remoteEndpoint = CACreateEndpointObject(flags,
1110 CA_ADAPTER_GATT_BTLE,
1112 bleData->remoteEndpoint->port);
1114 if (NULL == newSender->remoteEndpoint)
1116 OIC_LOG(ERROR, CALEADAPTER_TAG, "remoteEndpoint is NULL!");
1117 CALEFreeSenderInfo(newSender);
1118 oc_mutex_unlock(bleReceiveDataMutex);
1122 if (newSender->recvDataLen + dataOnlyLen > newSender->totalDataLen)
1124 OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
1125 CALEFreeSenderInfo(newSender);
1126 oc_mutex_unlock(bleReceiveDataMutex);
1129 memcpy(newSender->defragData,
1130 bleData->data + (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE),
1132 newSender->recvDataLen += dataOnlyLen;
1134 newSender->refCount = 1;
1136 if (!CALEAddSenderInfoToList(bleData->senderInfo, newSender))
1138 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to add sender info!");
1139 CALEFreeSenderInfo(newSender);
1140 oc_mutex_unlock(bleReceiveDataMutex);
1144 senderInfo = newSender;
1148 size_t dataOnlyLen = bleData->dataLen - CA_BLE_HEADER_SIZE;
1149 if (senderInfo->recvDataLen + dataOnlyLen > senderInfo->totalDataLen)
1151 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1152 "Data Length exceeding error!! Receiving [%zu] total length [%u]",
1153 senderInfo->recvDataLen + dataOnlyLen, senderInfo->totalDataLen);
1154 CALERemoveSenderInfoFromList(bleData->senderInfo, senderInfo);
1155 CALEFreeSenderInfo(senderInfo);
1156 oc_mutex_unlock(bleReceiveDataMutex);
1159 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%zu]",
1161 memcpy(senderInfo->defragData + senderInfo->recvDataLen,
1162 bleData->data + CA_BLE_HEADER_SIZE,
1164 senderInfo->recvDataLen += dataOnlyLen;
1165 OIC_LOG_V(INFO, CALEADAPTER_TAG, "totalDatalength [%d] received Datalen [%d]",
1166 senderInfo->totalDataLen, senderInfo->recvDataLen);
1169 if (senderInfo->totalDataLen == senderInfo->recvDataLen)
1171 if (NULL == g_networkPacketReceivedCallback)
1173 OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
1174 CALERemoveSenderInfoFromList(bleData->senderInfo, senderInfo);
1175 CALEFreeSenderInfo(senderInfo);
1176 oc_mutex_unlock(bleReceiveDataMutex);
1180 OIC_LOG(DEBUG, CALEADAPTER_TAG, "[CALEDataReceiverHandler] Received data up !");
1182 const CASecureEndpoint_t tmp =
1184 .endpoint = *senderInfo->remoteEndpoint
1187 OIC_LOG_V(INFO, CALEADAPTER_TAG, "endpoint flags : %d", tmp.endpoint.flags);
1188 #ifdef __WITH_DTLS__
1189 if (CA_SECURE & tmp.endpoint.flags)
1191 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Secure data received");
1192 switch (receiverType)
1194 case ADAPTER_CLIENT:
1195 g_dataType = CA_REQUEST_DATA;
1197 case ADAPTER_SERVER:
1198 g_dataType = CA_RESPONSE_DATA;
1201 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Unsupported rcvr type:%d",receiverType);
1202 CALERemoveSenderInfoFromList(bleData->senderInfo, senderInfo);
1203 senderInfo->remoteEndpoint = NULL;
1204 senderInfo->defragData = NULL;
1205 CALEFreeSenderInfo(senderInfo);
1206 oc_mutex_unlock(bleReceiveDataMutex);
1210 if (CA_STATUS_FAILED == CAdecryptSsl(&tmp,
1211 senderInfo->defragData,
1212 senderInfo->recvDataLen))
1214 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAdecryptSsl failed");
1218 OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAdecryptSsl successed");
1220 OICFree(senderInfo->defragData);
1225 OIC_LOG(INFO, CALEADAPTER_TAG, "Non-Secure data received");
1226 g_networkPacketReceivedCallback(&tmp,
1227 senderInfo->defragData,
1228 senderInfo->recvDataLen);
1229 #ifdef __WITH_DTLS__
1233 CALERemoveSenderInfoFromList(bleData->senderInfo, senderInfo);
1234 senderInfo->remoteEndpoint = NULL;
1235 senderInfo->defragData = NULL;
1236 CALEFreeSenderInfo(senderInfo);
1237 oc_mutex_unlock(bleReceiveDataMutex);
1240 CALEFreeSenderInfo(senderInfo);
1242 oc_mutex_unlock(bleReceiveDataMutex);
1246 static void CALEServerDataReceiverHandler(void *threadData)
1248 CALEDataReceiverHandler(threadData, ADAPTER_SERVER);
1251 static void CALEClientDataReceiverHandler(void *threadData)
1253 CALEDataReceiverHandler(threadData, ADAPTER_CLIENT);
1256 static void CALEServerSendDataThread(void *threadData)
1258 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1260 CALEData_t * const bleData = (CALEData_t *) threadData;
1263 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid bledata!");
1267 if (!bleData->remoteEndpoint)
1269 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid endpoint of bledata!");
1273 #if defined(__TIZEN__) || defined(__ANDROID__)
1275 g_mtuSize = CALEServerGetMtuSize(bleData->remoteEndpoint->addr);
1277 OIC_LOG_V(INFO, CALEADAPTER_TAG, "MTU size [%d]", g_mtuSize);
1279 uint32_t midPacketCount = 0;
1280 size_t remainingLen = 0;
1281 size_t totalLength = 0;
1282 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1284 CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
1290 VERIFY_CARESULT(result, CAGenerateVariableForFragmentation, bleData->remoteEndpoint, bleData->data, bleData->dataLen);
1292 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1293 "Packet info: data size[%d] midPacketCount[%u] remainingLen[%zu] totalLength[%zu]",
1294 bleData->dataLen, midPacketCount, remainingLen, totalLength);
1298 "Server total Data length with header is [%zu]",
1301 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1302 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1304 if (NULL != bleData->remoteEndpoint) //Unicast Data
1306 secureFlag = (bleData->remoteEndpoint->flags & CA_SECURE) ?
1307 CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
1309 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This Packet is secure? %d", secureFlag);
1310 result = CAGenerateHeader(dataHeader,
1311 CA_BLE_PACKET_START,
1312 g_localBLESourcePort,
1314 bleData->remoteEndpoint->port);
1316 else //Multicast Data
1318 result = CAGenerateHeader(dataHeader,
1319 CA_BLE_PACKET_START,
1320 g_localBLESourcePort,
1322 CA_BLE_MULTICAST_PORT);
1324 OIC_LOG_V(INFO, CALEADAPTER_TAG, "header info: secureFlag[%X]", secureFlag);
1326 VERIFY_CARESULT(result, CAGenerateHeader, bleData->remoteEndpoint, bleData->data, bleData->dataLen);
1328 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1329 result = CAGenerateHeaderPayloadLength(lengthHeader,
1330 CA_BLE_LENGTH_HEADER_SIZE,
1333 VERIFY_CARESULT(result, CAGenerateHeaderPayloadLength, bleData->remoteEndpoint, bleData->data, bleData->dataLen);
1335 uint32_t length = 0;
1336 uint32_t dataLen = 0;
1337 if (g_mtuSize > totalLength)
1339 length = (uint32_t)totalLength;
1340 dataLen = bleData->dataLen;
1345 dataLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1348 result = CAMakeFirstDataSegment(dataSegment,
1349 bleData->data, dataLen,
1350 dataHeader, lengthHeader);
1352 VERIFY_CARESULT(result, CAMakeFirstDataSegment, bleData->remoteEndpoint, bleData->data, bleData->dataLen);
1354 const uint32_t iter = midPacketCount;
1357 // Send the first segment with the header.
1358 if (NULL != bleData->remoteEndpoint) // Sending Unicast Data
1360 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Unicast Data");
1362 result = CAUpdateCharacteristicsToGattClient(
1363 bleData->remoteEndpoint->addr, dataSegment, length);
1365 VERIFY_CARESULT(result, CAUpdateCharacteristicsToGattClient, bleData->remoteEndpoint, bleData->data, bleData->dataLen);
1369 "Server Sent Unicast First Data - data length [%u]",
1372 result = CAGenerateHeader(dataHeader,
1373 CA_BLE_PACKET_NOT_START,
1374 g_localBLESourcePort,
1376 bleData->remoteEndpoint->port);
1378 VERIFY_CARESULT(result, CAGenerateHeader, bleData->remoteEndpoint, bleData->data, bleData->dataLen);
1380 for (index = 0; index < iter; index++)
1382 // Send the remaining header.
1383 result = CAMakeRemainDataSegment(dataSegment,
1384 g_mtuSize - CA_BLE_HEADER_SIZE,
1391 VERIFY_CARESULT(result, CAMakeRemainDataSegment, bleData->remoteEndpoint, bleData->data, bleData->dataLen);
1394 CAUpdateCharacteristicsToGattClient(
1395 bleData->remoteEndpoint->addr,
1399 VERIFY_CARESULT(result, CAUpdateCharacteristicsToGattClient, bleData->remoteEndpoint, bleData->data, bleData->dataLen);
1401 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]",
1405 if (remainingLen && (totalLength > g_mtuSize))
1407 // send the last segment of the data (Ex: 22 bytes of 622
1408 // bytes of data when MTU is 200)
1409 result = CAMakeRemainDataSegment(dataSegment,
1417 VERIFY_CARESULT(result, CAMakeRemainDataSegment, bleData->remoteEndpoint, bleData->data, bleData->dataLen);
1419 result = CAUpdateCharacteristicsToGattClient(
1420 bleData->remoteEndpoint->addr,
1422 remainingLen + CA_BLE_HEADER_SIZE);
1424 VERIFY_CARESULT(result, CAUpdateCharacteristicsToGattClient, bleData->remoteEndpoint, bleData->data, bleData->dataLen);
1428 "Server Sent Unicast Last Data - data length [%zu]",
1429 remainingLen + CA_BLE_HEADER_SIZE);
1434 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
1435 OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
1438 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1441 static void CALEClientSendDataThread(void *threadData)
1443 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1445 CALEData_t *bleData = (CALEData_t *) threadData;
1448 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid bledata!");
1452 if (!bleData->remoteEndpoint)
1454 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid endpoint of bledata!");
1458 #if defined(__ANDROID__)
1460 if (false == CALEClientIsConnected(bleData->remoteEndpoint->addr))
1462 // triggering to gatt connect and MTU negotiation
1463 CAResult_t res = CALEClientSendNegotiationMessage(
1464 bleData->remoteEndpoint->addr);
1466 VERIFY_CARESULT(res, CALEClientSendNegotiationMessage, bleData->remoteEndpoint, bleData->data, bleData->dataLen);
1469 #if defined(__TIZEN__) || defined(__ANDROID__)
1470 g_mtuSize = CALEClientGetMtuSize(bleData->remoteEndpoint->addr);
1472 OIC_LOG_V(INFO, CALEADAPTER_TAG, "MTU size [%d]", g_mtuSize);
1474 uint32_t midPacketCount = 0;
1475 size_t remainingLen = 0;
1476 size_t totalLength = 0;
1477 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1479 CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
1485 VERIFY_CARESULT(result, CAGenerateVariableForFragmentation, bleData->remoteEndpoint, bleData->data, bleData->dataLen);
1487 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1488 "Packet info: data size[%d] midPacketCount[%u] remainingLen[%zu] totalLength[%zu]",
1489 bleData->dataLen, midPacketCount, remainingLen, totalLength);
1491 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1492 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1494 if (NULL != bleData->remoteEndpoint) //Unicast Data
1496 secureFlag = (bleData->remoteEndpoint->flags & CA_SECURE) ?
1497 CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
1499 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This Packet is secure? %d", secureFlag);
1500 result = CAGenerateHeader(dataHeader,
1501 CA_BLE_PACKET_START,
1502 g_localBLESourcePort,
1504 bleData->remoteEndpoint->port);
1506 else //Multicast Data
1508 result = CAGenerateHeader(dataHeader,
1509 CA_BLE_PACKET_START,
1510 g_localBLESourcePort,
1512 CA_BLE_MULTICAST_PORT);
1515 OIC_LOG_V(INFO, CALEADAPTER_TAG, "header info: secureFlag[%X]", secureFlag);
1517 VERIFY_CARESULT(result, CAGenerateHeader, bleData->remoteEndpoint, bleData->data, bleData->dataLen);
1519 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1520 result = CAGenerateHeaderPayloadLength(lengthHeader,
1521 CA_BLE_LENGTH_HEADER_SIZE,
1524 VERIFY_CARESULT(result, CAGenerateHeaderPayloadLength, bleData->remoteEndpoint, bleData->data, bleData->dataLen);
1526 uint32_t length = 0;
1527 uint32_t dataLen = 0;
1528 if (g_mtuSize > totalLength)
1530 length = (uint32_t)totalLength;
1531 dataLen = bleData->dataLen;
1536 dataLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1539 result = CAMakeFirstDataSegment(dataSegment,
1540 bleData->data, dataLen,
1541 dataHeader, lengthHeader);
1543 VERIFY_CARESULT(result, CAMakeFirstDataSegment, bleData->remoteEndpoint, bleData->data, bleData->dataLen);
1545 const uint32_t iter = midPacketCount;
1547 if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
1549 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
1550 // Send the first segment with the header.
1552 CAUpdateCharacteristicsToGattServer(
1553 bleData->remoteEndpoint->addr,
1559 VERIFY_CARESULT(result, CAUpdateCharacteristicsToGattServer, bleData->remoteEndpoint, bleData->data, bleData->dataLen);
1562 "Client Sent Unicast First Data - data length [%u]",
1565 result = CAGenerateHeader(dataHeader,
1566 CA_BLE_PACKET_NOT_START,
1567 g_localBLESourcePort,
1569 bleData->remoteEndpoint->port);
1571 VERIFY_CARESULT(result, CAGenerateHeader, bleData->remoteEndpoint, bleData->data, bleData->dataLen);
1573 for (index = 0; index < iter; index++)
1575 result = CAMakeRemainDataSegment(dataSegment,
1576 g_mtuSize - CA_BLE_HEADER_SIZE,
1583 VERIFY_CARESULT(result, CAMakeRemainDataSegment, bleData->remoteEndpoint, bleData->data, bleData->dataLen);
1585 // Send the remaining header.
1586 result = CAUpdateCharacteristicsToGattServer(
1587 bleData->remoteEndpoint->addr,
1592 VERIFY_CARESULT(result, CAUpdateCharacteristicsToGattServer, bleData->remoteEndpoint, bleData->data, bleData->dataLen);
1595 "Client Sent Unicast %d Data - data(mtu) length [%hu]",
1600 if (remainingLen && (totalLength > g_mtuSize))
1602 // send the last segment of the data (Ex: 22 bytes of 622
1603 // bytes of data when MTU is 200)
1604 result = CAMakeRemainDataSegment(dataSegment,
1612 VERIFY_CARESULT(result, CAMakeRemainDataSegment, bleData->remoteEndpoint, bleData->data, bleData->dataLen);
1614 result = CAUpdateCharacteristicsToGattServer(
1615 bleData->remoteEndpoint->addr,
1617 remainingLen + CA_BLE_HEADER_SIZE,
1620 VERIFY_CARESULT(result, CAUpdateCharacteristicsToGattServer, bleData->remoteEndpoint, bleData->data, bleData->dataLen);
1623 "Client Sent Unicast Last Data - data length [%zu]",
1624 remainingLen + CA_BLE_HEADER_SIZE);
1629 //Sending Mulitcast Data
1630 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Client Sending Multicast Data");
1631 OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
1634 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1637 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
1638 const uint8_t *data,
1639 uint32_t dataLength,
1640 u_arraylist_t *senderInfo)
1642 CALEData_t * const bleData = OICMalloc(sizeof(CALEData_t));
1646 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1650 bleData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
1651 bleData->data = OICCalloc(dataLength + 1, 1);
1653 if (NULL == bleData->data)
1655 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1656 CAFreeLEData(bleData);
1660 memcpy(bleData->data, data, dataLength);
1661 bleData->dataLen = dataLength;
1664 bleData->senderInfo = senderInfo;
1670 static void CAFreeLEData(CALEData_t *bleData)
1672 VERIFY_NON_NULL_VOID(bleData, CALEADAPTER_TAG, "Param bleData is NULL");
1674 CAFreeEndpoint(bleData->remoteEndpoint);
1675 OICFree(bleData->data);
1679 static void CALEDataDestroyer(void *data, uint32_t size)
1681 if ((size_t)size < sizeof(CALEData_t *))
1683 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1684 "Destroy data too small %p %d", data, size);
1686 CALEData_t *ledata = (CALEData_t *) data;
1688 CAFreeLEData(ledata);
1692 #ifdef SINGLE_THREAD
1693 static void CALEDataReceiverHandlerSingleThread(const uint8_t *data,
1696 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1698 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1701 CABLEPacketStart_t startFlag = CA_BLE_PACKET_NOT_START;
1702 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1703 uint16_t sourcePort = 0;
1704 uint16_t destPort = 0;
1706 CAParseHeader(data, &startFlag, &sourcePort, &secureFlag, &destPort);
1707 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1708 "header info: startFlag[%X] sourcePort[%d] secureFlag[%X] destPort[%d]",
1709 startFlag, sourcePort, secureFlag, destPort);
1711 if (destPort != g_localBLESourcePort && destPort != CA_BLE_MULTICAST_PORT)
1713 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1714 "this packet is not valid for this app(port mismatch[mine:%d, packet:%d])",
1715 g_localBLESourcePort, destPort);
1721 if (g_singleThreadReceiveData)
1723 OIC_LOG(ERROR, CALEADAPTER_TAG,
1724 "This packet is start packet but exist senderInfo. Remove senderInfo");
1725 OICFree(g_singleThreadReceiveData->defragData);
1726 OICFree(g_singleThreadReceiveData);
1727 g_singleThreadReceiveData = NULL;
1730 uint32_t totalLength = 0;
1731 CAParseHeaderPayloadLength(data, CA_BLE_LENGTH_HEADER_SIZE, &totalLength);
1733 g_singleThreadReceiveData = OICMalloc(sizeof(CABLESenderInfo_t));
1735 if (!g_singleThreadReceiveData)
1737 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
1740 g_singleThreadReceiveData->recvDataLen = 0;
1741 g_singleThreadReceiveData->totalDataLen = 0;
1742 g_singleThreadReceiveData->defragData = NULL;
1743 g_singleThreadReceiveData->remoteEndpoint = NULL;
1745 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
1747 g_singleThreadReceiveData->totalDataLen = totalLength;
1749 if (!(g_singleThreadReceiveData->totalDataLen))
1751 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
1752 OICFree(g_singleThreadReceiveData);
1756 size_t dataOnlyLen = dataLen - (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE);
1757 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
1758 g_singleThreadReceiveData->totalDataLen);
1759 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%u] bytes",
1762 g_singleThreadReceiveData->defragData =
1763 OICCalloc(g_singleThreadReceiveData->totalDataLen + 1,
1764 sizeof(*g_singleThreadReceiveData->defragData));
1766 if (NULL == g_singleThreadReceiveData->defragData)
1768 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
1769 OICFree(g_singleThreadReceiveData);
1773 if (g_singleThreadReceiveData->recvDataLen + dataOnlyLen
1774 > g_singleThreadReceiveData->totalDataLen)
1776 OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
1777 OICFree(g_singleThreadReceiveData->defragData);
1778 OICFree(g_singleThreadReceiveData);
1781 memcpy(g_singleThreadReceiveData->defragData,
1782 data + (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE),
1784 g_singleThreadReceiveData->recvDataLen += dataOnlyLen;
1788 size_t dataOnlyLen = dataLen - CA_BLE_HEADER_SIZE;
1789 if (g_singleThreadReceiveData->recvDataLen + dataOnlyLen
1790 > g_singleThreadReceiveData->totalDataLen)
1792 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1793 "Data Length exceeding error!! Receiving [%d] total length [%d]",
1794 g_singleThreadReceiveData->recvDataLen + dataOnlyLen,
1795 g_singleThreadReceiveData->totalDataLen);
1796 OICFree(g_singleThreadReceiveData->defragData);
1797 OICFree(g_singleThreadReceiveData);
1800 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]",
1802 memcpy(g_singleThreadReceiveData->defragData + g_singleThreadReceiveData->recvDataLen,
1803 data + CA_BLE_HEADER_SIZE,
1805 g_singleThreadReceiveData->recvDataLen += dataOnlyLen;
1806 OIC_LOG_V(INFO, CALEADAPTER_TAG, "totalDatalength [%d] received Datalen [%d]",
1807 g_singleThreadReceiveData->totalDataLen, g_singleThreadReceiveData->recvDataLen);
1809 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1812 static CAResult_t CALEServerSendDataSingleThread(const uint8_t *data,
1815 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
1817 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1819 uint32_t midPacketCount = 0;
1820 size_t remainingLen = 0;
1821 size_t totalLength = 0;
1822 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1824 CAResult_t result = CAGenerateVariableForFragmentation(dataLen,
1830 if (CA_STATUS_OK != result)
1832 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1833 "CAGenerateVariableForFragmentation failed, result [%d]", result);
1837 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1838 "Packet info: data size[%d] midPacketCount[%d] remainingLen[%d] totalLength[%d]",
1839 dataLen, midPacketCount, remainingLen, totalLength);
1843 "Server total Data length with header is [%u]",
1846 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1847 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1849 result = CAGenerateHeader(dataHeader,
1850 CA_BLE_PACKET_START,
1851 g_localBLESourcePort,
1852 CA_BLE_PACKET_NON_SECURE,
1853 CA_BLE_MULTICAST_PORT);
1855 if (CA_STATUS_OK != result)
1857 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1858 "CAGenerateHeader failed, result [%d]", result);
1862 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1863 result = CAGenerateHeaderPayloadLength(lengthHeader,
1864 CA_BLE_LENGTH_HEADER_SIZE,
1867 if (CA_STATUS_OK != result)
1869 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1870 "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1874 uint32_t length = 0;
1875 uint32_t dataOnlyLen = 0;
1876 if (g_mtuSize > totalLength)
1878 length = totalLength;
1879 dataOnlyLen = dataLen;
1884 dataOnlyLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1887 result = CAMakeFirstDataSegment(dataSegment,
1889 dataHeader, lengthHeader);
1891 if (CA_STATUS_OK != result)
1893 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1894 "Making data segment failed, result [%d]", result);
1898 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
1899 result = CAUpdateCharacteristicsToAllGattClients(dataSegment, length);
1900 if (CA_STATUS_OK != result)
1902 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1909 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
1911 result = CAGenerateHeader(dataHeader,
1912 CA_BLE_PACKET_NOT_START,
1913 g_localBLESourcePort,
1914 CA_BLE_PACKET_NON_SECURE,
1915 CA_BLE_MULTICAST_PORT);
1917 if (CA_STATUS_OK != result)
1919 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1920 "CAGenerateHeader failed, result [%d]", result);
1924 const uint32_t dataLimit = midPacketCount;
1925 for (uint32_t iter = 0; iter < dataLimit; iter++)
1927 result = CAMakeRemainDataSegment(dataSegment,
1928 g_mtuSize - CA_BLE_HEADER_SIZE,
1935 if (CA_STATUS_OK != result)
1937 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1938 "Making data segment failed, result [%d]", result);
1942 result = CAUpdateCharacteristicsToAllGattClients(
1946 if (CA_STATUS_OK != result)
1948 OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
1955 if (remainingLen && (totalLength > g_mtuSize))
1957 // send the last segment of the data
1958 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1960 result = CAMakeRemainDataSegment(dataSegment,
1968 if (CA_STATUS_OK != result)
1970 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1971 "Making data segment failed, result [%d]", result);
1975 result = CAUpdateCharacteristicsToAllGattClients(
1977 remainingLen + CA_BLE_HEADER_SIZE);
1979 if (CA_STATUS_OK != result)
1981 OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
1991 static CAResult_t CAInitLEAdapterMutex()
1993 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
1995 if (NULL == g_bleIsServerMutex)
1997 g_bleIsServerMutex = oc_mutex_new();
1998 if (NULL == g_bleIsServerMutex)
2000 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2001 return CA_STATUS_FAILED;
2005 if (NULL == g_bleLocalAddressMutex)
2007 g_bleLocalAddressMutex = oc_mutex_new();
2008 if (NULL == g_bleLocalAddressMutex)
2010 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2011 CATerminateLEAdapterMutex();
2012 return CA_STATUS_FAILED;
2018 if (NULL == g_bleServerReceiveDataMutex)
2020 g_bleServerReceiveDataMutex = oc_mutex_new();
2021 if (NULL == g_bleServerReceiveDataMutex)
2023 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2024 return CA_STATUS_FAILED;
2028 if (NULL == g_bleClientReceiveDataMutex)
2030 g_bleClientReceiveDataMutex = oc_mutex_new();
2031 if (NULL == g_bleClientReceiveDataMutex)
2033 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2034 return CA_STATUS_FAILED;
2038 if (NULL == g_senderInfoMutex)
2040 g_senderInfoMutex = oc_mutex_new();
2041 if (NULL == g_senderInfoMutex)
2043 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2044 return CA_STATUS_FAILED;
2048 return CA_STATUS_OK;
2051 static void CATerminateLEAdapterMutex()
2053 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2055 oc_mutex_free(g_bleIsServerMutex);
2056 g_bleIsServerMutex = NULL;
2059 oc_mutex_free(g_bleLocalAddressMutex);
2060 g_bleLocalAddressMutex = NULL;
2062 oc_mutex_free(g_bleServerReceiveDataMutex);
2063 g_bleServerReceiveDataMutex = NULL;
2065 oc_mutex_free(g_bleClientReceiveDataMutex);
2066 g_bleClientReceiveDataMutex = NULL;
2068 oc_mutex_free(g_senderInfoMutex);
2069 g_senderInfoMutex = NULL;
2073 * Starting LE connectivity adapters.
2075 * As its peer to peer it does not require to start any servers.
2077 * @return ::CA_STATUS_OK or Appropriate error code.
2079 static CAResult_t CAStartLE();
2082 * Start listening server for receiving multicast search requests.
2084 * Transport Specific Behavior:
2085 * LE Starts GATT Server with prefixed UUID and Characteristics
2086 * per OIC Specification.
2087 * @return ::CA_STATUS_OK or Appropriate error code.
2089 static CAResult_t CAStartLEListeningServer();
2092 * Stops listening server from receiving multicast search requests.
2094 * Transport Specific Behavior:
2095 * LE Starts GATT Server with prefixed UUID and Characteristics
2096 * per OIC Specification.
2097 * @return ::CA_STATUS_OK or Appropriate error code.
2099 static CAResult_t CAStopLEListeningServer();
2102 * Sarting discovery of servers for receiving multicast
2105 * Transport Specific Behavior:
2106 * LE Starts GATT Server with prefixed UUID and Characteristics
2107 * per OIC Specification.
2109 * @return ::CA_STATUS_OK or Appropriate error code
2111 static CAResult_t CAStartLEDiscoveryServer();
2114 * Send data to the endpoint using the adapter connectivity.
2116 * @param[in] endpoint Remote Endpoint information (like MAC address,
2117 * reference URI and connectivity type) to which
2118 * the unicast data has to be sent.
2119 * @param[in] data Data which required to be sent.
2120 * @param[in] dataLen Size of data to be sent.
2122 * @note dataLen must be > 0.
2124 * @return The number of bytes sent on the network, or -1 on error.
2126 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2129 CADataType_t dataType);
2132 * Send multicast data to the endpoint using the LE connectivity.
2134 * @param[in] endpoint Remote Endpoint information to which the
2135 * multicast data has to be sent.
2136 * @param[in] data Data which required to be sent.
2137 * @param[in] dataLen Size of data to be sent.
2139 * @note dataLen must be > 0.
2141 * @return The number of bytes sent on the network, or -1 on error.
2143 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
2146 CADataType_t dataType);
2149 * Get LE Connectivity network information.
2151 * @param[out] info Local connectivity information structures.
2152 * @param[out] size Number of local connectivity structures.
2154 * @return ::CA_STATUS_OK or Appropriate error code.
2156 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info,
2160 * Read Synchronous API callback.
2162 * @return ::CA_STATUS_OK or Appropriate error code.
2164 static CAResult_t CAReadLEData();
2167 * Stopping the adapters and close socket connections.
2169 * LE Stops all GATT servers and GATT Clients.
2171 * @return ::CA_STATUS_OK or Appropriate error code.
2173 static CAResult_t CAStopLE();
2176 * Terminate the LE connectivity adapter.
2178 * Configuration information will be deleted from further use.
2180 static void CATerminateLE();
2183 * This function will receive the data from the GattServer and add the
2184 * data to the Server receiver queue.
2186 * @param[in] remoteAddress Remote address of the device from where
2188 * @param[in] data Actual data received from the remote
2190 * @param[in] dataLength Length of the data received from the
2192 * @param[in] sentLength Length of the data sent from the remote
2195 * @return ::CA_STATUS_OK or Appropriate error code.
2196 * @retval ::CA_STATUS_OK Successful.
2197 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2198 * @retval ::CA_STATUS_FAILED Operation failed.
2201 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
2202 const uint8_t *data,
2203 uint32_t dataLength,
2204 uint32_t *sentLength);
2207 * This function will receive the data from the GattClient and add the
2208 * data into the Client receiver queue.
2210 * @param[in] remoteAddress Remote address of the device from where
2212 * @param[in] data Actual data recevied from the remote
2214 * @param[in] dataLength Length of the data received from the
2216 * @param[in] sentLength Length of the data sent from the remote
2219 * @return ::CA_STATUS_OK or Appropriate error code.
2220 * @retval ::CA_STATUS_OK Successful.
2221 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2222 * @retval ::CA_STATUS_FAILED Operation failed.
2224 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
2225 const uint8_t *data,
2226 uint32_t dataLength,
2227 uint32_t *sentLength);
2230 * Set the NetworkPacket received callback to CA layer from adapter
2233 * @param[in] callback Callback handle sent from the upper layer.
2235 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
2238 * Push the data from CA layer to the Sender processor queue.
2240 * @param[in] remoteEndpoint Remote endpoint information of the
2242 * @param[in] data Data to be transmitted from LE.
2243 * @param[in] dataLen Length of the Data being transmitted.
2245 * @return ::CA_STATUS_OK or Appropriate error code.
2246 * @retval ::CA_STATUS_OK Successful.
2247 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2248 * @retval ::CA_STATUS_FAILED Operation failed.
2250 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
2251 const uint8_t *data,
2255 * Push the data from CA layer to the Sender processor queue.
2257 * @param[in] remoteEndpoint Remote endpoint information of the
2259 * @param[in] data Data to be transmitted from LE.
2260 * @param[in] dataLen Length of the Data being transmitted.
2262 * @return ::CA_STATUS_OK or Appropriate error code.
2263 * @retval ::CA_STATUS_OK Successful.
2264 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2265 * @retval ::CA_STATUS_FAILED Operation failed.
2267 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
2268 const uint8_t *data,
2271 static CAResult_t CALEAdapterGattServerStart()
2273 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2274 CAResult_t result = CA_STATUS_FAILED;
2276 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2278 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2279 caglobals.bleFlags);
2280 return CA_STATUS_OK;
2283 #ifndef DISABLE_BLE_SERVER
2284 OIC_LOG_V(INFO, CALEADAPTER_TAG, "Starting LE GATT Server");
2285 result = CAStartLEGattServer();
2288 #ifndef SINGLE_THREAD
2290 Don't start the server side sending queue thread until the
2291 server itself has actually started.
2293 if (CA_STATUS_OK == result)
2295 result = CAQueueingThreadStart(g_bleServerSendQueueHandle);
2296 if (CA_STATUS_OK != result)
2300 "Unable to start server queuing thread (%d)",
2309 static CAResult_t CALEAdapterGattServerStop()
2311 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2313 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2315 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2316 caglobals.bleFlags);
2317 return CA_STATUS_OK;
2320 #ifndef SINGLE_THREAD
2322 CAResult_t res = CAQueueingThreadStop(g_bleServerSendQueueHandle);
2323 if (CA_STATUS_OK != res)
2325 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAQueueingThreadStop has failed");
2327 res = CAStopLEGattServer();
2328 if (CA_STATUS_OK != res)
2330 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAStopLEGattServer has failed");
2335 return CAStopLEGattServer();
2339 static CAResult_t CALEAdapterGattClientStart()
2341 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2343 CAResult_t result = CAStartLEGattClient();
2345 #ifndef SINGLE_THREAD
2347 Don't start the client side sending queue thread until the
2348 client itself has actually started.
2350 if (CA_STATUS_OK == result)
2352 result = CAQueueingThreadStart(g_bleClientSendQueueHandle);
2353 if (CA_STATUS_OK != result)
2357 "Unable to start client queuing thread");
2365 static CAResult_t CALEAdapterGattClientStop()
2367 #ifndef SINGLE_THREAD
2368 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2369 CAStopLEGattClient();
2371 CAResult_t result = CAQueueingThreadStop(g_bleClientSendQueueHandle);
2375 CAStopLEGattClient();
2377 return CA_STATUS_OK;
2381 #ifdef __WITH_DTLS__
2382 static ssize_t CALESecureSendDataCB(CAEndpoint_t *endpoint, const void *data, size_t dataLen)
2384 VERIFY_NON_NULL(endpoint, CALEADAPTER_TAG, "endpoint is NULL");
2385 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "data is NULL");
2386 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2387 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "encrypted datalen = %zd", dataLen);
2390 CADataType_t dataType = g_dataType;
2393 if (ADAPTER_SERVER == g_adapterType ||
2394 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2396 result = CALEAdapterServerSendData(endpoint, data, dataLen);
2397 if (CA_STATUS_OK != result)
2399 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed" );
2403 g_errorHandler(endpoint, data, dataLen, result);
2407 ret = (ssize_t)dataLen;
2409 else if (ADAPTER_CLIENT == g_adapterType ||
2410 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
2411 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
2413 result = CALEAdapterClientSendData(endpoint, data, dataLen);
2414 if (CA_STATUS_OK != result)
2416 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
2420 g_errorHandler(endpoint, data, dataLen, result);
2424 ret = (ssize_t)dataLen;
2428 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2429 "Can't Send Message adapterType = %d, dataType = %d", g_adapterType, dataType);
2432 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2436 CAResult_t CALESecureReceiveDataCB(const CASecureEndpoint_t *sep, const void *data,
2439 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2441 VERIFY_NON_NULL(sep, CALEADAPTER_TAG, "sep is NULL");
2442 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "data is NULL");
2444 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2445 "Secure Data Receive - decrypted datalen = %zd", dataLen);
2449 OIC_LOG(ERROR, CALEADAPTER_TAG, "incorrect dataLen, derecypt fail !");
2450 return CA_STATUS_INVALID_PARAM;
2453 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2455 CAResult_t res = CA_STATUS_OK;
2456 if (g_networkPacketReceivedCallback)
2458 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2459 "[CALESecureReceiveDataCB] Secure flags = %d, %x",
2460 sep->endpoint.flags, sep->endpoint.flags);
2461 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2462 "[CALESecureReceiveDataCB] Received data up !");
2463 res = g_networkPacketReceivedCallback(sep, data, dataLen);
2464 if (CA_STATUS_OK != res)
2466 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Error parsing CoAP data, res = %d", res);
2473 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
2474 CANetworkPacketReceivedCallback reqRespCallback,
2475 CAAdapterChangeCallback netCallback,
2476 CAConnectionChangeCallback connCallback,
2477 CAErrorHandleCallback errorCallback,
2478 ca_thread_pool_t handle)
2480 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2483 VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null");
2484 VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null");
2485 VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null");
2486 VERIFY_NON_NULL(connCallback, CALEADAPTER_TAG, "ConnectionChange Callback is null");
2488 CAResult_t result = CA_STATUS_OK;
2489 result = CAInitLEAdapterMutex();
2490 if (CA_STATUS_OK != result)
2492 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
2493 return CA_STATUS_FAILED;
2496 result = CAInitializeLENetworkMonitor();
2497 if (CA_STATUS_OK != result)
2499 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
2500 return CA_STATUS_FAILED;
2502 CAInitializeLEAdapter();
2504 result = CAInitializeLEGattClient();
2505 if (CA_STATUS_OK != result)
2507 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattClient() failed");
2508 return CA_STATUS_FAILED;
2511 CASetLEClientThreadPoolHandle(handle);
2513 CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
2514 CASetLEServerThreadPoolHandle(handle);
2515 result = CAInitializeLEGattServer();
2516 if (CA_STATUS_OK != result)
2518 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattServer() failed");
2519 return CA_STATUS_FAILED;
2522 CASetLEAdapterThreadPoolHandle(handle);
2523 CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
2524 CASetLEReqRespAdapterCallback(reqRespCallback);
2526 CASetBLEClientErrorHandleCallback(CALEErrorHandler);
2527 CASetBLEServerErrorHandleCallback(CALEErrorHandler);
2528 CALERegisterNetworkNotifications(netCallback, connCallback);
2530 g_errorHandler = errorCallback;
2532 #ifdef __WITH_DTLS__
2533 if (CA_STATUS_OK != CAinitSslAdapter())
2535 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to init SSL adapter");
2539 CAsetSslAdapterCallbacks(CALESecureReceiveDataCB, CALESecureSendDataCB,
2540 CA_ADAPTER_GATT_BTLE);
2544 static const CAConnectivityHandler_t connHandler =
2546 .startAdapter = CAStartLE,
2547 .stopAdapter = CAStopLE,
2548 .startListenServer = CAStartLEListeningServer,
2549 .stopListenServer = CAStopLEListeningServer,
2550 .startDiscoveryServer = CAStartLEDiscoveryServer,
2551 .sendData = CASendLEUnicastData,
2552 .sendDataToAll = CASendLEMulticastData,
2553 .GetnetInfo = CAGetLEInterfaceInformation,
2554 .readData = CAReadLEData,
2555 .terminate = CATerminateLE,
2556 .cType = CA_ADAPTER_GATT_BTLE
2559 registerCallback(connHandler);
2560 return CA_STATUS_OK;
2563 static CAResult_t CAStartLE()
2565 return CAStartLEAdapter();
2568 static CAResult_t CAStopLE()
2571 #ifndef SINGLE_THREAD
2575 oc_mutex_lock(g_bleIsServerMutex);
2576 switch (g_adapterType)
2578 case ADAPTER_SERVER:
2579 CALEAdapterGattServerStop();
2581 case ADAPTER_CLIENT:
2582 CALEAdapterGattClientStop();
2584 case ADAPTER_BOTH_CLIENT_SERVER:
2585 CALEAdapterGattServerStop();
2586 CALEAdapterGattClientStop();
2591 oc_mutex_unlock(g_bleIsServerMutex);
2592 return CAStopLEAdapter();
2595 static void CATerminateLE()
2597 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2599 CASetLEReqRespServerCallback(NULL);
2600 CASetLEReqRespClientCallback(NULL);
2601 CALERegisterNetworkNotifications(NULL, NULL);
2602 CASetLEReqRespAdapterCallback(NULL);
2603 CATerminateLENetworkMonitor();
2605 oc_mutex_lock(g_bleIsServerMutex);
2606 switch (g_adapterType)
2608 case ADAPTER_SERVER:
2609 CATerminateLEGattServer();
2611 case ADAPTER_CLIENT:
2612 CATerminateLEGattClient();
2614 case ADAPTER_BOTH_CLIENT_SERVER:
2615 CATerminateLEGattServer();
2616 CATerminateLEGattClient();
2621 g_adapterType = ADAPTER_EMPTY;
2622 oc_mutex_unlock(g_bleIsServerMutex);
2624 #ifndef SINGLE_THREAD
2625 CATerminateLEQueues();
2628 #ifdef __WITH_DTLS__
2629 CAsetSslAdapterCallbacks(NULL, NULL, CA_ADAPTER_GATT_BTLE);
2632 CATerminateLEAdapterMutex();
2635 static CAResult_t CAStartLEListeningServer()
2637 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2639 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2641 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2642 caglobals.bleFlags);
2643 return CA_STATUS_OK;
2646 #ifndef ROUTING_GATEWAY
2647 CAResult_t result = CA_STATUS_OK;
2648 #ifndef SINGLE_THREAD
2649 result = CAInitLEServerQueues();
2650 if (CA_STATUS_OK != result)
2652 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
2657 oc_mutex_lock(g_bleIsServerMutex);
2658 switch (g_adapterType)
2660 case ADAPTER_CLIENT:
2661 g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2663 case ADAPTER_BOTH_CLIENT_SERVER:
2666 g_adapterType = ADAPTER_SERVER;
2668 oc_mutex_unlock(g_bleIsServerMutex);
2670 result = CAGetLEAdapterState();
2671 if (CA_STATUS_OK != result)
2673 if (CA_ADAPTER_NOT_ENABLED == result)
2677 "Listen Server will be started once BT Adapter is enabled");
2678 result = CA_STATUS_OK;
2683 result = CALEAdapterGattServerStart();
2686 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2689 // Routing Gateway only supports BLE client mode.
2690 OIC_LOG(ERROR, CALEADAPTER_TAG, "LE server not supported in Routing Gateway");
2691 return CA_NOT_SUPPORTED;
2695 static CAResult_t CAStopLEListeningServer()
2697 OIC_LOG(ERROR, CALEADAPTER_TAG, "Listen server stop not supported.");
2698 return CA_NOT_SUPPORTED;
2701 static CAResult_t CAStartLEDiscoveryServer()
2703 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2704 CAResult_t result = CA_STATUS_OK;
2705 #ifndef SINGLE_THREAD
2706 result = CAInitLEClientQueues();
2707 if (CA_STATUS_OK != result)
2709 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
2714 oc_mutex_lock(g_bleIsServerMutex);
2715 switch (g_adapterType)
2717 case ADAPTER_SERVER:
2718 g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2720 case ADAPTER_BOTH_CLIENT_SERVER:
2723 g_adapterType = ADAPTER_CLIENT;
2725 oc_mutex_unlock(g_bleIsServerMutex);
2727 result = CAGetLEAdapterState();
2728 if (CA_STATUS_OK != result)
2730 if (CA_ADAPTER_NOT_ENABLED == result)
2734 "Discovery Server will be started once BT Adapter is enabled");
2735 result = CA_STATUS_OK;
2740 result = CALEAdapterGattClientStart();
2743 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2747 static CAResult_t CAReadLEData()
2749 #ifdef SINGLE_THREAD
2752 return CA_STATUS_OK;
2755 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2758 CADataType_t dataType)
2760 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2761 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "type(%d)", dataType);
2764 VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
2765 VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2767 CAResult_t result = CA_STATUS_FAILED;
2769 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2770 if (ADAPTER_EMPTY == g_adapterType)
2772 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2775 oc_mutex_lock(g_bleIsServerMutex);
2776 if (ADAPTER_SERVER == g_adapterType ||
2777 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2779 #ifdef __WITH_DTLS__
2780 if (endpoint && endpoint->flags & CA_SECURE)
2782 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2783 "Response Data or server - secured data send(caadapternetdtlsencrypt) call");
2784 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2785 g_dataType = dataType;
2786 oc_mutex_unlock(g_bleIsServerMutex);
2788 result = CAencryptSsl(endpoint, (void *)data, dataLen);
2789 if (CA_STATUS_OK != result)
2791 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
2798 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2799 "server or both - none secured data send(CALEAdapterServerSendData) call");
2800 result = CALEAdapterServerSendData(endpoint, data, dataLen);
2803 result = CALEAdapterServerSendData(endpoint, data, dataLen);
2805 if (CA_STATUS_OK != result)
2807 oc_mutex_unlock(g_bleIsServerMutex);
2808 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed");
2811 g_errorHandler(endpoint, data, dataLen, result);
2817 else if (ADAPTER_CLIENT == g_adapterType ||
2818 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
2819 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
2821 #ifdef __WITH_DTLS__
2822 if (endpoint && endpoint->flags & CA_SECURE)
2824 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2825 "Request Data or client - secured data send(caadapternetdtlsencrypt) call");
2826 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2827 g_dataType = dataType;
2828 oc_mutex_unlock(g_bleIsServerMutex);
2830 result = CAencryptSsl(endpoint, (void *)data, dataLen);
2831 if (CA_STATUS_OK != result)
2833 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
2840 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2841 "client or both - none secured data send(CALEAdapterClientSendData) call");
2842 result = CALEAdapterClientSendData(endpoint, data, dataLen);
2845 result = CALEAdapterClientSendData(endpoint, data, dataLen);
2847 if (CA_STATUS_OK != result)
2849 oc_mutex_unlock(g_bleIsServerMutex);
2850 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
2854 g_errorHandler(endpoint, data, dataLen, result);
2859 oc_mutex_unlock(g_bleIsServerMutex);
2861 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2865 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
2868 CADataType_t dataType)
2870 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2873 VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2877 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
2881 CAResult_t result = CA_STATUS_FAILED;
2883 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2884 if (ADAPTER_EMPTY == g_adapterType)
2886 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2889 oc_mutex_lock(g_bleIsServerMutex);
2890 if (ADAPTER_SERVER == g_adapterType ||
2891 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2893 result = CALEAdapterServerSendData(NULL, data, dataLen);
2894 if (CA_STATUS_OK != result)
2896 oc_mutex_unlock(g_bleIsServerMutex);
2898 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data for server failed" );
2902 g_errorHandler(endpoint, data, dataLen, result);
2908 if (ADAPTER_CLIENT == g_adapterType ||
2909 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
2910 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
2912 result = CALEAdapterClientSendData(NULL, data, dataLen);
2913 if (CA_STATUS_OK != result)
2915 oc_mutex_unlock(g_bleIsServerMutex);
2917 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data for client failed" );
2921 g_errorHandler(endpoint, data, dataLen, result);
2926 oc_mutex_unlock(g_bleIsServerMutex);
2928 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2932 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
2934 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2936 VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
2938 char *local_address = NULL;
2940 CAResult_t res = CAGetLEAddress(&local_address);
2941 if (CA_STATUS_OK != res)
2943 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
2947 if (NULL == local_address)
2949 OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
2950 return CA_STATUS_FAILED;
2954 (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
2955 if (NULL == (*info))
2957 OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
2958 OICFree(local_address);
2959 return CA_STATUS_FAILED;
2962 size_t local_address_len = strlen(local_address);
2964 if(local_address_len >= sizeof(g_localBLEAddress) ||
2965 local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
2967 OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
2969 OICFree(local_address);
2970 return CA_STATUS_FAILED;
2973 OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
2974 oc_mutex_lock(g_bleLocalAddressMutex);
2975 OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
2976 oc_mutex_unlock(g_bleLocalAddressMutex);
2978 (*info)->adapter = CA_ADAPTER_GATT_BTLE;
2980 OICFree(local_address);
2982 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2983 return CA_STATUS_OK;
2986 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
2987 CAConnectionChangeCallback connCallback)
2989 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2991 g_networkCallback = netCallback;
2992 g_connectionCallback = connCallback;
2993 CAResult_t res = CA_STATUS_OK;
2996 res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
2997 if (CA_STATUS_OK != res)
2999 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
3004 res = CAUnSetLEAdapterStateChangedCb();
3005 if (CA_STATUS_OK != res)
3007 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
3011 if (g_connectionCallback)
3013 res = CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCb);
3014 if (CA_STATUS_OK != res)
3016 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLENWConnectionStateChangedCb failed!");
3021 res = CAUnSetLENWConnectionStateChangedCb();
3022 if (CA_STATUS_OK != res)
3024 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUnSetLENWConnectionStateChangedCb failed!");
3028 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3032 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
3035 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3037 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3040 CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE };
3041 OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), address);
3044 oc_mutex_lock(g_bleIsServerMutex);
3045 switch (g_adapterType)
3047 case ADAPTER_SERVER:
3048 CALEGattServerConnectionStateChanged(isConnected, address);
3050 case ADAPTER_CLIENT:
3051 CALEGattConnectionStateChanged(isConnected, address);
3053 case ADAPTER_BOTH_CLIENT_SERVER:
3054 CALEGattConnectionStateChanged(isConnected, address);
3055 CALEGattServerConnectionStateChanged(isConnected, address);
3060 oc_mutex_unlock(g_bleIsServerMutex);
3065 #ifndef SINGLE_THREAD
3066 if(g_bleClientSenderInfo)
3068 CALERemoveReceiveQueueData(g_bleClientSenderInfo, address);
3071 if(g_bleServerSenderInfo)
3073 CALERemoveReceiveQueueData(g_bleServerSenderInfo, address);
3076 // remove data of send queue.
3077 if (g_bleClientSendQueueHandle)
3079 CALERemoveSendQueueData(g_bleClientSendQueueHandle, address);
3082 if (g_bleServerSendQueueHandle)
3084 CALERemoveSendQueueData(g_bleServerSendQueueHandle, address);
3088 #ifdef __WITH_DTLS__
3089 #if defined(__TIZEN__) && !defined(SINGLE_THREAD)
3090 // CAcloseSslConnection returns CAResult_t instead of void*, but the size is the same and crash shouldn't occur
3092 pthread_attr_t attr;
3093 int initAttrRes = -1;
3094 int pthreadCreateRes = -1;
3095 int detachStatusRes = -1;
3096 int memoryAllocationRes = -1;
3100 initAttrRes = pthread_attr_init(&attr);
3101 if (initAttrRes != 0)
3105 CAEndpoint_t *localEndpointCpyPtr = OICMalloc(sizeof(CAEndpoint_t));
3107 if(NULL == localEndpointCpyPtr)
3109 memoryAllocationRes = -1;
3114 memoryAllocationRes = 0;
3117 (*localEndpointCpyPtr) = localEndpoint;
3118 // this piece of code is reached on the main thread
3119 // CAcloseSslConnection might wait for too long (network + mutexes) and watchdog might kill it
3120 // Asynchronous call protects this function from watchdog
3121 pthreadCreateRes = pthread_create(&ccThread, &attr, (void *(*)(void*))&CAcloseSslConnectionFreeEndpoint, (void*)localEndpointCpyPtr);
3123 if (pthreadCreateRes != 0)
3127 detachStatusRes = pthread_detach(ccThread);
3130 // regardless of CAcloseSslConnection result, the function will continue and g_connectionCallback will be called
3131 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "CAcloseSslConnection pthread_init [%d], mem_alloc [%d] pthread_create [%d], pthread_detach [%d]",
3132 initAttrRes, memoryAllocationRes, pthreadCreateRes, detachStatusRes);
3134 CAcloseSslConnection(&localEndpoint);
3139 if (g_connectionCallback)
3141 g_connectionCallback(&localEndpoint, isConnected);
3144 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3147 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
3149 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3151 if (CA_ADAPTER_ENABLED == adapter_state)
3153 oc_mutex_lock(g_bleIsServerMutex);
3154 switch (g_adapterType)
3156 case ADAPTER_SERVER:
3157 CALEAdapterGattServerStart();
3159 case ADAPTER_CLIENT:
3160 CALEAdapterGattClientStart();
3162 case ADAPTER_BOTH_CLIENT_SERVER:
3163 CALEAdapterGattServerStart();
3164 CALEAdapterGattClientStart();
3169 oc_mutex_unlock(g_bleIsServerMutex);
3173 oc_mutex_lock(g_bleIsServerMutex);
3174 switch (g_adapterType)
3176 case ADAPTER_SERVER:
3177 CALEAdapterGattServerStop();
3179 case ADAPTER_CLIENT:
3180 CALEAdapterGattClientStop();
3182 case ADAPTER_BOTH_CLIENT_SERVER:
3183 CALEAdapterGattServerStop();
3184 CALEAdapterGattClientStop();
3189 oc_mutex_unlock(g_bleIsServerMutex);
3192 if (NULL != g_networkCallback)
3194 g_networkCallback(CA_ADAPTER_GATT_BTLE, adapter_state);
3198 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
3201 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3204 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
3205 const uint8_t *data,
3208 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3209 #ifndef SINGLE_THREAD
3210 VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
3211 "g_bleClientSendQueueHandle is NULL",
3214 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%u]", dataLen);
3216 CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3219 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3220 return CA_MEMORY_ALLOC_FAILED;
3222 // Add message to send queue
3224 CAResult_t res = CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData,
3225 sizeof(CALEData_t), true);
3226 if (CA_STATUS_OK != res)
3228 CALEDataDestroyer(bleData, sizeof(CALEData_t));
3231 return CA_STATUS_OK;
3234 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
3235 const uint8_t *data,
3238 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3240 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3242 #ifdef SINGLE_THREAD
3243 if (!CAIsLEConnected())
3245 OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
3246 return CA_STATUS_FAILED;
3249 CAResult_t result = CALEServerSendDataSingleThread(data, dataLen);
3250 if (CA_STATUS_OK != result)
3252 OIC_LOG(ERROR, CALEADAPTER_TAG, "CALEServerSendDataSingleThread failed");
3253 return CA_STATUS_FAILED;
3256 VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
3257 "g_bleServerSendQueueHandle is NULL",
3260 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
3262 CALEData_t * const bleData =
3263 CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3267 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3268 return CA_MEMORY_ALLOC_FAILED;
3271 // Add message to send queue
3273 CAResult_t res = CAQueueingThreadAddData(g_bleServerSendQueueHandle,
3275 sizeof(CALEData_t), true);
3276 if (CA_STATUS_OK != res)
3278 CALEDataDestroyer(bleData, sizeof(CALEData_t));
3281 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3282 return CA_STATUS_OK;
3285 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
3286 const uint8_t *data,
3287 uint32_t dataLength,
3288 uint32_t *sentLength)
3290 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3293 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3294 VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3296 #ifdef SINGLE_THREAD
3297 CALEDataReceiverHandlerSingleThread(data, dataLength);
3299 if (g_singleThreadReceiveData->totalDataLen == g_singleThreadReceiveData->recvDataLen)
3301 if(g_networkPacketReceivedCallback)
3303 // will be filled by upper layer
3304 const CASecureEndpoint_t endpoint =
3305 { .endpoint = { .adapter = CA_ADAPTER_GATT_BTLE } };
3307 g_networkPacketReceivedCallback(&endpoint,
3308 g_singleThreadReceiveData->defragData,
3309 g_singleThreadReceiveData->recvDataLen);
3311 g_singleThreadReceiveData->remoteEndpoint = NULL;
3312 OICFree(g_singleThreadReceiveData->defragData);
3313 g_singleThreadReceiveData->defragData = NULL;
3314 OICFree(g_singleThreadReceiveData);
3315 g_singleThreadReceiveData = NULL;
3318 VERIFY_NON_NULL_RET(g_bleServerReceiverQueue,
3320 "g_bleServerReceiverQueue",
3323 //Add message to data queue
3324 CAEndpoint_t * const remoteEndpoint =
3325 CACreateEndpointObject(CA_DEFAULT_FLAGS,
3326 CA_ADAPTER_GATT_BTLE,
3330 if (NULL == remoteEndpoint)
3332 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3333 return CA_STATUS_FAILED;
3336 // Create bleData to add to queue
3339 "Data received from LE Server layer [%d]",
3342 CALEData_t * const bleData =
3343 CACreateLEData(remoteEndpoint, data, dataLength, g_bleServerSenderInfo);
3347 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3348 CAFreeEndpoint(remoteEndpoint);
3349 return CA_MEMORY_ALLOC_FAILED;
3352 CAFreeEndpoint(remoteEndpoint);
3353 // Add message to receiver queue
3354 CAResult_t result = CAQueueingThreadAddData(g_bleServerReceiverQueue, bleData, sizeof(CALEData_t), true);
3355 if (result != CA_STATUS_OK)
3357 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to add message to data queue!");
3358 CAFreeLEData(bleData);
3362 *sentLength = dataLength;
3364 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3365 return CA_STATUS_OK;
3368 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
3369 const uint8_t *data,
3370 uint32_t dataLength,
3371 uint32_t *sentLength)
3374 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3375 VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3376 #ifndef SINGLE_THREAD
3377 VERIFY_NON_NULL_RET(g_bleClientReceiverQueue, CALEADAPTER_TAG,
3378 "g_bleClientReceiverQueue",
3381 //Add message to data queue
3382 CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
3383 CA_ADAPTER_GATT_BTLE,
3385 if (NULL == remoteEndpoint)
3387 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3388 return CA_STATUS_FAILED;
3391 // Create bleData to add to queue
3394 "Data received from LE Client layer [%u]",
3397 CALEData_t * const bleData =
3398 CACreateLEData(remoteEndpoint, data, dataLength, g_bleClientSenderInfo);
3402 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3403 CAFreeEndpoint(remoteEndpoint);
3404 return CA_MEMORY_ALLOC_FAILED;
3407 CAFreeEndpoint(remoteEndpoint);
3408 // Add message to receiver queue
3409 CAResult_t result = CAQueueingThreadAddData(g_bleClientReceiverQueue, bleData, sizeof(CALEData_t), true);
3410 if (result != CA_STATUS_OK)
3412 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to add message to data queue!");
3413 CAFreeLEData(bleData);
3417 *sentLength = dataLength;
3419 return CA_STATUS_OK;
3422 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
3424 g_bleAdapterThreadPool = handle;
3428 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
3430 g_networkPacketReceivedCallback = callback;
3434 static void CALEErrorHandler(const char *remoteAddress,
3435 const uint8_t *data,
3439 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3441 VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
3443 CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS,
3444 CA_ADAPTER_GATT_BTLE,
3448 // if required, will be used to build remote endpoint
3449 g_errorHandler(rep, data, dataLen, result);
3451 CAFreeEndpoint(rep);
3453 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3456 #ifndef SINGLE_THREAD
3457 static bool CALEClearQueueAddressDataContext(void *data, uint32_t size, void *ctx)
3459 if (NULL == data || NULL == ctx)
3464 CALEData_t *caLeData = (CALEData_t *)data;
3465 const char *address = (const char *)ctx;
3467 if (NULL != caLeData && NULL != caLeData->remoteEndpoint)
3469 if (!strcasecmp(caLeData->remoteEndpoint->addr, address))
3477 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle, const char* address)
3479 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
3481 VERIFY_NON_NULL_VOID(queueHandle, CALEADAPTER_TAG, "queueHandle");
3482 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3484 CAResult_t res = CAQueueingThreadClearContextData(queueHandle,
3485 CALEClearQueueAddressDataContext,
3487 if (CA_STATUS_OK != res)
3490 OIC_LOG(ERROR, CALEADAPTER_TAG, "Could not clear the send queue");
3495 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList, const char* address)
3497 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
3499 VERIFY_NON_NULL_VOID(dataInfoList, CALEADAPTER_TAG, "dataInfoList");
3500 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3502 CABLESenderInfo_t *senderInfo = NULL;
3503 uint32_t senderIndex = 0;
3505 u_arraylist_t *portList = u_arraylist_create();
3506 if (CA_STATUS_OK == CALEGetPortsFromSenderInfo(address, dataInfoList, portList))
3508 uint32_t arrayLength = u_arraylist_length(portList);
3509 for (uint32_t i = 0; i < arrayLength; i++)
3511 uint16_t *port = (uint16_t *)u_arraylist_get(portList, i);
3514 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to get port from sender info !");
3515 u_arraylist_destroy(portList);
3519 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "port : %X", *port);
3521 if (CA_STATUS_OK == CALEGetSenderInfo(address, *port,
3522 dataInfoList, &senderInfo,
3525 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3526 "SenderInfo is removed for disconnection");
3527 CALERemoveSenderInfoFromList(dataInfoList, senderInfo);
3528 CALEFreeSenderInfo(senderInfo);
3532 OIC_LOG(DEBUG, CALEADAPTER_TAG, "SenderInfo doesn't exist");
3536 u_arraylist_destroy(portList);
3539 static CAResult_t CALEGetPortsFromSenderInfo(const char *leAddress,
3540 u_arraylist_t *senderInfoList,
3541 u_arraylist_t *portList)
3543 VERIFY_NON_NULL(leAddress,
3545 "NULL BLE address argument");
3547 const uint32_t listLength = u_arraylist_length(senderInfoList);
3548 const uint32_t addrLength = strlen(leAddress);
3550 for (uint32_t index = 0; index < listLength; index++)
3552 CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
3553 if (!info || !(info->remoteEndpoint))
3558 if (!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
3560 uint16_t *port = (uint16_t *)OICMalloc(sizeof(uint16_t));
3563 OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
3564 return CA_MEMORY_ALLOC_FAILED;
3566 *port = info->remoteEndpoint->port;
3567 u_arraylist_add(portList, (void *)port);
3571 if (u_arraylist_length(portList) != 0)
3573 return CA_STATUS_OK;
3577 return CA_STATUS_FAILED;
3582 void CALEStartGattServer()
3584 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3586 oc_mutex_lock(g_bleIsServerMutex);
3587 switch (g_adapterType)
3589 case ADAPTER_SERVER:
3590 CALEAdapterGattServerStart();
3592 case ADAPTER_CLIENT:
3593 CALEAdapterGattClientStart();
3595 case ADAPTER_BOTH_CLIENT_SERVER:
3596 CALEAdapterGattServerStart();
3597 CALEAdapterGattClientStart();
3602 oc_mutex_unlock(g_bleIsServerMutex);
3603 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3606 void CALEStopGattServer()
3608 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3610 oc_mutex_lock(g_bleIsServerMutex);
3611 switch (g_adapterType)
3613 case ADAPTER_SERVER:
3614 CALEAdapterGattServerStop();
3616 case ADAPTER_CLIENT:
3617 CALEAdapterGattClientStop();
3619 case ADAPTER_BOTH_CLIENT_SERVER:
3620 CALEAdapterGattServerStop();
3621 CALEAdapterGattClientStop();
3626 oc_mutex_unlock(g_bleIsServerMutex);
3627 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);