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,
1490 g_mtuSize = CALEClientGetMtuSize(bleData->remoteEndpoint->addr);
1492 OIC_LOG_V(INFO, CALEADAPTER_TAG, "MTU size [%d]", g_mtuSize);
1494 uint32_t midPacketCount = 0;
1495 size_t remainingLen = 0;
1496 size_t totalLength = 0;
1497 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1499 CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
1505 if (CA_STATUS_OK != result)
1507 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1508 "CAGenerateVariableForFragmentation failed, result [%d]", result);
1511 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1516 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1517 "Packet info: data size[%d] midPacketCount[%u] remainingLen[%zu] totalLength[%zu]",
1518 bleData->dataLen, midPacketCount, remainingLen, totalLength);
1520 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1521 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1523 if (NULL != bleData->remoteEndpoint) //Unicast Data
1525 secureFlag = (bleData->remoteEndpoint->flags & CA_SECURE) ?
1526 CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
1528 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This Packet is secure? %d", secureFlag);
1529 result = CAGenerateHeader(dataHeader,
1530 CA_BLE_PACKET_START,
1531 g_localBLESourcePort,
1533 bleData->remoteEndpoint->port);
1535 else //Multicast Data
1537 result = CAGenerateHeader(dataHeader,
1538 CA_BLE_PACKET_START,
1539 g_localBLESourcePort,
1541 CA_BLE_MULTICAST_PORT);
1544 OIC_LOG_V(INFO, CALEADAPTER_TAG, "header info: secureFlag[%X]", secureFlag);
1546 if (CA_STATUS_OK != result)
1548 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1549 "CAGenerateHeader failed, result [%d]", result);
1552 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1557 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1558 result = CAGenerateHeaderPayloadLength(lengthHeader,
1559 CA_BLE_LENGTH_HEADER_SIZE,
1562 if (CA_STATUS_OK != result)
1564 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1565 "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1568 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1573 uint32_t length = 0;
1574 uint32_t dataLen = 0;
1575 if (g_mtuSize > totalLength)
1577 length = (uint32_t)totalLength;
1578 dataLen = bleData->dataLen;
1583 dataLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1586 result = CAMakeFirstDataSegment(dataSegment,
1587 bleData->data, dataLen,
1588 dataHeader, lengthHeader);
1590 if (CA_STATUS_OK != result)
1592 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1593 "Making data segment failed, result [%d]", result);
1596 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1601 const uint32_t iter = midPacketCount;
1603 if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
1605 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
1606 // Send the first segment with the header.
1608 CAUpdateCharacteristicsToGattServer(
1609 bleData->remoteEndpoint->addr,
1615 if (CA_STATUS_OK != result)
1619 "Update characteristics failed, result [%d]",
1623 g_errorHandler(bleData->remoteEndpoint,
1632 "Client Sent Unicast First Data - data length [%u]",
1635 result = CAGenerateHeader(dataHeader,
1636 CA_BLE_PACKET_NOT_START,
1637 g_localBLESourcePort,
1639 bleData->remoteEndpoint->port);
1641 if (CA_STATUS_OK != result)
1643 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1644 "CAGenerateHeader failed, result [%d]", result);
1647 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1652 for (index = 0; index < iter; index++)
1654 result = CAMakeRemainDataSegment(dataSegment,
1655 g_mtuSize - CA_BLE_HEADER_SIZE,
1662 if (CA_STATUS_OK != result)
1664 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1665 "Making data segment failed, result [%d]", result);
1668 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1673 // Send the remaining header.
1674 result = CAUpdateCharacteristicsToGattServer(
1675 bleData->remoteEndpoint->addr,
1680 if (CA_STATUS_OK != result)
1684 "Update characteristics failed, result [%d]",
1688 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1694 "Client Sent Unicast %d Data - data(mtu) length [%hu]",
1699 if (remainingLen && (totalLength > g_mtuSize))
1701 // send the last segment of the data (Ex: 22 bytes of 622
1702 // bytes of data when MTU is 200)
1703 result = CAMakeRemainDataSegment(dataSegment,
1711 if (CA_STATUS_OK != result)
1713 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1714 "Making data segment failed, result [%d]", result);
1717 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1722 result = CAUpdateCharacteristicsToGattServer(
1723 bleData->remoteEndpoint->addr,
1725 remainingLen + CA_BLE_HEADER_SIZE,
1728 if (CA_STATUS_OK != result)
1730 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1734 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1740 "Client Sent Unicast Last Data - data length [%zu]",
1741 remainingLen + CA_BLE_HEADER_SIZE);
1746 //Sending Mulitcast Data
1747 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Client Sending Multicast Data");
1748 OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
1751 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1754 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
1755 const uint8_t *data,
1756 uint32_t dataLength,
1757 u_arraylist_t *senderInfo)
1759 CALEData_t * const bleData = OICMalloc(sizeof(CALEData_t));
1763 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1767 bleData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
1768 bleData->data = OICCalloc(dataLength + 1, 1);
1770 if (NULL == bleData->data)
1772 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1773 CAFreeLEData(bleData);
1777 memcpy(bleData->data, data, dataLength);
1778 bleData->dataLen = dataLength;
1781 bleData->senderInfo = senderInfo;
1787 static void CAFreeLEData(CALEData_t *bleData)
1789 VERIFY_NON_NULL_VOID(bleData, CALEADAPTER_TAG, "Param bleData is NULL");
1791 CAFreeEndpoint(bleData->remoteEndpoint);
1792 OICFree(bleData->data);
1796 static void CALEDataDestroyer(void *data, uint32_t size)
1798 if ((size_t)size < sizeof(CALEData_t *))
1800 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1801 "Destroy data too small %p %d", data, size);
1803 CALEData_t *ledata = (CALEData_t *) data;
1805 CAFreeLEData(ledata);
1809 #ifdef SINGLE_THREAD
1810 static void CALEDataReceiverHandlerSingleThread(const uint8_t *data,
1813 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1815 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1818 CABLEPacketStart_t startFlag = CA_BLE_PACKET_NOT_START;
1819 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1820 uint16_t sourcePort = 0;
1821 uint16_t destPort = 0;
1823 CAParseHeader(data, &startFlag, &sourcePort, &secureFlag, &destPort);
1824 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1825 "header info: startFlag[%X] sourcePort[%d] secureFlag[%X] destPort[%d]",
1826 startFlag, sourcePort, secureFlag, destPort);
1828 if (destPort != g_localBLESourcePort && destPort != CA_BLE_MULTICAST_PORT)
1830 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1831 "this packet is not valid for this app(port mismatch[mine:%d, packet:%d])",
1832 g_localBLESourcePort, destPort);
1838 if (g_singleThreadReceiveData)
1840 OIC_LOG(ERROR, CALEADAPTER_TAG,
1841 "This packet is start packet but exist senderInfo. Remove senderInfo");
1842 OICFree(g_singleThreadReceiveData->defragData);
1843 OICFree(g_singleThreadReceiveData);
1844 g_singleThreadReceiveData = NULL;
1847 uint32_t totalLength = 0;
1848 CAParseHeaderPayloadLength(data, CA_BLE_LENGTH_HEADER_SIZE, &totalLength);
1850 g_singleThreadReceiveData = OICMalloc(sizeof(CABLESenderInfo_t));
1852 if (!g_singleThreadReceiveData)
1854 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
1857 g_singleThreadReceiveData->recvDataLen = 0;
1858 g_singleThreadReceiveData->totalDataLen = 0;
1859 g_singleThreadReceiveData->defragData = NULL;
1860 g_singleThreadReceiveData->remoteEndpoint = NULL;
1862 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
1864 g_singleThreadReceiveData->totalDataLen = totalLength;
1866 if (!(g_singleThreadReceiveData->totalDataLen))
1868 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
1869 OICFree(g_singleThreadReceiveData);
1873 size_t dataOnlyLen = dataLen - (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE);
1874 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
1875 g_singleThreadReceiveData->totalDataLen);
1876 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%u] bytes",
1879 g_singleThreadReceiveData->defragData =
1880 OICCalloc(g_singleThreadReceiveData->totalDataLen + 1,
1881 sizeof(*g_singleThreadReceiveData->defragData));
1883 if (NULL == g_singleThreadReceiveData->defragData)
1885 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
1886 OICFree(g_singleThreadReceiveData);
1890 if (g_singleThreadReceiveData->recvDataLen + dataOnlyLen
1891 > g_singleThreadReceiveData->totalDataLen)
1893 OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
1894 OICFree(g_singleThreadReceiveData->defragData);
1895 OICFree(g_singleThreadReceiveData);
1898 memcpy(g_singleThreadReceiveData->defragData,
1899 data + (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE),
1901 g_singleThreadReceiveData->recvDataLen += dataOnlyLen;
1905 size_t dataOnlyLen = dataLen - CA_BLE_HEADER_SIZE;
1906 if (g_singleThreadReceiveData->recvDataLen + dataOnlyLen
1907 > g_singleThreadReceiveData->totalDataLen)
1909 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1910 "Data Length exceeding error!! Receiving [%d] total length [%d]",
1911 g_singleThreadReceiveData->recvDataLen + dataOnlyLen,
1912 g_singleThreadReceiveData->totalDataLen);
1913 OICFree(g_singleThreadReceiveData->defragData);
1914 OICFree(g_singleThreadReceiveData);
1917 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]",
1919 memcpy(g_singleThreadReceiveData->defragData + g_singleThreadReceiveData->recvDataLen,
1920 data + CA_BLE_HEADER_SIZE,
1922 g_singleThreadReceiveData->recvDataLen += dataOnlyLen;
1923 OIC_LOG_V(INFO, CALEADAPTER_TAG, "totalDatalength [%d] received Datalen [%d]",
1924 g_singleThreadReceiveData->totalDataLen, g_singleThreadReceiveData->recvDataLen);
1926 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1929 static CAResult_t CALEServerSendDataSingleThread(const uint8_t *data,
1932 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__););
1934 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1936 uint32_t midPacketCount = 0;
1937 size_t remainingLen = 0;
1938 size_t totalLength = 0;
1939 CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1941 CAResult_t result = CAGenerateVariableForFragmentation(dataLen,
1947 if (CA_STATUS_OK != result)
1949 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1950 "CAGenerateVariableForFragmentation failed, result [%d]", result);
1954 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1955 "Packet info: data size[%d] midPacketCount[%d] remainingLen[%d] totalLength[%d]",
1956 dataLen, midPacketCount, remainingLen, totalLength);
1960 "Server total Data length with header is [%u]",
1963 uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1964 uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1966 result = CAGenerateHeader(dataHeader,
1967 CA_BLE_PACKET_START,
1968 g_localBLESourcePort,
1969 CA_BLE_PACKET_NON_SECURE,
1970 CA_BLE_MULTICAST_PORT);
1972 if (CA_STATUS_OK != result)
1974 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1975 "CAGenerateHeader failed, result [%d]", result);
1979 uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1980 result = CAGenerateHeaderPayloadLength(lengthHeader,
1981 CA_BLE_LENGTH_HEADER_SIZE,
1984 if (CA_STATUS_OK != result)
1986 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1987 "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1991 uint32_t length = 0;
1992 uint32_t dataOnlyLen = 0;
1993 if (g_mtuSize > totalLength)
1995 length = totalLength;
1996 dataOnlyLen = dataLen;
2001 dataOnlyLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
2004 result = CAMakeFirstDataSegment(dataSegment,
2006 dataHeader, lengthHeader);
2008 if (CA_STATUS_OK != result)
2010 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2011 "Making data segment failed, result [%d]", result);
2015 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
2016 result = CAUpdateCharacteristicsToAllGattClients(dataSegment, length);
2017 if (CA_STATUS_OK != result)
2019 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
2026 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
2028 result = CAGenerateHeader(dataHeader,
2029 CA_BLE_PACKET_NOT_START,
2030 g_localBLESourcePort,
2031 CA_BLE_PACKET_NON_SECURE,
2032 CA_BLE_MULTICAST_PORT);
2034 if (CA_STATUS_OK != result)
2036 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2037 "CAGenerateHeader failed, result [%d]", result);
2041 const uint32_t dataLimit = midPacketCount;
2042 for (uint32_t iter = 0; iter < dataLimit; iter++)
2044 result = CAMakeRemainDataSegment(dataSegment,
2045 g_mtuSize - CA_BLE_HEADER_SIZE,
2052 if (CA_STATUS_OK != result)
2054 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2055 "Making data segment failed, result [%d]", result);
2059 result = CAUpdateCharacteristicsToAllGattClients(
2063 if (CA_STATUS_OK != result)
2065 OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2072 if (remainingLen && (totalLength > g_mtuSize))
2074 // send the last segment of the data
2075 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
2077 result = CAMakeRemainDataSegment(dataSegment,
2085 if (CA_STATUS_OK != result)
2087 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2088 "Making data segment failed, result [%d]", result);
2092 result = CAUpdateCharacteristicsToAllGattClients(
2094 remainingLen + CA_BLE_HEADER_SIZE);
2096 if (CA_STATUS_OK != result)
2098 OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2108 static CAResult_t CAInitLEAdapterMutex()
2110 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2112 if (NULL == g_bleIsServerMutex)
2114 g_bleIsServerMutex = oc_mutex_new();
2115 if (NULL == g_bleIsServerMutex)
2117 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2118 return CA_STATUS_FAILED;
2122 if (NULL == g_bleLocalAddressMutex)
2124 g_bleLocalAddressMutex = oc_mutex_new();
2125 if (NULL == g_bleLocalAddressMutex)
2127 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2128 CATerminateLEAdapterMutex();
2129 return CA_STATUS_FAILED;
2135 if (NULL == g_bleServerReceiveDataMutex)
2137 g_bleServerReceiveDataMutex = oc_mutex_new();
2138 if (NULL == g_bleServerReceiveDataMutex)
2140 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2141 return CA_STATUS_FAILED;
2145 if (NULL == g_bleClientReceiveDataMutex)
2147 g_bleClientReceiveDataMutex = oc_mutex_new();
2148 if (NULL == g_bleClientReceiveDataMutex)
2150 OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2151 return CA_STATUS_FAILED;
2155 return CA_STATUS_OK;
2158 static void CATerminateLEAdapterMutex()
2160 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2162 oc_mutex_free(g_bleIsServerMutex);
2163 g_bleIsServerMutex = NULL;
2166 oc_mutex_free(g_bleLocalAddressMutex);
2167 g_bleLocalAddressMutex = NULL;
2171 oc_mutex_free(g_bleServerReceiveDataMutex);
2172 g_bleServerReceiveDataMutex = NULL;
2174 oc_mutex_free(g_bleClientReceiveDataMutex);
2175 g_bleClientReceiveDataMutex = NULL;
2179 * Starting LE connectivity adapters.
2181 * As its peer to peer it does not require to start any servers.
2183 * @return ::CA_STATUS_OK or Appropriate error code.
2185 static CAResult_t CAStartLE();
2188 * Start listening server for receiving multicast search requests.
2190 * Transport Specific Behavior:
2191 * LE Starts GATT Server with prefixed UUID and Characteristics
2192 * per OIC Specification.
2193 * @return ::CA_STATUS_OK or Appropriate error code.
2195 static CAResult_t CAStartLEListeningServer();
2198 * Stops listening server from receiving multicast search requests.
2200 * Transport Specific Behavior:
2201 * LE Starts GATT Server with prefixed UUID and Characteristics
2202 * per OIC Specification.
2203 * @return ::CA_STATUS_OK or Appropriate error code.
2205 static CAResult_t CAStopLEListeningServer();
2208 * Sarting discovery of servers for receiving multicast
2211 * Transport Specific Behavior:
2212 * LE Starts GATT Server with prefixed UUID and Characteristics
2213 * per OIC Specification.
2215 * @return ::CA_STATUS_OK or Appropriate error code
2217 static CAResult_t CAStartLEDiscoveryServer();
2220 * Send data to the endpoint using the adapter connectivity.
2222 * @param[in] endpoint Remote Endpoint information (like MAC address,
2223 * reference URI and connectivity type) to which
2224 * the unicast data has to be sent.
2225 * @param[in] data Data which required to be sent.
2226 * @param[in] dataLen Size of data to be sent.
2228 * @note dataLen must be > 0.
2230 * @return The number of bytes sent on the network, or -1 on error.
2232 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2235 CADataType_t dataType);
2238 * Send multicast data to the endpoint using the LE connectivity.
2240 * @param[in] endpoint Remote Endpoint information to which the
2241 * multicast data has to be sent.
2242 * @param[in] data Data which required to be sent.
2243 * @param[in] dataLen Size of data to be sent.
2245 * @note dataLen must be > 0.
2247 * @return The number of bytes sent on the network, or -1 on error.
2249 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
2252 CADataType_t dataType);
2255 * Get LE Connectivity network information.
2257 * @param[out] info Local connectivity information structures.
2258 * @param[out] size Number of local connectivity structures.
2260 * @return ::CA_STATUS_OK or Appropriate error code.
2262 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info,
2266 * Read Synchronous API callback.
2268 * @return ::CA_STATUS_OK or Appropriate error code.
2270 static CAResult_t CAReadLEData();
2273 * Stopping the adapters and close socket connections.
2275 * LE Stops all GATT servers and GATT Clients.
2277 * @return ::CA_STATUS_OK or Appropriate error code.
2279 static CAResult_t CAStopLE();
2282 * Terminate the LE connectivity adapter.
2284 * Configuration information will be deleted from further use.
2286 static void CATerminateLE();
2289 * This function will receive the data from the GattServer and add the
2290 * data to the Server receiver queue.
2292 * @param[in] remoteAddress Remote address of the device from where
2294 * @param[in] data Actual data received from the remote
2296 * @param[in] dataLength Length of the data received from the
2298 * @param[in] sentLength Length of the data sent from the remote
2301 * @return ::CA_STATUS_OK or Appropriate error code.
2302 * @retval ::CA_STATUS_OK Successful.
2303 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2304 * @retval ::CA_STATUS_FAILED Operation failed.
2307 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
2308 const uint8_t *data,
2309 uint32_t dataLength,
2310 uint32_t *sentLength);
2313 * This function will receive the data from the GattClient and add the
2314 * data into the Client receiver queue.
2316 * @param[in] remoteAddress Remote address of the device from where
2318 * @param[in] data Actual data recevied from the remote
2320 * @param[in] dataLength Length of the data received from the
2322 * @param[in] sentLength Length of the data sent from the remote
2325 * @return ::CA_STATUS_OK or Appropriate error code.
2326 * @retval ::CA_STATUS_OK Successful.
2327 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2328 * @retval ::CA_STATUS_FAILED Operation failed.
2330 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
2331 const uint8_t *data,
2332 uint32_t dataLength,
2333 uint32_t *sentLength);
2336 * Set the NetworkPacket received callback to CA layer from adapter
2339 * @param[in] callback Callback handle sent from the upper layer.
2341 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
2344 * Push the data from CA layer to the Sender processor queue.
2346 * @param[in] remoteEndpoint Remote endpoint information of the
2348 * @param[in] data Data to be transmitted from LE.
2349 * @param[in] dataLen Length of the Data being transmitted.
2351 * @return ::CA_STATUS_OK or Appropriate error code.
2352 * @retval ::CA_STATUS_OK Successful.
2353 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2354 * @retval ::CA_STATUS_FAILED Operation failed.
2356 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
2357 const uint8_t *data,
2361 * Push the data from CA layer to the Sender processor queue.
2363 * @param[in] remoteEndpoint Remote endpoint information of the
2365 * @param[in] data Data to be transmitted from LE.
2366 * @param[in] dataLen Length of the Data being transmitted.
2368 * @return ::CA_STATUS_OK or Appropriate error code.
2369 * @retval ::CA_STATUS_OK Successful.
2370 * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
2371 * @retval ::CA_STATUS_FAILED Operation failed.
2373 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
2374 const uint8_t *data,
2377 static CAResult_t CALEAdapterGattServerStart()
2379 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2381 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2383 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2384 caglobals.bleFlags);
2385 return CA_STATUS_OK;
2388 CAResult_t result = CAStartLEGattServer();
2390 #ifndef SINGLE_THREAD
2392 Don't start the server side sending queue thread until the
2393 server itself has actually started.
2395 if (CA_STATUS_OK == result)
2397 result = CAQueueingThreadStart(g_bleServerSendQueueHandle);
2398 if (CA_STATUS_OK != result)
2402 "Unable to start server queuing thread (%d)",
2411 static CAResult_t CALEAdapterGattServerStop()
2413 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2415 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2417 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2418 caglobals.bleFlags);
2419 return CA_STATUS_OK;
2422 #ifndef SINGLE_THREAD
2424 CAResult_t res = CAQueueingThreadStop(g_bleServerSendQueueHandle);
2425 if (CA_STATUS_OK != res)
2427 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAQueueingThreadStop has failed");
2429 res = CAStopLEGattServer();
2430 if (CA_STATUS_OK != res)
2432 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAStopLEGattServer has failed");
2437 return CAStopLEGattServer();
2441 static CAResult_t CALEAdapterGattClientStart()
2443 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2445 CAResult_t result = CAStartLEGattClient();
2447 #ifndef SINGLE_THREAD
2449 Don't start the client side sending queue thread until the
2450 client itself has actually started.
2452 if (CA_STATUS_OK == result)
2454 result = CAQueueingThreadStart(g_bleClientSendQueueHandle);
2455 if (CA_STATUS_OK != result)
2459 "Unable to start client queuing thread");
2467 static CAResult_t CALEAdapterGattClientStop()
2469 #ifndef SINGLE_THREAD
2470 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2471 CAStopLEGattClient();
2473 CAResult_t result = CAQueueingThreadStop(g_bleClientSendQueueHandle);
2477 CAStopLEGattClient();
2479 return CA_STATUS_OK;
2483 #ifdef __WITH_DTLS__
2484 static ssize_t CALESecureSendDataCB(CAEndpoint_t *endpoint, const void *data, size_t dataLen)
2486 VERIFY_NON_NULL(endpoint, CALEADAPTER_TAG, "endpoint is NULL");
2487 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "data is NULL");
2488 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2489 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "encrypted datalen = %zd", dataLen);
2492 CADataType_t dataType = g_dataType;
2495 if (ADAPTER_SERVER == g_adapterType ||
2496 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2498 result = CALEAdapterServerSendData(endpoint, data, dataLen);
2499 if (CA_STATUS_OK != result)
2501 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed" );
2505 g_errorHandler(endpoint, data, dataLen, result);
2509 ret = (ssize_t)dataLen;
2511 else if (ADAPTER_CLIENT == g_adapterType ||
2512 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
2513 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
2515 result = CALEAdapterClientSendData(endpoint, data, dataLen);
2516 if (CA_STATUS_OK != result)
2518 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
2522 g_errorHandler(endpoint, data, dataLen, result);
2526 ret = (ssize_t)dataLen;
2530 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2531 "Can't Send Message adapterType = %d, dataType = %d", g_adapterType, dataType);
2534 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2538 CAResult_t CALESecureReceiveDataCB(const CASecureEndpoint_t *sep, const void *data,
2541 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2543 VERIFY_NON_NULL(sep, CALEADAPTER_TAG, "sep is NULL");
2544 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "data is NULL");
2546 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2547 "Secure Data Receive - decrypted datalen = %zd", dataLen);
2551 OIC_LOG(ERROR, CALEADAPTER_TAG, "incorrect dataLen, derecypt fail !");
2552 return CA_STATUS_INVALID_PARAM;
2555 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2557 CAResult_t res = CA_STATUS_OK;
2558 if (g_networkPacketReceivedCallback)
2560 OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2561 "[CALESecureReceiveDataCB] Secure flags = %d, %x",
2562 sep->endpoint.flags, sep->endpoint.flags);
2563 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2564 "[CALESecureReceiveDataCB] Received data up !");
2565 res = g_networkPacketReceivedCallback(sep, data, dataLen);
2566 if (CA_STATUS_OK != res)
2568 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Error parsing CoAP data, res = %d", res);
2575 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
2576 CANetworkPacketReceivedCallback reqRespCallback,
2577 CAAdapterChangeCallback netCallback,
2578 CAConnectionChangeCallback connCallback,
2579 CAErrorHandleCallback errorCallback,
2580 ca_thread_pool_t handle)
2582 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2585 VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null");
2586 VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null");
2587 VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null");
2588 VERIFY_NON_NULL(connCallback, CALEADAPTER_TAG, "ConnectionChange Callback is null");
2590 CAResult_t result = CA_STATUS_OK;
2591 result = CAInitLEAdapterMutex();
2592 if (CA_STATUS_OK != result)
2594 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
2595 return CA_STATUS_FAILED;
2598 result = CAInitializeLENetworkMonitor();
2599 if (CA_STATUS_OK != result)
2601 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
2602 return CA_STATUS_FAILED;
2604 CAInitializeLEAdapter();
2606 result = CAInitializeLEGattClient();
2607 if (CA_STATUS_OK != result)
2609 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattClient() failed");
2610 return CA_STATUS_FAILED;
2613 CASetLEClientThreadPoolHandle(handle);
2615 CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
2616 CASetLEServerThreadPoolHandle(handle);
2617 result = CAInitializeLEGattServer();
2618 if (CA_STATUS_OK != result)
2620 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattServer() failed");
2621 return CA_STATUS_FAILED;
2624 CASetLEAdapterThreadPoolHandle(handle);
2625 CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
2626 CASetLEReqRespAdapterCallback(reqRespCallback);
2628 CASetBLEClientErrorHandleCallback(CALEErrorHandler);
2629 CASetBLEServerErrorHandleCallback(CALEErrorHandler);
2630 CALERegisterNetworkNotifications(netCallback, connCallback);
2632 g_errorHandler = errorCallback;
2634 #ifdef __WITH_DTLS__
2635 if (CA_STATUS_OK != CAinitSslAdapter())
2637 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to init SSL adapter");
2641 CAsetSslAdapterCallbacks(CALESecureReceiveDataCB, CALESecureSendDataCB,
2642 CA_ADAPTER_GATT_BTLE);
2646 static const CAConnectivityHandler_t connHandler =
2648 .startAdapter = CAStartLE,
2649 .stopAdapter = CAStopLE,
2650 .startListenServer = CAStartLEListeningServer,
2651 .stopListenServer = CAStopLEListeningServer,
2652 .startDiscoveryServer = CAStartLEDiscoveryServer,
2653 .sendData = CASendLEUnicastData,
2654 .sendDataToAll = CASendLEMulticastData,
2655 .GetnetInfo = CAGetLEInterfaceInformation,
2656 .readData = CAReadLEData,
2657 .terminate = CATerminateLE,
2658 .cType = CA_ADAPTER_GATT_BTLE
2661 registerCallback(connHandler);
2662 return CA_STATUS_OK;
2665 static CAResult_t CAStartLE()
2667 return CAStartLEAdapter();
2670 static CAResult_t CAStopLE()
2673 #ifndef SINGLE_THREAD
2677 oc_mutex_lock(g_bleIsServerMutex);
2678 switch (g_adapterType)
2680 case ADAPTER_SERVER:
2681 CALEAdapterGattServerStop();
2683 case ADAPTER_CLIENT:
2684 CALEAdapterGattClientStop();
2686 case ADAPTER_BOTH_CLIENT_SERVER:
2687 CALEAdapterGattServerStop();
2688 CALEAdapterGattClientStop();
2693 oc_mutex_unlock(g_bleIsServerMutex);
2694 return CAStopLEAdapter();
2697 static void CATerminateLE()
2699 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2701 CASetLEReqRespServerCallback(NULL);
2702 CASetLEReqRespClientCallback(NULL);
2703 CALERegisterNetworkNotifications(NULL, NULL);
2704 CASetLEReqRespAdapterCallback(NULL);
2705 CATerminateLENetworkMonitor();
2707 oc_mutex_lock(g_bleIsServerMutex);
2708 switch (g_adapterType)
2710 case ADAPTER_SERVER:
2711 CATerminateLEGattServer();
2713 case ADAPTER_CLIENT:
2714 CATerminateLEGattClient();
2716 case ADAPTER_BOTH_CLIENT_SERVER:
2717 CATerminateLEGattServer();
2718 CATerminateLEGattClient();
2723 g_adapterType = ADAPTER_EMPTY;
2724 oc_mutex_unlock(g_bleIsServerMutex);
2726 #ifndef SINGLE_THREAD
2727 CATerminateLEQueues();
2730 #ifdef __WITH_DTLS__
2731 CAsetSslAdapterCallbacks(NULL, NULL, CA_ADAPTER_GATT_BTLE);
2734 CATerminateLEAdapterMutex();
2737 static CAResult_t CAStartLEListeningServer()
2739 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2741 if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2743 OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2744 caglobals.bleFlags);
2745 return CA_STATUS_OK;
2748 #ifndef ROUTING_GATEWAY
2749 CAResult_t result = CA_STATUS_OK;
2750 #ifndef SINGLE_THREAD
2751 result = CAInitLEServerQueues();
2752 if (CA_STATUS_OK != result)
2754 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
2759 oc_mutex_lock(g_bleIsServerMutex);
2760 switch (g_adapterType)
2762 case ADAPTER_CLIENT:
2763 g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2765 case ADAPTER_BOTH_CLIENT_SERVER:
2768 g_adapterType = ADAPTER_SERVER;
2770 oc_mutex_unlock(g_bleIsServerMutex);
2772 result = CAGetLEAdapterState();
2773 if (CA_STATUS_OK != result)
2775 if (CA_ADAPTER_NOT_ENABLED == result)
2779 "Listen Server will be started once BT Adapter is enabled");
2780 result = CA_STATUS_OK;
2785 result = CALEAdapterGattServerStart();
2788 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2791 // Routing Gateway only supports BLE client mode.
2792 OIC_LOG(ERROR, CALEADAPTER_TAG, "LE server not supported in Routing Gateway");
2793 return CA_NOT_SUPPORTED;
2797 static CAResult_t CAStopLEListeningServer()
2799 OIC_LOG(ERROR, CALEADAPTER_TAG, "Listen server stop not supported.");
2800 return CA_NOT_SUPPORTED;
2803 static CAResult_t CAStartLEDiscoveryServer()
2805 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2806 CAResult_t result = CA_STATUS_OK;
2807 #ifndef SINGLE_THREAD
2808 result = CAInitLEClientQueues();
2809 if (CA_STATUS_OK != result)
2811 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
2816 oc_mutex_lock(g_bleIsServerMutex);
2817 switch (g_adapterType)
2819 case ADAPTER_SERVER:
2820 g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2822 case ADAPTER_BOTH_CLIENT_SERVER:
2825 g_adapterType = ADAPTER_CLIENT;
2827 oc_mutex_unlock(g_bleIsServerMutex);
2829 result = CAGetLEAdapterState();
2830 if (CA_STATUS_OK != result)
2832 if (CA_ADAPTER_NOT_ENABLED == result)
2836 "Discovery Server will be started once BT Adapter is enabled");
2837 result = CA_STATUS_OK;
2842 result = CALEAdapterGattClientStart();
2845 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2849 static CAResult_t CAReadLEData()
2851 #ifdef SINGLE_THREAD
2854 return CA_STATUS_OK;
2857 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2860 CADataType_t dataType)
2862 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2863 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "type(%d)", dataType);
2866 VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
2867 VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2869 CAResult_t result = CA_STATUS_FAILED;
2871 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2872 if (ADAPTER_EMPTY == g_adapterType)
2874 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2877 oc_mutex_lock(g_bleIsServerMutex);
2878 if (ADAPTER_SERVER == g_adapterType ||
2879 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2881 #ifdef __WITH_DTLS__
2882 if (endpoint && endpoint->flags & CA_SECURE)
2884 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2885 "Response Data or server - secured data send(caadapternetdtlsencrypt) call");
2886 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2887 g_dataType = dataType;
2888 oc_mutex_unlock(g_bleIsServerMutex);
2890 result = CAencryptSsl(endpoint, (void *)data, dataLen);
2891 if (CA_STATUS_OK != result)
2893 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
2900 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2901 "server or both - none secured data send(CALEAdapterServerSendData) call");
2902 result = CALEAdapterServerSendData(endpoint, data, dataLen);
2905 result = CALEAdapterServerSendData(endpoint, data, dataLen);
2907 if (CA_STATUS_OK != result)
2909 oc_mutex_unlock(g_bleIsServerMutex);
2910 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed");
2913 g_errorHandler(endpoint, data, dataLen, result);
2919 else if (ADAPTER_CLIENT == g_adapterType ||
2920 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
2921 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
2923 #ifdef __WITH_DTLS__
2924 if (endpoint && endpoint->flags & CA_SECURE)
2926 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2927 "Request Data or client - secured data send(caadapternetdtlsencrypt) call");
2928 OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2929 g_dataType = dataType;
2930 oc_mutex_unlock(g_bleIsServerMutex);
2932 result = CAencryptSsl(endpoint, (void *)data, dataLen);
2933 if (CA_STATUS_OK != result)
2935 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
2942 OIC_LOG(DEBUG, CALEADAPTER_TAG,
2943 "client or both - none secured data send(CALEAdapterClientSendData) call");
2944 result = CALEAdapterClientSendData(endpoint, data, dataLen);
2947 result = CALEAdapterClientSendData(endpoint, data, dataLen);
2949 if (CA_STATUS_OK != result)
2951 oc_mutex_unlock(g_bleIsServerMutex);
2952 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
2956 g_errorHandler(endpoint, data, dataLen, result);
2961 oc_mutex_unlock(g_bleIsServerMutex);
2963 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2967 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
2970 CADataType_t dataType)
2972 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2975 VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2979 OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
2983 CAResult_t result = CA_STATUS_FAILED;
2985 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2986 if (ADAPTER_EMPTY == g_adapterType)
2988 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2991 oc_mutex_lock(g_bleIsServerMutex);
2992 if (ADAPTER_SERVER == g_adapterType ||
2993 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2995 result = CALEAdapterServerSendData(NULL, data, dataLen);
2996 if (CA_STATUS_OK != result)
2998 oc_mutex_unlock(g_bleIsServerMutex);
3000 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data for server failed" );
3004 g_errorHandler(endpoint, data, dataLen, result);
3010 if (ADAPTER_CLIENT == g_adapterType ||
3011 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
3012 (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
3014 result = CALEAdapterClientSendData(NULL, data, dataLen);
3015 if (CA_STATUS_OK != result)
3017 oc_mutex_unlock(g_bleIsServerMutex);
3019 OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data for client failed" );
3023 g_errorHandler(endpoint, data, dataLen, result);
3028 oc_mutex_unlock(g_bleIsServerMutex);
3030 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3034 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
3036 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3038 VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
3040 char *local_address = NULL;
3042 CAResult_t res = CAGetLEAddress(&local_address);
3043 if (CA_STATUS_OK != res)
3045 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
3049 if (NULL == local_address)
3051 OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
3052 return CA_STATUS_FAILED;
3056 (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
3057 if (NULL == (*info))
3059 OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
3060 OICFree(local_address);
3061 return CA_STATUS_FAILED;
3064 size_t local_address_len = strlen(local_address);
3066 if(local_address_len >= sizeof(g_localBLEAddress) ||
3067 local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
3069 OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
3071 OICFree(local_address);
3072 return CA_STATUS_FAILED;
3075 OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
3076 oc_mutex_lock(g_bleLocalAddressMutex);
3077 OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
3078 oc_mutex_unlock(g_bleLocalAddressMutex);
3080 (*info)->adapter = CA_ADAPTER_GATT_BTLE;
3082 OICFree(local_address);
3084 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3085 return CA_STATUS_OK;
3088 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
3089 CAConnectionChangeCallback connCallback)
3091 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3093 g_networkCallback = netCallback;
3094 g_connectionCallback = connCallback;
3095 CAResult_t res = CA_STATUS_OK;
3098 res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
3099 if (CA_STATUS_OK != res)
3101 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
3106 res = CAUnSetLEAdapterStateChangedCb();
3107 if (CA_STATUS_OK != res)
3109 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
3113 if (g_connectionCallback)
3115 res = CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCb);
3116 if (CA_STATUS_OK != res)
3118 OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLENWConnectionStateChangedCb failed!");
3123 res = CAUnSetLENWConnectionStateChangedCb();
3124 if (CA_STATUS_OK != res)
3126 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUnSetLENWConnectionStateChangedCb failed!");
3130 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3134 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
3137 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3139 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3142 CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE };
3143 OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), address);
3146 oc_mutex_lock(g_bleIsServerMutex);
3147 switch (g_adapterType)
3149 case ADAPTER_SERVER:
3150 CALEGattServerConnectionStateChanged(isConnected, address);
3152 case ADAPTER_CLIENT:
3153 CALEGattConnectionStateChanged(isConnected, address);
3155 case ADAPTER_BOTH_CLIENT_SERVER:
3156 CALEGattConnectionStateChanged(isConnected, address);
3157 CALEGattServerConnectionStateChanged(isConnected, address);
3162 oc_mutex_unlock(g_bleIsServerMutex);
3167 #ifndef SINGLE_THREAD
3168 if(g_bleClientSenderInfo)
3170 CALERemoveReceiveQueueData(g_bleClientSenderInfo, address);
3173 if(g_bleServerSenderInfo)
3175 CALERemoveReceiveQueueData(g_bleServerSenderInfo, address);
3178 // remove data of send queue.
3179 if (g_bleClientSendQueueHandle)
3181 CALERemoveSendQueueData(g_bleClientSendQueueHandle, address);
3184 if (g_bleServerSendQueueHandle)
3186 CALERemoveSendQueueData(g_bleServerSendQueueHandle, address);
3190 #ifdef __WITH_DTLS__
3191 CAcloseSslConnection(&localEndpoint);
3195 if (g_connectionCallback)
3197 g_connectionCallback(&localEndpoint, isConnected);
3200 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3203 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
3205 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3207 if (CA_ADAPTER_ENABLED == adapter_state)
3209 oc_mutex_lock(g_bleIsServerMutex);
3210 switch (g_adapterType)
3212 case ADAPTER_SERVER:
3213 CALEAdapterGattServerStart();
3215 case ADAPTER_CLIENT:
3216 CALEAdapterGattClientStart();
3218 case ADAPTER_BOTH_CLIENT_SERVER:
3219 CALEAdapterGattServerStart();
3220 CALEAdapterGattClientStart();
3225 oc_mutex_unlock(g_bleIsServerMutex);
3229 oc_mutex_lock(g_bleIsServerMutex);
3230 switch (g_adapterType)
3232 case ADAPTER_SERVER:
3233 CALEAdapterGattServerStop();
3235 case ADAPTER_CLIENT:
3236 CALEAdapterGattClientStop();
3238 case ADAPTER_BOTH_CLIENT_SERVER:
3239 CALEAdapterGattServerStop();
3240 CALEAdapterGattClientStop();
3245 oc_mutex_unlock(g_bleIsServerMutex);
3248 if (NULL != g_networkCallback)
3250 g_networkCallback(CA_ADAPTER_GATT_BTLE, adapter_state);
3254 OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
3257 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3260 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
3261 const uint8_t *data,
3264 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3265 #ifndef SINGLE_THREAD
3266 VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
3267 "g_bleClientSendQueueHandle is NULL",
3270 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%u]", dataLen);
3272 CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3275 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3276 return CA_MEMORY_ALLOC_FAILED;
3278 // Add message to send queue
3280 CAResult_t res = CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData,
3281 sizeof(CALEData_t));
3282 if (CA_STATUS_OK != res)
3284 CALEDataDestroyer(bleData, sizeof(CALEData_t));
3287 return CA_STATUS_OK;
3290 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
3291 const uint8_t *data,
3294 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3296 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3298 #ifdef SINGLE_THREAD
3299 if (!CAIsLEConnected())
3301 OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
3302 return CA_STATUS_FAILED;
3305 CAResult_t result = CALEServerSendDataSingleThread(data, dataLen);
3306 if (CA_STATUS_OK != result)
3308 OIC_LOG(ERROR, CALEADAPTER_TAG, "CALEServerSendDataSingleThread failed");
3309 return CA_STATUS_FAILED;
3312 VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
3313 "g_bleServerSendQueueHandle is NULL",
3316 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
3318 CALEData_t * const bleData =
3319 CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3323 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3324 return CA_MEMORY_ALLOC_FAILED;
3327 // Add message to send queue
3329 CAResult_t res = CAQueueingThreadAddData(g_bleServerSendQueueHandle,
3331 sizeof(CALEData_t));
3332 if (CA_STATUS_OK != res)
3334 CALEDataDestroyer(bleData, sizeof(CALEData_t));
3337 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3338 return CA_STATUS_OK;
3341 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
3342 const uint8_t *data,
3343 uint32_t dataLength,
3344 uint32_t *sentLength)
3346 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3349 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3350 VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3352 #ifdef SINGLE_THREAD
3353 CALEDataReceiverHandlerSingleThread(data, dataLength);
3355 if (g_singleThreadReceiveData->totalDataLen == g_singleThreadReceiveData->recvDataLen)
3357 if(g_networkPacketReceivedCallback)
3359 // will be filled by upper layer
3360 const CASecureEndpoint_t endpoint =
3361 { .endpoint = { .adapter = CA_ADAPTER_GATT_BTLE } };
3363 g_networkPacketReceivedCallback(&endpoint,
3364 g_singleThreadReceiveData->defragData,
3365 g_singleThreadReceiveData->recvDataLen);
3367 g_singleThreadReceiveData->remoteEndpoint = NULL;
3368 OICFree(g_singleThreadReceiveData->defragData);
3369 g_singleThreadReceiveData->defragData = NULL;
3370 OICFree(g_singleThreadReceiveData);
3371 g_singleThreadReceiveData = NULL;
3374 VERIFY_NON_NULL_RET(g_bleServerReceiverQueue,
3376 "g_bleServerReceiverQueue",
3379 //Add message to data queue
3380 CAEndpoint_t * const remoteEndpoint =
3381 CACreateEndpointObject(CA_DEFAULT_FLAGS,
3382 CA_ADAPTER_GATT_BTLE,
3386 if (NULL == remoteEndpoint)
3388 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3389 return CA_STATUS_FAILED;
3392 // Create bleData to add to queue
3395 "Data received from LE Server layer [%d]",
3398 CALEData_t * const bleData =
3399 CACreateLEData(remoteEndpoint, data, dataLength, g_bleServerSenderInfo);
3403 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3404 CAFreeEndpoint(remoteEndpoint);
3405 return CA_MEMORY_ALLOC_FAILED;
3408 CAFreeEndpoint(remoteEndpoint);
3409 // Add message to receiver queue
3410 CAQueueingThreadAddData(g_bleServerReceiverQueue, bleData, sizeof(CALEData_t));
3412 *sentLength = dataLength;
3414 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3415 return CA_STATUS_OK;
3418 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
3419 const uint8_t *data,
3420 uint32_t dataLength,
3421 uint32_t *sentLength)
3424 VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3425 VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3426 #ifndef SINGLE_THREAD
3427 VERIFY_NON_NULL_RET(g_bleClientReceiverQueue, CALEADAPTER_TAG,
3428 "g_bleClientReceiverQueue",
3431 //Add message to data queue
3432 CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
3433 CA_ADAPTER_GATT_BTLE,
3435 if (NULL == remoteEndpoint)
3437 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3438 return CA_STATUS_FAILED;
3441 // Create bleData to add to queue
3444 "Data received from LE Client layer [%u]",
3447 CALEData_t * const bleData =
3448 CACreateLEData(remoteEndpoint, data, dataLength, g_bleClientSenderInfo);
3452 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3453 CAFreeEndpoint(remoteEndpoint);
3454 return CA_MEMORY_ALLOC_FAILED;
3457 CAFreeEndpoint(remoteEndpoint);
3458 // Add message to receiver queue
3459 CAQueueingThreadAddData(g_bleClientReceiverQueue, bleData, sizeof(CALEData_t));
3461 *sentLength = dataLength;
3463 return CA_STATUS_OK;
3466 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
3468 g_bleAdapterThreadPool = handle;
3472 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
3474 g_networkPacketReceivedCallback = callback;
3478 static void CALEErrorHandler(const char *remoteAddress,
3479 const uint8_t *data,
3483 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3485 VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
3487 CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS,
3488 CA_ADAPTER_GATT_BTLE,
3492 // if required, will be used to build remote endpoint
3493 g_errorHandler(rep, data, dataLen, result);
3495 CAFreeEndpoint(rep);
3497 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3500 #ifndef SINGLE_THREAD
3501 static bool CALEClearQueueAddressDataContext(void *data, uint32_t size, void *ctx)
3503 if (NULL == data || NULL == ctx)
3508 CALEData_t *caLeData = (CALEData_t *)data;
3509 const char *address = (const char *)ctx;
3511 if (NULL != caLeData && NULL != caLeData->remoteEndpoint)
3513 if (!strcasecmp(caLeData->remoteEndpoint->addr, address))
3521 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle, const char* address)
3523 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
3525 VERIFY_NON_NULL_VOID(queueHandle, CALEADAPTER_TAG, "queueHandle");
3526 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3528 CAResult_t res = CAQueueingThreadClearContextData(queueHandle,
3529 CALEClearQueueAddressDataContext,
3531 if (CA_STATUS_OK != res)
3534 OIC_LOG(ERROR, CALEADAPTER_TAG, "Could not clear the send queue");
3539 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList, const char* address)
3541 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
3543 VERIFY_NON_NULL_VOID(dataInfoList, CALEADAPTER_TAG, "dataInfoList");
3544 VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3546 CABLESenderInfo_t *senderInfo = NULL;
3547 uint32_t senderIndex = 0;
3549 u_arraylist_t *portList = u_arraylist_create();
3550 if (CA_STATUS_OK == CALEGetPortsFromSenderInfo(address, dataInfoList, portList))
3552 uint32_t arrayLength = u_arraylist_length(portList);
3553 for (uint32_t i = 0; i < arrayLength; i++)
3555 uint16_t *port = (uint16_t *)u_arraylist_get(portList, i);
3558 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to get port from sender info !");
3559 u_arraylist_destroy(portList);
3563 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "port : %X", *port);
3565 if (CA_STATUS_OK == CALEGetSenderInfo(address, *port,
3566 dataInfoList, &senderInfo,
3569 u_arraylist_remove(dataInfoList, senderIndex);
3570 OICFree(senderInfo->defragData);
3571 OICFree(senderInfo->remoteEndpoint);
3572 OICFree(senderInfo);
3574 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3575 "SenderInfo is removed for disconnection");
3579 OIC_LOG(DEBUG, CALEADAPTER_TAG, "SenderInfo doesn't exist");
3583 u_arraylist_destroy(portList);
3586 static CAResult_t CALEGetPortsFromSenderInfo(const char *leAddress,
3587 u_arraylist_t *senderInfoList,
3588 u_arraylist_t *portList)
3590 VERIFY_NON_NULL(leAddress,
3592 "NULL BLE address argument");
3594 const uint32_t listLength = u_arraylist_length(senderInfoList);
3595 const uint32_t addrLength = strlen(leAddress);
3597 for (uint32_t index = 0; index < listLength; index++)
3599 CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
3600 if (!info || !(info->remoteEndpoint))
3605 if (!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
3607 uint16_t *port = (uint16_t *)OICMalloc(sizeof(uint16_t));
3610 OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
3611 return CA_MEMORY_ALLOC_FAILED;
3613 *port = info->remoteEndpoint->port;
3614 u_arraylist_add(portList, (void *)port);
3618 if (u_arraylist_length(portList) != 0)
3620 return CA_STATUS_OK;
3624 return CA_STATUS_FAILED;
3629 void CALEStartGattServer()
3631 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3633 oc_mutex_lock(g_bleIsServerMutex);
3634 switch (g_adapterType)
3636 case ADAPTER_SERVER:
3637 CALEAdapterGattServerStart();
3639 case ADAPTER_CLIENT:
3640 CALEAdapterGattClientStart();
3642 case ADAPTER_BOTH_CLIENT_SERVER:
3643 CALEAdapterGattServerStart();
3644 CALEAdapterGattClientStart();
3649 oc_mutex_unlock(g_bleIsServerMutex);
3650 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3653 void CALEStopGattServer()
3655 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3657 oc_mutex_lock(g_bleIsServerMutex);
3658 switch (g_adapterType)
3660 case ADAPTER_SERVER:
3661 CALEAdapterGattServerStop();
3663 case ADAPTER_CLIENT:
3664 CALEAdapterGattClientStop();
3666 case ADAPTER_BOTH_CLIENT_SERVER:
3667 CALEAdapterGattServerStop();
3668 CALEAdapterGattClientStop();
3673 oc_mutex_unlock(g_bleIsServerMutex);
3674 OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);