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 OIC_LOG_V(INFO, CALEADAPTER_TAG, "Get MTU size using API");
1188 g_mtuSize = CALEServerGetMtuSize(bleData->remoteEndpoint->addr);
1190 OIC_LOG_V(INFO, CALEADAPTER_TAG, "MTU size [%d]", g_mtuSize);
1192 uint32_t midPacketCount = 0;
1193 size_t remainingLen = 0;
1194 size_t totalLength = 0;
1195 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1197 CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
1203 if (CA_STATUS_OK != result)
1205 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1206 "CAGenerateVariableForFragmentation failed, result [%d]", result);
1209 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1214 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1215 "Packet info: data size[%d] midPacketCount[%u] remainingLen[%zu] totalLength[%zu]",
1216 bleData->dataLen, midPacketCount, remainingLen, totalLength);
1220 "Server total Data length with header is [%zu]",
1223 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1224 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1226 if (NULL != bleData->remoteEndpoint) //Unicast Data
1228 secureFlag = (bleData->remoteEndpoint->flags & CA_SECURE) ?
1229 CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
1231 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This Packet is secure? %d", secureFlag);
1232 result = CAGenerateHeader(dataHeader,
1233 CA_BLE_PACKET_START,
1234 g_localBLESourcePort,
1236 bleData->remoteEndpoint->port);
1238 else //Multicast Data
1240 result = CAGenerateHeader(dataHeader,
1241 CA_BLE_PACKET_START,
1242 g_localBLESourcePort,
1244 CA_BLE_MULTICAST_PORT);
1246 OIC_LOG_V(INFO, CALEADAPTER_TAG, "header info: secureFlag[%X]", secureFlag);
1248 if (CA_STATUS_OK != result)
1250 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1251 "CAGenerateHeader failed, result [%d]", result);
1254 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1259 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1260 result = CAGenerateHeaderPayloadLength(lengthHeader,
1261 CA_BLE_LENGTH_HEADER_SIZE,
1264 if (CA_STATUS_OK != result)
1266 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1267 "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1270 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1275 uint32_t length = 0;
1276 uint32_t dataLen = 0;
1277 if (g_mtuSize > totalLength)
1279 length = (uint32_t)totalLength;
1280 dataLen = bleData->dataLen;
1285 dataLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1288 result = CAMakeFirstDataSegment(dataSegment,
1289 bleData->data, dataLen,
1290 dataHeader, lengthHeader);
1292 if (CA_STATUS_OK != result)
1294 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1295 "Making data segment failed, result [%d]", result);
1298 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1303 const uint32_t iter = midPacketCount;
1306 // Send the first segment with the header.
1307 if (NULL != bleData->remoteEndpoint) // Sending Unicast Data
1309 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Unicast Data");
1311 result = CAUpdateCharacteristicsToGattClient(
1312 bleData->remoteEndpoint->addr, dataSegment, length);
1314 if (CA_STATUS_OK != result)
1318 "Update characteristics failed, result [%d]",
1322 g_errorHandler(bleData->remoteEndpoint,
1332 "Server Sent Unicast First Data - data length [%zu]",
1335 result = CAGenerateHeader(dataHeader,
1336 CA_BLE_PACKET_NOT_START,
1337 g_localBLESourcePort,
1339 bleData->remoteEndpoint->port);
1341 if (CA_STATUS_OK != result)
1343 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1344 "CAGenerateHeader failed, result [%d]", result);
1347 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1352 for (index = 0; index < iter; index++)
1354 // Send the remaining header.
1355 result = CAMakeRemainDataSegment(dataSegment,
1356 g_mtuSize - CA_BLE_HEADER_SIZE,
1363 if (CA_STATUS_OK != result)
1365 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1366 "Making data segment failed, result [%d]", result);
1369 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1375 CAUpdateCharacteristicsToGattClient(
1376 bleData->remoteEndpoint->addr,
1380 if (CA_STATUS_OK != result)
1382 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1383 "Update characteristics failed, result [%d]", result);
1386 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1390 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]",
1394 if (remainingLen && (totalLength > g_mtuSize))
1396 // send the last segment of the data (Ex: 22 bytes of 622
1397 // bytes of data when MTU is 200)
1398 result = CAMakeRemainDataSegment(dataSegment,
1406 if (CA_STATUS_OK != result)
1408 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1409 "Making data segment failed, result [%d]", result);
1412 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1417 result = CAUpdateCharacteristicsToGattClient(
1418 bleData->remoteEndpoint->addr,
1420 remainingLen + CA_BLE_HEADER_SIZE);
1422 if (CA_STATUS_OK != result)
1426 "Update characteristics failed, result [%d]",
1430 g_errorHandler(bleData->remoteEndpoint,
1439 "Server Sent Unicast Last Data - data length [%zu]",
1440 remainingLen + CA_BLE_HEADER_SIZE);
1445 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
1446 OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
1449 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1452 static void CALEClientSendDataThread(void *threadData)
1454 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1456 CALEData_t *bleData = (CALEData_t *) threadData;
1459 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid bledata!");
1463 if (!bleData->remoteEndpoint)
1465 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid endpoint of bledata!");
1469 #if defined(__ANDROID__)
1471 if (false == CALEClientIsConnected(bleData->remoteEndpoint->addr))
1473 // triggering to gatt connect and MTU negotiation
1474 CAResult_t res = CALEClientSendNegotiationMessage(
1475 bleData->remoteEndpoint->addr);
1477 if (CA_STATUS_OK != res)
1481 "CALEClientSendNegotiationMessage has failed, result [%d]",
1485 g_errorHandler(bleData->remoteEndpoint,
1493 g_mtuSize = CALEClientGetMtuSize(bleData->remoteEndpoint->addr);
1495 OIC_LOG_V(INFO, CALEADAPTER_TAG, "MTU size [%d]", g_mtuSize);
1497 uint32_t midPacketCount = 0;
1498 size_t remainingLen = 0;
1499 size_t totalLength = 0;
1500 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1502 CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
1508 if (CA_STATUS_OK != result)
1510 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1511 "CAGenerateVariableForFragmentation failed, result [%d]", result);
1514 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1519 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1520 "Packet info: data size[%d] midPacketCount[%u] remainingLen[%zu] totalLength[%zu]",
1521 bleData->dataLen, midPacketCount, remainingLen, totalLength);
1523 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1524 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1526 if (NULL != bleData->remoteEndpoint) //Unicast Data
1528 secureFlag = (bleData->remoteEndpoint->flags & CA_SECURE) ?
1529 CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
1531 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This Packet is secure? %d", secureFlag);
1532 result = CAGenerateHeader(dataHeader,
1533 CA_BLE_PACKET_START,
1534 g_localBLESourcePort,
1536 bleData->remoteEndpoint->port);
1538 else //Multicast Data
1540 result = CAGenerateHeader(dataHeader,
1541 CA_BLE_PACKET_START,
1542 g_localBLESourcePort,
1544 CA_BLE_MULTICAST_PORT);
1547 OIC_LOG_V(INFO, CALEADAPTER_TAG, "header info: secureFlag[%X]", secureFlag);
1549 if (CA_STATUS_OK != result)
1551 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1552 "CAGenerateHeader failed, result [%d]", result);
1555 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1560 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1561 result = CAGenerateHeaderPayloadLength(lengthHeader,
1562 CA_BLE_LENGTH_HEADER_SIZE,
1565 if (CA_STATUS_OK != result)
1567 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1568 "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1571 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1576 uint32_t length = 0;
1577 uint32_t dataLen = 0;
1578 if (g_mtuSize > totalLength)
1580 length = (uint32_t)totalLength;
1581 dataLen = bleData->dataLen;
1586 dataLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1589 result = CAMakeFirstDataSegment(dataSegment,
1590 bleData->data, dataLen,
1591 dataHeader, lengthHeader);
1593 if (CA_STATUS_OK != result)
1595 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1596 "Making data segment failed, result [%d]", result);
1599 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1604 const uint32_t iter = midPacketCount;
1606 if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
1608 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
1609 // Send the first segment with the header.
1611 CAUpdateCharacteristicsToGattServer(
1612 bleData->remoteEndpoint->addr,
1618 if (CA_STATUS_OK != result)
1622 "Update characteristics failed, result [%d]",
1626 g_errorHandler(bleData->remoteEndpoint,
1635 "Client Sent Unicast First Data - data length [%zu]",
1638 result = CAGenerateHeader(dataHeader,
1639 CA_BLE_PACKET_NOT_START,
1640 g_localBLESourcePort,
1642 bleData->remoteEndpoint->port);
1644 if (CA_STATUS_OK != result)
1646 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1647 "CAGenerateHeader failed, result [%d]", result);
1650 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1655 for (index = 0; index < iter; index++)
1657 result = CAMakeRemainDataSegment(dataSegment,
1658 g_mtuSize - CA_BLE_HEADER_SIZE,
1665 if (CA_STATUS_OK != result)
1667 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1668 "Making data segment failed, result [%d]", result);
1671 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1676 // Send the remaining header.
1677 result = CAUpdateCharacteristicsToGattServer(
1678 bleData->remoteEndpoint->addr,
1683 if (CA_STATUS_OK != result)
1687 "Update characteristics failed, result [%d]",
1691 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1697 "Client Sent Unicast %d Data - data(mtu) length [%zu]",
1702 if (remainingLen && (totalLength > g_mtuSize))
1704 // send the last segment of the data (Ex: 22 bytes of 622
1705 // bytes of data when MTU is 200)
1706 result = CAMakeRemainDataSegment(dataSegment,
1714 if (CA_STATUS_OK != result)
1716 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1717 "Making data segment failed, result [%d]", result);
1720 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1725 result = CAUpdateCharacteristicsToGattServer(
1726 bleData->remoteEndpoint->addr,
1728 remainingLen + CA_BLE_HEADER_SIZE,
1731 if (CA_STATUS_OK != result)
1733 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1737 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1743 "Client Sent Unicast Last Data - data length [%zu]",
1744 remainingLen + CA_BLE_HEADER_SIZE);
1749 //Sending Mulitcast Data
1750 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Client Sending Multicast Data");
1751 OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
1754 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1757 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
1758 const uint8_t *data,
1759 uint32_t dataLength,
1760 u_arraylist_t *senderInfo)
1762 CALEData_t * const bleData = OICMalloc(sizeof(CALEData_t));
1766 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1770 bleData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
1771 bleData->data = OICCalloc(dataLength + 1, 1);
1773 if (NULL == bleData->data)
1775 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1776 CAFreeLEData(bleData);
1780 memcpy(bleData->data, data, dataLength);
1781 bleData->dataLen = dataLength;
1784 bleData->senderInfo = senderInfo;
1790 static void CAFreeLEData(CALEData_t *bleData)
1792 VERIFY_NON_NULL_VOID(bleData, CALEADAPTER_TAG, "Param bleData is NULL");
1794 CAFreeEndpoint(bleData->remoteEndpoint);
1795 OICFree(bleData->data);
1799 static void CALEDataDestroyer(void *data, uint32_t size)
1801 if ((size_t)size < sizeof(CALEData_t *))
1803 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1804 "Destroy data too small %p %d", data, size);
1806 CALEData_t *ledata = (CALEData_t *) data;
1808 CAFreeLEData(ledata);
1812 #ifdef SINGLE_THREAD
1813 static void CALEDataReceiverHandlerSingleThread(const uint8_t *data,
1816 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1818 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1821 CABLEPacketStart_t startFlag = CA_BLE_PACKET_NOT_START;
1822 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1823 uint16_t sourcePort = 0;
1824 uint16_t destPort = 0;
1826 CAParseHeader(data, &startFlag, &sourcePort, &secureFlag, &destPort);
1827 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1828 "header info: startFlag[%X] sourcePort[%d] secureFlag[%X] destPort[%d]",
1829 startFlag, sourcePort, secureFlag, destPort);
1831 if (destPort != g_localBLESourcePort && destPort != CA_BLE_MULTICAST_PORT)
1833 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1834 "this packet is not valid for this app(port mismatch[mine:%d, packet:%d])",
1835 g_localBLESourcePort, destPort);
1841 if (g_singleThreadReceiveData)
1843 OIC_LOG(ERROR, CALEADAPTER_TAG,
1844 "This packet is start packet but exist senderInfo. Remove senderInfo");
1845 OICFree(g_singleThreadReceiveData->defragData);
1846 OICFree(g_singleThreadReceiveData);
1847 g_singleThreadReceiveData = NULL;
1850 uint32_t totalLength = 0;
1851 CAParseHeaderPayloadLength(data, CA_BLE_LENGTH_HEADER_SIZE, &totalLength);
1853 g_singleThreadReceiveData = OICMalloc(sizeof(CABLESenderInfo_t));
1855 if (!g_singleThreadReceiveData)
1857 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
1860 g_singleThreadReceiveData->recvDataLen = 0;
1861 g_singleThreadReceiveData->totalDataLen = 0;
1862 g_singleThreadReceiveData->defragData = NULL;
1863 g_singleThreadReceiveData->remoteEndpoint = NULL;
1865 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
1867 g_singleThreadReceiveData->totalDataLen = totalLength;
1869 if (!(g_singleThreadReceiveData->totalDataLen))
1871 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
1872 OICFree(g_singleThreadReceiveData);
1876 size_t dataOnlyLen = dataLen - (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE);
1877 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
1878 g_singleThreadReceiveData->totalDataLen);
1879 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%u] bytes",
1882 g_singleThreadReceiveData->defragData =
1883 OICCalloc(g_singleThreadReceiveData->totalDataLen + 1,
1884 sizeof(*g_singleThreadReceiveData->defragData));
1886 if (NULL == g_singleThreadReceiveData->defragData)
1888 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
1889 OICFree(g_singleThreadReceiveData);
1893 if (g_singleThreadReceiveData->recvDataLen + dataOnlyLen
1894 > g_singleThreadReceiveData->totalDataLen)
1896 OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
1897 OICFree(g_singleThreadReceiveData->defragData);
1898 OICFree(g_singleThreadReceiveData);
1901 memcpy(g_singleThreadReceiveData->defragData,
1902 data + (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE),
1904 g_singleThreadReceiveData->recvDataLen += dataOnlyLen;
1908 size_t dataOnlyLen = dataLen - CA_BLE_HEADER_SIZE;
1909 if (g_singleThreadReceiveData->recvDataLen + dataOnlyLen
1910 > g_singleThreadReceiveData->totalDataLen)
1912 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1913 "Data Length exceeding error!! Receiving [%d] total length [%d]",
1914 g_singleThreadReceiveData->recvDataLen + dataOnlyLen,
1915 g_singleThreadReceiveData->totalDataLen);
1916 OICFree(g_singleThreadReceiveData->defragData);
1917 OICFree(g_singleThreadReceiveData);
1920 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]",
1922 memcpy(g_singleThreadReceiveData->defragData + g_singleThreadReceiveData->recvDataLen,
1923 data + CA_BLE_HEADER_SIZE,
1925 g_singleThreadReceiveData->recvDataLen += dataOnlyLen;
1926 OIC_LOG_V(INFO, CALEADAPTER_TAG, "totalDatalength [%d] received Datalen [%d]",
1927 g_singleThreadReceiveData->totalDataLen, g_singleThreadReceiveData->recvDataLen);
1929 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1932 static CAResult_t CALEServerSendDataSingleThread(const uint8_t *data,
1935 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__););
1937 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1939 uint32_t midPacketCount = 0;
1940 size_t remainingLen = 0;
1941 size_t totalLength = 0;
1942 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1944 CAResult_t result = CAGenerateVariableForFragmentation(dataLen,
1950 if (CA_STATUS_OK != result)
1952 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1953 "CAGenerateVariableForFragmentation failed, result [%d]", result);
1957 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1958 "Packet info: data size[%d] midPacketCount[%d] remainingLen[%d] totalLength[%d]",
1959 dataLen, midPacketCount, remainingLen, totalLength);
1963 "Server total Data length with header is [%u]",
1966 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1967 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1969 result = CAGenerateHeader(dataHeader,
1970 CA_BLE_PACKET_START,
1971 g_localBLESourcePort,
1972 CA_BLE_PACKET_NON_SECURE,
1973 CA_BLE_MULTICAST_PORT);
1975 if (CA_STATUS_OK != result)
1977 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1978 "CAGenerateHeader failed, result [%d]", result);
1982 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1983 result = CAGenerateHeaderPayloadLength(lengthHeader,
1984 CA_BLE_LENGTH_HEADER_SIZE,
1987 if (CA_STATUS_OK != result)
1989 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1990 "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1994 uint32_t length = 0;
1995 uint32_t dataOnlyLen = 0;
1996 if (g_mtuSize > totalLength)
1998 length = totalLength;
1999 dataOnlyLen = dataLen;
2004 dataOnlyLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
2007 result = CAMakeFirstDataSegment(dataSegment,
2009 dataHeader, lengthHeader);
2011 if (CA_STATUS_OK != result)
2013 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2014 "Making data segment failed, result [%d]", result);
2018 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
2019 result = CAUpdateCharacteristicsToAllGattClients(dataSegment, length);
2020 if (CA_STATUS_OK != result)
2022 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
2029 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
2031 result = CAGenerateHeader(dataHeader,
2032 CA_BLE_PACKET_NOT_START,
2033 g_localBLESourcePort,
2034 CA_BLE_PACKET_NON_SECURE,
2035 CA_BLE_MULTICAST_PORT);
2037 if (CA_STATUS_OK != result)
2039 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2040 "CAGenerateHeader failed, result [%d]", result);
2044 const uint32_t dataLimit = midPacketCount;
2045 for (uint32_t iter = 0; iter < dataLimit; iter++)
2047 result = CAMakeRemainDataSegment(dataSegment,
2048 g_mtuSize - CA_BLE_HEADER_SIZE,
2055 if (CA_STATUS_OK != result)
2057 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2058 "Making data segment failed, result [%d]", result);
2062 result = CAUpdateCharacteristicsToAllGattClients(
2066 if (CA_STATUS_OK != result)
2068 OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2075 if (remainingLen && (totalLength > g_mtuSize))
2077 // send the last segment of the data
2078 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
2080 result = CAMakeRemainDataSegment(dataSegment,
2088 if (CA_STATUS_OK != result)
2090 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2091 "Making data segment failed, result [%d]", result);
2095 result = CAUpdateCharacteristicsToAllGattClients(
2097 remainingLen + CA_BLE_HEADER_SIZE);
2099 if (CA_STATUS_OK != result)
2101 OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2111 static CAResult_t CAInitLEAdapterMutex()
2113 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2115 if (NULL == g_bleIsServerMutex)
2117 g_bleIsServerMutex = oc_mutex_new();
2118 if (NULL == g_bleIsServerMutex)
2120 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2121 return CA_STATUS_FAILED;
2125 if (NULL == g_bleLocalAddressMutex)
2127 g_bleLocalAddressMutex = oc_mutex_new();
2128 if (NULL == g_bleLocalAddressMutex)
2130 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2131 CATerminateLEAdapterMutex();
2132 return CA_STATUS_FAILED;
2138 if (NULL == g_bleServerReceiveDataMutex)
2140 g_bleServerReceiveDataMutex = oc_mutex_new();
2141 if (NULL == g_bleServerReceiveDataMutex)
2143 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2144 return CA_STATUS_FAILED;
2148 if (NULL == g_bleClientReceiveDataMutex)
2150 g_bleClientReceiveDataMutex = oc_mutex_new();
2151 if (NULL == g_bleClientReceiveDataMutex)
2153 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2154 return CA_STATUS_FAILED;
2158 return CA_STATUS_OK;
2161 static void CATerminateLEAdapterMutex()
2163 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2165 oc_mutex_free(g_bleIsServerMutex);
2166 g_bleIsServerMutex = NULL;
2169 oc_mutex_free(g_bleLocalAddressMutex);
2170 g_bleLocalAddressMutex = NULL;
2174 oc_mutex_free(g_bleServerReceiveDataMutex);
2175 g_bleServerReceiveDataMutex = NULL;
2177 oc_mutex_free(g_bleClientReceiveDataMutex);
2178 g_bleClientReceiveDataMutex = NULL;
2182 * Starting LE connectivity adapters.
2184 * As its peer to peer it does not require to start any servers.
2186 * @return ::CA_STATUS_OK or Appropriate error code.
2188 static CAResult_t CAStartLE();
2191 * Start listening server for receiving multicast search requests.
2193 * Transport Specific Behavior:
2194 * LE Starts GATT Server with prefixed UUID and Characteristics
2195 * per OIC Specification.
2196 * @return ::CA_STATUS_OK or Appropriate error code.
2198 static CAResult_t CAStartLEListeningServer();
2201 * Stops listening server from receiving multicast search requests.
2203 * Transport Specific Behavior:
2204 * LE Starts GATT Server with prefixed UUID and Characteristics
2205 * per OIC Specification.
2206 * @return ::CA_STATUS_OK or Appropriate error code.
2208 static CAResult_t CAStopLEListeningServer();
2211 * Sarting discovery of servers for receiving multicast
2214 * Transport Specific Behavior:
2215 * LE Starts GATT Server with prefixed UUID and Characteristics
2216 * per OIC Specification.
2218 * @return ::CA_STATUS_OK or Appropriate error code
2220 static CAResult_t CAStartLEDiscoveryServer();
2223 * Send data to the endpoint using the adapter connectivity.
2225 * @param[in] endpoint Remote Endpoint information (like MAC address,
2226 * reference URI and connectivity type) to which
2227 * the unicast data has to be sent.
2228 * @param[in] data Data which required to be sent.
2229 * @param[in] dataLen Size of data to be sent.
2231 * @note dataLen must be > 0.
2233 * @return The number of bytes sent on the network, or -1 on error.
2235 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2238 CADataType_t dataType);
2241 * Send multicast data to the endpoint using the LE connectivity.
2243 * @param[in] endpoint Remote Endpoint information to which the
2244 * multicast data has to be sent.
2245 * @param[in] data Data which required to be sent.
2246 * @param[in] dataLen Size of data to be sent.
2248 * @note dataLen must be > 0.
2250 * @return The number of bytes sent on the network, or -1 on error.
2252 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
2255 CADataType_t dataType);
2258 * Get LE Connectivity network information.
2260 * @param[out] info Local connectivity information structures.
2261 * @param[out] size Number of local connectivity structures.
2263 * @return ::CA_STATUS_OK or Appropriate error code.
2265 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info,
2269 * Read Synchronous API callback.
2271 * @return ::CA_STATUS_OK or Appropriate error code.
2273 static CAResult_t CAReadLEData();
2276 * Stopping the adapters and close socket connections.
2278 * LE Stops all GATT servers and GATT Clients.
2280 * @return ::CA_STATUS_OK or Appropriate error code.
2282 static CAResult_t CAStopLE();
2285 * Terminate the LE connectivity adapter.
2287 * Configuration information will be deleted from further use.
2289 static void CATerminateLE();
2292 * This function will receive the data from the GattServer and add the
2293 * data to the Server receiver queue.
2295 * @param[in] remoteAddress Remote address of the device from where
2297 * @param[in] data Actual data received from the remote
2299 * @param[in] dataLength Length of the data received from the
2301 * @param[in] sentLength Length of the data sent from the remote
2304 * @return ::CA_STATUS_OK or Appropriate error code.
2305 * @retval ::CA_STATUS_OK Successful.
2306 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2307 * @retval ::CA_STATUS_FAILED Operation failed.
2310 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
2311 const uint8_t *data,
2312 uint32_t dataLength,
2313 uint32_t *sentLength);
2316 * This function will receive the data from the GattClient and add the
2317 * data into the Client receiver queue.
2319 * @param[in] remoteAddress Remote address of the device from where
2321 * @param[in] data Actual data recevied from the remote
2323 * @param[in] dataLength Length of the data received from the
2325 * @param[in] sentLength Length of the data sent from the remote
2328 * @return ::CA_STATUS_OK or Appropriate error code.
2329 * @retval ::CA_STATUS_OK Successful.
2330 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2331 * @retval ::CA_STATUS_FAILED Operation failed.
2333 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
2334 const uint8_t *data,
2335 uint32_t dataLength,
2336 uint32_t *sentLength);
2339 * Set the NetworkPacket received callback to CA layer from adapter
2342 * @param[in] callback Callback handle sent from the upper layer.
2344 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
2347 * Push the data from CA layer to the Sender processor queue.
2349 * @param[in] remoteEndpoint Remote endpoint information of the
2351 * @param[in] data Data to be transmitted from LE.
2352 * @param[in] dataLen Length of the Data being transmitted.
2354 * @return ::CA_STATUS_OK or Appropriate error code.
2355 * @retval ::CA_STATUS_OK Successful.
2356 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2357 * @retval ::CA_STATUS_FAILED Operation failed.
2359 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
2360 const uint8_t *data,
2364 * Push the data from CA layer to the Sender processor queue.
2366 * @param[in] remoteEndpoint Remote endpoint information of the
2368 * @param[in] data Data to be transmitted from LE.
2369 * @param[in] dataLen Length of the Data being transmitted.
2371 * @return ::CA_STATUS_OK or Appropriate error code.
2372 * @retval ::CA_STATUS_OK Successful.
2373 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2374 * @retval ::CA_STATUS_FAILED Operation failed.
2376 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
2377 const uint8_t *data,
2380 static CAResult_t CALEAdapterGattServerStart()
2382 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2384 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2386 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2387 caglobals.bleFlags);
2388 return CA_STATUS_OK;
2391 CAResult_t result = CAStartLEGattServer();
2393 #ifndef SINGLE_THREAD
2395 Don't start the server side sending queue thread until the
2396 server itself has actually started.
2398 if (CA_STATUS_OK == result)
2400 result = CAQueueingThreadStart(g_bleServerSendQueueHandle);
2401 if (CA_STATUS_OK != result)
2405 "Unable to start server queuing thread (%d)",
2414 static CAResult_t CALEAdapterGattServerStop()
2416 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2418 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2420 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2421 caglobals.bleFlags);
2422 return CA_STATUS_OK;
2425 #ifndef SINGLE_THREAD
2427 CAResult_t res = CAQueueingThreadStop(g_bleServerSendQueueHandle);
2428 if (CA_STATUS_OK != res)
2430 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAQueueingThreadStop has failed");
2432 res = CAStopLEGattServer();
2433 if (CA_STATUS_OK != res)
2435 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAStopLEGattServer has failed");
2440 return CAStopLEGattServer();
2444 static CAResult_t CALEAdapterGattClientStart()
2446 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2448 CAResult_t result = CAStartLEGattClient();
2450 #ifndef SINGLE_THREAD
2452 Don't start the client side sending queue thread until the
2453 client itself has actually started.
2455 if (CA_STATUS_OK == result)
2457 result = CAQueueingThreadStart(g_bleClientSendQueueHandle);
2458 if (CA_STATUS_OK != result)
2462 "Unable to start client queuing thread");
2470 static CAResult_t CALEAdapterGattClientStop()
2472 #ifndef SINGLE_THREAD
2473 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2474 CAStopLEGattClient();
2476 CAResult_t result = CAQueueingThreadStop(g_bleClientSendQueueHandle);
2480 CAStopLEGattClient();
2482 return CA_STATUS_OK;
2486 #ifdef __WITH_DTLS__
2487 static ssize_t CALESecureSendDataCB(CAEndpoint_t *endpoint, const void *data, size_t dataLen)
2489 VERIFY_NON_NULL(endpoint, CALEADAPTER_TAG, "endpoint is NULL");
2490 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "data is NULL");
2491 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2492 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "encrypted datalen = %d", dataLen);
2495 CADataType_t dataType = g_dataType;
2498 if (ADAPTER_SERVER == g_adapterType ||
2499 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2501 result = CALEAdapterServerSendData(endpoint, data, dataLen);
2502 if (CA_STATUS_OK != result)
2504 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed" );
2508 g_errorHandler(endpoint, data, dataLen, result);
2512 ret = (ssize_t)dataLen;
2514 else if (ADAPTER_CLIENT == g_adapterType ||
2515 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
2516 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
2518 result = CALEAdapterClientSendData(endpoint, data, dataLen);
2519 if (CA_STATUS_OK != result)
2521 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
2525 g_errorHandler(endpoint, data, dataLen, result);
2529 ret = (ssize_t)dataLen;
2533 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2534 "Can't Send Message adapterType = %d, dataType = %d", g_adapterType, dataType);
2537 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2541 CAResult_t CALESecureReceiveDataCB(const CASecureEndpoint_t *sep, const void *data,
2544 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2546 VERIFY_NON_NULL(sep, CALEADAPTER_TAG, "sep is NULL");
2547 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "data is NULL");
2549 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2550 "Secure Data Receive - decrypted datalen = %d", dataLen);
2554 OIC_LOG(ERROR, CALEADAPTER_TAG, "incorrect dataLen, derecypt fail !");
2555 return CA_STATUS_INVALID_PARAM;
2558 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2560 CAResult_t res = CA_STATUS_OK;
2561 if (g_networkPacketReceivedCallback)
2563 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2564 "[CALESecureReceiveDataCB] Secure flags = %d, %x",
2565 sep->endpoint.flags, sep->endpoint.flags);
2566 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2567 "[CALESecureReceiveDataCB] Received data up !");
2568 res = g_networkPacketReceivedCallback(sep, data, dataLen);
2569 if (CA_STATUS_OK != res)
2571 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Error parsing CoAP data, res = %d", res);
2578 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
2579 CANetworkPacketReceivedCallback reqRespCallback,
2580 CAAdapterChangeCallback netCallback,
2581 CAConnectionChangeCallback connCallback,
2582 CAErrorHandleCallback errorCallback,
2583 ca_thread_pool_t handle)
2585 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2588 VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null");
2589 VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null");
2590 VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null");
2591 VERIFY_NON_NULL(connCallback, CALEADAPTER_TAG, "ConnectionChange Callback is null");
2593 CAResult_t result = CA_STATUS_OK;
2594 result = CAInitLEAdapterMutex();
2595 if (CA_STATUS_OK != result)
2597 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
2598 return CA_STATUS_FAILED;
2601 result = CAInitializeLENetworkMonitor();
2602 if (CA_STATUS_OK != result)
2604 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
2605 return CA_STATUS_FAILED;
2607 CAInitializeLEAdapter();
2609 result = CAInitializeLEGattClient();
2610 if (CA_STATUS_OK != result)
2612 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattClient() failed");
2613 return CA_STATUS_FAILED;
2616 CASetLEClientThreadPoolHandle(handle);
2618 CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
2619 CASetLEServerThreadPoolHandle(handle);
2620 result = CAInitializeLEGattServer();
2621 if (CA_STATUS_OK != result)
2623 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattServer() failed");
2624 return CA_STATUS_FAILED;
2627 CASetLEAdapterThreadPoolHandle(handle);
2628 CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
2629 CASetLEReqRespAdapterCallback(reqRespCallback);
2631 CASetBLEClientErrorHandleCallback(CALEErrorHandler);
2632 CASetBLEServerErrorHandleCallback(CALEErrorHandler);
2633 CALERegisterNetworkNotifications(netCallback, connCallback);
2635 g_errorHandler = errorCallback;
2637 #ifdef __WITH_DTLS__
2638 if (CA_STATUS_OK != CAinitSslAdapter())
2640 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to init SSL adapter");
2644 CAsetSslAdapterCallbacks(CALESecureReceiveDataCB, CALESecureSendDataCB,
2645 CA_ADAPTER_GATT_BTLE);
2649 static const CAConnectivityHandler_t connHandler =
2651 .startAdapter = CAStartLE,
2652 .stopAdapter = CAStopLE,
2653 .startListenServer = CAStartLEListeningServer,
2654 .stopListenServer = CAStopLEListeningServer,
2655 .startDiscoveryServer = CAStartLEDiscoveryServer,
2656 .sendData = CASendLEUnicastData,
2657 .sendDataToAll = CASendLEMulticastData,
2658 .GetnetInfo = CAGetLEInterfaceInformation,
2659 .readData = CAReadLEData,
2660 .terminate = CATerminateLE,
2661 .cType = CA_ADAPTER_GATT_BTLE
2664 registerCallback(connHandler);
2665 return CA_STATUS_OK;
2668 static CAResult_t CAStartLE()
2670 return CAStartLEAdapter();
2673 static CAResult_t CAStopLE()
2676 #ifndef SINGLE_THREAD
2680 oc_mutex_lock(g_bleIsServerMutex);
2681 switch (g_adapterType)
2683 case ADAPTER_SERVER:
2684 CALEAdapterGattServerStop();
2686 case ADAPTER_CLIENT:
2687 CALEAdapterGattClientStop();
2689 case ADAPTER_BOTH_CLIENT_SERVER:
2690 CALEAdapterGattServerStop();
2691 CALEAdapterGattClientStop();
2696 oc_mutex_unlock(g_bleIsServerMutex);
2697 return CAStopLEAdapter();
2700 static void CATerminateLE()
2702 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2704 CASetLEReqRespServerCallback(NULL);
2705 CASetLEReqRespClientCallback(NULL);
2706 CALERegisterNetworkNotifications(NULL, NULL);
2707 CASetLEReqRespAdapterCallback(NULL);
2708 CATerminateLENetworkMonitor();
2710 oc_mutex_lock(g_bleIsServerMutex);
2711 switch (g_adapterType)
2713 case ADAPTER_SERVER:
2714 CATerminateLEGattServer();
2716 case ADAPTER_CLIENT:
2717 CATerminateLEGattClient();
2719 case ADAPTER_BOTH_CLIENT_SERVER:
2720 CATerminateLEGattServer();
2721 CATerminateLEGattClient();
2726 g_adapterType = ADAPTER_EMPTY;
2727 oc_mutex_unlock(g_bleIsServerMutex);
2729 #ifndef SINGLE_THREAD
2730 CATerminateLEQueues();
2733 #ifdef __WITH_DTLS__
2734 CAsetSslAdapterCallbacks(NULL, NULL, CA_ADAPTER_GATT_BTLE);
2737 CATerminateLEAdapterMutex();
2740 static CAResult_t CAStartLEListeningServer()
2742 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2744 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2746 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2747 caglobals.bleFlags);
2748 return CA_STATUS_OK;
2751 #ifndef ROUTING_GATEWAY
2752 CAResult_t result = CA_STATUS_OK;
2753 #ifndef SINGLE_THREAD
2754 result = CAInitLEServerQueues();
2755 if (CA_STATUS_OK != result)
2757 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
2762 oc_mutex_lock(g_bleIsServerMutex);
2763 switch (g_adapterType)
2765 case ADAPTER_CLIENT:
2766 g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2768 case ADAPTER_BOTH_CLIENT_SERVER:
2771 g_adapterType = ADAPTER_SERVER;
2773 oc_mutex_unlock(g_bleIsServerMutex);
2775 result = CAGetLEAdapterState();
2776 if (CA_STATUS_OK != result)
2778 if (CA_ADAPTER_NOT_ENABLED == result)
2782 "Listen Server will be started once BT Adapter is enabled");
2783 result = CA_STATUS_OK;
2788 result = CALEAdapterGattServerStart();
2791 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2794 // Routing Gateway only supports BLE client mode.
2795 OIC_LOG(ERROR, CALEADAPTER_TAG, "LE server not supported in Routing Gateway");
2796 return CA_NOT_SUPPORTED;
2800 static CAResult_t CAStopLEListeningServer()
2802 OIC_LOG(ERROR, CALEADAPTER_TAG, "Listen server stop not supported.");
2803 return CA_NOT_SUPPORTED;
2806 static CAResult_t CAStartLEDiscoveryServer()
2808 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2809 CAResult_t result = CA_STATUS_OK;
2810 #ifndef SINGLE_THREAD
2811 result = CAInitLEClientQueues();
2812 if (CA_STATUS_OK != result)
2814 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
2819 oc_mutex_lock(g_bleIsServerMutex);
2820 switch (g_adapterType)
2822 case ADAPTER_SERVER:
2823 g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2825 case ADAPTER_BOTH_CLIENT_SERVER:
2828 g_adapterType = ADAPTER_CLIENT;
2830 oc_mutex_unlock(g_bleIsServerMutex);
2832 result = CAGetLEAdapterState();
2833 if (CA_STATUS_OK != result)
2835 if (CA_ADAPTER_NOT_ENABLED == result)
2839 "Discovery Server will be started once BT Adapter is enabled");
2840 result = CA_STATUS_OK;
2845 result = CALEAdapterGattClientStart();
2848 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2852 static CAResult_t CAReadLEData()
2854 #ifdef SINGLE_THREAD
2857 return CA_STATUS_OK;
2860 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2863 CADataType_t dataType)
2865 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2866 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "type(%d)", dataType);
2869 VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
2870 VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2872 CAResult_t result = CA_STATUS_FAILED;
2874 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2875 if (ADAPTER_EMPTY == g_adapterType)
2877 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2880 oc_mutex_lock(g_bleIsServerMutex);
2881 if (ADAPTER_SERVER == g_adapterType ||
2882 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2884 #ifdef __WITH_DTLS__
2885 if (endpoint && endpoint->flags & CA_SECURE)
2887 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2888 "Response Data or server - secured data send(caadapternetdtlsencrypt) call");
2889 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2890 g_dataType = dataType;
2891 oc_mutex_unlock(g_bleIsServerMutex);
2893 result = CAencryptSsl(endpoint, (void *)data, dataLen);
2894 if (CA_STATUS_OK != result)
2896 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
2903 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2904 "server or both - none secured data send(CALEAdapterServerSendData) call");
2905 result = CALEAdapterServerSendData(endpoint, data, dataLen);
2908 result = CALEAdapterServerSendData(endpoint, data, dataLen);
2910 if (CA_STATUS_OK != result)
2912 oc_mutex_unlock(g_bleIsServerMutex);
2913 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed");
2916 g_errorHandler(endpoint, data, dataLen, result);
2922 else if (ADAPTER_CLIENT == g_adapterType ||
2923 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
2924 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
2926 #ifdef __WITH_DTLS__
2927 if (endpoint && endpoint->flags & CA_SECURE)
2929 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2930 "Request Data or client - secured data send(caadapternetdtlsencrypt) call");
2931 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2932 g_dataType = dataType;
2933 oc_mutex_unlock(g_bleIsServerMutex);
2935 result = CAencryptSsl(endpoint, (void *)data, dataLen);
2936 if (CA_STATUS_OK != result)
2938 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
2945 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2946 "client or both - none secured data send(CALEAdapterClientSendData) call");
2947 result = CALEAdapterClientSendData(endpoint, data, dataLen);
2950 result = CALEAdapterClientSendData(endpoint, data, dataLen);
2952 if (CA_STATUS_OK != result)
2954 oc_mutex_unlock(g_bleIsServerMutex);
2955 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
2959 g_errorHandler(endpoint, data, dataLen, result);
2964 oc_mutex_unlock(g_bleIsServerMutex);
2966 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2970 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
2973 CADataType_t dataType)
2975 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2978 VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2982 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
2986 CAResult_t result = CA_STATUS_FAILED;
2988 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2989 if (ADAPTER_EMPTY == g_adapterType)
2991 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2994 oc_mutex_lock(g_bleIsServerMutex);
2995 if (ADAPTER_SERVER == g_adapterType ||
2996 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2998 result = CALEAdapterServerSendData(NULL, data, dataLen);
2999 if (CA_STATUS_OK != result)
3001 oc_mutex_unlock(g_bleIsServerMutex);
3003 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data for server failed" );
3007 g_errorHandler(endpoint, data, dataLen, result);
3013 if (ADAPTER_CLIENT == g_adapterType ||
3014 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
3015 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
3017 result = CALEAdapterClientSendData(NULL, data, dataLen);
3018 if (CA_STATUS_OK != result)
3020 oc_mutex_unlock(g_bleIsServerMutex);
3022 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data for client failed" );
3026 g_errorHandler(endpoint, data, dataLen, result);
3031 oc_mutex_unlock(g_bleIsServerMutex);
3033 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3037 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
3039 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3041 VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
3043 char *local_address = NULL;
3045 CAResult_t res = CAGetLEAddress(&local_address);
3046 if (CA_STATUS_OK != res)
3048 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
3052 if (NULL == local_address)
3054 OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
3055 return CA_STATUS_FAILED;
3059 (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
3060 if (NULL == (*info))
3062 OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
3063 OICFree(local_address);
3064 return CA_STATUS_FAILED;
3067 size_t local_address_len = strlen(local_address);
3069 if(local_address_len >= sizeof(g_localBLEAddress) ||
3070 local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
3072 OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
3074 OICFree(local_address);
3075 return CA_STATUS_FAILED;
3078 OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
3079 oc_mutex_lock(g_bleLocalAddressMutex);
3080 OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
3081 oc_mutex_unlock(g_bleLocalAddressMutex);
3083 (*info)->adapter = CA_ADAPTER_GATT_BTLE;
3085 OICFree(local_address);
3087 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3088 return CA_STATUS_OK;
3091 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
3092 CAConnectionChangeCallback connCallback)
3094 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3096 g_networkCallback = netCallback;
3097 g_connectionCallback = connCallback;
3098 CAResult_t res = CA_STATUS_OK;
3101 res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
3102 if (CA_STATUS_OK != res)
3104 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
3109 res = CAUnSetLEAdapterStateChangedCb();
3110 if (CA_STATUS_OK != res)
3112 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
3116 if (g_connectionCallback)
3118 res = CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCb);
3119 if (CA_STATUS_OK != res)
3121 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLENWConnectionStateChangedCb failed!");
3126 res = CAUnSetLENWConnectionStateChangedCb();
3127 if (CA_STATUS_OK != res)
3129 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUnSetLENWConnectionStateChangedCb failed!");
3133 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3137 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
3140 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3142 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3145 CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE };
3146 OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), address);
3149 oc_mutex_lock(g_bleIsServerMutex);
3150 switch (g_adapterType)
3152 case ADAPTER_SERVER:
3153 CALEGattServerConnectionStateChanged(isConnected, address);
3155 case ADAPTER_CLIENT:
3156 CALEGattConnectionStateChanged(isConnected, address);
3158 case ADAPTER_BOTH_CLIENT_SERVER:
3159 CALEGattConnectionStateChanged(isConnected, address);
3160 CALEGattServerConnectionStateChanged(isConnected, address);
3165 oc_mutex_unlock(g_bleIsServerMutex);
3170 #ifndef SINGLE_THREAD
3171 if(g_bleClientSenderInfo)
3173 CALERemoveReceiveQueueData(g_bleClientSenderInfo, address);
3176 if(g_bleServerSenderInfo)
3178 CALERemoveReceiveQueueData(g_bleServerSenderInfo, address);
3181 // remove data of send queue.
3182 if (g_bleClientSendQueueHandle)
3184 CALERemoveSendQueueData(g_bleClientSendQueueHandle, address);
3187 if (g_bleServerSendQueueHandle)
3189 CALERemoveSendQueueData(g_bleServerSendQueueHandle, address);
3193 #ifdef __WITH_DTLS__
3194 CAcloseSslConnection(&localEndpoint);
3198 if (g_connectionCallback)
3200 g_connectionCallback(&localEndpoint, isConnected);
3203 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3206 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
3208 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3210 if (CA_ADAPTER_ENABLED == adapter_state)
3212 oc_mutex_lock(g_bleIsServerMutex);
3213 switch (g_adapterType)
3215 case ADAPTER_SERVER:
3216 CALEAdapterGattServerStart();
3218 case ADAPTER_CLIENT:
3219 CALEAdapterGattClientStart();
3221 case ADAPTER_BOTH_CLIENT_SERVER:
3222 CALEAdapterGattServerStart();
3223 CALEAdapterGattClientStart();
3228 oc_mutex_unlock(g_bleIsServerMutex);
3232 oc_mutex_lock(g_bleIsServerMutex);
3233 switch (g_adapterType)
3235 case ADAPTER_SERVER:
3236 CALEAdapterGattServerStop();
3238 case ADAPTER_CLIENT:
3239 CALEAdapterGattClientStop();
3241 case ADAPTER_BOTH_CLIENT_SERVER:
3242 CALEAdapterGattServerStop();
3243 CALEAdapterGattClientStop();
3248 oc_mutex_unlock(g_bleIsServerMutex);
3251 if (NULL != g_networkCallback)
3253 g_networkCallback(CA_ADAPTER_GATT_BTLE, adapter_state);
3257 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
3260 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3263 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
3264 const uint8_t *data,
3267 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3268 #ifndef SINGLE_THREAD
3269 VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
3270 "g_bleClientSendQueueHandle is NULL",
3273 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%u]", dataLen);
3275 CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3278 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3279 return CA_MEMORY_ALLOC_FAILED;
3281 // Add message to send queue
3283 CAResult_t res = CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData,
3284 sizeof(CALEData_t));
3285 if (CA_STATUS_OK != res)
3287 CALEDataDestroyer(bleData, sizeof(CALEData_t));
3290 return CA_STATUS_OK;
3293 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
3294 const uint8_t *data,
3297 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3299 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3301 #ifdef SINGLE_THREAD
3302 if (!CAIsLEConnected())
3304 OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
3305 return CA_STATUS_FAILED;
3308 CAResult_t result = CALEServerSendDataSingleThread(data, dataLen);
3309 if (CA_STATUS_OK != result)
3311 OIC_LOG(ERROR, CALEADAPTER_TAG, "CALEServerSendDataSingleThread failed");
3312 return CA_STATUS_FAILED;
3315 VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
3316 "g_bleServerSendQueueHandle is NULL",
3319 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
3321 CALEData_t * const bleData =
3322 CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3326 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3327 return CA_MEMORY_ALLOC_FAILED;
3330 // Add message to send queue
3332 CAResult_t res = CAQueueingThreadAddData(g_bleServerSendQueueHandle,
3334 sizeof(CALEData_t));
3335 if (CA_STATUS_OK != res)
3337 CALEDataDestroyer(bleData, sizeof(CALEData_t));
3340 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3341 return CA_STATUS_OK;
3344 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
3345 const uint8_t *data,
3346 uint32_t dataLength,
3347 uint32_t *sentLength)
3349 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3352 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3353 VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3355 #ifdef SINGLE_THREAD
3356 CALEDataReceiverHandlerSingleThread(data, dataLength);
3358 if (g_singleThreadReceiveData->totalDataLen == g_singleThreadReceiveData->recvDataLen)
3360 if(g_networkPacketReceivedCallback)
3362 // will be filled by upper layer
3363 const CASecureEndpoint_t endpoint =
3364 { .endpoint = { .adapter = CA_ADAPTER_GATT_BTLE } };
3366 g_networkPacketReceivedCallback(&endpoint,
3367 g_singleThreadReceiveData->defragData,
3368 g_singleThreadReceiveData->recvDataLen);
3370 g_singleThreadReceiveData->remoteEndpoint = NULL;
3371 OICFree(g_singleThreadReceiveData->defragData);
3372 g_singleThreadReceiveData->defragData = NULL;
3373 OICFree(g_singleThreadReceiveData);
3374 g_singleThreadReceiveData = NULL;
3377 VERIFY_NON_NULL_RET(g_bleServerReceiverQueue,
3379 "g_bleServerReceiverQueue",
3382 //Add message to data queue
3383 CAEndpoint_t * const remoteEndpoint =
3384 CACreateEndpointObject(CA_DEFAULT_FLAGS,
3385 CA_ADAPTER_GATT_BTLE,
3389 if (NULL == remoteEndpoint)
3391 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3392 return CA_STATUS_FAILED;
3395 // Create bleData to add to queue
3398 "Data received from LE Server layer [%d]",
3401 CALEData_t * const bleData =
3402 CACreateLEData(remoteEndpoint, data, dataLength, g_bleServerSenderInfo);
3406 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3407 CAFreeEndpoint(remoteEndpoint);
3408 return CA_MEMORY_ALLOC_FAILED;
3411 CAFreeEndpoint(remoteEndpoint);
3412 // Add message to receiver queue
3413 CAQueueingThreadAddData(g_bleServerReceiverQueue, bleData, sizeof(CALEData_t));
3415 *sentLength = dataLength;
3417 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3418 return CA_STATUS_OK;
3421 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
3422 const uint8_t *data,
3423 uint32_t dataLength,
3424 uint32_t *sentLength)
3427 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3428 VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3429 #ifndef SINGLE_THREAD
3430 VERIFY_NON_NULL_RET(g_bleClientReceiverQueue, CALEADAPTER_TAG,
3431 "g_bleClientReceiverQueue",
3434 //Add message to data queue
3435 CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
3436 CA_ADAPTER_GATT_BTLE,
3438 if (NULL == remoteEndpoint)
3440 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3441 return CA_STATUS_FAILED;
3444 // Create bleData to add to queue
3447 "Data received from LE Client layer [%zu]",
3450 CALEData_t * const bleData =
3451 CACreateLEData(remoteEndpoint, data, dataLength, g_bleClientSenderInfo);
3455 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3456 CAFreeEndpoint(remoteEndpoint);
3457 return CA_MEMORY_ALLOC_FAILED;
3460 CAFreeEndpoint(remoteEndpoint);
3461 // Add message to receiver queue
3462 CAQueueingThreadAddData(g_bleClientReceiverQueue, bleData, sizeof(CALEData_t));
3464 *sentLength = dataLength;
3466 return CA_STATUS_OK;
3469 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
3471 g_bleAdapterThreadPool = handle;
3475 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
3477 g_networkPacketReceivedCallback = callback;
3481 static void CALEErrorHandler(const char *remoteAddress,
3482 const uint8_t *data,
3486 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3488 VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
3490 CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS,
3491 CA_ADAPTER_GATT_BTLE,
3495 // if required, will be used to build remote endpoint
3496 g_errorHandler(rep, data, dataLen, result);
3498 CAFreeEndpoint(rep);
3500 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3503 #ifndef SINGLE_THREAD
3504 static bool CALEClearQueueAddressDataContext(void *data, uint32_t size, void *ctx)
3506 if (NULL == data || NULL == ctx)
3511 CALEData_t *caLeData = (CALEData_t *)data;
3512 const char *address = (const char *)ctx;
3514 if (NULL != caLeData && NULL != caLeData->remoteEndpoint)
3516 if (!strcasecmp(caLeData->remoteEndpoint->addr, address))
3524 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle, const char* address)
3526 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
3528 VERIFY_NON_NULL_VOID(queueHandle, CALEADAPTER_TAG, "queueHandle");
3529 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3531 CAResult_t res = CAQueueingThreadClearContextData(queueHandle,
3532 CALEClearQueueAddressDataContext,
3534 if (CA_STATUS_OK != res)
3537 OIC_LOG(ERROR, CALEADAPTER_TAG, "Could not clear the send queue");
3542 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList, const char* address)
3544 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
3546 VERIFY_NON_NULL_VOID(dataInfoList, CALEADAPTER_TAG, "dataInfoList");
3547 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3549 CABLESenderInfo_t *senderInfo = NULL;
3550 uint32_t senderIndex = 0;
3552 u_arraylist_t *portList = u_arraylist_create();
3553 if (CA_STATUS_OK == CALEGetPortsFromSenderInfo(address, dataInfoList, portList))
3555 uint32_t arrayLength = u_arraylist_length(portList);
3556 for (uint32_t i = 0; i < arrayLength; i++)
3558 uint16_t *port = (uint16_t *)u_arraylist_get(portList, i);
3561 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to get port from sender info !");
3562 u_arraylist_destroy(portList);
3566 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "port : %X", *port);
3568 if (CA_STATUS_OK == CALEGetSenderInfo(address, *port,
3569 dataInfoList, &senderInfo,
3572 u_arraylist_remove(dataInfoList, senderIndex);
3573 OICFree(senderInfo->defragData);
3574 OICFree(senderInfo->remoteEndpoint);
3575 OICFree(senderInfo);
3577 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3578 "SenderInfo is removed for disconnection");
3582 OIC_LOG(DEBUG, CALEADAPTER_TAG, "SenderInfo doesn't exist");
3586 u_arraylist_destroy(portList);
3589 static CAResult_t CALEGetPortsFromSenderInfo(const char *leAddress,
3590 u_arraylist_t *senderInfoList,
3591 u_arraylist_t *portList)
3593 VERIFY_NON_NULL(leAddress,
3595 "NULL BLE address argument");
3597 const uint32_t listLength = u_arraylist_length(senderInfoList);
3598 const uint32_t addrLength = strlen(leAddress);
3600 for (uint32_t index = 0; index < listLength; index++)
3602 CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
3603 if (!info || !(info->remoteEndpoint))
3608 if (!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
3610 uint16_t *port = (uint16_t *)OICMalloc(sizeof(uint16_t));
3613 OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
3614 return CA_MEMORY_ALLOC_FAILED;
3616 *port = info->remoteEndpoint->port;
3617 u_arraylist_add(portList, (void *)port);
3621 if (u_arraylist_length(portList) != 0)
3623 return CA_STATUS_OK;
3627 return CA_STATUS_FAILED;
3632 void CALEStartGattServer()
3634 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3636 oc_mutex_lock(g_bleIsServerMutex);
3637 switch (g_adapterType)
3639 case ADAPTER_SERVER:
3640 CALEAdapterGattServerStart();
3642 case ADAPTER_CLIENT:
3643 CALEAdapterGattClientStart();
3645 case ADAPTER_BOTH_CLIENT_SERVER:
3646 CALEAdapterGattServerStart();
3647 CALEAdapterGattClientStart();
3652 oc_mutex_unlock(g_bleIsServerMutex);
3653 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3656 void CALEStopGattServer()
3658 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3660 oc_mutex_lock(g_bleIsServerMutex);
3661 switch (g_adapterType)
3663 case ADAPTER_SERVER:
3664 CALEAdapterGattServerStop();
3666 case ADAPTER_CLIENT:
3667 CALEAdapterGattClientStop();
3669 case ADAPTER_BOTH_CLIENT_SERVER:
3670 CALEAdapterGattServerStop();
3671 CALEAdapterGattClientStop();
3676 oc_mutex_unlock(g_bleIsServerMutex);
3677 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);