1 /* ****************************************************************
3 * Copyright 2014 Samsung Electronics All Rights Reserved.
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 ******************************************************************/
20 #include "caleadapter.h"
25 #include "cafragmentation.h"
27 #include "caleinterface.h"
30 #include "caadapterutils.h"
32 #include "ca_adapter_net_ssl.h"
35 #include "caqueueingthread.h"
37 #if defined(__TIZEN__) || defined(__ANDROID__)
38 #include "caleserver.h"
39 #include "caleclient.h"
41 #include "oic_malloc.h"
42 #include "oic_string.h"
43 #include "caremotehandler.h"
47 * Logging tag for module name.
49 #define CALEADAPTER_TAG "OIC_CA_LE_ADAP"
52 * Stores information of all the senders.
54 * This structure will be used to track and defragment all incoming data packet.
59 uint32_t totalDataLen;
61 CAEndpoint_t *remoteEndpoint;
67 ADAPTER_BOTH_CLIENT_SERVER,
73 * mtu size to use in fragmentation logic.
74 * default value is 20 byte.
76 static uint16_t g_mtuSize = CA_DEFAULT_BLE_MTU_SIZE;
78 * Callback to provide the status of the network change to CA layer.
80 static CAAdapterChangeCallback g_networkCallback = NULL;
83 * Callback to provide the status of the connection change to CA layer.
85 static CAConnectionChangeCallback g_connectionCallback = NULL;
88 * Own port value to identify packet owner. Default port value is 1.
90 static uint8_t g_localBLESourcePort = 1;
93 * bleAddress of the local adapter. Value will be initialized to zero,
94 * and will be updated later.
96 static char g_localBLEAddress[18] = { 0 };
99 * Variable to differentiate btw GattServer and GattClient.
101 static CABLEAdapter_t g_adapterType = ADAPTER_EMPTY;
104 static CADataType_t g_dataType = CA_REQUEST_DATA;
108 * Mutex to synchronize the task to be executed on the GattServer
111 static oc_mutex g_bleIsServerMutex = NULL;
114 * Mutex to synchronize the updates of the local LE address of the
117 static oc_mutex g_bleLocalAddressMutex = NULL;
120 * Reference to thread pool.
122 static ca_thread_pool_t g_bleAdapterThreadPool = NULL;
125 * Mutex to synchronize the queing of the data from ReceiverQueue.
127 static oc_mutex g_bleClientReceiveDataMutex = NULL;
130 * Mutex to synchronize the queing of the data from ReceiverQueue.
132 static oc_mutex g_bleServerReceiveDataMutex = NULL;
136 * Callback to be called when network packet received from either
137 * GattServer or GattClient.
139 static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
142 * Callback to notify error from the BLE adapter.
144 static CAErrorHandleCallback g_errorHandler = NULL;
147 static CAResult_t CALESecureReceiveDataCB(const CASecureEndpoint_t *endpoint,
148 const void *data, size_t dataLength);
150 static ssize_t CALESecureSendDataCB(CAEndpoint_t *endpoint,
151 const void *data, size_t dataLength);
156 * Pointer to defragment received data from single threaded routine.
158 static CABLESenderInfo_t *g_singleThreadReceiveData = NULL;
161 * This function will be associated with the receive for single thread.
163 * This function will defragment the received data from sender
164 * respectively and will send it up to CA layer. Respective sender's
165 * header will provide the length of the data sent.
167 * @param[in] data Actual data received from the remote
169 * @param[in] dataLen Length of the data received from the
172 static void CALEDataReceiverHandlerSingleThread(const uint8_t *data,
176 * This function will be associated with the send for single threaded
179 * This function will fragment the data to the MTU of the transport
180 * and send the data in fragments to the adapters. The function will
181 * be blocked until all data is sent out from the adapter.
183 * @param[in] data Data to be transmitted from LE.
184 * @param[in] dataLen Length of the Data being transmitted.
186 static CAResult_t CALEServerSendDataSingleThread(const uint8_t *data,
191 * Register network change notification callback.
193 * @param[in] netCallback CAAdapterChangeCallback callback which will
194 * be set for the change in adapter.
195 * @param[in] connCallback CAConnectionChangeCallback callback which will
196 * be set for the change in connection.
198 * @return 0 on success otherwise a positive error value.
199 * @retval ::CA_STATUS_OK Successful.
200 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
201 * @retval ::CA_STATUS_FAILED Operation failed.
204 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
205 CAConnectionChangeCallback connCallback);
208 * Set the thread pool handle which is required for spawning new
211 * @param[in] handle Thread pool handle which is given by above layer
212 * for using thread creation task.
215 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle);
218 * Call the callback to the upper layer when the adapter state gets
221 * @param[in] adapter_state New state of the adapter to be notified to
224 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state);
227 * Call the callback to the upper layer when the device connection state gets
230 * @param[in] address LE address of the device to be notified to the upper layer.
231 * @param[in] isConnected whether connection state is connected or not.
233 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
237 * Used to initialize all required mutex variable for LE Adapter
240 * @return 0 on success otherwise a positive error value.
241 * @retval ::CA_STATUS_OK Successful.
242 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
243 * @retval ::CA_STATUS_FAILED Operation failed.
246 static CAResult_t CAInitLEAdapterMutex();
249 * Terminate all required mutex variables for LE adapter
252 static void CATerminateLEAdapterMutex();
255 * Prepares and notify error through error callback.
257 static void CALEErrorHandler(const char *remoteAddress,
262 #ifndef SINGLE_THREAD
264 * Stop condition of Server recvhandler.
266 static bool g_dataBleServerReceiverHandlerState = false;
269 * Stop condition of Client recvhandler.
271 static bool g_dataBleClientReceiverHandlerState = false;
274 * Sender information of Server.
276 static u_arraylist_t *g_bleServerSenderInfo = NULL;
279 * Sender information of Client.
281 static u_arraylist_t *g_bleClientSenderInfo = NULL;
284 * Queue to process the outgoing packets from GATTServer.
286 static CAQueueingThread_t *g_bleServerSendQueueHandle = NULL;
289 * Queue to process the outgoing packets from GATTClient.
291 static CAQueueingThread_t *g_bleClientSendQueueHandle = NULL;
294 * Queue to process the incoming packets from GATTServer.
296 static CAQueueingThread_t *g_bleServerReceiverQueue = NULL;
299 * Queue to process the incoming packets from GATTClient.
301 static CAQueueingThread_t *g_bleClientReceiverQueue = NULL;
304 * This function will be associated with the sender queue for
307 * This function will fragment the data to the MTU of the transport
308 * and send the data in fragments to the adapters. The function will
309 * be blocked until all data is sent out from the adapter.
311 * @param[in] threadData Data pushed to the queue which contains the
312 * info about RemoteEndpoint and Data.
314 static void CALEServerSendDataThread(void *threadData);
317 * This function will be associated with the sender queue for
320 * This function will fragment the data to the MTU of the transport
321 * and send the data in fragments to the adapters. The function will
322 * be blocked until all data is sent out from the adapter.
324 * @param[in] threadData Data pushed to the queue which contains the
325 * info about RemoteEndpoint and Data.
327 static void CALEClientSendDataThread(void *threadData);
330 * This function will defragment the received data from each sender
331 * respectively and will send it up to CA layer. Respective sender's
332 * header will provide the length of the data sent.
334 * @param[in] threadData Data pushed to the queue which contains the
335 * info about RemoteEndpoint and Data.
336 * @param[in] receiverType Whether receiver is server or client.
338 static void CALEDataReceiverHandler(void *threadData, CABLEAdapter_t receiverType);
341 * This function will be associated with the receiver queue for
344 * This function will call the function CALEDataReceiverHandler()
345 * with server type to defragment the received data.
347 * @param[in] threadData Data pushed to the queue which contains the
348 * info about RemoteEndpoint and Data.
350 static void CALEServerDataReceiverHandler(void *threadData);
353 * This function will be associated with the receiver queue for
356 * This function will call the function CALEDataReceiverHandler()
357 * with client type to defragment the received data.
359 * @param[in] threadData Data pushed to the queue which contains the
360 * info about RemoteEndpoint and Data.
362 static void CALEClientDataReceiverHandler(void *threadData);
365 * This function will stop all queues created for GattServer and
366 * GattClient. All four queues will be be stopped with this function
369 static void CAStopLEQueues();
372 * This function will terminate all queues created for GattServer and
373 * GattClient. All four queues will be be terminated with this
374 * function invocations.
376 static void CATerminateLEQueues();
379 * This function will initalize the Receiver and Sender queues for
380 * GattServer. This function will in turn call the functions
381 * CAInitBleServerReceiverQueue() and CAInitBleServerSenderQueue() to
382 * initialize the queues.
384 * @return ::CA_STATUS_OK or Appropriate error code.
385 * @retval ::CA_STATUS_OK Successful.
386 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
387 * @retval ::CA_STATUS_FAILED Operation failed.
389 static CAResult_t CAInitLEServerQueues();
392 * This function will initalize the Receiver and Sender queues for
393 * GattClient. This function will inturn call the functions
394 * CAInitBleClientReceiverQueue() and CAInitBleClientSenderQueue() to
395 * initialize the queues.
397 * @return ::CA_STATUS_OK or Appropriate error code.
398 * @retval ::CA_STATUS_OK Successful.
399 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
400 * @retval ::CA_STATUS_FAILED Operation failed.
403 static CAResult_t CAInitLEClientQueues();
406 * This function will initalize the Receiver queue for
407 * GattServer. This will initialize the queue to process the function
408 * CABLEServerSendDataThread() when ever the task is added to this
411 * @return ::CA_STATUS_OK or Appropriate error code.
412 * @retval ::CA_STATUS_OK Successful.
413 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
414 * @retval ::CA_STATUS_FAILED Operation failed.
416 static CAResult_t CAInitLEServerSenderQueue();
419 * This function will initalize the Receiver queue for
420 * GattClient. This will initialize the queue to process the function
421 * CABLEClientSendDataThread() when ever the task is added to this
424 * @return ::CA_STATUS_OK or Appropriate error code.
425 * @retval ::CA_STATUS_OK Successful.
426 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
427 * @retval ::CA_STATUS_FAILED Operation failed.
429 static CAResult_t CAInitLEClientSenderQueue();
432 * This function will initialize the Receiver queue for
433 * GattServer. This will initialize the queue to process the function
434 * CALEServerDataReceiverHandler() when ever the task is added to this
437 * @return ::CA_STATUS_OK or Appropriate error code
438 * @retval ::CA_STATUS_OK Successful
439 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments
440 * @retval ::CA_STATUS_FAILED Operation failed
443 static CAResult_t CAInitLEServerReceiverQueue();
446 * This function will initialize the Receiver queue for
447 * GattClient. This will initialize the queue to process the function
448 * CALEClientDataReceiverHandler() when ever the task is added to this
451 * @return ::CA_STATUS_OK or Appropriate error code
452 * @retval ::CA_STATUS_OK Successful
453 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments
454 * @retval ::CA_STATUS_FAILED Operation failed
457 static CAResult_t CAInitLEClientReceiverQueue();
460 * This function will create the Data required to send it in the
463 * @param[in] remoteEndpoint Remote endpoint information of the
465 * @param[in] data Data to be transmitted from LE.
466 * @param[in] dataLength Length of the Data being transmitted.
468 * @return ::CA_STATUS_OK or Appropriate error code.
469 * @retval ::CA_STATUS_OK Successful.
470 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
471 * @retval ::CA_STATUS_FAILED Operation failed.
473 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
476 u_arraylist_t *senderInfo);
479 * Used to free the BLE information stored in the sender/receiver
482 * @param[in] bleData Information for a particular data segment.
484 static void CAFreeLEData(CALEData_t *bleData);
489 static void CALEDataDestroyer(void *data, uint32_t size);
491 #ifndef SINGLE_THREAD
493 * remove request or response data of send queue.
495 * @param[in] queueHandle queue to process the outgoing packets.
496 * @param[in] mutex mutex related to sender for client / server.
497 * @param[in] address target address to remove data in queue.
499 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle,
500 const char* address);
503 * remove all received data of data list from receive queue.
505 * @param[in] dataInfoList received data list to remove for client / server.
506 * @param[in] address target address to remove data in queue.
508 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList,
509 const char* address);
512 * get received data info and positioned index from the received data list
513 * for client / server which is matched same leAddress and port.
515 * @param[in] leAddress target address to get serderInfo.
516 * @param[in] port target port to get senderInfo.
517 * @param[in] senderInfoList received data list for client / server.
518 * @param[out] senderInfo Pointer to contain matched(leAddress and port)
519 * received data info.
520 * @param[out] senderIndex Pointer to contain matched(leAddress and port)
521 * received data info index.
523 static CAResult_t CALEGetSenderInfo(const char *leAddress,
525 u_arraylist_t *senderInfoList,
526 CABLESenderInfo_t **senderInfo,
527 uint32_t *senderIndex);
530 * get ports related to remote address. It is need because multi application
531 * can have more than 2 senderInfo using same BLE address. So before remove
532 * receive queue data, should get port list from sender Info.
534 * @param[in] leAddress target address to get port in serderInfo.
535 * @param[in] senderInfoList received data list to remove for client / server.
536 * @param[out] portList target port list related to leAddress.
538 static CAResult_t CALEGetPortsFromSenderInfo(const char *leAddress,
539 u_arraylist_t *senderInfoList,
540 u_arraylist_t *portList);
543 static CAResult_t CAInitLEServerQueues()
546 CAResult_t result = CAInitLEServerSenderQueue();
547 if (CA_STATUS_OK != result)
549 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerSenderQueue failed");
551 return CA_STATUS_FAILED;
554 g_bleServerSenderInfo = u_arraylist_create();
555 if (!g_bleServerSenderInfo)
557 OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
558 return CA_MEMORY_ALLOC_FAILED;
561 result = CAInitLEServerReceiverQueue();
562 if (CA_STATUS_OK != result)
564 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerReceiverQueue failed");
565 u_arraylist_free(&g_bleServerSenderInfo);
566 return CA_STATUS_FAILED;
569 g_dataBleServerReceiverHandlerState = true;
573 static CAResult_t CAInitLEClientQueues()
575 CAResult_t result = CAInitLEClientSenderQueue();
576 if (CA_STATUS_OK != result)
578 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientSenderQueue failed");
579 return CA_STATUS_FAILED;
582 g_bleClientSenderInfo = u_arraylist_create();
583 if (!g_bleClientSenderInfo)
585 OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
586 return CA_MEMORY_ALLOC_FAILED;
589 result = CAInitLEClientReceiverQueue();
590 if (CA_STATUS_OK != result)
592 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientReceiverQueue failed");
593 u_arraylist_free(&g_bleClientSenderInfo);
594 return CA_STATUS_FAILED;
597 g_dataBleClientReceiverHandlerState = true;
602 static CAResult_t CAInitLEServerReceiverQueue()
604 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
605 // Check if the message queue is already initialized
606 if (g_bleServerReceiverQueue)
608 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
612 // Create recv message queue
613 g_bleServerReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
614 if (!g_bleServerReceiverQueue)
616 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
617 return CA_MEMORY_ALLOC_FAILED;
620 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerReceiverQueue,
621 g_bleAdapterThreadPool,
622 CALEServerDataReceiverHandler,
625 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize server receiver queue thread");
626 OICFree(g_bleServerReceiverQueue);
627 g_bleServerReceiverQueue = NULL;
628 return CA_STATUS_FAILED;
631 if (CA_STATUS_OK != CAQueueingThreadStart(g_bleServerReceiverQueue))
633 OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
634 OICFree(g_bleServerReceiverQueue);
635 g_bleServerReceiverQueue = NULL;
636 return CA_STATUS_FAILED;
642 static CAResult_t CAInitLEClientReceiverQueue()
644 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
645 // Check if the message queue is already initialized
646 if (g_bleClientReceiverQueue)
648 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
652 // Create recv message queue
653 g_bleClientReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
654 if (!g_bleClientReceiverQueue)
656 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
657 return CA_MEMORY_ALLOC_FAILED;
660 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientReceiverQueue,
661 g_bleAdapterThreadPool,
662 CALEClientDataReceiverHandler,
665 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize client receiver queue thread");
666 OICFree(g_bleClientReceiverQueue);
667 g_bleClientReceiverQueue = NULL;
668 return CA_STATUS_FAILED;
671 if (CA_STATUS_OK != CAQueueingThreadStart(g_bleClientReceiverQueue))
673 OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
674 OICFree(g_bleClientReceiverQueue);
675 g_bleClientReceiverQueue = NULL;
676 return CA_STATUS_FAILED;
682 static CAResult_t CAInitLEServerSenderQueue()
684 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
685 // Check if the message queue is already initialized
686 if (g_bleServerSendQueueHandle)
688 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Queue is already initialized!");
692 // Create send message queue
693 g_bleServerSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
694 if (!g_bleServerSendQueueHandle)
696 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
697 return CA_MEMORY_ALLOC_FAILED;
700 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerSendQueueHandle,
701 g_bleAdapterThreadPool,
702 CALEServerSendDataThread,
705 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
706 OICFree(g_bleServerSendQueueHandle);
707 g_bleServerSendQueueHandle = NULL;
708 return CA_STATUS_FAILED;
714 static void CALEClearSenderInfoImpl(u_arraylist_t **list)
716 const size_t length = u_arraylist_length(*list);
717 for (size_t i = 0; i < length; ++i)
719 CABLESenderInfo_t * const info =
720 (CABLESenderInfo_t *) u_arraylist_get(*list, i);
723 OICFree(info->defragData);
724 CAFreeEndpoint(info->remoteEndpoint);
728 u_arraylist_free(list);
731 static void CALEClearSenderInfo()
733 CALEClearSenderInfoImpl(&g_bleServerSenderInfo);
734 CALEClearSenderInfoImpl(&g_bleClientSenderInfo);
737 static CAResult_t CAInitLEClientSenderQueue()
739 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
741 if (g_bleClientSendQueueHandle)
743 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
747 // Create send message queue
748 g_bleClientSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
749 if (!g_bleClientSendQueueHandle)
751 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
752 return CA_MEMORY_ALLOC_FAILED;
755 if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientSendQueueHandle,
756 g_bleAdapterThreadPool,
757 CALEClientSendDataThread, CALEDataDestroyer))
759 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
760 OICFree(g_bleClientSendQueueHandle);
761 g_bleClientSendQueueHandle = NULL;
762 return CA_STATUS_FAILED;
767 static void CAStopLEQueues()
769 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
771 oc_mutex_lock(g_bleServerReceiveDataMutex);
772 if (NULL != g_bleServerReceiverQueue)
774 CAQueueingThreadStop(g_bleServerReceiverQueue);
776 oc_mutex_unlock(g_bleServerReceiveDataMutex);
778 oc_mutex_lock(g_bleClientReceiveDataMutex);
779 if (NULL != g_bleClientReceiverQueue)
781 CAQueueingThreadStop(g_bleClientReceiverQueue);
783 oc_mutex_unlock(g_bleClientReceiveDataMutex);
785 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
788 static void CATerminateLEQueues()
790 CAQueueingThreadDestroy(g_bleClientSendQueueHandle);
791 OICFree(g_bleClientSendQueueHandle);
792 g_bleClientSendQueueHandle = NULL;
794 CAQueueingThreadDestroy(g_bleServerSendQueueHandle);
795 OICFree(g_bleServerSendQueueHandle);
796 g_bleServerSendQueueHandle = NULL;
798 CAQueueingThreadDestroy(g_bleServerReceiverQueue);
799 OICFree(g_bleServerReceiverQueue);
800 g_bleServerReceiverQueue = NULL;
802 CAQueueingThreadDestroy(g_bleClientReceiverQueue);
803 OICFree(g_bleClientReceiverQueue);
804 g_bleClientReceiverQueue = NULL;
806 CALEClearSenderInfo();
809 static CAResult_t CALEGetSenderInfo(const char *leAddress,
811 u_arraylist_t *senderInfoList,
812 CABLESenderInfo_t **senderInfo,
813 uint32_t *senderIndex)
815 VERIFY_NON_NULL_RET(leAddress,
817 "NULL BLE address argument",
818 CA_STATUS_INVALID_PARAM);
819 VERIFY_NON_NULL_RET(senderIndex,
821 "NULL index argument",
822 CA_STATUS_INVALID_PARAM);
824 const uint32_t listLength = u_arraylist_length(senderInfoList);
825 const uint32_t addrLength = strlen(leAddress);
826 for (uint32_t index = 0; index < listLength; index++)
828 CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
829 if (!info || !(info->remoteEndpoint))
834 if (!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
836 if (info->remoteEndpoint->port == port)
838 *senderIndex = index;
848 return CA_STATUS_FAILED;
851 static void CALEDataReceiverHandler(void *threadData, CABLEAdapter_t receiverType)
853 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
855 oc_mutex bleReceiveDataMutex = NULL;
856 bool dataBleReceiverHandlerState = false;
858 switch (receiverType)
861 bleReceiveDataMutex = g_bleClientReceiveDataMutex;
862 dataBleReceiverHandlerState = g_dataBleClientReceiverHandlerState;
865 bleReceiveDataMutex = g_bleServerReceiveDataMutex;
866 dataBleReceiverHandlerState = g_dataBleServerReceiverHandlerState;
869 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Unsupported receiver type : %d", receiverType);
873 oc_mutex_lock(bleReceiveDataMutex);
875 if (dataBleReceiverHandlerState)
877 CALEData_t *bleData = (CALEData_t *) threadData;
880 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bleData!");
881 oc_mutex_unlock(bleReceiveDataMutex);
885 if (!(bleData->senderInfo))
887 OIC_LOG(ERROR, CALEADAPTER_TAG, "sender info is not available");
888 oc_mutex_unlock(bleReceiveDataMutex);
892 if (!(bleData->remoteEndpoint))
894 OIC_LOG(ERROR, CALEADAPTER_TAG, "RemoteEndPoint NULL!!");
895 oc_mutex_unlock(bleReceiveDataMutex);
899 CABLESenderInfo_t *senderInfo = NULL;
900 uint32_t senderIndex = 0;
903 CABLEPacketStart_t startFlag = CA_BLE_PACKET_NOT_START;
904 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
905 uint16_t sourcePort = 0;
906 uint16_t destPort = 0;
908 CAParseHeader(bleData->data, &startFlag, &sourcePort, &secureFlag, &destPort);
909 OIC_LOG_V(INFO, CALEADAPTER_TAG,
910 "header info: startFlag[%X] sourcePort[%d] secureFlag[%X] destPort[%d]",
911 startFlag, sourcePort, secureFlag, destPort);
913 if (destPort != g_localBLESourcePort && destPort != CA_BLE_MULTICAST_PORT)
915 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
916 "this packet is not valid for this app(port mismatch[mine:%d, packet:%d])",
917 g_localBLESourcePort, destPort);
918 oc_mutex_unlock(bleReceiveDataMutex);
922 bleData->remoteEndpoint->port = sourcePort;
924 if (CA_STATUS_OK != CALEGetSenderInfo(bleData->remoteEndpoint->addr,
925 bleData->remoteEndpoint->port,
927 &senderInfo, &senderIndex))
929 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This is a new client [%s:%X]",
930 bleData->remoteEndpoint->addr, bleData->remoteEndpoint->port);
936 OIC_LOG(ERROR, CALEADAPTER_TAG,
937 "This packet is start packet but exist senderInfo. Remove senderInfo");
938 u_arraylist_remove(bleData->senderInfo, senderIndex);
939 OICFree(senderInfo->defragData);
948 uint32_t totalLength = 0;
951 CAParseHeaderPayloadLength(bleData->data, CA_BLE_LENGTH_HEADER_SIZE, &totalLength);
955 OIC_LOG(ERROR, CALEADAPTER_TAG, "This packet is wrong packet! ignore.");
956 oc_mutex_unlock(bleReceiveDataMutex);
960 CABLESenderInfo_t *newSender = OICMalloc(sizeof(CABLESenderInfo_t));
963 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
964 oc_mutex_unlock(bleReceiveDataMutex);
967 newSender->recvDataLen = 0;
968 newSender->totalDataLen = 0;
969 newSender->defragData = NULL;
970 newSender->remoteEndpoint = NULL;
972 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
974 newSender->totalDataLen = totalLength;
976 if (!(newSender->totalDataLen))
978 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
980 oc_mutex_unlock(bleReceiveDataMutex);
985 bleData->dataLen - (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE);
986 OIC_LOG_V(INFO, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
987 newSender->totalDataLen);
988 OIC_LOG_V(INFO, CALEADAPTER_TAG, "data received in the first packet [%zu] bytes",
991 newSender->defragData = OICCalloc(newSender->totalDataLen + 1,
992 sizeof(*newSender->defragData));
994 if (NULL == newSender->defragData)
996 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
998 oc_mutex_unlock(bleReceiveDataMutex);
1001 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
1002 #ifdef __WITH_DTLS__
1003 if (CA_BLE_PACKET_SECURE == secureFlag)
1009 const char *remoteAddress = bleData->remoteEndpoint->addr;
1010 newSender->remoteEndpoint = CACreateEndpointObject(flags,
1011 CA_ADAPTER_GATT_BTLE,
1013 bleData->remoteEndpoint->port);
1015 if (NULL == newSender->remoteEndpoint)
1017 OIC_LOG(ERROR, CALEADAPTER_TAG, "remoteEndpoint is NULL!");
1018 OICFree(newSender->defragData);
1020 oc_mutex_unlock(bleReceiveDataMutex);
1024 if (newSender->recvDataLen + dataOnlyLen > newSender->totalDataLen)
1026 OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
1027 OICFree(newSender->defragData);
1028 CAFreeEndpoint(newSender->remoteEndpoint);
1030 oc_mutex_unlock(bleReceiveDataMutex);
1033 memcpy(newSender->defragData,
1034 bleData->data + (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE),
1036 newSender->recvDataLen += dataOnlyLen;
1038 u_arraylist_add(bleData->senderInfo,(void *)newSender);
1040 //Getting newSender index position in bleSenderInfo array list
1042 CALEGetSenderInfo(newSender->remoteEndpoint->addr,
1043 newSender->remoteEndpoint->port,
1044 bleData->senderInfo,
1045 NULL, &senderIndex))
1047 OIC_LOG(ERROR, CALEADAPTER_TAG, "Existing sender index not found!!");
1048 OICFree(newSender->defragData);
1049 CAFreeEndpoint(newSender->remoteEndpoint);
1051 oc_mutex_unlock(bleReceiveDataMutex);
1054 senderInfo = newSender;
1058 size_t dataOnlyLen = bleData->dataLen - CA_BLE_HEADER_SIZE;
1059 if (senderInfo->recvDataLen + dataOnlyLen > senderInfo->totalDataLen)
1061 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1062 "Data Length exceeding error!! Receiving [%zu] total length [%u]",
1063 senderInfo->recvDataLen + dataOnlyLen, senderInfo->totalDataLen);
1064 u_arraylist_remove(bleData->senderInfo, senderIndex);
1065 OICFree(senderInfo->defragData);
1066 OICFree(senderInfo);
1067 oc_mutex_unlock(bleReceiveDataMutex);
1070 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%zu]",
1072 memcpy(senderInfo->defragData + senderInfo->recvDataLen,
1073 bleData->data + CA_BLE_HEADER_SIZE,
1075 senderInfo->recvDataLen += dataOnlyLen;
1076 OIC_LOG_V(INFO, CALEADAPTER_TAG, "totalDatalength [%d] received Datalen [%d]",
1077 senderInfo->totalDataLen, senderInfo->recvDataLen);
1080 if (senderInfo->totalDataLen == senderInfo->recvDataLen)
1082 if (NULL == g_networkPacketReceivedCallback)
1084 OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
1086 u_arraylist_remove(bleData->senderInfo, senderIndex);
1087 OICFree(senderInfo->defragData);
1088 OICFree(senderInfo);
1089 oc_mutex_unlock(bleReceiveDataMutex);
1093 OIC_LOG(DEBUG, CALEADAPTER_TAG, "[CALEDataReceiverHandler] Received data up !");
1095 const CASecureEndpoint_t tmp =
1097 .endpoint = *senderInfo->remoteEndpoint
1100 OIC_LOG_V(INFO, CALEADAPTER_TAG, "endpoint flags : %d", tmp.endpoint.flags);
1101 #ifdef __WITH_DTLS__
1102 if (CA_SECURE & tmp.endpoint.flags)
1104 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Secure data received");
1105 switch (receiverType)
1107 case ADAPTER_CLIENT:
1108 g_dataType = CA_REQUEST_DATA;
1110 case ADAPTER_SERVER:
1111 g_dataType = CA_RESPONSE_DATA;
1114 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Unsupported rcvr type:%d",receiverType);
1115 u_arraylist_remove(bleData->senderInfo, senderIndex);
1116 senderInfo->remoteEndpoint = NULL;
1117 senderInfo->defragData = NULL;
1118 OICFree(senderInfo);
1119 oc_mutex_unlock(bleReceiveDataMutex);
1123 if (CA_STATUS_FAILED == CAdecryptSsl(&tmp,
1124 senderInfo->defragData,
1125 senderInfo->recvDataLen))
1127 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAdecryptSsl failed");
1131 OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAdecryptSsl successed");
1133 OICFree(senderInfo->defragData);
1138 OIC_LOG(INFO, CALEADAPTER_TAG, "Non-Secure data received");
1139 g_networkPacketReceivedCallback(&tmp,
1140 senderInfo->defragData,
1141 senderInfo->recvDataLen);
1142 #ifdef __WITH_DTLS__
1146 u_arraylist_remove(bleData->senderInfo, senderIndex);
1147 senderInfo->remoteEndpoint = NULL;
1148 senderInfo->defragData = NULL;
1149 OICFree(senderInfo);
1152 oc_mutex_unlock(bleReceiveDataMutex);
1156 static void CALEServerDataReceiverHandler(void *threadData)
1158 CALEDataReceiverHandler(threadData, ADAPTER_SERVER);
1161 static void CALEClientDataReceiverHandler(void *threadData)
1163 CALEDataReceiverHandler(threadData, ADAPTER_CLIENT);
1166 static void CALEServerSendDataThread(void *threadData)
1168 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1170 CALEData_t * const bleData = (CALEData_t *) threadData;
1173 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid bledata!");
1177 if (!bleData->remoteEndpoint)
1179 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid endpoint of bledata!");
1183 #if defined(__TIZEN__) || defined(__ANDROID__)
1185 g_mtuSize = CALEServerGetMtuSize(bleData->remoteEndpoint->addr);
1187 OIC_LOG_V(INFO, CALEADAPTER_TAG, "MTU size [%d]", g_mtuSize);
1189 uint32_t midPacketCount = 0;
1190 size_t remainingLen = 0;
1191 size_t totalLength = 0;
1192 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1194 CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
1200 if (CA_STATUS_OK != result)
1202 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1203 "CAGenerateVariableForFragmentation failed, result [%d]", result);
1206 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1211 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1212 "Packet info: data size[%d] midPacketCount[%u] remainingLen[%zu] totalLength[%zu]",
1213 bleData->dataLen, midPacketCount, remainingLen, totalLength);
1217 "Server total Data length with header is [%zu]",
1220 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1221 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1223 if (NULL != bleData->remoteEndpoint) //Unicast Data
1225 secureFlag = (bleData->remoteEndpoint->flags & CA_SECURE) ?
1226 CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
1228 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This Packet is secure? %d", secureFlag);
1229 result = CAGenerateHeader(dataHeader,
1230 CA_BLE_PACKET_START,
1231 g_localBLESourcePort,
1233 bleData->remoteEndpoint->port);
1235 else //Multicast Data
1237 result = CAGenerateHeader(dataHeader,
1238 CA_BLE_PACKET_START,
1239 g_localBLESourcePort,
1241 CA_BLE_MULTICAST_PORT);
1243 OIC_LOG_V(INFO, CALEADAPTER_TAG, "header info: secureFlag[%X]", secureFlag);
1245 if (CA_STATUS_OK != result)
1247 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1248 "CAGenerateHeader failed, result [%d]", result);
1251 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1256 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1257 result = CAGenerateHeaderPayloadLength(lengthHeader,
1258 CA_BLE_LENGTH_HEADER_SIZE,
1261 if (CA_STATUS_OK != result)
1263 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1264 "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1267 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1272 uint32_t length = 0;
1273 uint32_t dataLen = 0;
1274 if (g_mtuSize > totalLength)
1276 length = (uint32_t)totalLength;
1277 dataLen = bleData->dataLen;
1282 dataLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1285 result = CAMakeFirstDataSegment(dataSegment,
1286 bleData->data, dataLen,
1287 dataHeader, lengthHeader);
1289 if (CA_STATUS_OK != result)
1291 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1292 "Making data segment failed, result [%d]", result);
1295 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1300 const uint32_t iter = midPacketCount;
1303 // Send the first segment with the header.
1304 if (NULL != bleData->remoteEndpoint) // Sending Unicast Data
1306 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Unicast Data");
1308 result = CAUpdateCharacteristicsToGattClient(
1309 bleData->remoteEndpoint->addr, dataSegment, length);
1311 if (CA_STATUS_OK != result)
1315 "Update characteristics failed, result [%d]",
1319 g_errorHandler(bleData->remoteEndpoint,
1329 "Server Sent Unicast First Data - data length [%u]",
1332 result = CAGenerateHeader(dataHeader,
1333 CA_BLE_PACKET_NOT_START,
1334 g_localBLESourcePort,
1336 bleData->remoteEndpoint->port);
1338 if (CA_STATUS_OK != result)
1340 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1341 "CAGenerateHeader failed, result [%d]", result);
1344 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1349 for (index = 0; index < iter; index++)
1351 // Send the remaining header.
1352 result = CAMakeRemainDataSegment(dataSegment,
1353 g_mtuSize - CA_BLE_HEADER_SIZE,
1360 if (CA_STATUS_OK != result)
1362 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1363 "Making data segment failed, result [%d]", result);
1366 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1372 CAUpdateCharacteristicsToGattClient(
1373 bleData->remoteEndpoint->addr,
1377 if (CA_STATUS_OK != result)
1379 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1380 "Update characteristics failed, result [%d]", result);
1383 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1387 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]",
1391 if (remainingLen && (totalLength > g_mtuSize))
1393 // send the last segment of the data (Ex: 22 bytes of 622
1394 // bytes of data when MTU is 200)
1395 result = CAMakeRemainDataSegment(dataSegment,
1403 if (CA_STATUS_OK != result)
1405 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1406 "Making data segment failed, result [%d]", result);
1409 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1414 result = CAUpdateCharacteristicsToGattClient(
1415 bleData->remoteEndpoint->addr,
1417 remainingLen + CA_BLE_HEADER_SIZE);
1419 if (CA_STATUS_OK != result)
1423 "Update characteristics failed, result [%d]",
1427 g_errorHandler(bleData->remoteEndpoint,
1436 "Server Sent Unicast Last Data - data length [%zu]",
1437 remainingLen + CA_BLE_HEADER_SIZE);
1442 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
1443 OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
1446 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1449 static void CALEClientSendDataThread(void *threadData)
1451 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1453 CALEData_t *bleData = (CALEData_t *) threadData;
1456 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid bledata!");
1460 if (!bleData->remoteEndpoint)
1462 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid endpoint of bledata!");
1466 #if defined(__ANDROID__)
1468 if (false == CALEClientIsConnected(bleData->remoteEndpoint->addr))
1470 // triggering to gatt connect and MTU negotiation
1471 CAResult_t res = CALEClientSendNegotiationMessage(
1472 bleData->remoteEndpoint->addr);
1474 if (CA_STATUS_OK != res)
1478 "CALEClientSendNegotiationMessage has failed, result [%d]",
1482 g_errorHandler(bleData->remoteEndpoint,
1491 #if defined(__TIZEN__) || defined(__ANDROID__)
1492 g_mtuSize = CALEClientGetMtuSize(bleData->remoteEndpoint->addr);
1494 OIC_LOG_V(INFO, CALEADAPTER_TAG, "MTU size [%d]", g_mtuSize);
1496 uint32_t midPacketCount = 0;
1497 size_t remainingLen = 0;
1498 size_t totalLength = 0;
1499 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1501 CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
1507 if (CA_STATUS_OK != result)
1509 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1510 "CAGenerateVariableForFragmentation failed, result [%d]", result);
1513 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1518 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1519 "Packet info: data size[%d] midPacketCount[%u] remainingLen[%zu] totalLength[%zu]",
1520 bleData->dataLen, midPacketCount, remainingLen, totalLength);
1522 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1523 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1525 if (NULL != bleData->remoteEndpoint) //Unicast Data
1527 secureFlag = (bleData->remoteEndpoint->flags & CA_SECURE) ?
1528 CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
1530 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This Packet is secure? %d", secureFlag);
1531 result = CAGenerateHeader(dataHeader,
1532 CA_BLE_PACKET_START,
1533 g_localBLESourcePort,
1535 bleData->remoteEndpoint->port);
1537 else //Multicast Data
1539 result = CAGenerateHeader(dataHeader,
1540 CA_BLE_PACKET_START,
1541 g_localBLESourcePort,
1543 CA_BLE_MULTICAST_PORT);
1546 OIC_LOG_V(INFO, CALEADAPTER_TAG, "header info: secureFlag[%X]", secureFlag);
1548 if (CA_STATUS_OK != result)
1550 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1551 "CAGenerateHeader failed, result [%d]", result);
1554 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1559 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1560 result = CAGenerateHeaderPayloadLength(lengthHeader,
1561 CA_BLE_LENGTH_HEADER_SIZE,
1564 if (CA_STATUS_OK != result)
1566 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1567 "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1570 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1575 uint32_t length = 0;
1576 uint32_t dataLen = 0;
1577 if (g_mtuSize > totalLength)
1579 length = (uint32_t)totalLength;
1580 dataLen = bleData->dataLen;
1585 dataLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1588 result = CAMakeFirstDataSegment(dataSegment,
1589 bleData->data, dataLen,
1590 dataHeader, lengthHeader);
1592 if (CA_STATUS_OK != result)
1594 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1595 "Making data segment failed, result [%d]", result);
1598 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1603 const uint32_t iter = midPacketCount;
1605 if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
1607 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
1608 // Send the first segment with the header.
1610 CAUpdateCharacteristicsToGattServer(
1611 bleData->remoteEndpoint->addr,
1617 if (CA_STATUS_OK != result)
1621 "Update characteristics failed, result [%d]",
1625 g_errorHandler(bleData->remoteEndpoint,
1634 "Client Sent Unicast First Data - data length [%u]",
1637 result = CAGenerateHeader(dataHeader,
1638 CA_BLE_PACKET_NOT_START,
1639 g_localBLESourcePort,
1641 bleData->remoteEndpoint->port);
1643 if (CA_STATUS_OK != result)
1645 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1646 "CAGenerateHeader failed, result [%d]", result);
1649 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1654 for (index = 0; index < iter; index++)
1656 result = CAMakeRemainDataSegment(dataSegment,
1657 g_mtuSize - CA_BLE_HEADER_SIZE,
1664 if (CA_STATUS_OK != result)
1666 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1667 "Making data segment failed, result [%d]", result);
1670 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1675 // Send the remaining header.
1676 result = CAUpdateCharacteristicsToGattServer(
1677 bleData->remoteEndpoint->addr,
1682 if (CA_STATUS_OK != result)
1686 "Update characteristics failed, result [%d]",
1690 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1696 "Client Sent Unicast %d Data - data(mtu) length [%hu]",
1701 if (remainingLen && (totalLength > g_mtuSize))
1703 // send the last segment of the data (Ex: 22 bytes of 622
1704 // bytes of data when MTU is 200)
1705 result = CAMakeRemainDataSegment(dataSegment,
1713 if (CA_STATUS_OK != result)
1715 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1716 "Making data segment failed, result [%d]", result);
1719 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1724 result = CAUpdateCharacteristicsToGattServer(
1725 bleData->remoteEndpoint->addr,
1727 remainingLen + CA_BLE_HEADER_SIZE,
1730 if (CA_STATUS_OK != result)
1732 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1736 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1742 "Client Sent Unicast Last Data - data length [%zu]",
1743 remainingLen + CA_BLE_HEADER_SIZE);
1748 //Sending Mulitcast Data
1749 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Client Sending Multicast Data");
1750 OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
1753 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1756 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
1757 const uint8_t *data,
1758 uint32_t dataLength,
1759 u_arraylist_t *senderInfo)
1761 CALEData_t * const bleData = OICMalloc(sizeof(CALEData_t));
1765 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1769 bleData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
1770 bleData->data = OICCalloc(dataLength + 1, 1);
1772 if (NULL == bleData->data)
1774 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1775 CAFreeLEData(bleData);
1779 memcpy(bleData->data, data, dataLength);
1780 bleData->dataLen = dataLength;
1783 bleData->senderInfo = senderInfo;
1789 static void CAFreeLEData(CALEData_t *bleData)
1791 VERIFY_NON_NULL_VOID(bleData, CALEADAPTER_TAG, "Param bleData is NULL");
1793 CAFreeEndpoint(bleData->remoteEndpoint);
1794 OICFree(bleData->data);
1798 static void CALEDataDestroyer(void *data, uint32_t size)
1800 if ((size_t)size < sizeof(CALEData_t *))
1802 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1803 "Destroy data too small %p %d", data, size);
1805 CALEData_t *ledata = (CALEData_t *) data;
1807 CAFreeLEData(ledata);
1811 #ifdef SINGLE_THREAD
1812 static void CALEDataReceiverHandlerSingleThread(const uint8_t *data,
1815 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1817 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1820 CABLEPacketStart_t startFlag = CA_BLE_PACKET_NOT_START;
1821 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1822 uint16_t sourcePort = 0;
1823 uint16_t destPort = 0;
1825 CAParseHeader(data, &startFlag, &sourcePort, &secureFlag, &destPort);
1826 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1827 "header info: startFlag[%X] sourcePort[%d] secureFlag[%X] destPort[%d]",
1828 startFlag, sourcePort, secureFlag, destPort);
1830 if (destPort != g_localBLESourcePort && destPort != CA_BLE_MULTICAST_PORT)
1832 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1833 "this packet is not valid for this app(port mismatch[mine:%d, packet:%d])",
1834 g_localBLESourcePort, destPort);
1840 if (g_singleThreadReceiveData)
1842 OIC_LOG(ERROR, CALEADAPTER_TAG,
1843 "This packet is start packet but exist senderInfo. Remove senderInfo");
1844 OICFree(g_singleThreadReceiveData->defragData);
1845 OICFree(g_singleThreadReceiveData);
1846 g_singleThreadReceiveData = NULL;
1849 uint32_t totalLength = 0;
1850 CAParseHeaderPayloadLength(data, CA_BLE_LENGTH_HEADER_SIZE, &totalLength);
1852 g_singleThreadReceiveData = OICMalloc(sizeof(CABLESenderInfo_t));
1854 if (!g_singleThreadReceiveData)
1856 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
1859 g_singleThreadReceiveData->recvDataLen = 0;
1860 g_singleThreadReceiveData->totalDataLen = 0;
1861 g_singleThreadReceiveData->defragData = NULL;
1862 g_singleThreadReceiveData->remoteEndpoint = NULL;
1864 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
1866 g_singleThreadReceiveData->totalDataLen = totalLength;
1868 if (!(g_singleThreadReceiveData->totalDataLen))
1870 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
1871 OICFree(g_singleThreadReceiveData);
1875 size_t dataOnlyLen = dataLen - (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE);
1876 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
1877 g_singleThreadReceiveData->totalDataLen);
1878 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%u] bytes",
1881 g_singleThreadReceiveData->defragData =
1882 OICCalloc(g_singleThreadReceiveData->totalDataLen + 1,
1883 sizeof(*g_singleThreadReceiveData->defragData));
1885 if (NULL == g_singleThreadReceiveData->defragData)
1887 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
1888 OICFree(g_singleThreadReceiveData);
1892 if (g_singleThreadReceiveData->recvDataLen + dataOnlyLen
1893 > g_singleThreadReceiveData->totalDataLen)
1895 OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
1896 OICFree(g_singleThreadReceiveData->defragData);
1897 OICFree(g_singleThreadReceiveData);
1900 memcpy(g_singleThreadReceiveData->defragData,
1901 data + (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE),
1903 g_singleThreadReceiveData->recvDataLen += dataOnlyLen;
1907 size_t dataOnlyLen = dataLen - CA_BLE_HEADER_SIZE;
1908 if (g_singleThreadReceiveData->recvDataLen + dataOnlyLen
1909 > g_singleThreadReceiveData->totalDataLen)
1911 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1912 "Data Length exceeding error!! Receiving [%d] total length [%d]",
1913 g_singleThreadReceiveData->recvDataLen + dataOnlyLen,
1914 g_singleThreadReceiveData->totalDataLen);
1915 OICFree(g_singleThreadReceiveData->defragData);
1916 OICFree(g_singleThreadReceiveData);
1919 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]",
1921 memcpy(g_singleThreadReceiveData->defragData + g_singleThreadReceiveData->recvDataLen,
1922 data + CA_BLE_HEADER_SIZE,
1924 g_singleThreadReceiveData->recvDataLen += dataOnlyLen;
1925 OIC_LOG_V(INFO, CALEADAPTER_TAG, "totalDatalength [%d] received Datalen [%d]",
1926 g_singleThreadReceiveData->totalDataLen, g_singleThreadReceiveData->recvDataLen);
1928 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1931 static CAResult_t CALEServerSendDataSingleThread(const uint8_t *data,
1934 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__););
1936 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1938 uint32_t midPacketCount = 0;
1939 size_t remainingLen = 0;
1940 size_t totalLength = 0;
1941 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1943 CAResult_t result = CAGenerateVariableForFragmentation(dataLen,
1949 if (CA_STATUS_OK != result)
1951 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1952 "CAGenerateVariableForFragmentation failed, result [%d]", result);
1956 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1957 "Packet info: data size[%d] midPacketCount[%d] remainingLen[%d] totalLength[%d]",
1958 dataLen, midPacketCount, remainingLen, totalLength);
1962 "Server total Data length with header is [%u]",
1965 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1966 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1968 result = CAGenerateHeader(dataHeader,
1969 CA_BLE_PACKET_START,
1970 g_localBLESourcePort,
1971 CA_BLE_PACKET_NON_SECURE,
1972 CA_BLE_MULTICAST_PORT);
1974 if (CA_STATUS_OK != result)
1976 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1977 "CAGenerateHeader failed, result [%d]", result);
1981 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1982 result = CAGenerateHeaderPayloadLength(lengthHeader,
1983 CA_BLE_LENGTH_HEADER_SIZE,
1986 if (CA_STATUS_OK != result)
1988 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1989 "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1993 uint32_t length = 0;
1994 uint32_t dataOnlyLen = 0;
1995 if (g_mtuSize > totalLength)
1997 length = totalLength;
1998 dataOnlyLen = dataLen;
2003 dataOnlyLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
2006 result = CAMakeFirstDataSegment(dataSegment,
2008 dataHeader, lengthHeader);
2010 if (CA_STATUS_OK != result)
2012 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2013 "Making data segment failed, result [%d]", result);
2017 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
2018 result = CAUpdateCharacteristicsToAllGattClients(dataSegment, length);
2019 if (CA_STATUS_OK != result)
2021 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
2028 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
2030 result = CAGenerateHeader(dataHeader,
2031 CA_BLE_PACKET_NOT_START,
2032 g_localBLESourcePort,
2033 CA_BLE_PACKET_NON_SECURE,
2034 CA_BLE_MULTICAST_PORT);
2036 if (CA_STATUS_OK != result)
2038 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2039 "CAGenerateHeader failed, result [%d]", result);
2043 const uint32_t dataLimit = midPacketCount;
2044 for (uint32_t iter = 0; iter < dataLimit; iter++)
2046 result = CAMakeRemainDataSegment(dataSegment,
2047 g_mtuSize - CA_BLE_HEADER_SIZE,
2054 if (CA_STATUS_OK != result)
2056 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2057 "Making data segment failed, result [%d]", result);
2061 result = CAUpdateCharacteristicsToAllGattClients(
2065 if (CA_STATUS_OK != result)
2067 OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2074 if (remainingLen && (totalLength > g_mtuSize))
2076 // send the last segment of the data
2077 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
2079 result = CAMakeRemainDataSegment(dataSegment,
2087 if (CA_STATUS_OK != result)
2089 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2090 "Making data segment failed, result [%d]", result);
2094 result = CAUpdateCharacteristicsToAllGattClients(
2096 remainingLen + CA_BLE_HEADER_SIZE);
2098 if (CA_STATUS_OK != result)
2100 OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2110 static CAResult_t CAInitLEAdapterMutex()
2112 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2114 if (NULL == g_bleIsServerMutex)
2116 g_bleIsServerMutex = oc_mutex_new();
2117 if (NULL == g_bleIsServerMutex)
2119 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2120 return CA_STATUS_FAILED;
2124 if (NULL == g_bleLocalAddressMutex)
2126 g_bleLocalAddressMutex = oc_mutex_new();
2127 if (NULL == g_bleLocalAddressMutex)
2129 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2130 CATerminateLEAdapterMutex();
2131 return CA_STATUS_FAILED;
2137 if (NULL == g_bleServerReceiveDataMutex)
2139 g_bleServerReceiveDataMutex = oc_mutex_new();
2140 if (NULL == g_bleServerReceiveDataMutex)
2142 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2143 return CA_STATUS_FAILED;
2147 if (NULL == g_bleClientReceiveDataMutex)
2149 g_bleClientReceiveDataMutex = oc_mutex_new();
2150 if (NULL == g_bleClientReceiveDataMutex)
2152 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2153 return CA_STATUS_FAILED;
2157 return CA_STATUS_OK;
2160 static void CATerminateLEAdapterMutex()
2162 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2164 oc_mutex_free(g_bleIsServerMutex);
2165 g_bleIsServerMutex = NULL;
2168 oc_mutex_free(g_bleLocalAddressMutex);
2169 g_bleLocalAddressMutex = NULL;
2173 oc_mutex_free(g_bleServerReceiveDataMutex);
2174 g_bleServerReceiveDataMutex = NULL;
2176 oc_mutex_free(g_bleClientReceiveDataMutex);
2177 g_bleClientReceiveDataMutex = NULL;
2181 * Starting LE connectivity adapters.
2183 * As its peer to peer it does not require to start any servers.
2185 * @return ::CA_STATUS_OK or Appropriate error code.
2187 static CAResult_t CAStartLE();
2190 * Start listening server for receiving multicast search requests.
2192 * Transport Specific Behavior:
2193 * LE Starts GATT Server with prefixed UUID and Characteristics
2194 * per OIC Specification.
2195 * @return ::CA_STATUS_OK or Appropriate error code.
2197 static CAResult_t CAStartLEListeningServer();
2200 * Stops listening server from receiving multicast search requests.
2202 * Transport Specific Behavior:
2203 * LE Starts GATT Server with prefixed UUID and Characteristics
2204 * per OIC Specification.
2205 * @return ::CA_STATUS_OK or Appropriate error code.
2207 static CAResult_t CAStopLEListeningServer();
2210 * Sarting discovery of servers for receiving multicast
2213 * Transport Specific Behavior:
2214 * LE Starts GATT Server with prefixed UUID and Characteristics
2215 * per OIC Specification.
2217 * @return ::CA_STATUS_OK or Appropriate error code
2219 static CAResult_t CAStartLEDiscoveryServer();
2222 * Send data to the endpoint using the adapter connectivity.
2224 * @param[in] endpoint Remote Endpoint information (like MAC address,
2225 * reference URI and connectivity type) to which
2226 * the unicast data has to be sent.
2227 * @param[in] data Data which required to be sent.
2228 * @param[in] dataLen Size of data to be sent.
2230 * @note dataLen must be > 0.
2232 * @return The number of bytes sent on the network, or -1 on error.
2234 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2237 CADataType_t dataType);
2240 * Send multicast data to the endpoint using the LE connectivity.
2242 * @param[in] endpoint Remote Endpoint information to which the
2243 * multicast data has to be sent.
2244 * @param[in] data Data which required to be sent.
2245 * @param[in] dataLen Size of data to be sent.
2247 * @note dataLen must be > 0.
2249 * @return The number of bytes sent on the network, or -1 on error.
2251 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
2254 CADataType_t dataType);
2257 * Get LE Connectivity network information.
2259 * @param[out] info Local connectivity information structures.
2260 * @param[out] size Number of local connectivity structures.
2262 * @return ::CA_STATUS_OK or Appropriate error code.
2264 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info,
2268 * Read Synchronous API callback.
2270 * @return ::CA_STATUS_OK or Appropriate error code.
2272 static CAResult_t CAReadLEData();
2275 * Stopping the adapters and close socket connections.
2277 * LE Stops all GATT servers and GATT Clients.
2279 * @return ::CA_STATUS_OK or Appropriate error code.
2281 static CAResult_t CAStopLE();
2284 * Terminate the LE connectivity adapter.
2286 * Configuration information will be deleted from further use.
2288 static void CATerminateLE();
2291 * This function will receive the data from the GattServer and add the
2292 * data to the Server receiver queue.
2294 * @param[in] remoteAddress Remote address of the device from where
2296 * @param[in] data Actual data received from the remote
2298 * @param[in] dataLength Length of the data received from the
2300 * @param[in] sentLength Length of the data sent from the remote
2303 * @return ::CA_STATUS_OK or Appropriate error code.
2304 * @retval ::CA_STATUS_OK Successful.
2305 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2306 * @retval ::CA_STATUS_FAILED Operation failed.
2309 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
2310 const uint8_t *data,
2311 uint32_t dataLength,
2312 uint32_t *sentLength);
2315 * This function will receive the data from the GattClient and add the
2316 * data into the Client receiver queue.
2318 * @param[in] remoteAddress Remote address of the device from where
2320 * @param[in] data Actual data recevied from the remote
2322 * @param[in] dataLength Length of the data received from the
2324 * @param[in] sentLength Length of the data sent from the remote
2327 * @return ::CA_STATUS_OK or Appropriate error code.
2328 * @retval ::CA_STATUS_OK Successful.
2329 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2330 * @retval ::CA_STATUS_FAILED Operation failed.
2332 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
2333 const uint8_t *data,
2334 uint32_t dataLength,
2335 uint32_t *sentLength);
2338 * Set the NetworkPacket received callback to CA layer from adapter
2341 * @param[in] callback Callback handle sent from the upper layer.
2343 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
2346 * Push the data from CA layer to the Sender processor queue.
2348 * @param[in] remoteEndpoint Remote endpoint information of the
2350 * @param[in] data Data to be transmitted from LE.
2351 * @param[in] dataLen Length of the Data being transmitted.
2353 * @return ::CA_STATUS_OK or Appropriate error code.
2354 * @retval ::CA_STATUS_OK Successful.
2355 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2356 * @retval ::CA_STATUS_FAILED Operation failed.
2358 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
2359 const uint8_t *data,
2363 * Push the data from CA layer to the Sender processor queue.
2365 * @param[in] remoteEndpoint Remote endpoint information of the
2367 * @param[in] data Data to be transmitted from LE.
2368 * @param[in] dataLen Length of the Data being transmitted.
2370 * @return ::CA_STATUS_OK or Appropriate error code.
2371 * @retval ::CA_STATUS_OK Successful.
2372 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2373 * @retval ::CA_STATUS_FAILED Operation failed.
2375 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
2376 const uint8_t *data,
2379 static CAResult_t CALEAdapterGattServerStart()
2381 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2383 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2385 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2386 caglobals.bleFlags);
2387 return CA_STATUS_OK;
2390 CAResult_t result = CAStartLEGattServer();
2392 #ifndef SINGLE_THREAD
2394 Don't start the server side sending queue thread until the
2395 server itself has actually started.
2397 if (CA_STATUS_OK == result)
2399 result = CAQueueingThreadStart(g_bleServerSendQueueHandle);
2400 if (CA_STATUS_OK != result)
2404 "Unable to start server queuing thread (%d)",
2413 static CAResult_t CALEAdapterGattServerStop()
2415 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2417 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2419 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2420 caglobals.bleFlags);
2421 return CA_STATUS_OK;
2424 #ifndef SINGLE_THREAD
2426 CAResult_t res = CAQueueingThreadStop(g_bleServerSendQueueHandle);
2427 if (CA_STATUS_OK != res)
2429 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAQueueingThreadStop has failed");
2431 res = CAStopLEGattServer();
2432 if (CA_STATUS_OK != res)
2434 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAStopLEGattServer has failed");
2439 return CAStopLEGattServer();
2443 static CAResult_t CALEAdapterGattClientStart()
2445 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2447 CAResult_t result = CAStartLEGattClient();
2449 #ifndef SINGLE_THREAD
2451 Don't start the client side sending queue thread until the
2452 client itself has actually started.
2454 if (CA_STATUS_OK == result)
2456 result = CAQueueingThreadStart(g_bleClientSendQueueHandle);
2457 if (CA_STATUS_OK != result)
2461 "Unable to start client queuing thread");
2469 static CAResult_t CALEAdapterGattClientStop()
2471 #ifndef SINGLE_THREAD
2472 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2473 CAStopLEGattClient();
2475 CAResult_t result = CAQueueingThreadStop(g_bleClientSendQueueHandle);
2479 CAStopLEGattClient();
2481 return CA_STATUS_OK;
2485 #ifdef __WITH_DTLS__
2486 static ssize_t CALESecureSendDataCB(CAEndpoint_t *endpoint, const void *data, size_t dataLen)
2488 VERIFY_NON_NULL(endpoint, CALEADAPTER_TAG, "endpoint is NULL");
2489 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "data is NULL");
2490 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2491 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "encrypted datalen = %zd", dataLen);
2494 CADataType_t dataType = g_dataType;
2497 if (ADAPTER_SERVER == g_adapterType ||
2498 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2500 result = CALEAdapterServerSendData(endpoint, data, dataLen);
2501 if (CA_STATUS_OK != result)
2503 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed" );
2507 g_errorHandler(endpoint, data, dataLen, result);
2511 ret = (ssize_t)dataLen;
2513 else if (ADAPTER_CLIENT == g_adapterType ||
2514 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
2515 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
2517 result = CALEAdapterClientSendData(endpoint, data, dataLen);
2518 if (CA_STATUS_OK != result)
2520 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
2524 g_errorHandler(endpoint, data, dataLen, result);
2528 ret = (ssize_t)dataLen;
2532 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2533 "Can't Send Message adapterType = %d, dataType = %d", g_adapterType, dataType);
2536 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2540 CAResult_t CALESecureReceiveDataCB(const CASecureEndpoint_t *sep, const void *data,
2543 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2545 VERIFY_NON_NULL(sep, CALEADAPTER_TAG, "sep is NULL");
2546 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "data is NULL");
2548 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2549 "Secure Data Receive - decrypted datalen = %zd", dataLen);
2553 OIC_LOG(ERROR, CALEADAPTER_TAG, "incorrect dataLen, derecypt fail !");
2554 return CA_STATUS_INVALID_PARAM;
2557 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2559 CAResult_t res = CA_STATUS_OK;
2560 if (g_networkPacketReceivedCallback)
2562 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2563 "[CALESecureReceiveDataCB] Secure flags = %d, %x",
2564 sep->endpoint.flags, sep->endpoint.flags);
2565 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2566 "[CALESecureReceiveDataCB] Received data up !");
2567 res = g_networkPacketReceivedCallback(sep, data, dataLen);
2568 if (CA_STATUS_OK != res)
2570 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Error parsing CoAP data, res = %d", res);
2577 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
2578 CANetworkPacketReceivedCallback reqRespCallback,
2579 CAAdapterChangeCallback netCallback,
2580 CAConnectionChangeCallback connCallback,
2581 CAErrorHandleCallback errorCallback,
2582 ca_thread_pool_t handle)
2584 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2587 VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null");
2588 VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null");
2589 VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null");
2590 VERIFY_NON_NULL(connCallback, CALEADAPTER_TAG, "ConnectionChange Callback is null");
2592 CAResult_t result = CA_STATUS_OK;
2593 result = CAInitLEAdapterMutex();
2594 if (CA_STATUS_OK != result)
2596 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
2597 return CA_STATUS_FAILED;
2600 result = CAInitializeLENetworkMonitor();
2601 if (CA_STATUS_OK != result)
2603 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
2604 return CA_STATUS_FAILED;
2606 CAInitializeLEAdapter();
2608 result = CAInitializeLEGattClient();
2609 if (CA_STATUS_OK != result)
2611 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattClient() failed");
2612 return CA_STATUS_FAILED;
2615 CASetLEClientThreadPoolHandle(handle);
2617 CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
2618 CASetLEServerThreadPoolHandle(handle);
2619 result = CAInitializeLEGattServer();
2620 if (CA_STATUS_OK != result)
2622 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattServer() failed");
2623 return CA_STATUS_FAILED;
2626 CASetLEAdapterThreadPoolHandle(handle);
2627 CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
2628 CASetLEReqRespAdapterCallback(reqRespCallback);
2630 CASetBLEClientErrorHandleCallback(CALEErrorHandler);
2631 CASetBLEServerErrorHandleCallback(CALEErrorHandler);
2632 CALERegisterNetworkNotifications(netCallback, connCallback);
2634 g_errorHandler = errorCallback;
2636 #ifdef __WITH_DTLS__
2637 if (CA_STATUS_OK != CAinitSslAdapter())
2639 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to init SSL adapter");
2643 CAsetSslAdapterCallbacks(CALESecureReceiveDataCB, CALESecureSendDataCB,
2644 CA_ADAPTER_GATT_BTLE);
2648 static const CAConnectivityHandler_t connHandler =
2650 .startAdapter = CAStartLE,
2651 .stopAdapter = CAStopLE,
2652 .startListenServer = CAStartLEListeningServer,
2653 .stopListenServer = CAStopLEListeningServer,
2654 .startDiscoveryServer = CAStartLEDiscoveryServer,
2655 .sendData = CASendLEUnicastData,
2656 .sendDataToAll = CASendLEMulticastData,
2657 .GetnetInfo = CAGetLEInterfaceInformation,
2658 .readData = CAReadLEData,
2659 .terminate = CATerminateLE,
2660 .cType = CA_ADAPTER_GATT_BTLE
2663 registerCallback(connHandler);
2664 return CA_STATUS_OK;
2667 static CAResult_t CAStartLE()
2669 return CAStartLEAdapter();
2672 static CAResult_t CAStopLE()
2675 #ifndef SINGLE_THREAD
2679 oc_mutex_lock(g_bleIsServerMutex);
2680 switch (g_adapterType)
2682 case ADAPTER_SERVER:
2683 CALEAdapterGattServerStop();
2685 case ADAPTER_CLIENT:
2686 CALEAdapterGattClientStop();
2688 case ADAPTER_BOTH_CLIENT_SERVER:
2689 CALEAdapterGattServerStop();
2690 CALEAdapterGattClientStop();
2695 oc_mutex_unlock(g_bleIsServerMutex);
2696 return CAStopLEAdapter();
2699 static void CATerminateLE()
2701 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2703 CASetLEReqRespServerCallback(NULL);
2704 CASetLEReqRespClientCallback(NULL);
2705 CALERegisterNetworkNotifications(NULL, NULL);
2706 CASetLEReqRespAdapterCallback(NULL);
2707 CATerminateLENetworkMonitor();
2709 oc_mutex_lock(g_bleIsServerMutex);
2710 switch (g_adapterType)
2712 case ADAPTER_SERVER:
2713 CATerminateLEGattServer();
2715 case ADAPTER_CLIENT:
2716 CATerminateLEGattClient();
2718 case ADAPTER_BOTH_CLIENT_SERVER:
2719 CATerminateLEGattServer();
2720 CATerminateLEGattClient();
2725 g_adapterType = ADAPTER_EMPTY;
2726 oc_mutex_unlock(g_bleIsServerMutex);
2728 #ifndef SINGLE_THREAD
2729 CATerminateLEQueues();
2732 #ifdef __WITH_DTLS__
2733 CAsetSslAdapterCallbacks(NULL, NULL, CA_ADAPTER_GATT_BTLE);
2736 CATerminateLEAdapterMutex();
2739 static CAResult_t CAStartLEListeningServer()
2741 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2743 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2745 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2746 caglobals.bleFlags);
2747 return CA_STATUS_OK;
2750 #ifndef ROUTING_GATEWAY
2751 CAResult_t result = CA_STATUS_OK;
2752 #ifndef SINGLE_THREAD
2753 result = CAInitLEServerQueues();
2754 if (CA_STATUS_OK != result)
2756 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
2761 oc_mutex_lock(g_bleIsServerMutex);
2762 switch (g_adapterType)
2764 case ADAPTER_CLIENT:
2765 g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2767 case ADAPTER_BOTH_CLIENT_SERVER:
2770 g_adapterType = ADAPTER_SERVER;
2772 oc_mutex_unlock(g_bleIsServerMutex);
2774 result = CAGetLEAdapterState();
2775 if (CA_STATUS_OK != result)
2777 if (CA_ADAPTER_NOT_ENABLED == result)
2781 "Listen Server will be started once BT Adapter is enabled");
2782 result = CA_STATUS_OK;
2787 result = CALEAdapterGattServerStart();
2790 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2793 // Routing Gateway only supports BLE client mode.
2794 OIC_LOG(ERROR, CALEADAPTER_TAG, "LE server not supported in Routing Gateway");
2795 return CA_NOT_SUPPORTED;
2799 static CAResult_t CAStopLEListeningServer()
2801 OIC_LOG(ERROR, CALEADAPTER_TAG, "Listen server stop not supported.");
2802 return CA_NOT_SUPPORTED;
2805 static CAResult_t CAStartLEDiscoveryServer()
2807 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2808 CAResult_t result = CA_STATUS_OK;
2809 #ifndef SINGLE_THREAD
2810 result = CAInitLEClientQueues();
2811 if (CA_STATUS_OK != result)
2813 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
2818 oc_mutex_lock(g_bleIsServerMutex);
2819 switch (g_adapterType)
2821 case ADAPTER_SERVER:
2822 g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2824 case ADAPTER_BOTH_CLIENT_SERVER:
2827 g_adapterType = ADAPTER_CLIENT;
2829 oc_mutex_unlock(g_bleIsServerMutex);
2831 result = CAGetLEAdapterState();
2832 if (CA_STATUS_OK != result)
2834 if (CA_ADAPTER_NOT_ENABLED == result)
2838 "Discovery Server will be started once BT Adapter is enabled");
2839 result = CA_STATUS_OK;
2844 result = CALEAdapterGattClientStart();
2847 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2851 static CAResult_t CAReadLEData()
2853 #ifdef SINGLE_THREAD
2856 return CA_STATUS_OK;
2859 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2862 CADataType_t dataType)
2864 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2865 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "type(%d)", dataType);
2868 VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
2869 VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2871 CAResult_t result = CA_STATUS_FAILED;
2873 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2874 if (ADAPTER_EMPTY == g_adapterType)
2876 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2879 oc_mutex_lock(g_bleIsServerMutex);
2880 if (ADAPTER_SERVER == g_adapterType ||
2881 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2883 #ifdef __WITH_DTLS__
2884 if (endpoint && endpoint->flags & CA_SECURE)
2886 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2887 "Response Data or server - secured data send(caadapternetdtlsencrypt) call");
2888 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2889 g_dataType = dataType;
2890 oc_mutex_unlock(g_bleIsServerMutex);
2892 result = CAencryptSsl(endpoint, (void *)data, dataLen);
2893 if (CA_STATUS_OK != result)
2895 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
2902 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2903 "server or both - none secured data send(CALEAdapterServerSendData) call");
2904 result = CALEAdapterServerSendData(endpoint, data, dataLen);
2907 result = CALEAdapterServerSendData(endpoint, data, dataLen);
2909 if (CA_STATUS_OK != result)
2911 oc_mutex_unlock(g_bleIsServerMutex);
2912 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed");
2915 g_errorHandler(endpoint, data, dataLen, result);
2921 else if (ADAPTER_CLIENT == g_adapterType ||
2922 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
2923 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
2925 #ifdef __WITH_DTLS__
2926 if (endpoint && endpoint->flags & CA_SECURE)
2928 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2929 "Request Data or client - secured data send(caadapternetdtlsencrypt) call");
2930 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2931 g_dataType = dataType;
2932 oc_mutex_unlock(g_bleIsServerMutex);
2934 result = CAencryptSsl(endpoint, (void *)data, dataLen);
2935 if (CA_STATUS_OK != result)
2937 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
2944 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2945 "client or both - none secured data send(CALEAdapterClientSendData) call");
2946 result = CALEAdapterClientSendData(endpoint, data, dataLen);
2949 result = CALEAdapterClientSendData(endpoint, data, dataLen);
2951 if (CA_STATUS_OK != result)
2953 oc_mutex_unlock(g_bleIsServerMutex);
2954 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
2958 g_errorHandler(endpoint, data, dataLen, result);
2963 oc_mutex_unlock(g_bleIsServerMutex);
2965 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2969 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
2972 CADataType_t dataType)
2974 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2977 VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2981 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
2985 CAResult_t result = CA_STATUS_FAILED;
2987 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2988 if (ADAPTER_EMPTY == g_adapterType)
2990 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2993 oc_mutex_lock(g_bleIsServerMutex);
2994 if (ADAPTER_SERVER == g_adapterType ||
2995 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2997 result = CALEAdapterServerSendData(NULL, data, dataLen);
2998 if (CA_STATUS_OK != result)
3000 oc_mutex_unlock(g_bleIsServerMutex);
3002 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data for server failed" );
3006 g_errorHandler(endpoint, data, dataLen, result);
3012 if (ADAPTER_CLIENT == g_adapterType ||
3013 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
3014 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
3016 result = CALEAdapterClientSendData(NULL, data, dataLen);
3017 if (CA_STATUS_OK != result)
3019 oc_mutex_unlock(g_bleIsServerMutex);
3021 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data for client failed" );
3025 g_errorHandler(endpoint, data, dataLen, result);
3030 oc_mutex_unlock(g_bleIsServerMutex);
3032 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3036 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
3038 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3040 VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
3042 char *local_address = NULL;
3044 CAResult_t res = CAGetLEAddress(&local_address);
3045 if (CA_STATUS_OK != res)
3047 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
3051 if (NULL == local_address)
3053 OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
3054 return CA_STATUS_FAILED;
3058 (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
3059 if (NULL == (*info))
3061 OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
3062 OICFree(local_address);
3063 return CA_STATUS_FAILED;
3066 size_t local_address_len = strlen(local_address);
3068 if(local_address_len >= sizeof(g_localBLEAddress) ||
3069 local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
3071 OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
3073 OICFree(local_address);
3074 return CA_STATUS_FAILED;
3077 OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
3078 oc_mutex_lock(g_bleLocalAddressMutex);
3079 OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
3080 oc_mutex_unlock(g_bleLocalAddressMutex);
3082 (*info)->adapter = CA_ADAPTER_GATT_BTLE;
3084 OICFree(local_address);
3086 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3087 return CA_STATUS_OK;
3090 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
3091 CAConnectionChangeCallback connCallback)
3093 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3095 g_networkCallback = netCallback;
3096 g_connectionCallback = connCallback;
3097 CAResult_t res = CA_STATUS_OK;
3100 res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
3101 if (CA_STATUS_OK != res)
3103 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
3108 res = CAUnSetLEAdapterStateChangedCb();
3109 if (CA_STATUS_OK != res)
3111 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
3115 if (g_connectionCallback)
3117 res = CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCb);
3118 if (CA_STATUS_OK != res)
3120 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLENWConnectionStateChangedCb failed!");
3125 res = CAUnSetLENWConnectionStateChangedCb();
3126 if (CA_STATUS_OK != res)
3128 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUnSetLENWConnectionStateChangedCb failed!");
3132 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3136 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
3139 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3141 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3144 CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE };
3145 OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), address);
3148 oc_mutex_lock(g_bleIsServerMutex);
3149 switch (g_adapterType)
3151 case ADAPTER_SERVER:
3152 CALEGattServerConnectionStateChanged(isConnected, address);
3154 case ADAPTER_CLIENT:
3155 CALEGattConnectionStateChanged(isConnected, address);
3157 case ADAPTER_BOTH_CLIENT_SERVER:
3158 CALEGattConnectionStateChanged(isConnected, address);
3159 CALEGattServerConnectionStateChanged(isConnected, address);
3164 oc_mutex_unlock(g_bleIsServerMutex);
3169 #ifndef SINGLE_THREAD
3170 if(g_bleClientSenderInfo)
3172 CALERemoveReceiveQueueData(g_bleClientSenderInfo, address);
3175 if(g_bleServerSenderInfo)
3177 CALERemoveReceiveQueueData(g_bleServerSenderInfo, address);
3180 // remove data of send queue.
3181 if (g_bleClientSendQueueHandle)
3183 CALERemoveSendQueueData(g_bleClientSendQueueHandle, address);
3186 if (g_bleServerSendQueueHandle)
3188 CALERemoveSendQueueData(g_bleServerSendQueueHandle, address);
3192 #ifdef __WITH_DTLS__
3193 CAcloseSslConnection(&localEndpoint);
3197 if (g_connectionCallback)
3199 g_connectionCallback(&localEndpoint, isConnected);
3202 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3205 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
3207 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3209 if (CA_ADAPTER_ENABLED == adapter_state)
3211 oc_mutex_lock(g_bleIsServerMutex);
3212 switch (g_adapterType)
3214 case ADAPTER_SERVER:
3215 CALEAdapterGattServerStart();
3217 case ADAPTER_CLIENT:
3218 CALEAdapterGattClientStart();
3220 case ADAPTER_BOTH_CLIENT_SERVER:
3221 CALEAdapterGattServerStart();
3222 CALEAdapterGattClientStart();
3227 oc_mutex_unlock(g_bleIsServerMutex);
3231 oc_mutex_lock(g_bleIsServerMutex);
3232 switch (g_adapterType)
3234 case ADAPTER_SERVER:
3235 CALEAdapterGattServerStop();
3237 case ADAPTER_CLIENT:
3238 CALEAdapterGattClientStop();
3240 case ADAPTER_BOTH_CLIENT_SERVER:
3241 CALEAdapterGattServerStop();
3242 CALEAdapterGattClientStop();
3247 oc_mutex_unlock(g_bleIsServerMutex);
3250 if (NULL != g_networkCallback)
3252 g_networkCallback(CA_ADAPTER_GATT_BTLE, adapter_state);
3256 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
3259 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3262 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
3263 const uint8_t *data,
3266 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3267 #ifndef SINGLE_THREAD
3268 VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
3269 "g_bleClientSendQueueHandle is NULL",
3272 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%u]", dataLen);
3274 CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3277 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3278 return CA_MEMORY_ALLOC_FAILED;
3280 // Add message to send queue
3282 CAResult_t res = CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData,
3283 sizeof(CALEData_t));
3284 if (CA_STATUS_OK != res)
3286 CALEDataDestroyer(bleData, sizeof(CALEData_t));
3289 return CA_STATUS_OK;
3292 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
3293 const uint8_t *data,
3296 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3298 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3300 #ifdef SINGLE_THREAD
3301 if (!CAIsLEConnected())
3303 OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
3304 return CA_STATUS_FAILED;
3307 CAResult_t result = CALEServerSendDataSingleThread(data, dataLen);
3308 if (CA_STATUS_OK != result)
3310 OIC_LOG(ERROR, CALEADAPTER_TAG, "CALEServerSendDataSingleThread failed");
3311 return CA_STATUS_FAILED;
3314 VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
3315 "g_bleServerSendQueueHandle is NULL",
3318 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
3320 CALEData_t * const bleData =
3321 CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3325 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3326 return CA_MEMORY_ALLOC_FAILED;
3329 // Add message to send queue
3331 CAResult_t res = CAQueueingThreadAddData(g_bleServerSendQueueHandle,
3333 sizeof(CALEData_t));
3334 if (CA_STATUS_OK != res)
3336 CALEDataDestroyer(bleData, sizeof(CALEData_t));
3339 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3340 return CA_STATUS_OK;
3343 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
3344 const uint8_t *data,
3345 uint32_t dataLength,
3346 uint32_t *sentLength)
3348 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3351 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3352 VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3354 #ifdef SINGLE_THREAD
3355 CALEDataReceiverHandlerSingleThread(data, dataLength);
3357 if (g_singleThreadReceiveData->totalDataLen == g_singleThreadReceiveData->recvDataLen)
3359 if(g_networkPacketReceivedCallback)
3361 // will be filled by upper layer
3362 const CASecureEndpoint_t endpoint =
3363 { .endpoint = { .adapter = CA_ADAPTER_GATT_BTLE } };
3365 g_networkPacketReceivedCallback(&endpoint,
3366 g_singleThreadReceiveData->defragData,
3367 g_singleThreadReceiveData->recvDataLen);
3369 g_singleThreadReceiveData->remoteEndpoint = NULL;
3370 OICFree(g_singleThreadReceiveData->defragData);
3371 g_singleThreadReceiveData->defragData = NULL;
3372 OICFree(g_singleThreadReceiveData);
3373 g_singleThreadReceiveData = NULL;
3376 VERIFY_NON_NULL_RET(g_bleServerReceiverQueue,
3378 "g_bleServerReceiverQueue",
3381 //Add message to data queue
3382 CAEndpoint_t * const remoteEndpoint =
3383 CACreateEndpointObject(CA_DEFAULT_FLAGS,
3384 CA_ADAPTER_GATT_BTLE,
3388 if (NULL == remoteEndpoint)
3390 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3391 return CA_STATUS_FAILED;
3394 // Create bleData to add to queue
3397 "Data received from LE Server layer [%d]",
3400 CALEData_t * const bleData =
3401 CACreateLEData(remoteEndpoint, data, dataLength, g_bleServerSenderInfo);
3405 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3406 CAFreeEndpoint(remoteEndpoint);
3407 return CA_MEMORY_ALLOC_FAILED;
3410 CAFreeEndpoint(remoteEndpoint);
3411 // Add message to receiver queue
3412 CAQueueingThreadAddData(g_bleServerReceiverQueue, bleData, sizeof(CALEData_t));
3414 *sentLength = dataLength;
3416 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3417 return CA_STATUS_OK;
3420 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
3421 const uint8_t *data,
3422 uint32_t dataLength,
3423 uint32_t *sentLength)
3426 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3427 VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3428 #ifndef SINGLE_THREAD
3429 VERIFY_NON_NULL_RET(g_bleClientReceiverQueue, CALEADAPTER_TAG,
3430 "g_bleClientReceiverQueue",
3433 //Add message to data queue
3434 CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
3435 CA_ADAPTER_GATT_BTLE,
3437 if (NULL == remoteEndpoint)
3439 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3440 return CA_STATUS_FAILED;
3443 // Create bleData to add to queue
3446 "Data received from LE Client layer [%u]",
3449 CALEData_t * const bleData =
3450 CACreateLEData(remoteEndpoint, data, dataLength, g_bleClientSenderInfo);
3454 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3455 CAFreeEndpoint(remoteEndpoint);
3456 return CA_MEMORY_ALLOC_FAILED;
3459 CAFreeEndpoint(remoteEndpoint);
3460 // Add message to receiver queue
3461 CAQueueingThreadAddData(g_bleClientReceiverQueue, bleData, sizeof(CALEData_t));
3463 *sentLength = dataLength;
3465 return CA_STATUS_OK;
3468 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
3470 g_bleAdapterThreadPool = handle;
3474 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
3476 g_networkPacketReceivedCallback = callback;
3480 static void CALEErrorHandler(const char *remoteAddress,
3481 const uint8_t *data,
3485 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3487 VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
3489 CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS,
3490 CA_ADAPTER_GATT_BTLE,
3494 // if required, will be used to build remote endpoint
3495 g_errorHandler(rep, data, dataLen, result);
3497 CAFreeEndpoint(rep);
3499 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3502 #ifndef SINGLE_THREAD
3503 static bool CALEClearQueueAddressDataContext(void *data, uint32_t size, void *ctx)
3505 if (NULL == data || NULL == ctx)
3510 CALEData_t *caLeData = (CALEData_t *)data;
3511 const char *address = (const char *)ctx;
3513 if (NULL != caLeData && NULL != caLeData->remoteEndpoint)
3515 if (!strcasecmp(caLeData->remoteEndpoint->addr, address))
3523 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle, const char* address)
3525 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
3527 VERIFY_NON_NULL_VOID(queueHandle, CALEADAPTER_TAG, "queueHandle");
3528 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3530 CAResult_t res = CAQueueingThreadClearContextData(queueHandle,
3531 CALEClearQueueAddressDataContext,
3533 if (CA_STATUS_OK != res)
3536 OIC_LOG(ERROR, CALEADAPTER_TAG, "Could not clear the send queue");
3541 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList, const char* address)
3543 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
3545 VERIFY_NON_NULL_VOID(dataInfoList, CALEADAPTER_TAG, "dataInfoList");
3546 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3548 CABLESenderInfo_t *senderInfo = NULL;
3549 uint32_t senderIndex = 0;
3551 u_arraylist_t *portList = u_arraylist_create();
3552 if (CA_STATUS_OK == CALEGetPortsFromSenderInfo(address, dataInfoList, portList))
3554 uint32_t arrayLength = u_arraylist_length(portList);
3555 for (uint32_t i = 0; i < arrayLength; i++)
3557 uint16_t *port = (uint16_t *)u_arraylist_get(portList, i);
3560 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to get port from sender info !");
3561 u_arraylist_destroy(portList);
3565 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "port : %X", *port);
3567 if (CA_STATUS_OK == CALEGetSenderInfo(address, *port,
3568 dataInfoList, &senderInfo,
3571 u_arraylist_remove(dataInfoList, senderIndex);
3572 OICFree(senderInfo->defragData);
3573 OICFree(senderInfo->remoteEndpoint);
3574 OICFree(senderInfo);
3576 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3577 "SenderInfo is removed for disconnection");
3581 OIC_LOG(DEBUG, CALEADAPTER_TAG, "SenderInfo doesn't exist");
3585 u_arraylist_destroy(portList);
3588 static CAResult_t CALEGetPortsFromSenderInfo(const char *leAddress,
3589 u_arraylist_t *senderInfoList,
3590 u_arraylist_t *portList)
3592 VERIFY_NON_NULL(leAddress,
3594 "NULL BLE address argument");
3596 const uint32_t listLength = u_arraylist_length(senderInfoList);
3597 const uint32_t addrLength = strlen(leAddress);
3599 for (uint32_t index = 0; index < listLength; index++)
3601 CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
3602 if (!info || !(info->remoteEndpoint))
3607 if (!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
3609 uint16_t *port = (uint16_t *)OICMalloc(sizeof(uint16_t));
3612 OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
3613 return CA_MEMORY_ALLOC_FAILED;
3615 *port = info->remoteEndpoint->port;
3616 u_arraylist_add(portList, (void *)port);
3620 if (u_arraylist_length(portList) != 0)
3622 return CA_STATUS_OK;
3626 return CA_STATUS_FAILED;
3631 void CALEStartGattServer()
3633 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3635 oc_mutex_lock(g_bleIsServerMutex);
3636 switch (g_adapterType)
3638 case ADAPTER_SERVER:
3639 CALEAdapterGattServerStart();
3641 case ADAPTER_CLIENT:
3642 CALEAdapterGattClientStart();
3644 case ADAPTER_BOTH_CLIENT_SERVER:
3645 CALEAdapterGattServerStart();
3646 CALEAdapterGattClientStart();
3651 oc_mutex_unlock(g_bleIsServerMutex);
3652 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3655 void CALEStopGattServer()
3657 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3659 oc_mutex_lock(g_bleIsServerMutex);
3660 switch (g_adapterType)
3662 case ADAPTER_SERVER:
3663 CALEAdapterGattServerStop();
3665 case ADAPTER_CLIENT:
3666 CALEAdapterGattClientStop();
3668 case ADAPTER_BOTH_CLIENT_SERVER:
3669 CALEAdapterGattServerStop();
3670 CALEAdapterGattClientStop();
3675 oc_mutex_unlock(g_bleIsServerMutex);
3676 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);